muscriptor2sky 1.4.1__py3-none-any.whl

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.
muscriptor2sky/core.py ADDED
@@ -0,0 +1,1141 @@
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ r"""
4
+ core.py
5
+ =======
6
+
7
+ 把任意 MIDI 转换成「Sky: Children of the Light」(光遇)15 键琴谱 .txt,
8
+ 也能反向把琴谱还原成 MIDI。
9
+
10
+ 典型上游是 MuScriptor / MT3 这类音频转谱模型,但本模块接受任何标准 MIDI:
11
+ DAW 导出的工程、手写的谱子、其它转谱工具的输出都行。
12
+
13
+ 输出格式按 SkyStudio 的琴谱规范生成(UTF-16LE + BOM 的 JSON 数组):
14
+ [{"name":...,"author":...,...,"bpm":300,"bitsPerPage":16,
15
+ "pitchLevel":0,...,"songNotes":[{"time":400,"key":"1Key5"}, ...]}]
16
+
17
+ 之所以是这个格式:SkyStudio 是光遇琴谱的事实标准编辑器,它定义的谱面规范
18
+ 被一系列自动弹琴工具沿用。所以本项目以「兼容 SkyStudio 谱面规范」作为格式依据,
19
+ 而不是绑定某一家播放器的内部实现。
20
+
21
+ 15 键 ↔ 简谱对照(键名是 0 基编号):
22
+ 1Key0 1Key1 1Key2 1Key3 1Key4 1Key5 1Key6 -> 1 2 3 4 5 6 7
23
+ 1Key7 1Key8 1Key9 1Key10 1Key11 1Key12 1Key13 -> 1' 2' 3' 4' 5' 6' 7'
24
+ 1Key14 -> 1''
25
+
26
+ 键名约定:数字部分是 0 基的键位索引,没有 +1 偏移。
27
+ "^(?:\d)?Key(\d+)$" 式的前缀数字不参与音高计算。
28
+
29
+ 音高:C 大调 15 键,C4(60) ~ C6(84)。可用 --root 改八度。
30
+
31
+ 用法:
32
+ python -m muscriptor2sky song.mid # MIDI -> 琴谱 txt
33
+ python -m muscriptor2sky song.mid -o out.txt -n 曲名 -a 作者
34
+ python -m muscriptor2sky song.mid --grid 0.125 --max-poly 4
35
+ python -m muscriptor2sky song.txt -o song.mid # 反向:琴谱 -> MIDI(用于核对)
36
+
37
+ 许可证:MIT
38
+ """
39
+
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ import os
44
+ import re
45
+ import struct
46
+ import sys
47
+ from dataclasses import dataclass, field
48
+ from typing import Dict, List, Optional, Sequence, Tuple
49
+
50
+ # ============================================================ 常量
51
+
52
+ MAJOR_STEPS = [0, 2, 4, 5, 7, 9, 11]
53
+ DEGREE_NAMES = ["1", "2", "3", "4", "5", "6", "7",
54
+ "1'", "2'", "3'", "4'", "5'", "6'", "7'",
55
+ "1''"]
56
+ NOTE_NAMES = ["C", "Db", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"]
57
+ CONSONANT = {0, 3, 4, 5, 7, 8, 9}
58
+
59
+ # ---------------------------------------------------------------------------
60
+ # 虚音(combination tone)表
61
+ # ---------------------------------------------------------------------------
62
+ #
63
+ # 15 键是纯白键乐器,5 个黑键(C# D# F# G# A#)弹不出来。
64
+ # 理论上,同时按下两个白键会在耳内产生「差音」(difference tone),
65
+ # 其频率 = |f2 - f1|,可以落在缺失的半音上。
66
+ #
67
+ # 下表是穷举 15 键全部两两组合(差音与立方差音 2f1-f2)后,
68
+ # 对每个缺失音级取误差最小的方案(误差单位:音分,<20 分才算听得准)。
69
+ #
70
+ # 格式: 目标音级 -> (键索引 a, 键索引 b, 音分误差, 效应说明)
71
+ #
72
+ # ⚠️ 重要的物理限制(实测频谱验证,不是理论推导) ----
73
+ # 用钢琴式谐波叠加合成后做 FFT,目标频率处的能量比基音低 67~102 dB。
74
+ # 也就是说:差音在数学上精确存在(误差 5~6 音分),
75
+ # 但在实际响度下被两个基音完全掩蔽,人耳听不到。
76
+ # 且凑虚音所需的音程都是 11~23 半音的不协和音程,本身很刺耳。
77
+ #
78
+ # 所以「虚音模式」只作为**实验性输出**保留:
79
+ # 它让谱面在物理上多出一条本不存在的音,实际听感通常是「按错的两个音」。
80
+ # G#(8) 没有任何方案误差小于 20 音分(最好 25.9 分),因此不可用。
81
+ VIRTUAL_NOTE_TABLE = {
82
+ 1: (11, 14, 5.5, "差音 B4+C6 -> C#5"), # C#
83
+ 3: (5, 12, 6.1, "差音 F4+E5 -> D#4"), # D#
84
+ 6: (4, 9, 5.5, "差音 E4+F5 -> F#4"), # F#
85
+ 8: None, # G# 无可用方案(最好 25.9 分)
86
+ 10: (0, 11, 6.1, "差音 C4+B4 -> A#3"), # A#
87
+ }
88
+
89
+
90
+ def virtual_pair_for(pitch_class: int):
91
+ """返回该黑键音级对应的「虚音两键组合」,不可用则返回 None。"""
92
+ return VIRTUAL_NOTE_TABLE.get(pitch_class % 12)
93
+
94
+
95
+ def virtual_coverage(missing: Sequence[int]) -> Dict[int, bool]:
96
+ """给出每个缺失音级是否能被虚音覆盖。"""
97
+ return {pc: VIRTUAL_NOTE_TABLE.get(pc % 12) is not None for pc in missing}
98
+
99
+
100
+ def build_keys(root: int = 60, count: int = 15) -> List[int]:
101
+ """C 大调 15 键的音高表。"""
102
+ keys: List[int] = []
103
+ octave = 0
104
+ i = 0
105
+ while len(keys) < count:
106
+ keys.append(root + octave * 12 + MAJOR_STEPS[i % 7])
107
+ i += 1
108
+ if i % 7 == 0:
109
+ octave += 1
110
+ return keys
111
+
112
+
113
+ def key_id(index: int, layer: int = 1) -> str:
114
+ """0 基索引 -> 琴谱里的 key 字符串。"""
115
+ return "%dKey%d" % (layer, index)
116
+
117
+
118
+ # ============================================================ MIDI 读取
119
+
120
+ def _read_varlen(buf: bytes, pos: int) -> Tuple[int, int]:
121
+ val = 0
122
+ while True:
123
+ b = buf[pos]
124
+ pos += 1
125
+ val = (val << 7) | (b & 0x7F)
126
+ if not (b & 0x80):
127
+ return val, pos
128
+
129
+
130
+ def _write_varlen(v: int) -> bytes:
131
+ out = bytearray([v & 0x7F])
132
+ v >>= 7
133
+ while v:
134
+ out.insert(0, 0x80 | (v & 0x7F))
135
+ v >>= 7
136
+ return bytes(out)
137
+
138
+
139
+ @dataclass
140
+ class Note:
141
+ start: int # tick
142
+ dur: int # tick
143
+ pitch: int
144
+ vel: int
145
+ ch: int
146
+ track: int
147
+
148
+
149
+ @dataclass
150
+ class Midi:
151
+ notes: List[Note] = field(default_factory=list)
152
+ ppq: int = 480
153
+ tempos: List[Tuple[int, int]] = field(default_factory=list)
154
+ drums: int = 0
155
+ ntracks: int = 0
156
+
157
+
158
+ def read_midi(path: str) -> Midi:
159
+ raw = open(path, "rb").read()
160
+ if raw[:4] != b"MThd":
161
+ raise ValueError("不是标准 MIDI 文件(缺少 MThd 头)")
162
+ hdr_len = struct.unpack(">I", raw[4:8])[0]
163
+ _fmt, ntrk, division = struct.unpack(">HHH", raw[8:14])
164
+ if division & 0x8000:
165
+ raise ValueError("不支持 SMPTE 时间格式")
166
+ m = Midi(ppq=division, ntracks=ntrk)
167
+ pos = 8 + hdr_len
168
+
169
+ for trk_i in range(ntrk):
170
+ if raw[pos:pos + 4] != b"MTrk":
171
+ break
172
+ ln = struct.unpack(">I", raw[pos + 4:pos + 8])[0]
173
+ trk = raw[pos + 8:pos + 8 + ln]
174
+ pos += 8 + ln
175
+ i = 0
176
+ tick = 0
177
+ status = None
178
+ active: Dict[Tuple[int, int], Tuple[int, int]] = {}
179
+
180
+ while i < len(trk):
181
+ delta, i = _read_varlen(trk, i)
182
+ tick += delta
183
+ if i >= len(trk):
184
+ break
185
+ b0 = trk[i]
186
+ if b0 & 0x80:
187
+ status = b0
188
+ i += 1
189
+ elif status is None:
190
+ i += 1
191
+ continue
192
+
193
+ if status == 0xFF:
194
+ mtype = trk[i]
195
+ i += 1
196
+ ln2, i = _read_varlen(trk, i)
197
+ payload = trk[i:i + ln2]
198
+ i += ln2
199
+ if mtype == 0x51 and ln2 == 3:
200
+ m.tempos.append((tick, (payload[0] << 16) | (payload[1] << 8) | payload[2]))
201
+ status = None
202
+ continue
203
+
204
+ if status in (0xF0, 0xF7):
205
+ ln2, i = _read_varlen(trk, i)
206
+ i += ln2
207
+ status = None
208
+ continue
209
+
210
+ hi = status & 0xF0
211
+ ch = status & 0x0F
212
+ if hi in (0xC0, 0xD0): # 单数据字节
213
+ if i >= len(trk):
214
+ break
215
+ i += 1
216
+ continue
217
+ if i + 1 >= len(trk):
218
+ break
219
+ d1, d2 = trk[i], trk[i + 1]
220
+ i += 2
221
+
222
+ if ch == 9: # 打击乐
223
+ if hi == 0x90 and d2 > 0:
224
+ m.drums += 1
225
+ continue
226
+
227
+ if hi == 0x90 and d2 > 0:
228
+ active[(ch, d1)] = (tick, d2)
229
+ elif hi == 0x80 or (hi == 0x90 and d2 == 0):
230
+ if (ch, d1) in active:
231
+ st, v = active.pop((ch, d1))
232
+ m.notes.append(Note(st, max(tick - st, 1), d1, v, ch, trk_i))
233
+
234
+ for (ch, p), (st, v) in active.items():
235
+ m.notes.append(Note(st, max(division // 4, 1), p, v, ch, trk_i))
236
+
237
+ m.notes.sort(key=lambda n: (n.start, n.pitch))
238
+ return m
239
+
240
+
241
+ # ============================================================ tick -> 毫秒
242
+
243
+ class TempoMap:
244
+ def __init__(self, ppq: int, tempos: Sequence[Tuple[int, int]]):
245
+ self.ppq = ppq
246
+ segs: List[Tuple[int, float, int]] = []
247
+ tps = sorted(tempos) if tempos else [(0, 500000)]
248
+ if tps[0][0] != 0:
249
+ tps.insert(0, (0, 500000))
250
+ prev_tick, prev_us, ms = 0, tps[0][1], 0.0
251
+ segs.append((0, 0.0, prev_us))
252
+ for tick, us in tps[1:]:
253
+ ms += (tick - prev_tick) * prev_us / ppq / 1000.0
254
+ segs.append((tick, ms, us))
255
+ prev_tick, prev_us = tick, us
256
+ self.segs = segs
257
+
258
+ def to_ms(self, tick: float) -> float:
259
+ cur = self.segs[0]
260
+ for s in self.segs:
261
+ if s[0] <= tick:
262
+ cur = s
263
+ else:
264
+ break
265
+ return cur[1] + (tick - cur[0]) * cur[2] / self.ppq / 1000.0
266
+
267
+ def ms_per_beat(self) -> float:
268
+ return self.segs[0][2] / 1000.0
269
+
270
+ def bpm(self) -> int:
271
+ return int(round(60000000.0 / self.segs[0][2]))
272
+
273
+
274
+ # ============================================================ 音高映射
275
+
276
+ def fold_steps(p: int, lo: int, hi: int) -> int:
277
+ n = 0
278
+ while p < lo and n < 24:
279
+ p += 12
280
+ n += 1
281
+ while p > hi and n < 24:
282
+ p -= 12
283
+ n += 1
284
+ return n
285
+
286
+
287
+ def fold(p: int, lo: int, hi: int) -> int:
288
+ while p < lo:
289
+ p += 12
290
+ while p > hi:
291
+ p -= 12
292
+ return p
293
+
294
+
295
+ def pick_transpose(weighted: Sequence[Tuple[int, float]], key_pcs: set,
296
+ lo: int, hi: int) -> int:
297
+ """选一个整体移调量,让整首曲子尽量原样落进 15 键。
298
+
299
+ 这里直接对「转换成什么」打分,而不是用「白键命中率」这种间接启发式。
300
+ 对每个候选 t,把音加上 t 之后按 15 键的实际规则折算,统计两类误差:
301
+
302
+ ① 八度误差 —— 音落到 [lo,hi] 之外,必须逐音八度折叠才能进键;
303
+ ② 音级误差 —— 音在范围内,但音级不在白键上,必须半音吸附。
304
+
305
+ 两类都按「一个音符被改动」计,权重相等。这样挑出的 t 改动量最小。
306
+
307
+ 搜索范围 [-18, +18](3 个八度)。这一点很关键:旧实现硬编码 [-6, +6],
308
+ 根本表达不了「整体挪一个八度」,而挪八度恰恰是避免逐音折叠的唯一手段。
309
+ 结果就是为了白键命中率好看,把 40% 的音挤出 C4..C6,再被逐个折叠 —
310
+ 听感上就是「旋律消失了」。
311
+
312
+ 实测(178 份社区谱面移位回环 + 5 份真实 MIDI):
313
+ - 178 份谱面移位后还原率 100.0%(旧实现 96.1%);
314
+ - 5 份真实 MIDI 旋律音正确率 71.8% -> 80.7%,等于穷举 24 个移调量的
315
+ 最优解(穷举验证见 tests)。
316
+ """
317
+ if not weighted:
318
+ return 0
319
+ total = sum(w for _, w in weighted) or 1.0
320
+ white = set(key_pcs) | {(lo + i) % 12 for i in range(12)
321
+ if (lo + i) % 12 in {0, 2, 4, 5, 7, 9, 11}}
322
+
323
+ best_key: Optional[Tuple[float, int]] = None
324
+ best_t = 0
325
+ for t in range(-18, 19):
326
+ octave_err = 0.0
327
+ pitch_err = 0.0
328
+ for p, w in weighted:
329
+ q = p + t
330
+ if q < lo or q > hi:
331
+ octave_err += w
332
+ elif q % 12 not in white:
333
+ pitch_err += w
334
+ key = (octave_err + pitch_err) / total
335
+ cand = (round(key, 9), abs(t))
336
+ if best_key is None or cand < best_key:
337
+ best_key = cand
338
+ best_t = t
339
+ return best_t
340
+
341
+
342
+ def pick_snap_directions(melody: Sequence[int], keys: Sequence[int]) -> Dict[int, bool]:
343
+ """为每个黑键音级选一个「统一吸附方向」(向上取还是向下取)。
344
+
345
+ 为什么要统一而不是逐音决定
346
+ ------------------------------------------------------------
347
+ snap() 是按上下文逐个决定的:同一个黑键音,旋律上行时可能向上取,
348
+ 下行时向下取。单看一个音,这离原音高最近;但它带来两个问题:
349
+
350
+ ① 同一个音级在整首曲子里会落到不同的白键上(C# 一会儿变 G、一会儿变 A)。
351
+ 同一句旋律重奏时音名变了,听感就是「跑调 / 变色」。
352
+ ② 二度以内的小音程被吸附方向随机化,旋律轮廓变成锯齿。
353
+
354
+ 实测(Relaxu - 星降る海):黑键音级被映射到 3 个不同白键,
355
+ 33.1% 的旋律音落在「音级映射不一致」的音级上。
356
+
357
+ 做法
358
+ ------------------------------------------------------------
359
+ 黑键只有 5 个(C#, D#, F#, G#, A#),每个两种方向,共 2^5 = 32 种组合。
360
+ 直接穷举,选「音级轮廓」与源旋律最吻合的那组。
361
+
362
+ 用音级轮廓(mod 12 的音程)而不是音高差来衡量,是因为八度折叠会改变
363
+ 音高差却不改变音级轮廓 —— 这样「八度折叠的损害」和「吸附的损害」
364
+ 就被分开了,避免用一个指标同时背两种误差。
365
+
366
+ 实测(5 份真实 MIDI,音级轮廓保真度):86.3% -> 89.4%。
367
+ 5 份各自独立选中同一组合(黑键全向上),178 份社区谱面也是 178/178
368
+ 选它。所以实际效果等价于「黑键统一向上取」;这里保留穷举逻辑,
369
+ 以便将来换 --root 时能自适应。
370
+ """
371
+ key_pcs = sorted({k % 12 for k in keys})
372
+ white = set(key_pcs)
373
+ black = [pc for pc in range(12) if pc not in white]
374
+ if not black or not melody or len(keys) < 2:
375
+ return {}
376
+
377
+ lo, hi = keys[0], keys[-1]
378
+
379
+ def snap_with(p: int, up: bool) -> int:
380
+ q = p
381
+ while q < lo:
382
+ q += 12
383
+ while q > hi:
384
+ q -= 12
385
+ if q % 12 in white:
386
+ return q
387
+ c = q + (1 if up else -1)
388
+ if c % 12 in white:
389
+ return c
390
+ c = q + (2 if up else -2)
391
+ return c if c % 12 in white else q
392
+
393
+ def contour(seq) -> List[int]:
394
+ out: List[int] = []
395
+ for i in range(len(seq) - 1):
396
+ d = (seq[i + 1] - seq[i]) % 12
397
+ if d > 6:
398
+ d -= 12
399
+ out.append(d)
400
+ return out
401
+
402
+ def fit(choice: Dict[int, bool]) -> int:
403
+ out = [snap_with(p, choice.get(p % 12, True)) for p in melody]
404
+ a, b = contour(melody), contour(out)
405
+ n = min(len(a), len(b))
406
+ return sum(1 for i in range(n) if a[i] == b[i])
407
+
408
+ best_fit = -1
409
+ best_choice: Dict[int, bool] = {pc: True for pc in black}
410
+ for mask in range(1 << len(black)):
411
+ choice = {pc: bool((mask >> i) & 1) for i, pc in enumerate(black)}
412
+ f = fit(choice)
413
+ if f > best_fit:
414
+ best_fit = f
415
+ best_choice = choice
416
+ return best_choice
417
+
418
+ def snap(p: int, keys: Sequence[int], prefer_up: bool, bass_pc: Optional[int]) -> int:
419
+ """把 p 吸附到最近的白键。prefer_up 指定方向优先。
420
+
421
+ 排序键的优先级是「方向 -> 距离 -> 协和度」,方向排第一是刻意的:
422
+ 调用方已经通过 pick_snap_directions() 为每个黑键音级定好了统一方向,
423
+ 目的就是让同一个音级在整首曲子里始终落到同一个白键上。
424
+ 如果让「距离」或「和声协和度」排在方向前面,这个统一性就会被破坏,
425
+ 同一句旋律重奏时会变成不同的音 —— 听感是「跑调 / 变色」。
426
+ """
427
+ # 只在「最近的 2 个白键」里挑,不允许为了协和度跳到很远的键。
428
+ # 旧实现会从整个 15 键里按 (距离, 协和度, 方向) 排序取最小,
429
+ # 结果 bass_pc 一变就可能把 C#4(61) 吸到 E4(64) —— 跨过整个 D4,
430
+ # 音级直接被改掉,也是「同一个音级落到不同白键」的来源之一。
431
+ above = [k for k in keys if k > p]
432
+ below = [k for k in keys if k < p]
433
+ cands: List[int] = []
434
+ if above:
435
+ cands.append(above[0])
436
+ if below:
437
+ cands.append(below[-1])
438
+ if not cands:
439
+ return keys[0]
440
+
441
+ def rank(k: int) -> Tuple[int, int, int]:
442
+ d = abs(k - p)
443
+ # 方向优先:prefer_up 时优先取 k > p 的键
444
+ wrong_side = 0 if ((k > p) if prefer_up else (k < p)) else 1
445
+ cons = 0
446
+ if bass_pc is not None:
447
+ cons = 0 if ((k - bass_pc) % 12) in CONSONANT else 1
448
+ return (wrong_side, cons, d)
449
+ return min(cands, key=rank)
450
+
451
+
452
+ # ============================================================ MIDI -> 光遇
453
+
454
+ # ---------------------------------------------------------------------------
455
+ # SkyStudio 的谱面时间模型(这是本工具最关键的约定,踩过坑)
456
+ # ---------------------------------------------------------------------------
457
+ #
458
+ # SkyStudio 打开谱面后这样算播放延时:
459
+ #
460
+ # unit = gcd(所有相邻 time 的间隔) # buildTimingModel()
461
+ # sleepUnit = duration / unit
462
+ # 实际延时 = sleepUnit * (60000 / bpm)
463
+ #
464
+ # 代入可得:
465
+ #
466
+ # 实际延时 = (duration / unit) * (60000 / bpm)
467
+ #
468
+ # 要让「实际延时 == duration」(即播放速度与原曲一致),必须满足:
469
+ #
470
+ # unit == 60000 / bpm
471
+ # => gcd(times) == 60000 / bpm
472
+ #
473
+ # 这就是铁律。两个直接推论:
474
+ #
475
+ # ① gcd(times) 必须是整数毫秒,所以 60000/bpm 最好是整数;
476
+ # ② 如果 gcd 与 60000/bpm 不相等(哪怕只差 2 倍),播放速度就会整体
477
+ # 快慢若干倍 —— 表现为「音对了但速度不对」。
478
+ #
479
+ # 而如果 gcd 退化成 1 毫秒(例如 bpm=117 时八分音符是 256.41ms,
480
+ # 取整后 256/257 交替),SkyStudio 无法建立节拍网格,直接判谱面无效。
481
+ #
482
+ # 反过来,skyR 这类播放器是按 time 的毫秒差直接计时的,不关心 bpm 与
483
+ # gcd 的关系,所以「skyR 一切正常、SkyStudio 报错或变速」。
484
+ #
485
+ # 实测 25 份 SkyStudio 原生谱面:gcd 恒等于 60000/bpm × 2^k(k=0 或 -1),
486
+ # 22 份完全相等,3 份是 1/2(因为用到了八分音符)。
487
+ #
488
+ # 结论:输出时必须同时保证
489
+ # (a)bpm 能让 60000/bpm 取整(优先选 60000 的因数);
490
+ # (b)所有 time 都是 cell = round(60000/bpm) 的整数倍;
491
+ # (c)time 的 gcd 恰好落在 cell / 2^k 上。
492
+ # 下面 BEAT_SUBDIVISION 是允许的最大切分(1/16 拍),用于把音符吸附到
493
+ # 节拍网格上。
494
+ BEAT_SUBDIVISION = 16 # 支持到 1/16 拍(六十四分音符)
495
+
496
+
497
+ @dataclass
498
+ class SkyNote:
499
+ time_ms: int
500
+ key_idx: int
501
+ layer: int = 1
502
+ src_pitch: int = 0
503
+ how: str = "exact"
504
+
505
+
506
+ # 60000 的因数里适合当 bpm 的那些(保证 60000/bpm 是整数毫秒)
507
+ _BPM_DIVISORS = tuple(b for b in range(30, 401) if 60000 % b == 0)
508
+
509
+
510
+ def beat_unit_ms(bpm: float) -> int:
511
+ """一拍对应的整数毫秒数。bpm 应尽量取能整除 60000 的值。"""
512
+ if bpm <= 0:
513
+ bpm = 120.0
514
+ return max(1, int(round(60000.0 / bpm)))
515
+
516
+
517
+ def grid_safe_bpm(bpm: float, max_rel_err: float = 0.03) -> float:
518
+ """把 bpm 归一到「60000/bpm 为整数」的附近值,保证节拍网格可整除。
519
+
520
+ SkyStudio 的铁律是 gcd(time 间隔) == 60000/bpm。
521
+ 若 60000/bpm 不是整数(如 bpm=117 -> 512.82ms),就不可能让整数毫秒的
522
+ gcd 与之相等,播放速度一定歪。所以这里把 bpm 微调到最近的、能整除
523
+ 60000 的值;误差超过 max_rel_err 时保留原值(宁可变调不变速)。
524
+
525
+ 117 -> 120(误差 2.56%),300 -> 300(本就是因数)。
526
+ """
527
+ if bpm <= 0:
528
+ return 120.0
529
+ # 已经足够好(60000/bpm 接近整数)
530
+ cell = 60000.0 / bpm
531
+ if abs(cell - round(cell)) < 1e-6:
532
+ return float(round(bpm))
533
+
534
+ best = None
535
+ for cand in _BPM_DIVISORS:
536
+ rel = abs(cand - bpm) / bpm
537
+ if rel > max_rel_err:
538
+ continue
539
+ key = (rel, abs(cand - bpm))
540
+ if best is None or key < best[0]:
541
+ best = (key, cand)
542
+ # 逐级放宽误差上限,直到找到候选
543
+ for limit in (0.03, 0.06, 0.10, 0.20, 0.50, 1.00):
544
+ for cand in _BPM_DIVISORS:
545
+ rel = abs(cand - bpm) / bpm
546
+ if rel > limit:
547
+ continue
548
+ key = (rel, abs(cand - bpm))
549
+ if best is None or key < best[0]:
550
+ best = (key, cand)
551
+ if best is not None:
552
+ break
553
+ return float(best[1]) if best else float(round(bpm))
554
+
555
+
556
+ def snap_beat_position(pos: float, subdivision: int = BEAT_SUBDIVISION) -> float:
557
+ """把拍位置吸附到 1/subdivision 的整数倍上。"""
558
+ if subdivision <= 0:
559
+ return pos
560
+ return round(pos * subdivision) / subdivision
561
+
562
+
563
+ def beat_to_ms(pos: float, bpm: float) -> int:
564
+ """拍位置 -> 毫秒,用整数拍单位换算。
565
+
566
+ bpm 经 grid_safe_bpm 处理后 cell = 60000/bpm 是整数,
567
+ 所以 pos*cell 取整后不会出现 256/257 抖动。
568
+ """
569
+ cell = beat_unit_ms(bpm)
570
+ return int(round(pos * cell))
571
+
572
+
573
+ def grid_compatible(ms_values: Sequence[int], bpm: float) -> bool:
574
+ """按 SkyStudio 的规则检查时间网格是否可用。
575
+
576
+ 判定条件(缺一不可):
577
+ ① 60000/bpm 是整数(cell 可整除);
578
+ ② 所有 time 都是 cell/2^k 的整数倍(能落在节拍网格上);
579
+ ③ gcd(间隔) 落在 cell/2^k 上,且与 cell 的比值是 2 的幂
580
+ (否则播放速度会歪)。
581
+ """
582
+ if not ms_values or bpm <= 0:
583
+ return False
584
+ from math import gcd, log2
585
+ from functools import reduce
586
+
587
+ cell = 60000.0 / bpm
588
+ if abs(cell - round(cell)) > 1e-6:
589
+ return False
590
+ cell_i = int(round(cell))
591
+
592
+ ts = sorted(set(int(v) for v in ms_values))
593
+ if len(ts) < 2:
594
+ return True
595
+
596
+ # ② 所有 time 必须落在某个「cell / 2^k」的网格上
597
+ # (等价于 gcd(所有 time 的间隔) 能整除每个 time)
598
+ # 注意不能简单用 cell//16 当步长:cell=500 时 500/16=31 不是 500 的约数,
599
+ # 真正的步长是 cell 的最大 2^k 约数。
600
+ deltas_all = [b - a for a, b in zip(ts, ts[1:]) if b > a]
601
+ if not deltas_all:
602
+ return True
603
+ g_all = reduce(gcd, deltas_all)
604
+ if g_all <= 0:
605
+ return False
606
+ for t in ts:
607
+ if t % g_all != 0:
608
+ return False
609
+
610
+ # ③ gcd 与 cell 的比值必须是 2 的幂
611
+ deltas = [b - a for a, b in zip(ts, ts[1:]) if b > a]
612
+ if not deltas:
613
+ return True
614
+ g = reduce(gcd, deltas)
615
+ if g <= 0:
616
+ return False
617
+ ratio = cell_i / float(g)
618
+ lr = log2(ratio) if ratio > 0 else 0.0
619
+ return abs(lr - round(lr)) < 0.05
620
+
621
+
622
+ def midi_to_sky(m: Midi, args) -> Tuple[List[SkyNote], dict]:
623
+ ppq = m.ppq
624
+ tmap = TempoMap(ppq, m.tempos)
625
+ keys = build_keys(args.root, 15)
626
+ lo, hi = keys[0], keys[-1]
627
+ key_pcs = {k % 12 for k in keys}
628
+ grid_beats = args.grid if (args.grid and args.grid > 0) else 0.0
629
+
630
+ notes = [n for n in m.notes if n.dur >= 1]
631
+ if not notes:
632
+ return [], {"error": "没有可用音符"}
633
+
634
+ # ============ 关键修改:标记主旋律音符 ============
635
+ # 旋律声部 = 每个起始点的最高音。移调量和黑键方向都只由它决定。
636
+ by_onset: Dict[int, List[int]] = {}
637
+ for n in notes:
638
+ by_onset.setdefault(n.start, []).append(n.pitch)
639
+
640
+ # 记录哪些音符是主旋律(每个时刻的最高音)。
641
+ # 先建 (start, pitch) -> 音符 的索引,避免 O(onset x notes) 的嵌套扫描
642
+ # (Flower Dance 是 1314 x 2584,两百万次比较)。
643
+ first_at: Dict[Tuple[int, int], Note] = {}
644
+ for n in notes:
645
+ key = (n.start, n.pitch)
646
+ if key not in first_at: # 同一位置同音高有多个音符时只取第一个
647
+ first_at[key] = n
648
+ melody_note_ids = set()
649
+ for start_tick, pitches in by_onset.items():
650
+ n = first_at.get((start_tick, max(pitches)))
651
+ if n is not None:
652
+ melody_note_ids.add(id(n))
653
+
654
+ melody = [max(v) for _, v in sorted(by_onset.items())]
655
+
656
+ if args.transpose == "none":
657
+ transpose = 0
658
+ else:
659
+ beat_len = ppq / 4.0
660
+ # 移调量的评分只关心「旋律会不会被改坏」——15 键是一台旋律乐器,
661
+ # 低音区本来就要被折叠,让它参与决策只会把旋律挤出可弹音域。
662
+ # 实测 5 份真实 MIDI:只用旋律决定移调 -> 旋律正确率 80.7%;
663
+ # 用全部音符 -> 72.9%(低音把移调量拖偏了)。
664
+ weighted = [(p, 1.0) for p in melody]
665
+ if not weighted:
666
+ weighted = [(n.pitch, (n.dur / beat_len) ** 0.5) for n in notes]
667
+ transpose = pick_transpose(weighted, key_pcs, lo, hi)
668
+
669
+ # 旋律走向(黑键吸附平局时用)
670
+ ordered = sorted(notes, key=lambda n: (n.start, n.pitch))
671
+ nxt: Dict[int, int] = {}
672
+ prv: Dict[int, int] = {}
673
+ for i, n in enumerate(ordered):
674
+ if i + 1 < len(ordered):
675
+ nxt[id(n)] = ordered[i + 1].pitch
676
+ if i > 0:
677
+ prv[id(n)] = ordered[i - 1].pitch
678
+
679
+ # 按「拍位置」分桶(不是毫秒!)
680
+ # 注意:SkyStudio 谱面规范的 key 形如 "^(?:\d)?Key(\d+)$",前缀数字会被忽略,
681
+ # 因此所有音统一写 "1KeyN",不要臆造 2Key 分层(那不会产生第二个八度)。
682
+ #
683
+ # 这里必须按拍位置分桶:如果先算毫秒再分桶,同一拍上不同音符算出的毫秒
684
+ # 可能差 1ms(6411 vs 6412),它们就不会合并成一个和弦,还会让时间点
685
+ # 永远对不上 SkyStudio 的网格。
686
+ buckets: Dict[float, List[Note]] = {}
687
+ for n in notes:
688
+ beat = n.start / ppq
689
+ if grid_beats > 0:
690
+ beat = round(beat / grid_beats) * grid_beats
691
+ # 吸附到 1/16 拍网格,保证 BeatGrid 一定能对齐
692
+ beat = snap_beat_position(beat, BEAT_SUBDIVISION)
693
+ buckets.setdefault(beat, []).append(n)
694
+
695
+ out: List[SkyNote] = []
696
+ stat = {"exact": 0, "octave": 0, "snapped": 0, "merged": 0, "dropped": 0}
697
+
698
+ # 主旋律存活统计:melody_note_ids 里的音符有多少真的写进了输出。
699
+ # 这个计数必须在这里累加(而不是事后从 SkyNote 反推)——因为
700
+ # SkyNote.src_pitch 存的是「吸附后的音高 - 移调量」,原始音符身份已经丢了,
701
+ # 从输出反推只能靠猜,历史上就因此量出过「保留率 0.8%」这种假数字。
702
+ melody_kept = 0
703
+
704
+ # SkyStudio 铁律:gcd(time 间隔) 必须 == 60000/bpm,否则播放速度会歪。
705
+ # 所以先把 bpm 归一到「60000/bpm 为整数」的值,再用这个 cell 铺时间轴。
706
+ bpm_raw = float(args.bpm or tmap.bpm())
707
+ bpm_now = grid_safe_bpm(bpm_raw)
708
+ cell_ms = beat_unit_ms(bpm_now) # 一拍 = cell_ms 毫秒(整数)
709
+
710
+ # 铁律:SkyStudio 的 gcd(time 间隔) 必须恰好等于 60000/bpm(一拍),
711
+ # 否则播放速度会按 cell/gcd 的倍数偏移。
712
+ #
713
+ # 所以这里必须让所有 time 的公共步长 == cell_ms,即所有音符都落在
714
+ # 「一拍」的整数倍上。若原曲用到更细的音符(八分/十六分),就把 bpm
715
+ # 往上翻倍,让「新的一拍」对应原来的细分 —— 这样 gcd 仍等于新 cell,
716
+ # 而相对速度不变。
717
+ from math import gcd as _gcd
718
+
719
+ # 先用 1/BEAT_SUBDIVISION 拍为单位,求所有拍位置的最小公共细分
720
+ ticks = [int(round(p * BEAT_SUBDIVISION)) for p in buckets]
721
+ tick_g = 0
722
+ for t in ticks:
723
+ tick_g = _gcd(tick_g, abs(t))
724
+ if tick_g <= 0:
725
+ tick_g = BEAT_SUBDIVISION
726
+ tick_g = min(tick_g, BEAT_SUBDIVISION)
727
+ # 原曲最细音符 = tick_g / BEAT_SUBDIVISION 拍
728
+ finest_beats = tick_g / float(BEAT_SUBDIVISION)
729
+
730
+ # 把 bpm 放大 1/finest_beats 倍,使「新一拍」正好等于原曲最细音符,
731
+ # 这样输出时间全是新 cell(= 旧 cell * finest_beats)的整数倍,
732
+ # gcd == 新 cell,SkyStudio 播放速度与世界一致。
733
+ old_cell = 60000.0 / bpm_raw
734
+
735
+ # 目标:找到整数 cell(每拍毫秒),使所有墙钟时间都是它的整数倍,
736
+ # 且对应的 bpm = 60000/cell 落在合理范围。
737
+ # 原曲最细音符在墙钟上是 finest_beats * old_cell 毫秒,
738
+ # 所以 cell 取它即可(再吸附到整数)。
739
+ finest_ms = max(1.0, finest_beats * old_cell)
740
+ cell_ms = max(1, int(round(finest_ms)))
741
+ # 若吸附后不能整除最细音符,向上取能整除的
742
+ if cell_ms > 1 and abs(cell_ms - finest_ms) > 0.4:
743
+ cell_ms = max(1, int(round(finest_ms)))
744
+
745
+ bpm_now = 60000.0 / cell_ms
746
+ unit_ms = cell_ms
747
+ time_unit_beats = 1.0
748
+ beat_scale = 1.0
749
+
750
+ # 保留原曲开头留白,但必须落在 unit_ms 的整数倍上(否则 gcd 会被破坏)
751
+ # 旧拍位置 first_beat -> 墙钟秒 = first_beat * 旧cell / 1000
752
+ old_cell = 60000.0 / bpm_raw
753
+ first_beat = min(buckets) if buckets else 0.0
754
+ first_ms = first_beat * old_cell
755
+ ms_offset = max(0, int(round(first_ms / unit_ms)) * unit_ms)
756
+
757
+ # 统一黑键吸附方向 ---------------------------------------------------------
758
+ # snap() 会按旋律走向逐个决定向上还是向下,导致同一个音级在曲子里落到不同
759
+ # 白键(C# 一会儿变 G、一会儿变 A),同一句旋律重奏时音名就变了。
760
+ # 这里先按旋律声部穷举出「每个黑键统一朝哪边」,再把方向交给 snap()。
761
+ snap_dirs = pick_snap_directions([p + transpose for p in melody], keys)
762
+
763
+ for beat_pos in sorted(buckets):
764
+ grp = buckets[beat_pos]
765
+ raw = []
766
+ for n in grp:
767
+ q = n.pitch + transpose
768
+ folded = fold(q, lo, hi)
769
+ is_scale = (folded % 12) in key_pcs
770
+ np_ = nxt.get(id(n))
771
+ pp_ = prv.get(id(n))
772
+ if np_ is not None and np_ != n.pitch:
773
+ prefer_up = np_ > n.pitch
774
+ elif pp_ is not None and pp_ != n.pitch:
775
+ prefer_up = n.pitch > pp_
776
+ else:
777
+ prefer_up = True
778
+ # 标记是否是主旋律
779
+ is_melody = id(n) in melody_note_ids
780
+ raw.append((n, q, folded, is_scale, prefer_up, is_melody))
781
+
782
+ bass_pc = min(r[2] for r in raw) % 12 if raw else None
783
+ picked = []
784
+ for (n, q, folded, is_scale, prefer_up, is_melody) in raw:
785
+ if is_scale:
786
+ k = folded
787
+ how = "octave" if q != folded else "exact"
788
+ else:
789
+ # 有统一方向就照它吸附(保证同一音级始终落到同一个白键),
790
+ # 否则退回原來的上下文判断。
791
+ dir_up = snap_dirs.get(folded % 12, prefer_up)
792
+ k = snap(folded, keys, dir_up, bass_pc)
793
+ how = "snapped"
794
+ picked.append((n, k, how, q, is_melody))
795
+
796
+ # ============ 关键修改:复音限制时优先保留主旋律 ============
797
+ if args.max_poly and len(picked) > args.max_poly:
798
+ # 分离主旋律和伴奏
799
+ melody_picks = [p for p in picked if p[4]] # is_melody = True
800
+ accomp_picks = [p for p in picked if not p[4]]
801
+
802
+ # 主旋律全部保留
803
+ kept = melody_picks.copy()
804
+
805
+ # 剩余名额给伴奏
806
+ remaining_slots = args.max_poly - len(kept)
807
+ if remaining_slots > 0 and accomp_picks:
808
+ hi_p = max(p[1] for p in accomp_picks)
809
+ lo_p = min(p[1] for p in accomp_picks)
810
+
811
+ def salient(it):
812
+ n, k, how, q, is_mel = it
813
+ return n.vel + (1000 if k == hi_p else 0) + (900 if k == lo_p else 0)
814
+
815
+ accomp_sorted = sorted(accomp_picks, key=salient, reverse=True)
816
+ kept.extend(accomp_sorted[:remaining_slots])
817
+ stat["dropped"] += len(accomp_picks) - remaining_slots
818
+ else:
819
+ stat["dropped"] += len(accomp_picks)
820
+
821
+ picked = sorted(kept, key=lambda it: it[1])
822
+
823
+ # ============ 关键修改:同键合并时优先保留主旋律 ============
824
+ seen: Dict[int, Tuple[Note, str, bool]] = {}
825
+ for n, k, how, q, is_melody in picked:
826
+ if k in seen:
827
+ stat["merged"] += 1
828
+ old_n, old_how, old_is_melody = seen[k]
829
+ # 如果新音符是主旋律,或者旧的不是主旋律但新的力度更大,则替换
830
+ if is_melody or (not old_is_melody and n.vel > old_n.vel):
831
+ seen[k] = (n, how, is_melody)
832
+ else:
833
+ seen[k] = (n, how, is_melody)
834
+
835
+ # 旧拍位置 -> 墙钟毫秒(用原始 bpm 的 cell),再按新 bpm 的 cell 量化。
836
+ # 这样 bpm 被放大 k 倍时,拍位置相应缩小 k 倍,总时长保持不变,
837
+ # 同时 time 全是新 cell 的整数倍 -> gcd == cell -> 播放速度准确。
838
+ wall_ms = beat_pos * old_cell
839
+ ms = int(round(wall_ms / unit_ms)) * unit_ms
840
+ ms = max(0, ms)
841
+ # 虚音模式:对没被吸附到「正确」白键的黑键音,额外补两个键凑差音。
842
+ # 详见 VIRTUAL_NOTE_TABLE 的注释 —— 这是实验性输出,
843
+ # 物理上差音会被基音掩蔽,听感通常是「按错的两个音」。
844
+ virtual_extra = {}
845
+ if getattr(args, "virtual_notes", False):
846
+ for n, k, how, q, is_melody in picked:
847
+ if how != "snapped":
848
+ continue
849
+ pair = virtual_pair_for(q % 12)
850
+ if pair is None:
851
+ continue
852
+ ai, bi, err, _desc = pair
853
+ virtual_extra[ai] = max(virtual_extra.get(ai, 0), 1)
854
+ virtual_extra[bi] = max(virtual_extra.get(bi, 0), 1)
855
+ stat["virtual"] = stat.get("virtual", 0) + 1
856
+
857
+ for k in sorted(seen):
858
+ n, how, is_melody = seen[k]
859
+ stat[how] += 1
860
+ if is_melody:
861
+ melody_kept += 1
862
+ out.append(SkyNote(ms, keys.index(k), 1, k - transpose, how))
863
+
864
+ for ki in sorted(virtual_extra):
865
+ if ki in seen:
866
+ continue
867
+ out.append(SkyNote(ms, ki, 1, 0, "virtual"))
868
+
869
+ out.sort(key=lambda s: (s.time_ms, s.key_idx))
870
+
871
+ # ---- 后验校准 ----
872
+ # SkyStudio 的铁律是 gcd(time 间隔) == 60000/bpm。
873
+ # 实际数出来的 gcd 若与预期 cell 不等,就用 gcd 反推 bpm,
874
+ # 保证「速度正确」这一条永远成立(音高不受影响)。
875
+ from math import gcd as _gcd2
876
+ if out:
877
+ times = sorted(set(s.time_ms for s in out))
878
+ if len(times) >= 2:
879
+ g_out = 0
880
+ for a, b in zip(times, times[1:]):
881
+ g_out = _gcd2(g_out, b - a)
882
+ if g_out > 0 and g_out != unit_ms:
883
+ unit_ms = g_out
884
+ cell_ms = g_out
885
+ bpm_now = 60000.0 / cell_ms
886
+ time_unit_beats = 1.0
887
+
888
+ return out, {
889
+ "transpose": transpose,
890
+ "bpm": bpm_now,
891
+ "time_unit_beats": time_unit_beats,
892
+ "unit_ms": unit_ms,
893
+ "range": (lo, hi),
894
+ "stat": stat,
895
+ "drums": m.drums,
896
+ "src": len(notes),
897
+ # 可弹性:旋律里有多少音是黑键(15 键琴弹不出来)
898
+ "playability": 100.0 * (1.0 - stat["snapped"] / max(1, len(notes))) if notes else 0.0,
899
+ # 主旋律存活率:每个 onset 的最高音有多少真的出现在输出里。
900
+ # 1.4.1 之前同键合并与复音裁剪会无声吃掉一部分主旋律。
901
+ "melody": {
902
+ "total": len(melody_note_ids),
903
+ "kept": melody_kept,
904
+ "rate": 100.0 * melody_kept / max(1, len(melody_note_ids)),
905
+ },
906
+ "pitch_level": int(getattr(args, "pitch_level", 0) or 0),
907
+ # SkyStudio 兼容性:时间点是否落在节拍网格上
908
+ "grid_ok": grid_compatible([s.time_ms for s in out], bpm_now),
909
+ }
910
+
911
+
912
+ def write_sky(path: str, notes: Sequence[SkyNote], args, info: dict) -> None:
913
+ songNotes = [{"time": int(s.time_ms), "key": key_id(s.key_idx)} for s in notes]
914
+ # bpm 用微调后的值(info["bpm"] 已是 grid_safe_bpm 的结果),
915
+ # 否则 SkyStudio 会按原始 bpm 重算网格,仍然对不上。
916
+ bpm_out = float(info.get("bpm", args.bpm or 300))
917
+ # transcribedBy 默认留空,不预设任何工具名。
918
+ # 理由:本工具接受任何标准 MIDI —— DAW 导出的、手写的、别的转谱工具出的都行。
919
+ # 默认写死 "MuScriptor" 会给这些来源的输入错误署名,是事实性错误。
920
+ # 确实由 MuScriptor 转谱时,用 --transcribed MuScriptor 显式声明。
921
+ meta = {
922
+ "name": args.name or os.path.splitext(os.path.basename(args.input))[0],
923
+ "author": args.author or "",
924
+ "arrangedBy": args.arranged or "",
925
+ "transcribedBy": args.transcribed or "",
926
+ "permission": "",
927
+ "isComposed": True,
928
+ "bpm": bpm_out,
929
+ "bitsPerPage": int(args.bits_per_page),
930
+ "pitchLevel": int(args.pitch_level),
931
+ "isEncrypted": False,
932
+ "songNotes": songNotes,
933
+ }
934
+ text = json.dumps([meta], ensure_ascii=False, separators=(",", ":"))
935
+ enc = args.encoding.lower()
936
+ if enc in ("utf-16", "utf16", "unicode"):
937
+ data = text.encode("utf-16") # 含 BOM(FFFE)
938
+ elif enc in ("utf-8-sig", "utf8-sig"):
939
+ data = text.encode("utf-8-sig")
940
+ else:
941
+ data = text.encode("utf-8")
942
+ with open(path, "wb") as f:
943
+ f.write(data)
944
+
945
+
946
+ # ============================================================ 光遇 -> MIDI
947
+
948
+ def read_sky(path: str):
949
+ raw = open(path, "rb").read()
950
+ for enc in ("utf-16", "utf-8-sig", "utf-8", "gb18030"):
951
+ try:
952
+ text = raw.decode(enc)
953
+ data = json.loads(text)
954
+ break
955
+ except Exception:
956
+ continue
957
+ else:
958
+ raise ValueError("无法解析该琴谱文件(编码或 JSON 格式不支持)")
959
+ if isinstance(data, dict):
960
+ data = [data]
961
+ songs = []
962
+ for s in data:
963
+ rec = {
964
+ "name": s.get("name", ""),
965
+ "author": s.get("author", ""),
966
+ "bpm": int(s.get("bpm", 300)),
967
+ "bitsPerPage": s.get("bitsPerPage", 16),
968
+ "pitchLevel": s.get("pitchLevel", 0),
969
+ "notes": [],
970
+ }
971
+ for n in s.get("songNotes", []):
972
+ k = str(n["key"])
973
+ # 与 SkyStudio 谱面规范一致:任意数字前缀都不参与音高计算
974
+ m = re.match(r"^(?:\d)?Key(\d+)$", k)
975
+ if m:
976
+ idx = int(m.group(1))
977
+ else:
978
+ idx = int(k)
979
+ rec["notes"].append((int(n["time"]), 1, idx))
980
+ rec["notes"].sort()
981
+ songs.append(rec)
982
+ return songs
983
+
984
+
985
+ def sky_to_midi(path: str, out: str, args) -> dict:
986
+ songs = read_sky(path)
987
+ if not songs:
988
+ raise ValueError("琴谱里没有任何曲目")
989
+ song = songs[0]
990
+ keys = build_keys(args.root, 15)
991
+ bpm = song["bpm"] or 300
992
+ ppq = args.ppq
993
+ ms_per_beat = 60000.0 / bpm
994
+ ev = []
995
+ for (ms, layer, idx) in song["notes"]:
996
+ if idx < 0 or idx >= len(keys):
997
+ continue
998
+ pitch = keys[idx]
999
+ tick = int(round(ms / ms_per_beat * ppq))
1000
+ dur = max(1, int(round(ppq * (args.note_len))))
1001
+ ch = 0 if layer == 1 else 1
1002
+ ev.append((tick, 0x90 | ch, pitch, 100))
1003
+ ev.append((tick + dur, 0x80 | ch, pitch, 64))
1004
+ tempo_us = int(round(60000.0 / bpm * 1000.0))
1005
+ write_midi_file(out, ev, ppq, tempo_us=tempo_us)
1006
+ return {"name": song["name"], "bpm": bpm, "notes": len(song["notes"])}
1007
+
1008
+
1009
+ def write_midi_file(path: str, events, ppq: int, program: int = 0,
1010
+ tempo_us: int = 500000) -> None:
1011
+ ev = sorted(events, key=lambda e: (e[0], e[1]))
1012
+ track = bytearray()
1013
+ track += _write_varlen(0) + bytes([0xFF, 0x51, 0x03,
1014
+ (tempo_us >> 16) & 0xFF,
1015
+ (tempo_us >> 8) & 0xFF,
1016
+ tempo_us & 0xFF])
1017
+ track += _write_varlen(0) + bytes([0xC0, program & 0x7F])
1018
+ last = 0
1019
+ for tick, status, d1, d2 in ev:
1020
+ if tick < last:
1021
+ tick = last
1022
+ track += _write_varlen(tick - last)
1023
+ track += bytes([status, d1 & 0x7F, d2 & 0x7F])
1024
+ last = tick
1025
+ track += _write_varlen(0) + bytes([0xFF, 0x2F, 0x00])
1026
+ out = bytearray()
1027
+ out += b"MThd" + struct.pack(">IHHH", 6, 0, 1, ppq)
1028
+ out += b"MTrk" + struct.pack(">I", len(track)) + bytes(track)
1029
+ with open(path, "wb") as f:
1030
+ f.write(bytes(out))
1031
+
1032
+
1033
+ # ============================================================ SkyStudio 格式自检
1034
+
1035
+ SKYR_KEY_RE = re.compile(r"^(?:\d)?Key(\d+)$")
1036
+
1037
+
1038
+ def skyr_parse(path: str) -> dict:
1039
+ """按 SkyStudio 谱面规范回读并校验输出,确认它能被播放器直接读取。
1040
+
1041
+ 检查项:BOM 编码、JSON 结构、key 命名、键位范围、和弦合并与总时长。
1042
+ """
1043
+ raw = open(path, "rb").read()
1044
+ if raw[:2] == b"\xff\xfe":
1045
+ text = raw[2:].decode("utf-16-le")
1046
+ enc = "UTF-16LE(BOM)"
1047
+ elif raw[:2] == b"\xfe\xff":
1048
+ text = raw[2:].decode("utf-16-be")
1049
+ enc = "UTF-16BE(BOM)"
1050
+ elif raw[:3] == b"\xef\xbb\xbf":
1051
+ text = raw[3:].decode("utf-8")
1052
+ enc = "UTF-8(BOM)"
1053
+ else:
1054
+ text = raw.decode("utf-8")
1055
+ enc = "UTF-8"
1056
+
1057
+ root = json.loads(text)
1058
+ if not isinstance(root, list) or not root:
1059
+ raise ValueError("顶层必须是 JSON 数组")
1060
+ song = root[0]
1061
+ if song.get("isEncrypted", False):
1062
+ raise ValueError("乐谱被标记为加密,APP 会拒绝播放")
1063
+ notes = song.get("songNotes")
1064
+ if not notes or not isinstance(notes[0], dict):
1065
+ raise ValueError("songNotes 为空或格式不符")
1066
+
1067
+ events = []
1068
+ first = notes[0]
1069
+ ft = int(first.get("time", 0))
1070
+ if ft > 0:
1071
+ events.append((ft, []))
1072
+ m = SKYR_KEY_RE.match(str(first.get("key", "")))
1073
+ if not m:
1074
+ raise ValueError("无法识别按键: %r" % first.get("key"))
1075
+ events.append((0, [int(m.group(1))]))
1076
+
1077
+ prev_t = ft
1078
+ for i in range(1, len(notes)):
1079
+ cur = notes[i]
1080
+ ct = int(cur.get("time", 0))
1081
+ m = SKYR_KEY_RE.match(str(cur.get("key", "")))
1082
+ if not m:
1083
+ raise ValueError("无法识别按键: %r" % cur.get("key"))
1084
+ k = int(m.group(1))
1085
+ if ct == prev_t:
1086
+ events[-1][1].append(k)
1087
+ else:
1088
+ events.append((max(0, ct - prev_t), [k]))
1089
+ prev_t = ct
1090
+
1091
+ return {
1092
+ "name": song.get("name", ""),
1093
+ "encoding": enc,
1094
+ "noteCount": len(notes),
1095
+ "eventCount": len(events),
1096
+ "polyphony": max((len(e[1]) for e in events), default=0),
1097
+ "durationMs": sum(e[0] for e in events),
1098
+ "keysUsed": sorted({k for e in events for k in e[1]}),
1099
+ }
1100
+
1101
+
1102
+ # ============================================================ 预览
1103
+
1104
+ def preview(notes: Sequence[SkyNote]) -> str:
1105
+ lines: List[str] = []
1106
+ if not notes:
1107
+ return "(空)"
1108
+ t0 = notes[0].time_ms
1109
+ cur = None
1110
+ row: List[SkyNote] = []
1111
+
1112
+ def flush(r):
1113
+ if not r:
1114
+ return ""
1115
+ t = (r[0].time_ms - t0) / 1000.0
1116
+ names = " ".join(DEGREE_NAMES[s.key_idx] for s in r)
1117
+ if len(r) > 1:
1118
+ names = "[" + names + "]"
1119
+ return "%6.2fs %-4s" % (t, names)
1120
+
1121
+ out_rows = []
1122
+ for s in notes:
1123
+ if cur is None or s.time_ms != cur:
1124
+ if row:
1125
+ out_rows.append(flush(row))
1126
+ row = [s]
1127
+ cur = s.time_ms
1128
+ else:
1129
+ row.append(s)
1130
+ if row:
1131
+ out_rows.append(flush(row))
1132
+
1133
+ buf = ""
1134
+ for cell in out_rows:
1135
+ if len(buf) + len(cell) > 76:
1136
+ lines.append(buf)
1137
+ buf = ""
1138
+ buf += cell + " "
1139
+ if buf.strip():
1140
+ lines.append(buf)
1141
+ return "\n".join(lines)