67 lines
3.2 KiB
JavaScript

// Match the envelope of the published phrase at any loop position. Clipping
// each band to its own dynamic range tolerates different mic gain/noise floors.
const wrap = (n, length) => ((n % length) + length) % length;
export const phaseDelta = (a, b, length) => wrap(a-b+Math.floor(length/2), length)-Math.floor(length/2);
const LOOKBACK = 125;
function normalized(values) {
const floor = Math.max(...values)-30;
const clipped = values.map(x => Math.max(x, floor));
const mean = clipped.reduce((sum, x) => sum + x, 0) / clipped.length;
const centered = clipped.map(x => x-mean);
const norm = Math.sqrt(centered.reduce((sum,x) => sum+x*x,0));
if (norm < 3 * Math.sqrt(values.length)) return null;
return centered.map(x => x/norm);
}
export class SpeechAlignment {
constructor({levels, highs}) {
this.length = levels.length;
this.bands = [levels, highs];
this.peak = Math.max(...levels);
this.patterns = levels.map((_, phase) => this.bands.map(band =>
normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length]))));
}
match(frames, end) {
if (frames.length < LOOKBACK) return null;
const window = frames.slice(-LOOKBACK);
if (window.some(row=>!row[2])) return null;
const received = [0,1].map(b=>normalized(window.map(row=>row[b])));
if (received.some(band=>!band)) return null;
let best = -1, bestScore = 0;
const scores = this.patterns.map((pattern, i) => {
if (pattern.some(band=>!band)) return -1;
let dot = 0;
for (let k = 0; k < LOOKBACK; k++)
dot += pattern[0][k]*received[0][k] + pattern[1][k]*received[1][k];
const score = dot/2;
if (score>bestScore) { best=i; bestScore=score; }
return score;
});
if (bestScore<0.74 || scores.some((s,i)=>Math.abs(phaseDelta(i,best,this.length))>6 && s>bestScore-0.07)) return null;
const gains = [];
for (let k=0;k<LOOKBACK;k++) {
const expected=this.bands[0][(best+k)%this.length];
if (expected>this.peak-18) gains.push(window[k][0]-expected);
}
if (gains.length<15) return null;
gains.sort((a,b)=>a-b);
return {phase:wrap(best-(end-LOOKBACK),this.length), gain:gains[gains.length>>1]};
}
// A loud unrelated sound can overlap a word without reducing RMS. Examine
// the shape of short, active passages independently of the long phase lock.
unclearPassage(frames, first, anchor) {
const received=frames.map(row=>row[0]);
let best=-1;
for (const delta of [-1,0,1]) {
const expected=received.map((_,i)=>this.expected(first+i,anchor.phase+delta));
if (expected.filter(x=>x>this.peak-20).length<6) return false;
if (Math.max(...received)<Math.max(...expected)+anchor.gain-14) return false;
const a=normalized(expected), b=normalized(received);
if (!a) return false;
if (b) best=Math.max(best,a.reduce((sum,x,i)=>sum+x*b[i],0));
}
return best<0.38;
}
expected(index,phase) { return this.bands[0][wrap(index+phase,this.length)]; }
}