52 lines
2.2 KiB
JavaScript
52 lines
2.2 KiB
JavaScript
// Passive long watch: counts render callbacks and input samples on the audio
|
|
// thread (not subject to page timer throttling). Never copies or sends audio.
|
|
export class WatchCounter {
|
|
constructor(rate, now) {
|
|
this.rate=rate;this.now=now;this.last=0;this.zeroRun=0;this.zeroStart=0;this.reset(now());
|
|
}
|
|
reset(at) {
|
|
this.w={at,blocks:0,frames:0,noInput:0,energy:0,peak:0,zero:0,zeroMax:0,zeroMaxStart:0,
|
|
gaps:0,gapMax:0,gapStart:0};
|
|
}
|
|
block(samples, length) {
|
|
const now=this.now(),w=this.w;
|
|
// A render callback gap: the audio thread itself was not serviced.
|
|
if(this.last && now-this.last>50) {
|
|
w.gaps++;
|
|
if(now-this.last>w.gapMax){w.gapMax=now-this.last;w.gapStart=this.last;}
|
|
}
|
|
this.last=now;w.blocks++;
|
|
if(!samples){w.noInput+=length;this.zeroRun=0;}
|
|
else for(const v of samples) {
|
|
w.frames++;w.energy+=v*v;const a=Math.abs(v);if(a>w.peak)w.peak=a;
|
|
if(v===0) {
|
|
if(!this.zeroRun++)this.zeroStart=now;
|
|
w.zero++;
|
|
if(this.zeroRun>w.zeroMax){w.zeroMax=this.zeroRun;w.zeroMaxStart=this.zeroStart;}
|
|
} else this.zeroRun=0;
|
|
}
|
|
if(now-w.at<1000)return null;
|
|
const out={at:now,startedAt:w.at,blocks:w.blocks,frames:w.frames,noInputFrames:w.noInput,
|
|
rms:w.frames?Math.sqrt(w.energy/w.frames):0,peak:w.peak,zeroFrames:w.zero,
|
|
zeroRunMs:Math.round(w.zeroMax*1000/this.rate),zeroRunStart:w.zeroMaxStart,
|
|
gaps:w.gaps,gapMaxMs:w.gapMax,gapStart:w.gapStart,rate:this.rate};
|
|
this.reset(now);
|
|
return out;
|
|
}
|
|
}
|
|
|
|
if(typeof registerProcessor==='function') {
|
|
registerProcessor('av-watch',class extends AudioWorkletProcessor {
|
|
constructor() {
|
|
super();this.counter=new WatchCounter(sampleRate,()=>Date.now());this.stopped=false;
|
|
this.port.onmessage=({data})=>{if(data==='stop')this.stopped=true;};
|
|
}
|
|
process(inputs,outputs) {
|
|
if(this.stopped)return false;
|
|
const second=this.counter.block(inputs[0]?.[0],outputs[0]?.[0]?.length??128);
|
|
if(second)this.port.postMessage(second);
|
|
return true;
|
|
}
|
|
});
|
|
}
|