// Passive hours-long watch of one explicitly selected microphone. Numeric only. import {AudioReports} from './mic-reporting.js'; import {stopTracks} from './capture-lifecycle.js'; export const EVENTS={mute:1,unmute:2,ended:3,devicechange:4,'context-running':5,'context-suspended':6, 'context-closed':7,'context-interrupted':7,hidden:8,visible:9,freeze:10,resume:11, 'restart-attempt':12,'restart-ok':13,'restart-failed':14,'capture-started':15,'observer-error':16, 'worklet-stale':17,stop:18}; const CONTEXT={running:0,suspended:1,closed:2,interrupted:3}; const RETRY=[2000,5000,15000,30000,60000]; const LIMIT_MS=24*3600000; // Field order is the X-AV-Watch wire contract (see correlate-watch.mjs). export const FIELDS=['version','watchId','seq','sentUnixMs','intervalMs','contextFrames','contextRate', 'callbackGaps','callbackGapMaxMs','callbackGapStartUnixMs','rmsE5','peakE5','zeroFrames', 'zeroRunMaxMs','zeroRunStartUnixMs','deviceFrames','deviceDeliveredFrames','deviceDurationMs', 'frameDeficitMs','mutes','unmutes','ends','deviceChanges','contextChanges','visibilityChanges', 'hidden','contextState','trackState','restarts','timerLateMaxMs','messageLatencyMaxMs','workletAgeMs']; export function watchHeader(values, events) { const ints=FIELDS.map(k=>Math.round(values[k]??-1)); if(ints.some(v=>!Number.isSafeInteger(v)||Math.abs(v)>9999999999999))return null; const rows=events.slice(-16).map(e=>[e.serial,e.kind,e.at].join(',')); return [ints.join(','),...rows].join(';'); } export class WatchSession { constructor({deviceId,status,show,media=navigator.mediaDevices,Context=globalThis.AudioContext, Node=globalThis.AudioWorkletNode,Reports=AudioReports,now=()=>Date.now(),mono=()=>performance.now()}) { Object.assign(this,{deviceId,status,show,media,Context,Node,now,mono}); this.reports=new Reports(status); this.id=1+Math.floor(Math.random()*999999998);this.seq=0;this.events=[];this.serial=0; this.count={mutes:0,unmutes:0,ends:0,deviceChanges:0,contextChanges:0,visibilityChanges:0,restarts:0}; this.total={frames:0,zero:0};this.reset();this.live=null;this.stopped=false;this.failures=0; } reset(stats=null) { this.iv={frames:0,energy:0,peak:0,zero:0,gaps:0,gapMax:0,gapStart:0,zeroMax:0,zeroStart:0, late:0,latency:0,since:this.now(),stats}; } event(name) { const kind=EVENTS[name];if(!kind)return; this.events.push({serial:++this.serial,kind,at:this.now()}); if(this.events.length>16)this.events.shift(); } async start() { this.started=this.now();this.timerAt=this.mono(); this.timer=setInterval(()=>this.tick(),10000); this.deadline=setTimeout(()=>this.stop('24 hours complete'),LIMIT_MS); this.listeners=[[this.media,'devicechange',()=>{this.count.deviceChanges++;this.event('devicechange');}], [globalThis.document,'visibilitychange',()=>{this.count.visibilityChanges++;this.event(document.hidden?'hidden':'visible');}], [globalThis.document,'freeze',()=>this.event('freeze')],[globalThis.document,'resume',()=>this.event('resume')]]; for(const [target,name,fn] of this.listeners)target?.addEventListener?.(name,fn); await this.open(); } async open() { const live={};this.live=live; try { const stream=await this.media.getUserMedia({video:false,audio:{deviceId:{exact:this.deviceId}, echoCancellation:false,noiseSuppression:false,autoGainControl:false}}); live.stream=stream; if(this.live!==live||this.stopped){stopTracks(stream);return;} const track=live.track=stream.getAudioTracks()[0]; // Never accept a substituted device. if(track?.getSettings().deviceId!==this.deviceId)throw new Error('selection'); track.onmute=()=>{this.count.mutes++;this.event('mute');}; track.onunmute=()=>{this.count.unmutes++;this.event('unmute');}; track.onended=()=>{this.count.ends++;this.event('ended');this.restart();}; const context=live.context=new this.Context({sinkId:{type:'none'}}); if(typeof context.setSinkId!=='function')throw new Error('silent sink'); await context.setSinkId({type:'none'}); await context.audioWorklet.addModule('watch-worklet.js'); if(this.live!==live)return; const node=live.node=new this.Node(context,'av-watch'); node.onprocessorerror=()=>{this.event('observer-error');this.restart();}; node.port.onmessage=({data})=>this.second(data); live.source=context.createMediaStreamSource(stream);live.source.connect(node);node.connect(context.destination); context.onstatechange=()=>{ this.count.contextChanges++;this.event('context-'+context.state); if(context.state==='suspended'||context.state==='interrupted') setTimeout(()=>{if(this.live===live)void context.resume().catch(()=>{});},1000); if(context.state==='closed')this.restart(); }; await context.resume(); this.iv.stats=this.deviceStats(); this.event('capture-started');this.failures=0;this.workletAt=this.mono(); this.status(`Watching · ${track.label}`); } catch { if(this.live===live&&!this.stopped){this.event('restart-failed');this.restart();} } } deviceStats() { const s=this.live?.track?.stats; return s&&typeof s.totalFrames==='number'?{total:s.totalFrames,delivered:s.deliveredFrames, durationMs:s.totalFramesDuration}:null; } release(live) { if(!live)return; stopTracks(live.stream); try{live.node.port.onmessage=null;live.node.port.postMessage('stop');live.node.disconnect();}catch{} try{live.source.disconnect();}catch{} if(live.context){live.context.onstatechange=null;void live.context.close().catch(()=>{});} } restart() { const old=this.live;if(!old||this.stopped)return; this.live=null;this.release(old); const wait=RETRY[Math.min(this.failures++,RETRY.length-1)]; this.status(`Capture lost · retrying same microphone in ${wait/1000} s`); setTimeout(async()=>{ if(this.stopped||this.live)return; this.event('restart-attempt');await this.open(); if(this.live?.node){this.count.restarts++;this.event('restart-ok');} },wait); } second(d) { const iv=this.iv;this.workletAt=this.mono();this.stale=false; this.iv.latency=Math.max(iv.latency,this.now()-d.at);this.rate=d.rate; iv.frames+=d.frames;iv.energy+=d.rms*d.rms*d.frames;iv.peak=Math.max(iv.peak,d.peak);iv.zero+=d.zeroFrames; this.total.frames+=d.frames;this.total.zero+=d.zeroFrames; if(d.gapMaxMs>iv.gapMax){iv.gapMax=d.gapMaxMs;iv.gapStart=d.gapStart;}iv.gaps+=d.gaps; if(d.zeroRunMs>iv.zeroMax){iv.zeroMax=d.zeroRunMs;iv.zeroStart=d.zeroRunStart;} if(this.now()-iv.since>=10000)this.send(); } tick() { const now=this.mono(); this.iv.late=Math.max(this.iv.late,now-this.timerAt-10000);this.timerAt=now; // Audio-thread messages normally drive reports; the timer covers their absence. if(this.mono()-(this.workletAt??0)>15000) { if(!this.stale)this.event('worklet-stale'); this.stale=true;this.send(); } } values() { const iv=this.iv,now=this.now(),stats=this.deviceStats(),prev=iv.stats; const delta=k=>stats&&prev?stats[k]-prev[k]:-1; const track=this.live?.track; return {version:1,watchId:this.id,seq:++this.seq,sentUnixMs:now,intervalMs:now-iv.since, contextFrames:iv.frames,contextRate:this.rate??-1,callbackGaps:iv.gaps,callbackGapMaxMs:iv.gapMax, callbackGapStartUnixMs:iv.gapStart,rmsE5:iv.frames?1e5*Math.sqrt(iv.energy/iv.frames):0, peakE5:1e5*iv.peak,zeroFrames:iv.zero,zeroRunMaxMs:iv.zeroMax,zeroRunStartUnixMs:iv.zeroStart, deviceFrames:delta('total'),deviceDeliveredFrames:delta('delivered'),deviceDurationMs:delta('durationMs'), frameDeficitMs:this.rate?(now-this.started)-1000*this.total.frames/this.rate:-1,...this.count, hidden:Number(!!globalThis.document?.hidden),contextState:CONTEXT[this.live?.context?.state]??-1, trackState:!track?3:track.readyState==='ended'?2:track.muted?1:0, timerLateMaxMs:Math.max(0,iv.late),messageLatencyMaxMs:Math.max(0,iv.latency), workletAgeMs:this.workletAt===undefined?-1:this.mono()-this.workletAt,_stats:stats}; } snapshot() { const audio={inputFrames:this.total.frames,processedFrames:this.total.frames,exactZeroFrames:this.total.zero, rms:this.iv.frames?Math.sqrt(this.iv.energy/this.iv.frames):0,peak:this.iv.peak,sampleRate:this.rate}; // Evaluated at send time so the sequence counts real transmissions. audio.watch=()=>{const v=this.values();this.last=v;this.reset(v._stats);return watchHeader(v,this.events);}; return audio; } send() { const settings=this.live?.track?.getSettings?.()??{}; this.reports.observe(this.mono(),this.snapshot(),{sampleRate:settings.sampleRate,channelCount:settings.channelCount}); this.show?.(this); } stop(reason='operator') { if(this.stopped)return; this.event('stop');this.stopped=true;clearInterval(this.timer);clearTimeout(this.deadline); for(const [target,name,fn] of this.listeners??[])target?.removeEventListener?.(name,fn); const live=this.live;this.live=null;this.release(live); this.reports.finish(this.mono(),this.snapshot(),{},reason); this.status(`Stopped · ${reason}`); } }