// hear.mjs: listen to the film and report what the two ears say. Reads the film's own
// soundtrack only; it does not know the drums, only the film's clock and its declared
// damping rule (spine.mjs).
//
//   node hear.mjs film.mp4          (needs ffmpeg on PATH to decode)
//   node hear.mjs audio.wav         (16-bit stereo WAV, 48 kHz)
//
// 1. NOTES   the pitch of each ear in each of the twelve note windows. Equal notes: the two
//            ears agree. It also prints each note's ratio to the first.
// 2. STRIKE  after each solo strike, a least-squares fit of that ear to the twelve heard
//            pitches with the declared damping gives each note's loudness. The drums are
//            called "the same" only if the loudness ratios (note 2 : note 1, note 3 : note 1)
//            of the left strikes match the right strikes' within 10 per cent.
// 3. HEAT    near the end of the heat section, the loudness of the lowest note in each ear.
import { readFileSync, existsSync } from 'node:fs';
import { execFileSync } from 'node:child_process';
import { SR, NOTES, NOTE_LEN, STRIKES, STRIKE_WINDOW, HEAT, dampOf } from './spine.mjs';

export function readWav(buf) {
  let p = 12, fmt = null, data = null;
  while (p < buf.length - 8) { const id = buf.toString('ascii', p, p + 4), sz = buf.readUInt32LE(p + 4);
    if (id === 'fmt ') fmt = { ch: buf.readUInt16LE(p + 10), sr: buf.readUInt32LE(p + 12), bits: buf.readUInt16LE(p + 22) };
    if (id === 'data') { data = [p + 8, Math.min(sz, buf.length - p - 8)]; break; } p += 8 + sz + (sz & 1); }
  if (!fmt || fmt.ch !== 2 || fmt.bits !== 16 || fmt.sr !== SR) throw new Error(`need 16-bit stereo ${SR} Hz WAV`);
  const n = Math.floor(data[1] / 4), L = new Float64Array(n), R = new Float64Array(n);
  for (let i = 0; i < n; i++) { L[i] = buf.readInt16LE(data[0] + 4 * i) / 32767; R[i] = buf.readInt16LE(data[0] + 4 * i + 2) / 32767; }
  return { L, R };
}
export function load(file) {
  if (file.endsWith('.wav')) return readWav(readFileSync(file));
  const out = execFileSync('ffmpeg', ['-v', 'error', '-i', file, '-vn', '-ac', '2', '-ar', String(SR), '-f', 'wav', '-acodec', 'pcm_s16le', '-'], { maxBuffer: 1 << 30 });
  return readWav(out);
}

// |windowed DFT| at frequency f over samples [a, b)
function mag(x, a, b, f) { let re = 0, im = 0; const n = b - a, w = 2 * Math.PI * f / SR;
  for (let i = 0; i < n; i++) { const h = 0.5 - 0.5 * Math.cos(2 * Math.PI * i / (n - 1)), v = x[a + i] * h; re += v * Math.cos(w * i); im -= v * Math.sin(w * i); }
  return Math.hypot(re, im); }
function fft(re, im) {              // in place, radix 2
  const n = re.length;
  for (let i = 1, j = 0; i < n; i++) { let bit = n >> 1; for (; j & bit; bit >>= 1) j ^= bit; j ^= bit; if (i < j) { [re[i], re[j]] = [re[j], re[i]]; [im[i], im[j]] = [im[j], im[i]]; } }
  for (let len = 2; len <= n; len <<= 1) { const ang = -2 * Math.PI / len, wr = Math.cos(ang), wi = Math.sin(ang);
    for (let i = 0; i < n; i += len) { let cr = 1, ci = 0;
      for (let k = 0; k < len / 2; k++) { const ur = re[i + k], ui = im[i + k], vr = re[i + k + len / 2] * cr - im[i + k + len / 2] * ci, vi = re[i + k + len / 2] * ci + im[i + k + len / 2] * cr;
        re[i + k] = ur + vr; im[i + k] = ui + vi; re[i + k + len / 2] = ur - vr; im[i + k + len / 2] = ui - vi; const t = cr * wr - ci * wi; ci = cr * wi + ci * wr; cr = t; } } }
}
export function pitch(x, t0, t1) {
  const a = Math.round(t0 * SR), b = Math.round(t1 * SR), n = b - a, N = 1 << 18;
  const re = new Float64Array(N), im = new Float64Array(N);
  for (let i = 0; i < n; i++) re[i] = x[a + i] * (0.5 - 0.5 * Math.cos(2 * Math.PI * i / (n - 1)));
  fft(re, im);
  let bi = 0, best = 0; for (let i = Math.floor(60 * N / SR); i < 1200 * N / SR; i++) { const m = re[i] * re[i] + im[i] * im[i]; if (m > best) { best = m; bi = i; } }
  const bf = bi * SR / N, step = SR / N;
  let lo = bf - step, hi = bf + step; const g = (Math.sqrt(5) - 1) / 2;       // golden-section refine
  for (let it = 0; it < 40; it++) { const c = hi - g * (hi - lo), d = lo + g * (hi - lo); if (mag(x, a, b, c) > mag(x, a, b, d)) hi = d; else lo = c; }
  return (lo + hi) / 2;
}
function solve(A, y) { const n = y.length; const M = A.map((r, i) => [...r, y[i]]);
  for (let c = 0; c < n; c++) { let p = c; for (let r = c + 1; r < n; r++) if (Math.abs(M[r][c]) > Math.abs(M[p][c])) p = r; [M[c], M[p]] = [M[p], M[c]];
    for (let r = 0; r < n; r++) if (r !== c) { const f = M[r][c] / M[c][c]; for (let k = c; k <= n; k++) M[r][k] -= f * M[c][k]; } }
  return M.map((r, i) => r[n] / r[i]); }
/** loudness of each heard pitch after a strike at t0 (cos and sin parts, declared damping) */
export function weights(x, t0, freqs, len = STRIKE_WINDOW) {
  const a = Math.round(t0 * SR), n = Math.round(len * SR), K = freqs.length, P = 2 * K;
  const G = Array.from({ length: P }, () => new Float64Array(P)), y = new Float64Array(P), b = new Float64Array(P);
  for (let i = 0; i < n; i += 2) { const u = i / SR;
    for (let k = 0; k < K; k++) { const e = Math.exp(-u / dampOf(freqs[k])), w = 2 * Math.PI * freqs[k] * u; b[2 * k] = e * Math.cos(w); b[2 * k + 1] = e * Math.sin(w); }
    for (let p = 0; p < P; p++) { y[p] += b[p] * x[a + i]; for (let q = 0; q <= p; q++) G[p][q] += b[p] * b[q]; } }
  for (let p = 0; p < P; p++) for (let q = p + 1; q < P; q++) G[p][q] = G[q][p];
  const c = solve(G.map((r) => Array.from(r)), Array.from(y));
  return freqs.map((_, k) => Math.hypot(c[2 * k], c[2 * k + 1]));
}
function rms(x, t0, t1) { let s = 0; const a = Math.round(t0 * SR), b = Math.round(t1 * SR); for (let i = a; i < b; i++) s += x[i] * x[i]; return Math.sqrt(s / (b - a)); }

export function hear({ L, R }) {
  const notes = [];
  for (let k = 0; k < 12; k++) { const t0 = NOTES[0] + k * NOTE_LEN + 0.3, t1 = t0 + NOTE_LEN - 0.9; notes.push({ k: k + 1, L: pitch(L, t0, t1), R: pitch(R, t0, t1) }); }
  const f = notes.map((n) => (n.L + n.R) / 2);
  const strikes = STRIKES.filter((s) => s.ears !== 'LR').map((s) => {
    const x = s.ears === 'L' ? L : R, other = s.ears === 'L' ? R : L;
    const w = weights(x, s.t, f);
    return { t: s.t, ear: s.ears, w, r2: w[1] / w[0], r3: w[2] / w[0], otherRms: rms(other, s.t + 0.2, s.t + STRIKE_WINDOW), rms: rms(x, s.t + 0.2, s.t + STRIKE_WINDOW) };
  });
  const mean = (a) => a.reduce((s, v) => s + v, 0) / a.length;
  const Ls = strikes.filter((s) => s.ear === 'L'), Rs = strikes.filter((s) => s.ear === 'R');
  const left = { r2: mean(Ls.map((s) => s.r2)), r3: mean(Ls.map((s) => s.r3)) }, right = { r2: mean(Rs.map((s) => s.r2)), r3: mean(Rs.map((s) => s.r3)) };
  const close = (p, q) => Math.abs(p - q) <= 0.1 * Math.max(p, q) || Math.abs(p - q) < 0.01;
  const same = close(left.r2, right.r2) && close(left.r3, right.r3);
  // the lowest note near the end of the heat section (plain fit, no damping: it is held)
  const h0 = HEAT[1] - 6, h1 = HEAT[1] - 2.5;
  const hw = (x) => { const a = Math.round(h0 * SR), b = Math.round(h1 * SR); let c = 0, s = 0, cc = 0, ss = 0; for (let i = a; i < b; i++) { const w = 2 * Math.PI * f[0] * i / SR; c += x[i] * Math.cos(w); s += x[i] * Math.sin(w); cc += Math.cos(w) ** 2; ss += Math.sin(w) ** 2; } return Math.hypot(c / cc, s / ss); };
  const heat = { L: hw(L), R: hw(R) }; heat.ratio = heat.R / heat.L;
  return { notes, strikes, left, right, same, heat };
}

if (process.argv[1] && process.argv[1].endsWith('hear.mjs')) {
  const file = process.argv[2];
  if (!file || !existsSync(file)) { console.error('usage: node hear.mjs <film.mp4 | audio.wav>'); process.exit(2); }
  const h = hear(load(file));
  console.log('NOTES (Hz)          left        right      right/left - 1   ratio to note 1');
  for (const n of h.notes) console.log(`  note ${String(n.k).padStart(2)}   ${n.L.toFixed(4).padStart(10)}  ${n.R.toFixed(4).padStart(10)}   ${(n.R / n.L - 1).toExponential(1).padStart(9)}        ${(n.L / h.notes[0].L).toFixed(5)}`);
  console.log('\nSTRIKES (loudness of notes 1, 2, 3 in the struck ear; the other ear holds only the fading tail of its own last strike)');
  for (const s of h.strikes) console.log(`  ${s.t.toFixed(1).padStart(6)} s  ${s.ear}   ${s.w.slice(0, 3).map((x) => x.toFixed(4)).join('  ')}   note2/note1 ${s.r2.toFixed(3)}  note3/note1 ${s.r3.toFixed(3)}   other ear rms ${s.otherRms.toExponential(1)}`);
  console.log(`  left ear:  note2/note1 ${h.left.r2.toFixed(3)}  note3/note1 ${h.left.r3.toFixed(3)}`);
  console.log(`  right ear: note2/note1 ${h.right.r2.toFixed(3)}  note3/note1 ${h.right.r3.toFixed(3)}`);
  console.log(`  verdict: the two drums, struck, sound ${h.same ? 'THE SAME' : 'DIFFERENT'}`);
  console.log(`\nHEAT  lowest note near the end: left ${h.heat.L.toFixed(4)}  right ${h.heat.R.toFixed(4)}  right/left ${h.heat.ratio.toFixed(4)}`);
}
