Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289/** * The expensive half of loop detection, off the main thread. * * The split is where the measurement said to put it, not where it looked tidy: the * fingerprint needs the samples and the transform and costs ~60 ms, the search needs a * ~250 KB matrix of twelve numbers per frame and costs ~200 ms. Four times apart in cost and * two hundred times apart in message size, so the fingerprint stays here and the search goes * there — and what crosses is the chroma, never the audio. Handing the worker the samples * instead would mean *copying* them (an AudioBuffer's channel arrays are not transferable) * so a four-minute track would cost a 42 MB main-thread memcpy to save a message that is * 0.6% the size. * * The other consequence of drawing the line at the chroma: the worker needs no fft.js, no * `AudioBufferLike`, and no notion that audio is involved. It takes twelve numbers per frame * and returns regions. * * Everything in here that the tests need is exported as a plain function over plain data, * because the worker itself is the one piece of machinery in this feature that jsdom * cannot run (`Worker` is not implemented there): `runDetect` is what the message handler * calls, and the test calls it too, across the same `DetectRequest` shape. */import { beginDetectCapture, takeDetectCapture } from "./trace";import type { ChromaSeries } from "./chroma";import { detectTuning, searchSeries, type Candidate, type DetectOptions, type DetectResult,} from "./detect";
/** * What crosses to the worker: the chroma, the frame grid it was read on, and the decisions * to apply to it. * * The `frameSec` travels rather than being recomputed there — the search turns every * frame into a place in the track with it, and two halves on different threads each with * their own idea of what a second is is a bug that only shows up at 48 kHz. The options * travel for the same reason: the thread that chose the floor is the thread that says so. */export interface DetectRequest { /** * When the page posted this, on the clock the two threads share. * * The worker cannot tell a queue from an idle thread on its own: it knows when the search before * this one finished, and if that was four seconds ago the gap was nobody waiting for anything. * With the post time the two are distinguishable — the wait is what this question spent *after* * it was asked — and a `queue for the search` bar drawn from the difference cannot be an idle * evening wearing a stall's clothing. */ readonly sentAt?: number; /** frames × 12: the fingerprint's entire output, and the only audio-shaped thing that crosses */ readonly values: Float32Array; readonly frames: number; readonly frameSec: number; readonly audible: number; /** the twelve typicality weights, for the log line only — the search never re-applies them */ readonly weights: Float32Array; /** loudness per frame, when the caller has it: the seam term cannot be scored without it */ readonly energy?: Float32Array; /** * The audio, at the envelope rate the onset detector works at — see `downmix`. * * Optional, and its absence is a statement about the caller rather than the track: a page that has * the fingerprint but not the samples gets the frame grid, which is the clock this feature shipped * on. Present, and the worker builds a beat grid from it and searches that first. Seven and a half * megabytes of mono at 8 kHz for four minutes of music, copied by structured clone; the forty-one * it was downmixed from never crosses. */ readonly mono?: Float32Array; readonly monoRate?: number; /** * The neural tracker's beat and downbeat times, when it had them. * * Seconds of Float32Array — a grid, not audio — which is why they can ride the same message * the forty-megabyte question never could. Their presence reorders the clocks (the model's * beats pool the chroma, the dynamic program falls back to); their absence is the ordinary * case the feature shipped on, and the worker cannot and should not tell "no model" apart * from "model had nothing to say". */ readonly modelBeats?: Float32Array; readonly modelDownbeats?: Float32Array; readonly options: DetectOptions; /** * Echoed back verbatim. The current track and the prefetched successor are routinely in * the air together, so a reply has to be addressed rather than simply taken in the order * it arrives. */ readonly token?: number; /** * Which track these bins came from, for the trace only — the worker has no other way to * know, and a measurement that cannot say what it measured is how a `not sure* on one * track ends up being blamed on another. `token` addresses the *reply*; this names the * subject, and the two are not the same job. */ readonly label?: string; /** * Whether the page wants the measurement printed, decided by the thread that owns the switch * and handed over with the question. * * The worker is a separate instance of every module it imports, including the trace: the * console's `detectTrace(true)` sets a variable in the *page's* copy of that module, and the * worker's copy never hears about it. So the decision travels, and `runDetect` applies it * before searching — which is also what makes the two threads agree about printing at the * moment the work is done, rather than agreeing whenever the worker happened to be able to * read storage. Absent means "not said", which leaves the worker's own default in charge. */ readonly trace?: boolean;}
/** What comes back. Regions, or the named refusal — the same union the main thread returns. */export interface DetectReply { /** whatever the request carried, so the answer can find the question it belongs to */ readonly token?: number; candidates: Candidate[]; /** * How long this question sat waiting for the thread, and how long the search then took, both on * the worker's own clock — which is the same clock, the same `performance.now()`, since a worker * shares its page's time origin. * * The page cannot see the first of these from its side: the handler runs the whole search to * completion, so a second question's `onmessage` does not fire until the first has returned. With * the gridless pass and the snapped one crossing for every track that has a model, two arrive at * once as a matter of course — and a `loop search` bar of 1.9 s on a long track was half somebody * else's search, with nothing on the graph to say which half. */ readonly queuedMs?: number; readonly workMs?: number; not?: DetectResult["not"]; best?: number; /** what the search looked at, which the main thread keeps for the chip's tooltip */ stats?: DetectResult["stats"]; /** the grid's beat times, when there was one — the bar arms its pulse on these */ beats?: Float32Array; /** * The lines the worker would have printed, in order, printed by the page. See * `beginDetectCapture*: a worker's own console output is invisible to the page, and a trace * nobody can read is indistinguishable from a detector with nothing to say. */ trace?: string[];}
/** * The series → the message. A separate step so the shape is stated once and asserted on. * * `label` is optional and is not part of the answer's identity: leaving it out costs a log * line its subject and nothing else, which is the right trade for a probe. */export function toRequest( series: ChromaSeries, options: DetectOptions = {}, label?: string, trace?: boolean, audio?: { samples: Float32Array; sampleRate: number; modelBeats?: Float32Array; modelDownbeats?: Float32Array; },): DetectRequest { return { values: series.values, frames: series.frames, frameSec: series.frameSec, audible: series.audible, weights: series.weights, energy: series.energy, mono: audio?.samples, monoRate: audio?.sampleRate, modelBeats: audio?.modelBeats, modelDownbeats: audio?.modelDownbeats, // The tuning merged here, at the one place a request is built, rather than at whichever call // site remembered to ask for it: the search runs on another thread, which is another instance // of the module the console writes into, so a tuning that stays on this side is a suggestion // the worker never hears. The failure is invisible from both ends — the page reports // `tuning set (floor=0.8)`, the worker answers with the constants, and the listener concludes // their music is the problem. Explicit options still win: the caller's are about one track, // the console's are the listener's read on all of them. options: { ...detectTuning(), ...options }, label, trace, };}
/** The message → the series. The worker's whole idea of what audio is. */export function toSeries(request: DetectRequest): ChromaSeries { return { values: request.values, frames: request.frames, frameSec: request.frameSec, audible: request.audible, weights: request.weights, energy: request.energy, // Only a test that asked where a frequency landed reads this, and it is not on this thread. binHz: 0, };}
/** One request in, one answer out: the worker's entire job. */export function runDetect(request: DetectRequest): DetectReply { // The page said whether it wants the story (`trace`), and the lines are assembled rather than // printed because nothing the worker prints is reachable from the page's console. Cheap to // build, and skipped entirely when nobody asked. if (request.trace) beginDetectCapture(); // The measurement reports itself — see `search`, which is where the lines are printed, so // that the inline path (no worker, jsdom, a worker that died) says exactly what the worker // does instead of going quiet on precisely the path somebody is debugging. const { candidates, not, best, stats, beats } = searchSeries( toSeries(request), request.mono ? { samples: request.mono, sampleRate: request.monoRate ?? 0, modelBeats: request.modelBeats, modelDownbeats: request.modelDownbeats, } : undefined, request.options, request.label, ); // Assembled rather than printed: see the note on `DetectReply.trace`. Taken out of the capture // immediately after the search, while nothing else on this thread can interleave. const trace = request.trace ? takeDetectCapture() : undefined; return { token: request.token, candidates, not, best, stats, beats, trace };}
/** * The handshake, wired only where a worker actually is the global scope. * * The `document` test is the guard rather than the presence of `self`: under vitest's * jsdom this module is importable, `self` exists, and `self.onmessage` exists too — so a * test importing this to check the protocol would otherwise hang its assignment off the * window and start answering messages meant for the page. A worker has no document, and * that is the difference that means something here. */const scope = typeof self === "object" && self !== null && typeof (self as { document?: unknown }).document === "undefined" ? (self as unknown as { postMessage(message: DetectReply): void; onmessage: ((event: { data: DetectRequest }) => void) | null; }) : null;
/** * How long this question waited for the thread — and the one thing the thread cannot know alone. * * It knows when the previous search returned. If that was four seconds ago, and this question was * posted two seconds ago, then two of those seconds were an idle thread and nobody was waiting for * anything; measuring from the last return would draw a two-second stall that never happened. So the * page's post time is the other end of the interval, and the wait is what this question spent after * it was asked — never negative, and never somebody else's evening. */export function searchQueueGap( /** when this handler began */ started: number, /** when the previous search returned, or 0 if there has not been one */ lastFinished: number, /** when the page posted this, on the clock both threads share; unknown until it says so */ sentAt: number | undefined,): number { const from = Math.max(lastFinished, sentAt ?? started); return Math.max(0, started - from);}
/** When the last search returned, on this thread's clock; 0 until the first one has. */let lastFinished = 0;
if (scope) { scope.onmessage = (event) => { const started = performance.now(); // Nothing is transferred, only copied: the chroma is ~250 KB, and transferable buffers // would detach the caller's matrix — a series that reads as empty on the thread that just // built it, to save a copy smaller than one audio frame. const reply = runDetect(event.data); const finished = performance.now(); // The queue here is the message queue, and it is only visible from inside it: if something was // searched before this and returned a moment ago, the gap is how long this question waited. const queued = searchQueueGap(started, lastFinished, event.data.sentAt); lastFinished = finished; scope.postMessage({ ...reply, queuedMs: Math.round(queued), workMs: Math.round(finished - started), }); };}