// 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];
}