bstein: RCT mic test keeps playable flagged and control clips; detector phase fix
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
parent
d2f4e920ff
commit
f11813cb7b
@ -5,7 +5,10 @@ const query = new URLSearchParams(location.search);
|
|||||||
// test=digital: direct duration, no staging/unlock, for a digitally injected reference.
|
// test=digital: direct duration, no staging/unlock, for a digitally injected reference.
|
||||||
export const digitalTest = query.get('test') === 'digital';
|
export const digitalTest = query.get('test') === 'digital';
|
||||||
export const phoneTest = query.get('test') === 'phone' || digitalTest;
|
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;
|
const MINUTES = digitalTest ? DIGITAL_MINUTES : STAGE_MINUTES;
|
||||||
export const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
|
export const speechMode = new URLSearchParams(location.search).get('signal') !== 'tones';
|
||||||
const status = document.getElementById('path-state');
|
const status = document.getElementById('path-state');
|
||||||
|
|||||||
184
services/bstein-dev-home/av-observer/clip-store.js
Normal file
184
services/bstein-dev-home/av-observer/clip-store.js
Normal file
@ -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<frame && f<this.head+this.size; f++) this.data[f%this.size]=NaN;
|
||||||
|
}
|
||||||
|
if (this.head!==null && frame<this.head) { const skip=this.head-frame; if (skip>=count) return; frame+=skip; samples=samples.subarray(skip,count); count-=skip; }
|
||||||
|
for (let k=0;k<count;k++) this.data[(frame+k)%this.size]=samples[k];
|
||||||
|
this.head=frame+count;
|
||||||
|
}
|
||||||
|
available(from) { return this.head!==null && from>=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; f<to; f++) {
|
||||||
|
const x=Math.max(-1,Math.min(1,this.data[f%this.size] || 0));
|
||||||
|
out[f-from]=Math.round(x*32767);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
gapIn(from, to) {
|
||||||
|
if (!this.available(from) || to>this.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]<toMs && e[2]+Math.max(e[3],10)>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<p.to && this.ring.available(from)) continue;
|
||||||
|
const pcm=this.ring.read(from,p.to);
|
||||||
|
this.drop(p);
|
||||||
|
if (!pcm) { this.lost++; continue; }
|
||||||
|
const clip={id:++this.serial,type:p.type,kind:p.kind,startMs:p.fromMs+(from-p.from)*1000/this.rate,endMs:p.toMs,
|
||||||
|
eventMs:p.event?.[2]??null,phaseMs:p.phaseMs,event:p.event,tapGap:this.ring.gapIn(from,p.to),
|
||||||
|
rate:this.rate,pcm,meta:p.meta};
|
||||||
|
this.clips.push(clip); this.bytes+=pcm.byteLength; changed=true;
|
||||||
|
this.trim();
|
||||||
|
}
|
||||||
|
if (changed) this.onChange?.(this);
|
||||||
|
return changed;
|
||||||
|
}
|
||||||
|
drop(p) { const i=this.pending.indexOf(p); if (i>=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<s.length;i++) out[o+i]=s.charCodeAt(i); };
|
||||||
|
text(0,'RIFF'); v.setUint32(4,36+pcm.byteLength,true); text(8,'WAVE'); text(12,'fmt ');
|
||||||
|
v.setUint32(16,16,true); v.setUint16(20,1,true); v.setUint16(22,1,true); v.setUint32(24,rate,true);
|
||||||
|
v.setUint32(28,rate*2,true); v.setUint16(32,2,true); v.setUint16(34,16,true); text(36,'data');
|
||||||
|
v.setUint32(40,pcm.byteLength,true);
|
||||||
|
for (let i=0;i<pcm.length;i++) v.setInt16(44+2*i,pcm[i],true);
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
let crcTable=null;
|
||||||
|
function crc32(bytes) {
|
||||||
|
crcTable??=Uint32Array.from({length:256},(_,n)=>{ 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<bytes.length;i++) c=crcTable[(c^bytes[i])&0xFF]^(c>>>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];
|
||||||
|
}
|
||||||
85
services/bstein-dev-home/av-observer/clip-view.js
Normal file
85
services/bstein-dev-home/av-observer/clip-view.js
Normal file
@ -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();
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
44
services/bstein-dev-home/av-observer/clip-worklet.js
Normal file
44
services/bstein-dev-home/av-observer/clip-worklet.js
Normal file
@ -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);
|
||||||
@ -11,6 +11,9 @@ configMapGenerator:
|
|||||||
- name: lesavka-av-observer-assets
|
- name: lesavka-av-observer-assets
|
||||||
files:
|
files:
|
||||||
- mic-entry.js
|
- mic-entry.js
|
||||||
|
- clip-store.js
|
||||||
|
- clip-view.js
|
||||||
|
- clip-worklet.js
|
||||||
- mic-watch.js
|
- mic-watch.js
|
||||||
- watch-worklet.js
|
- watch-worklet.js
|
||||||
- speech-reference.flac
|
- speech-reference.flac
|
||||||
|
|||||||
@ -50,6 +50,7 @@ function stopOutput(reason='operator') {
|
|||||||
}
|
}
|
||||||
function release(run) {
|
function release(run) {
|
||||||
run.recording?.finish();
|
run.recording?.finish();
|
||||||
|
try{run.clips?.stop();}catch{}
|
||||||
stopTracks(run.stream);clearTimeout(run.setupTimer);clearTimeout(run.deadline);clearInterval(run.timer);
|
stopTracks(run.stream);clearTimeout(run.setupTimer);clearTimeout(run.deadline);clearInterval(run.timer);
|
||||||
if(run.detector){run.detector.port.onmessage=null;run.detector.onprocessorerror=null;
|
if(run.detector){run.detector.port.onmessage=null;run.detector.onprocessorerror=null;
|
||||||
run.detector.port.postMessage('stop');run.detector.disconnect();}
|
run.detector.port.postMessage('stop');run.detector.disconnect();}
|
||||||
|
|||||||
@ -30,7 +30,7 @@ export class AudioReports {
|
|||||||
this.last=this.snapshot(now,audio,settings,'observing');this.reporter.observe(this.last);
|
this.last=this.snapshot(now,audio,settings,'observing');this.reporter.observe(this.last);
|
||||||
}
|
}
|
||||||
remember() {
|
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) {
|
finish(now,audio,settings,reason) {
|
||||||
if(!this.reporter)return;
|
if(!this.reporter)return;
|
||||||
|
|||||||
@ -16,6 +16,8 @@
|
|||||||
<button id="save" disabled>Save metrics</button></div>
|
<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>
|
<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>
|
<span id="record-status"></span><audio controls id="speech-replay" hidden></audio> <button id="hear-finding" hidden>Replay first finding</button></div>
|
||||||
|
<p id="clips-status" role="status"></p>
|
||||||
|
<div id="clips" hidden><button id="clips-all" disabled title="ZIP: WAV clips + index.json">Download all</button> <span id="clips-count"></span><ol id="clip-list"></ol></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="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>
|
<p id="output-report">Output reporting idle</p>
|
||||||
<meter id="level" min="0" max="1" value="0" title="Current microphone peak"></meter>
|
<meter id="level" min="0" max="1" value="0" title="Current microphone peak"></meter>
|
||||||
|
|||||||
@ -43,32 +43,32 @@ export function stopState(reason) {
|
|||||||
// Only fixed, bounded integers supplement an authenticated acoustic receipt.
|
// Only fixed, bounded integers supplement an authenticated acoustic receipt.
|
||||||
// First-event offsets use offset+1, reserving zero for no event.
|
// First-event offsets use offset+1, reserving zero for no event.
|
||||||
export function acousticReceipt(path, clock) {
|
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 offset = value => value === null ? 0 : Math.round(value) + 1;
|
||||||
const timing = [path.stageMinutes,Math.round(path.observedMs),offset(path.firstLevelDropMs),
|
const timing = [path.stageMinutes,Math.round(path.observedMs),offset(path.firstLevelDropMs),
|
||||||
Math.round(path.longestLevelDropMs),offset(path.firstUnclearMs),Math.round(path.gapMaxMs),
|
Math.round(path.longestLevelDropMs),offset(path.firstUnclearMs),Math.round(path.gapMaxMs),
|
||||||
path.discontinuities];
|
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 end = clock && Number.isFinite(path.observedAtMono) ? Math.round(path.observedAtMono + clock.offset) : 0;
|
||||||
const t=path.timing;
|
const t=path.timing;
|
||||||
if (!t) return null;
|
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];
|
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(',');
|
return [...timing,end,clock?.uncertainty ?? 0,...warp].join(',');
|
||||||
}
|
}
|
||||||
|
|
||||||
export function speechReceipt(speech) {
|
export function speechReceipt(speech) {
|
||||||
if (!speech) return null;
|
if (!speech) return null;
|
||||||
const integer = (v,min,max) => Number.isSafeInteger(v) && v>=min && v<=max;
|
const integer = (v,min,max) => Number.isSafeInteger(v) && v>=min && v<=max;
|
||||||
if (!integer(speech.coverageMs,0,3600000) || !integer(speech.phase,-1,9999) ||
|
if (!integer(speech.coverageMs,0,7200000) || !integer(speech.phase,-1,9999) ||
|
||||||
!integer(speech.phaseAgeMs,-1,3600000) || !integer(speech.total,0,999999) ||
|
!integer(speech.phaseAgeMs,-1,7200000) || !integer(speech.total,0,999999) ||
|
||||||
!integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) ||
|
!integer(speech.maxCadencePpm,-1000000,1000000) || !Array.isArray(speech.events) ||
|
||||||
speech.events.length>16) return null;
|
speech.events.length>16) return null;
|
||||||
const rows=[[speech.kind===2?2:1,speech.coverageMs,speech.phase,speech.phaseAgeMs,speech.total,speech.maxCadencePpm]];
|
const rows=[[speech.kind===2?2:1,speech.coverageMs,speech.phase,speech.phaseAgeMs,speech.total,speech.maxCadencePpm]];
|
||||||
for (const row of speech.events) {
|
for (const row of speech.events) {
|
||||||
if (!Array.isArray(row) || row.length!==6 || !integer(row[0],1,speech.total) ||
|
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[1],1,4) || !integer(row[2],0,7200000) ||
|
||||||
!integer(row[3],0,3600000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null;
|
!integer(row[3],0,7200000-row[2]) || !integer(row[4],-1000000,1000000) || !integer(row[5],-1,9999)) return null;
|
||||||
rows.push(row);
|
rows.push(row);
|
||||||
}
|
}
|
||||||
return rows.map(row=>row.join(',')).join(';');
|
return rows.map(row=>row.join(',')).join(';');
|
||||||
|
|||||||
@ -18,6 +18,12 @@ export class SpeechAlignment {
|
|||||||
this.length = levels.length;
|
this.length = levels.length;
|
||||||
this.bands = [levels, highs];
|
this.bands = [levels, highs];
|
||||||
this.peak = Math.max(...levels);
|
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 =>
|
this.patterns = levels.map((_, phase) => this.bands.map(band =>
|
||||||
normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length]))));
|
normalized(Array.from({length:LOOKBACK}, (_,i)=>band[(phase+i)%this.length]))));
|
||||||
}
|
}
|
||||||
@ -63,4 +69,10 @@ export class SpeechAlignment {
|
|||||||
return best<0.38;
|
return best<0.38;
|
||||||
}
|
}
|
||||||
expected(index,phase) { return this.bands[0][wrap(index+phase,this.length)]; }
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@ -10,6 +10,17 @@ export class SpeechDetector {
|
|||||||
this.events=[]; this.maxDrop=this.maxUnknown=this.shift=this.maxRate=0;
|
this.events=[]; this.maxDrop=this.maxUnknown=this.shift=this.maxRate=0;
|
||||||
this.firstDrop=this.firstUnknown=this.firstShift=this.firstRate=null;
|
this.firstDrop=this.firstUnknown=this.firstShift=this.firstRate=null;
|
||||||
this.discontinuities=0; this.known=false; this.passage=[];
|
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) {
|
event(kind, start, duration, value=0, phase=null) {
|
||||||
const position=phase===null?-1:(start+phase)%this.align.length;
|
const position=phase===null?-1:(start+phase)%this.align.length;
|
||||||
@ -42,8 +53,14 @@ export class SpeechDetector {
|
|||||||
this.passage=[];
|
this.passage=[];
|
||||||
}
|
}
|
||||||
const expected=this.align.expected(i,anchor.phase);
|
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 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;
|
// Judged against the reference at this phase: 18 dB under it counts only
|
||||||
|
// when the received level also fell to the path floor (a gap, not a
|
||||||
|
// quieter rendition); 30 dB under the reference always counts.
|
||||||
|
const floor=this.floor(), deep=quietest+anchor.gain-30;
|
||||||
|
const attenuated=this.align.voiced(i,anchor.phase) && frame[0]<quietest+anchor.gain-18 &&
|
||||||
|
(frame[0]<deep || (floor!==null && frame[0]<floor+15));
|
||||||
if (attenuated) {
|
if (attenuated) {
|
||||||
this.loss??={start:i,last:i,active:0,phase:anchor.phase};
|
this.loss??={start:i,last:i,active:0,phase:anchor.phase};
|
||||||
this.loss.last=i; this.loss.active++;
|
this.loss.last=i; this.loss.active++;
|
||||||
|
|||||||
@ -1,6 +1,7 @@
|
|||||||
import {speechBuffer, referenceFeatures} from './speech-envelope.js';
|
import {speechBuffer, referenceFeatures} from './speech-envelope.js';
|
||||||
import {SpeechDetector} from './speech-detector.js';
|
import {SpeechDetector} from './speech-detector.js';
|
||||||
import {LocalRecording} from './local-recording.js';
|
import {LocalRecording} from './local-recording.js';
|
||||||
|
import {attachClips} from './clip-view.js';
|
||||||
|
|
||||||
const el=id=>document.getElementById(id);
|
const el=id=>document.getElementById(id);
|
||||||
const digital=new URLSearchParams(location.search).get('test')==='digital';
|
const digital=new URLSearchParams(location.search).get('test')==='digital';
|
||||||
@ -18,10 +19,17 @@ export async function attachSpeech(run, isCurrent, finish) {
|
|||||||
const serial=++replayGeneration;
|
const serial=++replayGeneration;
|
||||||
resetReplay();
|
resetReplay();
|
||||||
el('record-status').textContent='';
|
el('record-status').textContent='';
|
||||||
|
el('clips-status').textContent='';
|
||||||
await run.context.audioWorklet.addModule('speech-worklet.js');
|
await run.context.audioWorklet.addModule('speech-worklet.js');
|
||||||
const buffer=await speechBuffer(run.context);
|
const buffer=await speechBuffer(run.context);
|
||||||
if (!isCurrent()) return;
|
if (!isCurrent()) return;
|
||||||
const detector=new SpeechDetector(referenceFeatures(buffer.getChannelData(0),buffer.sampleRate),run.stage.minutes);
|
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}});
|
const node=new AudioWorkletNode(run.context,'speech-probe',{processorOptions:{minutes:run.stage.minutes}});
|
||||||
run.detector=node; run.pathInterruptions=0;
|
run.detector=node; run.pathInterruptions=0;
|
||||||
el('path-state').textContent='Listening for the spoken phrase';
|
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;
|
if(Math.abs(observedAtMono-run.pathStart-path.observedMs)>2000) run.clockGap=true;
|
||||||
path.discontinuities+=run.pathInterruptions+Number(!!run.clockGap);
|
path.discontinuities+=run.pathInterruptions+Number(!!run.clockGap);
|
||||||
run.path={...path,observedAtMono};
|
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.
|
// Receipt kind 2 marks a digitally injected source; 1 is the phone/acoustic source.
|
||||||
if (digital) run.path.speech={...path.speech,kind:2};
|
if (digital) run.path.speech={...path.speech,kind:2};
|
||||||
const s=path.speech;
|
const s=path.speech;
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user