bstein: serve staged mic tests and authenticated numeric timing receipts

This commit is contained in:
jenkins 2026-12-03 13:01:22 -06:00
parent 8a377d2747
commit 7e03a67bac
14 changed files with 250 additions and 52 deletions

View File

@ -1,5 +1,6 @@
// Match a pilot plus changing marker in 10 ms windows of the selected RCT input. // Match a pilot plus changing marker in 10 ms windows of the selected RCT input.
import {ANCHOR_HZ, MARKERS_HZ, ORDER, SYMBOL_SECONDS, TRIAL_SECONDS} from './acoustic-pattern.js'; import {ANCHOR_HZ, MARKERS_HZ, ORDER, SYMBOL_SECONDS, STAGE_MINUTES} from './acoustic-pattern.js';
import {AcousticTiming} from './acoustic-timing.js';
import {PilotWindow} from './pilot-window.js'; import {PilotWindow} from './pilot-window.js';
// A review threshold for continuous test sound. It does not model intelligibility. // A review threshold for continuous test sound. It does not model intelligibility.
@ -7,11 +8,15 @@ export const LEVEL_DROP_MS = 100;
const DROP_POWER_RATIO = 0.01; // 20 dB below the recently recognized reference. const DROP_POWER_RATIO = 0.01; // 20 dB below the recently recognized reference.
export class AcousticDetector { export class AcousticDetector {
constructor(rate) { constructor(rate, minutes = STAGE_MINUTES.at(-1)) {
if (!STAGE_MINUTES.includes(minutes)) throw new RangeError('unsupported stage');
this.minutes = minutes;
this.rate = rate; this.rate = rate;
this.size = Math.round(0.01 * rate); this.size = Math.round(0.01 * rate);
this.windowMs = 1000 * this.size / rate; this.windowMs = 1000 * this.size / rate;
this.target = Math.ceil(TRIAL_SECONDS * rate / this.size); this.timing = new AcousticTiming(this.windowMs);
this.anchorSin = Math.sin(2*Math.PI*ANCHOR_HZ/rate);
this.target = Math.ceil(minutes * 60 * rate / this.size);
this.coeff = [ANCHOR_HZ, ...MARKERS_HZ].map(f => 2 * Math.cos(2 * Math.PI * f / rate)); this.coeff = [ANCHOR_HZ, ...MARKERS_HZ].map(f => 2 * Math.cos(2 * Math.PI * f / rate));
this.q1 = new Float64Array(this.coeff.length); this.q1 = new Float64Array(this.coeff.length);
this.q2 = new Float64Array(this.coeff.length); this.q2 = new Float64Array(this.coeff.length);
@ -25,10 +30,12 @@ export class AcousticDetector {
this.referencePower = null; this.referencePower = null;
this.quietWindows = this.dropCount = this.longestDropMs = 0; this.quietWindows = this.dropCount = this.longestDropMs = 0;
this.firstDropMs = null; this.firstDropMs = null;
this.firstUnclearMs = null;
this.haveInput = true; this.haveInput = true;
this.inputMissing = false; this.inputMissing = false;
} }
interrupt() { interrupt() {
this.timing.reset();
if (this.locked && this.windows < this.target) { if (this.locked && this.windows < this.target) {
this.interruptions++; this.interruptions++;
this.record('observation interrupted'); this.record('observation interrupted');
@ -88,6 +95,7 @@ export class AcousticDetector {
this.record('marker order or timing'); this.record('marker order or timing');
valid = false; valid = false;
} }
if (this.locked && this.edges >= 2) this.timing.edge(pair, this.windows*this.windowMs);
this.slot = pair; this.slot = pair;
this.lastMarker = marker; this.lastMarker = marker;
this.lastChange = this.tick; this.lastChange = this.tick;
@ -100,12 +108,19 @@ export class AcousticDetector {
this.locked = true; this.locked = true;
} }
this.windows++; this.windows++;
this.scoredEndMs = endMs;
this.observeLevel(valid); this.observeLevel(valid);
const phase = marker>=0 && this.haveInput && !this.quietWindows ?
Math.atan2(this.anchorSin*this.q2[0], this.q1[0]-0.5*this.coeff[0]*this.q2[0])/(2*Math.PI) : null;
this.timing.carrier(phase, this.windows*this.windowMs);
if (!valid) { if (!valid) {
if (!this.gap) this.record('signal missing or out of sequence'); if (!this.gap) this.record('signal missing or out of sequence');
this.bad++; this.bad++;
this.gap++; this.gap++;
this.longest = Math.max(this.longest, this.gap); this.longest = Math.max(this.longest, this.gap);
if (this.gap * this.windowMs >= LEVEL_DROP_MS) {
this.firstUnclearMs ??= Math.round((this.windows - this.gap) * this.windowMs);
}
} else this.gap = 0; } else this.gap = 0;
this.recent.observe(valid, endMs); this.recent.observe(valid, endMs);
} }
@ -135,7 +150,8 @@ export class AcousticDetector {
return {locked: this.locked, complete: this.windows >= this.target, return {locked: this.locked, complete: this.windows >= this.target,
observedMs: this.windows * this.windowMs, windows: this.windows, observedMs: this.windows * this.windowMs, windows: this.windows,
levelDrops: this.dropCount, longestLevelDropMs: this.longestDropMs, levelDrops: this.dropCount, longestLevelDropMs: this.longestDropMs,
firstLevelDropMs: this.firstDropMs, firstLevelDropMs: this.firstDropMs, firstUnclearMs: this.firstUnclearMs,
timing:this.timing.summary(), stageMinutes: this.minutes, scoredEndMs: this.scoredEndMs ?? null,
missingWindows: this.bad, sequenceFaults: this.sequenceFaults, missingWindows: this.bad, sequenceFaults: this.sequenceFaults,
missingFraction: this.windows ? this.bad / this.windows : null, missingFraction: this.windows ? this.bad / this.windows : null,
gapMaxMs: this.longest * this.windowMs, trailingGapMs: this.gap * this.windowMs, gapMaxMs: this.longest * this.windowMs, trailingGapMs: this.gap * this.windowMs,

View File

@ -4,8 +4,9 @@ export const ANCHOR_HZ = 900;
export const MARKERS_HZ = [1400, 1800, 2200, 2600]; export const MARKERS_HZ = [1400, 1800, 2200, 2600];
export const ORDER = [0,1,0,2,0,3,1,2,1,3,2,3]; export const ORDER = [0,1,0,2,0,3,1,2,1,3,2,3];
export const SYMBOL_SECONDS = 0.1; export const SYMBOL_SECONDS = 0.1;
export const TRIAL_SECONDS = 30 * 60; export const STAGE_MINUTES = Object.freeze([1, 5, 10, 15, 20, 30]);
export const SOURCE_SECONDS = TRIAL_SECONDS + 120; export const TRIAL_SECONDS = STAGE_MINUTES.at(-1) * 60;
export const SOURCE_LEAD_SECONDS = 15;
export function referenceLoop(rate) { export function referenceLoop(rate) {
const data = new Float32Array(Math.round(rate * SYMBOL_SECONDS * ORDER.length)); const data = new Float32Array(Math.round(rate * SYMBOL_SECONDS * ORDER.length));

View File

@ -0,0 +1,72 @@
// Relative timing of a repeating acoustic reference; no phone/RCT clock synchronization required.
import {ANCHOR_HZ, ORDER, SYMBOL_SECONDS} from './acoustic-pattern.js';
const cycleMs = ORDER.length * SYMBOL_SECONDS * 1000;
const phaseDifference = (v, period) => v - period * Math.round(v / period);
export const RATE_REVIEW_PPM = 3000;
export const SHIFT_REVIEW_MS = 40;
export class AcousticTiming {
constructor(windowMs) {
this.windowMs=windowMs;
this.blockSize=Math.ceil(199.99/windowMs);
this.rateCoverageMs=0; this.edgeCount=0;
this.maxRatePpm=0; this.maxShiftMs=0;
this.firstRateMs=null; this.firstShiftMs=null; this.basePpm=null;
this.reset();
}
reset() {
this.lastPhase=null; this.sum=0; this.count=0; this.priorBlock=null;
this.edgePhase=null; this.lastEdge=null; this.candidate=null;
}
carrier(phase, atMs) {
if (phase===null || this.lastPhase===null) {
this.lastPhase=phase; this.count=0; this.sum=0; this.priorBlock=null;
return;
}
const turns=phaseDifference(phase-this.lastPhase-ANCHOR_HZ*this.windowMs/1000,1);
this.lastPhase=phase;
// A large phase jump can also be a splice; avoid turning it into a pitch estimate.
if (Math.abs(turns)>0.35) {this.sum=0; this.count=0; this.priorBlock=null; return;}
this.sum+=turns;
if (++this.count<this.blockSize) return;
const span=this.count*this.windowMs;
const ppm=this.sum*1e9/(span*ANCHOR_HZ);
const prior=this.priorBlock;
this.priorBlock=ppm; this.count=0; this.sum=0;
if (prior===null || Math.abs(prior-ppm)>1500) return;
this.rateCoverageMs+=span;
const stable=(prior+ppm)/2;
this.basePpm??=stable;
const change=Math.round(stable-this.basePpm);
if (Math.abs(change)>Math.abs(this.maxRatePpm)) this.maxRatePpm=change;
if (Math.abs(change)>=RATE_REVIEW_PPM) this.firstRateMs??=Math.max(0,Math.round(atMs-2*span));
}
edge(slot, atMs) {
this.edgeCount++;
const phase=atMs-slot*SYMBOL_SECONDS*1000;
if (this.lastEdge===null || atMs-this.lastEdge>=cycleMs/2) {
// Reacquisition across half a cycle is ambiguous. Start a fresh timing comparison.
this.edgePhase=phase; this.candidate=null;
}
this.lastEdge=atMs;
const shift=phaseDifference(phase-this.edgePhase,cycleMs);
if (Math.abs(shift)<SHIFT_REVIEW_MS-0.01) {
this.edgePhase+=0.2*shift; this.candidate=null; return;
}
if (this.candidate===null || Math.abs(shift-this.candidate.shift)>1.5*this.windowMs) {
this.candidate={atMs,shift,count:1}; return;
}
const c=this.candidate;
c.shift+=(shift-c.shift)/++c.count;
if (c.count<3) return;
const value=Math.round(c.shift);
if (Math.abs(value)>Math.abs(this.maxShiftMs)) this.maxShiftMs=value;
this.firstShiftMs??=Math.round(c.atMs);
this.edgePhase=phase; this.candidate=null;
}
summary() {
return {rateCoverageMs:Math.round(this.rateCoverageMs),edgeCount:this.edgeCount,
baselinePpm:this.basePpm===null?null:Math.round(this.basePpm),maxRatePpm:this.maxRatePpm,
firstRateMs:this.firstRateMs,maxShiftMs:this.maxShiftMs,firstShiftMs:this.firstShiftMs};
}
}

View File

@ -1,8 +1,35 @@
import {TRIAL_SECONDS} from './acoustic-pattern.js'; import {STAGE_MINUTES, TRIAL_SECONDS} from './acoustic-pattern.js';
export const phoneTest = new URLSearchParams(location.search).get('test') === 'phone'; export const phoneTest = new URLSearchParams(location.search).get('test') === 'phone';
const status = document.getElementById('path-state'); const status = document.getElementById('path-state');
const detail = document.getElementById('path-detail'); const detail = document.getElementById('path-detail');
const advance = document.getElementById('stage-next');
const timing = document.getElementById('path-timing');
let stageIndex = 0, device = null, attempt = 0;
function renderStage() {
document.getElementById('start').textContent = 'Start ' + STAGE_MINUTES[stageIndex] + '-minute receiver';
advance.hidden = true;
}
export function selectStageInput(input) {
if (device === input) return;
device = input; stageIndex = 0; attempt++;
renderStage();
}
export function beginStage(input) {
selectStageInput(input);
renderStage();
return {minutes:STAGE_MINUTES[stageIndex], attempt:++attempt};
}
export async function reviewStage(run, reason, delivered) {
if (reason !== 'phone test complete') return;
const ok = await delivered;
if (attempt !== run.stage.attempt) return;
if (!ok) { status.textContent = 'Stage held · Atlas receipt unavailable'; return; }
if (stageIndex + 1 < STAGE_MINUTES.length) {
advance.textContent = 'Advance to ' + STAGE_MINUTES[stageIndex + 1] + ' minutes';
advance.hidden = false;
}
}
const clock = ms => { const clock = ms => {
const s = Math.min(TRIAL_SECONDS, Math.floor(ms / 1000)); const s = Math.min(TRIAL_SECONDS, Math.floor(ms / 1000));
return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0');
@ -12,8 +39,9 @@ export function setupPhoneMode() {
if (!phoneTest) return; if (!phoneTest) return;
document.title = 'RCT microphone path test'; document.title = 'RCT microphone path test';
document.querySelector('h1').textContent = document.title; document.querySelector('h1').textContent = document.title;
document.getElementById('start').textContent = 'Start receiver'; renderStage();
document.getElementById('start').title = 'Wait for the phone signal, then measure 30 minutes.'; advance.onclick = () => { if (!advance.hidden) { stageIndex++; renderStage(); } };
document.getElementById('start').title = 'Wait for the phone signal, then measure the selected stage.';
for (const id of ['tone','tone-stop','output-status','output-report','path-link']) { for (const id of ['tone','tone-stop','output-status','output-report','path-link']) {
document.getElementById(id).hidden = true; document.getElementById(id).hidden = true;
} }
@ -23,11 +51,12 @@ export function setupPhoneMode() {
export async function attachDetector(run, isCurrent, finish) { export async function attachDetector(run, isCurrent, finish) {
await run.context.audioWorklet.addModule('acoustic-worklet.js'); await run.context.audioWorklet.addModule('acoustic-worklet.js');
if (!isCurrent()) return; if (!isCurrent()) return;
const node = new AudioWorkletNode(run.context, 'acoustic-probe'); const node = new AudioWorkletNode(run.context, 'acoustic-probe', {processorOptions:{minutes:run.stage.minutes}});
run.detector = node; run.detector = node;
run.pathInterruptions = 0; run.pathInterruptions = 0;
status.textContent = 'Waiting for phone signal'; status.textContent = 'Waiting for phone signal';
detail.hidden = true; detail.hidden = true; timing.hidden = true;
const listenStart = performance.now();
node.onprocessorerror = () => { if (isCurrent()) finish('detector failed'); }; node.onprocessorerror = () => { if (isCurrent()) finish('detector failed'); };
node.port.onmessage = ({data}) => { node.port.onmessage = ({data}) => {
if (!isCurrent()) return; if (!isCurrent()) return;
@ -42,21 +71,33 @@ export async function attachDetector(run, isCurrent, finish) {
if (data.locked && (Math.abs(now - run.pathStart - data.observedMs) > 2000 || if (data.locked && (Math.abs(now - run.pathStart - data.observedMs) > 2000 ||
Math.abs(wall - run.pathWall - data.observedMs) > 2000)) run.clockGap = true; Math.abs(wall - run.pathWall - data.observedMs) > 2000)) run.clockGap = true;
const interruptions = data.discontinuities + run.pathInterruptions + Number(!!run.clockGap); const interruptions = data.discontinuities + run.pathInterruptions + Number(!!run.clockGap);
run.path = {...data, discontinuities:interruptions}; const age = data.scoredEndMs === null ? 0 : Math.max(0, run.context.currentTime * 1000 - data.scoredEndMs);
run.path = {...data, discontinuities:interruptions, observedAtMono:now - age};
if (!data.locked && now-listenStart>=30000) { finish('phone signal not acquired'); return; }
if (data.locked) { if (data.locked) {
const gaps = data.missingWindows > 0 || data.sequenceFaults > 0; timing.hidden = data.timing.baselinePpm===null;
const drop = data.levelDrops > 0; timing.textContent = 'Largest pitch change · ' + (data.timing.maxRatePpm/10000).toFixed(2) +
const label = interruptions ? 'Observation interrupted' : drop ? '% · Confirmed marker timing step · ' + data.timing.maxShiftMs + ' ms';
'Received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms' : 'Signal tracking'; const target = run.stage.minutes + ':00';
detail.hidden = !gaps; const label = clock(data.observedMs) + ' / ' + target;
detail.textContent = gaps ? 'Longest reference mismatch · ' + Math.round(data.gapMaxMs) + ' ms' : ''; detail.hidden = data.missingWindows === 0 && data.sequenceFaults === 0;
status.textContent = label + ' · ' + clock(data.observedMs) + ' / 30:00'; detail.textContent = 'Longest reference mismatch · ' + Math.round(data.gapMaxMs) + ' ms';
if (data.complete) { let hold;
status.textContent = interruptions ? '30 minutes · incomplete observation' : if (interruptions) hold = 'Observation interrupted';
drop ? '30 minutes · received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms' : else if (data.levelDrops) hold = 'Received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms';
gaps ? '30 minutes · reference mismatches recorded' : '30 minutes · continuous reference received'; else if (data.timing.firstRateMs !== null) hold = 'Received pitch changed · ' + (data.timing.maxRatePpm/10000).toFixed(2) + '%';
else if (data.timing.firstShiftMs !== null) hold = 'Relative timing shift · ' + data.timing.maxShiftMs + ' ms';
else if (data.firstUnclearMs !== null) hold = 'Reference unclear · ' + Math.round(data.gapMaxMs) + ' ms';
else if (data.complete && (data.timing.rateCoverageMs < 0.8*data.observedMs ||
data.timing.edgeCount < 0.8*data.observedMs/100)) hold = 'Insufficient reference timing coverage';
if (hold) {
status.textContent = 'Stage held · ' + hold + ' · ' + label;
run.findingAt ??= data.observedMs;
if (interruptions || data.complete || data.observedMs-run.findingAt>=2000) finish('stage finding');
} else if (data.complete) {
status.textContent = 'Stage complete · ' + label + ' · review before advancing';
finish('phone test complete'); finish('phone test complete');
} } else status.textContent = 'Signal tracking · ' + label;
} }
}; };
run.source.connect(node); node.connect(run.context.destination); run.source.connect(node); node.connect(run.context.destination);

View File

@ -1,11 +1,11 @@
import {AcousticDetector} from './acoustic-detector.js'; import {AcousticDetector} from './acoustic-detector.js';
class AcousticProbe extends AudioWorkletProcessor { class AcousticProbe extends AudioWorkletProcessor {
constructor() { constructor(options) {
super(); super();
this.detector = new AcousticDetector(sampleRate); this.detector = new AcousticDetector(sampleRate, options.processorOptions.minutes);
this.next = currentFrame; this.next = currentFrame;
this.deadline = currentFrame + sampleRate * 35 * 60; this.deadline = currentFrame + sampleRate * (this.detector.minutes * 60 + 60);
this.ack = currentFrame; this.ack = currentFrame;
this.credit = true; this.credit = true;
this.stopped = false; this.stopped = false;

View File

@ -5,7 +5,7 @@
<link rel="stylesheet" href="style.css"> <link rel="stylesheet" href="style.css">
<main><h1>A/V Test</h1> <main><h1>A/V Test</h1>
<a href="mic.html" title="Microphone-only observation and selected speaker output, with numeric reports">Audio Test</a> <a href="mic.html" title="Microphone-only observation and selected speaker output, with numeric reports">Audio Test</a>
<p><a href="mic.html?test=phone">30-minute RCT mic test</a> · <a href="phone.html">Phone sound source</a></p> <p><a href="mic.html?test=phone">Staged RCT mic test</a> · <a href="phone.html">Phone sound source</a></p>
<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> <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> <div><button id="devices">Choose devices…</button>
<label>Video <select id="video-device"></select></label> <label>Video <select id="video-device"></select></label>

View File

@ -14,6 +14,7 @@ configMapGenerator:
- acoustic-pattern.js - acoustic-pattern.js
- acoustic-watch.js - acoustic-watch.js
- acoustic-worklet.js - acoustic-worklet.js
- acoustic-timing.js
- phone-source.js - phone-source.js
- phone.html - phone.html
- mic.html - mic.html

View File

@ -1,4 +1,4 @@
import {phoneTest, setupPhoneMode, attachDetector} from './acoustic-watch.js'; import {phoneTest, setupPhoneMode, attachDetector, beginStage, reviewStage, selectStageInput} from './acoustic-watch.js';
import {AudioReports} from './mic-reporting.js'; import {AudioReports} from './mic-reporting.js';
import {OutputPulses} from './mic-output.js'; import {OutputPulses} from './mic-output.js';
import {stopTracks} from './capture-lifecycle.js'; import {stopTracks} from './capture-lifecycle.js';
@ -27,7 +27,7 @@ function snapshot(run) {
endpointPlaybackMeasured:false,audioUploaded:false}; endpointPlaybackMeasured:false,audioUploaded:false};
} }
function audioReport(run) { function audioReport(run) {
return run.audio ? {...run.audio,path:run.path} : null; return run.audio || run.path ? {...run.audio,path:run.path} : null;
} }
function update(run) { function update(run) {
if(current!==run)return; if(current!==run)return;
@ -61,9 +61,10 @@ function stop(reason='operator') {
stopOutput(reason); stopOutput(reason);
const run=current;current=null; const run=current;current=null;
if(run){event(run,reason); if(run){event(run,reason);
if(phoneTest && reason!=='phone test complete')el('path-state').textContent='Incomplete · '+reason; if(phoneTest && !['stage finding','phone test complete'].includes(reason))el('path-state').textContent='Incomplete · '+reason;
release(run); release(run);
run.reports.finish(performance.now(),audioReport(run),run.settings,reason); 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;} last=snapshot(run);el('metrics').textContent=JSON.stringify(last,null,2);el('save').disabled=false;}
el('status').textContent=`Stopped · ${reason}`;buttons(); el('status').textContent=`Stopped · ${reason}`;buttons();
} }
@ -84,12 +85,14 @@ el('devices').onclick=async()=>{
} catch {if(ticket===generation)stop('device permission unavailable');} } catch {if(ticket===generation)stop('device permission unavailable');}
finally {clearTimeout(deadline);} finally {clearTimeout(deadline);}
}; };
for(const id of ['input','output'])el(id).onchange=buttons; el('input').onchange=()=>{if(phoneTest)selectStageInput(el('input').value);buttons();};
el('output').onchange=buttons;
el('start').onclick=async()=>{ el('start').onclick=async()=>{
if(current||!el('input').value)return; if(current||!el('input').value)return;
const ticket=++generation; const ticket=++generation;
const run={started:performance.now(),wall:Date.now(),audio:null,audioAt:null,settings:{},events:[], 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;})}; 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'; 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); run.setupTimer=setTimeout(()=>{if(current===run)stop('setup timeout');},20000);
try { try {
@ -126,7 +129,7 @@ el('start').onclick=async()=>{
el('selection').textContent=`Microphone: ${run.track.label}\nCapture output: silent sink`; 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'; el('status').textContent=phoneTest?'Receiver listening · start the phone sound':'Watching microphone · 20-minute limit';
run.timer=setInterval(()=>update(run),1000); run.timer=setInterval(()=>update(run),1000);
run.deadline=setTimeout(()=>{if(current===run)stop(phoneTest?'receiver time limit':'operator');},phoneTest?35*60000:1200000);update(run); 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');} } catch {if(current===run)stop('capture/setup failed');}
finally {if(current!==run)release(run);} finally {if(current!==run)release(run);}
}; };

View File

@ -5,7 +5,7 @@ import {RunReporter} from './reporting.js';
export class AudioReports { export class AudioReports {
constructor(status,Reporter=RunReporter) { constructor(status,Reporter=RunReporter) {
this.status=status;this.Reporter=Reporter;this.reporter=null;this.start=0; this.status=status;this.Reporter=Reporter;this.reporter=null;this.start=0;
this.baseline=null;this.ids=[];this.last=null; this.baseline=null;this.ids=[];this.last=null;this.stageWindows=[];
} }
snapshot(now,audio,settings,reason) { snapshot(now,audio,settings,reason) {
const b=this.baseline??{}; const b=this.baseline??{};
@ -22,7 +22,8 @@ export class AudioReports {
observe(now,audio,settings) { observe(now,audio,settings) {
if(this.reporter&&now-this.start>=120000) { if(this.reporter&&now-this.start>=120000) {
const reason=audio?.path?'signal report window closed':'120 seconds complete'; const reason=audio?.path?'signal report window closed':'120 seconds complete';
this.reporter.finish(this.snapshot(now,audio,settings,reason)); const delivered=this.reporter.finish(this.snapshot(now,audio,settings,reason));
if(audio?.path)this.stageWindows.push(delivered);
this.remember();this.reporter=null;this.baseline=audio?{...audio}:null; this.remember();this.reporter=null;this.baseline=audio?{...audio}:null;
} }
if(!this.reporter){this.start=now;this.reporter=new this.Reporter(this.status);} if(!this.reporter){this.start=now;this.reporter=new this.Reporter(this.status);}
@ -33,6 +34,7 @@ export class AudioReports {
} }
finish(now,audio,settings,reason) { finish(now,audio,settings,reason) {
if(!this.reporter)return; if(!this.reporter)return;
this.reporter.finish(this.snapshot(now,audio,settings,reason));this.remember(); const result=this.reporter.finish(this.snapshot(now,audio,settings,reason));this.remember();
return audio?.path ? Promise.all([...this.stageWindows,result]).then(values=>values.every(Boolean)) : result;
} }
} }

View File

@ -2,14 +2,15 @@
<html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width"> <html lang="en"><meta charset="utf-8"><meta name="viewport" content="width=device-width">
<title>Audio Test</title><link rel="stylesheet" href="style.css"> <title>Audio Test</title><link rel="stylesheet" href="style.css">
<main><h1>Audio Test</h1><a href="./">A/V Test</a> <main><h1>Audio Test</h1><a href="./">A/V Test</a>
<p><a id="path-link" href="mic.html?test=phone">30-minute 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></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-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-detail" hidden></p><p id="path-timing" hidden></p>
<div><button id="devices">Choose devices…</button> <div><button id="devices">Choose devices…</button>
<label>Microphone <select id="input"></select></label> <label>Microphone <select id="input"></select></label>
<label>Output <select id="output"></select></label></div> <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> <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="stop" disabled>Stop</button>
<button id="stage-next" hidden title="Advance after reviewing this stage on the same setup."></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" 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="tone-stop" disabled>Stop output</button>
<button id="save" disabled>Save metrics</button></div> <button id="save" disabled>Save metrics</button></div>

View File

@ -6,6 +6,25 @@ http {
include /etc/nginx/mime.types; include /etc/nginx/mime.types;
default_type application/octet-stream; default_type application/octet-stream;
access_log off; access_log off;
# The receipt service authenticates the body and sequence. Log only the
# numeric stage annotation of an accepted report, correlated by that body.
map $request_body $av_identity {
default "";
'~^[{]"run_id":"(?<av_id>[0-9a-f]{32})","sequence":(?<av_sequence>[1-9][0-9]?),"state":"(?<av_state>running|completed|failed|hidden|closed|stopped|device-change)",' "$av_id/$av_sequence/$av_state";
}
map $http_x_av_stage $av_annotation {
default "";
'~^(1|5|10|15|20|30)(,[0-9]{1,7}){6},(0|[0-9]{13}),[0-9]{1,5}(,-?[0-9]{1,7}){7}$' $http_x_av_stage;
}
map "$uri|$upstream_status|$av_identity|$av_annotation" $av_ack {
default "";
'~^/av-test/api/report[|]204[|][^|]+[|][0-9,]+$' 1;
}
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"}';
server_tokens off; server_tokens off;
client_max_body_size 4k; client_max_body_size 4k;
client_body_timeout 5s; client_body_timeout 5s;
@ -19,6 +38,8 @@ http {
listen 8080; listen 8080;
absolute_redirect off; absolute_redirect off;
root /usr/share/nginx/html; root /usr/share/nginx/html;
add_header X-AV-Clock $av_clock always;
add_header X-AV-Stage-Ack $av_ack always;
add_header Cache-Control "no-store" always; add_header Cache-Control "no-store" always;
add_header X-Content-Type-Options "nosniff" always; add_header X-Content-Type-Options "nosniff" always;
add_header X-Frame-Options "DENY" always; add_header X-Frame-Options "DENY" always;
@ -42,11 +63,12 @@ http {
if ($request_method !~ ^(GET|HEAD)$) { return 405; } if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files /av-test/index.html =404; try_files /av-test/index.html =404;
} }
location ~ ^/av-test/(acoustic-detector\.js|acoustic-pattern\.js|acoustic-watch\.js|acoustic-worklet\.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/(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; } if ($request_method !~ ^(GET|HEAD)$) { return 405; }
try_files $uri =404; try_files $uri =404;
} }
location ~ ^/av-test/api/(start|report)$ { location ~ ^/av-test/api/(start|report)$ {
access_log /dev/stdout av_stage if=$av_ack;
if ($request_method != POST) { return 405; } if ($request_method != POST) { return 405; }
proxy_pass http://127.0.0.1:8081; proxy_pass http://127.0.0.1:8081;
proxy_connect_timeout 2s; proxy_connect_timeout 2s;

View File

@ -1,9 +1,11 @@
import {AudioReports} from './mic-reporting.js'; import {AudioReports} from './mic-reporting.js';
import {referenceLoop, SOURCE_SECONDS} from './acoustic-pattern.js'; import {referenceLoop, STAGE_MINUTES, SOURCE_LEAD_SECONDS} from './acoustic-pattern.js';
const play = document.getElementById('play'); const play = document.getElementById('play');
const stopButton = document.getElementById('stop'); const stopButton = document.getElementById('stop');
const status = document.getElementById('state'); const status = document.getElementById('state');
const duration = document.getElementById('duration');
for (const minutes of STAGE_MINUTES) duration.add(new Option(minutes + ' min', String(minutes)));
let active = null; let active = null;
function clockSample(owner) { function clockSample(owner) {
const frames = Math.floor(Math.max(0,owner.context.currentTime - owner.started) * owner.context.sampleRate); const frames = Math.floor(Math.max(0,owner.context.currentTime - owner.started) * owner.context.sampleRate);
@ -25,12 +27,16 @@ function stop(message) {
void owner.context.close().catch(() => {}); void owner.context.close().catch(() => {});
void owner.wake?.release().catch(() => {}); void owner.wake?.release().catch(() => {});
} }
play.disabled = false; stopButton.disabled = true; play.disabled = false; stopButton.disabled = true; duration.disabled = false;
status.textContent = message; status.textContent = message;
} }
play.onclick = async () => { play.onclick = async () => {
if (active) return; if (active) return;
try { try {
const minutes = Number(duration.value);
if (!STAGE_MINUTES.includes(minutes)) return;
const sourceSeconds = 60 * minutes + SOURCE_LEAD_SECONDS;
duration.disabled = true;
const context = new AudioContext(); const context = new AudioContext();
const owner = {context}; const owner = {context};
active = owner; play.disabled = true; stopButton.disabled = false; active = owner; play.disabled = true; stopButton.disabled = false;
@ -52,10 +58,10 @@ play.onclick = async () => {
context.onstatechange = () => { context.onstatechange = () => {
if (active === owner && context.state !== 'running') stop('Speaker interrupted'); if (active === owner && context.state !== 'running') stop('Speaker interrupted');
}; };
source.start(start); source.stop(start + SOURCE_SECONDS); source.start(start); source.stop(start + sourceSeconds);
const show = () => { const show = () => {
owner.reports.observe(performance.now(), clockSample(owner), {sampleRate:context.sampleRate}); owner.reports.observe(performance.now(), clockSample(owner), {sampleRate:context.sampleRate});
const remaining = Math.max(0, Math.ceil(SOURCE_SECONDS - (context.currentTime - start))); const remaining = Math.max(0, Math.ceil(sourceSeconds - (context.currentTime - start)));
status.textContent = 'Playing · ' + Math.floor(remaining / 60) + ':' + status.textContent = 'Playing · ' + Math.floor(remaining / 60) + ':' +
String(remaining % 60).padStart(2, '0') + ' remaining'; String(remaining % 60).padStart(2, '0') + ' remaining';
}; };

View File

@ -3,8 +3,9 @@
<title>Phone audio source</title><link rel="stylesheet" href="style.css"> <title>Phone audio source</title><link rel="stylesheet" href="style.css">
<main><h1>Phone audio source</h1> <main><h1>Phone audio source</h1>
<p>Place the phone near the microphone. Use its speaker at a comfortable volume and keep this page visible.</p> <p>Place the phone near the microphone. Use its speaker at a comfortable volume and keep this page visible.</p>
<label>Receiver stage <select id="duration"></select></label>
<button id="play">Play test sound</button><button id="stop" disabled>Stop</button> <button id="play">Play test sound</button><button id="stop" disabled>Stop</button>
<p id="state" role="status">Ready · 32 minutes</p> <p id="state" role="status">Ready</p>
<p id="report">Playback reporting idle</p> <p id="report">Playback reporting idle</p>
<a href="mic.html?test=phone">RCT receiver test</a></main> <a href="mic.html?test=phone">RCT receiver test</a></main>
<script type="module" src="phone-source.js"></script></html> <script type="module" src="phone-source.js"></script></html>

View File

@ -40,6 +40,23 @@ export function stopState(reason) {
return 'failed'; return 'failed';
} }
// Only fixed, bounded integers supplement an authenticated acoustic receipt.
// First-event offsets use offset+1, reserving zero for no event.
export function acousticReceipt(path, clock) {
if (!path || ![1,5,10,15,20,30].includes(path.stageMinutes)) return null;
const offset = value => value === null ? 0 : Math.round(value) + 1;
const timing = [path.stageMinutes,Math.round(path.observedMs),offset(path.firstLevelDropMs),
Math.round(path.longestLevelDropMs),offset(path.firstUnclearMs),Math.round(path.gapMaxMs),
path.discontinuities];
if (!timing.every(v=>Number.isSafeInteger(v) && v>=0 && v<=1800011)) return null;
const end = clock && Number.isFinite(path.observedAtMono) ? Math.round(path.observedAtMono + clock.offset) : 0;
const t=path.timing;
if (!t) return null;
const warp=[Math.round(t.rateCoverageMs),t.edgeCount,t.maxRatePpm,offset(t.firstRateMs),t.maxShiftMs,offset(t.firstShiftMs),t.baselinePpm??0];
if (!warp.every(v=>Number.isSafeInteger(v) && Math.abs(v)<=1800011)) return null;
return [...timing,end,clock?.uncertainty ?? 0,...warp].join(',');
}
export class RunReporter { export class RunReporter {
constructor(status,request=globalThis.fetch.bind(globalThis)) { constructor(status,request=globalThis.fetch.bind(globalThis)) {
this.status=status;this.request=request;this.pending=null;this.busy=false; this.status=status;this.request=request;this.pending=null;this.busy=false;
@ -49,9 +66,16 @@ export class RunReporter {
} }
async open() { async open() {
try { try {
const sentAt=performance.now();
const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit', const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit',
headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)}); headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)});
if(!r.ok)throw new Error('start rejected'); if(!r.ok)throw new Error('start rejected');
const receivedAt=performance.now();
const stamp=r.headers?.get?.('X-AV-Clock');
if (/^[0-9]{10}\.[0-9]{3}$/.test(stamp)) {
this.clock={offset:Number(stamp)*1000-(sentAt+receivedAt)/2,
uncertainty:Math.ceil((receivedAt-sentAt)/2)+1};
}
const data=await r.json(); const data=await r.json();
if(!/^[a-f0-9]{32}$/.test(data.run_id)||!/^[A-Za-z0-9_-]{43}$/.test(data.write_token))throw new Error('bad receipt'); if(!/^[a-f0-9]{32}$/.test(data.run_id)||!/^[A-Za-z0-9_-]{43}$/.test(data.write_token))throw new Error('bad receipt');
this.runId=data.run_id;this.token=data.write_token; this.runId=data.run_id;this.token=data.write_token;
@ -69,13 +93,17 @@ export class RunReporter {
this.lastProgress=receipt.elapsedMs;this.queue('running',receipt); this.lastProgress=receipt.elapsedMs;this.queue('running',receipt);
} }
finish(receipt) { finish(receipt) {
if(this.terminal)return; if(!this.terminal) {
this.terminal=true;this.queue(stopState(receipt.reason),receipt); this.terminal=true;
this.finished=new Promise(resolve=>{this.resolveFinished=resolve;});
this.queue(stopState(receipt.reason),receipt);
}
return this.finished;
} }
queue(state,receipt) { queue(state,receipt) {
// One latest snapshot, not a growing queue. Terminal state supersedes // One latest snapshot, not a growing queue. Terminal state supersedes
// pending progress; a stopped run never becomes running again. // pending progress; a stopped run never becomes running again.
this.pending={state,metrics:reportMetrics(receipt)}; this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot};
void this.flush(); void this.flush();
} }
async flush() { async flush() {
@ -83,23 +111,27 @@ export class RunReporter {
this.busy=true; this.busy=true;
try { try {
await this.ready; await this.ready;
if(!this.available){this.pending=null;return;} if(!this.available){this.pending=null;this.resolveFinished?.(false);return;}
while(this.pending) { while(this.pending) {
const report=this.pending;this.pending=null; const report=this.pending;this.pending=null;
const payload={run_id:this.runId,sequence:++this.sequence,...report}; const payload={run_id:this.runId,sequence:++this.sequence,state:report.state,metrics:report.metrics};
const stage=acousticReceipt(report.path,this.clock);
const headers={'Content-Type':'application/json',Authorization:`Bearer ${this.token}`};
if(stage)headers['X-AV-Stage']=stage;
let delivered=false; let delivered=false;
for(let attempt=0;attempt<2&&!delivered;attempt++) { for(let attempt=0;attempt<2&&!delivered;attempt++) {
try { try {
const response=await this.request('/av-test/api/report',{ const response=await this.request('/av-test/api/report',{
method:'POST',credentials:'omit',keepalive:true, method:'POST',credentials:'omit',keepalive:true,
headers:{'Content-Type':'application/json',Authorization:`Bearer ${this.token}`}, headers,
body:JSON.stringify(payload),signal:AbortSignal.timeout(5000), body:JSON.stringify(payload),signal:AbortSignal.timeout(5000),
}); });
delivered=response.ok; delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1'));
if(response.status>=400&&response.status<500)break; if(response.status>=400&&response.status<500)break;
} catch { /* No raw exception or endpoint response is displayed. */ } } catch { /* No raw exception or endpoint response is displayed. */ }
} }
if(report.state!=='running') { if(report.state!=='running') {
this.resolveFinished?.(!!delivered);
this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` : this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` :
'Result not reported · use Save metrics'); 'Result not reported · use Save metrics');
} else if(!delivered) { } else if(!delivered) {