jpfun 0.2.0 → 0.3.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 +69 -11
- package/dist/diagnostic.js +5 -2
- package/dist/fraction.d.ts +24 -0
- package/dist/fraction.js +132 -0
- package/dist/functions/ASTtypes.d.ts +24 -7
- package/dist/functions/ASTtypes.js +35 -16
- package/dist/functions/adjust/index.d.ts +2 -0
- package/dist/functions/adjust/index.js +193 -0
- package/dist/functions/bar/index.d.ts +8 -0
- package/dist/functions/bar/index.js +39 -10
- package/dist/functions/beam/auto.js +32 -15
- package/dist/functions/beam/index.js +10 -6
- package/dist/functions/beam/layout.d.ts +3 -2
- package/dist/functions/beam/layout.js +42 -64
- package/dist/functions/box/index.js +35 -34
- package/dist/functions/br/index.js +9 -7
- package/dist/functions/dash/index.js +33 -1
- package/dist/functions/default.js +14 -7
- package/dist/functions/div/index.d.ts +16 -0
- package/dist/functions/div/index.js +45 -17
- package/dist/functions/dot/index.js +11 -3
- package/dist/functions/grace/index.d.ts +8 -11
- package/dist/functions/grace/index.js +82 -76
- package/dist/functions/head/index.d.ts +2 -0
- package/dist/functions/head/index.js +492 -0
- package/dist/functions/key/index.js +97 -3
- package/dist/functions/meter/index.d.ts +2 -0
- package/dist/functions/meter/index.js +154 -0
- package/dist/functions/note/accidentals.d.ts +24 -3
- package/dist/functions/note/accidentals.js +31 -1
- package/dist/functions/note/index.js +45 -65
- package/dist/functions/page/index.d.ts +9 -2
- package/dist/functions/page/index.js +50 -4
- package/dist/functions/set/index.js +37 -29
- package/dist/functions/stack/index.js +26 -22
- package/dist/functions/symbol/index.d.ts +21 -0
- package/dist/functions/symbol/index.js +94 -0
- package/dist/functions/symbol/ornament.d.ts +15 -0
- package/dist/functions/symbol/ornament.js +73 -0
- package/dist/functions/symbol/shape.d.ts +22 -0
- package/dist/functions/symbol/shape.js +48 -0
- package/dist/functions/symbol/symbols/accent.d.ts +2 -0
- package/dist/functions/symbol/symbols/accent.js +24 -0
- package/dist/functions/symbol/symbols/f.d.ts +2 -0
- package/dist/functions/symbol/symbols/f.js +55 -0
- package/dist/functions/symbol/symbols/fermata.d.ts +2 -0
- package/dist/functions/symbol/symbols/fermata.js +24 -0
- package/dist/functions/symbol/symbols/mordent.d.ts +2 -0
- package/dist/functions/symbol/symbols/mordent.js +43 -0
- package/dist/functions/symbol/symbols/p.d.ts +2 -0
- package/dist/functions/symbol/symbols/p.js +61 -0
- package/dist/functions/symbol/symbols/tr.d.ts +2 -0
- package/dist/functions/symbol/symbols/tr.js +75 -0
- package/dist/functions/tempo/glyph.d.ts +12 -0
- package/dist/functions/tempo/glyph.js +30 -0
- package/dist/functions/tempo/index.js +53 -2
- package/dist/functions/text/index.js +76 -24
- package/dist/functions/tie/index.js +102 -127
- package/dist/functions/tuplet/index.d.ts +2 -0
- package/dist/functions/tuplet/index.js +211 -0
- package/dist/functions/up/index.d.ts +1 -0
- package/dist/functions/up/index.js +245 -171
- package/dist/functions/voice/index.js +86 -68
- package/dist/functions/volta/index.d.ts +2 -0
- package/dist/functions/volta/index.js +227 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.js +4 -0
- package/dist/jpfun.min.js +143 -0
- package/dist/layout/engine.d.ts +4 -11
- package/dist/layout/engine.js +65 -59
- package/dist/layout/model.d.ts +8 -1
- package/dist/layout/model.js +16 -6
- package/dist/layout/path.d.ts +19 -0
- package/dist/layout/path.js +101 -0
- package/dist/layout/types.d.ts +51 -18
- package/dist/layout/types.js +3 -1
- package/dist/lowering/loweringContext.d.ts +18 -20
- package/dist/lowering/loweringContext.js +132 -94
- package/dist/lowering/track.d.ts +1 -1
- package/dist/lowering/track.js +1 -1
- package/dist/lowering/types.d.ts +49 -12
- package/dist/lowering/types.js +9 -3
- package/dist/parser/parse-utils/call-utils.d.ts +0 -2
- package/dist/parser/parse-utils/call-utils.js +0 -6
- package/dist/parser/parse-utils/note-utils.d.ts +8 -0
- package/dist/parser/parse-utils/note-utils.js +35 -13
- package/dist/parser/parse-utils/string-utils.d.ts +8 -0
- package/dist/parser/parse-utils/string-utils.js +20 -0
- package/dist/parser/parserContext.d.ts +8 -5
- package/dist/parser/parserContext.js +38 -33
- package/dist/parser/preprocess.js +17 -11
- package/dist/playback/compile.d.ts +18 -0
- package/dist/playback/compile.js +401 -0
- package/dist/playback/event.d.ts +91 -0
- package/dist/playback/event.js +87 -0
- package/dist/playback/time.d.ts +14 -0
- package/dist/playback/time.js +81 -0
- package/dist/playback/types.d.ts +128 -0
- package/dist/playback/types.js +3 -0
- package/dist/render/canvas.d.ts +4 -4
- package/dist/render/canvas.js +20 -5
- package/dist/render/index.d.ts +1 -0
- package/dist/render/index.js +1 -0
- package/dist/render/paint.d.ts +8 -0
- package/dist/render/paint.js +101 -0
- package/dist/render/svg.d.ts +3 -3
- package/dist/render/svg.js +10 -8
- package/dist/render/text.d.ts +17 -0
- package/dist/render/text.js +35 -0
- package/dist/render/types.d.ts +1 -1
- package/grammar.md +93 -10
- package/package.json +10 -6
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
import { ErrorDiagnostic, WarningDiagnostic } from "../diagnostic.js";
|
|
2
|
+
import { Fraction } from "../fraction.js";
|
|
3
|
+
import { DEFAULT_BPM } from "../lowering/types.js";
|
|
4
|
+
import { comparePlaybackDraftEvents, finalizePlaybackEvents } from "./event.js";
|
|
5
|
+
import { performanceTimeToSeconds } from "./time.js";
|
|
6
|
+
import { isPlaybackRelation } from "./types.js";
|
|
7
|
+
/**
|
|
8
|
+
* 按控制流声明展开出实际访问的列顺序
|
|
9
|
+
*
|
|
10
|
+
* 核心只维护游标、到达次数和标记表,跳转规则全部由函数在自己的 `playbackFlow` 里写:
|
|
11
|
+
* 反复线找最近的段起点标记,房子按段起点被访问过几次决定本遍演不演。
|
|
12
|
+
*/
|
|
13
|
+
function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
|
|
14
|
+
const columns = lowering.columns;
|
|
15
|
+
const columnOf = new Map();
|
|
16
|
+
// 先建立时间流内的 TemporalNode 的列索引
|
|
17
|
+
for (let index = 0; index < columns.length; index++) {
|
|
18
|
+
for (const node of columns[index])
|
|
19
|
+
columnOf.set(node, index);
|
|
20
|
+
}
|
|
21
|
+
// 再建立折叠元素的列索引,用此函数实现
|
|
22
|
+
const resolveColumn = (node) => {
|
|
23
|
+
for (let at = node; at; at = at.foldedInto) {
|
|
24
|
+
const index = columnOf.get(at);
|
|
25
|
+
if (index !== void 0)
|
|
26
|
+
return index;
|
|
27
|
+
}
|
|
28
|
+
return void 0;
|
|
29
|
+
};
|
|
30
|
+
// 收集流的控制信息,并直接按生效列建立索引
|
|
31
|
+
const marked = new Map(); // 用于查询最近的标签的列
|
|
32
|
+
const hooksByColumn = new Map();
|
|
33
|
+
const addHook = (owner, sourceSpan) => {
|
|
34
|
+
const hook = owner.playbackFlow?.(resolveColumn);
|
|
35
|
+
if (!hook)
|
|
36
|
+
return;
|
|
37
|
+
const [from, to] = hook.range ?? [0, columns.length - 1];
|
|
38
|
+
if (hook.range && (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
|
|
39
|
+
|| from < 0 || to < from || to >= columns.length)) {
|
|
40
|
+
throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", `播放控制流范围 [${from}, ${to}] 超出时间列边界`, sourceSpan);
|
|
41
|
+
}
|
|
42
|
+
const registered = { hook, sourceSpan };
|
|
43
|
+
for (let at = from; at <= to; at++) {
|
|
44
|
+
const list = hooksByColumn.get(at);
|
|
45
|
+
if (list)
|
|
46
|
+
list.push(registered);
|
|
47
|
+
else
|
|
48
|
+
hooksByColumn.set(at, [registered]);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
// 走 astToTemporal 而不是 columns,折叠成员才不会被漏掉
|
|
52
|
+
for (const nodes of lowering.astToTemporal.values()) {
|
|
53
|
+
for (const node of nodes) {
|
|
54
|
+
addHook(node, node.ast.sourceSpan);
|
|
55
|
+
const marks = node.playbackMarks?.();
|
|
56
|
+
if (!marks)
|
|
57
|
+
continue;
|
|
58
|
+
const at = resolveColumn(node);
|
|
59
|
+
if (at === void 0)
|
|
60
|
+
continue;
|
|
61
|
+
for (const mark of marks) {
|
|
62
|
+
const list = marked.get(mark);
|
|
63
|
+
if (list)
|
|
64
|
+
list.push(at);
|
|
65
|
+
else
|
|
66
|
+
marked.set(mark, [at]);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
for (const attach of lowering.attachments) {
|
|
71
|
+
addHook(attach, attach.sourceSpan ?? { start: 0, end: 0 });
|
|
72
|
+
}
|
|
73
|
+
// 如果没有任何控制流声明,直接按列顺序播放
|
|
74
|
+
if (hooksByColumn.size === 0)
|
|
75
|
+
return columns.map((_, index) => index);
|
|
76
|
+
for (const list of marked.values())
|
|
77
|
+
list.sort((a, b) => a - b);
|
|
78
|
+
const visits = new Array(columns.length).fill(0);
|
|
79
|
+
let index = 0;
|
|
80
|
+
const cursor = {
|
|
81
|
+
get column() { return index; },
|
|
82
|
+
visits: column => visits[column] ?? 0,
|
|
83
|
+
seek(mark, from, direction) {
|
|
84
|
+
const list = marked.get(mark);
|
|
85
|
+
if (!list)
|
|
86
|
+
return undefined;
|
|
87
|
+
if (direction > 0)
|
|
88
|
+
return list.find(column => column > from);
|
|
89
|
+
for (let i = list.length - 1; i >= 0; i--)
|
|
90
|
+
if (list[i] < from)
|
|
91
|
+
return list[i];
|
|
92
|
+
return undefined;
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
const order = []; // 记录最终的播放顺序
|
|
96
|
+
let steps = 0; // 防死循环
|
|
97
|
+
while (index < columns.length) {
|
|
98
|
+
if (++steps > maxFlowSteps) {
|
|
99
|
+
throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", `播放控制流访问超过 ${maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算`, columns[index][0].ast.sourceSpan);
|
|
100
|
+
}
|
|
101
|
+
visits[index]++;
|
|
102
|
+
let jumpTo;
|
|
103
|
+
for (const registered of hooksByColumn.get(index) ?? []) {
|
|
104
|
+
const hook = registered.hook;
|
|
105
|
+
const action = hook.run(cursor);
|
|
106
|
+
if (!action)
|
|
107
|
+
continue;
|
|
108
|
+
// stop 提前结束时,后面的列不算“任何一遍都不会演奏”
|
|
109
|
+
if (action.kind === "stop")
|
|
110
|
+
return order;
|
|
111
|
+
if (!Number.isSafeInteger(action.column)
|
|
112
|
+
|| action.column < 0 || action.column > columns.length) {
|
|
113
|
+
throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", `播放控制流跳转目标 ${action.column} 超出时间列边界`, registered.sourceSpan);
|
|
114
|
+
}
|
|
115
|
+
// 取最小的跳转目标到最前面
|
|
116
|
+
jumpTo = Math.min(jumpTo ?? Infinity, action.column);
|
|
117
|
+
}
|
|
118
|
+
if (jumpTo !== undefined)
|
|
119
|
+
index = jumpTo;
|
|
120
|
+
else { // 没有 hook 走这个分支
|
|
121
|
+
order.push(index);
|
|
122
|
+
index++;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
// 正常走到文末才报告从未演奏的列;连续缺失区间只报第一列
|
|
126
|
+
const played = new Set(order);
|
|
127
|
+
let previousMissing = false;
|
|
128
|
+
for (let index = 0; index < columns.length; index++) {
|
|
129
|
+
const missing = !played.has(index);
|
|
130
|
+
if (missing && !previousMissing) {
|
|
131
|
+
diagnostics.push(new WarningDiagnostic("W_PLAYBACK_COLUMN_NEVER_PLAYED", "这里在任何一遍里都不会演奏", columns[index][0].ast.sourceSpan));
|
|
132
|
+
}
|
|
133
|
+
previousMissing = missing;
|
|
134
|
+
}
|
|
135
|
+
return order;
|
|
136
|
+
}
|
|
137
|
+
/**
|
|
138
|
+
* 把 lowering 的时间流编译成完整的演奏计划
|
|
139
|
+
*
|
|
140
|
+
* 函数通过以下入口参与 playback(按作用顺序):
|
|
141
|
+
* - [hook] Temporal.playbackMarks / PlaybackFlow.playbackFlow:生成事件前先展开控制流;反复线贴起点标记并回跳,volta 按遍数跳过列
|
|
142
|
+
* - [state] Temporal.playbackState:每次实际访问节点时,把 lowering 已固化的 BPM 登记到演奏轴;note、tempo 和正时值 dash 都用它恢复记谱位置的速度
|
|
143
|
+
* - [hook] Temporal.emitPlayback:按展开后的列序逐次调用;note 登记 NoteOn/NoteOff,up/grace 通过 emitter.play 递归登记折叠成员
|
|
144
|
+
* - [API] PlaybackEmitter.control:emit 时只登记控制;所有节点访问完成后按演奏时刻执行,同刻合并后生成 Tempo;fermata 用它修改 bpmScale
|
|
145
|
+
* - [API] PlaybackEmitter.affectFollowing:把 transform 加入当前 play frame;后续目标音完整登记 NoteOn/NoteOff 后,将冻结的 transform 紧接着写入顺序流;accent、tr、mordent 使用它
|
|
146
|
+
* - [API] PlaybackEmitter.defer:把 hook 写在当前节点之后;状态扫描完成后重放顺序流,走到该位置才执行,可见完整 Tempo 和此前音符;dash 用它延长前一组 NoteOff
|
|
147
|
+
* - [hook] PlaybackRelation.applyPlayback:顺序流重放完并首次排序后执行,可观察和改写完整事件计划;tie 用它合并相距很远的端点
|
|
148
|
+
* - comparePlaybackDraftEvents / finalizePlaybackEvents:最后稳定排序,再校验 NoteOn/NoteOff 配对并剥离 origins、order 等编译期字段
|
|
149
|
+
*/
|
|
150
|
+
export function compilePlayback(lowering, options) {
|
|
151
|
+
const maxFlowSteps = options?.maxFlowSteps ?? 1 << 16;
|
|
152
|
+
if (!Number.isSafeInteger(maxFlowSteps) || maxFlowSteps <= 0) {
|
|
153
|
+
throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", "maxFlowSteps 必须是正安全整数", lowering.columns[0]?.[0]?.ast.sourceSpan ?? { start: 0, end: 0 });
|
|
154
|
+
}
|
|
155
|
+
const diagnostics = [];
|
|
156
|
+
const events = []; // 状态扫描先写 Tempo,顺序流再追加音符
|
|
157
|
+
const sequence = [];
|
|
158
|
+
// 同刻稳定次序与 NoteOn/NoteOff 配对各用独立的单调序号
|
|
159
|
+
let nextEventOrder = 0;
|
|
160
|
+
let nextId = 0;
|
|
161
|
+
const nextNoteId = () => nextId++;
|
|
162
|
+
// 控制事件不直接进入最终计划;origins 让生成的 Tempo 能追溯到声明节点
|
|
163
|
+
const controls = [];
|
|
164
|
+
const scheduleControl = (at, origins, apply) => controls.push({
|
|
165
|
+
at: at.clone(), // 调用者通常会继续原地修改 Fraction,因此所有持久时间都必须自己持有实例
|
|
166
|
+
origins, apply
|
|
167
|
+
});
|
|
168
|
+
/**
|
|
169
|
+
* 记录一次 Temporal 访问的全部事件和后处理声明
|
|
170
|
+
*
|
|
171
|
+
* activeTransforms 就是当前 play frame:同级兄弟共享同一数组,所以前面的
|
|
172
|
+
* accent/tr 能影响后面的音符;childTransforms 是进入复合子节点前的副本,
|
|
173
|
+
* 子 frame 能继承外层修饰,却不会把内部新增的修饰泄漏回外层。
|
|
174
|
+
*
|
|
175
|
+
* ancestors 是复合节点 lineage。叶节点发出的事件同时属于自身与所有外层复合体,
|
|
176
|
+
* 因此标注整个 Fold 的 tie 也能找到成员实际发出的 NoteOn/NoteOff。
|
|
177
|
+
*/
|
|
178
|
+
function play(node, // 本次访问并发布播放声明的节点
|
|
179
|
+
activeTransforms, // 当前 play frame 中已生效的局部变换
|
|
180
|
+
start, // 本次访问在演奏 QN 轴上的起点
|
|
181
|
+
duration, // 分配给本节点及默认子节点的演奏时值
|
|
182
|
+
ancestors = []) {
|
|
183
|
+
// 同一个 Temporal 在反复中会走到这里多次;每次创建独立 origin 对象区分访问实例
|
|
184
|
+
const origin = { node };
|
|
185
|
+
const lineage = [...ancestors, origin]; // 来源链
|
|
186
|
+
// 每个实际访问到的 Temporal 把自己的记谱状态同步到演奏轴
|
|
187
|
+
// 目前是无条件覆盖
|
|
188
|
+
if (node.playbackState) {
|
|
189
|
+
const { bpm } = node.playbackState;
|
|
190
|
+
scheduleControl(start, lineage, state => {
|
|
191
|
+
if (bpm)
|
|
192
|
+
state.bpm = bpm;
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
// 进入时已有的部分作用于本节点;同一副本也作为子 frame,内部新增变换不泄漏到外层
|
|
196
|
+
const inheritedCount = activeTransforms.length;
|
|
197
|
+
const childTransforms = [...activeTransforms];
|
|
198
|
+
const directEvents = [];
|
|
199
|
+
let localDeferred;
|
|
200
|
+
// 复合父节点不能重复执行叶节点的变换,因此只记录本次是否直接发布 NoteOn
|
|
201
|
+
let directNoteOnEmitted = false;
|
|
202
|
+
node.emitPlayback?.({
|
|
203
|
+
start,
|
|
204
|
+
end: start.clone().add(duration),
|
|
205
|
+
track: node.track,
|
|
206
|
+
nextNoteId,
|
|
207
|
+
emit(event) {
|
|
208
|
+
const draft = {
|
|
209
|
+
...event,
|
|
210
|
+
at: event.at.clone(),
|
|
211
|
+
order: nextEventOrder++,
|
|
212
|
+
origins: [...lineage],
|
|
213
|
+
};
|
|
214
|
+
if (draft.kind === "note-on") {
|
|
215
|
+
directNoteOnEmitted = true;
|
|
216
|
+
// NoteOn 承载音高、力度、Track 与来源;NoteOff 只靠 noteId 与它配对
|
|
217
|
+
const output = {
|
|
218
|
+
...draft,
|
|
219
|
+
track: node.track,
|
|
220
|
+
sourceSpans: [{ ...node.ast.sourceSpan }],
|
|
221
|
+
};
|
|
222
|
+
directEvents.push(output);
|
|
223
|
+
sequence.push(output);
|
|
224
|
+
}
|
|
225
|
+
else {
|
|
226
|
+
directEvents.push(draft);
|
|
227
|
+
sequence.push(draft);
|
|
228
|
+
}
|
|
229
|
+
},
|
|
230
|
+
control: (at, apply) => scheduleControl(at, lineage, apply),
|
|
231
|
+
// 注册到调用者的 frame,故意在 emitPlayback 返回后继续影响后续兄弟
|
|
232
|
+
affectFollowing: transform => activeTransforms.push(transform),
|
|
233
|
+
// 当前节点的局部变换执行后,再在本节点位置处理前序事件
|
|
234
|
+
defer: hook => (localDeferred ??= []).push(hook),
|
|
235
|
+
play: (child, childStart, childDuration) => play(child, childTransforms, childStart ?? start, childDuration ?? duration, lineage),
|
|
236
|
+
});
|
|
237
|
+
if (inheritedCount > 0 && directNoteOnEmitted) {
|
|
238
|
+
sequence.push(context => {
|
|
239
|
+
let owned = directEvents;
|
|
240
|
+
for (let i = 0; i < inheritedCount; i++) {
|
|
241
|
+
const ownedLength = owned.length;
|
|
242
|
+
const replacement = childTransforms[i](context, owned);
|
|
243
|
+
if (!replacement)
|
|
244
|
+
continue;
|
|
245
|
+
context.events.splice(context.events.length - ownedLength, ownedLength, ...replacement);
|
|
246
|
+
owned = replacement;
|
|
247
|
+
}
|
|
248
|
+
});
|
|
249
|
+
}
|
|
250
|
+
if (localDeferred)
|
|
251
|
+
sequence.push(...localDeferred);
|
|
252
|
+
}
|
|
253
|
+
/**
|
|
254
|
+
* 阶段1:把控制流列序列投影到一条连续的演奏 QN 轴,并收集所有声明
|
|
255
|
+
* 得到 scoreMap、controls 和待重放的音符/局部处理顺序
|
|
256
|
+
*/
|
|
257
|
+
const order = linearizeColumns(lowering, diagnostics, maxFlowSteps);
|
|
258
|
+
const firstScore = lowering.columns[order[0]]?.[0]?.t.clone() ?? new Fraction();
|
|
259
|
+
const scoreMap = [{
|
|
260
|
+
performance: new Fraction(), // 演奏时间0
|
|
261
|
+
score: firstScore // 记谱时间0
|
|
262
|
+
}];
|
|
263
|
+
const shift = new Fraction().sub(firstScore); // performance = score + shift
|
|
264
|
+
// 先按实际走过的列累计;dash 等 hook 若把 NoteOff 推得更远,收尾时还会再次扩展
|
|
265
|
+
const performanceEnd = new Fraction();
|
|
266
|
+
for (let step = 0; step < order.length; step++) {
|
|
267
|
+
const index = order[step];
|
|
268
|
+
for (const node of lowering.columns[index]) {
|
|
269
|
+
play(node, [], node.t.clone().add(shift), node.T.clone());
|
|
270
|
+
}
|
|
271
|
+
const boundary = lowering.columns[index + 1]?.[0]?.t ?? lowering.duration; // 当前列的控制终点
|
|
272
|
+
performanceEnd.copyFrom(boundary).add(shift);
|
|
273
|
+
const next = order[step + 1];
|
|
274
|
+
if (next === undefined || next === index + 1)
|
|
275
|
+
continue;
|
|
276
|
+
// 离开记谱顺序时 performance 不跳,只改变接下来所对应的 score 坐标
|
|
277
|
+
const resume = lowering.columns[next][0]?.t.clone() ?? new Fraction();
|
|
278
|
+
shift.add(boundary).sub(resume);
|
|
279
|
+
const point = { performance: performanceEnd.clone(), score: resume };
|
|
280
|
+
const previous = scoreMap[scoreMap.length - 1];
|
|
281
|
+
// 同一个演奏时刻指向后面最近的谱面时刻
|
|
282
|
+
if (previous.performance.equals(point.performance))
|
|
283
|
+
scoreMap[scoreMap.length - 1] = point;
|
|
284
|
+
else
|
|
285
|
+
scoreMap.push(point);
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* 阶段2:依演奏时间执行控制函数,把 controls 物化成可查询快照与最终 Tempo
|
|
289
|
+
* 消费 controls
|
|
290
|
+
* 得到 statePoints 和 Tempo events
|
|
291
|
+
*/
|
|
292
|
+
const system = {
|
|
293
|
+
bpm: DEFAULT_BPM,
|
|
294
|
+
bpmScale: new Fraction(1), // 给延长音等变速记号使用
|
|
295
|
+
};
|
|
296
|
+
const statePoints = [];
|
|
297
|
+
// 最终只在 effective BPM 真正变化时发 Tempo,基础 BPM 与倍率的抵消不会产生冗余事件
|
|
298
|
+
let emittedBpm;
|
|
299
|
+
const snapshotState = () => ({
|
|
300
|
+
bpm: system.bpm,
|
|
301
|
+
bpmScale: system.bpmScale.clone(),
|
|
302
|
+
effectiveBpm: system.bpm * system.bpmScale.toNumber(),
|
|
303
|
+
});
|
|
304
|
+
// 要求 at 和 origins 可以被安全引用
|
|
305
|
+
const pushStatePoint = (at, origins) => {
|
|
306
|
+
const snapshot = snapshotState();
|
|
307
|
+
if (!Number.isFinite(snapshot.effectiveBpm) || snapshot.effectiveBpm <= 0) {
|
|
308
|
+
throw new Error("Playback controls produced an invalid BPM");
|
|
309
|
+
}
|
|
310
|
+
const previous = statePoints[statePoints.length - 1];
|
|
311
|
+
if (previous
|
|
312
|
+
&& previous.state.bpm === snapshot.bpm
|
|
313
|
+
&& previous.state.bpmScale.equals(snapshot.bpmScale))
|
|
314
|
+
return;
|
|
315
|
+
statePoints.push({ at, state: snapshot });
|
|
316
|
+
// bpm 变动,发出等效 tempo 事件
|
|
317
|
+
if (emittedBpm !== snapshot.effectiveBpm) {
|
|
318
|
+
emittedBpm = snapshot.effectiveBpm;
|
|
319
|
+
events.push({
|
|
320
|
+
kind: "tempo",
|
|
321
|
+
at: at.clone(), // events会暴露给hook,因此必须复制
|
|
322
|
+
bpm: snapshot.effectiveBpm,
|
|
323
|
+
order: nextEventOrder++,
|
|
324
|
+
origins,
|
|
325
|
+
});
|
|
326
|
+
}
|
|
327
|
+
};
|
|
328
|
+
controls.sort((left, right) => left.at.compare(right.at));
|
|
329
|
+
let controlIndex = 0;
|
|
330
|
+
// 即使谱面没有显式 tempo/control,计划也需要从 0 开始的默认状态和 Tempo
|
|
331
|
+
if (controls[0]?.at.compare(0) !== 0)
|
|
332
|
+
pushStatePoint(new Fraction(), []);
|
|
333
|
+
while (controlIndex < controls.length) {
|
|
334
|
+
const at = controls[controlIndex].at.clone();
|
|
335
|
+
const origins = [];
|
|
336
|
+
// 先依稳定声明顺序执行同刻全部修改,再输出该时刻最终可观察状态
|
|
337
|
+
while (controlIndex < controls.length && at.equals(controls[controlIndex].at)) {
|
|
338
|
+
const control = controls[controlIndex++];
|
|
339
|
+
control.apply(system);
|
|
340
|
+
for (const origin of control.origins)
|
|
341
|
+
if (!origins.includes(origin))
|
|
342
|
+
origins.push(origin);
|
|
343
|
+
}
|
|
344
|
+
pushStatePoint(at, origins);
|
|
345
|
+
}
|
|
346
|
+
// hook 可以增删事件或移动时间;relation 开始前和最终输出前各整理一次。
|
|
347
|
+
// HookContext 是具体函数唯一看到的全局面:可信 hook 可直接改事件,
|
|
348
|
+
// 但来源查询和状态查询由 core 统一实现,避免每个符号重复解释 occurrence/control。
|
|
349
|
+
const context = {
|
|
350
|
+
events,
|
|
351
|
+
diagnostics,
|
|
352
|
+
nextNoteId,
|
|
353
|
+
stateAt: (time) => {
|
|
354
|
+
let left = 0;
|
|
355
|
+
let right = statePoints.length;
|
|
356
|
+
while (left < right) {
|
|
357
|
+
const middle = (left + right) >>> 1;
|
|
358
|
+
if (statePoints[middle].at.compare(time) <= 0)
|
|
359
|
+
left = middle + 1;
|
|
360
|
+
else
|
|
361
|
+
right = middle;
|
|
362
|
+
}
|
|
363
|
+
return statePoints[left - 1]?.state ?? snapshotState();
|
|
364
|
+
},
|
|
365
|
+
};
|
|
366
|
+
/**
|
|
367
|
+
* 阶段三:按生成顺序发布音符并执行局部处理
|
|
368
|
+
* Tempo 已完整生成,音符只暴露此前前缀
|
|
369
|
+
*/
|
|
370
|
+
for (const item of sequence) {
|
|
371
|
+
if (typeof item === "function")
|
|
372
|
+
item(context);
|
|
373
|
+
else
|
|
374
|
+
events.push(item);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* 阶段四:跨节点关系最后执行;tie 此时看到的是局部变换和 dash 都完成后的真实边界
|
|
378
|
+
*/
|
|
379
|
+
events.sort(comparePlaybackDraftEvents);
|
|
380
|
+
for (const attachment of lowering.attachments) {
|
|
381
|
+
if (isPlaybackRelation(attachment)) {
|
|
382
|
+
attachment.applyPlayback(context);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
// 收敛前按最终事件位置稳定排序
|
|
386
|
+
events.sort(comparePlaybackDraftEvents);
|
|
387
|
+
const output = finalizePlaybackEvents(events, lowering.tracks);
|
|
388
|
+
// 正常列序给出基础终点;已排序的末事件包含局部 hook 延长出的最远 NoteOff。
|
|
389
|
+
const eventEnd = events.at(-1)?.at;
|
|
390
|
+
if (eventEnd && eventEnd.compare(performanceEnd) > 0)
|
|
391
|
+
performanceEnd.copyFrom(eventEnd);
|
|
392
|
+
// 秒数是最终 Tempo 事件对 performance QN 的积分,绝不反向改写事件时间。
|
|
393
|
+
return {
|
|
394
|
+
events: output.events,
|
|
395
|
+
scoreMap,
|
|
396
|
+
tracks: output.tracks,
|
|
397
|
+
performanceDuration: performanceEnd,
|
|
398
|
+
durationSeconds: performanceTimeToSeconds(output.events, performanceEnd.toNumber()),
|
|
399
|
+
diagnostics,
|
|
400
|
+
};
|
|
401
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type { Fraction } from "../fraction.js";
|
|
2
|
+
import type { Track } from "../lowering/track.js";
|
|
3
|
+
import type { TemporalNodeBase } from "../lowering/types.js";
|
|
4
|
+
import type { SourceSpan } from "../parser/types.js";
|
|
5
|
+
export type PlaybackNoteId = number;
|
|
6
|
+
/** 最终可直接交给 MIDI 适配器的系统事件 */
|
|
7
|
+
export interface PlaybackTempoEvent {
|
|
8
|
+
readonly kind: "tempo";
|
|
9
|
+
readonly at: Fraction;
|
|
10
|
+
readonly bpm: number;
|
|
11
|
+
}
|
|
12
|
+
export interface PlaybackTimeSignatureEvent {
|
|
13
|
+
readonly kind: "time-signature";
|
|
14
|
+
readonly at: Fraction;
|
|
15
|
+
readonly numerator: number;
|
|
16
|
+
readonly denominator: number;
|
|
17
|
+
}
|
|
18
|
+
export interface PlaybackNoteOnEvent {
|
|
19
|
+
readonly kind: "note-on";
|
|
20
|
+
readonly at: Fraction;
|
|
21
|
+
readonly noteId: PlaybackNoteId;
|
|
22
|
+
readonly track: number;
|
|
23
|
+
readonly midi: number;
|
|
24
|
+
readonly velocity: number;
|
|
25
|
+
readonly sourceSpans: readonly SourceSpan[];
|
|
26
|
+
}
|
|
27
|
+
export interface PlaybackNoteOffEvent {
|
|
28
|
+
readonly kind: "note-off";
|
|
29
|
+
readonly at: Fraction;
|
|
30
|
+
readonly noteId: PlaybackNoteId;
|
|
31
|
+
readonly track: number;
|
|
32
|
+
readonly midi: number;
|
|
33
|
+
}
|
|
34
|
+
export type PlaybackEvent = PlaybackTempoEvent | PlaybackTimeSignatureEvent | PlaybackNoteOnEvent | PlaybackNoteOffEvent;
|
|
35
|
+
/** 一次 `play(node)` 访问;对象身份区分同一节点在反复中的不同访问 */
|
|
36
|
+
export interface PlaybackOrigin {
|
|
37
|
+
readonly node: TemporalNodeBase;
|
|
38
|
+
}
|
|
39
|
+
interface PlaybackDraftEventBase {
|
|
40
|
+
at: Fraction;
|
|
41
|
+
order: number;
|
|
42
|
+
origins: PlaybackOrigin[];
|
|
43
|
+
}
|
|
44
|
+
/** 编译期事件;函数 hook 可直接增删改,最终输出前会剥掉内部字段 */
|
|
45
|
+
export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
|
|
46
|
+
kind: "note-on";
|
|
47
|
+
noteId: PlaybackNoteId;
|
|
48
|
+
track: Track;
|
|
49
|
+
midi: number;
|
|
50
|
+
velocity: number;
|
|
51
|
+
transpose?: (steps: number) => number;
|
|
52
|
+
sourceSpans: SourceSpan[];
|
|
53
|
+
}
|
|
54
|
+
export interface PlaybackDraftNoteOffEvent extends PlaybackDraftEventBase {
|
|
55
|
+
kind: "note-off";
|
|
56
|
+
noteId: PlaybackNoteId;
|
|
57
|
+
}
|
|
58
|
+
export interface PlaybackDraftTempoEvent extends PlaybackDraftEventBase {
|
|
59
|
+
kind: "tempo";
|
|
60
|
+
bpm: number;
|
|
61
|
+
}
|
|
62
|
+
export interface PlaybackDraftTimeSignatureEvent extends PlaybackDraftEventBase {
|
|
63
|
+
kind: "time-signature";
|
|
64
|
+
numerator: number;
|
|
65
|
+
denominator: number;
|
|
66
|
+
}
|
|
67
|
+
export type PlaybackDraftEvent = PlaybackDraftNoteOnEvent | PlaybackDraftNoteOffEvent | PlaybackDraftTempoEvent | PlaybackDraftTimeSignatureEvent;
|
|
68
|
+
export type PlaybackEventInput = {
|
|
69
|
+
kind: "note-on";
|
|
70
|
+
at: Fraction;
|
|
71
|
+
noteId: PlaybackNoteId;
|
|
72
|
+
midi: number;
|
|
73
|
+
velocity: number;
|
|
74
|
+
transpose?: (steps: number) => number;
|
|
75
|
+
} | {
|
|
76
|
+
kind: "note-off";
|
|
77
|
+
at: Fraction;
|
|
78
|
+
noteId: PlaybackNoteId;
|
|
79
|
+
} | {
|
|
80
|
+
kind: "time-signature";
|
|
81
|
+
at: Fraction;
|
|
82
|
+
numerator: number;
|
|
83
|
+
denominator: number;
|
|
84
|
+
};
|
|
85
|
+
export declare function comparePlaybackDraftEvents(left: PlaybackDraftEvent, right: PlaybackDraftEvent): number;
|
|
86
|
+
/** 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件 */
|
|
87
|
+
export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[]): {
|
|
88
|
+
events: PlaybackEvent[];
|
|
89
|
+
tracks: Track[];
|
|
90
|
+
};
|
|
91
|
+
export {};
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
const EVENT_PRIORITY = {
|
|
2
|
+
tempo: 0,
|
|
3
|
+
"time-signature": 1,
|
|
4
|
+
"note-off": 2,
|
|
5
|
+
"note-on": 3,
|
|
6
|
+
};
|
|
7
|
+
export function comparePlaybackDraftEvents(left, right) {
|
|
8
|
+
const byTime = left.at.compare(right.at);
|
|
9
|
+
return byTime || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind] || left.order - right.order;
|
|
10
|
+
}
|
|
11
|
+
/** 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件 */
|
|
12
|
+
export function finalizePlaybackEvents(events, trackOrder) {
|
|
13
|
+
const noteOns = new Map();
|
|
14
|
+
const noteOffs = new Map();
|
|
15
|
+
for (const event of events) {
|
|
16
|
+
if (event.kind === "note-on") {
|
|
17
|
+
if (noteOns.has(event.noteId))
|
|
18
|
+
throw new Error(`Duplicate NoteOn ${event.noteId}`);
|
|
19
|
+
noteOns.set(event.noteId, event);
|
|
20
|
+
}
|
|
21
|
+
else if (event.kind === "note-off") {
|
|
22
|
+
if (noteOffs.has(event.noteId))
|
|
23
|
+
throw new Error(`Duplicate NoteOff ${event.noteId}`);
|
|
24
|
+
noteOffs.set(event.noteId, event);
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
for (const [noteId, on] of noteOns) {
|
|
28
|
+
const off = noteOffs.get(noteId);
|
|
29
|
+
if (!off)
|
|
30
|
+
throw new Error(`Note ${noteId} has no NoteOff`);
|
|
31
|
+
if (off.at.compare(on.at) <= 0)
|
|
32
|
+
throw new Error(`Note ${noteId} has a non-positive duration`);
|
|
33
|
+
if (on.origins.length === 0 || off.origins.length === 0)
|
|
34
|
+
throw new Error(`Note ${noteId} has no origin`);
|
|
35
|
+
}
|
|
36
|
+
for (const noteId of noteOffs.keys()) {
|
|
37
|
+
if (!noteOns.has(noteId))
|
|
38
|
+
throw new Error(`NoteOff ${noteId} has no NoteOn`);
|
|
39
|
+
}
|
|
40
|
+
const audible = new Set();
|
|
41
|
+
for (const on of noteOns.values())
|
|
42
|
+
audible.add(on.track);
|
|
43
|
+
// 保留 lowering 的稳定轨道顺序,只过滤 head 等纯布局 Track。
|
|
44
|
+
const trackIds = new Map();
|
|
45
|
+
for (const track of trackOrder) {
|
|
46
|
+
if (audible.has(track))
|
|
47
|
+
trackIds.set(track, trackIds.size);
|
|
48
|
+
}
|
|
49
|
+
// 可信扩展若替换成 lowering 之外的 Track,仍按首次 NoteOn 顺序追加。
|
|
50
|
+
for (const track of audible) {
|
|
51
|
+
if (!trackIds.has(track))
|
|
52
|
+
trackIds.set(track, trackIds.size);
|
|
53
|
+
}
|
|
54
|
+
const output = events.map(event => {
|
|
55
|
+
if (event.kind === "tempo")
|
|
56
|
+
return { kind: "tempo", at: event.at, bpm: event.bpm };
|
|
57
|
+
if (event.kind === "time-signature") {
|
|
58
|
+
return {
|
|
59
|
+
kind: "time-signature",
|
|
60
|
+
at: event.at,
|
|
61
|
+
numerator: event.numerator,
|
|
62
|
+
denominator: event.denominator,
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
const on = event.kind === "note-on" ? event : noteOns.get(event.noteId);
|
|
66
|
+
const track = trackIds.get(on.track);
|
|
67
|
+
if (event.kind === "note-on") {
|
|
68
|
+
return {
|
|
69
|
+
kind: "note-on",
|
|
70
|
+
at: event.at,
|
|
71
|
+
noteId: event.noteId,
|
|
72
|
+
track,
|
|
73
|
+
midi: event.midi,
|
|
74
|
+
velocity: event.velocity,
|
|
75
|
+
sourceSpans: event.sourceSpans,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
return {
|
|
79
|
+
kind: "note-off",
|
|
80
|
+
at: event.at,
|
|
81
|
+
noteId: event.noteId,
|
|
82
|
+
track,
|
|
83
|
+
midi: on.midi,
|
|
84
|
+
};
|
|
85
|
+
});
|
|
86
|
+
return { events: output, tracks: [...trackIds.keys()] };
|
|
87
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { PlaybackEvent, PlaybackPlan, PlaybackScorePoint } from "./types.js";
|
|
2
|
+
/** 演奏时间(QN)按分段速度积分为秒 */
|
|
3
|
+
export declare function performanceTimeToSeconds(events: readonly PlaybackEvent[], performanceTime: number): number;
|
|
4
|
+
export declare function secondsToPerformanceTime(events: readonly PlaybackEvent[], seconds: number): number;
|
|
5
|
+
/** 演奏进度换算为谱面进度 */
|
|
6
|
+
export declare function performanceTimeToScoreTime(scoreMap: readonly PlaybackScorePoint[], performanceTime: number): number;
|
|
7
|
+
/**
|
|
8
|
+
* 谱面位置换算为演奏时间,供“点击谱面从这里播放”使用
|
|
9
|
+
*
|
|
10
|
+
* 反复让同一个谱面位置对应多段演奏时间,这里取最早的一遍。
|
|
11
|
+
*/
|
|
12
|
+
export declare function scoreTimeToPerformanceTime(scoreMap: readonly PlaybackScorePoint[], scoreTime: number): number;
|
|
13
|
+
export declare function secondsToScoreTime(plan: PlaybackPlan, seconds: number): number;
|
|
14
|
+
export declare function scoreTimeToSeconds(plan: PlaybackPlan, scoreTime: number): number;
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
import { DEFAULT_BPM } from "../lowering/types.js";
|
|
2
|
+
/** 演奏时间(QN)按分段速度积分为秒 */
|
|
3
|
+
export function performanceTimeToSeconds(events, performanceTime) {
|
|
4
|
+
const target = Math.max(0, performanceTime);
|
|
5
|
+
let seconds = 0;
|
|
6
|
+
let position = 0;
|
|
7
|
+
let bpm = DEFAULT_BPM;
|
|
8
|
+
for (const event of events) {
|
|
9
|
+
if (event.kind !== "tempo")
|
|
10
|
+
continue;
|
|
11
|
+
const next = event.at.toNumber();
|
|
12
|
+
if (next > target)
|
|
13
|
+
break;
|
|
14
|
+
if (next > position)
|
|
15
|
+
seconds += (next - position) * 60 / bpm;
|
|
16
|
+
position = next;
|
|
17
|
+
bpm = event.bpm;
|
|
18
|
+
}
|
|
19
|
+
return seconds + (target - position) * 60 / bpm;
|
|
20
|
+
}
|
|
21
|
+
export function secondsToPerformanceTime(events, seconds) {
|
|
22
|
+
let remaining = Math.max(0, seconds);
|
|
23
|
+
let position = 0;
|
|
24
|
+
let bpm = DEFAULT_BPM;
|
|
25
|
+
for (const event of events) {
|
|
26
|
+
if (event.kind !== "tempo")
|
|
27
|
+
continue;
|
|
28
|
+
const next = event.at.toNumber();
|
|
29
|
+
const segmentSeconds = (next - position) * 60 / bpm;
|
|
30
|
+
if (remaining < segmentSeconds)
|
|
31
|
+
return position + remaining * bpm / 60;
|
|
32
|
+
remaining -= segmentSeconds;
|
|
33
|
+
position = next;
|
|
34
|
+
bpm = event.bpm;
|
|
35
|
+
}
|
|
36
|
+
return position + remaining * bpm / 60;
|
|
37
|
+
}
|
|
38
|
+
/** 演奏进度换算为谱面进度 */
|
|
39
|
+
export function performanceTimeToScoreTime(scoreMap, performanceTime) {
|
|
40
|
+
const target = Math.max(0, performanceTime);
|
|
41
|
+
let result = target;
|
|
42
|
+
for (const point of scoreMap) {
|
|
43
|
+
const performance = point.performance.toNumber();
|
|
44
|
+
if (performance > target)
|
|
45
|
+
break;
|
|
46
|
+
result = point.score.toNumber() + target - performance;
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
}
|
|
50
|
+
/**
|
|
51
|
+
* 谱面位置换算为演奏时间,供“点击谱面从这里播放”使用
|
|
52
|
+
*
|
|
53
|
+
* 反复让同一个谱面位置对应多段演奏时间,这里取最早的一遍。
|
|
54
|
+
*/
|
|
55
|
+
export function scoreTimeToPerformanceTime(scoreMap, scoreTime) {
|
|
56
|
+
const target = Math.max(0, scoreTime);
|
|
57
|
+
let nextReachable;
|
|
58
|
+
for (let i = 0; i < scoreMap.length; i++) {
|
|
59
|
+
const point = scoreMap[i];
|
|
60
|
+
const score = point.score.toNumber();
|
|
61
|
+
if (score > target) {
|
|
62
|
+
if (!nextReachable || score < nextReachable.score.toNumber())
|
|
63
|
+
nextReachable = point;
|
|
64
|
+
continue;
|
|
65
|
+
}
|
|
66
|
+
const next = scoreMap[i + 1];
|
|
67
|
+
const span = next ? next.performance.toNumber() - point.performance.toNumber() : Infinity;
|
|
68
|
+
if (target - score >= span)
|
|
69
|
+
continue;
|
|
70
|
+
return point.performance.toNumber() + (target - score);
|
|
71
|
+
}
|
|
72
|
+
return nextReachable?.performance.toNumber() ?? target;
|
|
73
|
+
}
|
|
74
|
+
export function secondsToScoreTime(plan, seconds) {
|
|
75
|
+
const performance = Math.min(secondsToPerformanceTime(plan.events, seconds), plan.performanceDuration.toNumber());
|
|
76
|
+
return performanceTimeToScoreTime(plan.scoreMap, performance);
|
|
77
|
+
}
|
|
78
|
+
export function scoreTimeToSeconds(plan, scoreTime) {
|
|
79
|
+
const performance = Math.min(scoreTimeToPerformanceTime(plan.scoreMap, scoreTime), plan.performanceDuration.toNumber());
|
|
80
|
+
return performanceTimeToSeconds(plan.events, performance);
|
|
81
|
+
}
|