Download demo/src/main.js from KGAudioLab/InstVELA-models-onnx: direct link, hf CLI and curl.
- Browser
- Download file 26.7 kB
-
https://huggingface.co/KGAudioLab/InstVELA-models-onnx/resolve/main/demo/src/main.js
- Command line
-
hf download hf://KGAudioLab/InstVELA-models-onnx/demo/src/main.js
-
curl -L -o main.js https://huggingface.co/KGAudioLab/InstVELA-models-onnx/resolve/main/demo/src/main.js
26.7 kB
| // 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, <code>${PITCH_MAP_EXAMPLE}</code> 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]) => | |
| `<tr><th scope="row">${articulation}</th><td>${pitch}</td><td>${midiNoteName(pitch)}</td></tr>`).join(""); | |
| let grid = $("score-settings"); | |
| const advanced = $("advanced-fields"); | |
| for (const f of FIELDS) { | |
| if (f.group) { | |
| advanced.insertAdjacentHTML("beforeend", `<section class="settings-group"><h3>${f.group}</h3><div class="settings-grid"></div></section>`); | |
| grid = advanced.lastElementChild.lastElementChild; | |
| continue; | |
| } | |
| const id = `set-${f.key}`; | |
| const hint = f.help ? ` aria-describedby="${id}-help"` : ""; | |
| const input = f.type === "select" | |
| ? `<select id="${id}"${hint}>${f.options.map(([v, l]) => `<option value="${v}">${l}</option>`).join("")}</select>` | |
| : f.type === "pitchmap" | |
| ? `<textarea id="${id}" rows="2" aria-describedby="${id}-help ${id}-error" spellcheck="false" placeholder='${PITCH_MAP_EXAMPLE}'></textarea>` + | |
| `<small id="${id}-error" class="bad" aria-live="polite"></small>` | |
| : `<input id="${id}"${hint} type="number" step="${f.step ?? "any"}"${f.min !== undefined ? ` min="${f.min}"` : ""}${f.max !== undefined ? ` max="${f.max}"` : ""}>`; | |
| const defaultLabel = f.type === "select" ? f.options.find(([v]) => v === DEFAULTS[f.key])[1] : DEFAULTS[f.key]; | |
| grid.insertAdjacentHTML("beforeend", `<div class="field"><label for="${id}">${f.label}</label>${input}` + | |
| (f.help ? `<small id="${id}-help">${f.help}</small>` : "") + | |
| (f.type === "pitchmap" ? "" : `<small class="default-value">Default: ${defaultLabel}</small>`) + `</div>`); | |
| const el = $(id); | |
| el.addEventListener("change", () => onSetting(f, el)); | |
| } | |
| showSettings(); | |
| } | |
| function showSettings() { | |
| for (const f of FIELDS) { | |
| if (f.group) continue; | |
| const el = $(`set-${f.key}`); | |
| el.value = String(settings[f.key]); | |
| if (f.type === "pitchmap") $(`set-${f.key}-error`).textContent = ""; | |
| el.closest(".field").classList.toggle("changed", settings[f.key] !== DEFAULTS[f.key]); | |
| } | |
| } | |
| function onSetting(f, el) { | |
| const old = settings[f.key]; | |
| if (f.type === "pitchmap") { | |
| const err = $(`set-${f.key}-error`); | |
| try { | |
| settings.pitchMap = pitchMapText(el.value); | |
| err.textContent = ""; | |
| } catch (e) { | |
| err.textContent = e.message; // keep the previous valid map until this one parses | |
| return; | |
| } | |
| showSettings(); | |
| if (settings.pitchMap === old) return; | |
| if (inputBytes) processInput(); | |
| invalidateRender(); | |
| log(settings.pitchMap ? `pitch map: ${settings.pitchMap}` : "pitch map cleared"); | |
| return; | |
| } | |
| settings[f.key] = f.type === "number" ? Number(el.value) : el.value; | |
| if (f.type === "number" && !Number.isFinite(settings[f.key])) settings[f.key] = old; | |
| showSettings(); | |
| if (settings[f.key] === old) return; | |
| if (["barOriginBeats", "useVelocity", "tailSeconds"].includes(f.key) && inputBytes) processInput(); | |
| invalidateRender(["device", "threads"].includes(f.key)); | |
| } | |
| $("reset").addEventListener("click", () => { | |
| const restart = settings.device !== DEFAULTS.device || settings.threads !== DEFAULTS.threads; | |
| const changed = Object.keys(changedSettings(settings)).length > 0; | |
| settings = { ...DEFAULTS }; | |
| showSettings(); | |
| if (!changed) return; | |
| if (inputBytes) processInput(); | |
| invalidateRender(restart); | |
| log(`settings reset to the ${INSTRUMENT_LABEL} defaults`); | |
| }); | |
| const changedSettings = (values) => Object.fromEntries(Object.entries(values).filter(([k, v]) => v !== DEFAULTS[k])); | |
| // ---- input ---- | |
| let inputBytes = null, inputName = null, request = null, inputLoad = 0; | |
| const pitchEdits = new Map(); | |
| const sourceNoteKey = ({ start, pitch }) => `${start}:${pitch}`; | |
| const zoomControl = $("zoom"); | |
| const { zoom, min_zoom: minZoom, max_zoom: maxZoom } = config.piano_roll; | |
| Object.assign(zoomControl, { min: minZoom, max: maxZoom, defaultValue: zoom }); | |
| const roll = new PianoRoll($("roll-scroller"), $("roll-spacer"), $("roll-canvas"), zoom); | |
| const rollLegend = Object.entries(ART_COLOURS).map(([a, c]) => `<span><i style="background:${c}"></i>${a}</span>`).join("") + | |
| `<span>Line length = velocity</span><span><i style="background:var(--roll-preroll)"></i>pre-roll</span>`; | |
| zoomControl.addEventListener("input", (e) => roll.setZoom(Number(e.target.value))); | |
| function processInput() { | |
| const info = $("file-info"); | |
| const inputCard = $("input-card"); | |
| const rollCard = $("roll-card"); | |
| try { | |
| const midi = prepareM01Input(inputBytes, { keyswitches: INSTRUMENT_KS, range: model.range, pitchMap: settings.pitchMap }); | |
| const uv = settings.useVelocity === "auto" ? null : settings.useVelocity === "on"; | |
| const original = requestFromScore(midi.score, INSTRUMENT_KS, settings.barOriginBeats, uv, INSTRUMENT); | |
| const { notes, edits } = normalizeMonophony(original.notes, original.tempo_bpm, config.midi.min_cropped_note_seconds); | |
| if (!notes.length) throw new Error("the MIDI has no playable notes"); | |
| request = { ...original, notes: notes.map((note) => ({ ...note, pitch: pitchEdits.get(sourceNoteKey(note)) ?? note.pitch })) }; | |
| const useVel = resolveUseVelocity(request); | |
| const spb = 60 / request.tempo_bpm; | |
| const dur = notes[notes.length - 1].end * spb; | |
| const arts = {}; | |
| for (const { articulation } of request.notes) arts[articulation] = (arts[articulation] ?? 0) + 1; | |
| const cropped = edits.filter((edit) => edit.new_end !== undefined).length; | |
| const removed = edits.length - cropped; | |
| info.innerHTML = `<b>${inputName}</b>: ${request.notes.length} notes, ${dur.toFixed(1)} s (+ ${(settings.tailSeconds + reverb.tail_seconds).toFixed(1)} s tail), ` + | |
| `${request.tempo_bpm} BPM, ${request.time_signature.join("/")}, pre-roll ${request.bar_origin_beats} beat(s), velocity ${useVel ? "on" : "off"}.` + | |
| `<ul><li>Articulations: ${Object.entries(arts).map(([a, n]) => `${a} ${n}`).join(", ")}</li>` + | |
| (settings.pitchMap ? `<li>Pitch map ${settings.pitchMap}: ${midi.remapped} note(s) remapped</li>` : "") + | |
| `<li>Keyswitches read separately (${midi.removed.keyswitchNotes} events). Ignored ${midi.removed.controlOrOther} other events ` + | |
| `(control changes, pitch bends, program changes, aftertouch, sysex, text)</li>` + | |
| (edits.length ? `<li class="warn">Monophonic conversion shortened ${cropped} and removed ${removed} notes.</li>` : "") + | |
| midi.warnings.map((w) => `<li class="warn">${w}</li>`).join("") + "</ul>"; | |
| $("legend").innerHTML = rollLegend + | |
| (cropped ? `<span><i class="edit-outline cropped" aria-hidden="true"></i>Cropped overlap</span>` : "") + | |
| (removed ? `<span><i class="edit-outline" aria-hidden="true"></i>Removed note</span>` : ""); | |
| rollCard.hidden = false; | |
| $("roll-footer").prepend(info); | |
| inputCard.hidden = true; | |
| roll.set({ notes: request.notes, edits, tempo: request.tempo_bpm, timeSignature: request.time_signature, barOrigin: request.bar_origin_beats, | |
| tail: settings.tailSeconds + reverb.tail_seconds, | |
| onPitchChange(index, pitch) { | |
| const source = notes[index]; | |
| const key = sourceNoteKey(source); | |
| if (source.pitch === pitch) pitchEdits.delete(key); | |
| else pitchEdits.set(key, pitch); | |
| const moved = request.notes.slice(); | |
| moved[index] = { ...moved[index], pitch }; | |
| request = { ...request, notes: moved }; | |
| invalidateRender(); | |
| return moved; | |
| }, | |
| }); | |
| } catch (e) { | |
| request = null; | |
| info.innerHTML = `<span class="bad">${inputName}: ${e.message}</span>`; | |
| rollCard.hidden = true; | |
| inputCard.append(info); | |
| inputCard.hidden = false; | |
| } | |
| } | |
| async function loadMidi(name, readBytes) { | |
| const load = ++inputLoad; | |
| let bytes; | |
| try { | |
| bytes = await readBytes(); | |
| } catch (error) { | |
| if (load === inputLoad) $("file-info").textContent = `${name}: ${error.message}`; | |
| return; | |
| } | |
| if (load !== inputLoad) return; | |
| inputBytes = new Uint8Array(bytes); | |
| inputName = name; | |
| pitchEdits.clear(); | |
| log(`loaded ${name} (${inputBytes.length} bytes)`); | |
| processInput(); | |
| invalidateRender(); | |
| } | |
| function loadFile(file) { return loadMidi(file.name, () => file.arrayBuffer()); } | |
| $("upload-own").addEventListener("click", () => { | |
| inputLoad++; | |
| inputBytes = null; | |
| inputName = null; | |
| request = null; | |
| pitchEdits.clear(); | |
| roll.clear(); | |
| zoomControl.value = zoomControl.defaultValue; | |
| roll.setZoom(zoom); | |
| $("roll-card").hidden = true; | |
| const info = $("file-info"); | |
| info.textContent = ""; | |
| $("input-card").append(info); | |
| $("input-card").hidden = false; | |
| $("file").value = ""; | |
| invalidateRender(); | |
| $("pick").focus(); | |
| }); | |
| $("pick").addEventListener("click", () => $("file").click()); | |
| $("file").addEventListener("change", (e) => e.target.files[0] && loadFile(e.target.files[0])); | |
| const drop = $("drop"); | |
| for (const t of ["dragenter", "dragover"]) drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.add("over"); }); | |
| for (const t of ["dragleave", "drop"]) drop.addEventListener(t, (e) => { e.preventDefault(); drop.classList.remove("over"); }); | |
| drop.addEventListener("drop", (e) => e.dataTransfer.files[0] && loadFile(e.dataTransfer.files[0])); | |
| window.addEventListener("dragover", (e) => e.preventDefault()); | |
| window.addEventListener("drop", (e) => e.preventDefault()); | |
| // ---- worker and device indicator ---- | |
| let worker = null, ready = false, activeRender = null, deviceState = null; | |
| let hasRendered = false; | |
| const threadCount = () => (self.crossOriginIsolated ? (settings.threads || Math.min(config.runtime.max_auto_threads, navigator.hardwareConcurrency || 1)) : 1); | |
| function showDevice(state) { | |
| deviceState = state; | |
| const mods = {}; | |
| for (const [g, st] of Object.entries(state.graphs)) (mods[MODULE_OF[g]] ??= []).push({ g, ...st }); | |
| const html = Object.entries(mods).map(([mod, list]) => { | |
| const backends = [...new Set(list.map((x) => x.backend))]; | |
| const fell = list.some((x) => (x.reason ?? "").startsWith("fell back")); | |
| const label = backends.map((b) => (b === "webgpu" ? "WebGPU" : `CPU (WebAssembly × ${state.threads})`)).join(" + "); | |
| const title = list.map((x) => `${x.g}: ${x.backend}${x.reason ? ` — ${x.reason}` : ""}${x.selftest ? ` (self-test ${x.selftest.relative.toExponential(1)})` : ""}`).join("\n"); | |
| return `<span class="badge ${fell ? "fallback" : backends.includes("wasm") ? "wasm" : "webgpu"}" title="${title.replace(/"/g, """)}">${mod}: ${label}${fell ? " (fallback)" : ""}</span>`; | |
| }).join(""); | |
| const gpu = state.webgpu?.available ? `<span class="badge" title="WebGPU adapter">GPU: ${state.webgpu.adapter?.vendor ?? "?"} ${state.webgpu.adapter?.architecture ?? ""}</span>` : ""; | |
| $("device").innerHTML = html + gpu; | |
| } | |
| function startWorker() { | |
| if (worker) worker.terminate(); | |
| activeRender = null; | |
| ready = false; | |
| resetProgress(); | |
| updateGenerate(); | |
| $("device").innerHTML = `<span class="badge">loading models…</span>`; | |
| $("status").textContent = "Loading models and running the self-test…"; | |
| worker = new Worker(new URL("./worker.js", import.meta.url), { type: "module" }); | |
| worker.onmessage = onWorker; | |
| worker.onerror = (e) => { | |
| if (e.currentTarget !== worker) return; | |
| activeRender = null; | |
| log(`worker error: ${e.message}`); | |
| $("status").innerHTML = `<span class="bad">Worker error: ${e.message}</span>`; | |
| updateGenerate(); | |
| }; | |
| const threads = threadCount(); | |
| log(`starting: ${settings.device === "wasm" ? "CPU only" : "WebGPU where the self-test passes"}, ${threads} WebAssembly thread(s)` + | |
| (self.crossOriginIsolated ? "" : " (page not cross-origin isolated: one thread)")); | |
| worker.postMessage({ type: "init", modelsUrl: new URL(MODELS_URL, location.origin).href, ortUrl: ORT_URL, threads, preferWebgpu: settings.device !== "wasm" }); | |
| } | |
| // ---- progress ---- | |
| const STAGES = ["loading models", "features", "F0 generator", "acoustic generator", "vocoder", "encode"]; | |
| const WEIGHT = { features: 0.01, "F0 generator": 0.36, "acoustic generator": 0.36, vocoder: 0.23, encode: 0.04 }; | |
| let stageStart = {}, current = null; | |
| function resetProgress() { | |
| stageStart = {}; | |
| current = null; | |
| $("progress").value = 0; | |
| $("stages").replaceChildren(); | |
| } | |
| function showReadyStatus() { | |
| $("status").textContent = `Models ready (${MODEL_SET}, ${INSTRUMENT_LABEL}).`; | |
| } | |
| function invalidateRender(restartWorker = false) { | |
| hasRendered = false; | |
| clearPlayer(); | |
| roll.setPlayhead(0); | |
| if (restartWorker || activeRender) { | |
| startWorker(); | |
| } else { | |
| if (ready) { | |
| resetProgress(); | |
| showReadyStatus(); | |
| } | |
| updateGenerate(); | |
| } | |
| } | |
| function showProgress(p) { | |
| if (p.stage === "done") return; | |
| if (p.stage !== current) { if (current) stageStart[current].end = performance.now(); current = p.stage; stageStart[p.stage] = { t: performance.now() }; } | |
| const el = $("stages"); | |
| el.innerHTML = STAGES.filter((s) => s !== "loading models" || !ready).map((s) => { | |
| const st = stageStart[s]; | |
| const cls = s === p.stage ? "active" : st?.end ? "done" : ""; | |
| let txt = s === "encode" ? "finalize audio" : s; | |
| if (s === p.stage && p.total) { | |
| const frac = p.done / p.total; | |
| const el2 = (performance.now() - st.t) / 1000; | |
| const eta = frac > 0 ? (el2 / frac) * (1 - frac) : null; | |
| txt += `: ${p.stage === "encode" ? Math.round(frac * 100) + " %" : `${p.done}/${p.total}`}${eta !== null && p.stage !== "encode" ? ` · ~${Math.ceil(eta)} s left` : ""}`; | |
| } else if (st?.end) txt += `: ${((st.end - st.t) / 1000).toFixed(1)} s`; | |
| return `<div class="${cls}">${txt}</div>`; | |
| }).join(""); | |
| if (ready && WEIGHT[p.stage] !== undefined) { | |
| let before = 0; | |
| for (const s of STAGES) { if (s === p.stage) break; before += WEIGHT[s] ?? 0; } | |
| $("progress").value = before + WEIGHT[p.stage] * (p.total ? p.done / p.total : 0); | |
| } else if (!ready && p.total) $("progress").value = p.done / p.total; | |
| } | |
| async function renderReverb({ wave, sampleRate, port }) { | |
| try { | |
| const stereo = await renderHall(wave, sampleRate, hallUrl, reverb); | |
| port.postMessage(stereo, [stereo.left.buffer, stereo.right.buffer]); | |
| } catch (error) { | |
| port.postMessage({ error: `Hall reverb: ${error.message}` }); | |
| } finally { | |
| port.close(); | |
| } | |
| } | |
| function onWorker(ev) { | |
| const m = ev.data; | |
| if (ev.currentTarget !== worker) { | |
| m.port?.close(); | |
| return; | |
| } | |
| if (m.type === "log") log(m.msg); | |
| else if (m.type === "state") showDevice(m.state); | |
| else if (m.type === "progress") showProgress(m); | |
| else if (m.type === "ready") { | |
| const have = m.constants?.instrument; | |
| if (have && have !== INSTRUMENT) { | |
| log(`error: ${MODEL_SET} is a set for ${have}, but this page tags requests ${INSTRUMENT}`); | |
| $("status").innerHTML = `<span class="bad">Error: model set ${MODEL_SET} is for ${have}, not ${INSTRUMENT}</span>`; | |
| return; | |
| } | |
| ready = true; | |
| resetProgress(); | |
| showReadyStatus(); | |
| log(`models ready: ${m.manifest.name}, exported ${m.manifest.created_utc}`); | |
| updateGenerate(); | |
| } else if (m.type === "reverb") void renderReverb(m); | |
| else if (m.type === "result") onResult(m); | |
| else if (m.type === "error") { | |
| activeRender = null; | |
| log(`error: ${m.message}\n${m.stack ?? ""}`); | |
| $("status").innerHTML = `<span class="bad">Error: ${m.message}</span>`; | |
| updateGenerate(); | |
| } | |
| } | |
| function updateGenerate() { $("generate").disabled = !(ready && request && !activeRender && !hasRendered); } | |
| $("generate").addEventListener("click", () => { | |
| if (!ready || !request || activeRender || hasRendered) return; | |
| const renderSettings = { ...settings }; | |
| activeRender = { id: Date.now(), inputName }; | |
| updateGenerate(); | |
| clearPlayer(); | |
| resetProgress(); | |
| $("status").textContent = "Generating…"; | |
| log(`generate: ${inputName}, changed settings ${JSON.stringify(changedSettings(renderSettings))}`); | |
| worker.postMessage({ type: "generate", id: activeRender.id, request, settings: renderSettings, midi: config.midi, audio: config.audio }); | |
| }); | |
| // ---- output ---- | |
| const player = $("player"); | |
| let playTimer = null; | |
| function clearPlayer() { | |
| $("render-output").hidden = true; | |
| $("out-info").textContent = ""; | |
| cancelAnimationFrame(playTimer); | |
| const url = player.src; | |
| if (!url) return; | |
| player.pause(); | |
| player.removeAttribute("src"); | |
| player.load(); | |
| URL.revokeObjectURL(url); | |
| } | |
| function onResult(m) { | |
| if (m.id !== activeRender?.id) return; | |
| const { inputName } = activeRender; | |
| activeRender = null; | |
| hasRendered = true; | |
| if (current && stageStart[current]) stageStart[current].end = performance.now(); | |
| showProgress({ stage: "done" }); | |
| $("progress").value = 1; | |
| const base = inputName.replace(/\.midi?$/i, ""); | |
| const ext = m.mime === "audio/wav" ? "wav" : "mp3"; | |
| const audioName = `${base}-m01preview.${ext}`; | |
| player.src = URL.createObjectURL(new File([m.audio], audioName, { type: m.mime })); | |
| $("render-output").hidden = false; | |
| const finalize = m.timing.reverb + m.timing.encode; | |
| $("out-info").textContent = `${m.info.audio_seconds.toFixed(1)} s of stereo audio, rendered in ${m.timing.total.toFixed(1)} s ` + | |
| `(${(m.timing.total / m.info.audio_seconds).toFixed(2)}× real time; F0 ${m.timing.f0_generator.toFixed(1)} s, acoustic ${m.timing.acoustic_generator.toFixed(1)} s, ` + | |
| `vocoder ${m.timing.vocoder.toFixed(1)} s, finalize ${finalize.toFixed(1)} s); peak ${m.info.peak_dbfs.toFixed(1)} dBFS` + | |
| (m.info.clipped_samples ? `, ${m.info.clipped_samples} samples clipped` : "") + "."; | |
| $("status").textContent = "Done."; | |
| log(`done: ${audioName}, ${m.timing.total.toFixed(1)} s`); | |
| updateGenerate(); | |
| player.onplay = () => { cancelAnimationFrame(playTimer); const tick = () => { roll.setPlayhead(player.currentTime, true); playTimer = requestAnimationFrame(tick); }; tick(); }; | |
| player.onpause = player.onended = () => { cancelAnimationFrame(playTimer); roll.setPlayhead(player.currentTime); }; | |
| player.onseeked = () => roll.setPlayhead(player.currentTime, true); | |
| } | |
| buildSettings(); | |
| $("pick").disabled = false; | |
| $("reset").disabled = false; | |
| startWorker(); | |
| if (model.demo_midi) { | |
| const url = songUrls[`../songs/${model.demo_midi}`] ?? new URL(model.demo_midi, publicUrl); | |
| void loadMidi(model.demo_midi.split("/").pop(), async () => { | |
| const response = await fetch(url); | |
| if (!response.ok) throw new Error(`Demo MIDI could not be loaded (${response.status})`); | |
| return response.arrayBuffer(); | |
| }); | |
| } | |
| } | |
| startApp().catch((error) => { | |
| const status = $("status"); | |
| status.classList.add("bad"); | |
| status.textContent = `Could not start the demo: ${error.message}`; | |
| }); | |