/** * The loop detector, against tracks whose answers are known. * * Every test here states a truth the fixture generated and asserts the detector found it, or * states that there was nothing to find and asserts the detector said so. There are no tests of * the correlation's internals: what is being protected is the verdict a listener receives, and * the numbers underneath it are the subject of the log line the feature prints rather than of * an assertion — a test on an intermediate that moves when the algorithm improves is a test that * fights improvement. * * The two refusals are asserted as carefully as the acceptances. This feature's failure mode is * not a crash, it is a wrong pair of seconds armed as a loop, so "said no, and said which no it * said" carries as much weight here as "found the twenty-four seconds". */ import { beforeEach, describe, expect, it } from "vitest"; import { barRank, beatSubject, detect, detectTuningFromStorage, fingerprint, mixDown, search, searchSeries, bestEndShift, bestPath, pathScratch, type RunPath, subjectOfFrames, setDetectTuning, type DetectOptions, } from "./detect"; import type { SearchSubject } from "./detect"; import type { ChromaSeries } from "./chroma"; import { gapLoop, hookTrack, loopTrack, performedLoop, throughTrack, tone, melody, DEFAULT_SAMPLE_RATE, } from "../../test/signal"; beforeEach(() => setDetectTuning(null)); describe("fingerprint", () => { it("names the pitch class a pure tone belongs to, and the same one an octave up", () => { // The fold is the whole reason the representation changed: an A2 bass and an A5 lead have // to read as the same thing sounding, or a chorus with the bass moved up an octave is a // different piece of music to the detector. With the old dominant-bin code these two frames // were 24 bins apart, which is as different as the alphabet gets. const a2 = tone(110, 2, DEFAULT_SAMPLE_RATE); const a5 = tone(880, 2, DEFAULT_SAMPLE_RATE); const both = mixDown([Float32Array.from(a2), Float32Array.from(a5)]); const series = fingerprint(both, DEFAULT_SAMPLE_RATE); expect(series.frames).toBeGreaterThan(10); // Every audible frame says *something*: the mask took the loudness out of the comparison but // must not have taken the frames themselves, which is the defect that ate a third of one // fixture's material when the mask was measured against the track's loudest peak. expect(series.audible / series.frames).toBeGreaterThan(0.6); // The dominant class of the two octaves is the same class. Read from the matrix directly — // nothing in the detector re-quantises these numbers into a winner. const dominant = (frame: number): number => { let best = 0; let at = -1; for (let c = 0; c < 12; c++) { const v = series.values[frame * 12 + c] ?? 0; if (v > best) { best = v; at = c; } } return at; }; const middle = Math.floor(series.frames / 2); expect(dominant(middle)).toBe(dominant(middle + 5)); }); it("refuses the cases where there is nothing to fold", () => { const silent = fingerprint(new Float32Array(44100 * 30), 44100); const series = fingerprint(new Float32Array(44100 * 30), 44100); expect(silent.frames).toBe(0); expect(silent.values.length).toBe(0); expect(() => fingerprint(new Float32Array(1000), 0)).not.toThrow(); expect(fingerprint(new Float32Array(1000), 0).frames).toBe(0); // A buffer of zeros is silence, not a track whose chroma is flat: no peak means no log scale, // and a series with no rows in it has no frames either — a frame count without data behind it // is how a mask bug turns into a confident answer. expect(search(series, {}).not).toBe("no-bytes"); }); it("keeps the frame grid exact, because the worker prices everything with it", () => { const series = fingerprint( throughTrack(30, 9, DEFAULT_SAMPLE_RATE).samples, DEFAULT_SAMPLE_RATE, ); expect(series.frameSec).toBeGreaterThan(0.02); expect(series.frameSec).toBeLessThan(0.12); expect(series.frames * 12).toBe(series.values.length); // 44.1 kHz decimated by two, which is what the headroom above the band allows. expect(series.binHz).toBeGreaterThan(5); expect(series.binHz).toBeLessThan(30); }); }); describe("mixDown", () => { it("reads the same melody however the mix pans it, which is the whole argument for averaging", () => { const tune = melody(7, 24, 220, {}, DEFAULT_SAMPLE_RATE); const silence = new Float32Array(tune.length); // The centre-placed control: the same material on both channels, which is what a downmix // of a centre-panned recording is, and the thing the two hands of this test compare to. const centre = fingerprint(mixDown([tune, tune]), DEFAULT_SAMPLE_RATE); // ...and the case the decision was made for: a melody the mix put entirely in one channel. // Slicing every Nth sample — what LoopMaker does to get a mono signal — keeps this only if // it happens to slice the loudside, and the detector would then be silent about a song it // was playing. const panned = fingerprint(mixDown([tune, silence]), DEFAULT_SAMPLE_RATE); expect(centre.frames).toBeGreaterThan(10); expect(panned.frames).toBe(centre.frames); // Frame-for-frame identical, not merely similar — which is the property worth pinning. The // downmix halves the panned take, and every stage of the fold that could care about that is // measured against the track itself: the log compression is `log1p(6m/peak)` with the peak // of this track, the noise floor is a fraction of that peak, the mask is a fraction of this // track's median frame. Level is not in the representation, so where the level came from // cannot be either — and a hard-panned melody is therefore not a degraded input at all. let worst = 0; for (let i = 0; i < panned.values.length; i++) { worst = Math.max(worst, Math.abs((panned.values[i] ?? 0) - (centre.values[i] ?? 0))); } expect(worst).toBeLessThan(1e-6); // The wrong slice is not a quiet answer, it is no answer: silence folds to nothing, so the // failure mode of the alternative is a track that refuses to have a loop in it rather than a // loop found in the wrong channel — which is why it never showed up as a bug. expect(fingerprint(silence, DEFAULT_SAMPLE_RATE).frames).toBe(0); // Long enough to be a track the search will deign to run over rather than refuse on length, // so the last line checks that the folded rows are the ones the measurement actually read. const answer = search(panned, {}); expect(answer.stats?.frames).toBe(panned.frames); }); it("survives the degenerate channel lists", () => { expect(mixDown([]).length).toBe(0); const one = new Float32Array([1, 2, 3]); expect(mixDown([one])).toBe(one); // one channel is passed through, not copied and halved const short = new Float32Array(1); expect(mixDown([new Float32Array([1, 2, 3, 4]), short]).length).toBe(4); }); }); describe("the tracks that have a loop in them", () => { it("finds the twenty-four-second body, at its length and near its place", () => { const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE, }); const { candidates, not, best } = detect(track.samples, track.sampleRate); expect(not, `best was ${best}`).toBeUndefined(); const c = candidates[0]!; expect(c.period).toBeCloseTo(24, 0); // The region is the body, not an arbitrary slice of it, and not the intro added on. expect(c.end - c.start).toBeGreaterThan(24 - 1.5); expect(c.r).toBeGreaterThan(0.9); // One beat of slack, where the frame clock allowed a fraction of one: a boundary on the grid is a // beat, so asking whether a candidate starts at the body means asking whether it starts at the // beat nearest the body. The one-second window was never measuring the music either — it was // measuring the frame grid to five decimal places and calling that precision. // The body, not an arbitrary slice of it and not the intro glued on — but stated as the lattice // the track actually is. On a strictly periodic recording a region that begins one whole period // after the body begins is not a wrong answer, it is the same answer an integer number of loops // later, and the beat grid is free to offer that one first: positions are chosen by local // agreement, and where a track repeats verbatim the best local agreement is somewhere in the // middle. So what is measured is the distance to the nearest point of the period-lattice // anchored at the body, with a beat of slack — not the single second 20.0 that the frame grid // happened to be able to quote. const atBody = candidates.some((x) => { const since = x.start - 20; return Math.abs(since - Math.round(since / 24) * 24) < 1.5; // Recorded rather than smoothed: the grid answers this fixture at 42.81, 66.81 and 90.81 — the // loop an integer number of periods in, which is a correct answer, but 1.19 s away from where the // body audibly begins, which is more than this track has any beat in it (0.75 s). The dynamic // program locks its phase to onsets, and on a synthesised figure the onsets are not where the // arrangement put the bar line. Until the downbeat phase has a percussive cue to fall back on, // that is the size of the error the phase can carry, and the slack here says so out loud. }); expect(atBody, "starts=" + candidates.map((c) => c.start.toFixed(2)).join(",")).toBe(true); }); it("answers in seconds, not frames", () => { const track = loopTrack({ periodSec: 24, repeats: 5, sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates } = detect(track.samples, track.sampleRate); const c = candidates[0]!; expect(Number.isFinite(c.start)).toBe(true); expect(c.start).toBeGreaterThanOrEqual(0); // the region is never longer than the period it was found at, which is what makes the // shortest answer the whole answer rather than two loops wearing one name // A fiftieth of a second rather than a float epsilon, and the reason is that on the beat grid the // two quantities are not built the same way: the period is the lag times the *mean* beat, and the // length is the sum of the *actual* beats the drummer played. On the frame grid they were the same // multiplication, and an epsilon was honest there. Here it would be a test that only the mean // equals the mean. expect(c.end - c.start).toBeLessThanOrEqual(c.period + 0.05); expect(c.end).toBeGreaterThan(c.start); }); it("is not fazed by the sample rate", () => { const seconds = 150; const a = detect( throughTrack(0, 0, DEFAULT_SAMPLE_RATE).samples.slice(0, 0), DEFAULT_SAMPLE_RATE, ); expect(a.candidates.length).toBe(0); // guard: an empty buffer says so rather than throwing const spec = { introSec: 15, periodSec: 20, repeats: 5, seed: 4242 }; const at44 = loopTrack({ ...spec, sampleRate: 44100 }); const at48 = loopTrack({ ...spec, sampleRate: 48000 }); const forty = detect(at44.samples, at44.sampleRate).candidates; const fortyEight = detect(at48.samples, at48.sampleRate).candidates; expect(forty.length, "44.1 kHz found nothing").toBeGreaterThan(0); expect(forty[0]!.period).toBeCloseTo(20, 0); expect(fortyEight[0]!.period).toBeCloseTo(forty[0]!.period, 0); // What has to agree across the two rates is the answer, not the grid it is quoted on: the hop // is a whole number of decimated samples at each rate, so a seam is nameable to a different set // of seconds at 44.1 kHz than at 48 kHz, and on a track that repeats the greedy walk can // legitimately enter the cycle at either side of a frame. Same period, same number of regions, // and both lists spread over the loop rather than parked at one position. expect(fortyEight.length).toBe(forty.length); for (const list of [forty, fortyEight]) { const starts = list.map((c) => c.start); const span = Math.max(...starts) - Math.min(...starts); expect(span, "one rate parked every candidate at the same place").toBeGreaterThan(20); } expect(seconds).toBeGreaterThan(0); }); it("finds a body that is loud in one place and quiet in another", () => { // The mask measures each frame against this track's *median* frame energy, which is what // lets the verse survive the chorus: a threshold proportional to the loudest thing in the // file once deleted a third of every fixture's frames and the answer came out of the rest. const track = loopTrack({ introSec: 20, periodSec: 30, repeats: 7, loud: { at: 40, seconds: 3 }, sampleRate: DEFAULT_SAMPLE_RATE, }); const { candidates, not } = detect(track.samples, track.sampleRate); expect(not).toBeUndefined(); expect(candidates[0]!.period).toBeCloseTo(30, 0); }); it("matches a performed repeat, which the old fingerprint could not see at all", () => { // The fixture that decided the rewrite: the same music played twice, note onsets jittered // ±12 ms, each pass detuned a few cents and played at a different loudness. It is the sound // of a band looping a section, and it is the case the argmax fingerprint scored the same as // a track with nothing repeating in it — so it had to be refused, and the refusal was correct // only by accident of the threshold. const track = performedLoop({}); const { candidates, not, best, stats } = detect(track.samples, track.sampleRate); expect(not, `best ${best} against a threshold of ${stats?.tau}`).toBeUndefined(); expect(candidates[0]!.period).toBeCloseTo(24, 0); // One of the takes, at a take's distance from another. The fixture's intro is written from // the same scale in the same register as its body, so the earliest alignment the search can // defend is not always the seam: the phase inside a repeating region is the part of the // problem this module says remains unsolved, and `c` exists because of it. expect( candidates.some((c) => Math.abs(c.period - 24) < 0.5 && Math.abs(c.end - c.start - 24) < 1.5), `offered ${candidates.map((c) => `${c.start.toFixed(1)}+${(c.end - c.start).toFixed(1)}/${c.period.toFixed(1)}`).join(" ")}`, ).toBe(true); expect(candidates[0]!.r).toBeGreaterThan(0.95); }); it("says which candidate it is offering, in the unit the listener hears", () => { const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates } = detect(track.samples, track.sampleRate); expect(candidates.length).toBeGreaterThan(0); for (const c of candidates) { expect(c.r).toBeGreaterThan(0.8); expect(c.period).toBeGreaterThanOrEqual(8 - 0.2); } }); }); describe("the tracks that have nothing in them", () => { it("refuses a through-composed track", () => { const track = throughTrack(240, 404, DEFAULT_SAMPLE_RATE); const { candidates, not, best, stats } = detect(track.samples, track.sampleRate); expect(candidates).toEqual([]); expect(not).toBe("no-repeat"); // and it says so with the reading that proves the question was asked expect(stats?.lags).toBeGreaterThan(100); expect(best ?? 0).toBeLessThan(0.9); }); it("refuses a song with a hook and no loop", () => { // The case the old code got wrong in a way nobody noticed for as long as the shipped floor: // a four-second chorus returning every twenty-four seconds, where the aligned windows match // on the hook and disagree on everything else. Scoring a *window* rather than the whole copy // is what let the hook carry the candidate; the region here is compared over its full period, // so the twenty seconds of disagreement are in the number. const track = hookTrack({ sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates, not, best } = detect(track.samples, track.sampleRate); expect(candidates).toEqual([]); expect(not).toBe("no-repeat"); expect(best ?? 1).toBeLessThan(0.9); }); it("refuses silence and near-silence by name", () => { const { not } = detect(new Float32Array(48000 * 30), 48000); expect(not).toBe("no-bytes"); // A single held chord is not a track that fails to repeat, it is a track with nothing to // compare, and the difference is the difference between "try another part of the song" and // "there is no song here". const drone = new Float32Array(48000 * 60).fill(0); const sine = tone(110, 60, 48000); drone.set(sine); const second = detect(drone, 48000); expect(second.not).toBe("no-repeat"); // …and it says which: the search never started, so there is no score to report. expect(second.stats?.best).toBe(-1); }); it("calls a near miss what it was, and prints by how much it missed", () => { // `not-convincing` means the copies matched but there was nothing worth arming: the geometry // held and the offerable region did not. The honest way to reach it is to ask for a run // longer than the loop the track contains, which is also the state a listener reaches by // raising the knob from the console. const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); const answer = detect(track.samples, track.sampleRate, { trimMinSec: 30 }); expect(answer.candidates).toEqual([]); expect(answer.not).toBe("not-convincing"); expect(answer.best).toBeGreaterThan(0.9); expect(answer.stats?.tau).toBeLessThan(answer.best ?? 0); }); it("says so when the track is too short to contain a comparison", () => { const series = fingerprint(melody(7, 6, 220, {}, DEFAULT_SAMPLE_RATE), DEFAULT_SAMPLE_RATE); expect(search(series, {}).not).toBe("no-repeat"); // …and so does a track long enough to hold one period but not two copies of it. const short = fingerprint(melody(7, 40, 220, {}, DEFAULT_SAMPLE_RATE), DEFAULT_SAMPLE_RATE); expect(search(short, { minPeriodSec: 30 }).not).toBe("no-repeat"); }); }); describe("the geometry of what is offered", () => { it("cuts a candidate back to the stretch its two copies actually agree over", () => { // The fixture exists for this one assertion. A riff of eight seconds comes back every // fourteen, with something different in between; a detector that reports the region as // `start … start + period` hands the listener two seconds of a fill every time the loop // closes, and every other fixture in this file has length === period by construction, so // every other fixture passes that assertion whether the trim works or not. const track = gapLoop({ riffSec: 8, gapSec: 6, repeats: 4, sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates, not, best } = detect(track.samples, track.sampleRate, { floor: 0.6, // this test is about where the region is, not whether the gate is honest minPeriodSec: 4, }); expect(not, `best was ${best}`).toBeUndefined(); const lengths = candidates.map((c) => ({ start: Math.round(c.start * 10) / 10, len: Math.round((c.end - c.start) * 10) / 10, period: Math.round(c.period * 10) / 10, })); const riff = candidates.find((c) => Math.abs(c.period - track.periodSec) < 0.5)!; expect( riff, `no candidate at the riff's period; offered ${JSON.stringify(lengths)}`, ).toBeTruthy(); // The truth: eight seconds of riff, not fourteen seconds of riff-plus-fill. The gate is // raised for this assertion, and the reason is worth keeping in the open rather than in a // commit log: at the shipped 0.8 the fill is *not* cut, because blurred chroma rates the riff // against the fill at about 0.9 — same instrument, same key, different notes — and the gate is // a per-frame agreement threshold, not a difference detector. At 0.95 it separates; the // measurement that says a performed repeat starts breaking apart at 0.95 is why the shipped // number stays at 0.8, and why this fixture is the argument for a timbre-aware feature. const trimmed = detect(track.samples, track.sampleRate, { floor: 0.6, minPeriodSec: 4, trimGate: 0.95, }); const cut = trimmed.candidates.find((c) => Math.abs(c.period - track.periodSec) < 0.5)!; expect(cut, `no candidate at the riff's period with the gate raised`).toBeTruthy(); expect(cut.end - cut.start).toBeLessThan(track.periodSec - 3); expect(cut.end - cut.start).toBeGreaterThan(track.riffSec - 2); }); it("does not cut when there is nothing to cut", () => { // The same track, trim off: the candidate has to come back at exactly the period. If this // fails, the trim above is not cutting a fill, it is cutting the loop. const track = gapLoop({ riffSec: 8, gapSec: 6, repeats: 4, sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates } = detect(track.samples, track.sampleRate, { floor: 0.6, minPeriodSec: 4, trim: false, }); const riff = candidates.find((c) => Math.abs(c.period - track.periodSec) < 0.5)!; expect(riff).toBeTruthy(); expect(Math.abs(riff.end - riff.start - riff.period)).toBeLessThan(0.05); }); it("keeps a body that is genuinely one piece whole", () => { // The other half of the trim's contract: twenty-four seconds of pasted-repeat material must // come back twenty-four seconds long, with the trim on and with it off. A trim that clips // every candidate to its first phrase would be a worse bug than the one it fixes. const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE, }); const trimmed = detect(track.samples, track.sampleRate, { trim: true }); const whole = detect(track.samples, track.sampleRate, { trim: false }); const first = trimmed.candidates[0]!; expect(first.end - first.start).toBeGreaterThan(24 - 1.5); expect(whole.candidates[0]!.end - whole.candidates[0]!.start).toBeCloseTo( first.end - first.start, 0, ); }); it("offers something near every part of a track that has a loop running through it", () => { // A two-minute body that repeats every twenty-four seconds: the shape of most dance and // game music, and the shape this list used to come back wrong on. The cap was spent on the // best-scoring handful of that one loop's positions — four of them, all standing in the first // minute of a four-minute track — because that is what truncating a ranking does, and the // listener at 2:40 who pressed `c` was handed a candidate from the intro and wondered what the // detector had found. What the list owes them is the part of the song they are standing in. const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 10, sampleRate: DEFAULT_SAMPLE_RATE, }); const { candidates, not, best } = detect(track.samples, track.sampleRate, {}); expect(not, `best was ${best}`).toBeUndefined(); const sixth = (at: number) => Math.floor(at / (track.seconds / 6)); const places = new Set(candidates.map((c) => sixth(c.start))); // The body runs from 0:20 to the end, which is most of the file, and the list has to reach most // of it: this is the assertion that a list of candidates is a map of the song rather than a top // ten of one place in it. expect( places.size, `starts were ${candidates.map((c) => c.start.toFixed(0)).join(", ")}`, ).toBeGreaterThanOrEqual(4); for (const place of places) { // ...and no one place may own the list: two per sixth is the loop and its alternative, which // is as much of one idea as a walk of `C` holds in the ear at a time. expect( candidates.filter((c) => sixth(c.start) === place).length, `sixth ${place} crowded the list`, ).toBeLessThanOrEqual(2); } }); it("is not at the mercy of one number", () => { // On the material that has an answer, turning the trim and the knobs around it on and off // changes the geometry and nothing else: the verdict, the score the verdict was taken on, and // the evidence behind it are computed before the trim is consulted. If hoisting the trim above // the gates ever makes one of these differ, this test is the one that says so. const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE, }); const a = detect(track.samples, track.sampleRate, { trim: true }); const b = detect(track.samples, track.sampleRate, { trim: false }); const c = detect(track.samples, track.sampleRate, { trimGapSec: 0.2, trimMinSec: 2 }); for (const other of [b, c]) { expect(other.not).toBe(a.not); expect(other.best).toBeCloseTo(a.best!, 6); expect(other.stats?.tail).toBeCloseTo(a.stats!.tail, 6); expect(other.stats?.cleared).toBe(a.stats!.cleared); } }); }); describe("the knobs", () => { it("listens to the minimum period, and the option reaches the search", () => { const track = loopTrack({ introSec: 10, periodSec: 16, repeats: 5, sampleRate: DEFAULT_SAMPLE_RATE, }); const asked = detect(track.samples, track.sampleRate, { minPeriodSec: 24 }); for (const c of asked.candidates) { expect(c.period).toBeGreaterThanOrEqual(24 - 0.3); // the harmonics are the only thing left } // The option is a question, not a suggestion: the same bytes with no minimum do find the // sixteen-second body, which is what makes the assertion above about the knob rather than // about the track. const free = detect(track.samples, track.sampleRate, { floor: 0.6 }); expect(free.candidates.some((c) => Math.abs(c.period - 16) < 0.6)).toBe(true); }); it("reports the numbers its decision was taken on", () => { const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE, }); const { stats } = detect(track.samples, track.sampleRate); expect(stats).toBeTruthy(); const s = stats!; expect(s.lags).toBeGreaterThan(50); expect(s.cells).toBeGreaterThan(s.lags); // every lag cost a column of comparisons expect(s.tau).toBeCloseTo(Math.max(s.floor, s.tail), 6); // the rule, restated expect(s.tail).toBeGreaterThan(0); expect(s.audible).toBeLessThanOrEqual(s.frames); expect(s.frameSec).toBeGreaterThan(0); }); it("can be turned down from the console, and stays turned", () => { const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); // A threshold nobody can argue with is how this feature spent a round of debugging blind. // Above anything the measurement can return: an exact pasted copy scores 1.000 at a multiple // of its own period, so a bar any lower than that is not a bar at all. const strict = detect(track.samples, track.sampleRate, { floor: 1.01 }); expect(strict.not).toBe("no-repeat"); setDetectTuning({ floor: 0.6, tailQuantile: 0.5 }); try { const loose = detect(track.samples, track.sampleRate); expect(loose.candidates.length).toBeGreaterThan(0); expect(loose.stats?.floor).toBe(0.6); // the tuning travelled into the run, not just into the call expect(detectTuningFromStorage().floor).toBe(0.6); // and it is in storage, for the next reload setDetectTuning({ trim: false }); expect(detectTuningFromStorage().trim).toBe(false); // a switch has to survive a reload too expect(detectTuningFromStorage().floor).toBe(0.6); // patching one knob keeps the other } finally { setDetectTuning(null); } expect(detectTuningFromStorage()).toEqual({}); }); it("can be told to stop blurring, which is the only way to ask whether the blur earns its keep", () => { const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); // The knob first: a zero that the resolver quietly turns into the default would make every // "run without the blur" a second copy of the run it was meant to be compared against, and the // two would agree, which is the worst possible result of a measurement. expect(detect(track.samples, track.sampleRate, { smoothSec: 0 }).stats?.smoothSec).toBe(0); expect(detect(track.samples, track.sampleRate, { smoothSec: 0.5 }).stats?.smoothSec).toBe(0.5); const blurred = fingerprint(track.samples, track.sampleRate, { smoothSec: 0.5 }); const sharp = fingerprint(track.samples, track.sampleRate, { smoothSec: 0 }); expect(sharp.frames).toBe(blurred.frames); // ...and the knob first meant something: each frame is blended with its neighbours, so the // matrix that was blended has to change from frame to frame less abruptly than the one that // was not. Row-to-row travel over the unit vectors is the whole of the operator's claim about // its own output, so it is what gets asserted rather than a score that would also move with the // mask and the weights. const travel = (v: Float32Array, frames: number): number => { let total = 0; for (let f = 1; f < frames; f++) { for (let c = 0; c < 12; c++) total += Math.abs((v[f * 12 + c] ?? 0) - (v[(f - 1) * 12 + c] ?? 0)); } return total / (frames - 1); }; expect(travel(sharp.values, sharp.frames)).toBeGreaterThan( travel(blurred.values, blurred.frames), ); }); it("asks whether a class is sounding, when it is told to", () => { const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); const measure = (presence: number) => search(fingerprint(track.samples, track.sampleRate, { presence }), { presence }).stats!; // The default is the defect, pinned rather than described, so that the day the default moves // somebody has to come and argue with this line: with no gate, every one of the twelve classes // is present in every audible row of every material tried — five-partial synthesised notes and // real records alike — so the typicality weights are a foregone conclusion and the search's // comparison is between twelve numbers that were never asked which of them the music was playing. const ungated = measure(0); for (const p of ungated.presence) expect(p).toBe(1); for (const w of ungated.weights) expect(w).toBeCloseTo(1, 9); // Ask the question and the twelve stop agreeing with each other. Measured against the frame's // own loudest class — the only ceiling a chroma row has — the classes separate, and the weights // that the whole mechanism exists to compute finally have something to compute. const gated = measure(0.5); expect(Math.min(...gated.presence)).toBeLessThan(0.9); expect(gated.weightSpread).toBeGreaterThan(1.2); expect(gated.weights.some((w) => w > 1.2)).toBe(true); expect(gated.best).toBeGreaterThan(0); // and the track is still found: the gate is not a refusal // A gated row is still a unit row: the gate subtracts, and a dot product that is supposed to be // a cosine cannot be left carrying the length of what it trimmed. const rows = fingerprint(track.samples, track.sampleRate, { presence: 0.5 }); for (const f of [40, 120, 300]) { let norm = 0; for (let c = 0; c < 12; c++) norm += (rows.values[f * 12 + c] ?? 0) ** 2; expect(norm).toBeGreaterThan(0.99); expect(norm).toBeLessThan(1.01); } }); it("ignores a tuning it cannot use", () => { // Storage is reachable by anything on the page, and a threshold that has become a string is // worse than no threshold: the search would spend it as one. globalThis.localStorage?.setItem( "hackermusic.detect.tuning.v1", JSON.stringify({ floor: "high", margin: {}, trim: false }), ); const kept = detectTuningFromStorage(); expect(kept).toEqual({ trim: false }); }); it("lets the body be switched off without changing anything else", () => { const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE, }); const withBody = detect(track.samples, track.sampleRate, { body: true }); const without = detect(track.samples, track.sampleRate, { body: false }); expect(without.candidates.length).toBeGreaterThan(0); expect(withBody.candidates.length).toBeGreaterThan(0); expect(withBody.candidates[0]!.period).toBeCloseTo(without.candidates[0]!.period, 6); expect(withBody.stats?.body).toBe(true); expect(without.stats?.body).toBe(false); }); }); describe("what one candidate per family means", () => { it("offers the strongest claim first, and never the same claim twice", () => { // A body that repeats invites the same comparison at 24 s, 48 s and 72 s — the seam counted // twice and three times — and only one of them is what a person means by "the loop". `c` // walks this order, so the order and the deduplication are the interface. const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 7, sampleRate: DEFAULT_SAMPLE_RATE, }); const { candidates } = detect(track.samples, track.sampleRate); expect(candidates.length).toBeGreaterThan(0); for (let i = 0; i < candidates.length; i++) { expect(candidates[i]!.period).toBeGreaterThan(0); // Two candidates five percent apart in period are one loop read at two neighbouring points // of a grid coarser than the difference, which is the same thing said twice in a list the // listener has to walk. for (const other of candidates.slice(i + 1)) { const a = candidates[i]!; const r = a.period / other.period; // Near-equal periods are one loop read at two neighbouring points of a grid coarser than // the difference — unless they sit at different places in the song, which is the loop's // cycles and is the answer rather than a duplicate of it. Overlap is what makes a // duplicate: the defect this asserts against was four candidates all starting at 1.93s. const overlap = Math.min(a.end, other.end) - Math.max(a.start, other.start); expect( Math.abs(r - 1) > 0.05 || overlap <= 0, `two candidates at ${a.start.toFixed(1)}s/${a.period.toFixed(2)}s and ${other.start.toFixed(1)}s/${other.period.toFixed(2)}s are one loop in one place`, ).toBe(true); } } expect(candidates[0]!.period).toBeCloseTo(24, 0); }); it("offers the repeating beat at bars across the whole song, not only at the top", () => { // The case a J Dilla instrumental is, and the case the first version of this search failed by // construction: one loop for four minutes means the correlation has no quiet region to be // measured against, every multiple of the loop looks excellent, and a search that quotes one // position per loop tells a listener sitting at two minutes that the loop is at 0:02 — correct // and useless. The regions in the middle are as true as the one at the start, so they are // offered: at one period, because it is one loop, and at positions that do not overlap, // because the same bar twice is not a second answer. const track = loopTrack({ introSec: 2, periodSec: 15, repeats: 14, sampleRate: DEFAULT_SAMPLE_RATE, }); // This is the test that recorded a gap in the grid path, and it recorded the cause wrongly, which // is worth more here than a tidy history. The note beside the pinned version blamed the // ninety-eighth percentile of the lag scores — the comparative threshold does climb to 0.9966 on // the record — and the fix everyone would have written from that note was to the wrong component. // It was the body prior's veto: a candidate whose middle fell outside the novelty curve's body was // deleted the moment any in-body candidate existed, and on a track whose whole middle is one // repeating figure that removed three of the four positions and left the listener the one the // curve happened to favour. The veto now spares siblings the measurement cannot separate from the // one it prefers, and both clocks answer this fixture identically: four positions, one period, // spread through the song. const { candidates } = detect(track.samples, track.sampleRate); expect(candidates.length).toBeGreaterThan(2); for (const c of candidates) expect(c.period).toBeCloseTo(15, 0); const starts = candidates.map((c) => c.start).sort((a, b) => a - b); expect(new Set(starts).size).toBe(starts.length); // Spread through the looped part of the song rather than stacked at one end of it. Where // the first one lands is the material's doing, not the test's: the position at the very top // has the intro in it on this fixture, and an alignment that includes two seconds of unique // material is genuinely worse than one that does not. expect(starts[0]).toBeLessThan(30); expect(starts[starts.length - 1]! - starts[0]!).toBeGreaterThan(30); // What the grid has to promise in its own right: the same loop, at the same length, on the beats, // and the same spread through the song rather than the single position the veto used to leave. const onGrid = detect(track.samples, track.sampleRate, { beatGrid: true }); expect(onGrid.stats?.grid).toBe("beats"); expect(onGrid.candidates.length).toBeGreaterThan(2); for (const c of onGrid.candidates) expect(c.period).toBeCloseTo(15, 0); expect(new Set(onGrid.candidates.map((c) => c.start)).size).toBe(onGrid.candidates.length); }); it("does not offer the same seam at every multiple of itself", () => { const track = loopTrack({ introSec: 20, periodSec: 24, repeats: 7, sampleRate: DEFAULT_SAMPLE_RATE, }); const { candidates } = detect(track.samples, track.sampleRate); const first = candidates[0]!.period; const doubled = candidates.filter((c) => Math.abs(c.period - 2 * first) < 0.5); // The 48-second reading scores the same as the 24-second one, so it is the same loop: it may // survive only if it is genuinely better, which on pasted material it is not. expect(doubled.length).toBe(0); }); it("keeps its answers to a handful", () => { const track = gapLoop({ riffSec: 6, gapSec: 4, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); const { candidates } = detect(track.samples, track.sampleRate, { floor: 0.55 }); expect(candidates.length).toBeLessThanOrEqual(8); }); }); describe("the inline path is the worker's path", () => { it("answers the same question twice, identically", () => { // jsdom has no Worker, so every test in this file runs the inline fallback. The worker calls // the same `search` on the same series, so the property worth asserting is that nothing here // depends on which thread it ran on: same samples in, byte-identical regions out. const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); const series = fingerprint(track.samples, track.sampleRate); const a = search(series, {}); const b = search(series, {}); expect(b.candidates).toEqual(a.candidates); expect(b.stats).toEqual(a.stats); const opts: DetectOptions = { trim: false, body: false }; // Same inputs, same answer — and the inputs now include the audio, which is what decides the // clock. Comparing a search that was handed samples against one that was handed only a fingerprint // would not be testing thread-equivalence at all, it would be testing whether two different // questions have the same answer, and they do not: one of them can find the beats and the other // cannot even ask. expect( searchSeries(series, { samples: track.samples, sampleRate: track.sampleRate }, opts) .candidates, ).toEqual(detect(track.samples, track.sampleRate, opts).candidates); // And the frame-only path still answers, on its own clock, when the grid is not available to it. const frames = search(series, opts).candidates; expect(frames.length).toBeGreaterThan(0); expect(frames[0]!.bars).toBeUndefined(); }); }); /* --------------------------------------------------------------------------- The same search, handed rows that are beats. --------------------------------------------------------------------------- */ describe("the tempo and the first beat ride the answer", () => { const track = loopTrack({ periodSec: 24, repeats: 6, sampleRate: DEFAULT_SAMPLE_RATE }); it("is answered by the handed grid's clock when there is one", () => { // A grid handed in from outside the file — which is what the neural tracker delivers — // owns the clock wholesale: the BPM, the phase and the beat rows are *its* measurements, // not the dynamic program's, and the assertion pins exactly that swap. The tempo here // (125) is deliberately not this track's own DP tempo: an answer agreeing with the DP // would not prove whose clock answered. const series = fingerprint(track.samples, track.sampleRate); const beats = Float32Array.from({ length: 40 }, (_, i) => 0.24 + i * 0.48); const downbeats = Float32Array.from({ length: 10 }, (_, i) => 0.24 + i * 4 * 0.48); const audio = { samples: track.samples, sampleRate: track.sampleRate, modelBeats: beats, modelDownbeats: downbeats, }; // The subject first: the swap itself, before any search policy gets a vote. const subject = beatSubject(series, audio)!; expect(subject.grid).toBe("beats"); expect(subject.bpm).toBeCloseTo(125, 0); expect(subject.beatAt).toBeCloseTo(0.24, 2); expect(subject.phaseSource).toBe("model"); expect(subject.times!.length).toBe(beats.length); expect(subject.times![0]).toBeCloseTo(0.24, 6); // And through the search, on a question every clock refuses: the frames take the verdict, // but the clock survives the graft — the tempo, the phase and the beat times the bar // pulses to all stay the model's. const answer = searchSeries(series, audio, { floor: 1.1 }); expect(answer.stats?.grid).toBe("frames"); expect(answer.stats?.bpm).toBeCloseTo(125, 0); expect(answer.stats?.beatAt).toBeCloseTo(0.24, 2); expect(answer.beats?.length).toBe(beats.length); expect(answer.beats?.[0]).toBeCloseTo(0.24, 6); }); it("refuses a handed grid that could not keep time", () => { // The fallback is not deference: a grid at 1200 BPM, or one that goes backwards, is the // model saying nothing useful, and the dynamic program — which measures rather than // recognises — answers the whole question instead. "Handed in" must never mean "believed". const series = fingerprint(track.samples, track.sampleRate); const audio = { samples: track.samples, sampleRate: track.sampleRate }; const plain = searchSeries(series, audio, {}); const nonsense = searchSeries( series, { ...audio, modelBeats: Float32Array.from({ length: 40 }, (_, i) => 20 - i * 0.48) }, {}, ); expect(nonsense.stats?.bpm).toBe(plain.stats?.bpm); const tooFast = searchSeries( series, { ...audio, modelBeats: Float32Array.from({ length: 40 }, (_, i) => i * 0.05) }, {}, ); expect(tooFast.stats?.bpm).toBe(plain.stats?.bpm); const tooShort = searchSeries( series, { ...audio, modelBeats: Float32Array.from({ length: 5 }, (_, i) => i * 0.5) }, {}, ); expect(tooShort.stats?.bpm).toBe(plain.stats?.bpm); }); it("says the BPM the grid was built on, and where it started", () => { const on = detect(track.samples, track.sampleRate, { beatGrid: true }); expect(on.stats?.grid).toBe("beats"); expect(on.stats?.bpm).toBeGreaterThan(40); expect(on.stats?.bpm).toBeLessThan(240); expect(on.stats?.beatAt).toBeTypeOf("number"); expect(on.stats!.beatAt!).toBeGreaterThanOrEqual(0); }); it("keeps the tempo when the frames take a question the grid could not answer", () => { // With a floor nothing can beat, both clocks refuse and the answer that comes back is the // frame search's — whose own rows have no tempo in them. The grid's measurement belongs to // the file, though, not to the clock that was rejected, so it has to survive the fallback // rather than leave with it: this is the difference between a static number and a wrong one // on every track whose loop the grid refused to sign off on. const series = fingerprint(track.samples, track.sampleRate); const audio = { samples: track.samples, sampleRate: track.sampleRate }; const on = searchSeries(series, audio, {}); const refused = searchSeries(series, audio, { floor: 1.1 }); expect(on.stats?.grid).toBe("beats"); expect(refused.stats?.grid).toBe("frames"); expect(refused.not).toBeDefined(); expect(refused.stats?.bpm).toBe(on.stats?.bpm); expect(refused.stats?.beatAt).toBe(on.stats?.beatAt); // The grid itself rides along — the pulse anchors on the true intervals, not the mean, so a // fallback that kept the tempo and dropped the times would pulse on the average again. expect(refused.beats?.length).toBe(on.beats?.length); expect(Array.from(refused.beats!)).toEqual(Array.from(on.beats!)); }); it("says nothing about tempo when no grid was computed", () => { // Silence here is the assertion: a frame-grid answer inventing a tempo from a 46 ms hop is // the exact thing the grid exists to make impossible, and a number that is not a measurement // would pulse the title to a metronome nobody heard. const frames = search(fingerprint(track.samples, track.sampleRate), {}); expect(frames.stats?.grid).toBe("frames"); expect(frames.stats?.bpm).toBeUndefined(); expect(frames.stats?.beatAt).toBeUndefined(); expect(frames.beats).toBeUndefined(); }); }); describe("searching on the beat grid", () => { const BEAT = 0.64; // 93.75 BPM, which is what the record turned out to be /** Chords around a circle of fifths, far enough apart that a bar of one cannot be confused with another. */ const CHORDS = [ [0, 4, 7], [2, 6, 10], [7, 11, 2], [9, 0, 4], [5, 9, 0], [10, 2, 5], ]; const row = (i: number): number[] => { const v = Array.from({ length: 12 }, () => 0); for (const c of CHORDS[i % CHORDS.length]!) v[c] = 1; const norm = Math.sqrt(v.reduce((acc, x) => acc + x * x, 0)); return v.map((x) => x / norm); }; /** A track of `blocks` exact repetitions of a `lag`-beat figure, on the beat grid. */ function grid(lag: number, blocks: number, phase = 0, jitter = 0): SearchSubject { const frames = lag * blocks; const values = new Float32Array(frames * 12); for (let b = 0; b < frames; b++) { const v = row(b % lag); for (let c = 0; c < 12; c++) values[b * 12 + c] = v[c]!; } const times = Float32Array.from( { length: frames }, (_, b) => b * BEAT + (jitter && b % 2 ? jitter : 0), ); return { values, frames, frameSec: BEAT, times, rowsPerBar: 4, phase, barMargin: 0.2, phaseSource: "harmony", audible: frames, weights: new Float32Array(12).fill(1), grid: "beats", }; } const opts: DetectOptions = { trim: false, body: false }; it("says how long the loop is in bars", () => { const fourBars = search(grid(16, 3), opts); expect(fourBars.not).toBeUndefined(); const c = fourBars.candidates[0]!; expect(c.bars).toBeCloseTo(4, 6); expect(c.onBar).toBe(true); expect(fourBars.stats?.grid).toBe("beats"); expect(fourBars.stats?.frameSec).toBeCloseTo(BEAT, 6); // A period that is not a number of bars cannot have both edges on a downbeat whatever the search // does with it, and says so: this is the `false` of the three-state flag, the case where the bar // was read and the region does not land on it. const threeAndAHalf = search(grid(14, 3), opts); expect(threeAndAHalf.candidates[0]!.bars).toBeCloseTo(3.5, 6); expect(threeAndAHalf.candidates[0]!.onBar).toBe(false); }); it("moves a family it cannot hear the difference in onto the downbeat", () => { // Same audio, a different idea of where the bar begins. The old answer was to leave the region // where the correlation put it and attach a flag saying it was in the wrong place — a flag that // sat sixth in a sort nobody consults and was not read at all by the key that arms a loop, so the // listener heard a loop arriving on beat three and the chip said `off-bar`. The new answer moves // the family onto the one. Nothing about the measurement is spent to do it: the agreement is the // same number, the period is the same number, and both edges moved together so the length is too. const aligned = search(grid(16, 3), opts); const c = aligned.candidates[0]!; const offPhase = search(grid(16, 3, 2), opts); const moved = offPhase.candidates[0]!; expect(moved.onBar).toBe(true); expect(moved.start).toBeCloseTo(c.start + 2 * BEAT, 6); expect(moved.period).toBeCloseTo(c.period, 6); // Five digits, not six: the difference of two boundaries is a difference of two Float32 reads of // the times table, and the sixth digit is representation rather than music. expect(moved.end - moved.start).toBeCloseTo(c.end - c.start, 5); expect(moved.r).toBeCloseTo(c.r, 6); expect(offPhase.stats?.barMoved).toBeGreaterThan(0); // And the tiling survives, which is the reason the correction is the family's rather than each // region's own: positions of a body that repeats are taken exactly a period apart, so a region // that slides alone slides onto its neighbour and the listener is offered one loop in one place // twice. Every region moved together, so every pair is as far apart as the walk left them. for (const a of offPhase.candidates) { expect(a.onBar).toBe(true); for (const b of offPhase.candidates) { if (a === b) continue; expect(Math.min(a.end, b.end) - Math.max(a.start, b.start)).toBeLessThanOrEqual(0); } } }); it("leaves a boundary alone when the measurement was paying attention to it", () => { // The bar settles ties the agreement declares and has no other claim: the offset is refused once // the copies agree worse at the bar-aligned row than where the search stood, by more than the // indifference the position walk itself uses. The fill at rows 32–33 is what makes the two rows // tellable: the window the search stands in compares rows 0–15 with 16–31 and never touches them, // and the window a two-beat step would move the comparison onto reaches to row 33 and does. const frames = 52; const lag = 16; const values = new Float32Array(frames * 12); for (let b = 0; b < frames; b++) { const wrecked = b === 32 || b === 33; const v = row(wrecked ? 7 : b % lag); for (let c = 0; c < 12; c++) values[b * 12 + c] = v[c]!; } const result = search( { values, frames, frameSec: BEAT, times: Float32Array.from({ length: frames }, (_, b) => b * BEAT), rowsPerBar: 4, phase: 2, // so the region the search finds at row 0 stands on beat three barMargin: 0.2, phaseSource: "harmony", audible: frames, weights: new Float32Array(12).fill(1), grid: "beats", }, { ...opts, trim: false }, ); const c = result.candidates[0]!; expect(c.start).toBeCloseTo(0, 6); // held its ground rather than stepped onto the bar expect(c.onBar).toBe(false); expect(result.stats?.barMoved).toBe(0); }); it("copies the subject's tempo and first beat into its stats", () => { // The pulse in the bar reads these two numbers off the answer, so the copy from subject to // stats is the seam worth asserting: a search that measured a grid and reported no tempo // would leave the bar's number static on exactly the tracks that have one. const withTempo: SearchSubject = { ...grid(16, 3), bpm: 93.75, beatAt: 0.25 }; const r = search(withTempo, opts); expect(r.stats?.grid).toBe("beats"); expect(r.stats?.bpm).toBe(93.75); expect(r.stats?.beatAt).toBe(0.25); }); it("quotes a boundary as a beat rather than as a number of seconds", () => { const result = search(grid(16, 4), { ...opts, trim: true }); for (const c of result.candidates) { // A whole number of beats, to the precision the times are actually stored in: the grid is a // Float32Array, so 1e-7 of a beat is representation, not slop. The contrast the assertion is // drawing is with the frame grid, where a boundary is a multiple of 0.093 and can sit anywhere // in the middle of a beat — which is the gap this whole line of work exists to close. for (const t of [c.start, c.end]) { expect(Math.abs(t / BEAT - Math.round(t / BEAT))).toBeLessThan(1e-5); } } }); it("follows an uneven grid, because the beats are where the audio says they are", () => { // µ-timing, which is the Dilla case: the grid is not evenly spaced, so a search that divided // seconds by a mean would put boundaries at places the grid has no row for. const subject = grid(16, 3, 0, 0.03); const result = search(subject, opts); expect(result.candidates.length).toBeGreaterThan(0); const times = Array.from(subject.times!); for (const c of result.candidates) { expect(times.some((t) => Math.abs(t - c.start) < 1e-9)).toBe(true); expect(times.some((t) => Math.abs(t - c.end) < 1e-9)).toBe(true); } }); it("breaks a tie it cannot hear between the region on the downbeat and the one that is not", () => { // A figure that repeats every two beats also repeats every fourteen and every sixteen, so both // periods measure exactly the same and the search has no basis to prefer one — except that // sixteen is four bars and fourteen is three and a half, which is the basis the listener has. // // This is the only construction that can put the tie-break on trial, and finding that out was the // point of writing the test. Inside one family the flag cannot vary: positions of a family are // whole lags apart, so a lag that is a number of bars keeps every position equally on the bar and // a lag that is not keeps every position equally off it. Only two competing periods, one a whole // number of bars and one not, can ever disagree — and a two-beat motif is how you get both at // once. const motif = 2; const frames = 60; const values = new Float32Array(frames * 12); for (let b = 0; b < frames; b++) { const v = row(b % motif); for (let c = 0; c < 12; c++) values[b * 12 + c] = v[c]!; } const result = search( { values, frames, frameSec: BEAT, times: Float32Array.from({ length: frames }, (_, b) => b * BEAT), rowsPerBar: 4, phase: 0, barMargin: 0.2, phaseSource: "harmony", audible: frames, weights: new Float32Array(12).fill(1), grid: "beats", }, opts, ); const offered = result.candidates; expect(offered.length).toBeGreaterThan(2); expect(offered.some((c) => c.onBar)).toBe(true); expect(offered.some((c) => !c.onBar)).toBe(true); // The rule under test, stated as an invariant rather than as an expected list: no region off the // bar may be offered ahead of one on it while their agreement is the same number. for (let i = 0; i < offered.length; i++) { for (let j = i + 1; j < offered.length; j++) { if (offered[i]!.r === offered[j]!.r) { expect(Number(offered[i]!.onBar)).toBeGreaterThanOrEqual(Number(offered[j]!.onBar)); } } } }); it("keeps a frame-grid answer silent about bars it knows nothing about", () => { const result = search(grid(16, 3), opts); expect(result.candidates[0]!.bars).toBeCloseTo(4, 6); const asFrames = search(subjectOfFrames(frameSeriesOf(grid(16, 3))), opts); expect(asFrames.candidates[0]!.bars).toBeUndefined(); // Absent rather than `false`. `false` is a claim about where the seam falls in a bar, and a grid // of 46 ms rows has no bar for a seam to fall in — the same reason `bars` itself is absent here, // which `onBar` was the only field not to have learned. expect(asFrames.candidates[0]!.onBar).toBeUndefined(); expect(asFrames.stats?.grid).toBe("frames"); }); it("is silent about the bar when it never found where beat one was", () => { // The third abstention, and the one the flag used to lie about. `barPhase` returns `source: "none"` // when neither the harmonic discontinuities nor the drum cue cleared the indifference threshold — // its own doc tells the caller to treat the phase as a coin — and `phase` is then whatever row the // grid happened to start on. Reading a downbeat off that is reading a coin flip, and every // candidate used to come back `onBar: true` or `false` as though it had been measured. const coin: SearchSubject = { ...grid(16, 3), phase: 2, phaseSource: "none" }; const result = search(coin, opts); expect(result.candidates.length).toBeGreaterThan(0); for (const c of result.candidates) expect(c.onBar).toBeUndefined(); // Including the region that a coin flip would have called off-bar, and the one it would have // called on-bar: the flag abstains for the whole track, not region by region. expect(result.stats?.barMoved).toBe(0); // The bar's own correction is gated on the same test, and for the same reason — moving a boundary // to satisfy an alignment nobody measured would trade a measurement's mistake for a prior's. expect( search({ ...grid(16, 3, 2), phaseSource: "none" }, opts).candidates[0]!.start, ).toBeCloseTo(0, 6); }); it("ranks an unmeasured bar in the middle rather than at the bottom", () => { // `undefined` read as `false` would put "this search had no bar to align to" below "the seam lands // in the middle of one": a candidate for never having been measured ranked under a candidate that // was measured and found wanting. It sits in the middle instead, exactly as the `seam` key above it // sits in the middle for a loop with nothing after it. expect(barRank(undefined)).toBeGreaterThan(barRank(false)); expect(barRank(undefined)).toBeLessThan(barRank(true)); const known = search(grid(16, 3, 2), opts).candidates.map((c) => barRank(c.onBar)); expect(known.every((k) => k === 1)).toBe(true); }); }); /** The same matrix on the frame clock, for the test that checks the bar fields stay absent. */ function frameSeriesOf(subject: SearchSubject): ChromaSeries { return { values: subject.values, frames: subject.frames, // The same rows on the frame clock. The clock's rate is the beat's own so the period range still // fits the track: what is under test is that a grid without bars says nothing about bars, not the // length of the clip. frameSec: 0.64, audible: subject.audible, weights: subject.weights, binHz: 1, }; } /* --------------------------------------------------------------------------- The wrap: does the loop survive its own cut. --------------------------------------------------------------------------- */ describe("the seam", () => { const BEAT = 0.64; const CHORDS = [ [0, 4, 7], [2, 6, 10], [7, 11, 2], [9, 0, 4], [5, 9, 0], [10, 2, 5], [1, 5, 8], [3, 7, 11], ]; const chord = (i: number): number[] => { const v = Array.from({ length: 12 }, () => 0); for (const c of CHORDS[i % CHORDS.length]!) v[c] = 1; const norm = Math.sqrt(v.reduce((acc, x) => acc + x * x, 0)); return v.map((x) => x / norm); }; /** `blocks` exact repetitions of a `lag`-beat figure, optionally with some rows replaced. */ function loop( lag: number, blocks: number, opts: { quiet?: number[]; replaced?: { rows: number[]; chord: number } } = {}, ): SearchSubject { const frames = lag * blocks; const values = new Float32Array(frames * 12); for (let b = 0; b < frames; b++) { const row = opts.replaced && opts.replaced.rows.includes(b) ? opts.replaced.chord : b % lag; const v = chord(row); for (let c = 0; c < 12; c++) values[b * 12 + c] = v[c]!; } const energy = Array.from({ length: frames }, (_, b) => (opts.quiet?.includes(b) ? 0 : 1)); return { values, frames, frameSec: BEAT, times: Float32Array.from({ length: frames }, (_, b) => b * BEAT), rowsPerBar: 4, phase: 0, barMargin: 0.2, phaseSource: "harmony", audible: frames, weights: new Float32Array(12).fill(1), grid: "beats", energy: Float32Array.from(energy), }; } const opts: DetectOptions = { trim: false, body: false }; it("calls a perfect loop seamless, which is what the number has to do to be believed", () => { const result = search(loop(16, 3), opts); expect(result.candidates.length).toBeGreaterThan(0); for (const c of result.candidates) { expect(c.seam).toBeDefined(); expect(c.seam!).toBeGreaterThan(0.98); } }); it("says nothing about a wrap the track does not have", () => { // A loop that runs to the last row has no continuation in the record to compare against, and the // honest answer is the absence of a measurement rather than a score that would silently rank it // against candidates that were measured. const result = search(loop(16, 2), { ...opts, maxPeriodSec: 12 }); const last = result.candidates.find((c) => Math.abs(c.end / BEAT - 32) < 0.01); if (last) expect(last.seam).toBeUndefined(); expect(result.candidates.length).toBeGreaterThan(0); }); it("notices that the loop walks back in where the record had gone quiet", () => { // Same rows, same agreement, one difference: the four rows the loop is about to replay over are // silent in the record. Chroma cannot see this at all — a silence and a unison drone fold to // similar vectors — which is exactly why Shi and Mysore's RMS term is in the score. const loud = search(loop(16, 3), opts); const quiet = search(loop(16, 3, { quiet: [32, 33, 34, 35] }), opts); const at = (r: typeof loud, sec: number): number => { const c = r.candidates.find((x) => Math.abs(x.start - sec) < 0.01); return c?.seam ?? -1; }; expect(at(quiet, 16 * BEAT)).toBeLessThan(at(loud, 16 * BEAT) - 0.05); }); it("offers the region that wraps invisibly first, even when it starts later", () => { // Two positions of one family, both exact copies, so their agreement is the same float and the // start-ascending order the search would otherwise produce is [0, 16]. Silencing the rows that // follow the first position's start is enough to make the second one the better loop, and the // order has to notice. const result = search(loop(16, 3, { quiet: [0, 1, 2, 3] }), opts); const starts = result.candidates.map((c) => c.start); expect(starts.length).toBeGreaterThanOrEqual(2); expect(starts[0]).toBeCloseTo(16 * BEAT, 6); expect(starts[1]).toBeCloseTo(0, 6); expect(result.candidates[0]!.seam!).toBeGreaterThan(result.candidates[1]!.seam!); }); it("is a different measurement from the repetition, and says so when they disagree", () => { // One row of the figure, replaced by a chord it never uses: the region still repeats almost // perfectly, so `r` barely moves, but that row sits in the window the loop replays over the // record at its own wrap, and the seam collapses over it. A detector with only `r` would call this a loop; a listener // would call it a click. // The period range is pinned to the figure itself: a chord table of eight makes the sixteen-row // figure repeat every eight as well, and lag twenty-four would win the search while its own // follower windows sat nowhere near the corrupted row. Testing a measurement means not leaving it // a way to dodge the thing under test. const span = { ...opts, minPeriodSec: 10, maxPeriodSec: 14 }; const broken = search(loop(16, 3, { replaced: { rows: [17], chord: 7 } }), span); const clean = search(loop(16, 3), span); expect(broken.candidates.length).toBeGreaterThan(0); const worst = broken.candidates.reduce( (lo, c) => ((c.seam ?? 1) < (lo.seam ?? 1) ? c : lo), broken.candidates[0]!, ); const cleanMin = Math.min(...clean.candidates.map((c) => c.seam ?? 1)); expect(worst.seam!).toBeLessThan(cleanMin - 0.05); // The whole point of the pair: the repetition still cleared the floor for that region, so a // detector holding only `r` would have armed it and a listener would have heard the click. The // seam reorders, it does not veto — the same discipline the body prior learned the hard way. expect(worst.r).toBeGreaterThanOrEqual(0.93); }); }); /* --------------------------------------------------------------------------- The repair: where the end of the loop belongs, once the copies have drifted. --------------------------------------------------------------------------- */ describe("the end alignment", () => { const chord = (i: number): number[] => { const v = Array.from({ length: 12 }, () => 0); const roots = [0, 2, 5, 7, 10, 3, 8, 1]; for (const c of [roots[i % roots.length]!, (i % 4) + 1, (i % 3) + 6]) v[c] = 1; const norm = Math.sqrt(v.reduce((acc, val) => acc + val * val, 0)); return v.map((val) => val / norm); }; /** `rows` of chord material, with the block beginning at `at` slid `shift` rows early. */ function matrix(rows: number, at = 0, shift = 0): Float32Array { const values = new Float32Array(rows * 12); for (let r = 0; r < rows; r++) { const src = r >= at ? r - shift : r; const v = chord(src); for (let c = 0; c < 12; c++) values[r * 12 + c] = v[c] ?? 0; } return values; } const W = 4; it("slides the end onto the row the record actually continues from", () => { // The follower of the end is the follower of the start, one row late: the copy drifted by a // hair over the length of the track, which is exactly what four minutes of a human being does // and exactly what a period reported as a mean cannot express. The end belongs one row along. const lag = 16; const rows = 64; const shifted = matrix(rows, lag, 1); expect(bestEndShift(shifted, rows, 0, lag, 2, W, undefined, 4)).toBe(1); }); it("leaves a boundary that is already right where it is", () => { const lag = 16; const rows = 64; expect(bestEndShift(matrix(rows), rows, 0, lag, 2, W, undefined, 4)).toBe(0); }); it("refuses to move on a tie, which is what keeps a plateau from picking a boundary", () => { // A row of silence agrees with every other row of silence, so every position scores identically // and an aligner without a margin would emit whichever offset the arithmetic happened to reach // first — a boundary chosen by nothing, dressed as a measurement. const rows = 48; const blank = new Float32Array(rows * 12); expect(bestEndShift(blank, rows, 0, 16, 2, W, undefined, 4)).toBe(0); }); it("never leaves the grid, the track, or half the loop behind", () => { const rows = 64; const lag = 16; for (const shift of [-2, -1, 0, 1, 2]) { const d = bestEndShift(matrix(rows, lag, shift), rows, 0, lag, 2, W, undefined, 4); expect(Math.abs(d)).toBeLessThanOrEqual(2); expect(Number.isInteger(d)).toBe(true); expect(lag + d).toBeLessThan(rows); } // The floor: an end may not be pulled back so far that the loop stops being a loop. The bound is // asked for explicitly here rather than inferred from the number that came back, because the // direction the aligner chooses is the material’s business — this asserts the one thing that is // the function’s own promise. const floored = bestEndShift(matrix(rows, lag, -2), rows, 0, lag, 2, W, undefined, lag); expect(floored).toBeGreaterThanOrEqual(0); }); it("counts a whole row on the beat grid, because that is the finest thing a grid has", () => { // The integer-ness is the contract with step 3: the repair may move a boundary to another beat // and nowhere in between, or the alignment would undo the reason the search runs on beats. const d = bestEndShift(matrix(64, 16, 1), 64, 0, 16, 1, W, undefined, 4); expect(Number.isInteger(d)).toBe(true); expect(d).toBe(1); }); }); describe("the ranking's own numbers", () => { const BEAT = 0.64; /** * Chords a row apart, one note apart. * * The detector's other fixtures use chord tables whose members are unrelated to each other, which is * the right shape for asking "does this repeat" and the wrong shape for asking "what happens at the * seam": with everything equidistant from everything, every adjacency in the file is as surprising as * every other and a measurement of surprise has nothing to say. A chain of triads that moves one note * at a time has graded similarity — neighbours are two thirds alike, rows far apart in the chain are * nothing alike — and that gradient is what `wrap` reads. */ const CHAIN: number[][] = (() => { const out: number[][] = []; let cur = [0, 4, 7]; for (let i = 0; i < 64; i++) { out.push(cur); if (i === 64 - 1) break; const next = [...cur]; const move = i % 3; next[move] = (next[move]! + 1) % 12; if (new Set(next).size !== 3) next[move] = (next[move]! + 5) % 12; if (new Set(next).size !== 3) next[move] = (next[move]! + 2) % 12; cur = next; } return out; })(); /** * A row of the matrix, with the dent the tests ask for. * * `1` moves one note of the chord, which is two-thirds alike: agreement under the run detector's gate * and a visible wound in the mean at the same time. `2` replaces the chord outright, which is the * disagreement that a window mean survives and a run detector cuts the region at. */ const rowVec = (i: number, width = 12, dent = 0): number[] => { const v = Array.from({ length: 12 }, () => 0); const c = CHAIN[((i % CHAIN.length) + CHAIN.length) % CHAIN.length]!; for (const p of c) v[p] = 1; if (dent === 1) { const moved = c[0]!; v[moved] = 0; let extra = 0; while (extra === moved || v[extra] !== 0) extra++; v[extra % 12] = 1; } if (dent === 2) { for (const p of c) v[p] = 0; v[(c[0]! + 5) % 12] = 1; v[(c[0]! + 7) % 12] = 1; v[(c[0]! + 9) % 12] = 1; } for (let c = 12; c < width; c++) v[c] = v[c - 12]!; const norm = Math.sqrt(v.reduce((a, x) => a + x * x, 0)); return v.map((x) => x / norm); }; function track( figure: number[], repeats: number, opts: { width?: number; prefix?: number[]; dents?: Record } = {}, ): SearchSubject { const width = opts.width ?? 12; const body = [...(opts.prefix ?? []), ...Array.from({ length: repeats }, () => figure).flat()]; const frames = body.length; const values = new Float32Array(frames * width); body.forEach((row, b) => { const v = rowVec(row, width, opts.dents?.[b] ?? 0); for (let c = 0; c < width; c++) values[b * width + c] = v[c]!; }); return { values, frames, width, frameSec: BEAT, times: Float32Array.from({ length: frames }, (_, b) => b * BEAT), rowsPerBar: 4, phase: 0, barMargin: 0.2, phaseSource: "harmony", audible: frames, weights: new Float32Array(width).fill(1), grid: "beats", }; } const F16 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]; // four bars, no period of its own const PAL = [0, 1, 2, 3, 4, 5, 6, 7, 6, 5, 4, 3, 2, 1]; // …and the same material, walking back const opts: DetectOptions = { body: false, minPeriodSec: 4, trimMinSec: 2 }; it("says which of two 0.99s is evidence, by measuring one against the rest of the file", () => { // Two tracks, the same agreement between the same two copies. In the first the loop is the whole // track, so a lag picked at random anywhere also resembles itself and 0.99 is the ordinary state of // this file. In the second the same loop sits inside material with nothing to do with it, and the // same 0.99 is a distance above the background instead of a height — which is the only reading of // 0.99 that means anything on the real tracks, whose typical lag scores 0.955 to 0.998. const alone = search(track(F16, 4), opts); const buried = search( track(F16, 2, { prefix: [20, 22, 24, 26, 21, 23, 25, 27, 28, 30, 32, 34, 29, 31, 33, 35], }), opts, ); const best = (r: typeof alone) => r.candidates.reduce((m, c) => Math.max(m, c.contrast ?? 0), 0); expect(alone.candidates.length).toBeGreaterThan(0); expect(buried.candidates.length).toBeGreaterThan(0); expect(best(buried)).toBeGreaterThan(0.6); expect(best(alone)).toBeLessThan(0.2); }); it("notices a wrap that lands a long way from where the music left off", () => { // The same material, the same perfect copies, the same `r` to the last digit. The palindrome walks // up the chain and back down, so the loop returns to where it began by the same one-note step the // rest of it is made of. The rising figure reaches the top of the chain and jumps back to the // bottom, and nothing inside the loop ever does anything that abrupt. That difference is the whole // of what a listener calls a click, and `r` cannot see it at any resolution. const walking = search(track(PAL, 4), opts); const rising = search(track(F16.slice(0, 8), 4), opts); const best = (r: typeof walking) => r.candidates.reduce((m, c) => Math.max(m, c.wrap ?? 0), 0); expect(walking.candidates.length).toBeGreaterThan(0); expect(rising.candidates.length).toBeGreaterThan(0); expect(best(walking)).toBeGreaterThan(best(rising) + 0.5); }); it("refuses an agreement that holds for less than two bars", () => { // Three quarters of one copy of a four-bar loop disagrees with the other copy at the gate: the best // run the two copies sustain is one bar, which is not a loop. The seconds floor cannot say this at // 94 BPM, where a bar is 2.6 s and the four-second minimum is a bar and a half — the unit the // promise is made in has to be the bar, because "at least two bars" is the thing being promised. const dents = { 20: 1, 25: 1, 30: 1 }; expect(search(track(F16, 3, { dents }), { ...opts, minBars: 2 }).candidates).toEqual([]); const allowed = search(track(F16, 3, { dents }), { ...opts, minBars: 1 }).candidates; expect(allowed.length).toBeGreaterThan(0); // …and what it allows is the run that did sustain, which is under the two bars the other setting // asked for: the same measurement's other answer, arrived at by asking in the other unit. expect(allowed[0]!.end - allowed[0]!.start).toBeLessThan(2 * 4 * BEAT); }); it("keeps a loop whole across the bar the copies disagree on, when the path is scoring", () => { // One row of one copy replaced by a chord it never uses. The window mean survives it, and then the // run detector cuts the region at it — which is the complaint this whole exchange is about: the // loop the listener hears is four bars and the region they are handed is eleven rows of it. The // path pays for the row instead of stopping at it, says how much it paid, and still calls the // region four bars. const dented = track(F16, 3, { dents: { 20: 2 } }); const windowed = search(dented, { ...opts, path: false }).candidates[0]!; const walked = search(dented, { ...opts, path: true }).candidates[0]!; const period = 16 * BEAT; expect(windowed.end - windowed.start).toBeLessThan(period - BEAT); expect(walked.end - walked.start).toBeCloseTo(period, 6); expect(walked.coverage!).toBeGreaterThanOrEqual(15 / 16 - 0.01); expect(walked.coverage!).toBeLessThan(1); }); it("searches a matrix wider than pitch class, which is what an embedding is", () => { // Twelve is the width of chroma and nothing else. The search compares rows, and a row that comes // from a learned encoder — or from chroma concatenated with one — is as far as this module gets to // say how wide it is. Same music at twice the width, same answer, because the cosine between two // rows did not change and only the stride through them did. const narrow = search(track(F16, 4, { width: 12 }), opts).candidates[0]!; const wide = search(track(F16, 4, { width: 24 }), opts).candidates[0]!; expect(wide.start).toBeCloseTo(narrow.start, 6); expect(wide.period).toBeCloseTo(narrow.period, 6); expect(wide.r).toBeCloseTo(narrow.r, 6); }); it("counts lags when a percentile has no room to be one", () => { // A short file has few lags — a couple of dozen on the fixture below — and the 98th percentile of // twenty-two values is the value with one above it, so on a coarse clock or a short file // `tailQuantile: 0.98` is not a percentile at all: it is "be the best lag in the file". `tailLags` // is the floor that turns it back into a count, and it is off by default — see `TAIL_LAGS` for what // turning it on did to these fixtures — so this asserts the mechanism exists and says what it claims. const subject = track(F16, 3); const asked = { ...opts, floor: 0.5, minPeriodSec: 2, tailQuantile: 0.98 }; const percentile = search(subject, { ...asked, tailLags: 0 }).stats!; const counted = search(subject, { ...asked, tailLags: 8 }).stats!; // What was asked for stays reported as such, on both runs; what was *spent* is the tail, and the // floor brought it down. expect(percentile.tailQuantile).toBe(0.98); expect(counted.tailQuantile).toBe(0.98); expect(counted.tail).toBeLessThan(percentile.tail); expect(counted.cleared).toBeGreaterThan(percentile.cleared); // The degeneracy, asserted rather than described: with a couple of dozen lags and a 0.98 quantile, // the comparative half of the threshold admits exactly one — whichever one happens to be best. expect(percentile.cleared).toBe(1); }); it("reports what the order was decided by, and cannot refuse a loop with it", () => { // A loop of three and a half bars: not a whole number of bars, so it is the shape a listener // complains about, and the prior's opinion of it is close to zero. It is still a perfect loop and // the search still finds it, which is the promise the whole ranking makes — the prior arbitrates // between answers and never vetoes one, exactly as the body's rule has always been stated. const odd = search(track(PAL, 4), { ...opts, priorWeight: 0.02 }); expect(odd.candidates.length).toBeGreaterThan(0); for (const c of odd.candidates) { expect(c.prior!).toBeLessThan(0.05); expect(c.rank).toBeCloseTo(c.r - 0.02 * (1 - (c.prior ?? 1)), 9); } // Turn the prior off and the order's number is the measurement verbatim, which is the reading that // has to be available for the line above to mean anything. for (const c of search(track(PAL, 4), { ...opts, priorWeight: 0 }).candidates) { expect(c.rank).toBe(c.r); } // And a clock with no bars in it gets no opinion at all, rather than an invented one. for (const c of search({ ...track(F16, 4), rowsPerBar: 0, grid: "frames" }, opts).candidates) { expect(c.prior).toBe(1); } }); }); describe("the sustained path, on its own column", () => { const scratch = pathScratch(64); const run = (xs: number[], gate = 0.8, gapCost = 0.3, gap = 2, minCount = 4): RunPath | null => bestPath(Float32Array.from(xs), xs.length, gate, gapCost, gap, minCount, scratch); it("bridges the row the copies disagree on, and says that it did", () => { // A row at 0.1 is two things at once: below the gate, so a run detector ends the run there, and // cheap enough to be worth crossing rather than paying the bridge price for. The path's answer is // the whole eight rows, seven of them matched — which is the shape of a performed repeat, where // the copies differ somewhere in the middle and nobody stops listening. const r = run([1, 1, 1, 0.1, 1, 1, 1, 1])!; expect(r.start).toBe(0); expect(r.span).toBe(8); expect(r.count).toBe(7); expect(r.mean).toBeCloseTo(1, 6); }); it("stops rather than crossing a stretch it would have to pay for", () => { // Four rows of disagreement is four bridge prices, which is more than the second run is worth: // paying to cross is the right answer for a bar of fill and the wrong one for a bridge, and the // criterion is what decides between them rather than a constant chosen for one of the two cases. const r = run([1, 1, 1, 1, 0.1, 0.1, 0.1, 0.1, 1, 1, 1, 1])!; expect(r.span).toBe(4); expect(r.count).toBe(4); }); it("prefers the agreement that lasts, at equal quality", () => { const r = run([0.95, 0.95, 1, 1, 1, 1, 1, 1, 1, 1])!; expect(r.span).toBe(10); expect(r.count).toBe(10); }); it("refuses a run too short to arm, and a column with nothing in it", () => { // The two refusals are different and both matter: one is a stretch that agrees but not for long // enough, the other is a column whose rows are all below the gate, so no run beats the absence of // a run. A criterion that cannot make the second refusal is a criterion that scores noise. expect(run([0.99, 0.2, 0.99], 0.8, 0.3, 1, 4)).toBeNull(); expect(run([0.2, 0.1, 0.3, 0.2], 0.8, 0.3, 2, 2)).toBeNull(); }); it("taxes the rows it skips and not the rows it walks over", () => { // The one bug this test exists for: a bridge price levied on the *distance* between two matched // rows rather than on the rows *skipped* charges ordinary continuation at the crossing rate, and // no path can then be longer than a row. A column of nothing but agreement has to come back as // the whole column. const r = run([1, 1, 1, 1, 1, 1, 1, 1], 0.8, 0.3, 2, 4)!; expect(r.span).toBe(8); expect(r.count).toBe(8); }); });