| 1 | |
| 2 | |
| 3 | |
| 4 | export class PCMQueue { |
| 5 | constructor() { |
| 6 | this.capacity = 12000; |
| 7 | this.left = new Float32Array(this.capacity); |
| 8 | this.right = new Float32Array(this.capacity); |
| 9 | this.read = 0; |
| 10 | this.count = 0; |
| 11 | this.fraction = 0; |
| 12 | this.playing = false; |
| 13 | } |
| 14 | push(data) { |
| 15 | if (!(data instanceof ArrayBuffer) || data.byteLength % 4) return; |
| 16 | const view = new DataView(data); |
| 17 | const frames = view.byteLength / 4; |
| 18 | if (this.count + frames > this.capacity) { |
| 19 | |
| 20 | this.read = this.count = this.fraction = 0; |
| 21 | this.playing = false; |
| 22 | } |
| 23 | for (let i = Math.max(0, frames - this.capacity); i < frames; i++) { |
| 24 | const at = (this.read + this.count) % this.capacity; |
| 25 | this.left[at] = view.getInt16(i * 4, true) / 32768; |
| 26 | this.right[at] = view.getInt16(i * 4 + 2, true) / 32768; |
| 27 | this.count++; |
| 28 | } |
| 29 | } |
| 30 | render(left, right, outputRate) { |
| 31 | left.fill(0); |
| 32 | right.fill(0); |
| 33 | if (!this.playing && this.count >= 2880) this.playing = true; |
| 34 | if (!this.playing) return; |
| 35 | const step = 48000 / outputRate; |
| 36 | for (let i = 0; i < left.length; i++) { |
| 37 | if (this.count < Math.max(2, Math.ceil(this.fraction + step))) { |
| 38 | this.playing = false; |
| 39 | this.read = this.count = this.fraction = 0; |
| 40 | return; |
| 41 | } |
| 42 | const next = (this.read + 1) % this.capacity; |
| 43 | left[i] = this.left[this.read] + (this.left[next] - this.left[this.read]) * this.fraction; |
| 44 | right[i] = this.right[this.read] + (this.right[next] - this.right[this.read]) * this.fraction; |
| 45 | this.fraction += step; |
| 46 | const consumed = Math.floor(this.fraction); |
| 47 | this.fraction -= consumed; |
| 48 | this.read = (this.read + consumed) % this.capacity; |
| 49 | this.count -= consumed; |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | if (typeof globalThis.registerProcessor === "function") { |
| 55 | class CageAudioProcessor extends globalThis.AudioWorkletProcessor { |
| 56 | constructor() { |
| 57 | super(); |
| 58 | this.queue = new PCMQueue(); |
| 59 | this.port.onmessage = ({ data }) => { |
| 60 | if (data === "reset") this.queue = new PCMQueue(); |
| 61 | else this.queue.push(data); |
| 62 | }; |
| 63 | } |
| 64 | process(_inputs, outputs) { |
| 65 | const [left, right] = outputs[0]; |
| 66 | if (left && right) this.queue.render(left, right, globalThis.sampleRate); |
| 67 | return true; |
| 68 | } |
| 69 | } |
| 70 | globalThis.registerProcessor("cage-audio", CageAudioProcessor); |
| 71 | } |