huashu-motion 0.5.0 → 0.6.0
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/README.en.md +28 -1
- package/README.md +28 -1
- package/THIRD_PARTY.md +2 -0
- package/cli/lib/arrange.js +570 -0
- package/cli/lib/beats-report.js +180 -0
- package/cli/lib/beats.js +351 -22
- package/cli/lib/check.js +16 -0
- package/cli/lib/music.js +156 -0
- package/cli/lib/render-om.js +2 -1
- package/cli/lib/render.js +11 -1
- package/cli/lib/sound.js +81 -12
- package/cli/lib/track.js +342 -0
- package/cli/om.js +15 -0
- package/music/LICENSE.md +35 -0
- package/music/catalog.json +316 -0
- package/package.json +2 -2
- package/runtime/om.js +48 -1
- package/skills/huashu-motion/SKILL.md +9 -6
- package/skills/huashu-motion/references/about-author.md +1 -0
- package/skills/huashu-motion/references/director.md +2 -2
- package/skills/huashu-motion/references/music-sources.md +47 -0
- package/skills/huashu-motion/references/music.md +4 -0
- package/skills/huashu-motion/references/rhythm.md +2 -0
- package/skills/huashu-motion/references/sound.md +63 -1
package/cli/lib/beats.js
CHANGED
|
@@ -7,10 +7,15 @@
|
|
|
7
7
|
//
|
|
8
8
|
// analyzeFile(file) / analyze(pcm) returns (all times in seconds from the start of the audio):
|
|
9
9
|
// {
|
|
10
|
-
// bpm, //
|
|
11
|
-
// confidence, // 0–1; < 0.3 means "no clear pulse": bpm/beats/downbeats are a best guess, trust `sections
|
|
10
|
+
// bpm, // fitted over the whole track (not an integer, e.g. 127.98); a steady tempo comes out to ~0.01 bpm
|
|
11
|
+
// confidence, // 0–1; < 0.3 means "no clear pulse": bpm/beats/downbeats are a best guess, trust `sections`;
|
|
12
|
+
// // lowered (at most by half) when another count of the pulse (3:4, 4:3, 2:3, 3:2) fits about as well
|
|
13
|
+
// alternatives: [{ ratio, bpm, score, onset, bars, matched, residualMs, steady }], // other counts, score relative to `bpm` (1 = as good)
|
|
14
|
+
// fit, // { method: 'steady' | 'tracked', residualMs, driftMs, matched, … }: one straight line through the
|
|
15
|
+
// // onsets (residual in ms, worst 30 s window's offset) or, when the tempo moves, per-beat tracking
|
|
16
|
+
// bars, // how the bar line was chosen: { basis: 'chords' | 'accent', chordContrast, … }
|
|
12
17
|
// beats: [t], // every beat, regular grid when the tempo is steady, raw tracker output when it drifts
|
|
13
|
-
// downbeats: [t], // first beat of each bar, 4/4 assumed (every 4th entry of `beats`)
|
|
18
|
+
// downbeats: [t], // first beat of each bar, 4/4 assumed (every 4th entry of `beats`), where the chords change
|
|
14
19
|
// sections: [{ start, end, energy }], // loudness segments cut on bar lines (4 s blocks when no pulse); energy 0–1, 1 = loudest
|
|
15
20
|
// drops: [{ t, score }], // up to 3 candidates, t on a downbeat, score 0–1 = size of the energy jump, best first
|
|
16
21
|
// end, // where the music really stops (last point above the silence threshold)
|
|
@@ -25,8 +30,8 @@ const r3 = (x) => Math.round(x * 1000) / 1000;
|
|
|
25
30
|
// ---------- decode ----------
|
|
26
31
|
|
|
27
32
|
// Any audio/video file → { L, R, rate, duration } (Float32Array per channel, mono sources are duplicated).
|
|
28
|
-
export function decode(file, rate = 48000) {
|
|
29
|
-
const r = spawnSync('ffmpeg', ['-v', 'error', '-nostdin', '-i', file, '-vn', '-f', 'f32le', '-ac', '2', '-ar', String(rate), '-'], { maxBuffer: Infinity });
|
|
33
|
+
export function decode(file, rate = 48000, tempo = 1) {
|
|
34
|
+
const r = spawnSync('ffmpeg', ['-v', 'error', '-nostdin', '-i', file, '-vn', ...(tempo !== 1 ? ['-af', `atempo=${tempo}`] : []), '-f', 'f32le', '-ac', '2', '-ar', String(rate), '-'], { maxBuffer: Infinity });
|
|
30
35
|
if (r.error) {
|
|
31
36
|
if (r.error.code === 'ENOENT') throw new OmError('ffmpeg not found — install it (macOS: brew install ffmpeg) to decode music files');
|
|
32
37
|
throw new OmError(`ffmpeg failed to start: ${r.error.message}`);
|
|
@@ -86,8 +91,8 @@ const FLUX_LEAD = 0.009;
|
|
|
86
91
|
|
|
87
92
|
// Decimate to ~12 kHz, STFT with hop 10 ms, log-magnitude half-wave flux per band, plus raw bass magnitude
|
|
88
93
|
// (linear, so accents survive) and block RMS at the full rate.
|
|
89
|
-
function features({ L, R, rate }) {
|
|
90
|
-
const D = Math.max(1, Math.round(rate / 12000)), r2 = rate / D, hop = Math.round(r2 /
|
|
94
|
+
function features({ L, R, rate }, perSec = 100) {
|
|
95
|
+
const D = Math.max(1, Math.round(rate / 12000)), r2 = rate / D, hop = Math.round(r2 / perSec), n = L.length;
|
|
91
96
|
const m = Math.floor(n / D), y = new Float32Array(m);
|
|
92
97
|
let ss = 0;
|
|
93
98
|
for (let i = 0; i < m; i++) { let s = 0; for (let k = 0; k < D; k++) s += L[i * D + k] + R[i * D + k]; y[i] = s / (2 * D); ss += y[i] * y[i]; }
|
|
@@ -96,7 +101,7 @@ function features({ L, R, rate }) {
|
|
|
96
101
|
const hann = new Float64Array(WIN);
|
|
97
102
|
for (let i = 0; i < WIN; i++) hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / WIN);
|
|
98
103
|
const re = new Float64Array(WIN), im = new Float64Array(WIN), prev = new Float64Array(WIN / 2 + 1), cur = new Float64Array(WIN / 2 + 1);
|
|
99
|
-
const flux = BANDS.map(() => new Float32Array(nF)), bass = new Float32Array(nF);
|
|
104
|
+
const flux = BANDS.map(() => new Float32Array(nF)), bass = new Float32Array(nF), bandLo = new Float32Array(nF), bandHi = new Float32Array(nF);
|
|
100
105
|
for (let f = 0; f < nF; f++) {
|
|
101
106
|
const s0 = f * hop - WIN / 2;
|
|
102
107
|
for (let i = 0; i < WIN; i++) { const j = s0 + i; re[i] = j >= 0 && j < m ? y[j] * hann[i] : 0; im[i] = 0; }
|
|
@@ -104,7 +109,7 @@ function features({ L, R, rate }) {
|
|
|
104
109
|
for (let k = 1; k < WIN / 2; k++) {
|
|
105
110
|
const a = Math.hypot(re[k], im[k]) / (WIN / 2) * gain;
|
|
106
111
|
cur[k] = Math.log1p(1000 * a);
|
|
107
|
-
if (k < 7) bass[f] += a;
|
|
112
|
+
if (k < 7) { bass[f] += a; bandLo[f] += a * a; } else if (k >= 107) bandHi[f] += a * a; // < 160 Hz and > 2.5 kHz, as power
|
|
108
113
|
}
|
|
109
114
|
for (let k = 1; k < WIN / 2; k++) {
|
|
110
115
|
// SuperFlux (Böck 2013): compare with the max of the neighbouring bins of the previous frame, so a
|
|
@@ -121,7 +126,7 @@ function features({ L, R, rate }) {
|
|
|
121
126
|
for (let i = a; i < e; i++) { const v = 0.5 * (L[i] + R[i]); s += v * v; }
|
|
122
127
|
rms[b] = Math.sqrt(s / Math.max(1, e - a));
|
|
123
128
|
}
|
|
124
|
-
return { hopSec: hop / r2, nF, flux, bass, rms, blockSec: hopF / rate };
|
|
129
|
+
return { hopSec: hop / r2, nF, flux, bass, bandLo, bandHi, rms, blockSec: hopF / rate };
|
|
125
130
|
}
|
|
126
131
|
|
|
127
132
|
// onset strength envelope: bands normalized by their own mean, bass-weighted sum, local mean removed.
|
|
@@ -221,14 +226,272 @@ function comb(x, P) {
|
|
|
221
226
|
return { p: best.p, ph: best.ph, quality: best.v / Math.max(1e-9, mean) };
|
|
222
227
|
}
|
|
223
228
|
|
|
229
|
+
// ---------- fine fit of a steady tempo ----------
|
|
230
|
+
|
|
231
|
+
// Generated and sequenced music is mostly a fixed tempo, often a whole or almost whole number of bpm. The grid from `comb`
|
|
232
|
+
// is good to a fraction of a percent, which is 50–150 ms by the end of a track. This refits it on a 2.7 ms onset envelope:
|
|
233
|
+
// scan period and phase for the grid that sits on the most onset energy, then least squares through the onset peaks
|
|
234
|
+
// found near each grid beat (outliers dropped), and compare 30 s windows with the global line. `steady` says the single line
|
|
235
|
+
// explains the track (every window within 15 ms of it); when it does not, the caller falls back to per-beat tracking.
|
|
236
|
+
// All times are in seconds on the envelope's own clock (add FLUX_LEAD for the acoustic onset).
|
|
237
|
+
function fitSteady(x, hopSec, P0, end, span = 0.025) {
|
|
238
|
+
const n = x.length, s = new Float32Array(n + 1);
|
|
239
|
+
for (let i = 0; i < n; i++) s[i] = 0.25 * (x[i - 1] ?? x[i]) + 0.5 * x[i] + 0.25 * (x[i + 1] ?? x[i]);
|
|
240
|
+
const last = Math.min(n - 2, Math.floor(end / hopSec));
|
|
241
|
+
const score = (p, ph) => { let v = 0, c = 0; for (let t = ph; t < last; t += p) { if (t < 0) continue; const i = t | 0; v += s[i] + (s[i + 1] - s[i]) * (t - i); c++; } return v / Math.max(1, c); };
|
|
242
|
+
const P = P0 / hopSec; // frames per beat
|
|
243
|
+
let best = { v: -1, p: P, ph: 0 };
|
|
244
|
+
for (let r = -span; r <= span * 1.0004; r += span / 62.5) for (let ph = 0; ph < P; ph += 1) { const p = P * (1 + r), v = score(p, ph); if (v > best.v) best = { v, p, ph }; }
|
|
245
|
+
for (let r = -0.0005; r <= 0.00051; r += 0.00004) for (let d = -1.5; d <= 1.501; d += 0.25) { const p = best.p * (1 + r), ph = best.ph + d, v = ph >= 0 ? score(p, ph) : -1; if (v > best.v) best = { v, p, ph }; }
|
|
246
|
+
// onset peaks near the grid, then a robust weighted line fit t = ph + k p
|
|
247
|
+
let line = { p: best.p, ph: best.ph };
|
|
248
|
+
let pts = [], res = [];
|
|
249
|
+
const win = Math.max(2, Math.min(Math.round(0.05 / hopSec), Math.floor(best.p / 8)));
|
|
250
|
+
for (let pass = 0; pass < 4; pass++) {
|
|
251
|
+
pts = [];
|
|
252
|
+
for (let k = 0; line.ph + k * line.p < last; k++) {
|
|
253
|
+
const c = Math.round(line.ph + k * line.p);
|
|
254
|
+
let m = Math.max(0, c - win);
|
|
255
|
+
for (let i = m; i <= Math.min(n - 2, c + win); i++) if (x[i] > x[m]) m = i;
|
|
256
|
+
if (m <= 0 || m >= n - 1 || x[m] < 1.0) continue; // x is in standard deviations: a real hit stands clear of the background
|
|
257
|
+
const a = x[m - 1], b = x[m], d = x[m + 1], den = a - 2 * b + d;
|
|
258
|
+
pts.push({ k, t: den < 0 ? m + clamp(0.5 * (a - d) / den, -0.5, 0.5) : m, w: Math.min(4, b) });
|
|
259
|
+
}
|
|
260
|
+
if (pts.length < 8) break;
|
|
261
|
+
// weighted least squares of t on k, then drop the worst until everything is within 2.5 sigma (at least 15 ms)
|
|
262
|
+
const fit = (q) => { let sw = 0, sk = 0, st = 0, skk = 0, skt = 0; for (const o of q) { sw += o.w; sk += o.w * o.k; st += o.w * o.t; skk += o.w * o.k * o.k; skt += o.w * o.k * o.t; } const den = sw * skk - sk * sk, p = (sw * skt - sk * st) / den; return { p, ph: (st - p * sk) / sw }; };
|
|
263
|
+
let use = pts, f = fit(use);
|
|
264
|
+
for (let it = 0; it < 5; it++) {
|
|
265
|
+
const r = use.map((o) => o.t - (f.ph + o.k * f.p)), sd = Math.sqrt(r.reduce((a, v) => a + v * v, 0) / r.length), lim = Math.max(0.015 / hopSec, 2.5 * sd);
|
|
266
|
+
const keep = use.filter((_, i) => Math.abs(r[i]) <= lim);
|
|
267
|
+
if (keep.length === use.length || keep.length < 8) break;
|
|
268
|
+
use = keep; f = fit(use);
|
|
269
|
+
}
|
|
270
|
+
line = f; pts = use;
|
|
271
|
+
}
|
|
272
|
+
if (pts.length < 8) return null;
|
|
273
|
+
res = pts.map((o) => (o.t - (line.ph + o.k * line.p)) * hopSec);
|
|
274
|
+
const rms = Math.sqrt(res.reduce((a, v) => a + v * v, 0) / res.length);
|
|
275
|
+
// local offsets: mean residual in 30 s windows
|
|
276
|
+
let maxLocal = 0;
|
|
277
|
+
for (let t0 = 0; t0 < end; t0 += 30) {
|
|
278
|
+
const w = pts.filter((o) => { const t = (line.ph + o.k * line.p) * hopSec; return t >= t0 && t < t0 + 30; });
|
|
279
|
+
if (w.length < 6) continue;
|
|
280
|
+
const m = w.reduce((a, o) => a + (o.t - (line.ph + o.k * line.p)) * hopSec, 0) / w.length;
|
|
281
|
+
maxLocal = Math.max(maxLocal, Math.abs(m));
|
|
282
|
+
}
|
|
283
|
+
const total = Math.max(1, Math.floor((last - line.ph) / line.p));
|
|
284
|
+
return { period: line.p * hopSec, phase: line.ph * hopSec, rms, maxLocal, matched: pts.length / total, steady: maxLocal <= 0.015 && rms <= 0.018 && pts.length / total >= 0.25, shiftScore: (sec) => score(line.p, line.ph + sec / hopSec) };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const FINE_HOP = 32 / 12000; // seconds: a 32-sample hop at the 12 kHz analysis rate (2.67 ms)
|
|
288
|
+
// normalized onset envelope at FINE_HOP, for the first `len` seconds
|
|
289
|
+
function fineEnv(L, R, rate, len) {
|
|
290
|
+
const F = features({ L, R, rate }, 375), n = Math.min(F.nF, Math.ceil(len / F.hopSec) + 1);
|
|
291
|
+
const e = envelope(F.flux, F.nF, F.hopSec).subarray(0, n);
|
|
292
|
+
let m = 0; for (let i = 0; i < n; i++) m += e[i]; m /= n;
|
|
293
|
+
let sd = 0; for (let i = 0; i < n; i++) sd += (e[i] - m) ** 2;
|
|
294
|
+
sd = Math.sqrt(sd / n) || 1;
|
|
295
|
+
return e.map((v) => v / sd);
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
// ---------- harmony: where the chords change ----------
|
|
299
|
+
|
|
300
|
+
const MEDIAN = 9, CHROMA_WIN = 2048, CHROMA_HOP = 256; // at 12 kHz: 5.9 Hz bins, a frame every 21 ms
|
|
301
|
+
// Pitch-class energy per frame (12 values, summed to 1), from 100–1600 Hz where chords and bass lines live, and the
|
|
302
|
+
// novelty of it: how different the 0.2 s after a moment sounds from the 0.2 s before. A chord changes on a bar line far
|
|
303
|
+
// more often than on any other beat, which is what decides where the bars are when the drums cannot (a kick that
|
|
304
|
+
// is strongest on beat 2, a 16th-note groove).
|
|
305
|
+
function harmony({ L, R, rate }) {
|
|
306
|
+
const D = Math.max(1, Math.round(rate / 12000)), r2 = rate / D, m = Math.floor(L.length / D), y = new Float32Array(m);
|
|
307
|
+
for (let i = 0; i < m; i++) { let s = 0; for (let k = 0; k < D; k++) s += L[i * D + k] + R[i * D + k]; y[i] = s / (2 * D); }
|
|
308
|
+
const nF = Math.floor(m / CHROMA_HOP) + 1, fft = makeFFT(CHROMA_WIN), hann = new Float64Array(CHROMA_WIN);
|
|
309
|
+
for (let i = 0; i < CHROMA_WIN; i++) hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / CHROMA_WIN);
|
|
310
|
+
const pc = new Int8Array(CHROMA_WIN / 2).fill(-1);
|
|
311
|
+
for (let k = 1; k < CHROMA_WIN / 2; k++) { const f = (k * r2) / CHROMA_WIN; if (f >= 130 && f <= 1600) pc[k] = (((Math.round(69 + 12 * Math.log2(f / 440)) % 12) + 12) % 12); }
|
|
312
|
+
const C = new Float32Array(nF * 12), re = new Float64Array(CHROMA_WIN), im = new Float64Array(CHROMA_WIN);
|
|
313
|
+
for (let f = 0; f < nF; f++) {
|
|
314
|
+
const s0 = f * CHROMA_HOP - CHROMA_WIN / 2;
|
|
315
|
+
for (let i = 0; i < CHROMA_WIN; i++) { const j = s0 + i; re[i] = j >= 0 && j < m ? y[j] * hann[i] : 0; im[i] = 0; }
|
|
316
|
+
fft(re, im);
|
|
317
|
+
let tot = 0;
|
|
318
|
+
for (let k = 1; k < CHROMA_WIN / 2; k++) if (pc[k] >= 0) { const a = Math.sqrt(Math.hypot(re[k], im[k])); C[f * 12 + pc[k]] += a; tot += a; }
|
|
319
|
+
if (tot > 0) for (let c = 0; c < 12; c++) C[f * 12 + c] /= tot;
|
|
320
|
+
}
|
|
321
|
+
// a drum hit smears the chroma for a few frames and is gone; a chord change is a step that stays. A running median over ~0.2 s
|
|
322
|
+
// removes the first and keeps the second.
|
|
323
|
+
const med = new Float32Array(C.length), win = new Float32Array(MEDIAN);
|
|
324
|
+
for (let c = 0; c < 12; c++) for (let f = 0; f < nF; f++) {
|
|
325
|
+
for (let k = 0; k < MEDIAN; k++) win[k] = C[Math.min(nF - 1, Math.max(0, f + k - (MEDIAN >> 1))) * 12 + c];
|
|
326
|
+
med[f * 12 + c] = win.slice().sort()[MEDIAN >> 1];
|
|
327
|
+
}
|
|
328
|
+
C.set(med);
|
|
329
|
+
const w = 8, nov = new Float32Array(nF), hopSec = CHROMA_HOP / r2;
|
|
330
|
+
const mean = (a, b) => { const o = new Float64Array(12); for (let f = a; f < b; f++) if (f >= 0 && f < nF) for (let c = 0; c < 12; c++) o[c] += C[f * 12 + c]; return o; };
|
|
331
|
+
const cos = (a, b) => { let d = 0, x = 0, z = 0; for (let c = 0; c < 12; c++) { d += a[c] * b[c]; x += a[c] * a[c]; z += b[c] * b[c]; } return x > 0 && z > 0 ? d / Math.sqrt(x * z) : 1; };
|
|
332
|
+
for (let f = w; f < nF - w; f++) nov[f] = 1 - cos(mean(f - w, f), mean(f, f + w));
|
|
333
|
+
let total = 0; for (let f = w; f < nF - w; f++) total += nov[f];
|
|
334
|
+
return { nov, hopSec, nF, C, mean: total / Math.max(1, nF - 2 * w) };
|
|
335
|
+
}
|
|
336
|
+
// novelty at time t (seconds): the boundary between frame f-1 and f sits half a frame before frame f's centre
|
|
337
|
+
const novAt = (H, t) => { const x = t / H.hopSec + 0.5; if (x <= 0 || x >= H.nF - 1) return 0; const i = Math.floor(x); return H.nov[i] + (H.nov[i + 1] - H.nov[i]) * (x - i); };
|
|
338
|
+
|
|
339
|
+
// How often the chords change, as a list of periods (seconds, with weights): the peaks of the chord-change novelty's autocorrelation.
|
|
340
|
+
// A progression repeats every 2, 4, 8 bars, so the strong periods are whole multiples of the half bar of the right count and
|
|
341
|
+
// not of a wrong one (a dotted-eighth echo at 4:3 of the beat has a bar 3/4 as long, and the progression does not divide into it).
|
|
342
|
+
function chordPeriods(H, end) {
|
|
343
|
+
const a = Math.ceil(3 / H.hopSec), b = Math.min(H.nF - 1, Math.floor((end - 1) / H.hopSec)), n = b - a;
|
|
344
|
+
if (n < 400) return [];
|
|
345
|
+
const x = new Float64Array(n); let mu = 0;
|
|
346
|
+
for (let i = 0; i < n; i++) mu += H.nov[a + i]; mu /= n;
|
|
347
|
+
for (let i = 0; i < n; i++) x[i] = H.nov[a + i] - mu;
|
|
348
|
+
let e0 = 0; for (let i = 0; i < n; i++) e0 += x[i] * x[i];
|
|
349
|
+
if (e0 <= 0) return [];
|
|
350
|
+
const lo = Math.ceil(0.6 / H.hopSec), hi = Math.min(n >> 1, Math.floor(40 / H.hopSec)), acf = new Float64Array(hi + 2);
|
|
351
|
+
for (let k = lo - 1; k <= hi + 1; k++) { let s = 0; for (let i = 0; i + k < n; i++) s += x[i] * x[i + k]; acf[k] = s / e0 * (n / (n - k)); }
|
|
352
|
+
const peaks = [];
|
|
353
|
+
for (let k = lo; k <= hi; k++) if (acf[k] > 0.05 && acf[k] >= acf[k - 1] && acf[k] > acf[k + 1]) peaks.push({ t: k * H.hopSec, w: acf[k] });
|
|
354
|
+
peaks.sort((p, q) => q.w - p.w);
|
|
355
|
+
const out = [];
|
|
356
|
+
for (const p of peaks) if (out.length < 8 && out.every((o) => Math.abs(o.t - p.t) > 0.25)) out.push(p);
|
|
357
|
+
return out;
|
|
358
|
+
}
|
|
359
|
+
// 1 when every strong period is a whole number of `g` seconds, about 0.25 when they fall between
|
|
360
|
+
const periodFit = (periods, g) => { let w = 0, s = 0; for (const p of periods) { w += p.w; s += p.w * (1 + Math.cos((2 * Math.PI * p.t) / g)) / 2; } return w > 0 ? s / w : 0.5; };
|
|
361
|
+
|
|
362
|
+
// ---------- the map of the track: one row per bar, then segments ----------
|
|
363
|
+
|
|
364
|
+
const KEY_MAJOR = [6.35, 2.23, 3.48, 2.33, 4.38, 4.09, 2.52, 5.19, 2.39, 3.66, 2.29, 2.88], KEY_MINOR = [6.33, 2.68, 3.52, 5.38, 2.6, 3.53, 2.54, 4.75, 3.98, 2.69, 3.34, 3.17];
|
|
365
|
+
const NOTE = ['C', 'C#', 'D', 'D#', 'E', 'F', 'F#', 'G', 'G#', 'A', 'A#', 'B'];
|
|
366
|
+
const cosine = (a, b) => { let d = 0, x = 0, y = 0; for (let i = 0; i < a.length; i++) { d += a[i] * b[i]; x += a[i] * a[i]; y += b[i] * b[i]; } return x > 0 && y > 0 ? d / Math.sqrt(x * y) : 0; };
|
|
367
|
+
const rot = (v, k) => v.map((_, i) => v[(i - k + 12) % 12]);
|
|
368
|
+
export const chromaCosine = cosine;
|
|
369
|
+
|
|
370
|
+
// Krumhansl–Schmuckler key of a 12-vector
|
|
371
|
+
function keyOf(chroma) {
|
|
372
|
+
let best = null;
|
|
373
|
+
for (let r = 0; r < 12; r++) for (const [mode, prof] of [['major', KEY_MAJOR], ['minor', KEY_MINOR]]) {
|
|
374
|
+
const c = cosine(chroma, rot(prof, r));
|
|
375
|
+
if (!best || c > best.c) best = { c, root: r, mode };
|
|
376
|
+
}
|
|
377
|
+
return { root: NOTE[best.root], rootIndex: best.root, mode: best.mode, chord: NOTE[best.root] + (best.mode === 'minor' ? 'm' : '') };
|
|
378
|
+
}
|
|
379
|
+
// the triad (major or minor) a 12-vector sounds most like
|
|
380
|
+
function chordOf(chroma) {
|
|
381
|
+
let best = null, second = -1;
|
|
382
|
+
for (let r = 0; r < 12; r++) for (const mode of ['major', 'minor']) {
|
|
383
|
+
const t = new Array(12).fill(0); t[r] = 1; t[(r + (mode === 'minor' ? 3 : 4)) % 12] = 1; t[(r + 7) % 12] = 1;
|
|
384
|
+
const c = cosine(chroma, t);
|
|
385
|
+
if (!best || c > best.c) { if (best) second = Math.max(second, best.c); best = { c, root: r, mode }; } else second = Math.max(second, c);
|
|
386
|
+
}
|
|
387
|
+
return { name: NOTE[best.root] + (best.mode === 'minor' ? 'm' : ''), conf: r3(best.c - second), fit: r3(best.c) };
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
// Per bar (between consecutive downbeats): loudness, brightness, low end, the chord, chroma of the head and the tail half
|
|
391
|
+
// (what a cut into or out of the bar sounds like); then the bars grouped into segments (intro / build / breakdown / main / outro / verse)
|
|
392
|
+
// with an energy grade, and the bars that can end a film (the tonic chord, followed by a decay or by the end).
|
|
393
|
+
// All the numbers a re-arrangement needs, so a track is analysed once and cut many ways.
|
|
394
|
+
function buildBarMap({ F, H, downbeats, end, ms, beatLen }) {
|
|
395
|
+
if (downbeats.length < 3) return null;
|
|
396
|
+
const edges = downbeats.filter((t) => t < end - 0.2);
|
|
397
|
+
edges.push(Math.min(end, edges.at(-1) + 4 * beatLen));
|
|
398
|
+
const bars = [], hop = H.hopSec, mean12 = new Float64Array(12);
|
|
399
|
+
const chromaOver = (a, b) => { const o = new Float64Array(12); let n = 0; for (let f = Math.max(0, Math.round(a / hop)); f < Math.min(H.nF, Math.round(b / hop)); f++) { for (let c = 0; c < 12; c++) o[c] += H.C[f * 12 + c]; n++; } return n ? Array.from(o, (v) => v / n) : o.map(() => 0); };
|
|
400
|
+
const bandOver = (arr, a, b) => { let s = 0, n = 0; for (let f = Math.max(0, Math.floor(a / F.hopSec)); f < Math.min(F.nF, Math.ceil(b / F.hopSec)); f++) { s += arr[f]; n++; } return n ? s / n : 0; };
|
|
401
|
+
const dB = (x) => 10 * Math.log10(x + 1e-12);
|
|
402
|
+
for (let i = 0; i + 1 < edges.length; i++) {
|
|
403
|
+
const a = edges[i], b = edges[i + 1], m = (a + b) / 2, all = chromaOver(a, b);
|
|
404
|
+
for (let c = 0; c < 12; c++) mean12[c] += all[c];
|
|
405
|
+
const ch = chordOf(all);
|
|
406
|
+
bars.push({ i, start: r3(a), end: r3(b), db: r3(dB(ms(a, b))), dbIn: r3(dB(ms(a, Math.min(b, a + 1)))), dbOut: r3(dB(ms(Math.max(a, b - 1), b))), atk: r3(dB(ms(a, Math.min(b, a + 0.12))) - dB(ms(Math.min(b, a + 0.3), b))), hf: r3(dB(bandOver(F.bandHi, a, b))), lf: r3(dB(bandOver(F.bandLo, a, b))), chord: ch.name, chordFit: ch.fit, chroma: Array.from(all, (v) => r3(v)), head: chromaOver(a, m).map(r3), tail: chromaOver(m, b).map(r3) });
|
|
407
|
+
}
|
|
408
|
+
const key = keyOf(Array.from(mean12));
|
|
409
|
+
// how much the track's loudness moves at all: a flat track (a few dB between its quietest and loudest bars) has no shape to re-cut
|
|
410
|
+
const dbs = bars.map((x) => x.db).sort((a, b) => a - b), q = (f) => dbs[Math.min(dbs.length - 1, Math.floor(f * dbs.length))];
|
|
411
|
+
const dynamics = { rangeDb: r3(q(0.98) - q(0.1)), quietBars: bars.filter((x) => x.db < q(0.98) - 6).length };
|
|
412
|
+
// normalized loudness / brightness (0–1 between the 10th and 98th percentile of the track's bars) and their mix
|
|
413
|
+
const pct = (xs, p) => { const s = [...xs].sort((x, y) => x - y); return s[Math.min(s.length - 1, Math.floor(p * s.length))]; };
|
|
414
|
+
const nz = (k) => { const v = bars.map((x) => x[k]), lo = pct(v, 0.1), hi = Math.max(lo + 1e-6, pct(v, 0.98)); return v.map((x) => clamp((x - lo) / (hi - lo))); };
|
|
415
|
+
const eL = nz('db'), eH = nz('hf');
|
|
416
|
+
// the home chord: what the key finder says, or the chord most bars sit on (dense mixes flatten the chroma, so either may be the one)
|
|
417
|
+
const tally = {}; for (const x of bars) tally[x.chord] = (tally[x.chord] || 0) + 1;
|
|
418
|
+
const common = Object.entries(tally).sort((a, b) => b[1] - a[1])[0][0], home = new Set([key.chord, common]);
|
|
419
|
+
bars.forEach((x, j) => { x.e = r3(0.65 * eL[j] + 0.35 * eH[j]); x.tonic = home.has(x.chord); });
|
|
420
|
+
// segments: a bar joins the running segment unless it is more than 0.18 away from the segment's mean (and the segment has 2 bars)
|
|
421
|
+
const segs = [];
|
|
422
|
+
for (const x of bars) {
|
|
423
|
+
const cur = segs.at(-1), mean = cur ? cur.sum / cur.n : 0;
|
|
424
|
+
if (!cur || (Math.abs(x.e - mean) > 0.18 && cur.n >= 2)) segs.push({ from: x.i, to: x.i + 1, sum: x.e, n: 1 }); else { cur.to = x.i + 1; cur.sum += x.e; cur.n++; }
|
|
425
|
+
}
|
|
426
|
+
const grade = (e) => (e < 0.35 ? 0 : e < 0.6 ? 1 : e < 0.85 ? 2 : 3);
|
|
427
|
+
const top = Math.max(...segs.map((q) => q.sum / q.n));
|
|
428
|
+
const out = segs.map((q, k) => {
|
|
429
|
+
const e = q.sum / q.n, prev = segs[k - 1] && segs[k - 1].sum / segs[k - 1].n, next = segs[k + 1] && segs[k + 1].sum / segs[k + 1].n;
|
|
430
|
+
const slope = q.n >= 2 ? bars[q.to - 1].e - bars[q.from].e : 0;
|
|
431
|
+
let label = grade(e) >= 2 ? 'main' : 'verse';
|
|
432
|
+
if (k === 0 && next != null && grade(e) <= 1 && next > e) label = 'intro';
|
|
433
|
+
else if (k === segs.length - 1 && k > 0 && e < 0.6 * top) label = 'outro';
|
|
434
|
+
else if (next != null && next > e + 0.12 && slope > 0.12 && grade(e) <= 2) label = 'build';
|
|
435
|
+
else if (prev != null && next != null && e < prev - 0.15 && e < next - 0.1) label = 'breakdown';
|
|
436
|
+
return { from: q.from, to: q.to, start: bars[q.from].start, end: bars[q.to - 1].end, label, grade: grade(e), energy: r3(e) };
|
|
437
|
+
});
|
|
438
|
+
// bars that can end a film: the tonic chord, then a decay (the next bar at least 0.12 quieter) or the end of the music
|
|
439
|
+
const closers = [];
|
|
440
|
+
bars.forEach((x, j) => {
|
|
441
|
+
if (!x.tonic) return;
|
|
442
|
+
const nxt = bars[j + 1], decay = nxt ? x.e - nxt.e : 0.4;
|
|
443
|
+
if (!nxt || decay >= 0.12) closers.push({ bar: j, score: r3(0.5 + 0.5 * clamp(decay / 0.4, 0, 1)) });
|
|
444
|
+
});
|
|
445
|
+
for (const x of bars) { delete x.chordFit; }
|
|
446
|
+
// lifts: a segment that starts at least 0.15 above the one before it. The bar before is its pickup (fill), kept with it by any re-cut.
|
|
447
|
+
const lifts = [];
|
|
448
|
+
out.forEach((g, k) => { if (k > 0 && g.energy - out[k - 1].energy >= 0.15) lifts.push({ bar: g.from, step: r3(g.energy - out[k - 1].energy), pickup: g.from - 1 }); });
|
|
449
|
+
// the opening: the track's own first bars, up to where its first segment ends (at least 2 bars)
|
|
450
|
+
const opening = { bars: Math.max(2, Math.min(8, out[0].to)), label: out[0].label };
|
|
451
|
+
// the ending: how the music stops. body = the loud half of the track; the last bars are compared with it.
|
|
452
|
+
const body = q(0.75), last = bars.length - 1;
|
|
453
|
+
// how long the music takes to die: from the end of the last bar within 8 dB of the body to the end of the music
|
|
454
|
+
const loudBar = Math.max(0, bars.findLastIndex((x) => x.db >= body - 8)), tLoud = Math.min(end, bars[loudBar].end), decaySec = r3(end - tLoud);
|
|
455
|
+
const strong = (() => { const lim = Math.max(...bars.slice(Math.max(0, last - 14)).map((x) => x.db)) - 6; for (let j = Math.min(last, loudBar); j >= 0; j--) if (bars[j].db >= lim && bars[j].atk > 1) return j; return loudBar; })();
|
|
456
|
+
let type = 'cadence';
|
|
457
|
+
if (decaySec < 0.6) type = 'hard stop'; else if (decaySec > 6) type = 'fade'; else if (!bars[strong].tonic) type = 'ring-out';
|
|
458
|
+
// a natural ending starts where the closing phrase does: a fade, at the bar before it begins; otherwise four bars before the last loud one
|
|
459
|
+
const loud3 = Math.max(0, bars.findLastIndex((x) => x.db >= body - 3)); // a natural ending must start at the level the music plays at
|
|
460
|
+
const startBar = Math.max(opening.bars, type === 'fade' ? loud3 : loud3 - 3);
|
|
461
|
+
const ending = { type, decaySec, loudUntil: r3(tLoud), bodyDb: r3(body), lastStrong: strong, lastStrongChord: bars[strong].chord, startBar, seconds: r3(end - bars[startBar].start) };
|
|
462
|
+
return { key: { chord: key.chord, root: key.root, mode: key.mode, common }, dynamics, bars, segments: out, closers, lifts, opening, ending };
|
|
463
|
+
}
|
|
464
|
+
|
|
224
465
|
// ---------- analysis ----------
|
|
225
466
|
|
|
226
|
-
|
|
467
|
+
// Where the music stops. Active = RMS above -55 dBFS; gaps under 0.4 s do not split it. When the last active stretch is short
|
|
468
|
+
// (≤ 4 s), follows a silence of at least 1 s, and is at least 12 dB under the loudest part of what comes before it, it is a
|
|
469
|
+
// separate piece (a spoken label), not the end of the music; the music ends where the stretch before it does.
|
|
470
|
+
function musicEnd(rms, blockSec, duration) {
|
|
471
|
+
const act = []; let cur = null;
|
|
472
|
+
for (let b = 0; b < rms.length; b++) if (rms[b] > 0.0018) { const t0 = b * blockSec, t1 = (b + 1) * blockSec; if (cur && t0 - cur.b < 0.4) { cur.b = t1; cur.peak = Math.max(cur.peak, rms[b]); } else { cur = { a: t0, b: t1, peak: rms[b] }; act.push(cur); } }
|
|
473
|
+
if (!act.length) return { end: 0, tail: null };
|
|
474
|
+
const peakOf = (xs) => Math.max(...xs.map((x) => x.peak));
|
|
475
|
+
let k = act.length - 1;
|
|
476
|
+
while (k > 0) {
|
|
477
|
+
const t = act[k], before = act.slice(0, k), body = before.reduce((a, x) => (x.b - x.a > a.b - a.a ? x : a), before[0]);
|
|
478
|
+
const gap = t.a - act[k - 1].b, lower = 20 * Math.log10(peakOf(before) / t.peak);
|
|
479
|
+
if (t.b - t.a <= 4 && gap >= 1 && lower >= 12 && body.b - body.a >= 8) k--; else break;
|
|
480
|
+
}
|
|
481
|
+
// a click after the music has died (a few ms of encoder noise, 20 dB or more under it) is not music either
|
|
482
|
+
while (k > 0 && act[k].b - act[k].a < 0.3 && 20 * Math.log10(peakOf(act.slice(0, k)) / act[k].peak) >= 20) k--;
|
|
483
|
+
const end = r3(Math.min(duration, act[k].b));
|
|
484
|
+
return { end, tail: k < act.length - 1 ? { from: r3(act[k + 1].a), to: r3(act.at(-1).b), gapSec: r3(act[k + 1].a - act[k].b), dbBelow: Math.round(20 * Math.log10(peakOf(act.slice(0, k + 1)) / peakOf(act.slice(k + 1)))) } : null };
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// opts.bpm: the tempo is known (the grid's period is fitted within 1 % of it, the phase freely)
|
|
488
|
+
export function analyze({ L, R, rate }, opts = {}) {
|
|
227
489
|
const duration = L.length / rate, F = features({ L, R, rate }), { hopSec, nF } = F;
|
|
228
490
|
// end of the music: last block above -55 dBFS RMS
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
491
|
+
// Platforms append a short spoken label after the music ("generated by AI"): a quiet gap, then about two seconds of speech 15–25 dB
|
|
492
|
+
// under the music. That is not music: `end` is where the music stops, and everything after the gap is reported as `tail` and
|
|
493
|
+
// never reaches a film (looping, the closing fade, re-cutting and the beat map all stop at `end`).
|
|
494
|
+
const { end, tail } = musicEnd(F.rms, F.blockSec, duration);
|
|
232
495
|
const nUse = Math.max(8, Math.min(nF, Math.ceil(end / hopSec) + 1));
|
|
233
496
|
const env = envelope(F.flux, nF, hopSec).subarray(0, nUse);
|
|
234
497
|
const bassEnv = envelope([F.flux[0]], nF, hopSec).subarray(0, nUse);
|
|
@@ -245,14 +508,66 @@ export function analyze({ L, R, rate }) {
|
|
|
245
508
|
const fr = track(x, tp.period), ts = fr.map((b) => peakNear(x, b) * hopSec + FLUX_LEAD);
|
|
246
509
|
// the grid holds when it sits on a clearly stronger envelope than chance, or when the tracker agrees with it
|
|
247
510
|
const agree = ts.filter((t) => { const r = (((t - cb.ph * hopSec) % (cb.p * hopSec)) + cb.p * hopSec) % (cb.p * hopSec); return Math.min(r, cb.p * hopSec - r) < 0.04; }).length / Math.max(1, ts.length);
|
|
248
|
-
let beats, period;
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
511
|
+
let beats, period, fit = null;
|
|
512
|
+
const gridOK = cb.quality >= 8 || (cb.quality >= 1.5 && agree >= 0.8);
|
|
513
|
+
const xf = fineEnv(L, R, rate, nUse * hopSec), H = harmony({ L, R, rate });
|
|
514
|
+
const forced = opts.bpm > 0 ? Number(opts.bpm) : null; // the user knows the tempo: fit the phase (and the last percent of the period) to it
|
|
515
|
+
// refit the grid on a finer envelope (see fitSteady); a track the single line does not explain is tracked beat by beat
|
|
516
|
+
let st = fitSteady(xf, FINE_HOP, forced ? 60 / forced : gridOK ? cb.p * hopSec : tp.period * hopSec, end, forced ? 0.01 : 0.025);
|
|
517
|
+
|
|
518
|
+
// Is this the right count? A grid at 3:4 or 4:3 of the pulse (a dotted-eighth echo, a triplet layer) fits the onsets as
|
|
519
|
+
// well as the beat does. Each candidate tempo is refitted and scored on three things: how much onset energy its grid sits
|
|
520
|
+
// on, and how sharply the chords change on ITS bar lines (peak to mean of the chord-change novelty folded at its bar
|
|
521
|
+
// period; a wrong count smears it). The three multiply into `score`. 2:1 and 1:2 (the same pulse counted twice as fast or
|
|
522
|
+
// slow) are listed but never chosen: that is a matter of feel, not of fit.
|
|
523
|
+
const fold = (per) => { const nb = 24, b = new Float64Array(nb), c = new Float64Array(nb); for (let t = 4; t < end - 2; t += 0.01) { const k = Math.floor(((t % per) / per) * nb); b[k] += novAt(H, t); c[k]++; } const v = Array.from(b, (q, i) => q / (c[i] || 1)), m = v.reduce((a, q) => a + q, 0) / nb; return m > 0 ? Math.max(...v) / m : 1; };
|
|
524
|
+
const P = chordPeriods(H, end); // when the chords change: periods that are whole multiples of the right half bar
|
|
525
|
+
const table = (period0, ratios) => ratios.map(([name, r]) => {
|
|
526
|
+
const bpm0 = (60 / period0) * r;
|
|
527
|
+
if (bpm0 < 55 || bpm0 > 200) return null;
|
|
528
|
+
const c = r === 1 ? st : fitSteady(xf, FINE_HOP, 60 / bpm0, end);
|
|
529
|
+
if (!c) return null;
|
|
530
|
+
const q = c.shiftScore(0), ch = fold((4 * 60) / (60 / c.period)), pf = P.length ? periodFit(P, 2 * c.period) : 1, score = q * ch * pf * (c.steady ? 1 : 0.5);
|
|
531
|
+
return { ratio: name, st: c, bpm: Math.round((60 / c.period) * 100) / 100, onset: r3(q), bars: r3(ch), chords: r3(pf), matched: r3(c.matched), residualMs: Math.round(c.rms * 10000) / 10, steady: c.steady, score };
|
|
532
|
+
}).filter(Boolean);
|
|
533
|
+
const SAME = [['1', 1]], FAMILY = [['1:2', 0.5], ['2:1', 2], ['3:4', 0.75], ['4:3', 4 / 3], ['2:3', 2 / 3], ['3:2', 1.5]];
|
|
534
|
+
const SWITCH = 2.25; // a 3:2-type candidate must score this many times the pulse found first. On the ten reference tracks (human-annotated beats from two models) every value from 1.0 to about 5 gives the same, correct answer: no wrong candidate scores above 0.48 of the right count, the two right switches score above 2.25 by a wide margin (see the margins in test/refpack.test.js)
|
|
535
|
+
let alternatives = [], ambiguity = 0, switchedFrom = null;
|
|
536
|
+
if (st && st.steady && !forced) {
|
|
537
|
+
let rows = table(st.period, [...SAME, ...FAMILY]);
|
|
538
|
+
const base = rows.find((r) => r.ratio === '1'), win = rows.filter((r) => /^[234]:[234]$/.test(r.ratio) && r.ratio !== '2:2' && r.steady && r.score >= SWITCH * base.score).sort((a, b) => b.score - a.score)[0];
|
|
539
|
+
if (win) { st = win.st; rows = table(st.period, [...SAME, ...FAMILY]); }
|
|
540
|
+
const me = rows.find((r) => r.ratio === '1');
|
|
541
|
+
alternatives = rows.filter((r) => r.ratio !== '1' && r.score >= 0.25 * me.score).sort((a, b) => b.score - a.score).slice(0, 4).map((r) => ({ ratio: r.ratio, bpm: r.bpm, score: r3(r.score / me.score), onset: r.onset, bars: r.bars, chords: r.chords, matched: r.matched, residualMs: r.residualMs, steady: r.steady }));
|
|
542
|
+
ambiguity = Math.max(0, ...alternatives.filter((r) => /^[234]:[234]$/.test(r.ratio) && r.steady).map((r) => r.score));
|
|
543
|
+
switchedFrom = win ? base.bpm : null;
|
|
544
|
+
}
|
|
545
|
+
if (st) fit = { method: st.steady || forced ? 'steady' : 'tracked', residualMs: Math.round(st.rms * 10000) / 10, driftMs: Math.round(st.maxLocal * 10000) / 10, matched: r3(st.matched), ...(forced ? { forcedBpm: forced } : {}), ...(switchedFrom ? { switchedFrom } : {}) };
|
|
546
|
+
const useLine = st ? (forced ? true : st.steady && (gridOK || st.matched >= 0.3)) : gridOK;
|
|
547
|
+
if (useLine) {
|
|
548
|
+
const p = st ? st.period : cb.p * hopSec, ph = (((st ? st.phase : cb.ph * hopSec) % p) + p) % p;
|
|
549
|
+
period = p; beats = [];
|
|
550
|
+
for (let k = 0; ph + k * p <= end + 1e-9; k++) beats.push(r3(ph + k * p + FLUX_LEAD));
|
|
252
551
|
} else {
|
|
253
552
|
beats = ts.map(r3).filter((v) => v <= end + 1e-9);
|
|
254
553
|
period = ts.length > 1 ? (ts.at(-1) - ts[0]) / (ts.length - 1) : tp.period * hopSec;
|
|
255
554
|
}
|
|
555
|
+
// A 16th-note groove has equal hits at four places in every beat; the strongest is not always the beat. Where several
|
|
556
|
+
// places are about as strong, the chord changes decide (they happen on bar lines).
|
|
557
|
+
const nov = (t) => (novAt(H, t - 0.03) + novAt(H, t) + novAt(H, t + 0.03)) / 3;
|
|
558
|
+
const barTable = (bs) => { const v = [0, 0, 0, 0], c = [0, 0, 0, 0]; bs.forEach((t, i) => { if (t > 1 && t < end - 1) { v[i % 4] += nov(t); c[i % 4]++; } }); return v.map((x, j) => (c[j] ? x / c[j] : 0)); };
|
|
559
|
+
let shifted = 0;
|
|
560
|
+
if (useLine && st) {
|
|
561
|
+
const base = st.shiftScore(0), grids = [];
|
|
562
|
+
for (const q of [1, 3]) if (st.shiftScore((q * st.period) / 4) >= 0.7 * base) grids.push(q); // a 16th early or late; the 8th-note offbeat is a groove, not an error
|
|
563
|
+
if (grids.length) {
|
|
564
|
+
const make = (q) => { const p = period, ph0 = (beats[0] - FLUX_LEAD + (q * p) / 4) % p, o = []; for (let k = 0; ph0 + k * p <= end + 1e-9; k++) o.push(r3(ph0 + k * p + FLUX_LEAD)); return o; };
|
|
565
|
+
const top = (bs) => Math.max(...barTable(bs));
|
|
566
|
+
let bestQ = 0, bestV = top(beats);
|
|
567
|
+
for (const q of grids) { const v = top(make(q)); if (v > bestV * 1.3) { bestV = v; bestQ = q; } }
|
|
568
|
+
if (bestQ) { beats = make(bestQ); shifted = bestQ; }
|
|
569
|
+
}
|
|
570
|
+
}
|
|
256
571
|
const bpm = Math.round(60 / period * 100) / 100;
|
|
257
572
|
|
|
258
573
|
// confidence: periodic (autocorrelation) × beats land on real onsets × onsets stand out from the background
|
|
@@ -262,7 +577,8 @@ export function analyze({ L, R, rate }) {
|
|
|
262
577
|
const c1 = clamp((tp.acf - 0.1) / 0.4), c2 = clamp(hit / nb / 0.6), c3 = clamp((atBeat / nb - 1.5) / 3);
|
|
263
578
|
// absolute gate: normalizing by the std would turn the numerical fuzz of a steady pad into "rhythm"
|
|
264
579
|
const c4 = clamp((mean - 0.3) / 0.6);
|
|
265
|
-
|
|
580
|
+
// a count that another tempo explains about as well is a count to doubt (see `alternatives`)
|
|
581
|
+
const confidence = r3(Math.cbrt(c1 * c2 * c3) * c4 / Math.min(2, 1 + Math.max(0, ambiguity - 0.7)));
|
|
266
582
|
const clear = confidence >= 0.3;
|
|
267
583
|
|
|
268
584
|
// mean square over [a, b) seconds from the 10 ms blocks, edge blocks weighted by overlap
|
|
@@ -279,8 +595,16 @@ export function analyze({ L, R, rate }) {
|
|
|
279
595
|
const bm = meanOf(bassAt), em = meanOf(beatE);
|
|
280
596
|
const phase = [0, 0, 0, 0];
|
|
281
597
|
beats.forEach((_, i) => { phase[i % 4] += bassAt[i] / bm + 0.5 * Math.max(0, (beatE[i] - (beatE[i - 1] ?? beatE[i])) / em); });
|
|
598
|
+
// the bar line: where the chords change, confirmed by the drums' own accent; a track whose harmony does not move
|
|
599
|
+
// (a drone, a loop) falls back to the accent alone
|
|
600
|
+
const hs = barTable(beats), hm = meanOf(hs), am = meanOf(phase), hn = hs.map((v) => v / (hm || 1)), an = phase.map((v) => v / am);
|
|
601
|
+
// clear when one phase's chord change stands out from the next best (a snare on 2 and 4 smears the chroma on two phases, so two
|
|
602
|
+
// phases high is the drums, not the chords) and from the track's usual amount of change
|
|
603
|
+
const hsSorted = [...hs].sort((a, b) => b - a), chordsClear = hm > 0 && hsSorted[0] >= 1.4 * hsSorted[1] && hsSorted[0] >= 1.5 * H.mean;
|
|
604
|
+
const total = hn.map((v, j) => (chordsClear ? 2 * v : 0) + an[j]);
|
|
282
605
|
let ph = 0;
|
|
283
|
-
for (let p = 1; p < 4; p++) if (
|
|
606
|
+
for (let p = 1; p < 4; p++) if (total[p] > total[ph] * 1.0001) ph = p;
|
|
607
|
+
const bars = { basis: chordsClear ? 'chords' : 'accent', chordContrast: r3(Math.max(...hn) / Math.max(1e-9, (hn.reduce((a, v) => a + v, 0) - Math.max(...hn)) / 3)), accentPhase: phase.indexOf(Math.max(...phase)), phase: ph };
|
|
284
608
|
const downbeats = beats.filter((_, i) => i % 4 === ph);
|
|
285
609
|
|
|
286
610
|
// bars (or 4 s blocks without a pulse) → loudness → sections and drops
|
|
@@ -319,7 +643,12 @@ export function analyze({ L, R, rate }) {
|
|
|
319
643
|
if (c.score < 0.05 || drops.length >= 3) break;
|
|
320
644
|
if (drops.every((d) => Math.abs(d.t - c.t) > 4 * period * 1.5)) drops.push(c);
|
|
321
645
|
}
|
|
322
|
-
|
|
646
|
+
let map = null;
|
|
647
|
+
try { if (downbeats.length >= 3) map = buildBarMap({ F, H, downbeats, end, ms, beatLen: period }); } catch { map = null; }
|
|
648
|
+
return { bpm, confidence, alternatives, map, ...(tail ? { tail } : {}), fit: fit && { ...fit, shiftedSixteenths: shifted }, bars, beats, downbeats, sections: outSections, drops, end, duration: r3(duration) };
|
|
323
649
|
}
|
|
324
650
|
|
|
325
|
-
export const analyzeFile = (file) => analyze(decode(file));
|
|
651
|
+
export const analyzeFile = (file, opts) => analyze(decode(file), opts);
|
|
652
|
+
|
|
653
|
+
// for the regression scripts and tests that look inside (not part of the API)
|
|
654
|
+
export const _internals = { chordPeriods, periodFit, harmony, novAt, features, envelope, fitSteady, fineEnv, FINE_HOP, FLUX_LEAD };
|
package/cli/lib/check.js
CHANGED
|
@@ -13,6 +13,7 @@ import zlib from 'node:zlib';
|
|
|
13
13
|
import { openFilm } from './capture.js';
|
|
14
14
|
import { isHdr, probeVideo } from './frames.js';
|
|
15
15
|
import { OmError, readSource, readVariables } from './project.js';
|
|
16
|
+
import { CUT_TOLERANCE, cutAlignment } from './track.js';
|
|
16
17
|
|
|
17
18
|
const GENERIC = new Set(['serif', 'sans-serif', 'monospace', 'cursive', 'fantasy', 'system-ui', 'ui-sans-serif', 'ui-serif', 'ui-monospace', 'ui-rounded', '-apple-system', 'blinkmacsystemfont', 'emoji', 'math', 'fangsong', 'inherit', 'initial', 'unset', 'revert', 'none']);
|
|
18
19
|
|
|
@@ -227,6 +228,21 @@ export async function checkPage(project, { samples = 24, fps = 30, onLog = () =>
|
|
|
227
228
|
return { root: r && parseFloat(r.getAttribute('data-duration')) || null, tl: tls.reduce((m, t) => Math.max(m, t.duration()), 0), sound: a ? parseFloat(a.getAttribute('data-duration')) : null }; })()`);
|
|
228
229
|
if (book.root && book.tl > book.root + 0.05) add('warning', 'cut-off', `the timeline runs ${book.tl.toFixed(2)}s but the root says data-duration="${book.root}" — the end is cut off`);
|
|
229
230
|
if (book.sound != null && Math.abs(book.sound - dur) > 0.1) add('warning', 'stale-sound', `the soundtrack is ${book.sound.toFixed(2)}s, the film ${dur.toFixed(2)}s — run om sound`);
|
|
231
|
+
// external music: its file is there, its beat map is current, and the scene cuts sit on its beats
|
|
232
|
+
const mus = await film.evaluate(`(() => { const o = window.__om || {}, m = o.sound ? o.sound().music : null; return { src: m && m.src || null, map: o.beatData ? o.beatData() : null }; })()`);
|
|
233
|
+
if (mus.src) {
|
|
234
|
+
if (!existsSync(resolve(project.root, mus.src))) add('error', 'music-missing', `OM.music({ src: '${mus.src}' }): no such file — put the track in assets/music/ (om sound --music <file> does it)`);
|
|
235
|
+
else if (!mus.map || mus.map.src !== mus.src) add('warning', 'music-beats', `OM.music({ src: '${mus.src}' }) has no beat map in index.html yet — run om sound, then OM.beat / OM.downbeat / OM.drop follow the track`);
|
|
236
|
+
else {
|
|
237
|
+
const cuts = Object.entries(info.labels || {}).filter(([k]) => k.startsWith('scene:')).map(([name, t]) => ({ name, t }));
|
|
238
|
+
const al = cutAlignment(cuts, { ...mus.map, duration: dur });
|
|
239
|
+
if (al === null) add('warning', 'music-pulse', `the track has no clear pulse (confidence ${mus.map.confidence}) — scene cuts cannot be put on its beat; trust its sections (OM.section(i)), not its beats`);
|
|
240
|
+
else {
|
|
241
|
+
const off = al.filter((c) => !c.ok);
|
|
242
|
+
if (off.length) add('warning', 'cut-off-beat', `${off.length} of ${al.length} scene cuts sit more than ${Math.round(CUT_TOLERANCE * 1000)} ms from the nearest beat of the track: ${off.slice(0, 6).map((c) => `${c.name} ${c.t.toFixed(2)}s (${c.off > 0 ? '+' : ''}${c.off} ms)`).join(', ')}${off.length > 6 ? ', …' : ''} — place them on OM.beat(n) / OM.downbeat(n)`, off[0].t);
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
}
|
|
230
246
|
for (const [k, v] of Object.entries(info.labels || {})) if (k.startsWith('scene:') && v >= dur) add('warning', 'scene-after-end', `${k} starts at ${v.toFixed(2)}s, at or after the end (${dur.toFixed(2)}s)`);
|
|
231
247
|
// footage the renderer cannot use
|
|
232
248
|
for (const m of await film.media()) {
|