Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 | 731x 731x 731x 731x 731x 731x 731x 731x 5x 591x 591x 731x 20x 20x 591x 591x 591x 591x 591x 731x 12x 591x 591x 1471x 1471x 1471x 591x 591x 185x 591x 591x 591x 15x 591x 591x 591x 591x 591x 146x 591x 588x 3x 588x 78x 588x 130x 458x 588x 15x 588x 13x 588x 13x 588x 588x 588x 588x 588x 588x 588x 588x 20823x 588x 588x 22725x 22725x 22725x 588x 588x 588x 588x 22293x 22293x 588x 22293x 588x 588x 588x 588x 10x 588x 35281x 35281x 35281x 35281x 35281x 16x 16x 35281x 35281x 35281x 35281x 28358x 28358x 28358x 28358x 28358x 28358x 28191x 28358x 28358x 28358x 28358x 28358x 28358x 28358x 4926x 4926x 4926x 4773x 4926x 4767x 4926x 124x 28358x 167x 167x 28191x 35281x 167x 2x 165x 588x 588x 1176x 210x 210x 210x 210x 210x 17x 17x 210x 363x 363x 363x 363x 2x 361x 361x 361x 361x 131x 361x 588x 588x 588x 588x 588x 588x 22723x 22723x 588x 588x 588x 588x 20823x 20823x 588x 54x 588x 588x 588x 22291x 22291x 588x 588x 731x 4x 727x 8x 719x 719x 8x 711x 16x 695x 695x 64x 631x 40x 591x | import { resolveBmsonModeHintLayout } from '@be-music/chart-model';
import { readBmsonExtraFields } from './bmson-extra-fields.ts';
import {
createEmptyJSON,
type BmsonMineChannelEntry,
type BeMusicEvent,
type BeMusicJSON,
type ChartDiagnostic,
} from '@be-music/chart-source';
import { countDistinctValues, createBmsonValueKeyTable, encodeBmsonKey, resolveBmsonKeyBase } from './bmson-keys.ts';
import { normalizeBmsonNoteLength, sortAndNormalizeEvents } from './event-utils.ts';
import {
bmsPlayableChannelToInvisibleChannel,
bmsPlayableChannelToLandmineChannel,
buildBmsonLaneMap,
createBmsonPositionResolver,
createMeasureLengthsFromBmsonLines,
type BmsonDocument,
normalizeBmsonBPMEvents,
normalizeBmsonBGAForIR,
normalizeBmsonInfoForIR,
normalizeBmsonKeyChannels,
normalizeBmsonMineChannels,
normalizeBmsonLines,
normalizeBmsonScrollEvents,
normalizeBmsonSoundChannels,
normalizeBmsonStopEvents,
resolveBmsonResolution,
} from './bmson.ts';
import { convertLegacyBmsonDocument, isLegacyBmsonDocument } from './bmson-legacy.ts';
export function parseBmsonDocument(source: BmsonDocument): BeMusicJSON {
// Pre-1.0 charts are read as Bemuse reads them; the result is an ordinary 1.0.0 document.
const legacy = isLegacyBmsonDocument(source);
const document = legacy ? convertLegacyBmsonDocument(source) : source;
const version = requireSupportedBmsonVersion(document);
const json = createEmptyJSON('bmson');
Object.assign(json.bmson, readBmsonExtraFields(document, 'root'));
const info = document.info ?? {};
const diagnostics: ChartDiagnostic[] = [];
if (legacy) {
diagnostics.push({
code: 'legacy-bmson',
message: 'Converted legacy bmson v0.21 input.',
position: { kind: 'field', path: '$' },
});
}
const rawHint: unknown = info.mode_hint;
const hint = typeof rawHint === 'string' ? rawHint.trim() : rawHint;
if (hint !== undefined && hint !== '' && (typeof hint !== 'string' || !resolveBmsonModeHintLayout(hint))) {
const subject = typeof hint === 'string' ? JSON.stringify(hint) : undefined;
diagnostics.push({
code: 'unknown-mode-hint',
message: subject === undefined ? 'Invalid bmson mode hint.' : `Unsupported bmson mode hint ${subject}.`,
...(subject === undefined ? {} : { subject }),
position: { kind: 'field', path: 'info.mode_hint' },
});
}
if (diagnostics.length > 0) json.diagnostics = diagnostics;
json.bmson.version = version;
const resolution = resolveBmsonResolution(document);
json.bmson.info = normalizeBmsonInfoForIR(info, resolution);
// Per spec, the difference between "lines missing" and "lines: []" matters: missing → assume 4/4 and generate a
// barline every 4 quarter notes (the renderer's default derive-from-events path); explicit empty → no barlines at all
// (the "100 % minimoo-G effect"). Detect the explicit- empty case here so the IR carries the suppress flag, since
// both shapes collapse to `[]` after `normalizeBmsonLines`.
const linesAuthoredEmpty = Array.isArray(document.lines) && document.lines.length === 0;
if (linesAuthoredEmpty) {
json.bmson.barlinesSuppressed = true;
}
const lines = normalizeBmsonLines(document.lines);
for (const line of document.lines ?? []) {
Iif (!line || typeof line !== 'object' || !Number.isFinite(line.y) || line.y < 0) continue;
const fields = readBmsonExtraFields(line, 'line').extraFields;
if (fields) (json.bmson.lineExtraFields ??= {})[String(Math.round(line.y))] = fields;
}
const positionResolver = createBmsonPositionResolver(resolution, lines);
if (lines.length > 0) {
json.preservation.bmson.lines = lines;
}
json.bmson.bga = normalizeBmsonBGAForIR(document.bga);
const measureLengths = createMeasureLengthsFromBmsonLines(lines, resolution);
if (measureLengths.length > 0) {
json.measures = measureLengths;
}
json.metadata.title = json.bmson.info.title;
json.metadata.subtitle = json.bmson.info.subtitle;
json.metadata.artist = json.bmson.info.artist;
json.metadata.genre = json.bmson.info.genre;
if (Number.isFinite(json.bmson.info.level)) {
json.metadata.playLevel = json.bmson.info.level;
}
if (Number.isFinite(json.bmson.info.initBPM) && (json.bmson.info.initBPM ?? 0) > 0) {
json.metadata.bpm = json.bmson.info.initBPM!;
} else {
// bmson 1.0.0 spec — "It is a fatal error if `info.init_bpm` is unspecified." A chart that omits / zeroes / negates
// `init_bpm` has no anchor for tempo-driven timing, so every downstream calculation (note seconds, BGA cues, gauge
// timing) silently falls back to whatever `metadata.bpm` was seeded with — typically the `DEFAULT_BPM = 130`
// placeholder, which produces visibly wrong playback for any chart that wasn't authored at 130. Surface the
// violation as a parse error so the loader surfaces a clear "broken chart" diagnostic rather than playing the chart
// back at the wrong tempo.
throw new Error('bmson: info.init_bpm is required (spec: "It is a fatal error if info.init_bpm is unspecified")');
}
if (Number.isFinite(json.bmson.info.judgeRank)) {
json.metadata.rank = json.bmson.info.judgeRank;
}
if (Number.isFinite(json.bmson.info.total)) {
json.metadata.total = json.bmson.info.total;
} else {
// bmson 1.0.0 spec — `info.total` default is 100. We pin that here (rather than letting the BMS-flavored
// `LR2_GROOVE_GAUGE_DEFAULT_TOTAL = 160` fallback take over) so a bmson chart that omits `total` runs with the
// gauge curve its author / the spec assumed.
json.metadata.total = 100;
}
// Mirror bmson's `info.backImage` / `bannerImage` / `eyecatchImage` onto the unified `metadata` slots so consumers
// (the select view's BACKBMP loader, rendered banner, etc.) don't need to branch on chart format.
if (json.bmson.info.backImage) {
json.metadata.backBMP = json.bmson.info.backImage;
}
if (json.bmson.info.bannerImage) {
json.metadata.banner = json.bmson.info.bannerImage;
}
if (json.bmson.info.eyecatchImage && !json.metadata.stageFile) {
json.metadata.stageFile = json.bmson.info.eyecatchImage;
}
if (json.bmson.info.titleImage) json.metadata.titleImage = json.bmson.info.titleImage;
const soundChannels = normalizeBmsonSoundChannels(document.sound_channels);
json.preservation.bmson.soundChannels = soundChannels;
// Lane mapping honors `mode_hint` so canonical That-Which-Must-Not-Be-Named / Pop'n bmson dialects route the right keys onto the right BMS
// channels — the legacy positional fallback would mis-route `beat-7k` x=6/7 onto scratch (`16`) / FREE ZONE (`17`)
// because those channel digits come next in numeric order.
// The positional fallback numbers every lane in use, so the beatoraja lane extensions (hidden notes and mines) count
// too: a mine on a lane no playable note uses still gets that lane instead of being dropped.
const keyChannels = normalizeBmsonKeyChannels(document.key_channels);
const mineChannels = normalizeBmsonMineChannels(document.mine_channels);
const laneMap = buildBmsonLaneMap([...soundChannels, ...keyChannels, ...mineChannels], json.bmson.info.modeHint);
const bpmEvents = normalizeBmsonBPMEvents(document.bpm_events);
const stopEvents = normalizeBmsonStopEvents(document.stop_events);
// Spec: `stop_events.duration` is measured in **pulses** at the chart's `resolution`. The downstream timing resolver
// reads `resources.stop[key]` through the BMS-style `(value / 192) × (240/bpm)` formula, which expects the value in
// "1/192-of-a-measure" units (1 measure = 4 beats = 192 BMS-spec STOP units, so 1 beat = 48 BMS units). To keep the
// BMS / bmson paths sharing one formula, convert bmson pulses into the equivalent 1/192-measure units at parse time:
//
// bms_units = pulses × 48 / resolution
//
// Default `resolution = 240` → 1 beat (`duration = 240`) becomes `48` BMS units, which the formula evaluates to
// `(48 / 192) × (240/bpm) = 60/bpm` seconds — exactly one beat. Without this conversion bmson stops were ~5× longer
// than authored at the default resolution.
const stopUnits = stopEvents.map((stopEvent) => (stopEvent.duration * 48) / resolution);
// Of several BPM changes on one pulse the last one in the list wins (jbms-parser sets the timeline's BPM event by
// event). Collapse them here, since `08` events on one position are ordered by key, and keys go by value.
const bpmByPulse = new Map<number, number>();
for (const bpmEvent of bpmEvents) {
bpmByPulse.delete(bpmEvent.y);
bpmByPulse.set(bpmEvent.y, bpmEvent.bpm);
}
const bpmFieldsByPulse = new Map(bpmEvents.map((event) => [event.y, readBmsonExtraFields(event, 'bpm', true)]));
const bpmValues = [...bpmByPulse.values()];
// beatoraja extension: `scroll_events` set the lane's scroll rate from `y` on, as BMS `#SCROLLxx` on channel `SC`,
// and the rate holds until the next event, as in BMS. jbms-parser sets the rate on the timeline at `y`, so of several
// events on one pulse the last one in the list wins; collapse them here, since `SC` events on one position are
// ordered by key, not by the list.
const scrollEvents = normalizeBmsonScrollEvents(document.scroll_events);
const scrollRateByPulse = new Map<number, number>();
for (const scrollEvent of scrollEvents) {
scrollRateByPulse.delete(scrollEvent.y);
scrollRateByPulse.set(scrollEvent.y, scrollEvent.rate);
}
const scrollFieldsByPulse = new Map(
scrollEvents.map((event) => [event.y, readBmsonExtraFields(event, 'scroll', true)]),
);
const scrollRates = [...scrollRateByPulse.values()];
// BPM / STOP get one key per distinct value (a gimmick chart with thousands of changes usually repeats a handful of
// values) and every sound / key / mine channel its own WAV slot. A resource that still needs more than the 1,295
// base-36 keys moves the chart to base-62 keys rather than letting a key wrap round onto an earlier value.
const wavSlotCount = soundChannels.length + keyChannels.length + mineChannels.length;
const keyBase = resolveBmsonKeyBase([
wavSlotCount,
countDistinctValues(bpmValues),
countDistinctValues(stopUnits),
countDistinctValues(scrollRates),
]);
if (keyBase === 62) {
json.bms.base = 62;
}
for (let index = 0; index < soundChannels.length; index += 1) {
const soundChannel = soundChannels[index]!;
const key = encodeBmsonKey(index + 1, keyBase)!;
json.resources.wav[key] = soundChannel.name;
const channelFields = readBmsonExtraFields(soundChannel, 'channel', true).extraFields;
if (channelFields) {
(json.bmson.channelExtraFields ??= {})[key] = channelFields;
(json.bmson.channelKinds ??= {})[key] = 'sound';
}
const notes = soundChannel.notes ?? [];
const playableTicks = new Set<number>();
const bgmCandidates: Array<{ pulse: number; event: BeMusicEvent }> = [];
for (const note of notes) {
Iif (!Number.isFinite(note.y)) {
continue;
}
const pulse = Math.round(note.y);
const lane = Number.isFinite(note.x) ? Math.floor(note.x!) : 0;
// An `x` the lane map has no lane for (x <= 0, missing, or outside the hint's table) is a BGM note: the spec makes
// x = 0 BGM, and beatoraja plays any x outside the hint's key table in the background too.
const playableChannel = lane > 0 ? laneMap.get(lane) : undefined;
const isBGMNote = playableChannel === undefined;
if (!isBGMNote) {
playableTicks.add(pulse);
}
const { measure, position } = positionResolver(note.y);
const channel = playableChannel ?? '01';
const event: BeMusicEvent = {
measure,
position,
channel,
value: key,
};
const noteLength = normalizeBmsonNoteLength(note.l);
const noteContinue = typeof note.c === 'boolean' ? note.c : undefined;
// beatoraja bmson extension — per-note long-note type, only meaningful on actual long notes (`l > 0`).
const noteLongNoteType =
(note.t === 1 || note.t === 2 || note.t === 3) && noteLength !== undefined && noteLength > 0
? note.t
: undefined;
if (
noteLength !== undefined ||
noteContinue !== undefined ||
noteLongNoteType !== undefined ||
typeof note.up === 'boolean' ||
note.extraFields !== undefined
) {
event.bmson = { ...readBmsonExtraFields(note, 'note', true) };
if (typeof note.up === 'boolean') event.bmson.up = note.up;
if (noteLength !== undefined) {
event.bmson.l = noteLength;
}
if (noteContinue !== undefined) {
event.bmson.c = noteContinue;
}
if (noteLongNoteType !== undefined) {
event.bmson.t = noteLongNoteType;
}
}
if (isBGMNote) {
bgmCandidates.push({ pulse, event });
continue;
}
json.events.push(event);
}
for (const candidate of bgmCandidates) {
if (playableTicks.has(candidate.pulse)) {
continue;
}
json.events.push(candidate.event);
}
}
// beatoraja's two lane extensions, read as jbms-parser's BMSONDecoder does: `key_channels` are hidden notes (keysounds
// that are never judged → BMS invisible `3x` / `4x`) and `mine_channels` are mines (→ BMS landmine `Dx` / `Ex`, each
// keeping its gauge `damage` on `event.bmson.damage`). Both read only `x`, `y` (and `damage` on mines), go through
// the same `mode_hint`-aware lane map as the playable notes, and drop a note without a lane. Their WAVs are
// registered after the sound channels in beatoraja's order — `key_channels`, then `mine_channels` — so the WAV ID
// space stays contiguous.
let nextWAVIndex = soundChannels.length + 1;
const pushBmsonExtensionNotes = (
channels: readonly BmsonMineChannelEntry[],
toChannel: (playableChannel: string) => string | undefined,
keepDamage: boolean,
): void => {
for (const extensionChannel of channels) {
const wavKey = encodeBmsonKey(nextWAVIndex, keyBase)!;
nextWAVIndex += 1;
json.resources.wav[wavKey] = extensionChannel.name;
const channelFields = readBmsonExtraFields(extensionChannel, 'channel', true).extraFields;
if (channelFields) {
(json.bmson.channelExtraFields ??= {})[wavKey] = channelFields;
(json.bmson.channelKinds ??= {})[wavKey] = keepDamage ? 'mine' : 'key';
}
for (const note of extensionChannel.notes) {
const lane = Number.isFinite(note.x) ? Math.floor(note.x!) : 0;
const playableChannel = lane > 0 ? laneMap.get(lane) : undefined;
const channel = playableChannel ? toChannel(playableChannel) : undefined;
if (!channel) {
continue;
}
const { measure, position } = positionResolver(note.y);
const event: BeMusicEvent = { measure, position, channel, value: wavKey };
if (note.extraFields) event.bmson = { ...readBmsonExtraFields(note, 'note', true) };
if (keepDamage && note.damage !== undefined) {
event.bmson = { ...event.bmson, damage: note.damage };
}
json.events.push(event);
}
}
};
pushBmsonExtensionNotes(keyChannels, bmsPlayableChannelToInvisibleChannel, false);
pushBmsonExtensionNotes(mineChannels, bmsPlayableChannelToLandmineChannel, true);
json.preservation.bmson.bpmEvents = bpmEvents;
const bpmKeys = createBmsonValueKeyTable(bpmValues, keyBase);
Object.assign(json.resources.bpm, bpmKeys.table);
[...bpmByPulse.keys()].forEach((y, index) => {
const { measure, position } = positionResolver(y);
json.events.push({
measure,
position,
channel: '08',
value: bpmKeys.keys[index]!,
...(bpmFieldsByPulse.get(y)?.extraFields ? { bmson: { ...bpmFieldsByPulse.get(y) } } : {}),
});
});
// STOPs on one pulse add up (bmson spec), so their order on the pulse does not matter.
json.preservation.bmson.stopEvents = stopEvents;
const stopKeys = createBmsonValueKeyTable(stopUnits, keyBase);
Object.assign(json.resources.stop, stopKeys.table);
stopEvents.forEach((stopEvent, index) => {
const { measure, position } = positionResolver(stopEvent.y);
json.events.push({
measure,
position,
channel: '09',
value: stopKeys.keys[index]!,
...(stopEvent.extraFields ? { bmson: { ...readBmsonExtraFields(stopEvent, 'stop', true) } } : {}),
});
});
if (scrollEvents.length > 0) {
json.preservation.bmson.scrollEvents = scrollEvents;
}
const scrollKeys = createBmsonValueKeyTable(scrollRates, keyBase);
Object.assign(json.bms.scroll, scrollKeys.table);
[...scrollRateByPulse.keys()].forEach((y, index) => {
const { measure, position } = positionResolver(y);
json.events.push({
measure,
position,
channel: 'SC',
value: scrollKeys.keys[index]!,
...(scrollFieldsByPulse.get(y)?.extraFields ? { bmson: { ...scrollFieldsByPulse.get(y) } } : {}),
});
});
json.events = sortAndNormalizeEvents(json.events, keyBase, true);
return json;
}
/** Only the stable 1.0.0 format is implemented; build metadata has no SemVer precedence. */
function requireSupportedBmsonVersion(document: BmsonDocument): string {
if (document === null || typeof document !== 'object' || Array.isArray(document)) {
throw new TypeError('Invalid bmson document: expected a JSON object with version "1.0.0".');
}
if (!Object.hasOwn(document, 'version')) {
throw new Error(
'Invalid bmson: version is missing, but the chart uses bmson 1.0.0 fields rather than the legacy v0.21 ones. Add "version": "1.0.0".',
);
}
const version: unknown = document.version;
if (version === null) {
throw new TypeError("Invalid bmson version: null is not allowed. Supply the chart's actual format version.");
}
if (typeof version !== 'string') {
throw new TypeError('Invalid bmson version: expected a Semantic Versioning 2.0.0 string such as "1.0.0".');
}
// Validate SemVer syntax before checking support; compare decimal components as strings to avoid precision loss.
const match =
/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/.exec(
version,
);
if (!match || match[4]?.split('.').some((part) => /^0[0-9]+$/.test(part))) {
throw new TypeError('Invalid bmson version: expected a Semantic Versioning 2.0.0 string such as "1.0.0".');
}
if (match[1] !== '1' || match[2] !== '0' || match[3] !== '0' || match[4] !== undefined) {
throw new Error(
`Unsupported bmson version "${version}". This reader supports stable 1.0.0 (with optional build metadata); convert the chart to that format or use a reader for its declared version.`,
);
}
return version;
}
|