bstein: measure received speech for full selected microphone stage

This commit is contained in:
jenkins 2026-12-03 13:33:21 -06:00
parent ec764ca66f
commit 2dc8a40e92
14 changed files with 412 additions and 19 deletions

View File

@ -1,6 +1,8 @@
import {attachSpeech} from './speech-watch.js';
import {STAGE_MINUTES, TRIAL_SECONDS} from './acoustic-pattern.js';
export const phoneTest = new URLSearchParams(location.search).get('test') === 'phone';
export const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
const status = document.getElementById('path-state');
const detail = document.getElementById('path-detail');
const duration = document.getElementById('stage-duration');
@ -44,6 +46,8 @@ export function setupPhoneMode() {
for (const minutes of STAGE_MINUTES) duration.add(new Option(minutes+' min',String(minutes)));
document.getElementById('stage-label').hidden = false;
renderStage();
document.getElementById('local-review').hidden = !speechMode;
if (speechMode) status.title='Compare received speech to the phone phrase';
duration.onchange = () => {
if (!duration.disabled && duration.selectedIndex>=0 && duration.selectedIndex<=unlockedIndex) {
stageIndex = duration.selectedIndex;
@ -58,6 +62,7 @@ export function setupPhoneMode() {
status.hidden = false; status.textContent = 'Choose the Lesavka USB microphone';
}
export async function attachDetector(run, isCurrent, finish) {
if (speechMode) return attachSpeech(run,isCurrent,finish);
await run.context.audioWorklet.addModule('acoustic-worklet.js');
if (!isCurrent()) return;
const node = new AudioWorkletNode(run.context, 'acoustic-probe', {processorOptions:{minutes:run.stage.minutes}});
@ -101,9 +106,8 @@ export async function attachDetector(run, isCurrent, finish) {
data.timing.edgeCount < 0.8*data.observedMs/100)) hold = 'Insufficient timing coverage · pitch ' + Math.round(100*data.timing.rateCoverageMs/data.observedMs) +
'% · markers ' + Math.round(10000*data.timing.edgeCount/data.observedMs) + '%';
if (hold) {
status.textContent = 'Stage held · ' + hold + ' · ' + label;
run.findingAt ??= data.observedMs;
if (interruptions || data.complete || data.observedMs-run.findingAt>=2000) finish('stage finding');
status.textContent = (data.complete ? 'Stage held · ' : 'Still measuring · ') + hold + ' · ' + label;
if (data.complete) finish('stage finding');
} else if (data.complete) {
status.textContent = 'Stage complete · ' + label + ' · review before advancing';
finish('phone test complete');

View File

@ -10,6 +10,12 @@ configMapGenerator:
files: [nginx.conf]
- name: lesavka-av-observer-assets
files:
- speech-reference.flac
- speech-alignment.js
- speech-detector.js
- speech-envelope.js
- speech-watch.js
- speech-worklet.js
- acoustic-detector.js
- acoustic-pattern.js
- acoustic-watch.js

View File

@ -2,8 +2,8 @@
// tracks or a network client; stopping it must not stop the numeric observer.
export class LocalRecording {
constructor({Recorder=globalThis.MediaRecorder,onStatus=()=>{},onReady=()=>{},
maxBytes=128*1024*1024,maxMs=180000}={}) {
Object.assign(this,{Recorder,onStatus,onReady,maxBytes,maxMs});
maxBytes=128*1024*1024,maxMs=180000,audioOnly=false}={}) {
Object.assign(this,{Recorder,onStatus,onReady,maxBytes,maxMs,audioOnly});
this.serial=0;this.active=null;
}
get supported() {return typeof this.Recorder==='function';}
@ -11,11 +11,13 @@ export class LocalRecording {
this.discard();
if(!this.supported){this.onStatus('Recording unavailable in this browser.');return false;}
const serial=this.serial;
const mimeType=['video/webm;codecs=vp8,opus','video/webm','video/mp4'].find(
const types=this.audioOnly?['audio/webm;codecs=opus','audio/webm','audio/mp4']:
['video/webm;codecs=vp8,opus','video/webm','video/mp4'];
const mimeType=types.find(
type=>this.Recorder.isTypeSupported(type));
try {
const recorder=new this.Recorder(stream,{...(mimeType?{mimeType}:{}),
videoBitsPerSecond:4000000,audioBitsPerSecond:128000});
...(this.audioOnly?{}:{videoBitsPerSecond:4000000}),audioBitsPerSecond:this.audioOnly?64000:128000});
const run={recorder,chunks:[],bytes:0,failed:false};
this.active=run;
recorder.ondataavailable=({data})=>{
@ -40,7 +42,7 @@ export class LocalRecording {
if(serial!==this.serial)return;
this.active=null;
if(!run.failed&&run.bytes) {
const blob=new Blob(run.chunks,{type:recorder.mimeType||mimeType||'video/webm'});
const blob=new Blob(run.chunks,{type:recorder.mimeType||mimeType||(this.audioOnly?'audio/webm':'video/webm')});
this.onReady(blob);
this.onStatus('Ready for local replay · nothing uploaded');
} else if(!run.failed)this.onStatus('No recording data was produced.');

View File

@ -1,4 +1,4 @@
import {phoneTest, setupPhoneMode, attachDetector, beginStage, reviewStage, selectStageInput} from './acoustic-watch.js';
import {phoneTest, speechMode, 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';
@ -10,7 +10,7 @@ function buttons() {
el('start').disabled=!!current||!el('input').value;
el('stop').disabled=!current;
el('devices').disabled=!!current||!!output;
if(phoneTest)el('stage-duration').disabled=!!current;
if(phoneTest){el('stage-duration').disabled=!!current;el('keep-speech').disabled=!!current;}
el('input').disabled=!!current;el('output').disabled=!!output;
el('tone').disabled=!!output||!el('output').value;
el('tone-stop').disabled=!output;
@ -49,6 +49,7 @@ function stopOutput(reason='operator') {
el('output-status').textContent=`Output stopped · ${reason}`;buttons();
}
function release(run) {
run.recording?.finish();
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();}
@ -128,7 +129,7 @@ el('start').onclick=async()=>{
if(run.context.state!=='running')throw new Error('Context suspended');
clearTimeout(run.setupTimer);event(run,'capture-started');
el('selection').textContent=`Microphone: ${run.track.label}\nCapture output: silent sink`;
el('status').textContent=phoneTest?'Receiver listening · start the phone sound':'Watching microphone · 20-minute limit';
el('status').textContent=phoneTest?'Receiver listening':'Watching microphone · 20-minute limit';
run.timer=setInterval(()=>update(run),1000);
run.deadline=setTimeout(()=>{if(current===run)stop(phoneTest?'receiver time limit':'operator');},phoneTest?(run.stage.minutes+1)*60000:1200000);update(run);
} catch {if(current===run)stop('capture/setup failed');}
@ -156,7 +157,11 @@ el('save').onclick=()=>{
};
navigator.mediaDevices?.addEventListener('devicechange',()=>{if(current)event(current,'device-list-changed');});
window.addEventListener('pagehide',()=>stop('page closed'));
document.addEventListener('visibilitychange',()=>{if(document.hidden&&(current||output))stop('page hidden; timing invalid');});
document.addEventListener('visibilitychange',()=>{
if (phoneTest && speechMode && current) {
event(current,document.hidden?'page-hidden':'page-visible');update(current);
} else if(document.hidden&&(current||output))stop('page hidden; timing invalid');
});
if(!window.isSecureContext||!navigator.mediaDevices||!window.AudioWorkletNode){
el('devices').disabled=true;el('status').textContent='Audio observation unavailable';
}

View File

@ -14,6 +14,8 @@
<button id="tone" disabled title="Quiet 1 kHz pulses on the explicitly selected output for two minutes. This exercises output separately; microphone audio is never monitored.">Start output pulses</button>
<button id="tone-stop" disabled>Stop output</button>
<button id="save" disabled>Save metrics</button></div>
<div id="local-review" hidden><label><input type="checkbox" id="keep-speech"> Keep received audio for replay on this RCT</label>
<span id="record-status"></span><audio controls id="speech-replay" hidden></audio> <button id="hear-finding" hidden>Replay first finding</button></div>
<p id="status" role="status">Stopped</p><p id="report-status">Mic reporting idle</p><p id="output-status">Output stopped</p>
<p id="output-report">Output reporting idle</p>
<meter id="level" min="0" max="1" value="0" title="Current microphone peak"></meter>

View File

@ -20,11 +20,19 @@ http {
default "";
'~^/av-test/api/report[|]204[|][^|]+[|][-0-9,]+$' 1;
}
map $http_x_av_speech $av_speech {
default "";
'~^1,[0-9]{1,7},-?[0-9]{1,4},-?[0-9]{1,7},[0-9]{1,6},-?[0-9]{1,7}(;[0-9]{1,6},[1-4],[0-9]{1,7},[0-9]{1,7},-?[0-9]{1,7},-?[0-9]{1,4}){0,16}$' $http_x_av_speech;
}
map "$av_ack|$av_speech" $av_speech_ack {
default "";
'~^1[|]1,' 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"}';
log_format av_stage escape=json '{"schema":"av-test.acoustic-stage.v1","received":"$msec","receipt":"$av_identity","stage":"$av_annotation","speech":"$av_speech"}';
server_tokens off;
client_max_body_size 4k;
client_body_timeout 5s;
@ -39,6 +47,7 @@ http {
absolute_redirect off;
root /usr/share/nginx/html;
add_header X-AV-Clock $av_clock always;
add_header X-AV-Speech-Ack $av_speech_ack 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;
@ -63,7 +72,7 @@ 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|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)$ {
location ~ ^/av-test/(speech-reference\.flac|speech-alignment\.js|speech-detector\.js|speech-envelope\.js|speech-watch\.js|speech-worklet\.js|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;
}

View File

@ -1,3 +1,4 @@
import {speechBuffer} from './speech-envelope.js';
import {AudioReports} from './mic-reporting.js';
import {referenceLoop, STAGE_MINUTES, SOURCE_LEAD_SECONDS} from './acoustic-pattern.js';
@ -6,6 +7,8 @@ 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)));
const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
play.textContent = speechMode ? 'Play spoken phrase' : 'Play diagnostic tones';
let active = null;
function clockSample(owner) {
const frames = Math.floor(Math.max(0,owner.context.currentTime - owner.started) * owner.context.sampleRate);
@ -43,9 +46,14 @@ play.onclick = async () => {
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);
let buffer;
if (speechMode) buffer = await speechBuffer(context);
else {
const data = referenceLoop(context.sampleRate);
buffer = context.createBuffer(1,data.length,context.sampleRate);
buffer.copyToChannel(data,0);
}
if (active !== owner) return;
const source = context.createBufferSource();
owner.source = source; source.buffer = buffer; source.loop = true;
source.connect(context.destination);
@ -71,7 +79,7 @@ play.onclick = async () => {
if (active === owner) owner.wake = wake;
else await wake?.release();
} catch {}
} catch { stop('Speaker unavailable'); }
} catch { if (active) stop('Speaker or reference unavailable'); }
};
stopButton.onclick = () => stop('Playback stopped');
document.addEventListener('visibilitychange', () => {

View File

@ -57,6 +57,23 @@ export function acousticReceipt(path, clock) {
return [...timing,end,clock?.uncertainty ?? 0,...warp].join(',');
}
export function speechReceipt(speech) {
if (!speech) return null;
const integer = (v,min,max) => Number.isSafeInteger(v) && v>=min && v<=max;
if (!integer(speech.coverageMs,0,1800000) || !integer(speech.phase,-1,9999) ||
!integer(speech.phaseAgeMs,-1,1800000) || !integer(speech.total,0,999999) ||
!integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) ||
speech.events.length>16) return null;
const rows=[[1,speech.coverageMs,speech.phase,speech.phaseAgeMs,speech.total,speech.maxCadencePpm]];
for (const row of speech.events) {
if (!Array.isArray(row) || row.length!==6 || !integer(row[0],1,speech.total) ||
!integer(row[1],1,4) || !integer(row[2],0,1800000) ||
!integer(row[3],0,1800000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null;
rows.push(row);
}
return rows.map(row=>row.join(',')).join(';');
}
export class RunReporter {
constructor(status,request=globalThis.fetch.bind(globalThis)) {
this.status=status;this.request=request;this.pending=null;this.busy=false;
@ -118,6 +135,8 @@ export class RunReporter {
const stage=acousticReceipt(report.path,this.clock);
const headers={'Content-Type':'application/json',Authorization:`Bearer ${this.token}`};
if(stage)headers['X-AV-Stage']=stage;
const speech=speechReceipt(report.path?.speech);
if(speech)headers['X-AV-Speech']=speech;
let delivered=false;
for(let attempt=0;attempt<2&&!delivered;attempt++) {
try {
@ -126,7 +145,8 @@ export class RunReporter {
headers,
body:JSON.stringify(payload),signal:AbortSignal.timeout(5000),
});
delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1'));
delivered=response.ok && (!stage || (this.clock && response.headers?.get?.('X-AV-Stage-Ack')==='1')) &&
(!report.path?.speech || (speech && response.headers?.get?.('X-AV-Speech-Ack')==='1'));
if(response.status>=400&&response.status<500)break;
} catch { /* No raw exception or endpoint response is displayed. */ }
}

View File

@ -0,0 +1,66 @@
// Match the envelope of the published phrase at any loop position. Clipping
// each band to its own dynamic range tolerates different mic gain/noise floors.
const wrap = (n, length) => ((n % length) + length) % length;
export const phaseDelta = (a, b, length) => wrap(a-b+Math.floor(length/2), length)-Math.floor(length/2);
const LOOKBACK = 125;
function normalized(values) {
const floor = Math.max(...values)-30;
const clipped = values.map(x => Math.max(x, floor));
const mean = clipped.reduce((sum, x) => sum + x, 0) / clipped.length;
const centered = clipped.map(x => x-mean);
const norm = Math.sqrt(centered.reduce((sum,x) => sum+x*x,0));
if (norm < 3 * Math.sqrt(values.length)) return null;
return centered.map(x => x/norm);
}
export class SpeechAlignment {
constructor({levels, highs}) {
this.length = levels.length;
this.bands = [levels, highs];
this.peak = Math.max(...levels);
this.patterns = levels.map((_, phase) => this.bands.map(band =>
normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length]))));
}
match(frames, end) {
if (frames.length < LOOKBACK) return null;
const window = frames.slice(-LOOKBACK);
if (window.some(row=>!row[2])) return null;
const received = [0,1].map(b=>normalized(window.map(row=>row[b])));
if (received.some(band=>!band)) return null;
let best = -1, bestScore = 0;
const scores = this.patterns.map((pattern, i) => {
if (pattern.some(band=>!band)) return -1;
let dot = 0;
for (let k = 0; k < LOOKBACK; k++)
dot += pattern[0][k]*received[0][k] + pattern[1][k]*received[1][k];
const score = dot/2;
if (score>bestScore) { best=i; bestScore=score; }
return score;
});
if (bestScore<0.74 || scores.some((s,i)=>Math.abs(phaseDelta(i,best,this.length))>6 && s>bestScore-0.07)) return null;
const gains = [];
for (let k=0;k<LOOKBACK;k++) {
const expected=this.bands[0][(best+k)%this.length];
if (expected>this.peak-18) gains.push(window[k][0]-expected);
}
if (gains.length<15) return null;
gains.sort((a,b)=>a-b);
return {phase:wrap(best-(end-LOOKBACK),this.length), gain:gains[gains.length>>1]};
}
// A loud unrelated sound can overlap a word without reducing RMS. Examine
// the shape of short, active passages independently of the long phase lock.
unclearPassage(frames, first, anchor) {
const received=frames.map(row=>row[0]);
let best=-1;
for (const delta of [-1,0,1]) {
const expected=received.map((_,i)=>this.expected(first+i,anchor.phase+delta));
if (expected.filter(x=>x>this.peak-20).length<6) return false;
if (Math.max(...received)<Math.max(...expected)+anchor.gain-14) return false;
const a=normalized(expected), b=normalized(received);
if (!a) return false;
if (b) best=Math.max(best,a.reduce((sum,x,i)=>sum+x*b[i],0));
}
return best<0.38;
}
expected(index,phase) { return this.bands[0][wrap(index+phase,this.length)]; }
}

View File

@ -0,0 +1,105 @@
import {SpeechAlignment, phaseDelta} from './speech-alignment.js';
// Event codes on the numeric receipt: 1 attenuated speech, 2 timing step,
// 3 uncertain alignment/level, 4 sustained cadence change. Time units are ms.
export class SpeechDetector {
constructor(reference,minutes) {
this.align=new SpeechAlignment(reference);
this.minutes=minutes;
this.frames=[]; this.end=this.scored=this.trusted=this.count=0;
this.events=[]; this.maxDrop=this.maxUnknown=this.shift=this.maxRate=0;
this.firstDrop=this.firstUnknown=this.firstShift=this.firstRate=null;
this.discontinuities=0; this.known=false; this.passage=[];
}
event(kind, start, duration, value=0, phase=null) {
const position=phase===null?-1:(start+phase)%this.align.length;
const row=[++this.count,kind,10*start,10*duration,value,position];
this.events.push(row);
if (this.events.length>16) this.events.shift();
if (kind===1) { this.firstDrop??=row[2]; this.maxDrop=Math.max(this.maxDrop,row[3]); }
if (kind===3) { this.firstUnknown??=row[2]; this.maxUnknown=Math.max(this.maxUnknown,row[3]); }
}
flushLoss() {
const loss=this.loss;
if (loss && loss.active>=10) this.event(1,loss.start,loss.last-loss.start+1,0,loss.phase);
this.loss=null;
}
score(to, anchor) {
const base=this.end-this.frames.length;
for (;this.scored<to;this.scored++) {
const i=this.scored, frame=this.frames[i-base];
if (!anchor || !frame?.[2]) {
this.flushLoss(); this.passage=[]; this.unknownStart??=i; continue;
}
if (this.unknownStart!=null) {
if (i-this.unknownStart>=10) this.event(3,this.unknownStart,i-this.unknownStart);
this.unknownStart=null;
}
this.trusted++;
this.passage.push(frame);
if (this.passage.length===20) {
if (this.align.unclearPassage(this.passage,i-19,anchor)) this.event(3,i-19,20,0,anchor.phase);
this.passage=[];
}
const expected=this.align.expected(i,anchor.phase);
const quietest=Math.min(expected,this.align.expected(i-1,anchor.phase),this.align.expected(i+1,anchor.phase));
const attenuated=expected>this.align.peak-20 && frame[0]<quietest+anchor.gain-18;
if (attenuated) {
this.loss??={start:i,last:i,active:0,phase:anchor.phase};
this.loss.last=i; this.loss.active++;
} else if (this.loss && (i-this.loss.last>3 || frame[0]>expected+anchor.gain-8)) this.flushLoss();
}
}
cadence(anchor) {
if (!this.rateBase) { this.rateBase={...anchor,end:this.end}; return; }
const ticks=this.end-this.rateBase.end;
if (ticks<500) return;
const ppm=Math.round(1e6*phaseDelta(anchor.phase,this.rateBase.phase,this.align.length)/ticks);
if (Math.abs(ppm)>=4000 && Math.sign(ppm)===Math.sign(this.previousRate) && Math.abs(this.previousRate)>=4000) {
this.firstRate??=10*this.rateBase.end;
this.event(4,this.rateBase.end,ticks,ppm,this.rateBase.phase);
}
if (Math.abs(ppm)>Math.abs(this.maxRate)) this.maxRate=ppm;
this.previousRate=ppm; this.rateBase={...anchor,end:this.end};
}
observe(batch, endMs, complete) {
this.frames.push(...batch); this.end+=batch.length;
const anchor=this.align.match(this.frames,this.end);
if (batch.some(row=>!row[2])) this.discontinuities++;
const previous=this.candidate;
const stable=anchor && previous && this.end-previous.end<=50 &&
Math.abs(phaseDelta(anchor.phase,previous.phase,this.align.length))<=2;
if (stable) {
const shift=this.anchor ? phaseDelta(anchor.phase,this.anchor.phase,this.align.length) : 0;
const fresh=this.anchor && this.end-this.anchor.end<=275;
if (!this.anchor && this.scored<this.end-150) this.score(this.end-150,null);
if (Math.abs(shift)>=4 && fresh) {
this.flushLoss(); this.firstShift??=10*this.scored;
if (Math.abs(10*shift)>Math.abs(this.shift)) this.shift=-10*shift;
this.event(2,this.scored,this.end-this.scored,-10*shift,this.anchor.phase);
this.rateBase=null; this.previousRate=0;
this.score(this.end,null);
} else {
this.score(this.end,anchor);
this.cadence(anchor);
}
this.anchor={...anchor,end:this.end}; this.known=true;
} else if (this.end-this.scored>275) this.score(this.end-150,null);
if (anchor) this.candidate={...anchor,end:this.end};
if (complete) {
this.score(this.end,null); this.flushLoss();
if (this.unknownStart!=null && this.end-this.unknownStart>=10) {
this.event(3,this.unknownStart,this.end-this.unknownStart); this.unknownStart=null;
}
}
if (this.frames.length>300) this.frames.splice(0,this.frames.length-300);
const drift=this.anchor ? (this.anchor.phase+this.end)%this.align.length : -1;
return {locked:this.known, complete, observedMs:10*this.end, windows:this.end, scoredEndMs:endMs,
stageMinutes:this.minutes,firstLevelDropMs:this.firstDrop,longestLevelDropMs:this.maxDrop,
firstUnclearMs:this.firstUnknown,gapMaxMs:this.maxUnknown,discontinuities:this.discontinuities,
timing:{rateCoverageMs:0,edgeCount:0,maxRatePpm:0,firstRateMs:null,maxShiftMs:this.shift,
firstShiftMs:this.firstShift,baselinePpm:null},
speech:{coverageMs:10*this.trusted,phase:drift,phaseAgeMs:this.anchor?10*(this.end-this.anchor.end):-1,
total:this.count,events:this.events.slice(),firstRateMs:this.firstRate,maxCadencePpm:this.maxRate}};
}
}

View File

@ -0,0 +1,45 @@
// A 10 ms speech-band level and a high-frequency level. The worklet sends
// these features to the page. Raw input never leaves the worklet on this port.
export class SpeechEnvelope {
constructor(rate, emit) {
this.rate = rate;
this.emit = emit;
this.lowCoeff = 1 - Math.exp(-2 * Math.PI * 150 / rate);
this.highCoeff = 1 - Math.exp(-2 * Math.PI * 1600 / rate);
this.low = this.high = this.energy = this.highEnergy = 0;
this.frames = this.count = 0;
this.next = Math.round(rate / 100);
this.bin = 0;
this.present = true;
}
push(samples, length) {
for (let i = 0; i < length; i++) {
const x = samples?.[i] ?? 0;
this.present &&= i < (samples?.length ?? 0);
this.low += this.lowCoeff * (x - this.low);
this.high += this.highCoeff * (x - this.high);
this.energy += (x - this.low) ** 2;
this.highEnergy += (x - this.high) ** 2;
this.count++;
if (++this.frames < this.next) continue;
const db = e => 10 * Math.log10(Math.max(1e-10, e / this.count));
this.emit(db(this.energy), db(this.highEnergy), this.present);
this.energy = this.highEnergy = this.count = 0;
this.present = true;
this.next = Math.round((++this.bin + 1) * this.rate / 100);
}
}
}
export async function speechBuffer(context) {
const response = await fetch('speech-reference.flac');
if (!response.ok) throw Error('Speech reference unavailable');
return context.decodeAudioData(await response.arrayBuffer());
}
export function referenceFeatures(samples, rate) {
const levels = [], highs = [];
const envelope = new SpeechEnvelope(rate, (level, high) => { levels.push(level); highs.push(high); });
envelope.push(samples, samples.length);
return {levels, highs};
}

View File

@ -0,0 +1,79 @@
import {speechBuffer, referenceFeatures} from './speech-envelope.js';
import {SpeechDetector} from './speech-detector.js';
import {LocalRecording} from './local-recording.js';
const el=id=>document.getElementById(id);
let replayUrl=null, replayGeneration=0;
function resetReplay() {
el('hear-finding').hidden=true; el('hear-finding').onclick=null;
el('speech-replay').hidden=true;
el('speech-replay').removeAttribute('src');
el('speech-replay').load();
if (replayUrl) URL.revokeObjectURL(replayUrl);
replayUrl=null;
}
const time=ms=>(ms/1000).toFixed(2)+' s';
export async function attachSpeech(run, isCurrent, finish) {
const serial=++replayGeneration;
resetReplay();
el('record-status').textContent='';
await run.context.audioWorklet.addModule('speech-worklet.js');
const buffer=await speechBuffer(run.context);
if (!isCurrent()) return;
const detector=new SpeechDetector(referenceFeatures(buffer.getChannelData(0),buffer.sampleRate),run.stage.minutes);
const node=new AudioWorkletNode(run.context,'speech-probe',{processorOptions:{minutes:run.stage.minutes}});
run.detector=node; run.pathInterruptions=0;
el('path-state').textContent='Listening for the spoken phrase';
el('path-detail').hidden=false;
el('path-timing').hidden=true;
if (el('keep-speech').checked) {
run.recording=new LocalRecording({audioOnly:true,maxMs:(run.stage.minutes+1)*60000,maxBytes:32*1024*1024,
onStatus:text=>{if(serial===replayGeneration) el('record-status').textContent=text;},
onReady:blob=>{
if(serial!==replayGeneration) return;
replayUrl=URL.createObjectURL(blob);
const player=el('speech-replay');
player.src=replayUrl; player.hidden=false;
if (Number.isFinite(run.firstFindingMs)) {
el('hear-finding').hidden=false;
el('hear-finding').onclick=()=>{
player.currentTime=Math.max(0,(run.pathStart-run.clipStart+run.firstFindingMs)/1000-1.5);
void player.play().catch(()=>{});
};
}
}});
run.clipStart=performance.now();
run.recording.start(run.stream);
}
node.onprocessorerror=()=>{if(isCurrent()) finish('speech detector failed');};
node.port.onmessage=({data})=>{
if (!isCurrent()) return;
if (data.expired) {finish('lost speech observer');return;}
node.port.postMessage('ack');
const path=detector.observe(data.batch,data.endMs,data.complete);
const now=performance.now();
const observedAtMono=now-Math.max(0,1000*run.context.currentTime-data.endMs);
run.pathStart??=observedAtMono-path.observedMs;
if(Math.abs(observedAtMono-run.pathStart-path.observedMs)>2000) run.clockGap=true;
path.discontinuities+=run.pathInterruptions+Number(!!run.clockGap);
run.path={...path,observedAtMono};
const s=path.speech;
const first=s.events[0]?.[2];
if (Number.isFinite(first)) run.firstFindingMs=Math.min(run.firstFindingMs??Infinity,first);
const clock=Math.floor(path.observedMs/60000)+':'+String(Math.floor(path.observedMs/1000)%60).padStart(2,'0');
let finding='';
if (path.firstLevelDropMs!==null) finding='Speech attenuation at '+time(path.firstLevelDropMs)+' · longest '+path.longestLevelDropMs+' ms';
else if (path.timing.firstShiftMs!==null) finding='Phrase timing shifted near '+time(path.timing.firstShiftMs);
else if (s.firstRateMs!==null) finding='Speech cadence changed near '+time(s.firstRateMs);
else if (path.discontinuities) finding='Capture interrupted';
else if (path.firstUnclearMs!==null || (data.complete && s.coverageMs<path.observedMs))
finding='Part of the phrase could not be verified';
el('path-detail').textContent='Reference matched '+time(s.coverageMs)+' of '+time(path.observedMs)+
(s.total?' · '+s.total+' recorded observations':'');
el('path-state').textContent=(data.complete?(finding?'Stage held':'Stage complete'):
(finding?'Still measuring':path.locked?'Tracking speech':'Acquiring speech'))+' · '+clock+' / '+run.stage.minutes+':00'+
(finding?' · '+finding:'');
if (data.complete) finish(finding?'stage finding':'phone test complete');
};
run.source.connect(node); node.connect(run.context.destination);
}

View File

@ -0,0 +1,42 @@
import {SpeechEnvelope} from './speech-envelope.js';
class SpeechProbe extends AudioWorkletProcessor {
constructor({processorOptions:{minutes}}) {
super();
this.limit = 6000 * minutes;
this.ticks = 0;
this.batch = [];
this.lastAck = currentFrame;
this.previousEnd = null;
this.contiguous = true;
this.port.onmessage = ({data}) => {
if (data === 'stop') this.stopped = true;
if (data === 'ack') this.lastAck = currentFrame;
};
this.envelope = new SpeechEnvelope(sampleRate, (level, high, present) => {
if (this.ticks >= this.limit) return;
this.batch.push([level, high, present && this.contiguous]);
this.contiguous = true;
this.ticks++;
});
}
process(inputs, outputs) {
if (this.stopped) return false;
if (currentFrame - this.lastAck > 10 * sampleRate) {
this.port.postMessage({expired:true}); return false;
}
const count = outputs[0][0].length;
if (this.previousEnd !== null && this.previousEnd !== currentFrame) this.contiguous = false;
this.previousEnd = currentFrame + count;
const before = this.envelope.frames;
this.envelope.push(inputs[0]?.[0], count);
const complete = this.ticks === this.limit;
if (this.batch.length >= 25 || complete) {
const end = currentFrame + Math.round(this.ticks * sampleRate / 100) - before;
this.port.postMessage({batch:this.batch, endMs:end * 1000 / sampleRate, complete});
this.batch = [];
}
return !complete;
}
}
registerProcessor('speech-probe', SpeechProbe);