diff --git a/services/bstein-dev-home/av-observer/acoustic-watch.js b/services/bstein-dev-home/av-observer/acoustic-watch.js index b763918f..bd4ab65d 100644 --- a/services/bstein-dev-home/av-observer/acoustic-watch.js +++ b/services/bstein-dev-home/av-observer/acoustic-watch.js @@ -5,7 +5,10 @@ const query = new URLSearchParams(location.search); // test=digital: direct duration, no staging/unlock, for a digitally injected reference. export const digitalTest = query.get('test') === 'digital'; export const phoneTest = query.get('test') === 'phone' || digitalTest; -const DIGITAL_MINUTES = [1, 5, 10, 15, 20, 30, 60]; +// Any whole number of minutes up to 120 may be requested with ?minutes=N. +const asked = Number(query.get('minutes')); +const DIGITAL_MINUTES = [...new Set([1, 5, 10, 15, 20, 30, 60, 90, 120, + ...(Number.isInteger(asked) && asked >= 1 && asked <= 120 ? [asked] : [])])].sort((a, b) => a - b); const MINUTES = digitalTest ? DIGITAL_MINUTES : STAGE_MINUTES; export const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones'; const status = document.getElementById('path-state'); diff --git a/services/bstein-dev-home/av-observer/clip-store.js b/services/bstein-dev-home/av-observer/clip-store.js new file mode 100644 index 00000000..743e4ab3 --- /dev/null +++ b/services/bstein-dev-home/av-observer/clip-store.js @@ -0,0 +1,184 @@ +// Digital mode only: local listening clips around detector events, plus clean +// controls. Audio stays in this page; nothing here is sent anywhere. +// Time base: absolute AudioContext frames (the tap and the speech probe share it). + +export const KIND = ['control','attenuation','timing step','unclear','cadence']; + +/** Fixed-size mono ring indexed by absolute context frame. */ +export class ClipRing { + constructor(rate, seconds=30) { + this.rate=rate; this.size=Math.ceil(rate*seconds); this.data=new Float32Array(this.size); + this.head=null; this.firstFrame=null; + } + write(frame, samples, count=samples.length) { + this.firstFrame??=frame; + if (this.head!==null && frame>this.head) { + // NaN marks missing samples for as long as they remain in the ring. + for (let f=this.head; f=count) return; frame+=skip; samples=samples.subarray(skip,count); count-=skip; } + for (let k=0;k=Math.max(this.firstFrame,this.head-this.size); } + /** 16-bit copy of [from,to), or null when that span has been overwritten. */ + read(from, to) { + if (!this.available(from) || to>this.head || to<=from) return null; + const out=new Int16Array(to-from); + for (let f=from; fthis.head) return true; + const start=from%this.size, end=start+to-from; + return this.data.subarray(start,end).includes(NaN) || + (end>this.size && this.data.subarray(0,end-this.size).includes(NaN)); + } +} + +/** + * A detector window is clean when every scored frame in it was trusted + * (history: [{scoredMs,trustedMs}] snapshots) and no event overlaps it. + */ +export function cleanWindow(history, events, fromMs, toMs, pending=false) { + if (pending || fromMs<0) return false; + const before=history.findLast?.(h=>h.scoredMs<=fromMs) ?? [...history].reverse().find(h=>h.scoredMs<=fromMs); + const after=history.find(h=>h.scoredMs>=toMs); + if (!before || !after) return false; + if (after.trustedMs-before.trustedMs < after.scoredMs-before.scoredMs) return false; + return !events.some(e=>e[2]fromMs); +} + +export class ClipStore { + constructor({rate, maxClips=60, maxBytes=48*1024*1024, preMs=3000, postMs=3000, maxClipMs=12000, + firstControlMs=30000, controlEveryMs=300000, ringSeconds=30}={}) { + Object.assign(this,{rate,maxClips,maxBytes,preMs,postMs,maxClipMs,firstControlMs,controlEveryMs}); + this.ring=new ClipRing(rate,ringSeconds); + this.clips=[]; this.pending=[]; this.bytes=0; this.serial=0; this.lost=0; + this.nextControlMs=firstControlMs; this.seenEvent=0; this.onChange=null; + this.origin=null; this.history=[]; this.recent=[]; + } + /** + * One speech-probe batch: path from SpeechDetector.observe, endMs the probe's + * context time for it. Queues event clips and, when due and clean, a control. + * Returns true when something waits for audio. + */ + observe(path, endMs, detector, controlMs=6000, settleMs=300) { + this.origin??=endMs-path.observedMs; + const meta={gainDb:detector.anchor?+detector.anchor.gain.toFixed(1):null, + matchedMs:path.speech.coverageMs,observedMs:path.observedMs}; + for (const row of path.speech.events) { + if (this.event(row,this.origin,meta)) { this.recent.push(row); if (this.recent.length>64) this.recent.shift(); } + } + const scoredMs=10*detector.scored; + this.history.push({scoredMs,trustedMs:10*detector.trusted}); if (this.history.length>96) this.history.shift(); + if (path.locked && detector.anchor && this.controlDue(scoredMs)) { + const to=scoredMs-settleMs, from=to-controlMs; + if (cleanWindow(this.history,this.recent,from,to,!!detector.loss || detector.unknownStart!=null)) { + const L=detector.align.length, position=((Math.round(from/10)+detector.anchor.phase)%L+L)%L; + this.control(from,to,this.origin,{...meta,phaseMs:10*position}); + } + } + return this.pending.length>0; + } + frameOf(originMs, ms) { return Math.round((originMs+ms)*this.rate/1000); } + /** Detector event row [serial,kind,startMs,durationMs,value,position]. */ + event(row, originMs, meta={}) { + if (row[0]<=this.seenEvent) return false; + this.seenEvent=row[0]; + const fromMs=row[2]-this.preMs, toMs=Math.min(row[2]+row[3]+this.postMs, fromMs+this.maxClipMs); + this.queue({type:KIND[row[1]]??'event',kind:row[1],event:row.slice(),fromMs,toMs, + phaseMs:row[5]>=0?row[5]*10:null,from:this.frameOf(originMs,fromMs),to:this.frameOf(originMs,toMs),meta}); + return true; + } + controlDue(scoredMs) { return scoredMs>=this.nextControlMs; } + control(fromMs, toMs, originMs, meta={}) { + this.nextControlMs=toMs+this.controlEveryMs; + this.queue({type:'control',kind:0,event:null,fromMs,toMs,phaseMs:meta.phaseMs??null, + from:this.frameOf(originMs,fromMs),to:this.frameOf(originMs,toMs),meta}); + } + queue(clip) { + this.pending.push(clip); + if (this.pending.length>32) { this.pending.shift(); this.lost++; } + } + /** Copy any pending clip whose span is now in the ring. Call off the audio thread. */ + collect() { + let changed=false; + for (const p of this.pending.slice()) { + if (this.ring.head===null) continue; + const from=Math.max(this.ring.firstFrame,p.from); + if (this.ring.head=0) this.pending.splice(i,1); } + trim() { + while (this.clips.length>this.maxClips || this.bytes>this.maxBytes) { + let i=this.clips.findIndex(c=>c.type!=='control'); + if (i<0) i=0; + this.bytes-=this.clips[i].pcm.byteLength; this.clips.splice(i,1); this.lost++; + } + } + index() { + return {schema:'rct-clips.v1',sampleRate:this.rate,preMs:this.preMs,postMs:this.postMs,dropped:this.lost, + clips:this.clips.map(c=>({file:clipName(c),id:c.id,type:c.type,runStartMs:c.startMs,runEndMs:c.endMs, + eventMs:c.eventMs,loopPhaseMs:c.phaseMs,tapGap:c.tapGap, + detector:c.event?{serial:c.event[0],kind:c.event[1],startMs:c.event[2],durationMs:c.event[3],value:c.event[4], + referencePosition:c.event[5]}:null,...c.meta}))}; + } +} + +export const clock=ms=>{ const s=Math.max(0,Math.floor(ms/1000)); return Math.floor(s/60)+':'+String(s%60).padStart(2,'0'); }; +export const clipName=c=>String(c.id).padStart(3,'0')+'-'+c.type.replace(/\s+/g,'-')+'-'+clock(c.eventMs??c.startMs).replace(':','m')+'s.wav'; + +export function wav(pcm, rate) { + const out=new Uint8Array(44+pcm.byteLength), v=new DataView(out.buffer); + const text=(o,s)=>{ for (let i=0;i{ let c=n; for (let k=0;k<8;k++) c=c&1?0xEDB88320^(c>>>1):c>>>1; return c>>>0; }); + let c=0xFFFFFFFF; + for (let i=0;i>>8); + return (c^0xFFFFFFFF)>>>0; +} +/** Uncompressed ZIP of [{name, data:Uint8Array}] as Blob parts. */ +export function zip(files) { + const parts=[], central=[]; let offset=0; + const enc=new TextEncoder(); + for (const {name,data} of files) { + const n=enc.encode(name), crc=crc32(data), h=new Uint8Array(30+n.length), v=new DataView(h.buffer); + v.setUint32(0,0x04034b50,true); v.setUint16(4,20,true); v.setUint16(8,0,true); + v.setUint16(10,0,true); v.setUint16(12,0x21,true); + v.setUint32(14,crc,true); v.setUint32(18,data.length,true); v.setUint32(22,data.length,true); + v.setUint16(26,n.length,true); h.set(n,30); + const c=new Uint8Array(46+n.length), w=new DataView(c.buffer); + w.setUint32(0,0x02014b50,true); w.setUint16(4,20,true); w.setUint16(6,20,true); + w.setUint16(14,0x21,true); w.setUint32(16,crc,true); w.setUint32(20,data.length,true); + w.setUint32(24,data.length,true); w.setUint16(28,n.length,true); w.setUint32(42,offset,true); c.set(n,46); + parts.push(h,data); central.push(c); offset+=h.length+data.length; + } + const size=central.reduce((s,c)=>s+c.length,0), end=new Uint8Array(22), e=new DataView(end.buffer); + e.setUint32(0,0x06054b50,true); e.setUint16(8,files.length,true); e.setUint16(10,files.length,true); + e.setUint32(12,size,true); e.setUint32(16,offset,true); + return [...parts,...central,end]; +} diff --git a/services/bstein-dev-home/av-observer/clip-view.js b/services/bstein-dev-home/av-observer/clip-view.js new file mode 100644 index 00000000..5a972e9d --- /dev/null +++ b/services/bstein-dev-home/av-observer/clip-view.js @@ -0,0 +1,85 @@ +// ?test=digital only: listening clips kept in this page. Never uploaded; the +// numeric receipts are unchanged. Not loaded by the passive watch mode. +import {ClipStore, wav, zip, clipName, clock} from './clip-store.js'; + +const el=id=>document.getElementById(id); +let player=null, playerUrl=null; + +function save(blob, name) { + const url=URL.createObjectURL(blob), a=document.createElement('a'); + a.href=url; a.download=name; a.click(); setTimeout(()=>URL.revokeObjectURL(url),2000); +} +function resetPlayer() { + if (!playerUrl) return; + player.pause(); + player.removeAttribute('src'); + player.load(); + URL.revokeObjectURL(playerUrl); + playerUrl=null; +} +function play(clip) { + player??=new Audio(); + resetPlayer(); + playerUrl=URL.createObjectURL(new Blob([wav(clip.pcm,clip.rate)],{type:'audio/wav'})); + player.src=playerUrl; void player.play().catch(()=>{}); +} +const phaseText=ms=>ms===null?'':' @'+(ms/1000).toFixed(2)+' s'; +function render(store) { + const list=el('clip-list'); + list.replaceChildren(...store.clips.map(clip=>{ + const li=document.createElement('li'); + const label=document.createElement('span'); + label.textContent=clock(clip.eventMs??clip.startMs)+' '+clip.type+phaseText(clip.phaseMs)+(clip.tapGap?' · gap':''); + if (clip.event) label.title='kind '+clip.event[1]+' · '+clip.event[3]+' ms · value '+clip.event[4]; + const button=document.createElement('button'); + button.textContent='▶'; button.title='Play'; button.onclick=()=>play(clip); + const link=document.createElement('a'); + link.href='#'; link.textContent='WAV'; link.title=clipName(clip); + link.onclick=e=>{e.preventDefault(); save(new Blob([wav(clip.pcm,clip.rate)],{type:'audio/wav'}),clipName(clip));}; + li.append(label,' ',button,' ',link); + return li; + })); + el('clips-count').textContent=store.clips.length+' clips'+(store.lost?' · '+store.lost+' dropped':''); + el('clips-all').disabled=!store.clips.length; +} + +export async function attachClips(run, minutes, isCurrent) { + await run.context.audioWorklet.addModule(new URL('./clip-worklet.js',import.meta.url).href); + if (!isCurrent()) return; + const store=new ClipStore({rate:run.context.sampleRate}); + const tap=new AudioWorkletNode(run.context,'clip-tap'); + let collectQueued=false, stopped=false; + const collect=()=>{ if (collectQueued) return; collectQueued=true; + setTimeout(()=>{collectQueued=false; store.collect();},0); }; + tap.port.onmessage=({data})=>{ + store.ring.write(data.frame,data.samples); + tap.port.postMessage(data.samples,[data.samples.buffer]); + if (store.pending.length) collect(); + }; + run.source.connect(tap); tap.connect(run.context.destination); + resetPlayer(); + store.onChange=render; + el('clips').hidden=false; render(store); + el('clips-all').onclick=()=>{ + const index=store.index(); index.minutes=minutes; + const files=store.clips.map(c=>({name:clipName(c),data:wav(c.pcm,c.rate)})); + files.push({name:'index.json',data:new TextEncoder().encode(JSON.stringify(index,null,2))}); + save(new Blob(zip(files),{type:'application/zip'}),'rct-clips-'+new Date().toISOString().slice(0,19).replace(/:/g,'')+'.zip'); + }; + run.clips={ + store, + observe(path, data, detector) { if (store.observe(path,data.endMs,detector)) collect(); }, + stop() { + if (stopped) return; + stopped=true; + tap.port.onmessage=null; tap.port.postMessage('stop'); + try { run.source?.disconnect(tap); tap.disconnect(); } catch {} + // Keep what was captured: shorten pending post-roll to the last delivered frame. + for (const p of store.pending) if (store.ring.head!==null && p.to>store.ring.head) { + p.to=store.ring.head; p.toMs=p.fromMs+(p.to-p.from)*1000/store.rate; + } + store.pending=store.pending.filter(p=>p.to>p.from); + store.collect(); + }, + }; +} diff --git a/services/bstein-dev-home/av-observer/clip-worklet.js b/services/bstein-dev-home/av-observer/clip-worklet.js new file mode 100644 index 00000000..9e0a78dc --- /dev/null +++ b/services/bstein-dev-home/av-observer/clip-worklet.js @@ -0,0 +1,44 @@ +// Digital mode listening tap: copies channel 0 into preallocated blocks that +// are transferred to the page and returned for reuse. process() allocates +// nothing; when no block is free the samples are skipped and the page sees +// the frame gap. The page keeps clips locally; nothing is uploaded. +const BLOCK = 4096, POOL = 24; +class ClipTap extends AudioWorkletProcessor { + constructor() { + super(); + this.free = []; for (let i = 0; i < POOL; i++) this.free.push(new Float32Array(BLOCK)); + this.top = POOL; this.current = null; this.fill = 0; this.start = 0; + this.message = {frame:0, samples:null}; this.transfer = [null]; + this.stopped = false; + this.port.onmessage = ({data}) => { + if (data === 'stop') { this.stopped = true; return; } + if (data instanceof Float32Array && data.length === BLOCK && this.top < POOL) this.free[this.top++] = data; + }; + } + process(inputs) { + if (this.stopped) return false; + const input = inputs[0]?.[0]; + const length = input ? input.length : 128; + // A skipped render quantum restarts the block so frame stamps stay exact. + if (this.current && this.start + this.fill !== currentFrame) { this.fill = 0; this.start = currentFrame; } + let offset = 0; + while (offset < length) { + if (!this.current) { + if (this.top === 0) return true; // pool exhausted: skip, page sees a gap + this.current = this.free[--this.top]; this.free[this.top] = null; + this.fill = 0; this.start = currentFrame + offset; + } + const n = Math.min(BLOCK - this.fill, length - offset), block = this.current; + for (let k = 0; k < n; k++) block[this.fill + k] = input ? input[offset + k] : 0; + this.fill += n; offset += n; + if (this.fill === BLOCK) { + this.message.frame = this.start; this.message.samples = block; + this.transfer[0] = block.buffer; + this.port.postMessage(this.message, this.transfer); + this.message.samples = null; this.transfer[0] = null; this.current = null; + } + } + return true; + } +} +registerProcessor('clip-tap', ClipTap); diff --git a/services/bstein-dev-home/av-observer/kustomization.yaml b/services/bstein-dev-home/av-observer/kustomization.yaml index 4275ec53..2ba240db 100644 --- a/services/bstein-dev-home/av-observer/kustomization.yaml +++ b/services/bstein-dev-home/av-observer/kustomization.yaml @@ -11,6 +11,9 @@ configMapGenerator: - name: lesavka-av-observer-assets files: - mic-entry.js + - clip-store.js + - clip-view.js + - clip-worklet.js - mic-watch.js - watch-worklet.js - speech-reference.flac diff --git a/services/bstein-dev-home/av-observer/mic-observer.js b/services/bstein-dev-home/av-observer/mic-observer.js index 33c881c9..7b53bba0 100644 --- a/services/bstein-dev-home/av-observer/mic-observer.js +++ b/services/bstein-dev-home/av-observer/mic-observer.js @@ -50,6 +50,7 @@ function stopOutput(reason='operator') { } function release(run) { run.recording?.finish(); + try{run.clips?.stop();}catch{} 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();} diff --git a/services/bstein-dev-home/av-observer/mic-reporting.js b/services/bstein-dev-home/av-observer/mic-reporting.js index 68486237..dfbb0bf5 100644 --- a/services/bstein-dev-home/av-observer/mic-reporting.js +++ b/services/bstein-dev-home/av-observer/mic-reporting.js @@ -30,7 +30,7 @@ export class AudioReports { this.last=this.snapshot(now,audio,settings,'observing');this.reporter.observe(this.last); } remember() { - if(this.reporter?.runId&&this.ids.length<32&&!this.ids.includes(this.reporter.runId))this.ids.push(this.reporter.runId); + if(this.reporter?.runId&&this.ids.length<64&&!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 2b4106af..010dd7b5 100644 --- a/services/bstein-dev-home/av-observer/mic.html +++ b/services/bstein-dev-home/av-observer/mic.html @@ -16,6 +16,8 @@ +

+

Stopped

Mic reporting idle

Output stopped

Output reporting idle

diff --git a/services/bstein-dev-home/av-observer/reporting.js b/services/bstein-dev-home/av-observer/reporting.js index b340067e..aaa3a2a0 100644 --- a/services/bstein-dev-home/av-observer/reporting.js +++ b/services/bstein-dev-home/av-observer/reporting.js @@ -43,32 +43,32 @@ export function stopState(reason) { // 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,60].includes(path.stageMinutes)) return null; + if (!path || !Number.isInteger(path.stageMinutes) || path.stageMinutes<1 || path.stageMinutes>120) 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<=3600011)) return null; + if (!timing.every(v=>Number.isSafeInteger(v) && v>=0 && v<=7200011)) 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)<=3600011)) return null; + if (!warp.every(v=>Number.isSafeInteger(v) && Math.abs(v)<=7200011)) return null; 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,3600000) || !integer(speech.phase,-1,9999) || - !integer(speech.phaseAgeMs,-1,3600000) || !integer(speech.total,0,999999) || + if (!integer(speech.coverageMs,0,7200000) || !integer(speech.phase,-1,9999) || + !integer(speech.phaseAgeMs,-1,7200000) || !integer(speech.total,0,999999) || !integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) || speech.events.length>16) return null; const rows=[[speech.kind===2?2: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,3600000) || - !integer(row[3],0,3600000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null; + !integer(row[1],1,4) || !integer(row[2],0,7200000) || + !integer(row[3],0,7200000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null; rows.push(row); } return rows.map(row=>row.join(',')).join(';'); diff --git a/services/bstein-dev-home/av-observer/speech-alignment.js b/services/bstein-dev-home/av-observer/speech-alignment.js index a10b4fe7..81db4249 100644 --- a/services/bstein-dev-home/av-observer/speech-alignment.js +++ b/services/bstein-dev-home/av-observer/speech-alignment.js @@ -18,6 +18,12 @@ export class SpeechAlignment { this.length = levels.length; this.bands = [levels, highs]; this.peak = Math.max(...levels); + // Loudest reference level within +-150 ms of each phase: the passage a frame belongs to. + this.local = levels.map((_, p) => { + let m = -Infinity; + for (let k = -15; k <= 15; k++) m = Math.max(m, levels[wrap(p+k, this.length)]); + return m; + }); this.patterns = levels.map((_, phase) => this.bands.map(band => normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length])))); } @@ -63,4 +69,10 @@ export class SpeechAlignment { return best<0.38; } expected(index,phase) { return this.bands[0][wrap(index+phase,this.length)]; } + // A frame is scored for attenuation only where the reference itself is + // voiced and not a quiet stretch of its own passage (word tails, closures). + voiced(index,phase) { + const p = wrap(index+phase,this.length), level = this.bands[0][p]; + return level > this.peak-20 && level >= this.local[p]-12; + } } diff --git a/services/bstein-dev-home/av-observer/speech-detector.js b/services/bstein-dev-home/av-observer/speech-detector.js index ed178399..b7a0a6a5 100644 --- a/services/bstein-dev-home/av-observer/speech-detector.js +++ b/services/bstein-dev-home/av-observer/speech-detector.js @@ -10,6 +10,17 @@ export class SpeechDetector { 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=[]; + this.pauses=new Float64Array(128); this.pauseCount=0; this.floorLevel=null; + } + // Received level while the reference is in a pause: the path's own floor. + pause(level) { this.pauses[this.pauseCount++%128]=level; this.floorLevel=undefined; } + floor() { + if (this.pauseCount<16) return null; + if (this.floorLevel===undefined) { + const n=Math.min(128,this.pauseCount), sorted=this.pauses.slice(0,n).sort(); + this.floorLevel=sorted[n>>1]; + } + return this.floorLevel; } event(kind, start, duration, value=0, phase=null) { const position=phase===null?-1:(start+phase)%this.align.length; @@ -42,8 +53,14 @@ export class SpeechDetector { this.passage=[]; } const expected=this.align.expected(i,anchor.phase); + if (expected<=this.align.peak-40) this.pause(frame[0]); 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]document.getElementById(id); const digital=new URLSearchParams(location.search).get('test')==='digital'; @@ -18,10 +19,17 @@ export async function attachSpeech(run, isCurrent, finish) { const serial=++replayGeneration; resetReplay(); el('record-status').textContent=''; + el('clips-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); + // Local listening clips (digital mode only; never uploaded). A failure here leaves the detector untouched. + if (digital) { + try { await attachClips(run,run.stage.minutes,isCurrent); } + catch { if (isCurrent()) el('clips-status').textContent='Listening clips unavailable'; } + if (!isCurrent()) return; + } 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'; @@ -58,6 +66,12 @@ export async function attachSpeech(run, isCurrent, finish) { if(Math.abs(observedAtMono-run.pathStart-path.observedMs)>2000) run.clockGap=true; path.discontinuities+=run.pathInterruptions+Number(!!run.clockGap); run.path={...path,observedAtMono}; + try { run.clips?.observe(path,data,detector); } + catch { + run.clips.stop(); + run.clips=null; + el('clips-status').textContent='Listening clips stopped'; + } // Receipt kind 2 marks a digitally injected source; 1 is the phone/acoustic source. if (digital) run.path.speech={...path.speech,kind:2}; const s=path.speech;