From af45190bfb003f0f9293df4115f02485b8e91ec3 Mon Sep 17 00:00:00 2001 From: jenkins Date: Thu, 3 Dec 2026 12:11:53 -0600 Subject: [PATCH] bstein: serve the phone sound source and 30-minute RCT microphone detector Vendor the web assets from Lesavka a5758755. The RCT browser performs signal recognition and sends numeric observations through the existing receipt service. --- .../av-observer/acoustic-detector.js | 108 ++++++++++++++++++ .../av-observer/acoustic-pattern.js | 23 ++++ .../av-observer/acoustic-watch.js | 56 +++++++++ .../av-observer/acoustic-worklet.js | 35 ++++++ .../bstein-dev-home/av-observer/index.html | 1 + .../av-observer/kustomization.yaml | 6 + .../av-observer/mic-observer.js | 33 ++++-- .../av-observer/mic-reporting.js | 12 +- services/bstein-dev-home/av-observer/mic.html | 2 + .../bstein-dev-home/av-observer/nginx.conf | 2 +- .../av-observer/phone-source.js | 74 ++++++++++++ .../bstein-dev-home/av-observer/phone.html | 10 ++ .../bstein-dev-home/av-observer/reporting.js | 4 +- 13 files changed, 351 insertions(+), 15 deletions(-) create mode 100644 services/bstein-dev-home/av-observer/acoustic-detector.js create mode 100644 services/bstein-dev-home/av-observer/acoustic-pattern.js create mode 100644 services/bstein-dev-home/av-observer/acoustic-watch.js create mode 100644 services/bstein-dev-home/av-observer/acoustic-worklet.js create mode 100644 services/bstein-dev-home/av-observer/phone-source.js create mode 100644 services/bstein-dev-home/av-observer/phone.html diff --git a/services/bstein-dev-home/av-observer/acoustic-detector.js b/services/bstein-dev-home/av-observer/acoustic-detector.js new file mode 100644 index 00000000..0b0fe704 --- /dev/null +++ b/services/bstein-dev-home/av-observer/acoustic-detector.js @@ -0,0 +1,108 @@ +// 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 {PilotWindow} from './pilot-window.js'; + +export class AcousticDetector { + constructor(rate) { + 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.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); + this.count = this.energy = this.tick = this.edges = this.lastChange = 0; + this.lastMarker = this.slot = -1; + this.locked = false; + this.windows = this.bad = this.gap = this.longest = this.sequenceFaults = this.interruptions = 0; + this.faults = []; + this.recent = new PilotWindow(this.windowMs); + this.nextFrame = null; + } + interrupt() { + if (this.locked && this.windows < this.target) { + this.interruptions++; + this.record('observation interrupted'); + this.recent.interrupt(); + } + this.edges = 0; + this.slot = this.lastMarker = -1; + this.count = this.energy = 0; + this.q1.fill(0); this.q2.fill(0); + } + record(kind) { + if (this.faults.length < 64) this.faults.push({atMs: Math.round(this.windows * this.windowMs), kind}); + } + detect() { + const power = this.coeff.map((c, i) => Math.max(0, + this.q1[i] ** 2 + this.q2[i] ** 2 - c * this.q1[i] * this.q2[i])); + const marker = power.indexOf(Math.max(...power.slice(1)), 1); + // Both tones must be distinguishable at room level, including against + // the optional RCT's separate 1 kHz output pulses. + const min = Math.max((0.0008 * this.size / 2) ** 2, 0.035 * this.size * this.energy); + if (power[0] < min || power[marker] < min || this.energy === 0) return -1; + return marker - 1; + } + window(marker, endMs) { + this.tick++; + let valid = marker >= 0; + const dwellMs = (this.tick - this.lastChange) * this.windowMs; + if (valid && marker !== this.lastMarker) { + const pair = ORDER.findIndex((v, i) => v === marker && + ORDER[(i + ORDER.length - 1) % ORDER.length] === this.lastMarker); + const expected = this.slot < 0 || pair === (this.slot + 1) % ORDER.length; + const onTime = Math.abs(dwellMs - 1000 * SYMBOL_SECONDS) <= 2.1 * this.windowMs; + const matched = pair >= 0 && expected && onTime; + this.edges = matched ? this.edges + 1 : 0; + if (this.locked && !matched) { + this.sequenceFaults++; + this.record('marker order or timing'); + valid = false; + } + this.slot = pair; + this.lastMarker = marker; + this.lastChange = this.tick; + } else if (valid && dwellMs > 1000 * SYMBOL_SECONDS + 2.1 * this.windowMs) { + valid = false; // A frozen or replayed single symbol is audible energy too. + } + if (!this.locked) { + if (!valid) this.edges = 0; + if (this.edges < 4) return; + this.locked = true; + } + this.windows++; + 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); + } else this.gap = 0; + this.recent.observe(valid, endMs); + } + process(samples, frame, length) { + if (this.windows >= this.target) return; + if (this.nextFrame !== null && this.nextFrame !== frame) this.interrupt(); + this.nextFrame = frame + length; + for (let i = 0; i < length && this.windows < this.target; i++) { + const x = samples?.[i] ?? 0; + this.energy += x * x; + for (let j = 0; j < this.coeff.length; j++) { + const q = x + this.coeff[j] * this.q1[j] - this.q2[j]; + this.q2[j] = this.q1[j]; this.q1[j] = q; + } + if (++this.count === this.size) { + this.window(this.detect(), (frame + i + 1) * 1000 / this.rate); + this.q1.fill(0); this.q2.fill(0); this.count = this.energy = 0; + } + } + } + summary(nowMs) { + return {locked: this.locked, complete: this.windows >= this.target, + observedMs: this.windows * this.windowMs, windows: this.windows, + missingWindows: this.bad, sequenceFaults: this.sequenceFaults, + missingFraction: this.windows ? this.bad / this.windows : null, + gapMaxMs: this.longest * this.windowMs, trailingGapMs: this.gap * this.windowMs, + discontinuities: this.interruptions, recent: this.recent.summary(nowMs), + firstFaults: this.faults.slice()}; + } +} diff --git a/services/bstein-dev-home/av-observer/acoustic-pattern.js b/services/bstein-dev-home/av-observer/acoustic-pattern.js new file mode 100644 index 00000000..1a90f73b --- /dev/null +++ b/services/bstein-dev-home/av-observer/acoustic-pattern.js @@ -0,0 +1,23 @@ +// Every ordered pair in the repeating marker sequence occurs once. This lets +// a receiver joining mid-cycle identify position without synchronized clocks. +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 function referenceLoop(rate) { + const data = new Float32Array(Math.round(rate * SYMBOL_SECONDS * ORDER.length)); + for (let i = 0; i < data.length; i++) { + const t = i / rate; + const slot = Math.min(ORDER.length - 1, Math.floor(i * ORDER.length / data.length)); + const tone = MARKERS_HZ[ORDER[slot]]; + const oldTone = MARKERS_HZ[ORDER[(slot + ORDER.length - 1) % ORDER.length]]; + const fade = Math.min(1, Math.max(0, (t - slot * SYMBOL_SECONDS) / 0.004)); + const phase = 2 * Math.PI * t; + data[i] = 0.15 * Math.sin(phase * ANCHOR_HZ) + + 0.15 * (fade * Math.sin(phase * tone) + (1 - fade) * Math.sin(phase * oldTone)); + } + return data; +} diff --git a/services/bstein-dev-home/av-observer/acoustic-watch.js b/services/bstein-dev-home/av-observer/acoustic-watch.js new file mode 100644 index 00000000..1b229b77 --- /dev/null +++ b/services/bstein-dev-home/av-observer/acoustic-watch.js @@ -0,0 +1,56 @@ +import {TRIAL_SECONDS} from './acoustic-pattern.js'; + +export const phoneTest = new URLSearchParams(location.search).get('test') === 'phone'; +const status = document.getElementById('path-state'); +const clock = ms => { + const s = Math.min(TRIAL_SECONDS, Math.floor(ms / 1000)); + return Math.floor(s / 60) + ':' + String(s % 60).padStart(2, '0'); +}; + +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.'; + for (const id of ['tone','tone-stop','output-status','output-report','path-link']) { + document.getElementById(id).hidden = true; + } + document.getElementById('output').closest('label').hidden = true; + status.hidden = false; status.textContent = 'Choose the Lesavka USB microphone'; +} +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'); + run.detector = node; + run.pathInterruptions = 0; + status.textContent = 'Waiting for phone signal'; + node.onprocessorerror = () => { if (isCurrent()) finish('detector failed'); }; + node.port.onmessage = ({data}) => { + if (!isCurrent()) return; + if (data.expired) { finish('receiver deadline or lost observer'); return; } + node.port.postMessage('ack'); + const now = performance.now(); + const wall = Date.now(); + if (data.locked && run.pathStart === undefined) { + run.pathStart = now - data.observedMs; + run.pathWall = wall - data.observedMs; + } + 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}; + if (data.locked) { + const gaps = data.missingWindows > 0 || data.sequenceFaults > 0; + const label = interruptions ? 'Observation interrupted' : gaps ? 'Signal breaks detected' : 'Signal tracking'; + status.textContent = label + ' · ' + clock(data.observedMs) + ' / 30:00'; + if (data.complete) { + status.textContent = interruptions ? '30 minutes · incomplete observation' : + gaps ? '30 minutes · signal breaks detected' : '30 minutes · continuous reference received'; + finish('phone test complete'); + } + } + }; + 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 new file mode 100644 index 00000000..c2c0fdfe --- /dev/null +++ b/services/bstein-dev-home/av-observer/acoustic-worklet.js @@ -0,0 +1,35 @@ +import {AcousticDetector} from './acoustic-detector.js'; + +class AcousticProbe extends AudioWorkletProcessor { + constructor() { + super(); + this.detector = new AcousticDetector(sampleRate); + this.next = currentFrame; + this.deadline = currentFrame + sampleRate * 35 * 60; + this.ack = currentFrame; + this.credit = true; + this.stopped = false; + this.port.onmessage = ({data}) => { + if (data === 'stop') this.stopped = true; + if (data === 'ack') { this.credit = true; this.ack = currentFrame; } + }; + } + process(inputs, outputs) { + if (this.stopped) return false; + if (currentFrame >= this.deadline || currentFrame - this.ack > 10 * sampleRate) { + this.port.postMessage({expired:true}); + return false; + } + const size = outputs[0][0].length; + this.detector.process(inputs[0]?.[0], currentFrame, size); + if (this.credit && currentFrame >= this.next) { + const sample = this.detector.summary((currentFrame + size) * 1000 / sampleRate); + this.port.postMessage(sample); + if (sample.complete) return false; + this.next = currentFrame + sampleRate; + this.credit = false; + } + return true; + } +} +registerProcessor('acoustic-probe', AcousticProbe); diff --git a/services/bstein-dev-home/av-observer/index.html b/services/bstein-dev-home/av-observer/index.html index dbf6dcce..84e43fcd 100644 --- a/services/bstein-dev-home/av-observer/index.html +++ b/services/bstein-dev-home/av-observer/index.html @@ -5,6 +5,7 @@

A/V Test

Audio Test +

30-minute 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 92f9aae2..15cb567a 100644 --- a/services/bstein-dev-home/av-observer/kustomization.yaml +++ b/services/bstein-dev-home/av-observer/kustomization.yaml @@ -10,6 +10,12 @@ configMapGenerator: files: [nginx.conf] - name: lesavka-av-observer-assets files: + - 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 diff --git a/services/bstein-dev-home/av-observer/mic-observer.js b/services/bstein-dev-home/av-observer/mic-observer.js index 0ebc3512..1676ce12 100644 --- a/services/bstein-dev-home/av-observer/mic-observer.js +++ b/services/bstein-dev-home/av-observer/mic-observer.js @@ -1,7 +1,9 @@ +import {phoneTest, setupPhoneMode, attachDetector} 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() { @@ -20,14 +22,18 @@ function snapshot(run) { 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.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,run.audio,run.settings); + 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); @@ -43,6 +49,8 @@ function stopOutput(reason='operator') { } 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{} @@ -52,8 +60,10 @@ 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); + if(run){event(run,reason); + if(phoneTest && reason!=='phone test complete')el('path-state').textContent='Incomplete · '+reason; + release(run); + run.reports.finish(performance.now(),audioReport(run),run.settings,reason); last=snapshot(run);el('metrics').textContent=JSON.stringify(last,null,2);el('save').disabled=false;} el('status').textContent=`Stopped · ${reason}`;buttons(); } @@ -67,10 +77,10 @@ el('devices').onclick=async()=>{ 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)); + 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='Select microphone and output';buttons(); + el('status').textContent=phoneTest?'Select the USB microphone':'Select microphone and output';buttons(); } catch {if(ticket===generation)stop('device permission unavailable');} finally {clearTimeout(deadline);} }; @@ -87,10 +97,11 @@ el('start').onclick=async()=>{ 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');update(run);}}; + 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'}}); @@ -104,14 +115,18 @@ el('start').onclick=async()=>{ 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}`);}; + 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='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.deadline=setTimeout(()=>{if(current===run)stop('operator');},1200000);update(run); + run.deadline=setTimeout(()=>{if(current===run)stop(phoneTest?'receiver time limit':'operator');},phoneTest?35*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 b6f04d63..054d70a1 100644 --- a/services/bstein-dev-home/av-observer/mic-reporting.js +++ b/services/bstein-dev-home/av-observer/mic-reporting.js @@ -10,20 +10,26 @@ export class AudioReports { 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, + const path=audio?.path; + const boundedMs=value=>value<=180000?value:null; + const paired=path?{pilot:{...path,windows:path.windows-(b.path?.windows??0), + gapMaxMs:boundedMs(path.gapMaxMs),trailingGapMs:boundedMs(path.trailingGapMs)}, + continuity:{badMarkers:path.sequenceFaults}}:null; + return {paired,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')); + const reason=audio?.path?'signal report window closed':'120 seconds complete'; + this.reporter.finish(this.snapshot(now,audio,settings,reason)); 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); + if(this.reporter?.runId&&this.ids.length<32&&!this.ids.includes(this.reporter.runId))this.ids.push(this.reporter.runId); } finish(now,audio,settings,reason) { if(!this.reporter)return; diff --git a/services/bstein-dev-home/av-observer/mic.html b/services/bstein-dev-home/av-observer/mic.html index a4583fde..70647a03 100644 --- a/services/bstein-dev-home/av-observer/mic.html +++ b/services/bstein-dev-home/av-observer/mic.html @@ -2,6 +2,8 @@ Audio Test

Audio Test

A/V Test +

30-minute 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 f16fb01f..66a7e27f 100644 --- a/services/bstein-dev-home/av-observer/nginx.conf +++ b/services/bstein-dev-home/av-observer/nginx.conf @@ -42,7 +42,7 @@ http { if ($request_method !~ ^(GET|HEAD)$) { return 405; } try_files /av-test/index.html =404; } - 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)$ { + 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)$ { if ($request_method !~ ^(GET|HEAD)$) { return 405; } try_files $uri =404; } diff --git a/services/bstein-dev-home/av-observer/phone-source.js b/services/bstein-dev-home/av-observer/phone-source.js new file mode 100644 index 00000000..c6c95549 --- /dev/null +++ b/services/bstein-dev-home/av-observer/phone-source.js @@ -0,0 +1,74 @@ +import {AudioReports} from './mic-reporting.js'; +import {referenceLoop, SOURCE_SECONDS} from './acoustic-pattern.js'; + +const play = document.getElementById('play'); +const stopButton = document.getElementById('stop'); +const status = document.getElementById('state'); +let active = null; +function clockSample(owner) { + const frames = Math.floor(Math.max(0,owner.context.currentTime - owner.started) * owner.context.sampleRate); + return {processedFrames:frames, sampleRate:owner.context.sampleRate}; +} +function stop(message) { + const owner = active; + active = null; + if (owner) { + clearInterval(owner.timer); + const reason = message === 'Playback complete' ? 'reference complete' : + message === 'Playback stopped' ? 'operator' : 'source interrupted'; + owner.reports?.finish(performance.now(), clockSample(owner), {sampleRate:owner.context.sampleRate}, reason); + owner.context.onstatechange = null; + if (owner.source) { + owner.source.onended = null; + try { owner.source.stop(); } catch {} + } + void owner.context.close().catch(() => {}); + void owner.wake?.release().catch(() => {}); + } + play.disabled = false; stopButton.disabled = true; + status.textContent = message; +} +play.onclick = async () => { + if (active) return; + try { + const context = new AudioContext(); + const owner = {context}; + active = owner; play.disabled = true; stopButton.disabled = false; + status.textContent = 'Starting speaker'; + await context.resume(); + if (active !== owner) return; + const data = referenceLoop(context.sampleRate); + const buffer = context.createBuffer(1, data.length, context.sampleRate); + buffer.copyToChannel(data, 0); + const source = context.createBufferSource(); + owner.source = source; source.buffer = buffer; source.loop = true; + source.connect(context.destination); + const start = context.currentTime; + owner.started = start; + owner.reports = new AudioReports(text => { + if (active === owner) document.getElementById('report').textContent = text; + }); + source.onended = () => { if (active === owner) stop('Playback complete'); }; + context.onstatechange = () => { + if (active === owner && context.state !== 'running') stop('Speaker interrupted'); + }; + source.start(start); source.stop(start + SOURCE_SECONDS); + const show = () => { + owner.reports.observe(performance.now(), clockSample(owner), {sampleRate:context.sampleRate}); + const remaining = Math.max(0, Math.ceil(SOURCE_SECONDS - (context.currentTime - start))); + status.textContent = 'Playing · ' + Math.floor(remaining / 60) + ':' + + String(remaining % 60).padStart(2, '0') + ' remaining'; + }; + show(); owner.timer = setInterval(show, 1000); + try { + const wake = await navigator.wakeLock?.request('screen'); + if (active === owner) owner.wake = wake; + else await wake?.release(); + } catch {} + } catch { stop('Speaker unavailable'); } +}; +stopButton.onclick = () => stop('Playback stopped'); +document.addEventListener('visibilitychange', () => { + if (document.hidden && active) stop('Playback interrupted · phone page hidden'); +}); +window.addEventListener('pagehide', () => stop('Playback stopped')); diff --git a/services/bstein-dev-home/av-observer/phone.html b/services/bstein-dev-home/av-observer/phone.html new file mode 100644 index 00000000..4f086033 --- /dev/null +++ b/services/bstein-dev-home/av-observer/phone.html @@ -0,0 +1,10 @@ + + +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

+

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 7658326a..682ac7d2 100644 --- a/services/bstein-dev-home/av-observer/reporting.js +++ b/services/bstein-dev-home/av-observer/reporting.js @@ -32,11 +32,11 @@ export function reportMetrics(receipt) { } export function stopState(reason) { - if(reason==='120 seconds complete')return 'completed'; + if(reason==='120 seconds complete'||reason==='phone test complete'||reason==='reference complete')return 'completed'; if(reason==='page hidden; timing invalid')return 'hidden'; if(reason==='page closed')return 'closed'; if(reason==='device ended'||reason==='device selection changed')return 'device-change'; - if(reason==='operator'||reason==='selecting devices')return 'stopped'; + if(reason==='operator'||reason==='selecting devices'||reason==='signal report window closed')return 'stopped'; return 'failed'; }