From 7e03a67bacd0243d983b3a64561fa3e79c98d92e Mon Sep 17 00:00:00 2001 From: jenkins Date: Thu, 3 Dec 2026 13:01:22 -0600 Subject: [PATCH] bstein: serve staged mic tests and authenticated numeric timing receipts --- .../av-observer/acoustic-detector.js | 24 +++++- .../av-observer/acoustic-pattern.js | 5 +- .../av-observer/acoustic-timing.js | 72 +++++++++++++++++ .../av-observer/acoustic-watch.js | 77 ++++++++++++++----- .../av-observer/acoustic-worklet.js | 6 +- .../bstein-dev-home/av-observer/index.html | 2 +- .../av-observer/kustomization.yaml | 1 + .../av-observer/mic-observer.js | 15 ++-- .../av-observer/mic-reporting.js | 8 +- services/bstein-dev-home/av-observer/mic.html | 5 +- .../bstein-dev-home/av-observer/nginx.conf | 24 +++++- .../av-observer/phone-source.js | 14 +++- .../bstein-dev-home/av-observer/phone.html | 3 +- .../bstein-dev-home/av-observer/reporting.js | 46 +++++++++-- 14 files changed, 250 insertions(+), 52 deletions(-) create mode 100644 services/bstein-dev-home/av-observer/acoustic-timing.js diff --git a/services/bstein-dev-home/av-observer/acoustic-detector.js b/services/bstein-dev-home/av-observer/acoustic-detector.js index 4f137c02..6e7b7f8d 100644 --- a/services/bstein-dev-home/av-observer/acoustic-detector.js +++ b/services/bstein-dev-home/av-observer/acoustic-detector.js @@ -1,5 +1,6 @@ // 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'; // 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. 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.size = Math.round(0.01 * 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.q1 = new Float64Array(this.coeff.length); this.q2 = new Float64Array(this.coeff.length); @@ -25,10 +30,12 @@ export class AcousticDetector { this.referencePower = null; this.quietWindows = this.dropCount = this.longestDropMs = 0; this.firstDropMs = null; + this.firstUnclearMs = null; this.haveInput = true; this.inputMissing = false; } interrupt() { + this.timing.reset(); if (this.locked && this.windows < this.target) { this.interruptions++; this.record('observation interrupted'); @@ -88,6 +95,7 @@ export class AcousticDetector { this.record('marker order or timing'); valid = false; } + if (this.locked && this.edges >= 2) this.timing.edge(pair, this.windows*this.windowMs); this.slot = pair; this.lastMarker = marker; this.lastChange = this.tick; @@ -100,12 +108,19 @@ export class AcousticDetector { this.locked = true; } this.windows++; + this.scoredEndMs = endMs; 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 (!this.gap) this.record('signal missing or out of sequence'); this.bad++; 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; this.recent.observe(valid, endMs); } @@ -135,7 +150,8 @@ export class AcousticDetector { return {locked: this.locked, complete: this.windows >= this.target, observedMs: this.windows * this.windowMs, windows: this.windows, 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, missingFraction: this.windows ? this.bad / this.windows : null, gapMaxMs: this.longest * this.windowMs, trailingGapMs: this.gap * this.windowMs, diff --git a/services/bstein-dev-home/av-observer/acoustic-pattern.js b/services/bstein-dev-home/av-observer/acoustic-pattern.js index 1a90f73b..9131bfe6 100644 --- a/services/bstein-dev-home/av-observer/acoustic-pattern.js +++ b/services/bstein-dev-home/av-observer/acoustic-pattern.js @@ -4,8 +4,9 @@ export const ANCHOR_HZ = 900; 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 SYMBOL_SECONDS = 0.1; -export const TRIAL_SECONDS = 30 * 60; -export const SOURCE_SECONDS = TRIAL_SECONDS + 120; +export const STAGE_MINUTES = Object.freeze([1, 5, 10, 15, 20, 30]); +export const TRIAL_SECONDS = STAGE_MINUTES.at(-1) * 60; +export const SOURCE_LEAD_SECONDS = 15; export function referenceLoop(rate) { const data = new Float32Array(Math.round(rate * SYMBOL_SECONDS * ORDER.length)); diff --git a/services/bstein-dev-home/av-observer/acoustic-timing.js b/services/bstein-dev-home/av-observer/acoustic-timing.js new file mode 100644 index 00000000..e6a17875 --- /dev/null +++ b/services/bstein-dev-home/av-observer/acoustic-timing.js @@ -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.count1500) 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)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}; + } +} diff --git a/services/bstein-dev-home/av-observer/acoustic-watch.js b/services/bstein-dev-home/av-observer/acoustic-watch.js index 3eac2549..c4b61b06 100644 --- a/services/bstein-dev-home/av-observer/acoustic-watch.js +++ b/services/bstein-dev-home/av-observer/acoustic-watch.js @@ -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'; const status = document.getElementById('path-state'); 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 s = Math.min(TRIAL_SECONDS, Math.floor(ms / 1000)); return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); @@ -12,8 +39,9 @@ export function setupPhoneMode() { if (!phoneTest) return; document.title = 'RCT microphone path test'; document.querySelector('h1').textContent = document.title; - document.getElementById('start').textContent = 'Start receiver'; - document.getElementById('start').title = 'Wait for the phone signal, then measure 30 minutes.'; + renderStage(); + 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']) { document.getElementById(id).hidden = true; } @@ -23,11 +51,12 @@ export function setupPhoneMode() { export async function attachDetector(run, isCurrent, finish) { await run.context.audioWorklet.addModule('acoustic-worklet.js'); 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.pathInterruptions = 0; 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.port.onmessage = ({data}) => { 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 || Math.abs(wall - run.pathWall - data.observedMs) > 2000)) run.clockGap = true; 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) { - const gaps = data.missingWindows > 0 || data.sequenceFaults > 0; - const drop = data.levelDrops > 0; - const label = interruptions ? 'Observation interrupted' : drop ? - 'Received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms' : 'Signal tracking'; - detail.hidden = !gaps; - detail.textContent = gaps ? 'Longest reference mismatch · ' + Math.round(data.gapMaxMs) + ' ms' : ''; - status.textContent = label + ' · ' + clock(data.observedMs) + ' / 30:00'; - if (data.complete) { - status.textContent = interruptions ? '30 minutes · incomplete observation' : - drop ? '30 minutes · received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms' : - gaps ? '30 minutes · reference mismatches recorded' : '30 minutes · continuous reference received'; + timing.hidden = data.timing.baselinePpm===null; + timing.textContent = 'Largest pitch change · ' + (data.timing.maxRatePpm/10000).toFixed(2) + + '% · Confirmed marker timing step · ' + data.timing.maxShiftMs + ' ms'; + const target = run.stage.minutes + ':00'; + const label = clock(data.observedMs) + ' / ' + target; + detail.hidden = data.missingWindows === 0 && data.sequenceFaults === 0; + detail.textContent = 'Longest reference mismatch · ' + Math.round(data.gapMaxMs) + ' ms'; + let hold; + if (interruptions) hold = 'Observation interrupted'; + else if (data.levelDrops) hold = 'Received audio level drop · ' + Math.round(data.longestLevelDropMs) + ' ms'; + 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'); - } + } else status.textContent = 'Signal tracking · ' + label; } }; run.source.connect(node); node.connect(run.context.destination); diff --git a/services/bstein-dev-home/av-observer/acoustic-worklet.js b/services/bstein-dev-home/av-observer/acoustic-worklet.js index c2c0fdfe..b1792e6d 100644 --- a/services/bstein-dev-home/av-observer/acoustic-worklet.js +++ b/services/bstein-dev-home/av-observer/acoustic-worklet.js @@ -1,11 +1,11 @@ import {AcousticDetector} from './acoustic-detector.js'; class AcousticProbe extends AudioWorkletProcessor { - constructor() { + constructor(options) { super(); - this.detector = new AcousticDetector(sampleRate); + this.detector = new AcousticDetector(sampleRate, options.processorOptions.minutes); this.next = currentFrame; - this.deadline = currentFrame + sampleRate * 35 * 60; + this.deadline = currentFrame + sampleRate * (this.detector.minutes * 60 + 60); this.ack = currentFrame; this.credit = true; this.stopped = false; diff --git a/services/bstein-dev-home/av-observer/index.html b/services/bstein-dev-home/av-observer/index.html index 84e43fcd..9c57a14c 100644 --- a/services/bstein-dev-home/av-observer/index.html +++ b/services/bstein-dev-home/av-observer/index.html @@ -5,7 +5,7 @@

A/V Test

Audio Test -

30-minute RCT mic test · Phone sound source

+

Staged RCT mic test · Phone sound source

Select a camera and microphone. Quick checks report numeric metrics automatically. Watches keep metrics here for Save metrics; audio and video never upload.

diff --git a/services/bstein-dev-home/av-observer/kustomization.yaml b/services/bstein-dev-home/av-observer/kustomization.yaml index 15cb567a..2e80f20f 100644 --- a/services/bstein-dev-home/av-observer/kustomization.yaml +++ b/services/bstein-dev-home/av-observer/kustomization.yaml @@ -14,6 +14,7 @@ configMapGenerator: - acoustic-pattern.js - acoustic-watch.js - acoustic-worklet.js + - acoustic-timing.js - phone-source.js - phone.html - mic.html diff --git a/services/bstein-dev-home/av-observer/mic-observer.js b/services/bstein-dev-home/av-observer/mic-observer.js index 1676ce12..51caff06 100644 --- a/services/bstein-dev-home/av-observer/mic-observer.js +++ b/services/bstein-dev-home/av-observer/mic-observer.js @@ -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 {OutputPulses} from './mic-output.js'; import {stopTracks} from './capture-lifecycle.js'; @@ -27,7 +27,7 @@ function snapshot(run) { endpointPlaybackMeasured:false,audioUploaded:false}; } 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) { if(current!==run)return; @@ -61,9 +61,10 @@ function stop(reason='operator') { stopOutput(reason); const run=current;current=null; 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); - 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;} el('status').textContent=`Stopped · ${reason}`;buttons(); } @@ -84,12 +85,14 @@ el('devices').onclick=async()=>{ } catch {if(ticket===generation)stop('device permission unavailable');} 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()=>{ 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 { @@ -126,7 +129,7 @@ el('start').onclick=async()=>{ 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?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');} finally {if(current!==run)release(run);} }; diff --git a/services/bstein-dev-home/av-observer/mic-reporting.js b/services/bstein-dev-home/av-observer/mic-reporting.js index 054d70a1..68486237 100644 --- a/services/bstein-dev-home/av-observer/mic-reporting.js +++ b/services/bstein-dev-home/av-observer/mic-reporting.js @@ -5,7 +5,7 @@ import {RunReporter} from './reporting.js'; 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; + this.baseline=null;this.ids=[];this.last=null;this.stageWindows=[]; } snapshot(now,audio,settings,reason) { const b=this.baseline??{}; @@ -22,7 +22,8 @@ export class AudioReports { observe(now,audio,settings) { if(this.reporter&&now-this.start>=120000) { 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; } 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) { 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; } } diff --git a/services/bstein-dev-home/av-observer/mic.html b/services/bstein-dev-home/av-observer/mic.html index 9fbb781b..2be4a931 100644 --- a/services/bstein-dev-home/av-observer/mic.html +++ b/services/bstein-dev-home/av-observer/mic.html @@ -2,14 +2,15 @@ Audio Test

Audio Test

A/V Test -

30-minute RCT receiver test Phone sound source

+

Staged RCT receiver test Phone sound source

- +
+
diff --git a/services/bstein-dev-home/av-observer/nginx.conf b/services/bstein-dev-home/av-observer/nginx.conf index 66a7e27f..649637bd 100644 --- a/services/bstein-dev-home/av-observer/nginx.conf +++ b/services/bstein-dev-home/av-observer/nginx.conf @@ -6,6 +6,25 @@ http { include /etc/nginx/mime.types; default_type application/octet-stream; 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":"(?[0-9a-f]{32})","sequence":(?[1-9][0-9]?),"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; client_max_body_size 4k; client_body_timeout 5s; @@ -19,6 +38,8 @@ http { listen 8080; absolute_redirect off; 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 X-Content-Type-Options "nosniff" always; add_header X-Frame-Options "DENY" always; @@ -42,11 +63,12 @@ http { if ($request_method !~ ^(GET|HEAD)$) { return 405; } 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; } try_files $uri =404; } location ~ ^/av-test/api/(start|report)$ { + access_log /dev/stdout av_stage if=$av_ack; if ($request_method != POST) { return 405; } proxy_pass http://127.0.0.1:8081; proxy_connect_timeout 2s; diff --git a/services/bstein-dev-home/av-observer/phone-source.js b/services/bstein-dev-home/av-observer/phone-source.js index c6c95549..8a40c062 100644 --- a/services/bstein-dev-home/av-observer/phone-source.js +++ b/services/bstein-dev-home/av-observer/phone-source.js @@ -1,9 +1,11 @@ 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 stopButton = document.getElementById('stop'); 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; function clockSample(owner) { 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.wake?.release().catch(() => {}); } - play.disabled = false; stopButton.disabled = true; + play.disabled = false; stopButton.disabled = true; duration.disabled = false; status.textContent = message; } play.onclick = async () => { if (active) return; 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 owner = {context}; active = owner; play.disabled = true; stopButton.disabled = false; @@ -52,10 +58,10 @@ play.onclick = async () => { context.onstatechange = () => { 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 = () => { 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) + ':' + String(remaining % 60).padStart(2, '0') + ' remaining'; }; diff --git a/services/bstein-dev-home/av-observer/phone.html b/services/bstein-dev-home/av-observer/phone.html index 4f086033..923a1541 100644 --- a/services/bstein-dev-home/av-observer/phone.html +++ b/services/bstein-dev-home/av-observer/phone.html @@ -3,8 +3,9 @@ Phone audio source

Phone audio source

Place the phone near the microphone. Use its speaker at a comfortable volume and keep this page visible.

+ -

Ready · 32 minutes

+

Ready

Playback reporting idle

RCT receiver test
diff --git a/services/bstein-dev-home/av-observer/reporting.js b/services/bstein-dev-home/av-observer/reporting.js index 682ac7d2..7be44645 100644 --- a/services/bstein-dev-home/av-observer/reporting.js +++ b/services/bstein-dev-home/av-observer/reporting.js @@ -40,6 +40,23 @@ export function stopState(reason) { 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 { constructor(status,request=globalThis.fetch.bind(globalThis)) { this.status=status;this.request=request;this.pending=null;this.busy=false; @@ -49,9 +66,16 @@ export class RunReporter { } async open() { try { + const sentAt=performance.now(); const r=await this.request('/av-test/api/start',{method:'POST',credentials:'omit', headers:{'Content-Type':'application/json'},body:'{}',signal:AbortSignal.timeout(5000)}); 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(); 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; @@ -69,13 +93,17 @@ export class RunReporter { this.lastProgress=receipt.elapsedMs;this.queue('running',receipt); } finish(receipt) { - if(this.terminal)return; - this.terminal=true;this.queue(stopState(receipt.reason),receipt); + if(!this.terminal) { + this.terminal=true; + this.finished=new Promise(resolve=>{this.resolveFinished=resolve;}); + this.queue(stopState(receipt.reason),receipt); + } + return this.finished; } 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)}; + this.pending={state,metrics:reportMetrics(receipt),path:receipt.paired?.pilot}; void this.flush(); } async flush() { @@ -83,23 +111,27 @@ export class RunReporter { this.busy=true; try { await this.ready; - if(!this.available){this.pending=null;return;} + if(!this.available){this.pending=null;this.resolveFinished?.(false);return;} while(this.pending) { 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; for(let attempt=0;attempt<2&&!delivered;attempt++) { try { const response=await this.request('/av-test/api/report',{ method:'POST',credentials:'omit',keepalive:true, - headers:{'Content-Type':'application/json',Authorization:`Bearer ${this.token}`}, + headers, 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; } catch { /* No raw exception or endpoint response is displayed. */ } } if(report.state!=='running') { + this.resolveFinished?.(!!delivered); this.status(delivered ? `Result reported · test ${this.runId.slice(0,8)}` : 'Result not reported · use Save metrics'); } else if(!delivered) {