bstein: publish microphone watch and selected output test

Vendor tested Lesavka observer source a1ac564e. Reuse numeric-only receipts; no backend, routing or installed relay changes. Validated Kustomize, client dry-run, 70 Node tests plus recent-level test, and isolated fake-device Chromium capture/output/cleanup.
This commit is contained in:
jenkins 2026-12-03 11:20:27 -06:00
parent 5f84adbf29
commit 64d0eb42f6
8 changed files with 251 additions and 4 deletions

View File

@ -4,6 +4,8 @@ class Activity extends AudioWorkletProcessor {
super(); this.frames=0; this.inputFrames=0; this.zeroFrames=0;
this.energy=0; this.peak=0; this.credit=true; this.next=0; this.stopped=false;
this.watch=options?.processorOptions?.continuityWatch===true;
this.recent=options?.processorOptions?.recentLevels===true;
this.windowEnergy=0;this.windowFrames=0;this.windowPeak=0;
this.startedFrame=this.watch?currentFrame:0;this.lastAckFrame=this.startedFrame;
this.port.onmessage=({data})=>{
if(data==='ack'){this.credit=true;if(this.watch)this.lastAckFrame=currentFrame;}
@ -25,14 +27,17 @@ class Activity extends AudioWorkletProcessor {
this.frames+=block;
if(samples) for(const value of samples) {
this.inputFrames++; this.energy+=value*value;
this.windowFrames++;this.windowEnergy+=value*value;this.windowPeak=Math.max(this.windowPeak,Math.abs(value));
this.peak=Math.max(this.peak,Math.abs(value));
if(value===0)this.zeroFrames++;
}
// Output is left at zero: no monitoring/playback or acoustic feedback.
if(this.credit && this.frames>=this.next) {
this.port.postMessage({inputFrames:this.inputFrames,processedFrames:this.frames,
exactZeroFrames:this.zeroFrames,rms:this.inputFrames ? Math.sqrt(this.energy/this.inputFrames) : 0,
peak:this.peak,sampleRate});
exactZeroFrames:this.zeroFrames,rms:this.recent ? (this.windowFrames?Math.sqrt(this.windowEnergy/this.windowFrames):0)
: (this.inputFrames?Math.sqrt(this.energy/this.inputFrames):0),
peak:this.recent?this.windowPeak:this.peak,sampleRate});
this.windowFrames=0;this.windowEnergy=0;this.windowPeak=0;
this.credit=false; this.next=this.frames+sampleRate;
}
return true;

View File

@ -4,6 +4,7 @@
<title>A/V Test</title>
<link rel="stylesheet" href="style.css">
<main><h1>A/V Test</h1>
<a href="mic.html" title="Microphone-only observation and selected speaker output, with numeric reports">Audio Test</a>
<p>Select a camera and microphone. Quick checks report numeric metrics automatically. Watches keep metrics here for Save metrics; audio and video never upload.</p>
<div><button id="devices">Choose devices…</button>
<label>Video <select id="video-device"></select></label>

View File

@ -10,6 +10,10 @@ configMapGenerator:
files: [nginx.conf]
- name: lesavka-av-observer-assets
files:
- mic.html
- mic-observer.js
- mic-reporting.js
- mic-output.js
- index.html
- observer.js
- local-recording.js

View File

@ -0,0 +1,143 @@
import {AudioReports} from './mic-reporting.js';
import {OutputPulses} from './mic-output.js';
import {stopTracks} from './capture-lifecycle.js';
const el=id=>document.getElementById(id);
let generation=0,current=null,output=null,last=null,reportingRun=null,reportingOutput=null;
const event=(run,kind)=>{if(run.events.length<256)run.events.push({atUnixMs:Date.now(),kind});};
function buttons() {
el('start').disabled=!!current||!el('input').value;
el('stop').disabled=!current;
el('devices').disabled=!!current||!!output;
el('input').disabled=!!current;el('output').disabled=!!output;
el('tone').disabled=!!output||!el('output').value;
el('tone-stop').disabled=!output;
}
function snapshot(run) {
run.reports.remember();
return {schema:'audio-test.observer.v1',elapsedMs:performance.now()-run.started,
startedUnixMs:run.wall,audio:run.audio,settings:run.settings,
observationAgeMs:run.audioAt===null?null:performance.now()-run.audioAt,
contextState:run.context?.state??'unavailable',trackMuted:run.track?.muted??null,
trackState:run.track?.readyState??'unavailable',events:run.events,
microphoneRunIds:run.reports.ids,outputRunIds:run.outputIds??[],
outputContextFrames:output?.pulses.sample()?.processedFrames??null,
endpointPlaybackMeasured:false,audioUploaded:false};
}
function update(run) {
if(current!==run)return;
const now=performance.now();
// Timer keeps reporting even when the worklet or input stops making progress.
run.reports.observe(now,run.audio,run.settings);
if(output)output.reports.observe(now,output.pulses.sample(),{sampleRate:output.pulses.context?.sampleRate,channelCount:1});
el('level').value=run.audio?.peak??0;
el('metrics').textContent=JSON.stringify(snapshot(run),null,2);
}
function stopOutput(reason='operator') {
const run=output;output=null;
if(run){
const sample=run.pulses.sample();run.pulses.stop();clearTimeout(run.timeout);clearInterval(run.timer);
run.reports.finish(performance.now(),sample,{sampleRate:run.pulses.context?.sampleRate,channelCount:1},reason);
if(current){event(current,'output-stopped');current.outputIds=run.reports.ids;}
}
el('output-status').textContent=`Output stopped · ${reason}`;buttons();
}
function release(run) {
stopTracks(run.stream);clearTimeout(run.setupTimer);clearTimeout(run.deadline);clearInterval(run.timer);
if(run.node){run.node.port.onmessage=null;run.node.onprocessorerror=null;
try{run.node.port.postMessage('stop');run.node.disconnect();}catch{}}
try{run.source?.disconnect();}catch{}
if(run.context){run.context.onstatechange=null;void run.context.close().catch(()=>{});}
}
function stop(reason='operator') {
generation++;
stopOutput(reason);
const run=current;current=null;
if(run){event(run,reason);release(run);
run.reports.finish(performance.now(),run.audio,run.settings,reason);
last=snapshot(run);el('metrics').textContent=JSON.stringify(last,null,2);el('save').disabled=false;}
el('status').textContent=`Stopped · ${reason}`;buttons();
}
el('devices').onclick=async()=>{
stop('selecting devices');const ticket=++generation;
el('devices').disabled=true;el('stop').disabled=false;el('status').textContent='Requesting microphone permission';
const deadline=setTimeout(()=>{if(ticket===generation)stop('permission timeout');},20000);
try {
const stream=await navigator.mediaDevices.getUserMedia({audio:true,video:false});
stopTracks(stream);if(ticket!==generation)return;
const devices=await navigator.mediaDevices.enumerateDevices();if(ticket!==generation)return;
for(const [id,kind] of [['input','audioinput'],['output','audiooutput']]) {
const select=el(id),saved=select.value;select.replaceChildren(new Option('Select device',''));
for(const device of devices.filter(d=>d.kind===kind))select.add(new Option(device.label||'Unnamed device',device.deviceId));
select.value=saved;
}
el('status').textContent='Select microphone and output';buttons();
} catch {if(ticket===generation)stop('device permission unavailable');}
finally {clearTimeout(deadline);}
};
for(const id of ['input','output'])el(id).onchange=buttons;
el('start').onclick=async()=>{
if(current||!el('input').value)return;
const ticket=++generation;
const run={started:performance.now(),wall:Date.now(),audio:null,audioAt:null,settings:{},events:[],
reports:new AudioReports(text=>{if(reportingRun===run)el('report-status').textContent=text;})};
current=run;reportingRun=run;last=null;run.reports.observe(performance.now(),null,run.settings);buttons();el('save').disabled=true;el('status').textContent='Starting microphone';
run.setupTimer=setTimeout(()=>{if(current===run)stop('setup timeout');},20000);
try {
const stream=await navigator.mediaDevices.getUserMedia({video:false,audio:{
deviceId:{exact:el('input').value},echoCancellation:false,noiseSuppression:false,autoGainControl:false}});
if(ticket!==generation){stopTracks(stream);return;}run.stream=stream;run.track=stream.getAudioTracks()[0];
const settings=run.track.getSettings();
run.settings={sampleRate:settings.sampleRate,channelCount:settings.channelCount,
echoCancellation:settings.echoCancellation,noiseSuppression:settings.noiseSuppression,autoGainControl:settings.autoGainControl};
run.track.onended=()=>{if(current===run)stop('device ended');};
run.track.onmute=()=>{if(current===run){event(run,'track-muted');update(run);}};
run.track.onunmute=()=>{if(current===run){event(run,'track-unmuted');update(run);}};
if(typeof AudioContext.prototype.setSinkId!=='function')throw new Error('Silent sink unsupported');
run.context=new AudioContext({sinkId:{type:'none'}});
await run.context.setSinkId({type:'none'});if(ticket!==generation)return;
await run.context.audioWorklet.addModule('activity-worklet.js');if(ticket!==generation)return;
run.node=new AudioWorkletNode(run.context,'av-activity',{processorOptions:{continuityWatch:true,recentLevels:true}});
run.node.onprocessorerror=()=>{if(current===run)stop('audio observer error');};
run.node.port.onmessage=({data})=>{
if(current!==run)return;
if(data.watchStopped){stop('audio observer deadline or lost owner');return;}
run.audio=data;run.audioAt=performance.now();run.node.port.postMessage('ack');
};
run.source=run.context.createMediaStreamSource(stream);run.source.connect(run.node);run.node.connect(run.context.destination);
run.context.onstatechange=()=>{if(current===run)event(run,`context-${run.context.state}`);};
await run.context.resume();if(ticket!==generation)return;
if(run.context.state!=='running')throw new Error('Context suspended');
clearTimeout(run.setupTimer);event(run,'capture-started');
el('selection').textContent=`Microphone: ${run.track.label}\nCapture output: silent sink`;
el('status').textContent='Watching microphone · 20-minute limit';
run.timer=setInterval(()=>update(run),1000);
run.deadline=setTimeout(()=>{if(current===run)stop('operator');},1200000);update(run);
} catch {if(current===run)stop('capture/setup failed');}
finally {if(current!==run)release(run);}
};
el('tone').onclick=async()=>{
if(output||!el('output').value)return;
const run={pulses:new OutputPulses(),reports:new AudioReports(text=>{if(reportingOutput===run)el('output-report').textContent=text;})};
output=run;reportingOutput=run;buttons();el('output-status').textContent='Starting selected output';
run.timeout=setTimeout(()=>{if(output===run)stopOutput('setup timeout');},10000);
try {
await run.pulses.start(el('output').value,()=>{if(output===run)stopOutput('120 seconds complete');});
if(output!==run)return;clearTimeout(run.timeout);
if(current)event(current,'output-started');
el('output-status').textContent='Output pulses · 1 kHz · two minutes';
run.timer=setInterval(()=>{if(output===run)run.reports.observe(performance.now(),run.pulses.sample(),
{sampleRate:run.pulses.context.sampleRate,channelCount:1});},1000);
} catch {if(output===run)stopOutput('output selection/setup failed');}
};
el('tone-stop').onclick=()=>stopOutput();el('stop').onclick=()=>stop();
el('save').onclick=()=>{
if(!last)return;const url=URL.createObjectURL(new Blob([JSON.stringify(last,null,2)],{type:'application/json'}));
const link=document.createElement('a');link.href=url;link.download='audio-test-metrics.json';link.click();
setTimeout(()=>URL.revokeObjectURL(url),1000);
};
navigator.mediaDevices?.addEventListener('devicechange',()=>{if(current)event(current,'device-list-changed');});
window.addEventListener('pagehide',()=>stop('page closed'));
document.addEventListener('visibilitychange',()=>{if(document.hidden&&(current||output))stop('page hidden; timing invalid');});
if(!window.isSecureContext||!navigator.mediaDevices||!window.AudioWorkletNode){
el('devices').disabled=true;el('status').textContent='Audio observation unavailable';
}

View File

@ -0,0 +1,45 @@
// Explicit selected output only. A scheduled native audio deadline bounds tones
// even when JavaScript is delayed. No microphone is connected to this graph.
export function pulseSamples(rate) {
const data=new Float32Array(rate);
for(let i=0;i<rate;i++) {
const time=i/rate;
const envelope=time<.12?Math.min(1,time/.005,(.12-time)/.005):0;
data[i]=.025*envelope*Math.sin(2*Math.PI*1000*time);
}
return data;
}
export class OutputPulses {
constructor(Context=AudioContext){this.Context=Context;this.closed=false;this.context=null;}
async start(device,ended) {
if(!device)throw new Error('Output selection required');
const context=this.context=new this.Context({sinkId:device});
if(typeof context.setSinkId!=='function')throw new Error('Output selection unavailable');
await context.setSinkId(device);
if(this.closed)return;
this.source=context.createBufferSource();
const buffer=context.createBuffer(1,context.sampleRate,context.sampleRate);
buffer.copyToChannel(pulseSamples(context.sampleRate),0);
this.source.buffer=buffer;this.source.loop=true;
this.source.connect(context.destination);
await context.resume();
if(this.closed)return;
if(context.state!=='running')throw new Error('Output suspended');
this.started=context.currentTime;
this.source.onended=ended;
this.source.start();this.source.stop(this.started+120);
}
sample() {
if(!Number.isFinite(this.started))return null;
// Context-clock progress is not USB or acoustic playback evidence.
return {inputFrames:null,processedFrames:Math.round(Math.min(120,
Math.max(0,this.context.currentTime-this.started))*this.context.sampleRate),
exactZeroFrames:null,rms:null,peak:null,sampleRate:this.context.sampleRate};
}
stop() {
this.closed=true;
if(this.source){this.source.onended=null;try{this.source.stop();}catch{}try{this.source.disconnect();}catch{}}
if(this.context)void this.context.close().catch(()=>{});
}
}

View File

@ -0,0 +1,32 @@
// Existing numeric-only receipt contract; no new backend or media upload.
import {RunReporter} from './reporting.js';
/** Rotate bounded receipt windows without reopening the selected audio device. */
export class AudioReports {
constructor(status,Reporter=RunReporter) {
this.status=status;this.Reporter=Reporter;this.reporter=null;this.start=0;
this.baseline=null;this.ids=[];this.last=null;
}
snapshot(now,audio,settings,reason) {
const b=this.baseline??{};
const delta=k=>typeof audio?.[k]==='number'?Math.max(0,audio[k]-(b[k]??0)):null;
return {elapsedMs:Math.max(0,now-this.start),reason,settings:{audio:settings},video:null,
audio:audio?{...audio,inputFrames:delta('inputFrames'),processedFrames:delta('processedFrames'),
exactZeroFrames:delta('exactZeroFrames')}:null};
}
observe(now,audio,settings) {
if(this.reporter&&now-this.start>=120000) {
this.reporter.finish(this.snapshot(now,audio,settings,'120 seconds complete'));
this.remember();this.reporter=null;this.baseline=audio?{...audio}:null;
}
if(!this.reporter){this.start=now;this.reporter=new this.Reporter(this.status);}
this.last=this.snapshot(now,audio,settings,'observing');this.reporter.observe(this.last);
}
remember() {
if(this.reporter?.runId&&this.ids.length<16&&!this.ids.includes(this.reporter.runId))this.ids.push(this.reporter.runId);
}
finish(now,audio,settings,reason) {
if(!this.reporter)return;
this.reporter.finish(this.snapshot(now,audio,settings,reason));this.remember();
}
}

View File

@ -0,0 +1,17 @@
<!doctype html>
<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>
<div><button id="devices">Choose devices…</button>
<label>Microphone <select id="input"></select></label>
<label>Output <select id="output"></select></label></div>
<div><button id="start" disabled title="One uninterrupted microphone capture, up to 20 minutes. Numeric reports every ten seconds. No camera or audio upload.">Start mic watch</button>
<button id="stop" disabled>Stop</button>
<button id="tone" disabled title="Quiet 1 kHz pulses on the explicitly selected output for two minutes. This exercises output separately; microphone audio is never monitored.">Start output pulses</button>
<button id="tone-stop" disabled>Stop output</button>
<button id="save" disabled>Save metrics</button></div>
<p id="status" role="status">Stopped</p><p id="report-status">Mic reporting idle</p><p id="output-status">Output stopped</p>
<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>

View File

@ -23,7 +23,7 @@ http {
add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always;
add_header Referrer-Policy "no-referrer" always;
add_header Permissions-Policy "camera=(self), microphone=(self), geolocation=(), display-capture=()" always;
add_header Permissions-Policy "camera=(self), microphone=(self), speaker-selection=(self), geolocation=(), display-capture=()" always;
add_header Cross-Origin-Opener-Policy "same-origin" always;
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; media-src 'self' blob:; connect-src 'self'; worker-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'" always;
location = /lesavka-av-test { return 308 /av-test/; }
@ -42,7 +42,7 @@ http {
if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files /av-test/index.html =404;
}
location ~ ^/av-test/(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\.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;
}