jpfun 0.7.0 → 0.9.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 (152) hide show
  1. package/Bravura-LICENSE.txt +93 -0
  2. package/README.md +49 -146
  3. package/dist/Bravura-LICENSE.txt +93 -0
  4. package/dist/converter/midi/convert.d.ts +0 -10
  5. package/dist/converter/midi/convert.js +19 -56
  6. package/dist/converter/musicxml/features.d.ts +16 -8
  7. package/dist/converter/musicxml/features.js +88 -19
  8. package/dist/converter/musicxml/index.js +88 -50
  9. package/dist/converter/musicxml/model.d.ts +9 -0
  10. package/dist/converter/source.d.ts +4 -7
  11. package/dist/converter/source.js +11 -9
  12. package/dist/core.d.ts +1 -0
  13. package/dist/core.js +1 -0
  14. package/dist/diagnostic.d.ts +7 -1
  15. package/dist/diagnostic.js +40 -88
  16. package/dist/fraction.js +3 -2
  17. package/dist/functions/ASTtypes.d.ts +3 -32
  18. package/dist/functions/ASTtypes.js +5 -52
  19. package/dist/functions/adjust/index.js +45 -33
  20. package/dist/functions/arpeggio/index.js +50 -55
  21. package/dist/functions/arpeggio/shape.d.ts +2 -3
  22. package/dist/functions/arpeggio/shape.js +20 -50
  23. package/dist/functions/bar/index.d.ts +8 -0
  24. package/dist/functions/bar/index.js +105 -8
  25. package/dist/functions/beam/auto.d.ts +1 -2
  26. package/dist/functions/beam/auto.js +80 -135
  27. package/dist/functions/beam/index.js +6 -12
  28. package/dist/functions/beam/layout.d.ts +1 -1
  29. package/dist/functions/beam/layout.js +1 -1
  30. package/dist/functions/box/index.js +0 -6
  31. package/dist/functions/br/index.d.ts +34 -2
  32. package/dist/functions/br/index.js +5 -4
  33. package/dist/functions/dash/index.js +9 -10
  34. package/dist/functions/default.js +2 -1
  35. package/dist/functions/div/index.d.ts +3 -4
  36. package/dist/functions/div/index.js +18 -14
  37. package/dist/functions/dot/index.js +5 -11
  38. package/dist/functions/dyn/index.js +55 -57
  39. package/dist/functions/gliss/index.js +131 -103
  40. package/dist/functions/grace/index.d.ts +3 -12
  41. package/dist/functions/grace/index.js +52 -102
  42. package/dist/functions/head/index.js +10 -7
  43. package/dist/functions/key/index.js +13 -15
  44. package/dist/functions/meter/index.d.ts +56 -1
  45. package/dist/functions/meter/index.js +15 -10
  46. package/dist/functions/note/index.js +6 -6
  47. package/dist/functions/note/noteName.d.ts +16 -0
  48. package/dist/functions/note/noteName.js +88 -0
  49. package/dist/functions/note/source-transform.js +8 -10
  50. package/dist/functions/ottava/index.js +35 -40
  51. package/dist/functions/page/index.d.ts +1 -0
  52. package/dist/functions/page/index.js +27 -21
  53. package/dist/functions/pagebreak/index.js +2 -2
  54. package/dist/functions/rest/index.js +5 -5
  55. package/dist/functions/set/index.js +4 -4
  56. package/dist/functions/slide/index.js +0 -1
  57. package/dist/functions/stack/index.js +8 -57
  58. package/dist/functions/symbol/index.d.ts +21 -2
  59. package/dist/functions/symbol/index.js +69 -24
  60. package/dist/functions/symbol/ornament.d.ts +1 -2
  61. package/dist/functions/symbol/shape.d.ts +6 -0
  62. package/dist/functions/symbol/shape.js +16 -3
  63. package/dist/functions/symbol/symbols/coda.d.ts +4 -0
  64. package/dist/functions/symbol/symbols/coda.js +56 -0
  65. package/dist/functions/symbol/symbols/dynamics.d.ts +1 -1
  66. package/dist/functions/symbol/symbols/dynamics.js +18 -8
  67. package/dist/functions/symbol/symbols/harmonic.d.ts +2 -0
  68. package/dist/functions/symbol/symbols/harmonic.js +11 -0
  69. package/dist/functions/symbol/symbols/marcato.d.ts +2 -0
  70. package/dist/functions/symbol/symbols/marcato.js +22 -0
  71. package/dist/functions/symbol/symbols/staccato.d.ts +2 -0
  72. package/dist/functions/symbol/symbols/staccato.js +24 -0
  73. package/dist/functions/symbol/symbols/tenuto.d.ts +2 -0
  74. package/dist/functions/symbol/symbols/tenuto.js +11 -0
  75. package/dist/functions/symbol/symbols/tocoda.d.ts +2 -0
  76. package/dist/functions/symbol/symbols/tocoda.js +16 -0
  77. package/dist/functions/symbol/symbols/turn.d.ts +3 -0
  78. package/dist/functions/symbol/symbols/turn.js +50 -0
  79. package/dist/functions/symbol/symbols/wheel.d.ts +2 -0
  80. package/dist/functions/symbol/symbols/wheel.js +36 -0
  81. package/dist/functions/temporal.d.ts +3 -2
  82. package/dist/functions/temporal.js +8 -0
  83. package/dist/functions/text/index.js +38 -35
  84. package/dist/functions/tie/index.js +44 -43
  85. package/dist/functions/tremolo/index.d.ts +2 -0
  86. package/dist/functions/tremolo/index.js +318 -0
  87. package/dist/functions/tuplet/index.js +4 -14
  88. package/dist/functions/up/index.js +81 -85
  89. package/dist/functions/voice/connections.d.ts +2 -1
  90. package/dist/functions/voice/connections.js +48 -10
  91. package/dist/functions/voice/index.d.ts +2 -3
  92. package/dist/functions/voice/index.js +2 -963
  93. package/dist/functions/voice/lyrics.d.ts +30 -0
  94. package/dist/functions/voice/lyrics.js +289 -0
  95. package/dist/functions/voice/voice.d.ts +63 -0
  96. package/dist/functions/voice/voice.js +373 -0
  97. package/dist/functions/voice/voices.d.ts +106 -0
  98. package/dist/functions/voice/voices.js +423 -0
  99. package/dist/functions/volta/index.js +5 -23
  100. package/dist/jpfun.core.min.js +76 -59
  101. package/dist/jpfun.from-midi.min.js +5 -5
  102. package/dist/jpfun.from-musicxml.min.js +8 -8
  103. package/dist/jpfun.min.js +81 -64
  104. package/dist/layout/default.d.ts +0 -1
  105. package/dist/layout/default.js +0 -1
  106. package/dist/layout/engine.js +30 -18
  107. package/dist/layout/model.d.ts +0 -1
  108. package/dist/layout/model.js +1 -4
  109. package/dist/layout/page.d.ts +2 -1
  110. package/dist/layout/page.js +14 -14
  111. package/dist/layout/range.d.ts +7 -6
  112. package/dist/layout/range.js +23 -14
  113. package/dist/layout/types.d.ts +9 -28
  114. package/dist/lowering/loweringContext.d.ts +18 -23
  115. package/dist/lowering/loweringContext.js +33 -46
  116. package/dist/lowering/track.d.ts +8 -1
  117. package/dist/lowering/types.d.ts +13 -11
  118. package/dist/parser/parse-utils/call-utils.d.ts +1 -2
  119. package/dist/parser/parse-utils/call-utils.js +6 -34
  120. package/dist/parser/parse-utils/note-utils.d.ts +3 -3
  121. package/dist/parser/parse-utils/note-utils.js +21 -33
  122. package/dist/parser/parse-utils/string-utils.d.ts +3 -2
  123. package/dist/parser/parse-utils/string-utils.js +20 -5
  124. package/dist/parser/parserContext.d.ts +9 -9
  125. package/dist/parser/parserContext.js +62 -11
  126. package/dist/pipeline.js +2 -3
  127. package/dist/playback/compile.js +131 -82
  128. package/dist/playback/event.d.ts +6 -6
  129. package/dist/playback/event.js +13 -49
  130. package/dist/playback/time.js +42 -31
  131. package/dist/playback/types.d.ts +3 -1
  132. package/dist/render/canvas.js +4 -22
  133. package/dist/render/recording.js +1 -4
  134. package/dist/render/svg.d.ts +0 -1
  135. package/dist/render/svg.js +33 -31
  136. package/dist/render/text.d.ts +36 -1
  137. package/dist/render/text.js +134 -0
  138. package/dist/render/translate.d.ts +0 -1
  139. package/dist/render/translate.js +6 -23
  140. package/dist/render/types.d.ts +0 -2
  141. package/grammar.md +39 -30
  142. package/package.json +3 -3
  143. package/dist/functions/note/noteNameFSM.d.ts +0 -8
  144. package/dist/functions/note/noteNameFSM.js +0 -181
  145. package/dist/iife/core.d.ts +0 -1
  146. package/dist/iife/core.js +0 -3
  147. package/dist/iife/from-midi.d.ts +0 -1
  148. package/dist/iife/from-midi.js +0 -15
  149. package/dist/iife/from-musicxml.d.ts +0 -1
  150. package/dist/iife/from-musicxml.js +0 -3
  151. package/dist/iife/full.d.ts +0 -1
  152. package/dist/iife/full.js +0 -3
@@ -13,15 +13,17 @@ import { isPlaybackRelation } from "./types.js";
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
15
15
  const columns = lowering.columns;
16
- const columnOf = new Map();
17
- // 先建立时间流内的 TemporalNode 的列索引
18
- for (let index = 0; index < columns.length; index++) {
19
- for (const node of columns[index])
20
- columnOf.set(node, index);
21
- }
16
+ let columnOf;
22
17
  // 折叠成员不单独占列,沿 foldedInto 找到最近的已入列宿主
23
18
  // 标记和关系端点都使用这个映射,保持控制流与实际时间列一致
24
19
  const resolveColumn = (node, edge) => {
20
+ if (!columnOf) {
21
+ columnOf = new Map();
22
+ for (let index = 0; index < columns.length; index++) {
23
+ for (const item of columns[index])
24
+ columnOf.set(item, index);
25
+ }
26
+ }
25
27
  for (let at = node; at; at = at.foldedInto) {
26
28
  const index = columnOf.get(at);
27
29
  if (index === undefined)
@@ -49,7 +51,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
49
51
  const [from, to] = hook.range ?? [0, columns.length - 1];
50
52
  if (hook.range && (!Number.isSafeInteger(from) || !Number.isSafeInteger(to)
51
53
  || from < 0 || to < from || to >= columns.length)) {
52
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", `播放控制流范围 [${from}, ${to}] 超出时间列边界`, sourceSpan);
54
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_RANGE", "播放控制流范围 [{from}, {to}] 超出时间列边界", sourceSpan, { from, to });
53
55
  }
54
56
  const registered = { hook, sourceSpan };
55
57
  // 预先按范围分发,执行时只检查当前列相关的声明。
@@ -66,7 +68,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
66
68
  for (const node of nodes) {
67
69
  addHook(node, node.ast.sourceSpan);
68
70
  const marks = node.playbackMarks?.();
69
- if (!marks)
71
+ if (!marks?.length)
70
72
  continue;
71
73
  const at = resolveColumn(node);
72
74
  if (at === void 0)
@@ -113,7 +115,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
113
115
  // 先记录到达,再决定本列去留;跳过的列也算一次到达,但不会发布声音
114
116
  while (index < columns.length) {
115
117
  if (++steps > maxFlowSteps) {
116
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", `播放控制流访问超过 ${maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算`, columns[index][0].ast.sourceSpan);
118
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_LIMIT", "播放控制流访问超过 {maxFlowSteps} 步;可通过 maxFlowSteps 提高展开预算", columns[index][0].ast.sourceSpan, { maxFlowSteps });
117
119
  }
118
120
  visits[index]++;
119
121
  let jumpTo;
@@ -128,7 +130,7 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
128
130
  return order;
129
131
  if (!Number.isSafeInteger(action.column)
130
132
  || action.column < 0 || action.column > columns.length) {
131
- throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", `播放控制流跳转目标 ${action.column} 超出时间列边界`, registered.sourceSpan);
133
+ throw new ErrorDiagnostic("E_PLAYBACK_FLOW_JUMP", "播放控制流跳转目标 {column} 超出时间列边界", registered.sourceSpan, { column: action.column });
132
134
  }
133
135
  // 取最小的跳转目标到最前面
134
136
  jumpTo = Math.min(jumpTo ?? Infinity, action.column);
@@ -140,11 +142,11 @@ function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
140
142
  index++;
141
143
  }
142
144
  }
143
- // 正常走到文末才报告从未演奏的列;连续缺失区间只报第一列
145
+ // 正常走到文末才报告从未演奏的正时值列;换行、声部头、回跳小节线等零时值列不算未演奏
144
146
  const played = new Set(order);
145
147
  let previousMissing = false;
146
148
  for (let index = 0; index < columns.length; index++) {
147
- const missing = !played.has(index);
149
+ const missing = !played.has(index) && columns[index].some(node => !node.T.isZero());
148
150
  if (missing && !previousMissing) {
149
151
  diagnostics.push(new WarningDiagnostic("W_PLAYBACK_COLUMN_NEVER_PLAYED", "这里在任何一遍里都不会演奏", columns[index][0].ast.sourceSpan));
150
152
  }
@@ -175,7 +177,18 @@ export function compilePlayback(lowering, options) {
175
177
  const changes = [{ kind: "initial", at: new Fraction(), origins: [] }];
176
178
  const factors = new Map();
177
179
  const spanScales = new Map();
178
- const structureContext = { spans, notes, diagnostics };
180
+ const structureContext = {
181
+ spans,
182
+ notes,
183
+ diagnostics,
184
+ transform(note, transform) {
185
+ if (notes.lastIndexOf(note) < 0) {
186
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_TARGET", "声音变换目标必须属于当前计划的已发布音段", note.sourceSpans?.[0] ?? { start: 0, end: 0 });
187
+ }
188
+ const list = transforms.get(note);
189
+ transforms.set(note, list ? [...list, transform] : [transform]);
190
+ },
191
+ };
179
192
  /** 固化控制的演奏时刻和来源,回调留到最终状态扫描时统一执行 */
180
193
  const scheduleControl = (at, origins, apply) => {
181
194
  if (!Number.isFinite(at.toNumber()) || at.compare(0) < 0) {
@@ -187,13 +200,15 @@ export function compilePlayback(lowering, options) {
187
200
  function play(node, activeTransforms, activeScales, start, duration, ancestors = [],
188
201
  // 折叠成员沿用正文事件的轨发声,倚音各声部的私有轨因此并入宿主轨
189
202
  track = node.track) {
203
+ if (!node.playbackState && !node.emitPlayback)
204
+ return;
190
205
  const lineage = [...ancestors, { node }];
191
- // 当前目标使用进入时的效果快照;子节点序列使用副本,内部新增效果不会回灌外层
192
- const childTransforms = [...activeTransforms];
193
- const inheritedTransforms = [...activeTransforms];
194
- const childScales = [...activeScales];
195
- const inheritedScales = [...activeScales];
196
- const deferred = [];
206
+ // 当前目标使用进入时的效果快照;子节点序列按需复制,内部新增效果不会回灌外层
207
+ const inheritedTransforms = activeTransforms.length ? [...activeTransforms] : undefined;
208
+ const inheritedScales = activeScales.length ? [...activeScales] : undefined;
209
+ let childTransforms;
210
+ let childScales;
211
+ let deferred;
197
212
  /** 复制可变的时间和源码位置,避免结构修改影响输入或另一遍访问 */
198
213
  function publishSpan(input) {
199
214
  const span = {
@@ -205,7 +220,7 @@ export function compilePlayback(lowering, options) {
205
220
  sourceSpans: [{ ...node.ast.sourceSpan }],
206
221
  };
207
222
  spans.push(span);
208
- if (inheritedScales.length)
223
+ if (inheritedScales)
209
224
  spanScales.set(span, inheritedScales);
210
225
  return span;
211
226
  }
@@ -213,8 +228,7 @@ export function compilePlayback(lowering, options) {
213
228
  const program = node.playbackState?.program;
214
229
  if (program !== undefined && activePrograms.get(track) !== program) {
215
230
  activePrograms.set(track, program);
216
- events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++,
217
- origins: lineage, track, program });
231
+ events.push({ kind: "program-change", at: start.clone(), order: nextEventOrder++, track, program });
218
232
  }
219
233
  const bpm = node.playbackState?.bpm;
220
234
  if (bpm !== undefined)
@@ -228,12 +242,13 @@ export function compilePlayback(lowering, options) {
228
242
  note(input) {
229
243
  const note = publishSpan(input);
230
244
  notes.push(note);
231
- if (inheritedTransforms.length)
245
+ if (inheritedTransforms)
232
246
  transforms.set(note, inheritedTransforms);
233
247
  },
234
248
  /** 延长原区间,并把当前访问携带的效果定位到新增部分 */
235
249
  extend(span) {
236
- if (!spans.includes(span) || !span.end.equals(start) || duration.compare(0) <= 0) {
250
+ // 待延长目标总在已发布末尾附近,反向查找无需额外 Set 即可 O(1) 命中
251
+ if (spans.lastIndexOf(span) < 0 || !span.end.equals(start) || duration.compare(0) <= 0) {
237
252
  throw new ErrorDiagnostic("E_PLAYBACK_EXTEND_RANGE", "扩展必须接续当前计划内的区间且时值为正", node.ast.sourceSpan);
238
253
  }
239
254
  const previousDuration = span.end.clone().sub(span.start);
@@ -243,15 +258,16 @@ export function compilePlayback(lowering, options) {
243
258
  ? { ...scale, startRatio: scale.startRatio.clone().mul(previousDuration).div(extendedDuration) }
244
259
  : scale);
245
260
  // 新效果从旧终点开始;保存比例后,后续整体结构缩放仍能同步移动它的起点
246
- for (const scale of inheritedScales) {
247
- scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
261
+ if (inheritedScales) {
262
+ for (const scale of inheritedScales) {
263
+ scales.push({ ...scale, startRatio: previousDuration.clone().div(extendedDuration) });
264
+ }
248
265
  }
249
266
  if (scales.length)
250
267
  spanScales.set(span, scales);
251
268
  span.end.add(duration);
252
269
  },
253
- emit: event => events.push({ ...event, at: event.at.clone(),
254
- order: nextEventOrder++, origins: lineage }),
270
+ emit: event => events.push({ ...event, at: event.at.clone(), order: nextEventOrder++ }),
255
271
  control: (at, apply) => scheduleControl(at, lineage, apply),
256
272
  /** 只登记效果身份和比例,范围等结构与连接确定后再计算 */
257
273
  scaleFollowingBpm(key, numerator, denominator = 1, options) {
@@ -269,12 +285,13 @@ export function compilePlayback(lowering, options) {
269
285
  origins: lineage });
270
286
  },
271
287
  affectFollowing: transform => activeTransforms.push(transform),
272
- defer: hook => deferred.push(hook),
273
- play: (child, childStart, childDuration) => play(child, childTransforms, childScales, childStart ?? start, childDuration ?? duration, lineage, track),
288
+ defer: hook => (deferred ??= []).push(hook),
289
+ play: (child, childStart, childDuration) => play(child, childTransforms ??= [...activeTransforms], childScales ??= [...activeScales], childStart ?? start, childDuration ?? duration, lineage, track),
274
290
  });
275
291
  // 当前节点发布完成就执行结构处理,因此 hook 只能看到当前位置此前的目标
276
- for (const hook of deferred)
277
- hook(structureContext);
292
+ if (deferred)
293
+ for (const hook of deferred)
294
+ hook(structureContext);
278
295
  }
279
296
  const order = linearizeColumns(lowering, diagnostics, maxFlowSteps);
280
297
  const firstScore = lowering.columns[order[0]]?.[0]?.t.clone() ?? new Fraction();
@@ -289,6 +306,8 @@ export function compilePlayback(lowering, options) {
289
306
  const index = order[step];
290
307
  // 同列各顶层访问共享演奏坐标,但分别建立自己的效果作用域
291
308
  for (const node of lowering.columns[index]) {
309
+ if (!node.playbackState && !node.emitPlayback)
310
+ continue;
292
311
  play(node, [], [], node.t.clone().add(shift), node.T.clone());
293
312
  }
294
313
  const boundary = lowering.columns[index + 1]?.[0]?.t ?? lowering.duration; // 当前列的控制终点
@@ -326,7 +345,7 @@ export function compilePlayback(lowering, options) {
326
345
  Object.freeze(span.sourceSpans);
327
346
  Object.freeze(span);
328
347
  }
329
- const noteSet = new Set(notes);
348
+ let noteSet;
330
349
  const connections = new Map();
331
350
  const predecessors = new Map();
332
351
  const relationContext = {
@@ -334,6 +353,7 @@ export function compilePlayback(lowering, options) {
334
353
  diagnostics,
335
354
  /** 只建立一进一出的逻辑连接,保留两个音段各自的边界和修饰 */
336
355
  connect(from, to) {
356
+ noteSet ??= new Set(notes);
337
357
  if (!noteSet.has(from) || !noteSet.has(to) || !from.end.equals(to.start)) {
338
358
  throw new ErrorDiagnostic("E_PLAYBACK_CONNECTION", "音段连接必须属于当前计划且时间相接", from.sourceSpans[0]);
339
359
  }
@@ -350,23 +370,19 @@ export function compilePlayback(lowering, options) {
350
370
  if (isPlaybackRelation(attachment))
351
371
  attachment.applyPlayback(relationContext);
352
372
  }
353
- const reverseNotes = [...notes].sort((left, right) => right.start.compare(left.start));
354
- const connectedEnds = new Map();
355
- // 连接严格向未来推进;逆序处理保证后继的链尾已知,一次算出所有逻辑终点
356
- for (const note of reverseNotes) {
357
- const next = connections.get(note);
358
- const end = next ? connectedEnds.get(next) : note.end;
359
- connectedEnds.set(note, end);
360
- }
361
373
  // 将有声、无声区间上的效果转换为进入和退出边界,交给同一条全局状态时间线
362
- for (const span of spans) {
363
- const end = connectedEnds.get(span) ?? span.end;
374
+ for (const [span, scales] of spanScales) {
375
+ let tail = span;
376
+ if (scales.some(scale => scale.followConnections)) {
377
+ while (connections.has(tail))
378
+ tail = connections.get(tail);
379
+ }
364
380
  // 连接只可能延续效果终点;每个效果仍从自己在原区间内的位置开始
365
- for (const scale of spanScales.get(span) ?? []) {
381
+ for (const scale of scales) {
366
382
  const start = scale.startRatio
367
383
  ? span.start.clone().add(span.end.clone().sub(span.start).mul(scale.startRatio))
368
384
  : span.start;
369
- changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? end : span.end,
385
+ changes.push({ kind: "scale", at: start, origins: scale.origins, scale, delta: 1 }, { kind: "scale", at: scale.followConnections ? tail.end : span.end,
370
386
  origins: scale.origins, scale, delta: -1 });
371
387
  }
372
388
  }
@@ -383,12 +399,11 @@ export function compilePlayback(lowering, options) {
383
399
  // 结构与连接全部确定后,只扫描一次状态;后续声音变换统一读取这份最终结果
384
400
  while (changeIndex < changes.length) {
385
401
  const at = changes[changeIndex].at;
386
- const origins = new Set();
402
+ let lastOrigin;
387
403
  // 同刻控制和效果边界全部应用后才生成快照,避免输出由扫描顺序造成的瞬时速度
388
404
  while (changeIndex < changes.length && changes[changeIndex].at.equals(at)) {
389
405
  const change = changes[changeIndex++];
390
- for (const origin of change.origins)
391
- origins.add(origin);
406
+ lastOrigin = change.origins.at(-1) ?? lastOrigin;
392
407
  if (change.kind === "control")
393
408
  change.apply(system);
394
409
  else if (change.kind === "scale") {
@@ -410,7 +425,7 @@ export function compilePlayback(lowering, options) {
410
425
  effectiveBpm: system.bpm * bpmScale.toNumber(),
411
426
  };
412
427
  if (!Number.isFinite(snapshot.effectiveBpm) || snapshot.effectiveBpm <= 0) {
413
- throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", [...origins].at(-1)?.node.ast.sourceSpan ?? { start: 0, end: 0 });
428
+ throw new ErrorDiagnostic("E_PLAYBACK_BPM", "系统控制产生了无效速度", lastOrigin?.node.ast.sourceSpan ?? { start: 0, end: 0 });
414
429
  }
415
430
  const previous = statePoints.at(-1)?.state;
416
431
  if (!previous || previous.bpm !== snapshot.bpm || !previous.bpmScale.equals(bpmScale)) {
@@ -423,7 +438,6 @@ export function compilePlayback(lowering, options) {
423
438
  at: at.clone(),
424
439
  bpm: snapshot.effectiveBpm,
425
440
  order: nextEventOrder++,
426
- origins: [...origins],
427
441
  });
428
442
  }
429
443
  }
@@ -445,57 +459,92 @@ export function compilePlayback(lowering, options) {
445
459
  return { ...snapshot, bpmScale: snapshot.bpmScale.clone() };
446
460
  },
447
461
  };
462
+ const canAbsorb = (from, to) => !transforms.has(to)
463
+ && from.track === to.track && from.midi === to.midi && from.percussion === to.percussion;
464
+ const audible = new Set();
448
465
  const realized = new Map();
449
- // 每个逻辑音段独立展开声音,连接不会让后一段继承前一段的装饰
466
+ // 后继无独立变换时直接并入前驱音段,使首段装饰与奏法覆盖连续连音;有新变换时从该处分段并在交界处合并同音
450
467
  for (const note of notes) {
451
- let owned = [{ ...note, start: note.start.clone(), end: note.end.clone() }];
452
- // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
453
- for (const transform of transforms.get(note) ?? []) {
454
- owned = transform(transformContext, owned) ?? owned;
468
+ const previous = predecessors.get(note);
469
+ if (previous && canAbsorb(previous, note))
470
+ continue;
471
+ let tail = note;
472
+ let next = connections.get(tail);
473
+ let mergedSpans;
474
+ while (next && canAbsorb(tail, next)) {
475
+ connections.delete(tail);
476
+ mergedSpans ??= [...note.sourceSpans];
477
+ mergedSpans.push(...next.sourceSpans);
478
+ tail = next;
479
+ next = connections.get(tail);
455
480
  }
456
- let first;
457
- let last;
458
- // 各子音必须留在原区间内;同时收集整体边界,防止声音阶段改写已确定的结构范围
459
- for (const sound of owned) {
460
- if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
461
- || sound.start.compare(note.start) < 0 || sound.end.compare(note.end) > 0
462
- || sound.end.compare(sound.start) <= 0) {
463
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
481
+ if (tail !== note) {
482
+ connections.delete(tail);
483
+ if (next)
484
+ connections.set(note, next);
485
+ }
486
+ const segmentEnd = tail.end;
487
+ const segmentSpans = mergedSpans ? Object.freeze(mergedSpans) : note.sourceSpans;
488
+ const noteTransforms = transforms.get(note);
489
+ let owned;
490
+ if (noteTransforms) {
491
+ owned = [{ ...note, start: note.start.clone(), end: segmentEnd.clone(), sourceSpans: segmentSpans }];
492
+ // 变换按登记顺序消费上一项的结果,每项对这个逻辑音段只执行一次
493
+ for (const transform of noteTransforms) {
494
+ owned = transform(transformContext, owned) ?? owned;
495
+ }
496
+ let first;
497
+ // 各子音必须留在原区间内;同时收集整体起点,防止声音阶段延迟起音或返回空结果
498
+ for (const sound of owned) {
499
+ if (!Number.isFinite(sound.start.toNumber()) || !Number.isFinite(sound.end.toNumber())
500
+ || sound.start.compare(note.start) < 0 || sound.end.compare(segmentEnd) > 0
501
+ || sound.end.compare(sound.start) <= 0) {
502
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须位于原音段区间内且时值为正", note.sourceSpans[0]);
503
+ }
504
+ if (!first || sound.start.compare(first) < 0)
505
+ first = sound.start;
506
+ }
507
+ if (!first?.equals(note.start)) {
508
+ throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起点", note.sourceSpans[0]);
464
509
  }
465
- if (!first || sound.start.compare(first) < 0)
466
- first = sound.start;
467
- if (!last || sound.end.compare(last) > 0)
468
- last = sound.end;
469
510
  }
470
- if (!first?.equals(note.start) || !last?.equals(note.end)) {
471
- throw new ErrorDiagnostic("E_PLAYBACK_TRANSFORM_RANGE", "声音展开必须保持原音段的起止边界", note.sourceSpans[0]);
511
+ else {
512
+ owned = [tail === note ? note : { ...note, end: segmentEnd, sourceSpans: segmentSpans }];
472
513
  }
473
- // 现在才分配实际音符身份;变换专用字段不再进入点事件,配对留给边界合并使用
474
- realized.set(note, owned.map(sound => {
475
- const { start, end, track, midi, velocity, percussion, origins, sourceSpans } = sound;
514
+ // 现在才分配实际音符身份;仅分段后仍存在跨段连接的音段需要记录事件对供边界合并
515
+ const pairs = (next !== undefined || previous !== undefined)
516
+ ? []
517
+ : undefined;
518
+ for (const sound of owned) {
519
+ const { start, end, track, midi, velocity, percussion, sourceSpans } = sound;
476
520
  const noteId = nextNoteId++;
477
521
  const on = {
478
522
  kind: "note-on", at: start.clone(), noteId, order: nextEventOrder++,
479
523
  track, midi, velocity, percussion,
480
- origins: [...origins], sourceSpans: sourceSpans.map(span => ({ ...span })),
524
+ sourceSpans: [...sourceSpans],
481
525
  };
482
526
  const off = {
483
- kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++, origins: [...origins],
527
+ kind: "note-off", at: end.clone(), noteId, order: nextEventOrder++,
528
+ track, midi,
484
529
  };
530
+ audible.add(track);
485
531
  events.push(on, off);
486
- return { on, off };
487
- }));
532
+ pairs?.push({ on, off });
533
+ }
534
+ if (pairs)
535
+ realized.set(note, pairs);
488
536
  }
489
537
  const removed = new Set();
490
538
  const joinedSources = new Map();
539
+ const connectedNotes = connections.size > 1
540
+ ? [...connections.keys()].sort((left, right) => right.start.compare(left.start))
541
+ : connections.keys();
491
542
  // 后继先完成合并,前驱便可直接接到它更新后的终点;仅合并连接处实际同音的事件
492
- for (const note of reverseNotes) {
543
+ for (const note of connectedNotes) {
493
544
  const next = connections.get(note);
494
- if (!next)
495
- continue;
496
545
  // 只有到达原音段末端的子音可以跨边界连接,中间子音保留自己的起止
497
546
  for (const tail of realized.get(note)) {
498
- if (!tail.off.at.equals(note.end))
547
+ if (!tail.off.at.equals(next.start))
499
548
  continue;
500
549
  const head = realized.get(next).find(pair => !removed.has(pair.on)
501
550
  && pair.on.at.equals(next.start) && pair.on.track === tail.on.track
@@ -516,9 +565,9 @@ export function compilePlayback(lowering, options) {
516
565
  on.sourceSpans.push(...next.sourceSpans);
517
566
  }
518
567
  }
519
- // 稳定排序后,由统一出口检查配对、压实轨道编号并剥离编译期字段
568
+ // 稳定排序后,由统一出口压实轨道编号并剥离编译期字段
520
569
  const finalEvents = (removed.size ? events.filter(event => !removed.has(event)) : events).sort(comparePlaybackDraftEvents);
521
- const output = finalizePlaybackEvents(finalEvents, lowering.tracks);
570
+ const output = finalizePlaybackEvents(finalEvents, lowering.tracks, audible);
522
571
  const eventEnd = finalEvents.at(-1)?.at;
523
572
  if (eventEnd && eventEnd.compare(performanceEnd) > 0)
524
573
  performanceEnd.copyFrom(eventEnd);
@@ -46,9 +46,8 @@ export interface PlaybackOrigin {
46
46
  interface PlaybackDraftEventBase {
47
47
  at: Fraction;
48
48
  order: number;
49
- origins: PlaybackOrigin[];
50
49
  }
51
- /** 声音展开后生成的点事件;最终输出前会校验并剥离内部字段 */
50
+ /** 声音展开后生成的点事件;最终输出前压实轨道编号并剥离编译期字段 */
52
51
  export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
53
52
  kind: "note-on";
54
53
  noteId: PlaybackNoteId;
@@ -56,12 +55,13 @@ export interface PlaybackDraftNoteOnEvent extends PlaybackDraftEventBase {
56
55
  midi: number;
57
56
  velocity: number;
58
57
  percussion?: true;
59
- transpose?: (steps: number) => number;
60
58
  sourceSpans: SourceSpan[];
61
59
  }
62
60
  export interface PlaybackDraftNoteOffEvent extends PlaybackDraftEventBase {
63
61
  kind: "note-off";
64
62
  noteId: PlaybackNoteId;
63
+ track: Track;
64
+ midi: number;
65
65
  }
66
66
  export interface PlaybackDraftTempoEvent extends PlaybackDraftEventBase {
67
67
  kind: "tempo";
@@ -87,10 +87,10 @@ export interface PlaybackEventInput {
87
87
  /** 同刻先处理系统状态,再关音和开音;相同类别保持原发布次序 */
88
88
  export declare function comparePlaybackDraftEvents(left: PlaybackDraftEvent, right: PlaybackDraftEvent): number;
89
89
  /**
90
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
90
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
91
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
92
92
  */
93
- export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[]): {
93
+ export declare function finalizePlaybackEvents(events: readonly PlaybackDraftEvent[], trackOrder: readonly Track[], audible: ReadonlySet<Track>): {
94
94
  events: PlaybackEvent[];
95
95
  tracks: Track[];
96
96
  };
@@ -11,44 +11,10 @@ export function comparePlaybackDraftEvents(left, right) {
11
11
  return byTime || EVENT_PRIORITY[left.kind] - EVENT_PRIORITY[right.kind] || left.order - right.order;
12
12
  }
13
13
  /**
14
- * 校验配对、压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
- * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象和音符配对转换为公开字段
14
+ * 压实发声 Track 编号并剥掉编译期字段,得到稳定、可序列化的公开事件
15
+ * 输入已经稳定排序;这里保留次序,将编译期的 Track 对象转换为公开通道编号
16
16
  */
17
- export function finalizePlaybackEvents(events, trackOrder) {
18
- const noteOns = new Map();
19
- const noteOffs = new Map();
20
- // 同一音符的两端不一定相邻,先按 noteId 建立索引并拒绝重复的开音或关音
21
- for (const event of events) {
22
- if (event.kind === "note-on") {
23
- if (noteOns.has(event.noteId))
24
- throw new Error(`Duplicate NoteOn ${event.noteId}`);
25
- noteOns.set(event.noteId, event);
26
- }
27
- else if (event.kind === "note-off") {
28
- if (noteOffs.has(event.noteId))
29
- throw new Error(`Duplicate NoteOff ${event.noteId}`);
30
- noteOffs.set(event.noteId, event);
31
- }
32
- }
33
- // 物理合并完成后仍必须一一配对,并保留正时值和可追溯的来源
34
- for (const [noteId, on] of noteOns) {
35
- const off = noteOffs.get(noteId);
36
- if (!off)
37
- throw new Error(`Note ${noteId} has no NoteOff`);
38
- if (off.at.compare(on.at) <= 0)
39
- throw new Error(`Note ${noteId} has a non-positive duration`);
40
- if (on.origins.length === 0 || off.origins.length === 0)
41
- throw new Error(`Note ${noteId} has no origin`);
42
- }
43
- // 再从关音侧反查,避免只检查开音时漏掉孤立的 NoteOff
44
- for (const noteId of noteOffs.keys()) {
45
- if (!noteOns.has(noteId))
46
- throw new Error(`NoteOff ${noteId} has no NoteOn`);
47
- }
48
- const audible = new Set();
49
- // 只从实际 NoteOn 收集轨道,无声区间和纯布局轨道不占输出编号
50
- for (const on of noteOns.values())
51
- audible.add(on.track);
17
+ export function finalizePlaybackEvents(events, trackOrder, audible) {
52
18
  // 保留 lowering 的稳定轨道顺序,只过滤未实际发声的轨道
53
19
  const trackIds = new Map();
54
20
  for (const track of trackOrder) {
@@ -76,20 +42,18 @@ export function finalizePlaybackEvents(events, trackOrder) {
76
42
  });
77
43
  continue;
78
44
  }
45
+ const track = trackIds.get(event.track);
46
+ if (track === undefined)
47
+ continue;
79
48
  if (event.kind === "program-change") {
80
- const track = trackIds.get(event.track);
81
- if (track !== undefined)
82
- output.push({
83
- kind: "program-change",
84
- at: event.at,
85
- track,
86
- program: event.program,
87
- });
49
+ output.push({
50
+ kind: "program-change",
51
+ at: event.at,
52
+ track,
53
+ program: event.program,
54
+ });
88
55
  continue;
89
56
  }
90
- // NoteOff 从配对的 NoteOn 取得轨道和键号,保证两端始终使用相同的最终身份
91
- const on = event.kind === "note-on" ? event : noteOns.get(event.noteId);
92
- const track = trackIds.get(on.track);
93
57
  if (event.kind === "note-on") {
94
58
  output.push({
95
59
  kind: "note-on",
@@ -108,7 +72,7 @@ export function finalizePlaybackEvents(events, trackOrder) {
108
72
  at: event.at,
109
73
  noteId: event.noteId,
110
74
  track,
111
- midi: on.midi,
75
+ midi: event.midi,
112
76
  });
113
77
  }
114
78
  return { events: output, tracks: [...trackIds.keys()] };
@@ -1,7 +1,11 @@
1
1
  import { DEFAULT_BPM } from "../functions/temporal.js";
2
- /** 演奏时间(QN)按分段速度积分为秒 */
3
- export function performanceTimeToSeconds(events, performanceTime) {
4
- const target = Math.max(0, performanceTime);
2
+ const tempoSegmentsCache = new WeakMap();
3
+ /** 提取并缓存分段速度积分表,使帧级时间换算无需重复扫描全部音符事件 */
4
+ function tempoSegmentsOf(events) {
5
+ let segments = tempoSegmentsCache.get(events);
6
+ if (segments)
7
+ return segments;
8
+ const built = [{ performance: 0, seconds: 0, bpm: DEFAULT_BPM }];
5
9
  let seconds = 0;
6
10
  let position = 0;
7
11
  let bpm = DEFAULT_BPM;
@@ -9,43 +13,50 @@ export function performanceTimeToSeconds(events, performanceTime) {
9
13
  if (event.kind !== "tempo")
10
14
  continue;
11
15
  const next = event.at.toNumber();
12
- if (next > target)
13
- break;
14
- if (next > position)
16
+ if (next > position) {
15
17
  seconds += (next - position) * 60 / bpm;
16
- position = next;
18
+ position = next;
19
+ }
17
20
  bpm = event.bpm;
21
+ const last = built[built.length - 1];
22
+ if (last.performance === position)
23
+ last.bpm = bpm;
24
+ else
25
+ built.push({ performance: position, seconds, bpm });
18
26
  }
19
- return seconds + (target - position) * 60 / bpm;
27
+ tempoSegmentsCache.set(events, built);
28
+ return built;
20
29
  }
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;
30
+ function stepAt(items, target, valueOf) {
31
+ let low = 0;
32
+ let high = items.length;
33
+ while (low < high) {
34
+ const middle = (low + high) >>> 1;
35
+ if (valueOf(items[middle]) <= target)
36
+ low = middle + 1;
37
+ else
38
+ high = middle;
35
39
  }
36
- return position + remaining * bpm / 60;
40
+ return items[Math.max(0, low - 1)];
41
+ }
42
+ /** 演奏时间(QN)按分段速度积分为秒 */
43
+ export function performanceTimeToSeconds(events, performanceTime) {
44
+ const target = Math.max(0, performanceTime);
45
+ const segment = stepAt(tempoSegmentsOf(events), target, item => item.performance);
46
+ return segment.seconds + (target - segment.performance) * 60 / segment.bpm;
47
+ }
48
+ export function secondsToPerformanceTime(events, seconds) {
49
+ const target = Math.max(0, seconds);
50
+ const segment = stepAt(tempoSegmentsOf(events), target, item => item.seconds);
51
+ return segment.performance + (target - segment.seconds) * segment.bpm / 60;
37
52
  }
38
53
  /** 演奏进度换算为谱面进度 */
39
54
  export function performanceTimeToScoreTime(scoreMap, performanceTime) {
40
55
  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;
56
+ const point = stepAt(scoreMap, target, item => item.performance.toNumber());
57
+ return point && point.performance.toNumber() <= target
58
+ ? point.score.toNumber() + target - point.performance.toNumber()
59
+ : target;
49
60
  }
50
61
  /**
51
62
  * 谱面位置换算为演奏时间,供“点击谱面从这里播放”使用
@@ -92,7 +92,7 @@ export interface PlaybackNote extends PlaybackNoteInput, PlaybackSpan {
92
92
  }
93
93
  /** 当前节点发布完成后,修改此前音段的结构;此时尚未生成系统状态 */
94
94
  export type PlaybackHook = (context: PlaybackHookContext) => void;
95
- /** 在最终状态下展开一个音段;结果须保持原音段的起止边界 */
95
+ /** 在最终状态下展开一个音段;结果须位于原音段区间内并保持原起点 */
96
96
  export type PlaybackTransform = (context: PlaybackTransformContext, notes: PlaybackNote[]) => PlaybackNote[] | void;
97
97
  /** 结构阶段的已发布前缀;集合只读,其中区间的边界仍可调整 */
98
98
  export interface PlaybackHookContext {
@@ -101,6 +101,8 @@ export interface PlaybackHookContext {
101
101
  /** 按发布顺序排列,仅包含当前位置此前已发布的有声音段 */
102
102
  readonly notes: readonly PlaybackNote[];
103
103
  readonly diagnostics: Diagnostic[];
104
+ /** 为当前计划内的已发布音段追加声音展开变换 */
105
+ transform(note: PlaybackNote, transform: PlaybackTransform): void;
104
106
  }
105
107
  /** 声音阶段只查询最终状态,接口不提供全局区间的写入口 */
106
108
  export interface PlaybackTransformContext {