@jgorset/beatnet 0.0.0-stage → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/dbn.js ADDED
@@ -0,0 +1,600 @@
1
+ import states from './dbn.json' with { type: 'json' };
2
+ import { getBeatNetWasm } from './wasm.js';
3
+ const compiledCache = new WeakMap();
4
+ function compileHmm(hmm) {
5
+ const cached = compiledCache.get(hmm);
6
+ if (cached)
7
+ return cached;
8
+ const numStates = hmm.initial.length;
9
+ const pointers = Int32Array.from(hmm.pointers);
10
+ const predStates = Int32Array.from(hmm.states);
11
+ const logTransitions = Float64Array.from(hmm.logTransitions);
12
+ const observations = Uint8Array.from(hmm.observations);
13
+ const positions = Float64Array.from(hmm.positions);
14
+ const initial = Float64Array.from(hmm.initial);
15
+ // Detect linear-chain structure (all madmom beat/downbeat HMMs):
16
+ // Each chain starts at a head state, followed by states with single predecessor s-1 and logTransition === 0,
17
+ // observations [obsType repeated k times, then 0...0], and all head predecessors are chain tails.
18
+ const headList = [];
19
+ for (let s = 0; s < numStates; s++) {
20
+ const p0 = pointers[s], p1 = pointers[s + 1];
21
+ if (p1 - p0 !== 1 || predStates[p0] !== s - 1 || logTransitions[p0] !== 0)
22
+ headList.push(s);
23
+ }
24
+ const numChains = headList.length;
25
+ let chainValid = numChains > 0 && numChains < numStates && numChains <= 65535;
26
+ const tailToChain = chainValid ? new Int32Array(numStates).fill(-1) : undefined;
27
+ const heads = chainValid ? Int32Array.from(headList) : undefined;
28
+ const lens = chainValid ? new Uint16Array(numChains) : undefined;
29
+ const obsType = chainValid ? new Uint8Array(numChains) : undefined;
30
+ const obsCount = chainValid ? new Uint8Array(numChains) : undefined;
31
+ let maxLen = 0;
32
+ if (chainValid && tailToChain && heads && lens && obsType && obsCount) {
33
+ for (let c = 0; c < numChains; c++) {
34
+ const start = heads[c];
35
+ const stop = c + 1 < numChains ? heads[c + 1] : numStates;
36
+ const len = stop - start;
37
+ if (len < 1) {
38
+ chainValid = false;
39
+ break;
40
+ }
41
+ lens[c] = len;
42
+ if (len > maxLen)
43
+ maxLen = len;
44
+ tailToChain[stop - 1] = c;
45
+ const firstObs = observations[start];
46
+ if (firstObs !== 1 && firstObs !== 2) {
47
+ chainValid = false;
48
+ break;
49
+ }
50
+ let k = 0;
51
+ while (k < len && observations[start + k] === firstObs)
52
+ k++;
53
+ for (let j = k; j < len; j++) {
54
+ if (observations[start + j] !== 0) {
55
+ chainValid = false;
56
+ break;
57
+ }
58
+ }
59
+ if (!chainValid)
60
+ break;
61
+ obsType[c] = firstObs;
62
+ obsCount[c] = k;
63
+ }
64
+ }
65
+ if (chainValid && tailToChain && heads && lens && obsType && obsCount) {
66
+ let totalPreds = 0;
67
+ for (let c = 0; c < numChains; c++) {
68
+ const h = heads[c];
69
+ const p0 = pointers[h], p1 = pointers[h + 1];
70
+ totalPreds += p1 - p0;
71
+ for (let p = p0; p < p1; p++) {
72
+ if (tailToChain[predStates[p]] < 0) {
73
+ chainValid = false;
74
+ break;
75
+ }
76
+ }
77
+ if (!chainValid)
78
+ break;
79
+ }
80
+ if (chainValid) {
81
+ const predPtrs = new Int32Array(numChains + 1);
82
+ const predChains = new Uint16Array(totalPreds);
83
+ const predLogTrans = new Float64Array(totalPreds);
84
+ const predStartChain = new Uint16Array(numChains);
85
+ const predCount = new Uint16Array(numChains);
86
+ let allContiguous = true;
87
+ let outP = 0;
88
+ for (let c = 0; c < numChains; c++) {
89
+ predPtrs[c] = outP;
90
+ const h = heads[c];
91
+ const pStart = pointers[h], pEnd = pointers[h + 1];
92
+ const deg = pEnd - pStart;
93
+ predCount[c] = deg;
94
+ const firstPred = deg > 0 ? tailToChain[predStates[pStart]] : 0;
95
+ predStartChain[c] = firstPred;
96
+ for (let p = pStart, idx = 0; p < pEnd; p++, idx++) {
97
+ const pc = tailToChain[predStates[p]];
98
+ if (pc !== firstPred + idx)
99
+ allContiguous = false;
100
+ predChains[outP] = pc;
101
+ predLogTrans[outP] = logTransitions[p];
102
+ outP++;
103
+ }
104
+ }
105
+ predPtrs[numChains] = outP;
106
+ let ringStride = 1;
107
+ while (ringStride <= maxLen)
108
+ ringStride <<= 1;
109
+ const compiled = {
110
+ kind: 'chain', numStates, numChains, ringStride, ringMask: ringStride - 1,
111
+ heads, lens, obsType, obsCount, predPtrs, predChains, predLogTrans,
112
+ predStartChain, predCount, allContiguous,
113
+ initial, observations, positions,
114
+ };
115
+ compiledCache.set(hmm, compiled);
116
+ return compiled;
117
+ }
118
+ }
119
+ const compiled = {
120
+ kind: 'general', numStates, states: predStates, pointers, logTransitions, observations, positions, initial,
121
+ };
122
+ compiledCache.set(hmm, compiled);
123
+ return compiled;
124
+ }
125
+ export function decodeDbn(scores, config = states) {
126
+ if (!(scores instanceof Float32Array) || scores.length % 2)
127
+ throw new TypeError('Provide finite interleaved beat and downbeat probabilities.');
128
+ const len = scores.length;
129
+ for (let i = 0; i < len; i++) {
130
+ const v = scores[i];
131
+ if (v - v !== 0)
132
+ throw new TypeError('Provide finite interleaved beat and downbeat probabilities.');
133
+ }
134
+ const threshold = config.threshold;
135
+ let first = -1, last = 0;
136
+ for (let i = 0; i < len; i += 2) {
137
+ const b = scores[i], d = scores[i + 1];
138
+ if (b < 0 || d < 0 || b + d > 1.000001)
139
+ throw new RangeError('Invalid beat probabilities.');
140
+ if (b >= threshold || d >= threshold) {
141
+ const frame = i >>> 1;
142
+ if (first < 0)
143
+ first = frame;
144
+ last = frame + 1;
145
+ }
146
+ }
147
+ if (first < 0)
148
+ return { beats: [], downbeats: [], workingBytes: 0 };
149
+ const frames = last - first;
150
+ const invLambda = 1 / (config.observationLambda - 1);
151
+ const densities = new Float64Array(frames * 3);
152
+ let allD0Finite = true;
153
+ let sumD0 = 0;
154
+ for (let t = 0; t < frames; t++) {
155
+ const idx = (first + t) << 1;
156
+ const beat = scores[idx], downbeat = scores[idx + 1];
157
+ const d0 = Math.log((1 - beat - downbeat) * invLambda);
158
+ densities[3 * t] = d0;
159
+ densities[3 * t + 1] = Math.log(beat);
160
+ densities[3 * t + 2] = Math.log(downbeat);
161
+ if (!Number.isFinite(d0))
162
+ allD0Finite = false;
163
+ else
164
+ sumD0 += d0;
165
+ }
166
+ const compiledHmms = config.hmms.map(compileHmm);
167
+ const useChain = allD0Finite && compiledHmms.every(h => h.kind === 'chain');
168
+ if (useChain) {
169
+ return decodeChainDbn(scores, first, frames, densities, sumD0, compiledHmms);
170
+ }
171
+ return decodeGeneralDbn(scores, first, frames, densities, compiledHmms);
172
+ }
173
+ function decodeChainDbn(scores, first, frames, densities, sumD0, hmms) {
174
+ // Normalized log-emission deltas: delta1[t] = d1[t] - d0[t], delta2[t] = d2[t] - d0[t].
175
+ // Padded with 0s past `frames` so partial head runs at the end of the recording truncate cleanly.
176
+ let maxObsCount = 1;
177
+ for (const h of hmms)
178
+ for (let c = 0; c < h.numChains; c++)
179
+ if (h.obsCount[c] > maxObsCount)
180
+ maxObsCount = h.obsCount[c];
181
+ const pad = maxObsCount;
182
+ const delta1 = new Float64Array(frames + pad);
183
+ const delta2 = new Float64Array(frames + pad);
184
+ for (let t = 0; t < frames; t++) {
185
+ const d0 = densities[3 * t];
186
+ delta1[t] = densities[3 * t + 1] - d0;
187
+ delta2[t] = densities[3 * t + 2] - d0;
188
+ }
189
+ // Precompute head-run sums for k = 1..maxObsCount (typically 1..4) so each chain step is O(1).
190
+ const bonus1 = new Array(maxObsCount + 1);
191
+ const bonus2 = new Array(maxObsCount + 1);
192
+ bonus1[1] = delta1;
193
+ bonus2[1] = delta2;
194
+ for (let k = 2; k <= maxObsCount; k++) {
195
+ const b1 = new Float64Array(frames), b2 = new Float64Array(frames);
196
+ const prev1 = bonus1[k - 1], prev2 = bonus2[k - 1];
197
+ for (let t = 0; t < frames; t++) {
198
+ b1[t] = prev1[t] + delta1[t + k - 1];
199
+ b2[t] = prev2[t] + delta2[t + k - 1];
200
+ }
201
+ bonus1[k] = b1;
202
+ bonus2[k] = b2;
203
+ }
204
+ const block = 500;
205
+ let workingBytes = densities.byteLength + (delta1.byteLength + delta2.byteLength) * maxObsCount;
206
+ let winner;
207
+ const initRing = (hmm, ring) => {
208
+ const { numChains, ringMask, heads, lens, obsType, obsCount, initial } = hmm;
209
+ ring.fill(-Infinity);
210
+ for (let c = 0; c < numChains; c++) {
211
+ const h = heads[c], L = lens[c], k = obsCount[c];
212
+ const delta = obsType[c] === 1 ? delta1 : delta2;
213
+ for (let j = L - 1; j >= 0; j--) {
214
+ const m = L - 2 - j;
215
+ if (m >= frames)
216
+ break;
217
+ let sum = initial[h + j];
218
+ const lastObsU = Math.min(m, k - 2 - j);
219
+ for (let u = 0; u <= lastObsU; u++)
220
+ sum += delta[u];
221
+ const slot = (m - (L - 1)) & ringMask;
222
+ ring[slot * numChains + c] = sum;
223
+ }
224
+ }
225
+ };
226
+ const frameBonus = new Float64Array(maxObsCount * 2);
227
+ const wasm = getBeatNetWasm();
228
+ // DBN arena starts at byte offset 600 KB in the 2 MB WASM memory (FFT uses 0..~420 KB).
229
+ const DBN_ARENA = 614400;
230
+ const runBlockWasm = (hmm, ring, chainBonusIdx, trace) => {
231
+ if (!wasm || !hmm.allContiguous)
232
+ return null;
233
+ const { numChains, ringStride, ringMask, lens, predPtrs, predStartChain, predCount, predLogTrans } = hmm;
234
+ const bonusStride = maxObsCount * 2;
235
+ const align8 = (x) => (x + 7) & ~7;
236
+ let ptr = DBN_ARENA;
237
+ const alloc = (bytes) => { const p = align8(ptr); ptr = p + bytes; return p; };
238
+ const predPtrsP = alloc(predPtrs.byteLength);
239
+ const predStartP = alloc(predStartChain.byteLength);
240
+ const predCountP = alloc(predCount.byteLength);
241
+ const predLogTransP = alloc(predLogTrans.byteLength);
242
+ const lensP = alloc(lens.byteLength);
243
+ const chainBonusIdxP = alloc(chainBonusIdx.byteLength);
244
+ const frameBonusesP = alloc(block * bonusStride * 8);
245
+ const ringP = alloc(ring.byteLength);
246
+ const tailScoresP = alloc(numChains * 8);
247
+ const traceP = trace ? alloc(block * numChains * 2) : -1;
248
+ if (ptr > wasm.mem.buffer.byteLength)
249
+ return null;
250
+ const buf = wasm.mem.buffer;
251
+ new Int32Array(buf, predPtrsP, predPtrs.length).set(predPtrs);
252
+ new Uint16Array(buf, predStartP, predStartChain.length).set(predStartChain);
253
+ new Uint16Array(buf, predCountP, predCount.length).set(predCount);
254
+ new Float64Array(buf, predLogTransP, predLogTrans.length).set(predLogTrans);
255
+ new Uint16Array(buf, lensP, lens.length).set(lens);
256
+ new Uint8Array(buf, chainBonusIdxP, chainBonusIdx.length).set(chainBonusIdx);
257
+ const wFrameBonuses = new Float64Array(buf, frameBonusesP, block * bonusStride);
258
+ const wRing = new Float64Array(buf, ringP, ring.length);
259
+ const wTrace = trace ? new Uint16Array(buf, traceP, block * numChains) : null;
260
+ return {
261
+ wRing,
262
+ wTrace,
263
+ run(tStart, tStop) {
264
+ const count = tStop - tStart;
265
+ for (let i = 0; i < count; i++) {
266
+ const t = tStart + i;
267
+ const base = i * bonusStride;
268
+ for (let k = 1; k <= maxObsCount; k++) {
269
+ wFrameBonuses[base + k - 1] = bonus1[k][t];
270
+ wFrameBonuses[base + maxObsCount + k - 1] = bonus2[k][t];
271
+ }
272
+ }
273
+ wasm.dbnRunBlock(tStart, tStop, numChains, ringMask, predPtrsP, predStartP, predCountP, predLogTransP, lensP, chainBonusIdxP, frameBonusesP, bonusStride, ringP, tailScoresP, traceP);
274
+ },
275
+ };
276
+ };
277
+ for (const hmm of hmms) {
278
+ const { numChains, ringStride, ringMask, heads, lens, obsType, obsCount, predPtrs, predChains, predLogTrans, predStartChain, predCount, allContiguous, initial } = hmm;
279
+ // Time-major layout: ring[slot * numChains + c] keeps per-frame writes contiguous in L1 cache.
280
+ const ring = new Float64Array(ringStride * numChains);
281
+ const tailScores = new Float64Array(numChains);
282
+ const chainBonusIdx = new Uint8Array(numChains);
283
+ for (let c = 0; c < numChains; c++) {
284
+ chainBonusIdx[c] = (obsType[c] === 1 ? 0 : maxObsCount) + (obsCount[c] - 1);
285
+ }
286
+ initRing(hmm, ring);
287
+ const checkpoints = [];
288
+ const wasmRunner = runBlockWasm(hmm, ring, chainBonusIdx, null);
289
+ if (wasmRunner) {
290
+ wasmRunner.wRing.set(ring);
291
+ for (let start = 0; start < frames; start += block) {
292
+ checkpoints.push(wasmRunner.wRing.slice());
293
+ wasmRunner.run(start, Math.min(frames, start + block));
294
+ }
295
+ ring.set(wasmRunner.wRing);
296
+ }
297
+ else {
298
+ for (let t = 0; t < frames; t++) {
299
+ if (t % block === 0)
300
+ checkpoints.push(ring.slice());
301
+ const writeBase = (t & ringMask) * numChains;
302
+ for (let k = 1; k <= maxObsCount; k++) {
303
+ frameBonus[k - 1] = bonus1[k][t];
304
+ frameBonus[maxObsCount + k - 1] = bonus2[k][t];
305
+ }
306
+ for (let c = 0; c < numChains; c++) {
307
+ tailScores[c] = ring[((t - lens[c]) & ringMask) * numChains + c];
308
+ }
309
+ if (allContiguous) {
310
+ for (let c = 0; c < numChains; c++) {
311
+ let best = -Infinity;
312
+ let p = predPtrs[c];
313
+ let pc = predStartChain[c];
314
+ const pEnd = p + predCount[c];
315
+ const pEnd4 = pEnd - 3;
316
+ for (; p < pEnd4; p += 4, pc += 4) {
317
+ const c0 = tailScores[pc] + predLogTrans[p];
318
+ if (c0 > best)
319
+ best = c0;
320
+ const c1 = tailScores[pc + 1] + predLogTrans[p + 1];
321
+ if (c1 > best)
322
+ best = c1;
323
+ const c2 = tailScores[pc + 2] + predLogTrans[p + 2];
324
+ if (c2 > best)
325
+ best = c2;
326
+ const c3 = tailScores[pc + 3] + predLogTrans[p + 3];
327
+ if (c3 > best)
328
+ best = c3;
329
+ }
330
+ for (; p < pEnd; p++, pc++) {
331
+ const cand = tailScores[pc] + predLogTrans[p];
332
+ if (cand > best)
333
+ best = cand;
334
+ }
335
+ ring[writeBase + c] = best + frameBonus[chainBonusIdx[c]];
336
+ }
337
+ }
338
+ else {
339
+ for (let c = 0; c < numChains; c++) {
340
+ let best = -Infinity;
341
+ for (let p = predPtrs[c], pEnd = predPtrs[c + 1]; p < pEnd; p++) {
342
+ const cand = tailScores[predChains[p]] + predLogTrans[p];
343
+ if (cand > best)
344
+ best = cand;
345
+ }
346
+ ring[writeBase + c] = best + frameBonus[chainBonusIdx[c]];
347
+ }
348
+ }
349
+ }
350
+ }
351
+ // Find the best final state (c, j) across all states at frame t = frames - 1.
352
+ let bestScore = -Infinity, bestChain = 0, bestOffset = 0;
353
+ for (let c = 0; c < numChains; c++) {
354
+ const h = heads[c], L = lens[c], k = obsCount[c];
355
+ const delta = obsType[c] === 1 ? delta1 : delta2;
356
+ for (let j = 0; j < L; j++) {
357
+ const t0 = frames - 1 - j;
358
+ let score;
359
+ if (t0 >= 0) {
360
+ score = ring[(t0 & ringMask) * numChains + c];
361
+ }
362
+ else {
363
+ const jStart = j - frames;
364
+ score = initial[h + jStart];
365
+ const lastObsU = Math.min(frames - 1, k - 2 - jStart);
366
+ for (let u = 0; u <= lastObsU; u++)
367
+ score += delta[u];
368
+ }
369
+ if (score > bestScore) {
370
+ bestScore = score;
371
+ bestChain = c;
372
+ bestOffset = j;
373
+ }
374
+ }
375
+ }
376
+ const totalScore = bestScore + sumD0;
377
+ if (!winner || totalScore > winner.score) {
378
+ winner = { hmm, score: totalScore, chain: bestChain, offset: bestOffset, checkpoints };
379
+ }
380
+ workingBytes = Math.max(workingBytes, densities.byteLength + ring.byteLength * (checkpoints.length + 1) + tailScores.byteLength);
381
+ }
382
+ if (!winner || !Number.isFinite(winner.score))
383
+ return { beats: [], downbeats: [], workingBytes };
384
+ // Checkpointed traceback on the winning HMM (only stores predecessor chains for the C chain heads).
385
+ const { hmm, checkpoints } = winner;
386
+ const { numChains, ringMask, heads, lens, obsType, obsCount, predPtrs, predChains, predLogTrans, predStartChain, predCount, allContiguous } = hmm;
387
+ const chainBonusIdx = new Uint8Array(numChains);
388
+ for (let c = 0; c < numChains; c++) {
389
+ chainBonusIdx[c] = (obsType[c] === 1 ? 0 : maxObsCount) + (obsCount[c] - 1);
390
+ }
391
+ const path = new Uint32Array(frames);
392
+ const trace = new Uint16Array(block * numChains);
393
+ const tailScores = new Float64Array(numChains);
394
+ workingBytes += trace.byteLength + path.byteLength;
395
+ let curChain = winner.chain;
396
+ let curOffset = winner.offset;
397
+ let tCursor = frames - 1;
398
+ const tbWasm = runBlockWasm(hmm, checkpoints[0], chainBonusIdx, trace);
399
+ for (let chunk = checkpoints.length - 1; chunk >= 0 && tCursor >= 0; chunk--) {
400
+ const start = chunk * block;
401
+ const stop = Math.min(frames, start + block);
402
+ if (tCursor < start)
403
+ continue;
404
+ let activeTrace = trace;
405
+ if (tbWasm && tbWasm.wTrace) {
406
+ tbWasm.wRing.set(checkpoints[chunk]);
407
+ tbWasm.run(start, stop);
408
+ activeTrace = tbWasm.wTrace;
409
+ }
410
+ else {
411
+ const ring = checkpoints[chunk].slice();
412
+ for (let t = start; t < stop; t++) {
413
+ const writeBase = (t & ringMask) * numChains;
414
+ const traceBase = (t - start) * numChains;
415
+ for (let k = 1; k <= maxObsCount; k++) {
416
+ frameBonus[k - 1] = bonus1[k][t];
417
+ frameBonus[maxObsCount + k - 1] = bonus2[k][t];
418
+ }
419
+ for (let c = 0; c < numChains; c++) {
420
+ tailScores[c] = ring[((t - lens[c]) & ringMask) * numChains + c];
421
+ }
422
+ if (allContiguous) {
423
+ for (let c = 0; c < numChains; c++) {
424
+ let best = -Infinity, pred = 0;
425
+ let p = predPtrs[c], pc = predStartChain[c];
426
+ const pEnd = p + predCount[c];
427
+ for (; p < pEnd; p++, pc++) {
428
+ const cand = tailScores[pc] + predLogTrans[p];
429
+ if (cand > best) {
430
+ best = cand;
431
+ pred = pc;
432
+ }
433
+ }
434
+ ring[writeBase + c] = best + frameBonus[chainBonusIdx[c]];
435
+ trace[traceBase + c] = pred;
436
+ }
437
+ }
438
+ else {
439
+ for (let c = 0; c < numChains; c++) {
440
+ let best = -Infinity, pred = 0;
441
+ for (let p = predPtrs[c], pEnd = predPtrs[c + 1]; p < pEnd; p++) {
442
+ const pc = predChains[p];
443
+ const cand = tailScores[pc] + predLogTrans[p];
444
+ if (cand > best) {
445
+ best = cand;
446
+ pred = pc;
447
+ }
448
+ }
449
+ ring[writeBase + c] = best + frameBonus[chainBonusIdx[c]];
450
+ trace[traceBase + c] = pred;
451
+ }
452
+ }
453
+ }
454
+ }
455
+ while (tCursor >= start) {
456
+ const h = heads[curChain];
457
+ const steps = Math.min(curOffset, tCursor - start);
458
+ for (let s = 0; s <= steps; s++) {
459
+ path[tCursor - s] = h + curOffset - s;
460
+ }
461
+ tCursor -= steps;
462
+ curOffset -= steps;
463
+ if (curOffset === 0) {
464
+ const pred = activeTrace[(tCursor - start) * numChains + curChain];
465
+ tCursor--;
466
+ curChain = pred;
467
+ curOffset = lens[curChain] - 1;
468
+ }
469
+ else {
470
+ tCursor--;
471
+ curOffset--;
472
+ }
473
+ }
474
+ }
475
+ return extractEvents(scores, first, frames, path, hmm.observations, hmm.positions, workingBytes);
476
+ }
477
+ function decodeGeneralDbn(scores, first, frames, densities, compiledHmms) {
478
+ const block = 500;
479
+ let workingBytes = densities.byteLength;
480
+ let winner;
481
+ const toGeneral = (h) => {
482
+ if (h.kind === 'general')
483
+ return h;
484
+ // Reconstruct general arrays from chain HMM if d0 hit -Infinity
485
+ const numStates = h.numStates;
486
+ const pointers = new Int32Array(numStates + 1);
487
+ let edges = 0;
488
+ for (let c = 0; c < h.numChains; c++) {
489
+ edges += (h.predPtrs[c + 1] - h.predPtrs[c]) + (h.lens[c] - 1);
490
+ }
491
+ const st = new Int32Array(edges);
492
+ const lt = new Float64Array(edges);
493
+ let p = 0;
494
+ for (let c = 0; c < h.numChains; c++) {
495
+ const head = h.heads[c];
496
+ pointers[head] = p;
497
+ for (let k = h.predPtrs[c]; k < h.predPtrs[c + 1]; k++) {
498
+ const pc = h.predChains[k];
499
+ st[p] = h.heads[pc] + h.lens[pc] - 1;
500
+ lt[p] = h.predLogTrans[k];
501
+ p++;
502
+ }
503
+ for (let j = 1; j < h.lens[c]; j++) {
504
+ pointers[head + j] = p;
505
+ st[p] = head + j - 1;
506
+ lt[p] = 0;
507
+ p++;
508
+ }
509
+ }
510
+ pointers[numStates] = p;
511
+ return { kind: 'general', numStates, states: st, pointers, logTransitions: lt, observations: h.observations, positions: h.positions, initial: h.initial };
512
+ };
513
+ const advance = (hmm, previous, next, t, trace, offset = 0) => {
514
+ const { states: st, pointers, logTransitions, observations } = hmm;
515
+ const dBase = t * 3;
516
+ const d0 = densities[dBase], d1 = densities[dBase + 1], d2 = densities[dBase + 2];
517
+ const n = next.length;
518
+ for (let state = 0; state < n; state++) {
519
+ let best = -Infinity, predecessor = 0;
520
+ for (let p = pointers[state], pEnd = pointers[state + 1]; p < pEnd; p++) {
521
+ const ps = st[p];
522
+ const candidate = previous[ps] + logTransitions[p];
523
+ if (candidate > best) {
524
+ best = candidate;
525
+ predecessor = ps;
526
+ }
527
+ }
528
+ const obs = observations[state];
529
+ next[state] = best + (obs === 0 ? d0 : obs === 1 ? d1 : d2);
530
+ if (trace)
531
+ trace[offset + state] = predecessor;
532
+ }
533
+ };
534
+ for (const raw of compiledHmms) {
535
+ const hmm = toGeneral(raw);
536
+ let previous = hmm.initial.slice(), next = new Float64Array(hmm.numStates);
537
+ const checkpoints = [];
538
+ for (let t = 0; t < frames; t++) {
539
+ if (t % block === 0)
540
+ checkpoints.push(previous.slice());
541
+ advance(hmm, previous, next, t);
542
+ [previous, next] = [next, previous];
543
+ }
544
+ let state = 0;
545
+ for (let s = 1; s < previous.length; s++)
546
+ if (previous[s] > previous[state])
547
+ state = s;
548
+ if (!winner || previous[state] > winner.score)
549
+ winner = { hmm, score: previous[state], state, checkpoints };
550
+ workingBytes = Math.max(workingBytes, densities.byteLength + previous.byteLength * (checkpoints.length + 2));
551
+ }
552
+ if (!winner || !Number.isFinite(winner.score))
553
+ return { beats: [], downbeats: [], workingBytes };
554
+ const { hmm, checkpoints } = winner;
555
+ const path = new Uint32Array(frames);
556
+ const numStates = hmm.numStates;
557
+ const trace = new Uint32Array(block * numStates);
558
+ workingBytes += trace.byteLength + path.byteLength;
559
+ let state = winner.state;
560
+ for (let chunk = checkpoints.length - 1; chunk >= 0; chunk--) {
561
+ const start = chunk * block, stop = Math.min(frames, start + block);
562
+ let previous = checkpoints[chunk].slice(), next = new Float64Array(numStates);
563
+ for (let t = start; t < stop; t++) {
564
+ advance(hmm, previous, next, t, trace, (t - start) * numStates);
565
+ [previous, next] = [next, previous];
566
+ }
567
+ for (let t = stop - 1; t >= start; t--) {
568
+ path[t] = state;
569
+ state = trace[(t - start) * numStates + state];
570
+ }
571
+ }
572
+ return extractEvents(scores, first, frames, path, hmm.observations, hmm.positions, workingBytes);
573
+ }
574
+ function extractEvents(scores, first, frames, path, observations, positions, workingBytes) {
575
+ const beats = [], downbeats = [];
576
+ for (let t = 0; t < frames;) {
577
+ if (observations[path[t]] < 1) {
578
+ t++;
579
+ continue;
580
+ }
581
+ const start = t;
582
+ while (t < frames && observations[path[t]] >= 1)
583
+ t++;
584
+ let peak = start, value = -Infinity;
585
+ for (let p = start; p < t; p++) {
586
+ const idx = (first + p) << 1;
587
+ const b = scores[idx], d = scores[idx + 1];
588
+ const candidate = b > d ? b : d;
589
+ if (candidate > value) {
590
+ value = candidate;
591
+ peak = p;
592
+ }
593
+ }
594
+ const time = (first + peak) / 50;
595
+ beats.push(time);
596
+ if (Math.floor(positions[path[peak]]) === 0)
597
+ downbeats.push(time);
598
+ }
599
+ return { beats, downbeats, workingBytes };
600
+ }