// 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);