bstein: serve passive RCT mic watch and log its numeric receipts

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
jenkins 2026-12-03 13:59:48 -06:00
parent 2dc8a40e92
commit 0e05c0cd38
7 changed files with 285 additions and 7 deletions

View File

@ -10,6 +10,9 @@ configMapGenerator:
files: [nginx.conf]
- name: lesavka-av-observer-assets
files:
- mic-entry.js
- mic-watch.js
- watch-worklet.js
- speech-reference.flac
- speech-alignment.js
- speech-detector.js

View File

@ -0,0 +1,41 @@
// mic.html?mode=watch: passive long watch; otherwise the existing mic page.
const watchMode=new URLSearchParams(location.search).get('mode')==='watch';
if(!watchMode) await import('./mic-observer.js');
else {
const {WatchSession}=await import('./mic-watch.js');
const el=id=>document.getElementById(id);
for(const id of ['output','tone','tone-stop','stage-label','local-review','output-status','output-report','path-link'])
(el(id).closest('label')??el(id)).hidden=true;
document.querySelector('h1').textContent='Passive mic watch';
el('start').textContent='Start watch';el('start').title='Holds the selected microphone open up to 24 h; numeric report every 10 s.';
let session=null,last=null;
const buttons=()=>{el('start').disabled=!!session||!el('input').value;el('stop').disabled=!session;
el('devices').disabled=!!session;el('input').disabled=!!session;el('save').disabled=!last;};
const show=s=>{last={watchId:s.id,events:s.events,last:{...s.last,_stats:undefined}};
el('level').value=(s.last?.peakE5??0)/1e5;el('metrics').textContent=JSON.stringify(last,null,2);buttons();};
el('devices').onclick=async()=>{
try {
const stream=await navigator.mediaDevices.getUserMedia({audio:true,video:false});
for(const t of stream.getTracks())t.stop();
const select=el('input'),saved=select.value;select.replaceChildren(new Option('Select device',''));
for(const d of await navigator.mediaDevices.enumerateDevices())
if(d.kind==='audioinput'&&!['default','communications'].includes(d.deviceId))select.add(new Option(d.label||'Unnamed device',d.deviceId));
select.value=saved;el('status').textContent='Select the USB microphone';
} catch {el('status').textContent='Device permission unavailable';}
buttons();
};
el('input').onchange=buttons;
el('start').onclick=async()=>{
if(session||!el('input').value)return;
session=new WatchSession({deviceId:el('input').value,status:t=>{el('status').textContent=t;},show});
session.reports.status=t=>{el('report-status').textContent=t;};
buttons();await session.start();
};
el('stop').onclick=()=>{session?.stop();if(session)show(session);session=null;buttons();};
el('save').onclick=()=>{
const url=URL.createObjectURL(new Blob([JSON.stringify(last,null,2)],{type:'application/json'}));
const a=document.createElement('a');a.href=url;a.download='mic-watch.json';a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);
};
window.addEventListener('pagehide',()=>session?.stop('page closed'));
buttons();
}

View File

@ -0,0 +1,167 @@
// 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}`);
}
}

View File

@ -2,7 +2,7 @@
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Audio Test</title><link rel="stylesheet" href="style.css">
<main><h1>Audio Test</h1><a href="./">A/V Test</a>
<p><a id="path-link" href="mic.html?test=phone">Staged RCT receiver test</a> <a href="phone.html">Phone sound source</a></p>
<p><a id="path-link" href="mic.html?test=phone">Staged RCT receiver test</a> <a href="phone.html">Phone sound source</a> <a href="mic.html?mode=watch">Passive watch</a></p>
<p id="path-state" role="status" title="Level drops require at least 100 ms at least 20 dB below the recognized phone reference." hidden></p>
<p id="path-detail" hidden></p><p id="path-timing" hidden></p>
<div><button id="devices">Choose devices…</button>
@ -20,4 +20,4 @@
<p id="output-report">Output reporting idle</p>
<meter id="level" min="0" max="1" value="0" title="Current microphone peak"></meter>
<pre id="selection"></pre><pre id="metrics">No observations</pre>
</main><script type="module" src="mic-observer.js"></script></html>
</main><script type="module" src="mic-entry.js"></script></html>

View File

@ -28,11 +28,23 @@ http {
default "";
'~^1[|]1,' 1;
}
map $http_x_av_watch $av_watch {
default "";
'~^1(,-?[0-9]{1,13}){31}(;[0-9]{1,6},[0-9]{1,2},[0-9]{13}){0,16}$' $http_x_av_watch;
}
map "$uri|$upstream_status|$av_identity|$av_watch" $av_watch_ack {
default "";
'~^/av-test/api/report[|]204[|][^|]+[|]1,' 1;
}
map "$av_ack$av_watch_ack" $av_log {
default 1;
"" 0;
}
map "$uri|$upstream_status" $av_clock {
default "";
"/av-test/api/start|201" $msec;
}
log_format av_stage escape=json '{"schema":"av-test.acoustic-stage.v1","received":"$msec","receipt":"$av_identity","stage":"$av_annotation","speech":"$av_speech"}';
log_format av_stage escape=json '{"schema":"av-test.acoustic-stage.v1","received":"$msec","receipt":"$av_identity","stage":"$av_annotation","speech":"$av_speech","watch":"$av_watch"}';
server_tokens off;
client_max_body_size 4k;
client_body_timeout 5s;
@ -48,6 +60,7 @@ http {
root /usr/share/nginx/html;
add_header X-AV-Clock $av_clock always;
add_header X-AV-Speech-Ack $av_speech_ack always;
add_header X-AV-Watch-Ack $av_watch_ack always;
add_header X-AV-Stage-Ack $av_ack always;
add_header Cache-Control "no-store" always;
add_header X-Content-Type-Options "nosniff" always;
@ -72,12 +85,12 @@ http {
if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files /av-test/index.html =404;
}
location ~ ^/av-test/(speech-reference\.flac|speech-alignment\.js|speech-detector\.js|speech-envelope\.js|speech-watch\.js|speech-worklet\.js|acoustic-detector\.js|acoustic-pattern\.js|acoustic-watch\.js|acoustic-worklet\.js|acoustic-timing\.js|phone-source\.js|phone\.html|mic\.html|mic-observer\.js|mic-reporting\.js|mic-output\.js|index\.html|observer\.js|local-recording\.js|review-controls\.js|metrics\.js|reporting\.js|activity-worklet\.js|paired-observer\.js|paired-worklet\.js|paired-signals\.js|test-signals\.js|continuity-signals\.js|pilot-window\.js|capture-lifecycle\.js|continuity-watch\.js|style\.css)$ {
location ~ ^/av-test/(mic-entry\.js|mic-watch\.js|watch-worklet\.js|speech-reference\.flac|speech-alignment\.js|speech-detector\.js|speech-envelope\.js|speech-watch\.js|speech-worklet\.js|acoustic-detector\.js|acoustic-pattern\.js|acoustic-watch\.js|acoustic-worklet\.js|acoustic-timing\.js|phone-source\.js|phone\.html|mic\.html|mic-observer\.js|mic-reporting\.js|mic-output\.js|index\.html|observer\.js|local-recording\.js|review-controls\.js|metrics\.js|reporting\.js|activity-worklet\.js|paired-observer\.js|paired-worklet\.js|paired-signals\.js|test-signals\.js|continuity-signals\.js|pilot-window\.js|capture-lifecycle\.js|continuity-watch\.js|style\.css)$ {
if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files $uri =404;
}
location ~ ^/av-test/api/(start|report)$ {
access_log /dev/stdout av_stage if=$av_ack;
access_log /dev/stdout av_stage if=$av_log;
if ($request_method != POST) { return 405; }
proxy_pass http://127.0.0.1:8081;
proxy_connect_timeout 2s;

View File

@ -120,7 +120,7 @@ export class RunReporter {
queue(state,receipt) {
// One latest snapshot, not a growing queue. Terminal state supersedes
// pending progress; a stopped run never becomes running again.
this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot};
this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot,watch:receipt.audio?.watch};
void this.flush();
}
async flush() {
@ -137,6 +137,8 @@ export class RunReporter {
if(stage)headers['X-AV-Stage']=stage;
const speech=speechReceipt(report.path?.speech);
if(speech)headers['X-AV-Speech']=speech;
const watch=typeof report.watch==='function'?report.watch():null;
if(watch)headers['X-AV-Watch']=watch;
let delivered=false;
for(let attempt=0;attempt<2&&!delivered;attempt++) {
try {
@ -146,7 +148,8 @@ export class RunReporter {
body:JSON.stringify(payload),signal:AbortSignal.timeout(5000),
});
delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1')) &&
(!report.path?.speech || (speech && response.headers?.get?.('X-AV-Speech-Ack')==='1'));
(!report.path?.speech || (speech && response.headers?.get?.('X-AV-Speech-Ack')==='1')) &&
(!watch || response.headers?.get?.('X-AV-Watch-Ack')==='1');
if(response.status>=400&&response.status<500)break;
} catch { /* No raw exception or endpoint response is displayed. */ }
}

View File

@ -0,0 +1,51 @@
// 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;
}
});
}