Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327/** * The model, as far as the store is concerned. * * The same shape of seam as `analyze.ts`: the store injects it the way it injects the engine * and the client, jsdom never sees a `Worker`, and a test that wants behaviour rather than a * story hands in something that answers. And the same fallback policy: a model that cannot * exist — no worker, no asset, a runtime the browser refused to start, an inference that took * longer than a song should — resolves to `null`, and `null` is not an error but the ordinary * way of saying *"ask the dynamic program"*. The neural grid is an upgrade, and an upgrade that * ever interrupts the feature it upgraded has been installed wrong. * * One deliberate limit: a worker that fails twice in a row is retired for the session. The DP * answers every question without the network; re-loading eleven megabytes per track to watch * it fail per track would be paying rent on a broken appliance. */import type { AudioBufferLike } from "./engine";import { mixDown } from "./detect";import type { NeuralGrid } from "./beattrack";import type { BeatModelPhase, BeatModelRuntime, BeatTrackReply } from "./beatmodel.worker";
/** * What one question to the model cost, and how it ended. * * The grid is the answer; this is the *bill*, and it exists because the wait for a grid is the * longest bar in the load and was, until it arrived, entirely unattributed. Twenty seconds of * "beat model" means one of several different things — a cold start only the first track pays, * nine windows of arithmetic every track pays, a runtime that never got the GPU it asked for, or a * timeout that bought nothing — and only the phases can say which. */export interface BeatModelReport { readonly outcome: | "answered" | "empty" | "busy" | "dropped" | "timed out" | "failed" | "retired" | "unavailable"; readonly phases: readonly BeatModelPhase[]; readonly runtime?: BeatModelRuntime; readonly error?: string;}
/** * How much of a track the model is asked about. * * The number comes out of a real device's report, not out of a feeling. For a 338-second track the * model's whole wait was 4272ms, and 44% of it was arithmetic that wants no GPU at all: 633ms of * resampling and 1256ms of log-mel, both scaling with the length of the track, against 190ms for * each of its twelve inference windows. Long tracks pay for the spectrogram of every second of them * to answer a question about the pulse. * * The question is a period and a phase, and three minutes of a steady track establishes both — the * dynamic program still scores the *whole* track, because its chromagram is measured separately and * this changes nothing about it. What this costs: a track whose first three minutes have no pulse in * them (the fade-in, the orchestral swell) gives the model nothing to find, and the answer is the * fallback that existed before the model at all. Raising the constant is one line. The better change * is to analyse the *loudest* three minutes rather than the first, which needs the grid's phase * re-anchored to the slice's start — worth doing, worth doing only with a test that proves the loop * boundaries still land on the sound. */const MODEL_ANALYSIS_SECONDS = 180;
export interface BeatModel { /** * Resolves always, never rejects: a grid, or `null` for "nothing to say". The buffer's * samples are folded and copied once and the copy is *transferred* — a four-minute * full-rate channel is forty-seven megabytes, and a structured-clone copy of it on the * main thread every track would tax the very thread this feature exists to keep free. */ track( buffer: AudioBufferLike, report?: (r: BeatModelReport) => void, /** `key` is how the page knows this track: it is the name `priority` later uses. */ opts?: { key?: string }, ): Promise<NeuralGrid | null>; /** * Which of the questions out there somebody is waiting for, most wanted first. * * Everything named is served ahead of everything not named, and everything not named stops. Not * a failure for the tracks that stop: their loops are already on screen — the search answers * without the grid now — and what is being given up is the refinement, on a track the listener has * skipped past. The thread has no way to know any of this on its own; it holds samples, not songs. */ priority?(keys: readonly string[]): void; close?(): void;}
export interface BeatModelWorkerLike { postMessage(message: unknown, transfer?: Transferable[]): void; onmessage: ((event: { data?: BeatTrackReply }) => void) | null; onerror: ((event: unknown) => void) | null; terminate(): void;}
export interface BeatModelOverrides { createWorker?: () => BeatModelWorkerLike | null; /** where to fetch the weights and the mel matrix from; repo-relative by default */ modelUrl?: string; melUrl?: string; /** a track the network has not finished thinking about in this long falls back to the DP */ timeoutMs?: number;}
const MODEL_PATH = "models/beat-this-small0.onnx";const MEL_PATH = "models/mel-filterbank.f32";/** Longer than a laptop's worst cold-start of the wasm runtime, shorter than patience. */const DEFAULT_TIMEOUT_MS = 45_000;
export function createBeatModel(overrides: BeatModelOverrides = {}): BeatModel { const base = (import.meta as { env?: { BASE_URL?: string } }).env?.BASE_URL ?? "/"; const modelUrl = overrides.modelUrl ?? `${base}${MODEL_PATH}`; const melUrl = overrides.melUrl ?? `${base}${MEL_PATH}`; const timeoutMs = overrides.timeoutMs ?? DEFAULT_TIMEOUT_MS; const make = overrides.createWorker ?? (() => { if (typeof Worker !== "function") return null; try { return new Worker(new URL("./beatmodel.worker.ts", import.meta.url), { type: "module", }) as unknown as BeatModelWorkerLike; } catch { return null; } });
let worker: BeatModelWorkerLike | null = null; /** * The runtime as the last answer described it. * * Kept because the answer that never comes is the one that needs it: a track whose model timed out * reports no runtime of its own, and "this device has no GPU and one wasm thread" is the sentence * that explains a timeout. It is the same session for every track after the first, so the answer * from an earlier track is the truth for this one — and `undefined` is what a session that has * never answered says, rather than a guess. */ let lastRuntime: BeatModelRuntime | null = null; let retired = false; /** * Why the model stopped answering, in the words the load's bar prints. * * `unavailable` used to arrive with no reason at all, and the page filled the silence with * "this browser cannot run the model" — a sentence about the device, printed by a browser that had * answered in 6.2 seconds the day before, because two tracks had been skipped and the thread had * retired itself. A bar is allowed to say the feature is gone; it is not allowed to blame the wrong * thing for it, and "a reload brings it back" is the difference between closing the tab and filing * a bug against Chrome. */ let retiredBecause: string | null = null; let failures = 0; const waiting = new Map< number, { resolve: (g: NeuralGrid | null) => void; report: ((r: BeatModelReport) => void) | undefined; timer: ReturnType<typeof setTimeout>; } >(); let token = 0;
/** * Settle one question, and hand over its bill. * * Exactly once per track: the reporter closes the caller's span, so a second call would close a * bar that has already been drawn, and no call at all would leave a bar growing under a graph * that says the load is over. The timeout and the retirement are the two paths where nothing ever * comes back from the thread — which is precisely when the caller most needs to close the bar and * say why. */ function settle( id: number, grid: NeuralGrid | null, outcome: BeatModelReport["outcome"], phases: readonly BeatModelPhase[] = [], runtime?: BeatModelRuntime, error?: string, ): void { const wait = waiting.get(id); if (!wait) return; waiting.delete(id); clearTimeout(wait.timer); wait.report?.({ outcome, phases, runtime, error }); wait.resolve(grid); }
function remembered(): BeatModelRuntime | undefined { return lastRuntime ?? undefined; }
function retire(why = "the model stopped answering this session; a reload brings it back"): void { worker?.terminate(); worker = null; retired = true; retiredBecause = why; for (const [id] of waiting) { settle(id, null, "retired", [], remembered()); } }
function ensure(): BeatModelWorkerLike | null { if (worker || retired) return worker; worker = make(); if (!worker) { // No worker at all is not a failure to count — it is the environment saying this // feature does not exist here, and asking again per track costs nothing but noise. retired = true; retiredBecause = "this browser has no worker thread, so the model cannot run here"; return null; } worker.onmessage = (event) => { const reply = event.data; if (reply?.token === undefined || !waiting.has(reply.token)) return; if (reply.runtime) lastRuntime = reply.runtime; if (reply.error) { failures += 1; // The bill goes back even for a failure: "the model threw, after 22s of windows" is the // finding, and throwing it away would be throwing away the only evidence of why. settle(reply.token, null, "failed", reply.phases ?? [], reply.runtime, reply.error); // Named, so the bar can say what actually finished the feature rather than guessing at the // device from a word that means three different things. if (failures >= 2) retire( `the model failed ${failures} times in a row (${reply.error}); a reload brings it back`, ); } else if (reply.busy) { // Busy is not broken. The thread was holding the session for another track and this question // gave up inside its budget — ordinary traffic, two loads a second apart — and counting it as // a failure would retire the model after two perfectly good plays. The count is left alone // rather than cleared: a genuine fault before this still counts, and one after it will too. settle(reply.token, null, "busy", reply.phases ?? [], reply.runtime); } else if (reply.dropped) { // Not a failure, and not a strike: the page said — correctly, and by name — that nobody was // waiting for this answer any more. The listener skipped on, and the next track took this // one's place in the queue. Whatever the search already published about it stands. settle(reply.token, null, "dropped", reply.phases ?? [], reply.runtime); } else { failures = 0; const grid = reply.grid ?? null; settle( reply.token, grid, grid ? "answered" : "empty", reply.phases ?? [], reply.runtime, reply.error, ); } }; worker.onerror = () => retire(); return worker; }
return { async track(buffer, report, opts) { const w = ensure(); if (!w) { // The environment has said this feature does not exist here, or this page has said it of // itself by retiring the thread. The answer is still `null` and still immediate — but the // bill still goes back, because the caller opened a bar for a question that is never going // to be asked, and a bar with no way down grows forever. And it goes back with the reason: // `unavailable` alone could only be read as a verdict about the browser. report?.({ outcome: "unavailable", phases: [], runtime: remembered(), error: retiredBecause ?? "the model could not be started", }); return null; } // Fold, copy, transfer. The fold is the same mean-of-channels the analyzer uses — // two answers about one track that disagreed about which channel it listened to would // be a stranger kind of wrong than either of them being. // The cap is applied to the channels before the fold, not to the mix afterwards: the fold is a // pass over every sample of every channel on this thread, and there is no reason to pay it for // audio the model will never see. const wanted = Math.round( Math.min(MODEL_ANALYSIS_SECONDS, buffer.duration) * buffer.sampleRate, ); const channels: Float32Array[] = []; for (let c = 0; c < buffer.numberOfChannels; c++) channels.push(buffer.getChannelData(c).subarray(0, wanted)); const samples = mixDown(channels); const id = ++token; return await new Promise<NeuralGrid | null>((resolve) => { const timer = setTimeout(() => { // The worker keeps working on a question nobody asked for; its answer arrives to // an empty slot and is dropped. A slow model is a fallback, not a hostage — and the // caller is told it was dropped, with whatever phases the thread had got through // before the wait ran out, which is how "the phone is three times slower than the // laptop" stops being a theory. settle(id, null, "timed out", [], remembered()); }, timeoutMs); waiting.set(id, { resolve, report, timer }); w.postMessage( { token: id, samples, sampleRate: buffer.sampleRate, // The name the page will use to say whether it still wants this answer. key: opts?.key ?? "", // What the track *is*, as distinct from what was sent: the thread puts both on the bar, // so a reader can see that 180 of 338 seconds were analysed rather than wondering why a // five-minute track has six windows in it. // Whole seconds: it goes on the bar beside `seconds=`, and `of=495.8666666666667` // — which is what the first real report said — answers nobody's question. trackSeconds: Math.round(buffer.duration), modelUrl, melUrl, }, [samples.buffer], ); }); }, priority(keys) { // No worker means no queue, and a queue is the only thing this can act on — so a page that // changes track before anything has been asked to the model says nothing to nobody, which is // correct rather than missed. worker?.postMessage({ priority: [...keys] }); }, close() { retire("the page closed the model"); }, };}