/** * Auto-detecting the A–B region: the repeating span a track was written to loop in. * * The second version of this file. The first was a port of ~/dev/Looper's * `find_loop_point`, whose whole detection is one argmax per frame, a Pearson correlation of * that series with itself, and a search over it; the port kept that representation and * inherited its three complaints. This one keeps the *shape* of the search — a time-lag * surface, scored per period, offered as candidates for a human to accept or dismiss — and * replaces the measurement and the decision underneath it, which is what the literature * (Goto's RefraiD, Bartsch & Wakefield's chromagram, Mauch et al.'s diagonal criteria) has * been saying about this task since 2001. * * Four changes, each of which is argued where it is made and each of which was measured * against the fixtures in `test/signal.ts` before being shipped: * * - **the frame is a chroma vector, not a dominant bin** (see `chroma.ts`). One argmax per * frame is a fine signal for a monophonic game tune and a blind one for anything else. * The measured difference: the performed repeat the old fingerprint could not see at all * (refused, best 0.84, the same as a file with nothing in it) now scores 0.99 and ranks * first of 457 candidate lags. * - **the score is a copy against its copy, not a window against a window.** `start … start * + period` is compared over the *whole period*, which is what "this region repeats" * means. The old fixed 13 s window let a four-second hook carry a twenty-four-second * candidate, which is the shape of the "candidates come back somewhat long" complaint. * - **the statistic is a mean over the copy, so a threshold can be honest.** The old search * took the maximum over a couple of million window pairs, and the maximum of that many * correlated draws reaches 0.77 on a file with nothing repeating in it — so no absolute * floor could both accept a real repeat and refuse a hook. Per-lag means do not inflate * with the size of the search: measured on the fixtures, the no-loop tracks top out at * 0.64/0.68 and the four real repeats sit at 0.90–0.99. * - **the threshold is partly the file's own.** `τ = max(floor, bulk + margin)`, where `bulk` * is this track's own typical lag score. The floor alone floods a track that is mostly * chorus (where every lag resembles every other at 0.87); the comparative term alone * accepts a file whose only distinction is a modest peak. Both fixtures of each kind are * refused by the pair of them. * * What is *not* here, and why: no hidden Markov model, no dynamic programming, no learned * embedding. The app's analysis runs in a module worker beside a playing track with one * dependency (a five-hundred-line FFT) and a few hundred milliseconds; everything that would * beat this at MIREX needs a model tens of megabytes, and its advantage is robustness to * *different recordings of the same piece*, which is not the problem here — the two copies * are the same file at the same tempo. What the literature contributed instead is free: the * representation, the aggregation, and the threshold. * * The phase — where A lands — is still not recovered beyond the earliest position that * clears the threshold. On a body that is truly periodic every alignment inside it scores the * same, so there is no best to find; what is offered is the candidate list and the `c` key. * * Pure function over samples: no audio graph, no clock, no DOM, no signals. That is what makes * it testable, and what makes the inline fallback in `analyze.ts` the *same code* rather than * a second implementation of it. */ import { chroma, rowDot, type ChromaOptions, type ChromaSeries } from "./chroma"; import { barPhase, beatGrid, poolEnergy, poolToBeats } from "./beat"; import { traceDetect } from "./trace"; import { rankerLine, rankerState } from "./detectrank"; import { count } from "../print"; /** * A repeating span, in seconds of the decoded buffer — the same unit as `LoopRegion`, so a * candidate can be handed to `setLoop` without a translation to get wrong. */ export interface Candidate { start: number; end: number; /** the period that was detected, which after a trim is no longer the length */ period: number; /** the copy-vs-copy agreement over the region: 1.0 is indistinguishable, 0.9 is performed */ r: number; /** * What the order was decided by: `r` with the period prior spent against it and the learned weight * spent on its contrast. Reported because the order is a claim about the track and a listener * pressing `c` deserves to see the number behind it rather than reverse-engineer it from a position * in a list — and because with no telemetry logged this is `r` less a term that is zero. */ rank?: number; /** * Length in bars, when the search ran on a beat grid. Absent on the frame grid, where a bar is * not a property of the rows and inventing one would be a number with nothing behind it. */ bars?: number; /** * Both boundaries land on downbeats — or `undefined`, which means there was no bar to land on. * * Three states, because there are three sentences and collapsing the last two was a lie of the * tidy boolean: `true` is "the bar is known and this region begins on the one", `false` is "the bar * is known and this region does not", and `undefined` is "this search had no bar" — a frame grid, * where a bar is not a property of the rows, or a beat grid whose downbeat was never measured, or * one whose four candidate phases tied so evenly that the phase left the arithmetic as a coin. * Reporting `false` for that last case would have the detector claiming a region is off the bar * using a bar alignment it has itself just disowned, and the difference between "it does not land * on the one" and "nobody knew where the one was" is the whole difference between shrugging and * lying. See `barKnown`. */ onBar?: boolean; /** * How invisible the wrap is, on the 0..1 scale the agreement uses — 0.5 when there was nothing to * measure, which is what a candidate at the very end of a track gets. * * This is the measurement the loop detector never had, and it is a different measurement from * `r`. `r` asks whether the region repeats, which is a property of the region. `seam` asks how much * of the music the loop has to destroy in order to replay it: Shi and Mysore's argument (LoopMaker, * CHI 2018) is that a loop is `a` + `b`, the music that follows `b` in the song is `c`, the song as * played is seamless so `b` into `c` is seamless, therefore the loop is inaudible to exactly the * extent that what it plays after the jump — `a` again — resembles what the record actually has * there, which is `c`. Compare the follower of the start against the follower of the end and the * number says how much of the transition survives the cut. * * For an exact repetition the two followers are the same rows an integer period apart and the seam * comes out at 1.0, which looks redundant until the copies drift — and on a real record, performed * by a human over four minutes, they always drift. That is where the four positions of one family * separate, which is what this number is for: the listener's complaint was never that the region did * not repeat, it was that the loop clicked. */ seam?: number; /** * How far this region's agreement stands above what the same period scores everywhere else in this * track, normalised on 0..1 by `CONTRAST_SCALE`. The answer to "is 0.99 a lot?", which the score * alone cannot give on material where every lag scores 0.99: two candidates that tie on agreement * are not tied on evidence, and the one that stands out from its own background is the one that * means something. */ contrast?: number; /** * How musically ordinary this period's shape is, on 0..1 — a whole number of bars, and a length in * the range loops are written in. Reported so a listener can see the ranking's opinion rather than * infer it from the order, and so a bad opinion is arguable at the console. */ prior?: number; /** * How unexpected the wrap is, on the same 0..1 scale as `seam`: the jump the cut introduces, * measured against the worst step the loop already takes inside itself. LoopGen's seam perplexity * read in a feature space instead of a token space. * * Not a duplicate of `seam`. `seam` compares what the loop replays against what the record has * there — how much of the record's continuation survives. `wrap` asks whether the arrival is * surprising at all. A loop can return to something identical to what the record played next and * still arrive there with a gear change, and the two numbers disagree precisely on the candidates * where that matters. */ wrap?: number; /** * What fraction of the region agreed outright rather than being bridged: matched rows over spanned * rows. A loop that is 1.000 on its matched rows and 0.62 on this field is a loop with two bars of * fill in the middle of it that the search talked its way past, which is worth knowing before * arming it. */ coverage?: number; } /** * Why there is no region. Three refusals, not one, because they are three different sentences * to a listener who pressed a key and got silence: the bytes are not here yet, nothing in this * track repeats at all, and something repeated but not enough to bet a boundary on. */ export type Notfound = "no-bytes" | "no-repeat" | "not-convincing"; export interface DetectResult { /** shortest period first; empty exactly when `not` says why */ candidates: Candidate[]; not?: Notfound; /** * The strongest score the search saw, whether or not it cleared the threshold. Nothing * renders it; it exists so that the threshold can be argued with from the console rather * than reconstructed by rebuilding the module. See `SearchStats.tau`. */ best?: number; /** what the search looked at, as opposed to what it concluded */ stats?: SearchStats; /** * The beat times in seconds, when a beat grid was computed for this file — the grid the search * pooled its rows on, handed over whole rather than summarised to `stats.bpm` and `stats.beatAt`. * * It crosses the worker seam for the bar's pulse. A mean period can only ever pulse near the * music: the grid's own intervals are where the transients are — the dynamic program chose each * beat for having an onset there — so a cycle armed on one interval keeps its flash honest only * until the next interval disagrees with the mean. The array is ~4 KB of Float32Array for four * minutes, and it is the same number the detector already computed and threw away. */ beats?: Float32Array; } /** * What the search looked at. Every field is here because a wrong answer has to be diagnosable * from the log line alone — the feature's history is a series of verdicts that could not be * argued with because the measurement had been discarded on the way to the verdict. */ export interface SearchStats { /** frames in the analysis grid */ frames: number; /** frames that cleared the loudness mask; the ratio is the mask's report on the track */ audible: number; /** the range of periods searched, in frames */ periodFrom: number; periodTo: number; /** how many lags were scanned, and how many similarity computations that cost */ lags: number; cells: number; /** the best copy-vs-copy score anywhere, or NO_MATCH when nothing was comparable */ best: number; /** this track's own typical lag score: half the threshold, see `tau` */ tail: number; /** the quantile `tail` was taken at */ tailQuantile: number; /** how many lags that half had to let above it, at minimum */ tailLags: number; /** the threshold this run was decided by: `max(floor, tail)` */ tau: number; /** how many lags cleared it */ cleared: number; /** the twelve typicality weights this track produced, as a spread: 0 means every class is equally typical */ weightSpread: number; /** * The twelve typicality weights themselves, in C…B order, mean 1.0. * * The spread was the summary and it turns out to be the one number that cannot tell the story: * nine real tracks in a row reported a spread of 1.00, which is either "this library uses every * note equally" or "the weighting never got a chance to disbelieve anything", and those two want * opposite fixes. Only the twelve numbers say which — a single dead class is a fact about the * music, twelve equal ones is a fact about the code. */ weights: number[]; /** * The fraction of the audible rows in which each of the twelve classes was sounding, C…B. * * Printed for one reason: with the gate off — and with the gate on but set too low — every entry * is 1.0, and that is the signature of a front end that is comparing twelve numbers no frame ever * disputed about. Twelve ones is not "this music uses every note", it is "nothing was ever * asked"; a real track with the gate working reports a spread, and the shape of that spread says * whether the detector is being told which notes matter in this song. */ presence: number[]; /** the numbers the decision was taken on, echoed back so one log line reads on its own */ floor: number; trim: boolean; trimGate: number; trimGapSec: number; trimMinSec: number; /** how many candidates were cut back to the stretch that actually repeats */ trimmed: number; /** * How many boundaries the bar moved onto a downbeat, and so how often the rule at `barShift` had * anything to say about this track. * * Reported for one reason: the change it measures is allowed to fire only where the measurement * could not tell two rows apart, and "only where the measurement abstained" is a claim about the * arithmetic rather than one anybody can see. Zero on every track means the bar never had a vote and * the loop is where the correlation put it; a number near `cleared` means it fired on most regions, * which would mean the indifference margin is doing the aligning and not the correlation. Either * reading argues with the change, and neither is visible from the candidate list. */ barMoved: number; body: boolean; /** the body the candidates were confined to, in frames, when there was one */ bodyFrom: number; bodyTo: number; smoothSec: number; frameSec: number; /** which clock the answer came out of: seconds are seconds, but a boundary is not */ grid: "frames" | "beats"; /** * The track's tempo in BPM, when a beat grid was computed for it — even if the lags were finally * scored on the frames, and even if nothing repeated: the tempo is a measurement of the file, * and the bar shows it beside the title where a listener can check it against their own foot. */ bpm?: number; /** * The first beat of the grid whose `bpm` this is, in seconds — the origin the bar's pulse counts * its phase from. Absent together with `bpm` on a frame-grid answer with no grid under it. */ beatAt?: number; /** rows per bar on that clock; 0 for frames */ rowsPerBar: number; /** how far the downbeat phase stood over its runner-up — small means it was a tie */ barMargin: number; /** the weight the period prior was allowed to spend against a score, in agreement units */ priorWeight: number; /** the period the prior thinks is ordinary, in bars */ priorBars: number; /** how many bars the agreement had to sustain for */ minBars: number; /** whether the lags were scored by sustained path or by window mean */ path: boolean; /** the most distinctive lag the search saw, in contrast units — 0 says the track had no contrast at all */ bestContrast: number; } /** What `score` answers when a pair is not a comparison at all. */ const NO_MATCH = -1; /* ------------------------------------------------------------------------- */ /* The constants, each next to the measurement that set it */ /* ------------------------------------------------------------------------- */ /** * 8 s, which is the literature's floor for "a segment worth calling a pattern" — RefraiD's * line segments have to exceed 6.4 s, and its chorus prior runs 7.7–40 s. * * The old default was 13 s, inherited from Looper's 500 MP3 frames rather than chosen. It can * come down now because the thing that forced it up was the short-lag false positives a * dominant-bin code produces — measured, the through-composed fixture's best 5-second lag * reaches 0.845, which the pair of thresholds below refuses on its own merits. At 8 s the * detector can find a two-bar riff at 120 BPM, which is a thing a person practising a song * wants, and the fixture suite says it costs nothing in false positives. */ const MIN_PERIOD_SEC = 8; const MAX_PERIOD_SEC = 180; /** * The absolute half of the threshold: a copy has to agree with its copy this much. * * Measured on the fixtures with the answers known, with the chroma's own temporal smoothing on. * The two tracks that have nothing repeating in them top out below this — a through-composed * melody at 0.880, a song with a recurring four-second hook and no loop at 0.858 — while every * one of the four that do repeat scores 0.985, 0.987, 0.991 and 0.999 at its own period, which is * also rank 0 of every lag the search tried. The gap between the worst yes (0.985) and the best * no (0.880) is where this number sits. * * It is worth saying what changed, because the previous version of this file could not make an * absolute threshold work at all: the *statistic* changed, not the tolerance. Comparing a whole * copy against its whole copy, on vectors that have been blurred over a quarter second, is a * different measurement from taking the maximum of a couple of million window-pair correlations, * and it is the one that has a floor under the noise. * * Still a number chosen on synthesised material, so it is tunable (`hackermusic.detectTuning({floor})`) * and the refusal prints the reading it was decided against. */ const FLOOR = 0.93; /** * The comparative half: a lag has to be in this top fraction of the track's own lag scores. * * The floor alone floods the tracks that are *mostly chorus* — the performed fixture and the * riff-with-fills fixture have no quiet half to be measured against, so nine hundred lags in them * score 0.95 and a floor anywhere near that either floods them or refuses their real answer. What * separates the answer on those two files is not its absolute height but its standing: 0.999 * where the track's 98th percentile is 0.97, and 0.987 where its is 0.98. * * A quantile rather than a fixed margin above the median, because the two hard fixtures have * almost no spread to rise above — the riff fixture's per-lag scores run 0.966 to 0.987, so a * margin of six points would refuse its real answer while this admits it. The quantile asks the * question that survives a compressed distribution: is this the best thing in the file? * * Two knobs therefore do two different jobs and neither can be dropped: the quantile alone accepts * the best of a file that has nothing (its 0.88 would be its own top percentile), and the floor * alone accepts a chorus that resembles itself everywhere. * * A third thing has to be said here, because a quantile is not the same rule on every clock and the * arithmetic is better written down than discovered. The lags run from `minPeriodSec` to * `maxPeriodSec`, so how many there are is set by the length of a row: a four-minute track has about * 2 400 of them on the frame grid and about 225 on a beat grid — and the 98th percentile of 225 values * is the value with five above it. On a beat grid, `TAIL_QUANTILE = 0.98` is not a percentile at all: it * is "be among the five best lags", while the same music measured on the finer clock gets a threshold * with forty-nine above it. A short clip is the degenerate case, where one lag clears it and the rule is * literally "be the best lag in the file". * * That is a third contributor to what §11 of `RESEARCH-loops-to-the-beat.md` found, next to the flat * representation and the inert floor: a body that repeats contributes its period, its double, its triple * and the grid neighbours of each, which is comfortably more than five lags scoring near 1.0 — so the * tail sits at 0.99+ on a beat grid *whatever the representation is*, and part of what read as chroma * being unable to tell two frames apart is the comparator having no room left to compare in. `TAIL_LAGS` * is the fix, and `scripts/ssl-bakeoff/bakeoff.mjs --selftest` prints both readings side by side. */ const TAIL_QUANTILE = 0.98; /** * How many lags the comparative half has to let sit above it, however the quantile works out. Default * `0`, which means "no floor: spend the quantile as asked", because this is today's behaviour and the * evidence for changing it is not in yet. * * The floor is on the *count*: the quantile actually spent is * `min(tailQuantile, 1 − (tailLags + 1)/lags)`, which is the percentile wherever a percentile has room * to mean something and a count where it does not. * * Off by default, and the reason is worth more than the knob. It was tried at 12 — enough lags that a * percentile could be a percentile again on a beat grid — and what arrived on the fixtures was the * §11 failure reproduced on demand: the twenty-four-second answer the fixture was written to contain * displaced by the shortest period the search is allowed, 4.2 and 4.8 seconds, because loosening the * threshold lets through every short lag that overlaps a few copies of a representation which cannot * tell its frames apart. The ranking cannot clean that up, and it is not supposed to: the prior is * capped at the indifference margin deliberately, so a short lag that genuinely scores higher is not * moved by a prior, and should not be. * * Which is the strongest argument in the repo that the lever is upstream of the threshold. Turning this * number up is a way to see the problem more clearly at a console; it is not a way to fix it, and the * one measurement of what it is worth is `scripts/ssl-bakeoff/`, run on files whose answers are known. */ const TAIL_LAGS = 0; /** * How far a copy may dent before the run that contains it is over, and how short a run may be * and still be offered. * * The run is the line segment: the stretch along the diagonal over which the two copies agree, * which is what the region is cut to. A dent is one frame of a performed take leaning on the * neighbouring bin; a fill that never returns is seconds. Three quarters of a second sits * between the two, and 4 s is below which a run is not something a person can loop. */ const TRIM_GAP_SEC = 0.75; const TRIM_MIN_SEC = 4; /** * How many bars the agreement has to sustain for, before the region is worth arming. * * Two. It reads as a truism and it is the only term in this file that argues with `TRIM_MIN_SEC` in * seconds, which is the reason it exists: four seconds of a slow track is one bar, and one bar of * anything is not a loop, it is a coincidence with a bar of agreement in it. Four seconds of a fast * track is four bars, which is a loop — so neither unit is the right one on its own, the bar is the * unit the music is in, and the two floors are combined by whichever asks for more. */ const MIN_BARS = 2; /** Per-frame agreement counted as "still the same music" inside a run. */ const TRIM_GATE = 0.8; /** * How far to denoise the diagonal before scoring it: a box average this wide. * * RefraiD smooths `r(t,l)` with a moving average before thresholding it, for the reason every * smoothing in this file has: a single frame is not evidence and a single frame is not a * contradiction either. Half a second is a fifth of the shortest period offered, which is the * point at which smoothing starts being a lie about the note length. */ const SMOOTH_SEC = 0.5; /** Two lags this close in ratio are the same loop counted twice (the 2×, 3× harmonics of a seam). */ /** * How far apart two lags have to be to count as two different claims about the track. * * This is a resolution statement, not a tuning knob. The chroma is blurred over a quarter of a * second and the diagonal is averaged over half one, so a period estimate is only good to * roughly that much — a period of fifteen seconds is really "fifteen, give or take half a second", * and the grid steps it in 46 ms increments. Lags 0.46 s apart at fifteen seconds are therefore * the *same* answer written at three neighbouring grid points, and offering all three is what * made the candidate list on a one-loop J Dilla instrumental read as three overlapping regions: * 14.81, 15.27 and 15.73, all four percent apart, all the same loop. * * The first version of the rewrite had a one-second spacing rule and the harmonic test was * believed to subsume it. It is not the same test: the harmonic tolerance is a fraction of the * *ratio to the parent*, which at fifteen seconds puts the boundary at exactly the spacing where * these duplicates live, so they walked straight through it. */ const FAMILY_TOLERANCE = 0.05; /** How many small integers a period ratio has to be reducible to before the two are one family. */ const FAMILY_MAX_DENOMINATOR = 4; /** * Whether two periods are the same claim: near-equal, or one a small whole multiple of the other. * * "Small whole multiple" is stated as a ratio close to p/q with q ≤ 4 rather than as an integer, * because the peaks a repeating body throws are not only its multiples: a fifteen-second loop * whose halves also line up produces a lag at two thirds of it, and that is the same loop being * counted, not a shorter loop inside it. Restricting to small denominators is what keeps the * test from collapsing two genuinely different loops that happen to sit at a weird ratio. */ function oneFamily(lag: number, of: number): boolean { // Either number an exact multiple of the other, in either direction: the multiples a periodic // body throws, and the fundamental they all divide by. Stated separately from the rational test // below because it must not be capped by the denominator limit — a five-second loop and the // seventy-five-second window that is five of them are one claim, and 1/5 is past q ≤ 4. for (const [big, small] of [ [lag, of], [of, lag], ] as const) { const times = big / small; if (Math.abs(times - Math.round(times)) <= FAMILY_TOLERANCE * Math.max(1, Math.round(times))) return true; } const r = lag / of; for (let q = 1; q <= FAMILY_MAX_DENOMINATOR; q++) { const p = Math.max(1, Math.round(r * q)); // The epsilon is not fudge: 15/75 is 0.2, which is not representable, and the difference // against 1/4 lands on the wrong side of a tolerance boundary purely because of how the number // is stored. A test that flips on the last bit of a float is a test of IEEE, not of music. if (Math.abs(r - p / q) <= FAMILY_TOLERANCE + 1e-9) return true; } return false; } /** Inside this of a lag's best score, the *earliest* such position wins: the composer's seam. */ const TIE_MARGIN = 0.02; /** Below this fraction of frames audible there is nothing to correlate: silence, or a track the mask swallowed. */ const MIN_AUDIBLE_RATIO = 0.05; const MIN_AUDIBLE_FRAMES = 16; /** * A track whose chroma never changes — one chord, one drone — has no evidence to compare, and * "the best of no comparisons" must not become an answer the way the old code's zero-variance * series did. Measured as the mean deviation of a frame from the track's own average frame. */ const MIN_VARIATION = 0.003; /* ------------------------------------------------------------------------- */ /* Ranking: what to believe when the measurement cannot tell two answers apart */ /* ------------------------------------------------------------------------- */ /** * How much the shape of a period is worth, in units of agreement. * * Set equal to `TIE_MARGIN`, and the equality is the whole design. The first version of this * ranking had no length prior at all and the ten real tracks of `docs/research/calibrate-loops.md` * answered it the way a search with no tie-breaker answers: every winner at 7.7, 8.5, 9.9, 10.9 s — * the shortest lag the search is allowed, every time, because a short lag overlaps the most copies * of a representation that cannot tell its frames apart. Nothing about that is a measurement of the * music; it is an artefact of the search having no opinion and the shortest lag always being first * in an argument with no content. * * So the prior is worth exactly the indifference margin: it can break a tie, and it cannot overturn * a difference the measurement can actually hear. A four-bar loop at 0.981 outranks a two-bar one at * 0.994, which is the case that was wrong. A four-bar loop at 0.80 does not outrank a two-bar one at * 0.99, which is the case that would be wrong the other way. Raising this number buys the failures it * is set up to avoid, which is why it is a knob and not a tuned constant. */ const PRIOR_WEIGHT = 0.02; /** * The period the prior thinks is ordinary, in bars, on a log scale. * * Eight, which is the centre of what a person who says "loop that bit" means: the literature's own * numbers bracket it (RefraiD's chorus prior runs 7.7–40 s; LooperGP mines phrases bookended by a * repeated phrase; LoopGen doubles and halves until a generated loop is a whole number of bars * because "a 2.5-bar unit is musically unpleasing when repeated"). At 120 BPM eight bars is 16 s, * which is also where the observed winners wanted to be. Two bars is disfavoured to exp(−(ln 4)²/2σ²) * ≈ 0.18 of full weight — a fourth of the indifference margin against it, so a genuinely better * two-bar riff still wins comfortably. */ const PRIOR_BARS = 8; /** In natural-log units of bar count, ≈1.1 octaves: wide enough not to be a claim about form. */ const PRIOR_BARS_SIGMA = 0.75; /** * How far from a whole number of bars a period may be before the fit falls away, in bars. * * A tenth and a half of one: the beat grid quantises a period to beats, so a period that is not a * whole number of bars is not a rounding error — it is a loop whose second pass comes in half a bar * late, which is the thing listeners complain about when they say a loop is "not on the beat". */ const BAR_FIT_SIGMA = 0.15; /** * The agreement difference that counts as a full-strength contrast: how far a candidate has to stand * above what the *same lag* scores everywhere else in the track to be called distinctive rather than * typical of this track's background. * * Stated as a difference and not as a z-score deliberately. Dividing by the lag's own spread is the * textbook normalisation and it fails on exactly the material that needs it: on a track whose lag * scores are all 0.99 the spread is ~0.001, so every position of every lag scores a spectacular * z-score and the normalisation manufactures the contrast it was supposed to measure. The raw * difference cannot do that — a flat track's best position is 0.005 above its own median, which is * what it looks like and what it is worth. */ const CONTRAST_SCALE = 0.12; /** Bins over [0,1] for the per-lag median, so the contrast costs one pass and 256 counters. */ const CONTRAST_BINS = 256; /** * The middle of a histogrammed column, to half a bin. * * The median rather than the mean because the peak is in the column: on a track that really does * contain a loop, the mean of the lag's own positions is dragged up by the loop's own positions, and * the contrast that comes out measures the loop against itself. The count-based middle is not moved by * one spectacular position, which is the whole property wanted here. */ function histMedian(hist: Int32Array, count: number): number { if (!(count > 0)) return 0; const half = count / 2; let acc = 0; for (let b = 0; b < hist.length; b++) { const next = acc + (hist[b] ?? 0); if (next >= half) return (b + 0.5) / hist.length; acc = next; } return 1; } /** * How much worse than the worst step inside itself a wrap may be before it scores nothing. * * This is the scale of the `wrap` measurement, which is LoopGen's seam perplexity read in a feature * space rather than a token space: the jump the loop introduces is compared against the worst * adjacency the loop already contains, because a transition that is no more surprising than the * music's own worst moment is, to the extent that anything is, inaudible. 0.2 of cosine is a * chord change; a wrap that bad is a different chord, and there is no ranking that makes it good. */ const WRAP_SCALE = 0.2; /** Per-row cost of bridging a disagreement in the path score, in units of agreement. */ const PATH_GAP_COST = 0.3; /** How far apart the two copies may be allowed to disagree and still be one run, in seconds. */ const PATH_GAP_SEC = 1.2; /** * How musically ordinary a period is, on 0..1: the whole-number-of-bars fit times a log-normal on * the bar count. * * `1` means "this is exactly what a loop is shaped like" and it costs the ranking nothing; `0` means * the ranking will spend the whole indifference margin against it. On a frame grid — where a bar is * not a property of the rows and inventing one would be a number with nothing behind it — the answer * is neutral `1`, which is the same honesty the candidate's `bars` field already practises. */ function metricPrior(lagRows: number, rowsPerBar: number, o: Resolved): number { if (!(rowsPerBar > 0) || !(lagRows > 0)) return 1; const bars = lagRows / rowsPerBar; const off = bars - Math.round(bars); const fit = Math.exp(-(off * off) / (2 * BAR_FIT_SIGMA * BAR_FIT_SIGMA)); const centre = o.priorBars > 0 ? o.priorBars : PRIOR_BARS; const ln = Math.log(bars / centre); const shape = Math.exp(-(ln * ln) / (2 * PRIOR_BARS_SIGMA * PRIOR_BARS_SIGMA)); return fit * shape; } /** * How surprising the wrap is, on the 0..1 scale the other seam measurements use. * * The loop plays `[start … end)` and then plays it again, so the only adjacency the loop *creates* is * the pair `(end − 1, start)`; every other adjacency in the played audio already exists on the record. * That makes the measurement a comparison of one number against a distribution of the loop's own * making: `jump`, the discontinuity of the wrap pair, against the 90th percentile of the * discontinuities the loop contains between its own adjacent rows. A wrap no worse than the worst * step the music already takes is a wrap the listener has already agreed to hear. * * Two measurements of the wrap are better than one, and they are not duplicates of each other. `seam` * above (LoopMaker) asks how much of *the record's* continuation the cut destroys; `wrap` asks how * *unexpected* the cut is in the loop's own terms. A candidate can be strong on one and weak on the * other — the loop that returns to a bar identical to what the record played next but arrives there * with a gear change is the example — and a listener hearing one of the two failures should be offered * the candidate that does not have it. * * `undefined` is the answer for a loop with nothing after it and for a loop too short to have an * interior to be compared against, which is the same "there was nothing to measure" the other * numbers report rather than a score of zero. */ function wrap( values: Float32Array, frames: number, start: number, end: number, width: number, ): number | undefined { if (!(end > start + 1) || !(end <= frames)) return undefined; const step = (a: number, b: number): number => 1 - rowDot(values, a * width, values, b * width, width); const jump = step(end - 1, start); const seen: number[] = []; for (let i = start; i < end - 1; i++) seen.push(step(i, i + 1)); if (seen.length < 2) return undefined; seen.sort((a, b) => a - b); const worst = seen[Math.min(seen.length - 1, Math.floor(0.9 * seen.length))] ?? 0; const excess = Math.max(0, jump - worst); return Math.max(0, Math.min(1, 1 - excess / WRAP_SCALE)); } /** * The best-sustained-agreement run along one lag's column. * * The replacement for "the mean over a window exactly one period long, plus a separate run detector * with a hard gate in it", and it exists because those two are two measurements of one thing and they * can disagree. This is the alignment literature's object — the same max-sum diagonal that cover-song * identification has run since Serrà et al. put dynamic programming on a cross-similarity matrix — * applied to the self-similarity of one track: a path along the diagonal that may bridge a stretch * where the copies disagree, paying `gapCost` per row bridged, scored by the sum of the rows it * actually matched. * * Two properties the window mean does not have: * * - **support comes out of the criterion rather than being bolted on.** A max-*sum* prefers a long * agreement to a short flattering one; the argmax of a *mean* is indifferent to how long the * agreement lasts, which is half of why short lags were winning. The span and the matched count * come back with the path, so "this region agreed for twenty-two seconds" is a measurement and * not a claim about the period. * - **there is one gate, and it has a price.** `TRIM_GATE` was a threshold on a per-row similarity, * so a row at 0.79 ended a run and a row at 0.81 did not. Here a bad row costs what it is worth * and the path keeps going when it is worth going. * * The recurrence is `A[t] = (col[t] − gate) + max(0, max over p in [t − gap, t − 1] of A[p] − gapCost·(t − p − 1))`: * either start a run here, or extend the best run that ended at some matched row `p` and pay for the * rows skipped. The price is per row *skipped*, and the −1 is what says so: extending from the row next * door skips nothing and costs nothing, and a charge levied on the distance instead would tax ordinary * continuation at the bridge rate — which is not a subtlety, it is the difference between a path that * can run and one that can only ever be a single row long. The inner maximum is a sliding-window * maximum over `A[p] + gapCost·(p + 1)`, so the whole thing is one pass with a deque rather than * `O(n·gap)` — which matters, because this runs per lag. * * **The row is scored against the gate and not against zero, and that is the load-bearing part.** * Without it the criterion is a sum of non-negative numbers, and a sum of non-negative numbers is * always maximised by taking everything: every bad row would rather be *included* at its own low value * than skipped at the bridge price, the gap states would be unreachable in practice, and the "path" * would be the whole column with a name on it. Scoring each row as its excess above the gate is what * makes the two ways of handling a bad row comparable — include it and lose `gate − col[t]`, bridge it * and lose `gapCost` — and it is the same arithmetic the run detector has always done with its * threshold, with a price in place of a wall. * * Returns `null` when no path long enough exists, which is the caller's cue to refuse the lag rather * than to score it with something else. */ export interface RunPath { /** the first matched row, relative to the column */ start: number; /** first matched row to last matched row, inclusive — the span the region is cut to */ span: number; /** rows the path actually matched inside that span, which is `span` minus the rows bridged */ count: number; /** mean agreement over the matched rows — comparable with the window mean this replaces */ mean: number; /** sum of the matched rows' agreement: the quantity the path was chosen for */ sum: number; } /** The forward pass's tables, kept so a run can be recovered from any end without recomputing it. */ export interface PathSet { readonly a: Float64Array; readonly count: Int32Array; readonly from: Int32Array; readonly len: number; readonly minCount: number; } /** * The tables one scan needs, allocated once per search rather than once per lag. * * Exported with `bestPath` because the scan is per lag and there are thousands of lags in a track: * five arrays per lag is a megabyte of allocation per pass and a collection to run while the audio is * playing. A caller that asks for a path asks for the scratch to put it in. */ export interface PathScratch { a: Float64Array; key: Float64Array; from: Int32Array; count: Int32Array; deque: Int32Array; } export function pathScratch(frames: number): PathScratch { return { a: new Float64Array(frames), key: new Float64Array(frames), from: new Int32Array(frames), count: new Int32Array(frames), deque: new Int32Array(frames), }; } /** * One forward pass over a column: the best run ending at every row, in `a`, with its predecessor in * `from` and its matched-row count in `count`. * * `a[t]` is the *sum* the recurrence maximises, gaps already paid for — a run's mean is not additive, * so the mean is recovered in `pathAt` rather than being chased through the pass. */ function pathScan( col: Float32Array, len: number, gate: number, gapCost: number, gap: number, minCount: number, scratch: PathScratch, ): PathSet { const { a, key, from, count, deque } = scratch; let head = 0; let tail = 0; for (let t = 0; t < len; t++) { let base = 0; // starting a run here costs nothing and earns nothing let src = -1; let cnt = 0; // Drop predecessors too far back to bridge — `gap` rows may be skipped, so the oldest usable run // ended at t − gap − 1 — then take the best of what is left: the deque is kept in decreasing // `key`, so its head is the sliding-window maximum. while (head < tail && deque[head]! < t - gap - 1) head++; if (head < tail) { const p = deque[head]!; const bridged = (key[p] ?? 0) - gapCost * t; if (bridged > 0) { base = bridged; src = p; cnt = count[p] ?? 0; } } a[t] = (col[t] ?? 0) - gate + base; from[t] = src; count[t] = cnt + 1; key[t] = (a[t] ?? 0) + gapCost * (t + 1); while (head < tail && (key[deque[tail - 1]!] ?? 0) <= (key[t] ?? 0)) tail--; deque[tail++] = t; } return { a, count, from, len, minCount }; } /** Recover the run that ends at `t`: its matched rows, their span, their mean and their sum. * * `clip` bounds the answer to the rows a loop of this period would actually arm. It exists because a * max-sum path has no reason to stop at a period — on a body that repeats three times the best path is * two periods long, and the evidence that it is two periods long is exactly what makes it worth * arming, while the region a listener hears is still one period of it. With a clip the run reports the * rows inside the first `clip` of its span, which is the part the candidate is cut to, and the span * beyond the clip stays where it belongs: in the evidence, not in the boundaries. */ function pathAt( col: Float32Array, set: PathSet, t: number, clip = Infinity, scratch?: Int32Array, ): RunPath { const { from } = set; // The chain of matched rows, newest first. A caller that only wants the whole run does not need the // list, so it is only materialised when a clip asks for one. const rows = scratch ?? new Int32Array(set.len); let n = 0; let at = t; for (let guard = 0; guard <= set.len; guard++) { rows[n++] = at; const p = from[at] ?? -1; if (p < 0) break; at = p; } const whole = rows[n - 1] ?? t; const last = Math.min(t, whole + clip - 1); // Walk the chain from the oldest row forward and keep what falls inside the clip: the chain is in // decreasing row order, so the rows outside it are the ones at the front of the list. let sum = 0; let kept = 0; for (let i = n - 1; i >= 0; i--) { const row = rows[i]!; if (row > last) break; sum += col[row] ?? 0; kept++; } const span = last - whole + 1; return { start: whole, span, count: Math.max(1, kept), mean: sum / Math.max(1, kept), sum, }; } /** * The end of the best run in the column, or -1 when no run is long enough to be worth calling one, or * worth anything at all: the excess over the gate has to come out positive, which is the same promise * the run detector's minimum makes in rows rather than in score. * * Chosen on `a`, the sum the recurrence maximises: the mean is what the candidate *reports*, and the * sum is what makes a long agreement beat a short flattering one, which is the whole reason the path * is the object being optimised. */ function bestEnd(set: PathSet): number { const { a, count, len, minCount } = set; let best = 0; // not -Infinity: a run has to be worth more than not having a run let at = -1; for (let t = 0; t < len; t++) { if ((count[t] ?? 0) < minCount) continue; if ((a[t] ?? 0) > best) { best = a[t] ?? 0; at = t; } } return at; } /** * The best path in the column, or `null` when nothing sustained itself. * * Exported for its own tests, in the same spirit as `bestEndShift`: the behaviour that distinguishes * it from a window mean — bridging a bad stretch, preferring a long agreement — is only visible in a * column built to contain one, and a fixture weak enough to make the two differ is a fixture the * detector would refuse anyway. */ export function bestPath( col: Float32Array, len: number, gate: number, gapCost: number, gap: number, minCount: number, scratch: PathScratch, ): RunPath | null { if (len <= 0 || gap < 1) return null; const set = pathScan(col, len, gate, gapCost, gap, minCount, scratch); const at = bestEnd(set); return at < 0 ? null : pathAt(col, set, at); } /* ------------------------------------------------------------------------- */ /* Body detection: where the song starts, and where it ends */ /* ------------------------------------------------------------------------- */ /** * How wide a stretch of music the novelty kernel compares across, and how coarse its grid is. * * The checkerboard kernel is Foote's, and it is doing a different job from the rest of this * module: not "does this repeat" but "where does the track's character change", so that an * intro that never comes back and a tail that never came in can be excluded from the search * rather than offered as a loop. audiolooper's README puts the reason best, describing the * failure of the tool it replaces: *"its top candidate for a track with a long intro will often * be two mid-body moments that happen to sound alike"*. * * Twenty-four seconds, which is a section rather than a phrase: the first version of this used * eight and found the *body's own internal structure* — peaks at 40 s and 133 s on a fixture * whose only real boundary is at 20 s — because a kernel narrower than the period reads the * period as a boundary. Wide is the safe direction; a false boundary near the edge costs a * slightly shorter search, a missed one costs an intro inside the loop. */ const BODY_KERNEL_SEC = 24; /** Frames on the novelty grid: half a second, which is what the SSM is built at. */ const BODY_FRAME_SEC = 0.5; /** A novelty peak has to be this much above the track's median novelty to count as a boundary… */ const BODY_PEAK_MARGIN = 0.02; /** …and lie within this fraction of the track's length from the end it claims, or it is a mid-song change and not an intro. */ const BODY_SEARCH_FRACTION = 0.25; /** And the body has to keep at least this much of the track, or the peaks are noise and the whole track is the body. */ const BODY_MIN_KEEP = 0.4; export interface DetectOptions extends ChromaOptions { /** * Search the beat grid first, and fall back to the frame grid when the pulse is not there to be * found. On by default — the grid is the better clock where a grid exists, the fallback underneath * it is what makes an opt-out enough of a decision for a listener to have to make only that one, * and the fixtures have been re-quoted against the beat answer rather than left quoting the frame * one. It stays a knob: `detectTuning({ beatGrid: false })` is how a listening session puts the * two clocks side by side on the same track. */ beatGrid?: boolean; /** the shortest span worth offering as a loop */ minPeriodSec?: number; /** the longest */ maxPeriodSec?: number; /** the absolute half of the threshold */ floor?: number; /** the comparative half: the top fraction of the track's own lag scores a lag has to be in */ tailQuantile?: number; /** * The other spelling of the same threshold: how many lags have to be allowed to sit above it, whatever * this clock says a percentile costs. See `TAIL_LAGS` for the arithmetic behind it and for why the * default spends the quantile exactly as asked instead of flooring it. */ tailLags?: number; /** * The chromagram's temporal blur, in seconds — the window each frame is blended with its * neighbours over, which is what lets a performed repeat match itself (`chroma.ts` keeps the * argument). Zero is a real answer here rather than an absent one: it is how the blur is asked * whether it is earning its keep, and the guard below has to let it through for the question to * be askable at all. */ smoothSec?: number; /** per-frame agreement inside a run */ trimGate?: number; /** how long a sustained disagreement is, before the run that contains it is over */ trimGapSec?: number; /** the shortest run worth arming */ trimMinSec?: number; /** cut candidates back to the stretch their two copies actually agree over */ trim?: boolean; /** exclude the intro and the outro from where a candidate may be found */ body?: boolean; /** the novelty kernel's width, in seconds */ bodyKernelSec?: number; /** take a candidate whose score is within this of its lag's best at the earliest such position */ tieMargin?: number; /** * How much the shape of a period is allowed to count, in units of agreement. See `PRIOR_WEIGHT`: * the default is the indifference margin itself, so the prior can break a tie and nothing else. */ priorWeight?: number; /** the period the prior considers ordinary, in bars, on a log scale */ priorBars?: number; /** * How many bars the two copies have to go on agreeing for, when there is a bar to count. The * seconds floor (`trimMinSec`) still applies as well, and the two are combined by whichever is * longer — which is what "at least two bars, and never less than four seconds" says. */ minBars?: number; /** * Score a lag by its best-sustained-agreement path rather than by the best window mean, and cut * the region to that path. See `bestPath` for what changes and why; off until the real files have * said which of the two is the better ruler, for the reason every other switch in this module * exists: a change to how a thing is measured is not a change to be made by argument. */ path?: boolean; /** how far apart the copies may disagree and still count as one run, in seconds, in path mode */ pathGapSec?: number; } /** * The knobs, overridable at runtime, and overridable *from the console* on purpose: settling * these numbers means watching the detector re-decide the same track as a number moves, which * a constant forces a rebuild to do and a rebuild loses the track, the scroll position and the * patience the measurement needs. The override is consulted in `resolve`, the one place options * become numbers, so it reaches the worker too — by travelling in the request, not by the worker * happening to have been built beside the same constants. And it outlives the tab: a listener * finding a threshold that suits their library is running an experiment, and an experiment whose * settings are wiped by a reload is an experiment that is not run. */ const TUNING_KEY = "hackermusic.detect.tuning.v1"; let tuning: DetectOptions = readTuning(); export function detectTuning(): DetectOptions { return tuning; } /** Patch the knobs, or clear them back to the constants with `null`. Only the keys given travel. */ export function setDetectTuning(patch: DetectOptions | null): DetectOptions { tuning = patch ? { ...tuning, ...keepKnown(defined(patch), "the console") } : {}; writeTuning(tuning); traceDetect(`tuning ${patch ? "set" : "cleared"}`, undefined, undefined, () => Object.keys(tuning).length ? { ...tuning } : { defaults: "yes" }, ); return tuning; } /** Exported for the test: what storage would give the module at startup. */ export function detectTuningFromStorage(): DetectOptions { return readTuning(); } /** * The knobs the detector reads, spelled once so a key nobody recognises can be refused instead of * kept. The compile-time check below is what keeps the list honest: an option added to * `DetectOptions` without being listed here does not typecheck, so the drift that a hand-maintained * allowlist is famous for — the knob that silently does nothing — is a build failure instead. */ export const KNOB_NAMES = [ "beatGrid", "minPeriodSec", "maxPeriodSec", "floor", "tailQuantile", "tailLags", "smoothSec", "trimGate", "trimGapSec", "trimMinSec", "trim", "body", "bodyKernelSec", "tieMargin", "priorWeight", "priorBars", "minBars", "path", "pathGapSec", "loHz", "hiHz", "frameSec", "hopSec", "cut", "soft", "typical", "presence", "a440", ] as const satisfies readonly (keyof DetectOptions)[]; /** The other half of that check: the list may not name a knob that the options do not have. */ export type KnobCoverage = Exclude<(typeof KNOB_NAMES)[number], keyof DetectOptions> extends never ? Exclude extends never ? true : never : never; /** Proves `KnobCoverage` at the declaration rather than at a call site that would have to exist. */ export const KNOBS_ARE_COMPLETE: KnobCoverage = true; /** * A key the detector does not have is refused rather than kept, and said out loud when it is. * * Two ways this happens and both were seen on a real page. An experiment outlives its option: one * library's storage was still carrying `windowSec: 12` from a detector version that no longer * exists, inert and harmless except that the calibration report printed it as the tuning the run * was decided by, which makes the paste a lie about the experiment it describes. And a typo at the * console — `{ flor: 0.8 }` — is accepted by anything that keeps unknown keys, appears in the * report as a setting, changes nothing, and leaves the listener concluding that their music is the * problem. Both are worth a line of console at the moment they happen. */ function keepKnown(incoming: object, where: string): DetectOptions { const out: Record = {}; const refused: string[] = []; for (const [key, value] of Object.entries(incoming as Record)) { const known = (KNOB_NAMES as readonly string[]).includes(key); // Numbers and booleans, or nothing. A tuning that has acquired a string is worse than no // tuning, because `resolve` would spend it as a threshold; and a switch that comes back on // every reload is a switch that was never off, which is why `trim: false` and // `typical: false` have to survive the round trip too. if ( known && (typeof value === "boolean" || (typeof value === "number" && Number.isFinite(value))) ) out[key] = value; else refused.push(`${key}=${JSON.stringify(value)}`); } if (refused.length) { console.warn( `[detect] ${where} carried knobs the detector does not have: ${refused.join(", ")} — dropped.`, ); } return out as DetectOptions; } function readTuning(): DetectOptions { try { const raw = globalThis.localStorage?.getItem(TUNING_KEY); if (!raw) return {}; const parsed: unknown = JSON.parse(raw); if (typeof parsed !== "object" || parsed === null) return {}; return keepKnown(parsed as Record, "storage"); } catch { return {}; } } function writeTuning(tuning: DetectOptions): void { try { if (!Object.keys(tuning).length) globalThis.localStorage?.removeItem(TUNING_KEY); else globalThis.localStorage?.setItem(TUNING_KEY, JSON.stringify(tuning)); } catch { // A private-mode tab that refuses storage gets a session of tuning rather than an error. } } /** Strip the `undefined`s, so an absent option stays absent rather than becoming a zero. */ function defined(opts: DetectOptions): DetectOptions { const out: Record = {}; for (const [key, value] of Object.entries(opts)) if (value !== undefined) out[key] = value; return out as DetectOptions; } interface Resolved extends Required { minPeriodSec: number; maxPeriodSec: number; floor: number; tailQuantile: number; tailLags: number; smoothSec: number; trimGate: number; trimGapSec: number; trimMinSec: number; trim: boolean; body: boolean; bodyKernelSec: number; beatGrid: boolean; tieMargin: number; priorWeight: number; priorBars: number; minBars: number; path: boolean; pathGapSec: number; } function resolve(opts: DetectOptions): Resolved { const given = { ...tuning, ...defined(opts) }; const num = (value: number | undefined, fallback: number): number => typeof value === "number" && Number.isFinite(value) && value > 0 ? value : fallback; const between = (value: number | undefined, fallback: number): number => typeof value === "number" && value >= 0 && value <= 1 ? value : fallback; // Like `positive`, but letting zero through, for the one knob where zero is the interesting // setting — and it has to be the same rule as `chroma.ts`'s or the run that means "no blur" gets // answered with a quarter second of it, on both sides of the boundary between the modules. const allowed = (value: number | undefined, fallback: number): number => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : fallback; return { // The chroma half's defaults live in `chroma.ts`, which is where they are argued; these // exist only so the resolved shape this module logs is total, and they must agree with it. loHz: num(given.loHz, 55), hiHz: num(given.hiHz, 4000), frameSec: num(given.frameSec, 0.093), hopSec: num(given.hopSec, num(given.frameSec, 0.093) / 2), cut: between(given.cut, 0.05), soft: given.soft !== false, typical: given.typical !== false, // Same rule as `chroma.ts`, and it has to be the same rule: the page resolves these to hand them // to the worker, and a gate that one side reads as zero and the other as 0.5 is a run whose // report describes a different experiment from the one that ran. presence: typeof given.presence === "number" && given.presence > 0 && given.presence <= 1 ? given.presence : 0, a440: num(given.a440, 440), minPeriodSec: num(given.minPeriodSec, MIN_PERIOD_SEC), maxPeriodSec: num(given.maxPeriodSec, MAX_PERIOD_SEC), floor: typeof given.floor === "number" && Number.isFinite(given.floor) ? given.floor : FLOOR, tailQuantile: typeof given.tailQuantile === "number" && given.tailQuantile >= 0 && given.tailQuantile <= 1 ? given.tailQuantile : TAIL_QUANTILE, tailLags: num(given.tailLags, TAIL_LAGS), smoothSec: allowed(given.smoothSec, SMOOTH_SEC), trimGate: between(given.trimGate, TRIM_GATE), trimGapSec: num(given.trimGapSec, TRIM_GAP_SEC), trimMinSec: num(given.trimMinSec, TRIM_MIN_SEC), // On unless told otherwise: the grid is the better clock where it exists, and the fallback // underneath it means an opt-out is the only decision a listener has to be able to make. beatGrid: given.beatGrid !== false, trim: given.trim !== false, body: given.body !== false, bodyKernelSec: num(given.bodyKernelSec, BODY_KERNEL_SEC), tieMargin: between(given.tieMargin, TIE_MARGIN), priorWeight: between(given.priorWeight, PRIOR_WEIGHT), priorBars: num(given.priorBars, PRIOR_BARS), minBars: num(given.minBars, MIN_BARS), path: given.path === true, pathGapSec: num(given.pathGapSec, PATH_GAP_SEC), }; } /** * Samples in, the twelve-number view of them out. The cheap half and the half that runs on the * main thread: it needs the samples and the transform, and nothing else. See `chroma.ts` for * what it costs and what it decides. */ export function fingerprint( samples: Float32Array, sampleRate: number, opts: DetectOptions = {}, ): ChromaSeries { return chroma(samples, sampleRate, opts); } /** * The channels, summed — the app plays stereo and taking one channel loses a melody panned to * the other one. Averaging rather than maxing: a melody panned hard left is still a melody, and * maxing would double-count anything the two mics disagree about. */ export function mixDown(channels: readonly Float32Array[]): Float32Array { const first = channels[0]; if (!first) return new Float32Array(0); if (channels.length === 1) return first; const out = new Float32Array(first.length); for (const channel of channels) { const n = Math.min(out.length, channel.length); for (let i = 0; i < n; i++) out[i] = (out[i] ?? 0) + channel[i]! / channels.length; } return out; } /* ------------------------------------------------------------------------- */ /* The measurement: one time-lag column at a time */ /* ------------------------------------------------------------------------- */ /** * Whether a frame said anything. The fingerprint zeroes a masked frame's row, and only the * fingerprint does that, so a zero row is the record of "this frame was below the loudness * mask" — which the comparison has to be able to tell apart from a frame whose energy happened * to cancel in the fold. */ function silent(values: Float32Array, f: number, width: number): boolean { const at = f * width; for (let c = 0; c < width; c++) if (values[at + c] !== 0) return false; return true; } /** * The similarity of every frame to the frame one period away, in one pass: the column of the * time-lag matrix at that lag. * * Both frames silent answers *agreement*, not zero. A rest in the melody sits at the same place * in both copies of a loop, and a comparison that scored two silences as disagreement would cut * every loop at its first rest and call the result precision — which is the same error the old * code's `agreementRun` documented and handled, and the reason the two frames' silence has to * be tested before the dot product rather than left to it. (Two zero rows dot to zero, which is * maximal disagreement, at exactly the moment the track is saying the same thing twice.) * * One frame silent and the other not *is* disagreement — a note where the other copy rests is * the copies differing, and it is counted. */ /** * The seam: how much of the transition survives the cut. * * `window` rows after the start are compared, row against row, with the same `lag` rows after the end: * the loop will play the former where the record has the latter, and every row of disagreement is a row * the listener hears replaced. One bar on the beat grid (Shi and Mysore use four beats, which is not a * coincidence of taste — a seam is a local phenomenon and a window longer than a bar starts averaging * over the thing it is measuring); half a second on the frame grid, which is the nearest equivalent * when no bar is known. * * The weights are theirs — chroma 1.0, RMS 0.2 — and the MFCC term at 0.6 is deliberately missing: * it would need a second feature path through the worker for a measurement whose contribution to their * own results was smaller than the energy term's, and shipping an approximation of a feature is worse * than shipping its absence with a comment saying so. */ function seam( values: Float32Array, frames: number, start: number, lag: number, window: number, energy: Float32Array | undefined, width: number, ): number | undefined { const at = (row: number): boolean => row >= 0 && row < frames; let cos = 0; let n = 0; for (let k = 0; k < window; k++) { const a = start + k; const c = start + lag + k; if (!at(a) || !at(c)) break; cos += rowDot(values, a * width, values, c * width, width); n++; } if (n === 0) return undefined; // nothing follows the loop: there is no seam to have let score = (cos / n) * SEAM_CHROMA; let weight = SEAM_CHROMA; if (energy && energy.length >= frames) { let a = 0; let c = 0; for (let k = 0; k < n; k++) { a += energy[start + k] ?? 0; c += energy[start + lag + k] ?? 0; } a /= n; c /= n; const louder = Math.max(a, c); // A ratio, not a difference: what is audible at the wrap is the step the loop introduces, and a // step down from a chorus to a quiet bar is the same size to an ear as a step up by the same // ratio — which a difference in arbitrary units would have said was not. const step = louder > 0 ? 1 - Math.min(a, c) / louder : 0; score += (1 - step) * SEAM_ENERGY; weight += SEAM_ENERGY; } return score / weight; } /** * Where the end of the loop actually belongs. * * The trim answers how long the agreement holds. This answers a different question, and the one * that decides whether a loop clicks: the region repeats perfectly and the seam still lands a row * or two the wrong side of the transient, because the copy drifted by a hair over four minutes and * the period is a mean. Nudge the end by up to `span` rows and score each candidate position with * the seam itself — what follows the end against what follows the start — and move only if some * other position is clearly better than the one the search picked. * * Two things this deliberately cannot do. It cannot leave the grid, because the shift is a whole * number of rows and on a beat grid a row is a beat: an alignment that put the boundary between * beats would undo the entire reason the search runs on beats, however good it looked on the * metric. And it cannot move on a tie, because the margin is what keeps a measurement that is * indifferent from a measurement that was consulted: without it the end of every loop in the * library would slide to whichever side of the plateau the arithmetic happened to prefer. */ export function bestEndShift( values: Float32Array, frames: number, start: number, end: number, span: number, window: number, energy: Float32Array | undefined, earliest: number, width = 12, ): number { // `seam` takes the lag that puts the follower window where it belongs, so the candidate // position is converted back to one rather than handed over as a row. const score = (row: number): number => row > earliest && row < frames ? (seam(values, frames, start, row - start, window, energy, width) ?? -1) : -1; const here = score(end); if (here < 0) return 0; let best = 0; let bestScore = here; for (let d = -span; d <= span; d++) { if (d === 0) continue; const s = score(end + d); if (s > bestScore + ALIGN_MARGIN) { bestScore = s; best = d; } } return best; } /** * Exported for its tests, which is an admission rather than a design: the shift is only visible * when a follower window is offset from the copy, and anything that offsets it far enough to move * the boundary also damages the copy's own agreement by enough to prune the candidate that would * have shown it. Testing it through a candidate list would mean either weakening the fixture until * the aligner has nothing to say, or weakening the threshold until the search survives its own * fixture. So the function is handed its rows directly. */ /** How much better another position has to be before the end is moved to it. */ const ALIGN_MARGIN = 0.02; /** Shi and Mysore's weights, minus the term whose feature this module does not compute. */ const SEAM_CHROMA = 1.0; const SEAM_ENERGY = 0.2; function column( values: Float32Array, frames: number, lag: number, out: Float32Array, width: number, ): number { const n = frames - lag; let computed = 0; for (let t = 0; t < n; t++) { const a = t * width; const b = (t + lag) * width; const qa = silent(values, t, width); const qb = silent(values, t + lag, width); out[t] = qa && qb ? 1 : rowDot(values, a, values, b, width); computed++; } return computed; } /** * A trailing box average along the diagonal. See `SMOOTH_SEC`: one frame of a performed take * is not evidence and not a contradiction, and the smoothing is what makes the threshold below * about the music rather than about a transient. */ function smooth(col: Float32Array, n: number, out: Float32Array): Float32Array { if (n <= 1) return col; let acc = 0; for (let i = 0; i < col.length; i++) { acc += col[i] ?? 0; if (i >= n) acc -= col[i - n] ?? 0; out[i] = acc / Math.min(i + 1, n); } return out; } /** * The longest stretch over which the copies go on agreeing. * * This is the line segment — the object RefraiD searches for and the thing the region is cut * to — and it is computed from the same column as the score rather than from a second * measurement, which is why the trim and the score cannot disagree about what the track did. * * A run ends at the last frame that said something, not at the last shared silence: a body that * runs into two seconds of nothing is still an eight-second body. And `gap` frames of * disagreement do not end it, because the copies of a performed take differ in one frame here * and another there, and a run-detector that cut at the first of them turns every loop into its * first bar — which is the failure the trim has to be careful of in the other direction from the * one it exists to fix. */ function agreementRun( col: Float32Array, from: number, len: number, gate: number, gap: number, ): { start: number; len: number } { let bestStart = 0; let bestLen = 0; let start = -1; let lastGood = -1; let bad = 0; const close = () => { if (start >= 0) { const length = lastGood - start + 1; if (length > bestLen) { bestLen = length; bestStart = start; } } start = -1; bad = 0; }; for (let k = 0; k < len; k++) { if ((col[from + k] ?? 0) >= gate) { if (start < 0) start = k; lastGood = k; bad = 0; continue; } if (start < 0) continue; // disagreement before a run has begun is not a gap in it if (++bad >= gap) close(); } close(); return { start: bestStart, len: bestLen }; } /* ------------------------------------------------------------------------- */ /* The search */ /* ------------------------------------------------------------------------- */ /** What one lag came back with. */ interface Lag { lag: number; /** the best copy-vs-copy agreement at this lag, and where it was found */ score: number; start: number; /** the mean over the whole column, for the log: what this lag is worth *not* counting */ mean: number; /** * How far `score` stands above what this same lag scores at a typical position in this track, in * agreement units — the contrast. The number that separates "this region stands out" from "this * track resembles itself everywhere", which the absolute score cannot say on real material: the ten * tracks of `docs/research/calibrate-loops.md` scored 0.955–0.998 for their own typical lag, so a * score of 0.99 there is not evidence of anything and a score of 0.99 on a track whose background * is 0.80 is. */ contrast: number; /** how musically ordinary this period is, on 0..1 — see `metricPrior` */ prior: number; /** * `score` with the prior spent against it: what the ranking argues with, as opposed to what the * threshold argues with. The threshold reads `score` alone, deliberately — a prior is allowed to * arbitrate between answers and never to veto one. */ rank: number; } /** * Bins in… — rather: chroma in, every candidate out. The expensive half, which is why it lives * in a worker and why the message that reaches it is the ~250 KB chroma matrix rather than the * ~42 MB of samples. * * The whole time-lag surface is evaluated exactly — every lag, every position — for a cost * around a fifth of the old strided scan, because of one trick worth naming: the copy-vs-copy * score is a *mean over a window*, and the mean over any window of a column is two lookups into * that column's prefix sums. So a lag costs one pass to build the column and one cheap pass to * rank every position in it, and the stride that the old search needed (and which was the thing * that made it miss the composer's seam) is gone. The measured cost for a four-minute track is * ~200 ms of a worker core; the old one was 769 ms and looked at a fifth of the positions. */ /** * What the search is given: a matrix of twelve-wide rows, and the only thing it is allowed to know * about how rows become seconds. * * The search never wanted frames. It wanted rows that can be compared to themselves one lag later, * and frames were the only rows the feature extractor could offer — which is why the whole detector * inherited a 46 ms clock, quantised its boundaries to it, blurred the features to survive it, and * negotiated tolerances with the near-equal answers that quantisation produced. Handed rows that are * beats instead, the same algorithm measures the same thing on the axis the music is organised along, * and the clock it inherits is the one the drummer keeps. * * `times` is what makes the grid a *grid* rather than a resampling: on the beat grid the rows are not * evenly spaced, because the beats are where the audio says they are. Every conversion between rows * and seconds therefore goes through `secOf`/`rowOf` below, and no arithmetic by `frameSec` is * allowed anywhere else — a stray multiply by a constant is how a boundary ends up 45 ms early on * half the tracks and 45 ms late on the other half. */ export interface SearchSubject { readonly values: Float32Array; /** * Numbers per row. Twelve is pitch-class space, which is what every caller in the app has passed * since this feature existed; the field exists because the search never wanted twelve, it wanted * rows that can be compared to themselves one lag later, and a matrix whose rows come from a * learned embedding (or from chroma *concatenated with* a learned embedding) has whatever width * its source has. Absent means twelve. What must stay true for the comparison to mean anything is * not the width but the normalisation: an audible row is a unit vector, so the dot of two of them * is the cosine between them. */ readonly width?: number; /** rows of the matrix: frames on the frame grid, beats on the beat grid */ readonly frames: number; /** seconds per row, when the rows are evenly spaced */ readonly frameSec: number; /** seconds at which row i begins, when they are not — the beat grid */ readonly times?: Float32Array; /** rows per bar; 0 when the rows are not beats */ readonly rowsPerBar: number; /** * The tempo the rows were beat-pooled at, BPM. Present exactly when `grid` is `"beats"` — a * frame-grid subject has no tempo, and inventing one from a 46 ms hop is what the grid exists to * stop doing. Read by the bar's faded `120` beside the title as much as by the search: the * measurement is worth showing even on a track that contains no repeat. */ readonly bpm?: number; /** * The first beat, in seconds — the phase that the tempo alone cannot carry. * * Two tracks at the same BPM beat at different moments, and the difference is not academic to a * pulse: a beat counter that does not know where the grid started can sit a whole beat off and * sound broken while measuring perfectly. One float crosses for that; the rest of the grid stays * where it was, inside the search that needed it. */ readonly beatAt?: number; /** which row of the bar begins a bar, when there is a bar to begin */ readonly phase: number; /** how far the winning phase stood over its runner-up; a tie reports itself as a small number */ readonly barMargin: number; /** * Whether the bar alignment came from the harmony, from the drummer, or from neither. Carried all * the way to the log line because a phase chosen by a prior about kick drums should be visible as * such when somebody asks why the loop starts where it does. */ readonly phaseSource: "harmony" | "drums" | "model" | "none"; readonly audible: number; readonly weights: Float32Array; readonly grid: "frames" | "beats"; /** * Loudness per row, same length as the matrix, any units the caller likes as long as they are * consistent within a track. Optional because the detector works without it; the seam's second term * needs it, and a loop that wraps from a chorus into a quiet bar is a different claim from one that * does not. */ readonly energy?: Float32Array; } /** A frame-grid series, which is what every caller has passed since the detector existed. */ export function subjectOfFrames(series: ChromaSeries): SearchSubject { return { values: series.values, frames: series.frames, frameSec: series.frameSec, rowsPerBar: 0, phase: 0, barMargin: 0, phaseSource: "none", audible: series.audible, weights: series.weights, grid: "frames", energy: series.energy, }; } /** The audio the grid is derived from — handed alongside the fingerprint, never instead of it. */ export interface AudioForBeats { readonly samples: Float32Array; readonly sampleRate: number; /** * Beat and downbeat times in seconds from the neural tracker, when it had something to say. * * They arrive as data rather than as a knob because they *are* data — a measurement made * elsewhere, arriving on the same seam as the audio it measures — and the DP below stays the * answer for every track the model declines: absent, too short, or degenerate (a grid with no * plausible tempo is the model's way of saying "nothing", and being talked into a pulse by a * run of 250 ms "beats" is not what a fallback is for). */ readonly modelBeats?: Float32Array; readonly modelDownbeats?: Float32Array; } /** At least two bars of pulse before a grid is called a grid. */ const MIN_GRID_BEATS = 8; /** Whether handed-over model beats can serve as a clock: enough of them, in order, at a tempo. */ function beatsUsable(times: Float32Array | undefined): boolean { if (!times || times.length < MIN_GRID_BEATS) return false; let span = 0; for (let i = 1; i < times.length; i++) { const gap = times[i]! - times[i - 1]!; if (gap <= 0) return false; // not strictly increasing: not a clock span += gap; } const mean = span / (times.length - 1); return mean > 0.2 && mean < 1.5; // outside 40…300 BPM the grid means nothing } /** * The beat grid, expressed as something this search can be handed — or `null`, which is the track * saying it has no pulse worth arming on. * * The neural tracker answers first when it has; the dynamic program answers for every track it * has not, and both roads run through the same pooling and the same subject — the one promise is * that a boundary is a beat, a period is an integer, and a bar is countable, whoever found the * beat. The chromagram is pooled rather than recomputed either way: the fingerprint's frames are * the measurement the mask already approved, and reading the grid off them keeps the mask's * opinion about silence in the answer. */ export function beatSubject(series: ChromaSeries, audio: AudioForBeats): SearchSubject | null { if (!audio?.samples?.length || !(audio.sampleRate > 0)) return null; if (beatsUsable(audio.modelBeats)) { const fromModel = modelSubject(series, audio.modelBeats!, audio.modelDownbeats); if (fromModel) return fromModel; } return dpSubject(series, audio); } /** Middle of a sorted copy; the even case averages its two centrepieces. */ function medianOf(xs: number[]): number { if (!xs.length) return 0; const s = [...xs].sort((a, b) => a - b); const n = s.length; return n % 2 ? s[(n - 1) / 2]! : (s[n / 2 - 1]! + s[n / 2]!) / 2; } /** * The subject on times the neural tracker chose: same pooling, same bar arithmetic, different clock. */ function modelSubject( series: ChromaSeries, times: Float32Array, downbeats: Float32Array | undefined, ): SearchSubject | null { const pooled = poolToBeats(series, times); if (pooled.beats < MIN_GRID_BEATS) return null; const gaps: number[] = []; for (let i = 1; i < pooled.times.length; i++) gaps.push(pooled.times[i]! - pooled.times[i - 1]!); const mean = gaps.length ? gaps.reduce((a, b) => a + b, 0) / gaps.length : 0; // Two numbers from the same gaps, and they are deliberately different statistics. `frameSec` // is a *duration* — seconds of music per row, for spans — and the sum-preserving mean is // right for arithmetic. `bpm` is an *answer to "how fast is this?"*, and the mean answers it // wrong whenever the model missed a beat or two in a sparse passage: two dropped beats in a // three-minute 137 make the average say 131, every listener disagree, and nobody can see why. // The median is the tempo the grid actually keeps; the mean is its throughput. const mid = medianOf(gaps); if (!(mid > 0.2 && mid < 1.5)) return null; // The phase is read directly off the model's downbeat picks — a downbeat is what a phase *is*. // `barMargin` has no meaning here (the network reports a pick, not a contrast against the // runner-up), so it is set to the one value that says "this phase was measured, not tied": the // consumer that refuses to move on a tie should move on a measurement. let phase = 0; let source: "model" | "none" = "none"; if (downbeats?.length) { const d = downbeats[0]!; let best = 0; let bestDist = Infinity; for (let i = 0; i < pooled.times.length; i++) { const dist = Math.abs(pooled.times[i]! - d); if (dist < bestDist) { bestDist = dist; best = i; } } phase = best % 4; source = "model"; } let audible = 0; for (let b = 0; b < pooled.beats; b++) { for (let c = 0; c < 12; c++) { if ((pooled.values[b * 12 + c] ?? 0) !== 0) { audible++; break; } } } return { values: pooled.values, frames: pooled.beats, bpm: 60 / mid, beatAt: pooled.times[0] ?? times[0]!, frameSec: mean, times: pooled.times, rowsPerBar: 4, phase, barMargin: source === "model" ? 1 : 0, phaseSource: source, audible, weights: series.weights, grid: "beats", energy: series.energy ? poolEnergy(series.energy, series.frameSec, pooled.times) : undefined, }; } /** The subject on the dynamic program's own grid — the grid that needs no weights to answer. */ function dpSubject(series: ChromaSeries, audio: AudioForBeats): SearchSubject | null { const grid = beatGrid(audio.samples, audio.sampleRate); if (grid.beats.length < MIN_GRID_BEATS) return null; const pooled = poolToBeats(series, grid.beats); if (pooled.beats < MIN_GRID_BEATS) return null; // The downbeat is asked for and may legitimately come back undecided; `barMargin` carries that // answer either way rather than withholding it until it is convenient. // The drummer gets asked, but only gets to answer when the harmony abstains — see `barPhase`. const bar = barPhase(pooled, 4, { env: grid.onset.low, hopSec: grid.onset.hopSec, }); let audible = 0; for (let b = 0; b < pooled.beats; b++) { for (let c = 0; c < 12; c++) { if ((pooled.values[b * 12 + c] ?? 0) !== 0) { audible++; break; } } } return { values: pooled.values, frames: pooled.beats, bpm: grid.bpm, beatAt: grid.beats[0], // The mean beat, reported as the row length: anything needing a position goes through the table // of times, and this is only ever read as a duration. frameSec: grid.periodSec, times: pooled.times, rowsPerBar: 4, phase: bar.phase, barMargin: bar.margin, phaseSource: bar.source, audible, weights: series.weights, grid: "beats", energy: series.energy ? poolEnergy(series.energy, series.frameSec, pooled.times) : undefined, }; } /** * Search the track on whichever clock can be trusted, and say which one answered. * * The grid first, because it is the better clock when it exists: boundaries land on beats, periods are * integers, bars are countable, and the near-equal lags that needed a family heuristic to survive on * the frame grid are not expressible there. The frames second, because the grid can honestly refuse — * a track with no onsets, a tempo the dynamic program could not settle, or a periodicity so sharp that * the comparative threshold rose above the loop the listener can hear. That last case is why the * fallback is a policy rather than an assumption: on the record, the grid's own threshold climbed to * 0.9966, and a loop at 0.99 would be refused there and accepted here. Which clock failed is a * measurement problem; the listener pressed a key looking for a region. */ export function searchSeries( series: ChromaSeries, audio?: AudioForBeats, opts: DetectOptions = {}, label?: string, ): DetectResult { const o = resolve(opts); const subject = audio && o.beatGrid ? beatSubject(series, audio) : null; if (subject) { const onGrid = search(subject, opts, label); if (onGrid.candidates.length) return onGrid; // The frame fallback is the better answer and knows less: it ran on rows with no tempo in // them, and the track's tempo is not less true for having failed to carry a loop. The stats // object is fresh from `search`, so grafting is safe and the log line keeps telling the truth // about which clock scored the lags. const offGrid = search(series, opts, label); if (offGrid.stats) { if (subject.bpm) offGrid.stats.bpm = subject.bpm; if (subject.beatAt !== undefined) offGrid.stats.beatAt = subject.beatAt; } // The grid outlived its veto: a refused loop is still a track with a pulse, and the pulse the // bar shows is a measurement of the file, not a claim about repetition. if (!offGrid.beats) offGrid.beats = subject.times; return offGrid; } return search(series, opts, label); } export function search( input: SearchSubject | ChromaSeries, opts: DetectOptions = {}, label?: string, ): DetectResult { const o = resolve(opts); const series = "grid" in input ? input : subjectOfFrames(input); const values = series.values; const frames = series.frames; const times = series.times; // Twelve unless the matrix says otherwise: the search is about rows compared to rows, and the // width only ever enters as "how far to walk along a row for the dot product". const width = series.width && series.width > 0 ? series.width : 12; // The mean row length, used only where a *duration* is wanted rather than a position: a period is // a span of rows, and on a grid whose rows are beats the honest number is the average of this // track's own inter-beat intervals, not a constant anyone wrote down. const rowSec = times && frames > 1 ? (times[frames - 1]! - times[0]!) / (frames - 1) : series.frameSec; if ( !(frames > 0) || !(rowSec > 0) || !Number.isFinite(rowSec) || values.length < frames * width ) { return { candidates: [], not: "no-bytes" }; } // Rows to seconds, and seconds back to rows. Both directions are searches of the same table on the // beat grid, and the inverse is a binary search rather than a division because the rows really are // uneven: dividing by a mean beat would put a boundary at a place the grid has no row for, which is // the entire defect this refactor exists to remove. const secOf = (row: number): number => times ? (times[Math.max(0, Math.min(frames - 1, Math.round(row)))] ?? 0) : row * series.frameSec; const rowOf = (seconds: number): number => { if (!times) return Math.max(1, Math.round(seconds / series.frameSec)); let lo = 0; let hi = frames - 1; while (lo < hi) { const mid = (lo + hi) >> 1; if (times[mid]! < seconds) lo = mid + 1; else hi = mid; } // Nearest row, not the first row past it: a boundary belongs to whichever beat it is closer to, // and the off-by-one bias of a floor would push every trimmed edge a fraction of a beat late. const before = lo > 0 ? lo - 1 : 0; return Math.abs(times[before]! - seconds) <= Math.abs(times[lo]! - seconds) ? Math.max(1, before) : Math.max(1, lo); }; const from = rowOf(o.minPeriodSec); const to = Math.min(rowOf(o.maxPeriodSec), frames - from); const smoothN = rowOf(o.smoothSec); const gap = rowOf(o.trimGapSec); // The shortest run of rows that can carry a loop, in rows. // // This used to be `Math.max(MIN_AUDIBLE_FRAMES, ...)`, and MIN_AUDIBLE_FRAMES is a statement about // *frames* — enough of them for a correlation to mean something — which on a beat grid of 0.64 s // rows silently turned the four-second minimum into a ten-second one and dropped every candidate the // search had just found. A sixteen in the code that means "sixteen frames" has no business being the // floor of a quantity measured in beats; the minimum is a duration, so it is converted from one. const minRun = Math.max(2, rowOf(o.trimMinSec)); // The support the agreement has to sustain, in rows, per period. // // The two floors are combined differently, and the difference is the whole point. The seconds floor // is uncapped, because it has always been a statement about the period as well as the run: a // `trimMinSec` longer than a period means that period cannot be checked at all, and the search has // refused it since the first version — capping it here would quietly turn "too short to certify" into // "as good as it can get". The bar floor is capped at the period, because two bars of a one-bar loop // is not a demand, it is a contradiction: a one-bar figure is a legitimate loop and the most its own // copy can sustain is one bar. const barsFloor = series.rowsPerBar > 0 ? Math.max(0, Math.round(o.minBars * series.rowsPerBar)) : 0; const supportOf = (lag: number): number => Math.max(minRun, Math.min(barsFloor, lag)); // How far apart two agreeing stretches may be and still count as one run, in rows, in path mode. const pathGap = Math.max(1, rowOf(o.pathGapSec)); const scratch = pathScratch(frames); const pathRows = new Int32Array(frames); // Counts of "what this lag scores at a random place in this track", per lag. See `CONTRAST_SCALE`. const hist = new Int32Array(CONTRAST_BINS); let bestContrast = 0; // What this listener's own accepts have said the contrast term is worth. Read once per search, so one // list is ordered by one weight rather than by whatever the storage happened to say mid-sort; 0 until // enough choices have been logged to have an opinion, which is the same as this feature not existing. const learned = rankerState().weight; const thin = (why: string): DetectResult => { const stats: SearchStats = { frames, audible: series.audible, periodFrom: from, periodTo: to, lags: 0, cells: 0, best: NO_MATCH, tail: 0, tailQuantile: o.tailQuantile, tailLags: o.tailLags, tau: 0, cleared: 0, weightSpread: spread(series.weights), weights: Array.from(series.weights), presence: presenceOf(values, frames, width), floor: o.floor, trim: o.trim, trimGate: o.trimGate, trimGapSec: o.trimGapSec, trimMinSec: o.trimMinSec, priorWeight: o.priorWeight, priorBars: o.priorBars, minBars: o.minBars, path: o.path, bestContrast: 0, trimmed: 0, barMoved: 0, body: o.body, bodyFrom: 0, bodyTo: frames, smoothSec: o.smoothSec, frameSec: rowSec, grid: series.grid, bpm: series.bpm, beatAt: series.beatAt, rowsPerBar: series.rowsPerBar, barMargin: series.barMargin, }; traceDetect(`refused: no-repeat (${why})`, label, undefined, () => ({ ...stats })); return { candidates: [], not: "no-repeat", stats }; }; // No evidence, as opposed to evidence of nothing: silence, a track the mask swallowed, or a // track whose chroma never changes. The numbers go back with the refusal because this is the // branch a listener's "but it clearly loops" lands in most often, and `audible` against // `frames` is the one reading that says whether the mask ate the track or the track is quiet. if ( series.audible < MIN_AUDIBLE_FRAMES || series.audible / frames < MIN_AUDIBLE_RATIO || variation(values, frames, width) < MIN_VARIATION ) { const why = series.audible < MIN_AUDIBLE_FRAMES ? "nothing audible" : series.audible / frames < MIN_AUDIBLE_RATIO ? "too little survived the mask" : "the chroma never changes: one chord, no pitch to compare"; return thin(why); } const region = o.body ? bodyRegion(values, frames, rowSec, o, width) : { from: 0, to: frames - 1, all: true }; const col = new Float32Array(frames); const smoothed = new Float32Array(frames); const prefix = new Float64Array(frames + 1); const lags: Lag[] = []; let cells = 0; for (let lag = from; lag <= to; lag++) { const n = frames - lag; if (n < lag) break; // no room for a second copy of even this lag, and none for any longer one cells += column(values, frames, lag, col, width); const s = smoothN > 1 ? smooth(col, smoothN, smoothed) : col; prefix[0] = 0; for (let i = 0; i < n; i++) prefix[i + 1] = (prefix[i] ?? 0) + (s[i] ?? 0); const mean = (i: number, len: number): number => ((prefix[i + len] ?? 0) - (prefix[i] ?? 0)) / len; // The copies being compared are [i, i+lag) and [i+lag, i+2lag): the whole region against the // whole thing that is supposed to be it, which is why the window is `lag` and not a constant. const last = n - lag; let score = -2; let start = -1; let sum = 0; let counted = 0; hist.fill(0); for (let i = 0; i <= last; i++) { const v = mean(i, lag); if (v > score) { score = v; start = i; } sum += v; counted++; hist[Math.min(CONTRAST_BINS - 1, Math.max(0, Math.floor(v * CONTRAST_BINS)))]++; } if (start < 0 || !counted) continue; const contrast = score - histMedian(hist, counted); if (contrast > bestContrast) bestContrast = contrast; // In path mode the score is the best *sustained* agreement rather than the flattest window, and // the window machinery above still runs: it is what the histogram is built from, and the contrast // is a statement about positions, which the path does not measure. if (o.path) { const set = pathScan(s, n, o.trimGate, PATH_GAP_COST, pathGap, supportOf(lag), scratch); const at = bestEnd(set); if (at < 0) continue; // nothing this lag does for long enough to be a loop const run = pathAt(s, set, at, lag, pathRows); // Reported on the same ruler as the window mean — the mean over the rows of the region, bridged // ones included — because the two modes have to be comparable in the calibration report or the // experiment cannot be run. What the path did with the bad rows is `coverage`, not the score. score = mean(run.start, run.span); start = run.start; } const prior = metricPrior(lag, series.rowsPerBar, o); lags.push({ lag, score, start, mean: sum / counted, contrast, prior, rank: score - o.priorWeight * (1 - prior), }); } if (!lags.length) { traceDetect("refused: no-repeat (no lag had room for two copies)", label, undefined, () => ({ frames, audible: series.audible, periodFrom: from, periodTo: to, })); return { candidates: [], not: "no-repeat" }; } // The file's own idea of what its best lags are like, and the threshold built from it. The // quantile rather than the median because the two hard fixtures have no spread to rise above // (see `TAIL_QUANTILE`), and the floor as well because a file with nothing in it has a low // quantile of its own and a peak that is its own best anyway. const scores = lags.map((l) => l.score).sort((a, b) => a - b); // The quantile, floored by a count — see `TAIL_LAGS`. `tailQuantile` keeps reporting what was asked // for and this is what was spent, which on a short file or a coarse grid are not the same rule. const quantile = Math.max(0, Math.min(o.tailQuantile, 1 - (o.tailLags + 1) / scores.length)); const tail = scores[Math.min(scores.length - 1, Math.floor(quantile * scores.length))] ?? 0; const best = scores[scores.length - 1] ?? NO_MATCH; const tau = Math.max(o.floor, tail); const survivors = lags.filter((l) => l.score >= tau); // Which of the survivors are the same loop counted at a multiple of its own period. On a body // that repeats, lag 24 s, 48 s and 72 s all score the same — the second and third are the same // seam compared two and three times over — and only 24 s is the loop the listener means. The // shortest survives; the longer ones survive only if they are better by more than the // indifference, which on genuinely periodic material they are not. // Which of the survivors are the same claim about the track, counted twice: the near-equal grid // neighbours of one period, the multiples of a periodic body, and the sub-multiples its halves // throw. One representative survives per family. // // Descending rank, and quantised at exactly what the prior is worth (`PRIOR_WEIGHT`, one bin of // this) so it can only separate lags it is entitled to separate. Quantised rather than exact because // a family is decided between claims that are the *same* claim, where a period and its own multiple // score identically: on an exact tie the shorter is the loop and the longer is that loop taken twice // round, and letting the length prior invent a two-thousandths difference between two identical // scores — which it does, an eight-bar prior prefers six bars to four — would pick the family's // keeper by an arithmetic accident. What the prior decides is the order between *different* claims // about the track, which is the final sort's job, at a finer bin. // // The one exception is the true fundamental, which wins over its own multiple when the two are // within indifference of each other — 24 seconds is the loop and 48 is that loop twice round, // and a two-hundredth-of-a-score advantage does not make 48 the better answer. survivors.sort((a, b) => Math.round(b.rank * 50) - Math.round(a.rank * 50) || a.lag - b.lag); const kept: Lag[] = []; for (const l of survivors) { const at = kept.findIndex((k) => oneFamily(l.lag, k.lag)); if (at < 0) { kept.push(l); continue; } const k = kept[at]!; // Is `l` the fundamental of `k` — an exact division of it? If a lag clears the bar on its own, // its multiples are not competing answers, they are that answer taken twice round, and the // fundamental wins whatever the two scores say: the indifference margin is there for lags that // merely resemble each other, not for a number and its own doubled self. const times = k.lag / l.lag; const fundamental = l.lag < k.lag && times >= 2 && Math.abs(times - Math.round(times)) <= FAMILY_TOLERANCE * Math.round(times); if (fundamental) kept[at] = l; } const candidates: Candidate[] = []; const inBody: boolean[] = []; let trimmed = 0; let onBarShifted = 0; for (const l of kept) { // The column again, for the geometry only — the score above is the evidence and is not // recomputed here, because a region whose bounds were chosen by the flattering part of the // comparison is how this feature came to be wrong the last several times somebody adjusted a // number in it. column(values, frames, l.lag, col, width); const s = smoothN > 1 ? smooth(col, smoothN, smoothed) : col; const prefixOf = new Float64Array(frames + 1); for (let i = 0; i < frames - l.lag; i++) prefixOf[i + 1] = (prefixOf[i] ?? 0) + (s[i] ?? 0); const mean = (i: number, len: number): number => ((prefixOf[i + len] ?? 0) - (prefixOf[i] ?? 0)) / len; // Every place this loop holds, not one of them. // // This is the part the first version of the rewrite got wrong in a way that only shows up on // a track that is genuinely a repeating beat: the family collapse leaves one lag standing, and // then the search quoted a single position for it — the earliest within a tie of the best, // which on such a track is the top of the song — and the listener sitting at two minutes heard // "the loop is at 0:02". That is not what a loop detector is for. A beat that repeats for // three minutes contains three minutes of loopable regions, and the ones in the middle are as // true as the one at the start; collapsing them was throwing away the answer and keeping its // signature. // // Positions are taken greedily and are not allowed to overlap (each is at least a period from // the last), so the list walks the song rather than quoting the same bar twice, and each // carries its own score rather than the family's, so the best region is offered first and `c` // walks the rest of the track from there. const positions: { start: number; score: number; end: number; coverage?: number }[] = []; if (o.path) { // The places this loop holds are the runs the path found, not windows the mean likes: each is a // stretch that sustained itself, with the bridged rows already paid for. Successive runs are // taken from where the last one stopped, which is the path mode's reading of the rule window mode // states as "positions at least a period apart" — and it is the rule that keeps a beat that // repeats for three minutes offering three minutes of loops rather than one of them. const n = frames - l.lag; let cursor = 0; while (positions.length < MAX_POSITIONS && cursor < n) { const tail = s.subarray(cursor); const set = pathScan( tail, n - cursor, o.trimGate, PATH_GAP_COST, pathGap, supportOf(l.lag), scratch, ); const at = bestEnd(set); if (at < 0) break; // nothing left of this lag sustains itself const run = pathAt(tail, set, at, l.lag, pathRows); const first = cursor + run.start; const last = first + run.span - 1; positions.push({ start: first, score: mean(first, run.span), end: last, coverage: run.count / run.span, }); // Past the region just taken. A run of its own period is the widest claim this period can make // about this part of the track, and the next one has to start beyond it. cursor = last + 1; } } else { for (let i = 0; i <= frames - 2 * l.lag && positions.length < MAX_POSITIONS; i++) { const v = mean(i, l.lag); if (v < l.score - o.tieMargin) continue; if (positions.length && i - positions[positions.length - 1]!.start < l.lag) continue; positions.push({ start: i, score: v, end: i + l.lag - 1 }); i += l.lag - 1; // the next position that does not overlap this one } } if (!positions.length) positions.push({ start: l.start, score: l.score, end: l.start + l.lag - 1 }); // Where the region this lag armed last finished. Positions ascend, so the region already armed is // the only earlier neighbour a later one can reach into once the trim and the seam alignment have // moved its edges, and the run it belongs to is the only thing it may move with. See // `groupBarOffset`. let lastArmedEnd = -Infinity; for (let pi = 0; pi < positions.length; pi++) { const p = positions[pi]!; const start = p.start; // The rows are the answer and the seconds are a rendering of it, so the trim moves the rows and // the rendering is derived once at the end. Deriving the seconds first and adjusting them in // place is how a boundary drifts: the frame grid at least has the excuse that multiplying by a // constant is exact, and the beat grid does not. let rowStart = start; let rowEnd = start + l.lag; let coverage = p.coverage; if (o.path) { // The path *is* the trim: the region is cut to the stretch that sustained itself, which is the // same measurement rather than a second one that can disagree with the first. rowStart = p.start; rowEnd = p.end + 1; trimmed++; } else if (o.trim) { const run = agreementRun(s, start, l.lag, o.trimGate, gap); // The minimum is a gate, not only a threshold for shrinking: a candidate whose copies go on // agreeing for less than the shortest span worth arming is not a loop that is merely small, // it is a coincidence with a few frames of agreement in it. Keeping the whole period in // that case — which the first version did — armed a region the measurement had just said // did not hold together. const need = supportOf(l.lag); if (run.len > 0 && run.len < need) continue; if (run.len >= need) { rowStart = start + run.start; rowEnd = rowStart + run.len; coverage = 1; // the window run bridges nothing: every row in it passed the gate trimmed++; } } // An intro that never comes back and a tail that never came in are not the loop, and the // body's bounds are where the candidates that are standing outside it get demoted. // // Demoted, not deleted. The first version of this vetoed: a candidate whose middle fell // outside the body was discarded, and on the fixture whose body starts at 20 s the novelty // curve's strongest head peak sits at 40 s — inside the body, because a checkerboard reads a // periodic body's own structure as a boundary — which threw away the only correct answer the // search had found. A prior that can outvote the measurement is not a prior, it is a second // measurement, and a weaker one: the correlation looked at the candidate and the novelty // curve looked at a half-second profile of it. So the body decides the *order*, and gets to // remove out-of-body candidates only when an in-body one exists to offer instead. inBody.push( !o.body || region.all ? true : secOf(start + l.lag / 2) >= secOf(region.from) && secOf(start + l.lag / 2) <= secOf(region.to), ); // The position's own agreement, not the family's: what `c` is being pressed to rank is this // region, and three minutes of a repeating beat has places where it lines up better than // others — which is the listener's cue for where the seam actually is. let startSec = 0; // both boundaries are set below, once the end is aligned and the bar has had its turn let endSec = 0; // Measured at the position the search actually chose, before the trim moved the edges: the seam // is about what the loop destroys at the wrap, and the trim answers a different question about // how long the agreement holds. const seamWindow = series.rowsPerBar > 0 ? series.rowsPerBar : Math.max(1, rowOf(0.5)); // Half a bar on the grid, a tenth of a second on the frames: enough to cross the transient // the copy drifted past, not enough to reach the neighbouring beat and call it an alignment. const span = Math.max(1, Math.floor(seamWindow / 2)); let rowEndAligned = rowEnd + bestEndShift( values, frames, start, rowEnd, span, seamWindow, series.energy, rowStart + Math.max(2, Math.floor(l.lag / 2)), width, ); // The bar last, because it is the only step here that is allowed to move a boundary the // measurement already chose, and it is entitled to do that only over what is left after the // seam alignment has taken everything it can see. Both edges move together, so the length the // aligner just settled on is untouched. // // Two rules, and each covers the other's blind spot. A family that stands uniformly on the bar // slides as a family, which is free — a common translation moves no region onto another, and the // tiling of a repeating body has no slack in it for anything else. Everything else slides alone, // into the room its neighbours left: the region this lag armed before it, and the next position // the walk took. A family whose residues differ is a family whose positions are *not* packed a // period apart — the walk skipped ahead where the agreement dipped, and that gap is exactly the // slack a single region may use — so the two cases do not overlap. // The bar last, because it is the only step here that is allowed to move a boundary the // measurement already chose, and it is entitled to do that only over what is left after the // seam alignment has taken everything it can see. Both edges move together, so the length the // aligner just settled on is untouched, and the whole rigid run of the family moves by the same // amount, so nothing is put on top of anything else — see `groupBarOffset`. let shift = groupBarOffset(series, mean, positions, pi, l.lag, frames, o.tieMargin); // The run is bounded by the *positions*, which is what the walk guaranteed; this checks the // geometry that actually survived the trim and the seam alignment, which can leave less room // than the positions had. Where there is not enough, the region keeps the boundary the search // chose for it. if (shift && rowStart + shift < lastArmedEnd) shift = 0; if (shift) { rowStart += shift; rowEndAligned += shift; onBarShifted++; } lastArmedEnd = rowEndAligned; startSec = secOf(rowStart); endSec = secOf(rowEndAligned); // Scored at the end the search *found*, not the one this function is about to hand over. The // alignment maximises exactly the quantity the ranking reads, so measuring after repairing would // quietly award every candidate in the library a perfect seam and throw away the only thing that // separates four positions of one family: the repair is what the listener gets, the measurement // is what they are offered in an order, and the two have to be made of different rows or the // order says nothing. const s0 = seam(values, frames, start, rowEnd - start, seamWindow, series.energy, width); const w0 = wrap(values, frames, rowStart, rowEndAligned, width); const contrast = Math.max(0, Math.min(1, l.contrast / CONTRAST_SCALE)); const bars = series.rowsPerBar > 0 ? l.lag / series.rowsPerBar : undefined; candidates.push({ start: startSec, end: endSec, period: l.lag * rowSec, r: p.score, rank: p.score - o.priorWeight * (1 - l.prior) + learned * contrast, contrast, prior: l.prior, coverage, bars, // Downbeat on both ends, measured on the rows this region is actually armed at — after the // trim, after the seam alignment, and after the bar's own correction. A candidate that // repeated perfectly but whose seam falls in the middle of a bar is a different claim from one // that did not, and the difference is the one a listener hears as the loop being "on the beat". // Absent rather than false when there was no bar to measure it against: see `barKnown`. onBar: barKnown(series) ? isDownbeat(rowStart, series) && isDownbeat(rowEndAligned, series) : undefined, seam: s0, wrap: w0, }); } } // The body's veto, if it has one: keep the outside only when there is nothing else. if (o.body && !region.all && inBody.includes(true)) { // …and "nothing else" now means what it says. The veto used to delete every out-of-body // candidate the moment one in-body candidate existed, which on a track whose whole middle is // one repeating figure removed three of the four positions of the loop and left the listener // with the one the novelty curve happened to favour. That is the same error the comment above // this block was written to record, one level up: the body is a prior, and a prior is allowed to // arbitrate between answers the measurement can separate. Between answers the measurement cannot // separate — same loop, same agreement, four bars apart — deleting one because a 24-second // window sat nearer a peak is a prior outvoting a measurement it was never entitled to argue // with. Those siblings stay, ordered after the one the body prefers, which is where a prior that // is merely unsure belongs. let bestInBody = -Infinity; for (let i = 0; i < candidates.length; i++) { if (inBody[i] && candidates[i]!.r > bestInBody) bestInBody = candidates[i]!.r; } for (let i = candidates.length - 1; i >= 0; i--) { if (!inBody[i]) { if (candidates[i]!.r > bestInBody - o.tieMargin) continue; candidates.splice(i, 1); inBody.splice(i, 1); } } } const stats: SearchStats = { frames, audible: series.audible, periodFrom: from, periodTo: to, lags: lags.length, cells, best, tail, tailQuantile: o.tailQuantile, tailLags: o.tailLags, tau, cleared: survivors.length, weightSpread: spread(series.weights), weights: Array.from(series.weights), presence: presenceOf(values, frames, width), floor: o.floor, trim: o.trim, trimGate: o.trimGate, trimGapSec: o.trimGapSec, trimMinSec: o.trimMinSec, priorWeight: o.priorWeight, priorBars: o.priorBars, minBars: o.minBars, path: o.path, bestContrast, trimmed, barMoved: onBarShifted, body: o.body, bodyFrom: region.from, bodyTo: region.to, smoothSec: o.smoothSec, frameSec: rowSec, grid: series.grid, bpm: series.bpm, beatAt: series.beatAt, rowsPerBar: series.rowsPerBar, barMargin: series.barMargin, }; if (!candidates.length) { // Two refusals, and the line between them is the useful part: nothing ever reached the // absolute floor (`no-repeat`: this track does not contain a copy of anything), or something // did but it was no better than the rest of itself (`not-convincing`). const why = best < o.floor ? "no-repeat" : "not-convincing"; report(label, why, stats, []); return { candidates: [], not: why, best: best === NO_MATCH ? undefined : best, stats, beats: series.times, }; } // Strongest evidence first, shortest as the tie-break. Length used to be the primary key, // because the harmonic duplicates a periodic body invites all score the same and only length // can tell the loop from two loops — but those are collapsed away before this point now, and // what remains is a choice between different claims about the track, which is made on the // measurement. The performed fixture is the case this ordering is for: a 13-second lag at 0.960 // and the real twenty-four-second answer at 0.994, and `c` should hand over the 0.994 first. // Strongest evidence first, shortest as the tie-break. Length used to be the primary key, // because the harmonic duplicates a periodic body invites all score the same and only length // can tell the loop from two loops — but those are collapsed away before this point now, and // what remains is a choice between different claims about the track, which is made on the // measurement. The performed fixture is the case this ordering is for: a 13-second lag at 0.960 // and the real twenty-four-second answer at 0.994, and `c` should hand over the 0.994 first. // Strongest first, and then — within a bin of agreement too fine for an ear to resolve, a // fiftieth of the 0.02 the tie margin already grants — the region whose seam lands on a downbeat. // The agreement is quantised before the bar preference is consulted rather than compared exactly, // because exact equality of a float mean almost never happens and a tie-break that never fires is // decoration. What the ordering says is: the measurement decides, and where the measurement cannot // tell two regions apart, the drummer does. candidates.sort( (a, b) => Math.round((b.rank ?? b.r) * 200) - Math.round((a.rank ?? a.r) * 200) || // Then how far the claim stands above the track's own background, in bins of a twenty-fifth of // `CONTRAST_SCALE`. It is a per-period number, so what it separates is families rather than // positions: on the real tracks, where a typical lag scores 0.955–0.998, agreement alone has // almost no resolving power left, and "this one stands out from the rest of this file" is the // only reading of 0.99 that means anything. Math.round((b.contrast ?? 0) * 40) - Math.round((a.contrast ?? 0) * 40) || // Then the seam, in bins of a fiftieth: does the loop survive its own cut. An unmeasured seam // sits at the middle rather than at the bottom, because "there was nothing after the loop" is // not evidence against the candidate, and ranking it below a measured 0.2 would be ranking it // below a candidate that was measured and found wanting. Math.round((b.seam ?? 0.5) * 50) - Math.round((a.seam ?? 0.5) * 50) || // ...and the other seam measurement, which is not the same question: whether the arrival is // surprising, as opposed to whether it destroys the record's continuation. Both are given a // turn because they disagree on precisely the candidates where the disagreement is audible. Math.round((b.wrap ?? 0.5) * 50) - Math.round((a.wrap ?? 0.5) * 50) || Number(barRank(b.onBar)) - Number(barRank(a.onBar)) || a.period - b.period || a.start - b.start, ); // The pool the spread chooses from, deliberately wider than the list it chooses: truncating to the // cap first would mean the eight best regions of the intro were chosen before anybody asked where // they were, which is the behaviour being replaced. if (candidates.length > CANDIDATE_POOL) candidates.length = CANDIDATE_POOL; // ...and then spread out. The ten real tracks this detector has been watched over all offered // the same sight: `periods=15.31s@0.0, @15.3, @30.6, @45.9` — one family's four positions, in the // first twenty seconds of a four-minute track, and nothing at all for the remaining three minutes // of it. That is the right answer to a question nobody asked. `c` is a key for *finding the loop in // this part of the song*, so what a track owes the listener is a candidate near where they are // standing, and a list that all lives in the intro cannot be that however well it scores. // // So: keep the strongest two candidates of each sixth of the file, and if that comes to fewer than // the cap, backfill from the rest in score order — which is the old behaviour, arriving late enough // to matter only on the tracks that genuinely have one thing going on. Six is not a measurement; // it is the number of places a hand reaching for `c` can be standing in a song, and two per place // is the pair the key is for: the loop, and the alternative someone might want to compare it with. const offered = acrossTrack(candidates, series.frames * series.frameSec); report(label, "ok", stats, offered); return { candidates: offered, best: best === NO_MATCH ? undefined : best, stats, beats: series.times, }; } /** * How many places in a song a listener can be standing, for the purposes of offering them a loop — * and of carrying them between the loops one place at a time, which is the same partition seen from * the other end (`PlayerStore.stepPlace`). It is one number for both, because a list chosen two per * sixth and keys that walk sixths disagreeing about the size of a sixth is two features each half * working, in the specific way that feels like bad luck rather than bad code. */ export const LOOP_PLACES = 6; /** * The candidates worth showing, chosen so that the parts of the track a listener might be standing * in are each represented, in the order the chip shows them (strongest first). * * `candidates` arrives already ranked by measurement; this does not re-rank anything, it decides who * is allowed through the cap, which is a different question and was being answered by the wrong one. * A region counts as belonging to the sixth its `start` falls in — because `start` is where the key * puts you — and the backfill pass is what keeps a track with one genuine loop from being punished * for it: two per sixth is a ceiling on crowding, never a reason to show fewer than there is room for. */ function acrossTrack(ranked: Candidate[], seconds: number): Candidate[] { if (!(seconds > 0) || ranked.length <= MAX_CANDIDATES) return ranked; const sixth = seconds / LOOP_PLACES; const place = (c: Candidate) => Math.min(LOOP_PLACES - 1, Math.max(0, Math.floor(c.start / sixth))); const perPlace = new Array(LOOP_PLACES).fill(0); const taken: Candidate[] = []; for (const c of ranked) { if (taken.length >= MAX_CANDIDATES) break; const at = place(c); if ((perPlace[at] ?? 0) >= PER_PLACE) continue; perPlace[at] = (perPlace[at] ?? 0) + 1; taken.push(c); } if (taken.length < MAX_CANDIDATES) { const inList = new Set(taken); for (const c of ranked) { if (taken.length >= MAX_CANDIDATES) break; if (inList.has(c)) continue; inList.add(c); taken.push(c); } } return taken; } /** * The bar preference as a sort key, with the third state kept out of the bottom drawer. * * `onBar` is now three-valued, and a sort that reads `undefined` as `false` would rank "this search * had no bar to align to" below "the seam lands in the middle of a bar" — a candidate for having never * been measured ranking beneath a candidate that was measured and found wanting. That is precisely the * error the `seam` key two lines above refuses to make, and refuses for the same reason: an unmeasured * field is not evidence against the candidate. So the unknown sits in the middle: it beats nothing, is * beaten by nothing, and cannot be traded against a region the bar was actually read off. * * Exported for its tests, in the same spirit as `bestEndShift`: the three states it exists to keep * apart are invisible from a candidate list, because one search runs on one subject and so gives every * candidate the same one. */ export const barRank = (onBar: boolean | undefined): number => onBar === undefined ? 0.5 : onBar ? 1 : 0; /** Whether this row of a beat grid begins a bar, phase included. */ function isDownbeat(row: number, series: SearchSubject): boolean { return series.rowsPerBar > 0 && barResidue(row, series) === 0; } /** * Whether this subject knows where beat one is, and so whether a row may be called a downbeat at all. * * `phase` always carries a number — a row has to begin a bar somehow for the arithmetic to run — and * the number being present is not the same as the phase having been measured. `barPhase` says so in * its own `source`: `none` means the harmonic discontinuities and the drum cue both failed to clear * the indifference threshold, and its doc tells the caller to "treat the phase as a coin". The model * path is `none` when the tracker reported beats but no downbeats. In both cases `phase` is whatever * row the grid happened to start on, and the two uses of it — the flag on a candidate and the choice * of where to arm a loop — have to abstain together rather than answer from the coin. * * A frame grid is the third abstention and the oldest: there is no bar in rows that are 46 ms apart, * and `bars` has said so by being absent since the day it was written. `onBar` was the one field that * did not, and answered `false` — which reads as "off the beat" — for every candidate the frame grid * ever returned. */ function barKnown(series: SearchSubject): boolean { return series.rowsPerBar > 1 && series.phaseSource !== "none"; } /** Which beat of the bar a row stands on, phase included, modulus kept positive. */ function barResidue(row: number, series: SearchSubject): number { const bpb = series.rowsPerBar; if (!(bpb > 1)) return 0; const r = Math.round(row); return (((r - series.phase) % bpb) + bpb) % bpb; } /** * How far to move a region so that it starts on the one, or `0` to leave it where the search put it. * * The detector has always known which regions land on a downbeat and has never used that knowledge * for anything. `onBar` sits sixth in a sort whose bins the numbers routinely clear, and the key that * actually arms a region (`PlayerStore.pressNearest`) chooses by distance to the playhead and does not * read it at all, so the one number in the candidate list that answers the listener's "that loop isn't * on the beat" was a chip beside the title. This gives the bar a vote, and a deliberately narrow one: * * - Both edges move by the same amount, so the period and the length are exactly what the search * found. A loop whose length is not a whole number of bars comes in at a different beat every pass, * which is a worse version of the same complaint, and shifting both edges together cannot cause it. * - The offset is at most half a bar, because that is how far two rows can be and still be the same * claim about the track rather than a different region of it. * - The move is refused unless the copies agree at the bar-aligned row as well as they did where the * search stood, to within `tieMargin` — the same indifference the position walk already applies to * its own positions, on the same column, at the same window length. Where the measurement can tell * the two rows apart it decides, exactly as it always did; where it cannot, the drummer answers * rather than the row arithmetic winning on a rounding detail. * * So this is not the bar outvoting a measurement, which is the error this file has been written and * rewritten to avoid: it is the bar settling a tie the measurement had already declared. And it only * runs when `barKnown` — moving a boundary to satisfy an alignment nobody measured would trade a * measurement's mistake for a prior's. * * `back` and `forward` are how many rows the move may travel in each direction before it runs into * something it is not allowed to move: the edge of the file, the region this family armed last, or * the next position the walk took. Whoever calls has to decide which of those is nearest, because the * answer is not the same for a whole family sliding together and for one region sliding alone. */ function barShift( series: SearchSubject, agreement: (row: number, len: number) => number, start: number, lag: number, back: number, forward: number, indifference: number, ): number { const bpb = series.rowsPerBar; if (!(bpb > 1) || !barKnown(series)) return 0; const residue = barResidue(start, series); if (residue === 0) return 0; // already starts on the one, and so — both edges moving — ends there too const allowed = agreement(start, lag) - indifference; // Both directions are offered, and one of them is always within half a bar: a row that is `residue` // beats past a downbeat is `bpb - residue` beats short of the next one. let best = 0; let bestScore = allowed; let bestDistance = Infinity; for (const shift of [-residue, bpb - residue]) { // Room to travel: whoever called has already folded the edge of the file into `back` and // `forward`, so a move that fits them keeps the window the agreement is measured over inside too. if (shift < -back || shift > forward) continue; const score = agreement(start + shift, lag); const distance = Math.abs(shift); // Better agreement wins; at an equal agreement — which is the ordinary case, the two rows being // the same repeating figure read a beat apart — the nearer row is the smaller change to a boundary // the search already chose, and a forward step loses to a backward one only because it is the // bigger edit on the tie between them. if (score > bestScore || (score === bestScore && distance < bestDistance)) { best = shift; bestScore = score; bestDistance = distance; } } return best; } /** * The offset that puts a whole run of one family's regions on the one, or `0` to leave them alone. * * See the argument at `barShift` and at the call site: the correction is only safe when everything * that is packed against everything else moves together, because a translation changes no distance * between any two of the things it moves, and the positions of a body that repeats are packed a * period apart with nothing to spare — so a region that slides alone slides onto its neighbour and the * listener is offered one loop in one place twice. * * "Everything packed together" is not the whole family. A family's positions are taken greedily and * the trim starts each run where the agreement actually holds, so one family routinely contains a run * of regions all standing on beat one and, further along the track, another run all standing on beat * three, with a gap of unfound agreement between them. Those two runs are separate rigid bodies: each * slides as a unit, into the room the gap on either side of it leaves, and neither may reach into the * other. Measuring the agreement at the run's first position is enough for the whole run — on a body * that repeats, every position of it agrees as well as the first does by construction, and checking * each one would be a second, stricter rule than the one that chose the positions. */ function groupBarOffset( series: SearchSubject, agreement: (row: number, len: number) => number, positions: readonly { start: number; end: number }[], at: number, lag: number, frames: number, indifference: number, ): number { if (!barKnown(series)) return 0; const residue = barResidue(positions[at]!.start, series); if (residue === 0) return 0; // this run already stands on the one let first = at; while (first > 0 && barResidue(positions[first - 1]!.start, series) === residue) first--; let last = at; while (last + 1 < positions.length && barResidue(positions[last + 1]!.start, series) === residue) last++; const head = positions[first]!; // Room to move: the region the family left behind on one side (or the top of the file), and the next // region the walk took on the other (or the bottom of the file). Between them is the unfound // agreement the greedy walk skipped, which is exactly the slack a rigid run may use. const back = first > 0 ? head.start - (positions[first - 1]!.end + 1) : head.start; const forward = last + 1 < positions.length ? positions[last + 1]!.start - (positions[last]!.end + 1) : frames - (positions[last]!.end + 1); if (back < 0 || forward < 0) return 0; // packed solid against something it may not move // ...and the window the agreement is measured over has to stay inside the file whatever else fits. return barShift( series, agreement, head.start, lag, back, Math.min(forward, frames - (head.start + lag)), indifference, ); } /** A cap on what one track offers, which is the chip's problem rather than the algorithm's. */ const MAX_CANDIDATES = 12; /** * How many ranked regions the spread gets to choose between — twice the list, so a track whose best * evidence all stands in one place can actually be spread rather than truncated into it. */ const CANDIDATE_POOL = 24; /** How many of them may claim the same sixth of the file — see `acrossTrack`. */ const PER_PLACE = 2; /** * How many places one loop is offered — deliberately generous, because the culling that matters * happens in `acrossTrack`. * * This used to be four, which was the right cap for a key that walked the list by hand and the * wrong one for the shape the list is meant to have: a beat that repeats for three minutes is three * minutes of loopable regions, and offering four of them all from the first quarter of the song is * what left the listener at 2:40 with a candidate from the intro. The cap that keeps the list short * is now the one per place in the file, and this one only has to keep the search's own output from * being unlimited — which the pool it feeds already does. */ const MAX_POSITIONS = CANDIDATE_POOL; /** The typicality weights' own reading of the track: 0 is a flat histogram, nothing to learn. */ /** * How many of the rows said each pitch class was sounding, as a fraction of the rows that said * anything at all. A row the mask zeroed is not a row where nothing sounded — it is a row nobody * looked at — so it is out of both the numerator and the denominator. */ function presenceOf(values: Float32Array, frames: number, width: number): number[] { const counts = new Array(width).fill(0); let rows = 0; for (let f = 0; f < frames; f++) { const at = f * width; let said = false; for (let c = 0; c < width; c++) { if ((values[at + c] ?? 0) === 0) continue; if (!said) { said = true; rows++; } counts[c] = (counts[c] ?? 0) + 1; } } return rows ? counts.map((c) => (c ?? 0) / rows) : counts; } function spread(weights: Float32Array): number { let min = Infinity; let max = -Infinity; for (let c = 0; c < weights.length; c++) { const w = weights[c] ?? 1; if (w < min) min = w; if (w > max) max = w; } return min === Infinity ? 0 : max / min; } /** * How much the track's chroma moves around its own average frame, on a 0..1 scale: 0 is one * chord forever. A track that never changes has no comparison to make, and reporting the best * of no comparisons as an answer is the failure this guards (the old code had a zero-variance * drone in its test suite precisely because Pearson is undefined on one). */ function variation(values: Float32Array, frames: number, width: number): number { const mean = new Float32Array(width); let n = 0; for (let f = 0; f < frames; f++) { const at = f * width; if (silent(values, f, width)) continue; n++; for (let c = 0; c < width; c++) mean[c] = (mean[c] ?? 0) + (values[at + c] ?? 0); } if (!n) return 0; let norm = 0; for (let c = 0; c < width; c++) { mean[c] = (mean[c] ?? 0) / n; norm += (mean[c] ?? 0) * (mean[c] ?? 0); } norm = Math.sqrt(norm); if (!(norm > 0)) return 0; for (let c = 0; c < width; c++) mean[c] = (mean[c] ?? 0) / norm; let acc = 0; for (let f = 0; f < frames; f++) { if (silent(values, f, width)) continue; acc += 1 - rowDot(values, f * width, mean, 0, width); } return acc / n; } /* ------------------------------------------------------------------------- */ /* Where the song is */ /* ------------------------------------------------------------------------- */ /** * The body: the stretch between the first change of character near the head and the last one * near the tail, in frames. * * Foote's checkerboard kernel, on a chroma self-similarity matrix at `BODY_FRAME_SEC`, is the * novelty curve; the peaks of it are where the music's character changes. Taking the first and * last strong peak as the body's bounds is what the loop-point tools that came before this all * do, and for the reason they all state — a detector with *"no notion of intro vs. body"* offers * *"two mid-body moments that happen to sound alike"* on a track with a long intro, and, worse, * can offer the intro against itself. * * Three guards keep it from being a liability, because a novelty curve on synthesised material * is a blunt instrument and the damage it can do is to silently cut the answer's head off: * * - a peak only counts if it is near the end it claims (`BODY_SEARCH_FRACTION` of the track). * A change of character at 40% is a bridge, not an intro, and treating it as either would * discard the middle of the song; * - the body has to keep most of the track (`BODY_MIN_KEEP`) or the peaks were noise and the * whole track is the body; * - and the candidate is rejected only if its *middle* is outside the body, not its edges: * a loop that starts one second before the detected body start is a loop that starts there. * * Returns the whole track when there is nothing to exclude, which is the answer for an * instrumental through-composed piece and most game tunes. */ function bodyRegion( values: Float32Array, frames: number, frameSec: number, o: Resolved, width: number, ): { from: number; to: number; all: boolean } { const whole = { from: 0, to: frames - 1, all: true }; const step = Math.max(1, Math.round(BODY_FRAME_SEC / frameSec)); const n = Math.floor(frames / step); if (n < 8) return whole; // The grid the SSM is built on: mean chroma per half-second, re-normalised, so a bar of // silence and a bar of chord differ in direction rather than in how loud the track was. const grid = new Float32Array(n * width); for (let g = 0; g < n; g++) { for (let k = 0; k < step; k++) { const f = g * step + k; if (f >= frames) break; const at = f * width; for (let c = 0; c < width; c++) grid[g * width + c] = (grid[g * width + c] ?? 0) + (values[at + c] ?? 0); } let norm = 0; for (let c = 0; c < width; c++) { const v = grid[g * width + c] ?? 0; norm += v * v; } norm = Math.sqrt(norm); if (norm > 0) for (let c = 0; c < width; c++) grid[g * width + c] = (grid[g * width + c] ?? 0) / norm; } const half = Math.max(1, Math.round(o.bodyKernelSec / 2 / BODY_FRAME_SEC)); if (n <= half * 2 + 2) return whole; // the kernel is wider than the track, so it says nothing const novelty = new Float32Array(n); // The checkerboard's two terms: the self-similarity inside each side of the boundary, and the // cross-similarity across it. A boundary is where the first is high and the second is not. // Direct rather than via prefix sums over a materialised matrix — at half a second per frame // the matrix is 230 KB and the kernel is what it costs to convolve, and the first version of // this comment promised the cheaper thing it does not do. for (let i = half; i < n - half; i++) { let inner = 0; let across = 0; for (let a = i - half; a < i; a++) { for (let b = i - half; b < i; b++) inner += rowDot(grid, a * width, grid, b * width, width); for (let b = i; b < i + half; b++) across += rowDot(grid, a * width, grid, b * width, width); } const area = half * half; novelty[i] = (inner - across) / area; } let median = 0; { const seen: number[] = []; for (let i = half; i < n - half; i++) seen.push(novelty[i] ?? 0); seen.sort((a, b) => a - b); median = seen[seen.length >> 1] ?? 0; } const threshold = median + BODY_PEAK_MARGIN; const seconds = n * BODY_FRAME_SEC; const headLimit = seconds * BODY_SEARCH_FRACTION; const tailLimit = seconds * (1 - BODY_SEARCH_FRACTION); // The strongest peak in the head's window, and the strongest in the tail's — not the first // above the threshold, because a curve's first bump out of the intro's own noise is a poor // estimate of where the intro ends. let from = 0; let bestHead = threshold; for (let i = half; i < n - half; i++) { if (i * BODY_FRAME_SEC > headLimit) break; if ((novelty[i] ?? 0) > bestHead) { bestHead = novelty[i] ?? 0; from = i; } } let to = n - 1; let bestTail = threshold; for (let i = n - half - 1; i >= half; i--) { if (i * BODY_FRAME_SEC < tailLimit) break; if ((novelty[i] ?? 0) > bestTail) { bestTail = novelty[i] ?? 0; to = i; } } if (to - from < n * BODY_MIN_KEEP) return whole; return { from: from * step, to: to * step, all: false }; } /* ------------------------------------------------------------------------- */ /* The two lines it leaves behind */ /* ------------------------------------------------------------------------- */ /** * The reading, then the decision taken on it. Separate lines: the first is the number somebody * argues with and the second is what the bar renders. Merged, the `not sure` reports a verdict * without ever saying by how much it missed, which is the failure that made the old floor * unarguable for as long as it took two rounds of instrumentation to fix. */ function report( label: string | undefined, why: string, s: SearchStats, candidates: Candidate[], ): void { traceDetect("measured", label, undefined, () => ({ frames: s.frames, audible: s.audible, kept: s.frames ? `${((100 * s.audible) / s.frames).toFixed(0)}%` : undefined, tempo: s.bpm ? s.bpm.toFixed(1) : undefined, weightSpread: s.weightSpread.toFixed(2), lags: s.lags, cells: s.cells, periods: `${s.periodFrom}–${s.periodTo}`, best: s.best < 0 ? undefined : s.best.toFixed(3), tail: s.tail.toFixed(3), tailQuantile: s.tailQuantile, // How many lags the comparative half had to let above it. Printed next to the quantile because on a // short file or a coarse grid the quantile is not the rule that decided anything — see `TAIL_LAGS`. tailLags: s.tailLags, tau: s.tau.toFixed(3), floor: s.floor, cleared: s.cleared, trim: s.trim, trimGate: s.trimGate, trimGapSec: s.trimGapSec, trimmed: s.trimmed, // How many boundaries the bar moved, and how many it left alone: the rule is only entitled to // settle a tie the agreement declared, and this is the field that says whether it did. barMoved: s.barMoved, // What the order was decided by, next to what the acceptance was decided by: the two are different // numbers on purpose and a calibration sitting has to be able to see them separately. priorWeight: s.priorWeight, priorBars: s.priorBars, minBars: s.minBars, scoredBy: s.path ? "sustained path" : "window mean", // The most distinctive period in the file, measured against the file's own background. A track // whose whole answer is a small number here is a track the representation cannot resolve, which is // the reading the calibration sitting is looking for and the one no other field in this line gives. bestContrast: s.bestContrast.toFixed(3), body: s.body ? `${(s.bodyFrom * s.frameSec).toFixed(1)}–${(s.bodyTo * s.frameSec).toFixed(1)}s` : "off", smoothSec: s.smoothSec, })); traceDetect( candidates.length ? `offered ${count(candidates.length, "candidate")}` : `refused: ${why}`, label, undefined, () => ({ best: s.best < 0 ? undefined : s.best.toFixed(3), shortOfTheThresholdBy: why === "not-convincing" && s.best >= 0 ? Math.round((s.tau - s.best) * 1000) / 1000 : undefined, periods: candidates.length ? candidates.map((c) => `${c.period.toFixed(2)}s@${c.start.toFixed(1)}`).join(", ") : undefined, lengths: candidates.length ? candidates.map((c) => `${(c.end - c.start).toFixed(2)}s`).join(", ") : undefined, scores: candidates.length ? candidates.map((c) => c.r.toFixed(3)).join(", ") : undefined, // The four numbers the order was made of, printed rather than inferred from the order: a listener // who disagrees with which candidate came first should be able to see which of these said so. contrasts: candidates.length ? candidates.map((c) => (c.contrast ?? 0).toFixed(2)).join(", ") : undefined, priors: candidates.length ? candidates.map((c) => (c.prior ?? 1).toFixed(2)).join(", ") : undefined, seams: candidates.length ? candidates.map((c) => (c.seam ?? 0.5).toFixed(2)).join(", ") : undefined, wraps: candidates.length ? candidates.map((c) => (c.wrap ?? 0.5).toFixed(2)).join(", ") : undefined, coverages: candidates.length ? candidates.map((c) => (c.coverage ?? 1).toFixed(2)).join(", ") : undefined, ranks: candidates.length ? candidates.map((c) => (c.rank ?? c.r).toFixed(3)).join(", ") : undefined, ranking: rankerLine(), }), ); } /** * Both halves, one call — the shape the store's injected analysis falls back to when a Worker * cannot be constructed, and the shape the tests call directly. Not a third implementation: the * same `fingerprint` and the same `search`, on this thread. */ export function detect( samples: Float32Array, sampleRate: number, opts: DetectOptions = {}, ): DetectResult { // The samples go to the search as well as to the fingerprint: one pass of audio, two features read // out of it, and the search decides which clock it can answer on. const series = fingerprint(samples, sampleRate, opts); return searchSeries(series, { samples, sampleRate }, opts); }