// M01Preview browser app: page logic. Model work runs in ./worker.js. The piano roll and inference use the same MIDI request.
import { prepareM01Input } from "./core/midi.js";
import { loadDemoConfig, pitchMapText, readRenderDefaults } from "./core/config.js";
import { requestFromScore, normalizeMonophony, resolveUseVelocity } from "./core/features.js";
import { MODULE_OF } from "./core/backend.js";
import { renderHall } from "./core/reverb.js";
import { PianoRoll, ART_COLOURS, midiNoteName } from "./pianoroll.js";
const publicUrl = new URL(import.meta.env.BASE_URL, location.href);
const songUrls = import.meta.glob("../songs/*.mid", { eager: true, query: "?url", import: "default" });
const $ = (id) => document.getElementById(id);
async function startApp() {
const config = await loadDemoConfig(new URL("config.json", publicUrl));
const requestedModel = new URLSearchParams(location.search).get("models");
const model = requestedModel === null ? config.models[0] : config.models.find((entry) => entry.model === requestedModel);
if (!model) throw new Error(`Unknown model ${requestedModel}`);
const { model: MODEL_SET, name: INSTRUMENT_LABEL, instrument: INSTRUMENT, keyswitches: INSTRUMENT_KS, keyswitchPitches: KS_PITCHES } = model;
const MODELS_URL = `/models/${MODEL_SET}`;
const reverb = config.audio.reverb;
const hallUrl = new URL(reverb.impulse_response, publicUrl);
document.title = `InstVELA M01Preview · ${INSTRUMENT_LABEL} Renderer`;
document.querySelector("h1").textContent = `InstVELA M01Preview · ${INSTRUMENT_LABEL} renderer`;
const headerLogo = document.querySelector(".header-logo");
new ResizeObserver(([entry]) => {
// The grid stretches the logo through the status row. Match that height without stretching the image.
requestAnimationFrame(() => headerLogo.style.setProperty("--header-logo-height", `${entry.contentRect.height}px`));
}).observe(headerLogo);
{ // Each instrument loads its own ONNX bundle and defaults.
const select = $("instrument");
select.replaceChildren(...config.models.filter((entry) => entry.show_in_menu !== false)
.map((entry) => new Option(entry.name, entry.model)));
select.value = MODEL_SET;
select.disabled = select.options.length === 0;
select.addEventListener("change", () => {
const url = new URL(location.href);
url.searchParams.set("models", select.value);
location.href = url.href;
});
}
const ORT_URL = new URL("/ort/ort.all.min.mjs", location.origin).href;
const log = (msg) => { $("log").textContent += `${new Date().toLocaleTimeString()} ${msg}\n`; };
const reducedMotion = matchMedia("(prefers-reduced-motion: reduce)");
for (const content of document.querySelectorAll(".expander-content")) {
const details = content.parentElement;
const summary = details.firstElementChild;
let animation = null;
let targetOpen = details.open;
summary.addEventListener("click", (event) => {
event.preventDefault();
const opening = !(animation ? targetOpen : details.open);
const from = details.open ? content.getBoundingClientRect().height : 0;
animation?.cancel();
targetOpen = opening;
if (!opening && content.contains(document.activeElement)) summary.focus();
if (reducedMotion.matches) {
details.open = opening;
content.inert = false;
animation = null;
return;
}
if (opening) details.open = true;
content.inert = !opening;
const to = opening ? content.getBoundingClientRect().height : 0;
const next = content.animate([
{ height: `${from}px`, overflow: "hidden" },
{ height: `${to}px`, overflow: "hidden" },
], { duration: 240, easing: "ease", fill: "both" });
animation = next;
next.onfinish = () => {
if (animation !== next) return;
details.open = opening;
content.inert = false;
next.cancel();
animation = null;
};
});
}
// ---- settings ----
const EXAMPLE_SOURCE = KS_PITCHES.sustain > 0 ? KS_PITCHES.sustain - 1 : 127;
const PITCH_MAP_EXAMPLE = `{"${EXAMPLE_SOURCE}": ${KS_PITCHES.pizzicato}}`;
const FIELDS = [
{ key: "pitchMap", label: "Pitch map (optional JSON)", type: "pitchmap",
help: "Find your keyswitch’s MIDI number in your MIDI editor. " +
"Enter that number in quotes on the left and the target MIDI number from the table on the right. " +
`For example, ${PITCH_MAP_EXAMPLE} makes MIDI ${EXAMPLE_SOURCE} trigger pizzicato. Separate multiple pairs with commas inside the braces. ` +
"Use MIDI numbers from 0 to 127. Every note with a matching source number is remapped, so use numbers reserved for keyswitches. " +
"Press Tab or click outside the field to apply. Leave it blank to use the original MIDI pitches." },
{ key: "barOriginBeats", configKey: "pre_roll_beats", label: "Pre-roll before bar 1 (beats)", type: "number", step: 0.5, min: 0 },
{ group: "Score" },
{ key: "useVelocity", label: "Velocity", type: "select", options: [["auto", "auto (AIRE rule: on when velocities vary)"], ["on", "on"], ["off", "off"]] },
{ key: "tailSeconds", configKey: "tail", label: "Model tail after the last note (s)", type: "number", step: 0.5, min: 0 },
{ group: "Performance" },
{ key: "seed", integer: true, label: "Seed", type: "number", step: 1, min: 0, help: "same seed, same take in this app" },
{ key: "pitchExpression", label: "Pitch expression", type: "number", step: 0.05, min: 0, max: 3, help: "scales the generated pitch deviation" },
{ key: "transpose", integer: true, label: "Transpose (semitones)", type: "number", step: 1, help: "applied at the vocoder only" },
{ group: "Sampling" },
{ key: "stepsF0", integer: true, label: "Euler steps, F0 generator", type: "number", step: 1, min: 1, max: 200 },
{ key: "stepsAc", integer: true, label: "Euler steps, acoustic generator", type: "number", step: 1, min: 1, max: 200 },
{ key: "cfgF0", label: "Guidance, F0 generator", type: "number", step: 0.1, min: 0, help: "1 = no guidance (half the cost)" },
{ key: "cfgAc", label: "Guidance, acoustic generator", type: "number", step: 0.1, min: 0 },
{ group: "Windows" },
{ key: "windowSeconds", label: "Generator window (s)", type: "number", step: 1, min: 2 },
{ key: "knownPrefixSeconds", label: "Known prefix (s)", type: "number", step: 0.5, min: 0 },
{ key: "vocoderChunkSeconds", label: "Vocoder chunk (s)", type: "number", step: 1, min: 2, help: "smaller uses less GPU memory" },
{ key: "vocoderContextSeconds", label: "Vocoder context (s)", type: "number", step: 0.5, min: 0 },
{ group: "Output and device" },
{ key: "format", label: "Audio format", type: "select", options: [["mp3", `MP3 (${config.audio.mp3_kbps} kbps)`], ["wav", "WAV (24-bit)"]] },
{ key: "device", label: "Device", type: "select", options: [["auto", "auto (WebGPU where the self-test passes)"], ["wasm", "CPU only (WebAssembly)"]] },
{ key: "threads", integer: true, label: "CPU threads", type: "number", step: 1, min: 0, max: 32, help: "0 = auto; several only when cross-origin isolated" },
];
const DEFAULTS = readRenderDefaults(model, FIELDS);
let settings = { ...DEFAULTS };
function buildSettings() {
$("keyswitch-rows").innerHTML = Object.entries(KS_PITCHES).map(([articulation, pitch]) =>
`
${articulation}
${pitch}
${midiNoteName(pitch)}
`).join("");
let grid = $("score-settings");
const advanced = $("advanced-fields");
for (const f of FIELDS) {
if (f.group) {
advanced.insertAdjacentHTML("beforeend", `