163 lines
10 KiB
JavaScript

import {phoneTest, setupPhoneMode, attachDetector, beginStage, reviewStage, selectStageInput} from './acoustic-watch.js';
import {AudioReports} from './mic-reporting.js';
import {OutputPulses} from './mic-output.js';
import {stopTracks} from './capture-lifecycle.js';
const el=id=>document.getElementById(id);
setupPhoneMode();
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;
if(phoneTest)el('stage-duration').disabled=!!current;
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??[],
path:run.path??null,
outputContextFrames:output?.pulses.sample()?.processedFrames??null,
endpointPlaybackMeasured:false,audioUploaded:false};
}
function audioReport(run) {
return run.audio || run.path ? {...run.audio,path:run.path} : null;
}
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,audioReport(run),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.detector){run.detector.port.onmessage=null;run.detector.onprocessorerror=null;
run.detector.port.postMessage('stop');run.detector.disconnect();}
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);
if(phoneTest && !['stage finding','phone test complete'].includes(reason))el('path-state').textContent='Incomplete · '+reason;
release(run);
const delivered=run.reports.finish(performance.now(),audioReport(run),run.settings,reason);
if(phoneTest)void reviewStage(run,reason,delivered);
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&&(!phoneTest||!['default','communications'].includes(d.deviceId))))select.add(new Option(device.label||'Unnamed device',device.deviceId));
select.value=saved;
}
el('status').textContent=phoneTest?'Select the USB microphone':'Select microphone and output';buttons();
} catch {if(ticket===generation)stop('device permission unavailable');}
finally {clearTimeout(deadline);}
};
el('input').onchange=()=>{if(phoneTest)selectStageInput(el('input').value);buttons();};
el('output').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;})};
if(phoneTest)run.stage=beginStage(el('input').value);
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();
if(phoneTest && settings.deviceId!==el('input').value)throw new Error('USB selection unverified');
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');if(run.path?.locked)run.pathInterruptions++;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);
if(phoneTest){await attachDetector(run,()=>current===run,stop);if(ticket!==generation)return;}
run.context.onstatechange=()=>{if(current===run){
event(run,`context-${run.context.state}`);
if(run.path?.locked && run.context.state!=='running')run.pathInterruptions++;
}};
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=phoneTest?'Receiver listening · start the phone sound':'Watching microphone · 20-minute limit';
run.timer=setInterval(()=>update(run),1000);
run.deadline=setTimeout(()=>{if(current===run)stop(phoneTest?'receiver time limit':'operator');},phoneTest?(run.stage.minutes+1)*60000: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';
}