jpfun 0.4.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/README.md +53 -113
  2. package/dist/converter/midi/convert.js +14 -7
  3. package/dist/converter/musicxml/features.d.ts +57 -16
  4. package/dist/converter/musicxml/features.js +204 -42
  5. package/dist/converter/musicxml/index.d.ts +7 -2
  6. package/dist/converter/musicxml/index.js +256 -268
  7. package/dist/converter/musicxml/model.d.ts +36 -7
  8. package/dist/converter/musicxml/resolve.d.ts +10 -0
  9. package/dist/converter/musicxml/resolve.js +152 -0
  10. package/dist/core.d.ts +1 -0
  11. package/dist/core.js +1 -0
  12. package/dist/fraction.js +7 -1
  13. package/dist/functions/ASTtypes.d.ts +6 -3
  14. package/dist/functions/ASTtypes.js +30 -23
  15. package/dist/functions/adjust/index.js +10 -50
  16. package/dist/functions/arpeggio/index.js +40 -25
  17. package/dist/functions/beam/auto.js +2 -11
  18. package/dist/functions/box/index.js +132 -82
  19. package/dist/functions/dash/index.js +20 -11
  20. package/dist/functions/default.js +2 -1
  21. package/dist/functions/div/index.d.ts +1 -1
  22. package/dist/functions/div/index.js +9 -10
  23. package/dist/functions/dot/index.js +4 -5
  24. package/dist/functions/dyn/index.js +28 -32
  25. package/dist/functions/grace/index.d.ts +23 -8
  26. package/dist/functions/grace/index.js +138 -119
  27. package/dist/functions/head/index.js +11 -4
  28. package/dist/functions/key/index.js +1 -1
  29. package/dist/functions/meter/index.js +40 -7
  30. package/dist/functions/meter/shape.d.ts +3 -0
  31. package/dist/functions/meter/shape.js +43 -0
  32. package/dist/functions/note/index.d.ts +6 -1
  33. package/dist/functions/note/index.js +60 -57
  34. package/dist/functions/note/source-transform.d.ts +21 -0
  35. package/dist/functions/note/source-transform.js +164 -0
  36. package/dist/functions/page/index.d.ts +5 -0
  37. package/dist/functions/page/index.js +8 -5
  38. package/dist/functions/rest/index.d.ts +2 -0
  39. package/dist/functions/rest/index.js +233 -0
  40. package/dist/functions/set/index.js +5 -1
  41. package/dist/functions/symbol/index.d.ts +2 -0
  42. package/dist/functions/symbol/index.js +1 -1
  43. package/dist/functions/symbol/ornament.d.ts +3 -3
  44. package/dist/functions/symbol/ornament.js +21 -35
  45. package/dist/functions/symbol/symbols/accent.js +5 -5
  46. package/dist/functions/symbol/symbols/fermata.js +5 -4
  47. package/dist/functions/temporal.d.ts +21 -7
  48. package/dist/functions/temporal.js +14 -4
  49. package/dist/functions/tie/index.js +36 -42
  50. package/dist/functions/tuplet/index.js +20 -24
  51. package/dist/functions/up/index.js +54 -34
  52. package/dist/functions/voice/connections.d.ts +19 -0
  53. package/dist/functions/voice/connections.js +88 -0
  54. package/dist/functions/voice/index.js +248 -102
  55. package/dist/functions/volta/index.js +7 -12
  56. package/dist/jpfun.core.min.js +61 -41
  57. package/dist/jpfun.from-midi.min.js +5 -5
  58. package/dist/jpfun.from-musicxml.min.js +8 -8
  59. package/dist/jpfun.min.js +70 -50
  60. package/dist/layout/engine.d.ts +13 -1
  61. package/dist/layout/engine.js +458 -129
  62. package/dist/layout/model.js +22 -66
  63. package/dist/layout/page.js +3 -1
  64. package/dist/layout/range.d.ts +26 -0
  65. package/dist/layout/range.js +75 -0
  66. package/dist/layout/types.d.ts +63 -49
  67. package/dist/lowering/loweringContext.d.ts +1 -1
  68. package/dist/lowering/loweringContext.js +34 -4
  69. package/dist/lowering/types.d.ts +5 -0
  70. package/dist/parser/parse-utils/length-utils.js +2 -0
  71. package/dist/parser/parse-utils/note-utils.d.ts +2 -0
  72. package/dist/parser/parse-utils/note-utils.js +6 -2
  73. package/dist/parser/parserContext.js +5 -9
  74. package/dist/parser/preprocess.js +4 -6
  75. package/dist/playback/compile.d.ts +2 -9
  76. package/dist/playback/compile.js +297 -186
  77. package/dist/playback/event.d.ts +8 -16
  78. package/dist/playback/event.js +13 -3
  79. package/dist/playback/types.d.ts +76 -18
  80. package/dist/playback/types.js +1 -0
  81. package/dist/render/index.d.ts +1 -1
  82. package/dist/render/index.js +1 -1
  83. package/dist/render/paint.js +1 -1
  84. package/dist/render/recording.d.ts +1 -0
  85. package/dist/render/recording.js +21 -0
  86. package/dist/render/translate.d.ts +14 -0
  87. package/dist/render/translate.js +48 -0
  88. package/grammar.md +200 -250
  89. package/package.json +4 -4
@@ -9,6 +9,7 @@ import { isPlaybackRelation } from "./types.js";
9
9
  *
10
10
  * 核心只维护游标、到达次数和标记表,跳转规则全部由函数在自己的 `playbackFlow` 里写:
11
11
  * 反复线找最近的段起点标记,房子按段起点被访问过几次决定本遍演不演。
12
+ * 本阶段只产生列索引;游标计数和标记索引每次编译重新建立,不会回写 lowering。
12
13
  */
13
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
14
15
  const columns = lowering.columns;
@@ -18,7 +19,8 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
18
19
  for (const node of columns[index])
19
20
  columnOf.set(node, index);
20
21
  }
21
- // 再建立折叠元素的列索引,用此函数实现
22
+ // 折叠成员不单独占列,沿 foldedInto 找到最近的已入列宿主
23
+ // 标记和关系端点都使用这个映射,保持控制流与实际时间列一致
22
24
  const resolveColumn = (node) => {
23
25
  for (let at = node; at; at = at.foldedInto) {
24
26
  const index = columnOf.get(at);
@@ -30,6 +32,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
30
32
  // 收集流的控制信息,并直接按生效列建立索引
31
33
  const marked = new Map(); // 用于查询最近的标签的列
32
34
  const hooksByColumn = new Map();
35
+ /** 校验控制流声明的范围,并将它登记到每个有效列 */
33
36
  const addHook = (owner, sourceSpan) => {
34
37
  const hook = owner.playbackFlow?.(resolveColumn);
35
38
  if (!hook)
@@ -40,6 +43,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
40
43
  throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", `播放控制流范围 [${from}, ${to}] 超出时间列边界`, sourceSpan);
41
44
  }
42
45
  const registered = { hook, sourceSpan };
46
+ // 预先按范围分发,执行时只检查当前列相关的声明。
43
47
  for (let at = from; at <= to; at++) {
44
48
  const list = hooksByColumn.get(at);
45
49
  if (list)
@@ -48,7 +52,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
48
52
  hooksByColumn.set(at, [registered]);
49
53
  }
50
54
  };
51
- // 走 astToTemporal 而不是 columns,折叠成员才不会被漏掉
55
+ // astToTemporal 保留了折叠成员,内部节点发布的控制流和标记也必须参与编译
52
56
  for (const nodes of lowering.astToTemporal.values()) {
53
57
  for (const node of nodes) {
54
58
  addHook(node, node.ast.sourceSpan);
@@ -67,12 +71,14 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
67
71
  }
68
72
  }
69
73
  }
74
+ // 附件通过同一个能力接口声明控制流,核心无需判断具体附件种类
70
75
  for (const attach of lowering.attachments) {
71
76
  addHook(attach, attach.sourceSpan ?? { start: 0, end: 0 });
72
77
  }
73
78
  // 如果没有任何控制流声明,直接按列顺序播放
74
79
  if (hooksByColumn.size === 0)
75
80
  return columns.map((_, index) => index);
81
+ // 标记按记谱列排序,正向和反向查询都能找到指定方向上最近的一项
76
82
  for (const list of marked.values())
77
83
  list.sort((a, b) => a - b);
78
84
  const visits = new Array(columns.length).fill(0);
@@ -80,6 +86,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
80
86
  const cursor = {
81
87
  get column() { return index; },
82
88
  visits: column => visits[column] ?? 0,
89
+ /** 查找严格位于 from 之前或之后的标记,排除起始列自身 */
83
90
  seek(mark, from, direction) {
84
91
  const list = marked.get(mark);
85
92
  if (!list)
@@ -94,12 +101,14 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
94
101
  };
95
102
  const order = []; // 记录最终的播放顺序
96
103
  let steps = 0; // 防死循环
104
+ // 先记录到达,再决定本列去留;跳过的列也算一次到达,但不会发布声音
97
105
  while (index < columns.length) {
98
106
  if (++steps > maxFlowSteps) {
99
107
  throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", `播放控制流访问超过 ${maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算`, columns[index][0].ast.sourceSpan);
100
108
  }
101
109
  visits[index]++;
102
110
  let jumpTo;
111
+ // 同列多个跳转请求取最早目标;停止请求立即结束整个计划
103
112
  for (const registered of hooksByColumn.get(index) ?? []) {
104
113
  const hook = registered.hook;
105
114
  const action = hook.run(cursor);
@@ -137,15 +146,8 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
137
146
  /**
138
147
  * 把 lowering 的时间流编译成完整的演奏计划
139
148
  *
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、波音使用它
146
- * - [API] PlaybackEmitter.defer:把 hook 写在当前节点之后;状态扫描完成后重放顺序流,走到该位置才执行,可见完整 Tempo 和此前音符;dash 用它延长前一组 NoteOff
147
- * - [hook] PlaybackRelation.applyPlayback:顺序流重放完并首次排序后执行,可观察和改写完整事件计划;tie 用它合并相距很远的端点
148
- * - comparePlaybackDraftEvents / finalizePlaybackEvents:最后稳定排序,再校验 NoteOn/NoteOff 配对并剥离 origins、order 等编译期字段
149
+ * 控制流展开 -> 音段结构 -> 连接及效果范围 -> 最终系统状态 -> 声音展开 -> 点事件
150
+ * 结构处理不读取最终状态,声音展开不改变结构边界;每个声明只执行一次
149
151
  */
150
152
  export function compilePlayback(lowering, options) {
151
153
  const maxFlowSteps = options?.maxFlowSteps ?? 1 << 16;
@@ -153,120 +155,118 @@ export function compilePlayback(lowering, options) {
153
155
  throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", "maxFlowSteps 必须是正安全整数", lowering.columns[0]?.[0]?.ast.sourceSpan ?? { start: 0, end: 0 });
154
156
  }
155
157
  const diagnostics = [];
156
- const events = []; // 状态扫描先写 Tempo,顺序流再追加音符
157
- const sequence = [];
158
+ const events = [];
159
+ // notes 是 spans 中有声对象的引用视图,结构修改只需维护同一份边界
160
+ const spans = [];
161
+ const notes = [];
162
+ const transforms = new Map();
158
163
  const activePrograms = new Map();
159
- // 同刻稳定次序与 NoteOn/NoteOff 配对各用独立的单调序号
160
164
  let nextEventOrder = 0;
161
- let nextId = 0;
162
- const nextNoteId = () => nextId++;
163
- // 控制事件不直接进入最终计划;origins 让生成的 Tempo 能追溯到声明节点
164
- const controls = [];
165
- const scheduleControl = (at, origins, apply) => controls.push({
166
- at: at.clone(), // 调用者通常会继续原地修改 Fraction,因此所有持久时间都必须自己持有实例
167
- origins, apply
168
- });
169
- /**
170
- * 记录一次 Temporal 访问的全部事件和后处理声明
171
- *
172
- * activeTransforms 就是当前 play frame:同级兄弟共享同一数组,所以前面的
173
- * accent/tr 能影响后面的音符;childTransforms 是进入复合子节点前的副本,
174
- * 子 frame 能继承外层修饰,却不会把内部新增的修饰泄漏回外层。
175
- *
176
- * ancestors 是复合节点 lineage。叶节点发出的事件同时属于自身与所有外层复合体,
177
- * 因此标注整个 Fold 的 tie 也能找到成员实际发出的 NoteOn/NoteOff。
178
- */
179
- function play(node, // 本次访问并发布播放声明的节点
180
- activeTransforms, // 当前 play frame 中已生效的局部变换
181
- start, // 本次访问在演奏 QN 轴上的起点
182
- duration, // 分配给本节点及默认子节点的演奏时值
183
- ancestors = []) {
184
- // 同一个 Temporal 在反复中会走到这里多次;每次创建独立 origin 对象区分访问实例
185
- const origin = { node };
186
- const lineage = [...ancestors, origin]; // 来源链
187
- const program = node.playbackState?.program;
188
- if (program !== undefined && activePrograms.get(node.track) !== program) {
189
- activePrograms.set(node.track, program);
190
- sequence.push({
191
- kind: "program-change",
192
- at: start.clone(),
193
- order: nextEventOrder++,
194
- origins: [...lineage],
195
- track: node.track,
196
- program,
197
- });
165
+ let nextNoteId = 0;
166
+ const changes = [{ kind: "initial", at: new Fraction(), origins: [] }];
167
+ const factors = new Map();
168
+ const spanScales = new Map();
169
+ const structureContext = { spans, notes, diagnostics };
170
+ /** 固化控制的演奏时刻和来源,回调留到最终状态扫描时统一执行 */
171
+ const scheduleControl = (at, origins, apply) => {
172
+ if (!Number.isFinite(at.toNumber()) || at.compare(0) < 0) {
173
+ throw new ErrorDiagnostic("E_PLAYBACK_CONTROL_TIME", "系统控制时刻必须是非负有限值", origins.at(-1).node.ast.sourceSpan);
198
174
  }
199
- // 每个实际访问到的 Temporal 把自己的记谱状态同步到演奏轴
200
- // 目前是无条件覆盖
201
- if (node.playbackState) {
202
- const { bpm } = node.playbackState;
203
- scheduleControl(start, lineage, state => {
204
- if (bpm)
205
- state.bpm = bpm;
206
- });
207
- }
208
- // 进入时已有的部分作用于本节点;同一副本也作为子 frame,内部新增变换不泄漏到外层
209
- const inheritedCount = activeTransforms.length;
175
+ changes.push({ kind: "control", at: at.clone(), origins, apply });
176
+ };
177
+ /** 为一次节点访问建立独立来源身份,收集区间、控制和各阶段的处理声明 */
178
+ function play(node, activeTransforms, activeScales, start, duration, ancestors = [],
179
+ // 折叠成员沿用正文事件的轨发声,倚音各声部的私有轨因此并入宿主轨
180
+ track = node.track) {
181
+ const lineage = [...ancestors, { node }];
182
+ // 当前目标使用进入时的效果快照;子节点序列使用副本,内部新增效果不会回灌外层
210
183
  const childTransforms = [...activeTransforms];
211
- const directEvents = [];
212
- let localDeferred;
213
- // 复合父节点不能重复执行叶节点的变换,因此只记录本次是否直接发布 NoteOn
214
- let directNoteOnEmitted = false;
184
+ const inheritedTransforms = [...activeTransforms];
185
+ const childScales = [...activeScales];
186
+ const inheritedScales = [...activeScales];
187
+ const deferred = [];
188
+ /** 复制可变的时间和源码位置,避免结构修改影响输入或另一遍访问 */
189
+ function publishSpan(input) {
190
+ const span = {
191
+ ...input,
192
+ start: input.start.clone(),
193
+ end: input.end.clone(),
194
+ track,
195
+ origins: lineage,
196
+ sourceSpans: [{ ...node.ast.sourceSpan }],
197
+ };
198
+ spans.push(span);
199
+ if (inheritedScales.length)
200
+ spanScales.set(span, inheritedScales);
201
+ return span;
202
+ }
203
+ // 每次访问都恢复记谱位置固化的基础状态,回跳不继承上一遍结束时的状态
204
+ const program = node.playbackState?.program;
205
+ if (program !== undefined && activePrograms.get(track) !== program) {
206
+ activePrograms.set(track, program);
207
+ events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++,
208
+ origins: lineage, track, program });
209
+ }
210
+ const bpm = node.playbackState?.bpm;
211
+ if (bpm !== undefined)
212
+ scheduleControl(start, lineage, state => { state.bpm = bpm; });
215
213
  node.emitPlayback?.({
216
214
  start,
217
215
  end: start.clone().add(duration),
218
- track: node.track,
219
- nextNoteId,
220
- emit(event) {
221
- const draft = {
222
- ...event,
223
- at: event.at.clone(),
224
- order: nextEventOrder++,
225
- origins: [...lineage],
226
- };
227
- if (draft.kind === "note-on") {
228
- directNoteOnEmitted = true;
229
- // NoteOn 承载音高、力度、Track 与来源;NoteOff 只靠 noteId 与它配对
230
- const output = {
231
- ...draft,
232
- track: node.track,
233
- sourceSpans: [{ ...node.ast.sourceSpan }],
234
- };
235
- directEvents.push(output);
236
- sequence.push(output);
216
+ track,
217
+ span(input) { publishSpan(input); },
218
+ /** 有声目标沿用已发布的区间对象,只额外登记声音变换 */
219
+ note(input) {
220
+ const note = publishSpan(input);
221
+ notes.push(note);
222
+ if (inheritedTransforms.length)
223
+ transforms.set(note, inheritedTransforms);
224
+ },
225
+ /** 延长原区间,并把当前访问携带的效果定位到新增部分 */
226
+ extend(span) {
227
+ if (!spans.includes(span) || !span.end.equals(start) || duration.compare(0) <= 0) {
228
+ throw new ErrorDiagnostic("E_PLAYBACK_EXTEND_RANGE", "扩展必须接续当前计划内的区间且时值为正", node.ast.sourceSpan);
237
229
  }
238
- else {
239
- directEvents.push(draft);
240
- sequence.push(draft);
230
+ const previousDuration = span.end.clone().sub(span.start);
231
+ const extendedDuration = previousDuration.clone().add(duration);
232
+ // 比例以总时长为分母;延长后重新标定,保持既有效果的实际起点不动
233
+ const scales = (spanScales.get(span) ?? []).map(scale => scale.startRatio
234
+ ? { ...scale, startRatio: scale.startRatio.clone().mul(previousDuration).div(extendedDuration) }
235
+ : scale);
236
+ // 新效果从旧终点开始;保存比例后,后续整体结构缩放仍能同步移动它的起点
237
+ for (const scale of inheritedScales) {
238
+ scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
241
239
  }
240
+ if (scales.length)
241
+ spanScales.set(span, scales);
242
+ span.end.add(duration);
242
243
  },
244
+ emit: event => events.push({ ...event, at: event.at.clone(),
245
+ order: nextEventOrder++, origins: lineage }),
243
246
  control: (at, apply) => scheduleControl(at, lineage, apply),
244
- // 注册到调用者的 frame,故意在 emitPlayback 返回后继续影响后续兄弟
247
+ /** 只登记效果身份和比例,范围等结构与连接确定后再计算 */
248
+ scaleFollowingBpm(key, numerator, denominator = 1, options) {
249
+ if (!Number.isSafeInteger(numerator) || !Number.isSafeInteger(denominator)
250
+ || numerator <= 0 || denominator <= 0) {
251
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM_SCALE", "速度比例必须是正有理数", node.ast.sourceSpan);
252
+ }
253
+ const factor = new Fraction(numerator, denominator);
254
+ const previous = factors.get(key);
255
+ if (previous && !previous.equals(factor)) {
256
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM_SCALE", "同一速度效果 key 必须使用固定比例", node.ast.sourceSpan);
257
+ }
258
+ factors.set(key, factor);
259
+ activeScales.push({ key, factor, followConnections: options?.followConnections ?? false,
260
+ origins: lineage });
261
+ },
245
262
  affectFollowing: transform => activeTransforms.push(transform),
246
- // 当前节点的局部变换执行后,再在本节点位置处理前序事件
247
- defer: hook => (localDeferred ??= []).push(hook),
248
- play: (child, childStart, childDuration) => play(child, childTransforms, childStart ?? start, childDuration ?? duration, lineage),
263
+ defer: hook => deferred.push(hook),
264
+ play: (child, childStart, childDuration) => play(child, childTransforms, childScales, childStart ?? start, childDuration ?? duration, lineage, track),
249
265
  });
250
- if (inheritedCount > 0 && directNoteOnEmitted) {
251
- sequence.push(context => {
252
- let owned = directEvents;
253
- for (let i = 0; i < inheritedCount; i++) {
254
- const ownedLength = owned.length;
255
- const replacement = childTransforms[i](context, owned);
256
- if (!replacement)
257
- continue;
258
- context.events.splice(context.events.length - ownedLength, ownedLength, ...replacement);
259
- owned = replacement;
260
- }
261
- });
262
- }
263
- if (localDeferred)
264
- sequence.push(...localDeferred);
266
+ // 当前节点发布完成就执行结构处理,因此 hook 只能看到当前位置此前的目标
267
+ for (const hook of deferred)
268
+ hook(structureContext);
265
269
  }
266
- /**
267
- * 阶段1:把控制流列序列投影到一条连续的演奏 QN 轴,并收集所有声明
268
- * 得到 scoreMap、controls 和待重放的音符/局部处理顺序
269
- */
270
270
  const order = linearizeColumns(lowering, diagnostics, maxFlowSteps);
271
271
  const firstScore = lowering.columns[order[0]]?.[0]?.t.clone() ?? new Fraction();
272
272
  const scoreMap = [{
@@ -274,12 +274,13 @@ export function compilePlayback(lowering, options) {
274
274
  score: firstScore // 记谱时间0
275
275
  }];
276
276
  const shift = new Fraction().sub(firstScore); // performance = score + shift
277
- // 先按实际走过的列累计;dash 等 hook 若把 NoteOff 推得更远,收尾时还会再次扩展
277
+ // 先按实际走过的列累计;结构处理若把音段推得更远,收尾时还会扩展
278
278
  const performanceEnd = new Fraction();
279
279
  for (let step = 0; step < order.length; step++) {
280
280
  const index = order[step];
281
+ // 同列各顶层访问共享演奏坐标,但分别建立自己的效果作用域
281
282
  for (const node of lowering.columns[index]) {
282
- play(node, [], node.t.clone().add(shift), node.T.clone());
283
+ play(node, [], [], node.t.clone().add(shift), node.T.clone());
283
284
  }
284
285
  const boundary = lowering.columns[index + 1]?.[0]?.t ?? lowering.duration; // 当前列的控制终点
285
286
  performanceEnd.copyFrom(boundary).add(shift);
@@ -297,75 +298,133 @@ export function compilePlayback(lowering, options) {
297
298
  else
298
299
  scoreMap.push(point);
299
300
  }
300
- /**
301
- * 阶段2:依演奏时间执行控制函数,把 controls 物化成可查询快照与最终 Tempo
302
- * 消费 controls
303
- * 得到 statePoints 和 Tempo events
304
- */
301
+ // 所有结构处理已完成;先校验最终边界,再冻结它们供连接和声音阶段共享
302
+ for (const span of spans) {
303
+ if (!Number.isFinite(span.start.toNumber()) || !Number.isFinite(span.end.toNumber())
304
+ || span.start.compare(0) < 0 || span.end.compare(span.start) <= 0) {
305
+ throw new ErrorDiagnostic("E_PLAYBACK_NOTE_RANGE", "音段必须具有非负起点和正时值", span.sourceSpans[0]);
306
+ }
307
+ if (span.end.compare(performanceEnd) > 0)
308
+ performanceEnd.copyFrom(span.end);
309
+ // Fraction 和来源对象也可被原地修改,单独冻结外层 span 不足以保护共享数据
310
+ Object.freeze(span.start);
311
+ Object.freeze(span.end);
312
+ for (const origin of span.origins)
313
+ Object.freeze(origin);
314
+ for (const sourceSpan of span.sourceSpans)
315
+ Object.freeze(sourceSpan);
316
+ Object.freeze(span.origins);
317
+ Object.freeze(span.sourceSpans);
318
+ Object.freeze(span);
319
+ }
320
+ const noteSet = new Set(notes);
321
+ const connections = new Map();
322
+ const predecessors = new Map();
323
+ const relationContext = {
324
+ notes,
325
+ diagnostics,
326
+ /** 只建立一进一出的逻辑连接,保留两个音段各自的边界和修饰 */
327
+ connect(from, to) {
328
+ if (!noteSet.has(from) || !noteSet.has(to) || !from.end.equals(to.start)) {
329
+ throw new ErrorDiagnostic("E_PLAYBACK_CONNECTION", "音段连接必须属于当前计划且时间相接", from.sourceSpans[0]);
330
+ }
331
+ if ((connections.has(from) && connections.get(from) !== to)
332
+ || (predecessors.has(to) && predecessors.get(to) !== from))
333
+ return false;
334
+ connections.set(from, to);
335
+ predecessors.set(to, from);
336
+ return true;
337
+ },
338
+ };
339
+ // 关系按最终结构匹配逻辑音段,此时还没有装饰音的实际 NoteOn/NoteOff
340
+ for (const attachment of lowering.attachments) {
341
+ if (isPlaybackRelation(attachment))
342
+ attachment.applyPlayback(relationContext);
343
+ }
344
+ const reverseNotes = [...notes].sort((left, right) => right.start.compare(left.start));
345
+ const connectedEnds = new Map();
346
+ // 连接严格向未来推进;逆序处理保证后继的链尾已知,一次算出所有逻辑终点
347
+ for (const note of reverseNotes) {
348
+ const next = connections.get(note);
349
+ const end = next ? connectedEnds.get(next) : note.end;
350
+ connectedEnds.set(note, end);
351
+ }
352
+ // 将有声、无声区间上的效果转换为进入和退出边界,交给同一条全局状态时间线
353
+ for (const span of spans) {
354
+ const end = connectedEnds.get(span) ?? span.end;
355
+ // 连接只可能延续效果终点;每个效果仍从自己在原区间内的位置开始
356
+ for (const scale of spanScales.get(span) ?? []) {
357
+ const start = scale.startRatio
358
+ ? span.start.clone().add(span.end.clone().sub(span.start).mul(scale.startRatio))
359
+ : span.start;
360
+ changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? end : span.end,
361
+ origins: scale.origins, scale, delta: -1 });
362
+ }
363
+ }
305
364
  const system = {
306
365
  bpm: DEFAULT_BPM,
307
- bpmScale: new Fraction(1), // 给延长音等变速记号使用
366
+ bpmScale: new Fraction(1),
308
367
  };
368
+ const activeCounts = new Map();
369
+ const activeScale = new Fraction(1);
309
370
  const statePoints = [];
310
- // 最终只在 effective BPM 真正变化时发 Tempo,基础 BPM 与倍率的抵消不会产生冗余事件
371
+ changes.sort((left, right) => left.at.compare(right.at));
372
+ let changeIndex = 0;
311
373
  let emittedBpm;
312
- const snapshotState = () => ({
313
- bpm: system.bpm,
314
- bpmScale: system.bpmScale.clone(),
315
- effectiveBpm: system.bpm * system.bpmScale.toNumber(),
316
- });
317
- // 要求 at 和 origins 可以被安全引用
318
- const pushStatePoint = (at, origins) => {
319
- const snapshot = snapshotState();
374
+ // 结构与连接全部确定后,只扫描一次状态;后续声音变换统一读取这份最终结果
375
+ while (changeIndex < changes.length) {
376
+ const at = changes[changeIndex].at;
377
+ const origins = new Set();
378
+ // 同刻控制和效果边界全部应用后才生成快照,避免输出由扫描顺序造成的瞬时速度
379
+ while (changeIndex < changes.length && changes[changeIndex].at.equals(at)) {
380
+ const change = changes[changeIndex++];
381
+ for (const origin of change.origins)
382
+ origins.add(origin);
383
+ if (change.kind === "control")
384
+ change.apply(system);
385
+ else if (change.kind === "scale") {
386
+ const { key, factor } = change.scale;
387
+ // 同 key 的重叠只累计层数,只有进入或离开整个覆盖范围时才乘除比例
388
+ const before = activeCounts.get(key) ?? 0;
389
+ const after = before + change.delta;
390
+ activeCounts.set(key, after);
391
+ if (before === 0 && after > 0)
392
+ activeScale.mul(factor);
393
+ else if (before > 0 && after === 0)
394
+ activeScale.div(factor);
395
+ }
396
+ }
397
+ const bpmScale = system.bpmScale.clone().mul(activeScale);
398
+ const snapshot = {
399
+ bpm: system.bpm,
400
+ bpmScale,
401
+ effectiveBpm: system.bpm * bpmScale.toNumber(),
402
+ };
320
403
  if (!Number.isFinite(snapshot.effectiveBpm) || snapshot.effectiveBpm <= 0) {
321
- throw new Error("Playback controls produced an invalid BPM");
404
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", [...origins].at(-1)?.node.ast.sourceSpan ?? { start: 0, end: 0 });
405
+ }
406
+ const previous = statePoints.at(-1)?.state;
407
+ if (!previous || previous.bpm !== snapshot.bpm || !previous.bpmScale.equals(bpmScale)) {
408
+ statePoints.push({ at: at.clone(), state: snapshot });
322
409
  }
323
- const previous = statePoints[statePoints.length - 1];
324
- if (previous
325
- && previous.state.bpm === snapshot.bpm
326
- && previous.state.bpmScale.equals(snapshot.bpmScale))
327
- return;
328
- statePoints.push({ at, state: snapshot });
329
- // bpm 变动,发出等效 tempo 事件
330
410
  if (emittedBpm !== snapshot.effectiveBpm) {
331
411
  emittedBpm = snapshot.effectiveBpm;
332
412
  events.push({
333
413
  kind: "tempo",
334
- at: at.clone(), // events会暴露给hook,因此必须复制
414
+ at: at.clone(),
335
415
  bpm: snapshot.effectiveBpm,
336
416
  order: nextEventOrder++,
337
- origins,
417
+ origins: [...origins],
338
418
  });
339
419
  }
340
- };
341
- controls.sort((left, right) => left.at.compare(right.at));
342
- let controlIndex = 0;
343
- // 即使谱面没有显式 tempo/control,计划也需要从 0 开始的默认状态和 Tempo
344
- if (controls[0]?.at.compare(0) !== 0)
345
- pushStatePoint(new Fraction(), []);
346
- while (controlIndex < controls.length) {
347
- const at = controls[controlIndex].at.clone();
348
- const origins = [];
349
- // 先依稳定声明顺序执行同刻全部修改,再输出该时刻最终可观察状态
350
- while (controlIndex < controls.length && at.equals(controls[controlIndex].at)) {
351
- const control = controls[controlIndex++];
352
- control.apply(system);
353
- for (const origin of control.origins)
354
- if (!origins.includes(origin))
355
- origins.push(origin);
356
- }
357
- pushStatePoint(at, origins);
358
420
  }
359
- // hook 可以增删事件或移动时间;relation 开始前和最终输出前各整理一次。
360
- // HookContext 是具体函数唯一看到的全局面:可信 hook 可直接改事件,
361
- // 但来源查询和状态查询由 core 统一实现,避免每个符号重复解释 occurrence/control。
362
- const context = {
363
- events,
421
+ const transformContext = {
364
422
  diagnostics,
365
- nextNoteId,
366
- stateAt: (time) => {
423
+ /** 查询不晚于指定演奏时刻的最后一份最终状态,并隔离可变的比例对象 */
424
+ stateAt(time) {
367
425
  let left = 0;
368
426
  let right = statePoints.length;
427
+ // 二分定位右侧边界;减一后就是该时刻已经生效的快照
369
428
  while (left < right) {
370
429
  const middle = (left + right) >>> 1;
371
430
  if (statePoints[middle].at.compare(time) <= 0)
@@ -373,36 +432,88 @@ export function compilePlayback(lowering, options) {
373
432
  else
374
433
  right = middle;
375
434
  }
376
- return statePoints[left - 1]?.state ?? snapshotState();
435
+ const snapshot = statePoints[Math.max(0, left - 1)].state;
436
+ return { ...snapshot, bpmScale: snapshot.bpmScale.clone() };
377
437
  },
378
438
  };
379
- /**
380
- * 阶段三:按生成顺序发布音符并执行局部处理
381
- * Tempo 已完整生成,音符只暴露此前前缀
382
- */
383
- for (const item of sequence) {
384
- if (typeof item === "function")
385
- item(context);
386
- else
387
- events.push(item);
439
+ const realized = new Map();
440
+ // 每个逻辑音段独立展开声音,连接不会让后一段继承前一段的装饰
441
+ for (const note of notes) {
442
+ let owned = [{ ...note, start: note.start.clone(), end: note.end.clone() }];
443
+ // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
444
+ for (const transform of transforms.get(note) ?? []) {
445
+ owned = transform(transformContext, owned) ?? owned;
446
+ }
447
+ let first;
448
+ let last;
449
+ // 各子音必须留在原区间内;同时收集整体边界,防止声音阶段改写已确定的结构范围
450
+ for (const sound of owned) {
451
+ if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
452
+ || sound.start.compare(note.start) < 0 || sound.end.compare(note.end) > 0
453
+ || sound.end.compare(sound.start) <= 0) {
454
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
455
+ }
456
+ if (!first || sound.start.compare(first) < 0)
457
+ first = sound.start;
458
+ if (!last || sound.end.compare(last) > 0)
459
+ last = sound.end;
460
+ }
461
+ if (!first?.equals(note.start) || !last?.equals(note.end)) {
462
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起止边界", note.sourceSpans[0]);
463
+ }
464
+ // 现在才分配实际音符身份;变换专用字段不再进入点事件,配对留给边界合并使用
465
+ realized.set(note, owned.map(sound => {
466
+ const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
467
+ const noteId = nextNoteId++;
468
+ const on = {
469
+ kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
470
+ track, midi, velocity, percussion,
471
+ origins: [...origins], sourceSpans: sourceSpans.map(span => ({ ...span })),
472
+ };
473
+ const off = {
474
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins: [...origins],
475
+ };
476
+ events.push(on, off);
477
+ return { on, off };
478
+ }));
388
479
  }
389
- /**
390
- * 阶段四:跨节点关系最后执行;tie 此时看到的是局部变换和 dash 都完成后的真实边界
391
- */
392
- events.sort(comparePlaybackDraftEvents);
393
- for (const attachment of lowering.attachments) {
394
- if (isPlaybackRelation(attachment)) {
395
- attachment.applyPlayback(context);
480
+ const removed = new Set();
481
+ const joinedSources = new Map();
482
+ // 后继先完成合并,前驱便可直接接到它更新后的终点;仅合并连接处实际同音的事件
483
+ for (const note of reverseNotes) {
484
+ const next = connections.get(note);
485
+ if (!next)
486
+ continue;
487
+ // 只有到达原音段末端的子音可以跨边界连接,中间子音保留自己的起止
488
+ for (const tail of realized.get(note)) {
489
+ if (!tail.off.at.equals(note.end))
490
+ continue;
491
+ const head = realized.get(next).find(pair => !removed.has(pair.on)
492
+ && pair.on.at.equals(next.start) && pair.on.track === tail.on.track
493
+ && pair.on.midi === tail.on.midi && pair.on.percussion === tail.on.percussion);
494
+ if (!head)
495
+ continue;
496
+ tail.off.at.copyFrom(head.off.at);
497
+ joinedSources.set(tail.on, head.on);
498
+ removed.add(head.on);
499
+ removed.add(head.off);
500
+ }
501
+ }
502
+ // 中间节点只保留来源引用;最终给存活链头汇总一次,避免沿长链反复复制来源后缀
503
+ for (const on of joinedSources.keys()) {
504
+ if (removed.has(on))
505
+ continue;
506
+ for (let next = joinedSources.get(on); next; next = joinedSources.get(next)) {
507
+ on.sourceSpans.push(...next.sourceSpans);
396
508
  }
397
509
  }
398
- // 收敛前按最终事件位置稳定排序
399
- events.sort(comparePlaybackDraftEvents);
400
- const output = finalizePlaybackEvents(events, lowering.tracks);
401
- // 正常列序给出基础终点;已排序的末事件包含局部 hook 延长出的最远 NoteOff。
402
- const eventEnd = events.at(-1)?.at;
510
+ // 稳定排序后,由统一出口检查配对、压实轨道编号并剥离编译期字段
511
+ const finalEvents = (removed.size ? events.filter(event => !removed.has(event)) : events).sort(comparePlaybackDraftEvents);
512
+ const output = finalizePlaybackEvents(finalEvents, lowering.tracks);
513
+ const eventEnd = finalEvents.at(-1)?.at;
403
514
  if (eventEnd && eventEnd.compare(performanceEnd) > 0)
404
515
  performanceEnd.copyFrom(eventEnd);
405
- // 秒数是最终 Tempo 事件对 performance QN 的积分,绝不反向改写事件时间。
516
+ // 秒数是最终 Tempo 事件对 performance QN 的积分,绝不反向改写事件时间
406
517
  return {
407
518
  events: output.events,
408
519
  scoreMap,