| 1 | import assert from "node:assert/strict"; |
| 2 | import test from "node:test"; |
| 3 | import { PCMQueue } from "./audio-worklet.js"; |
| 4 | |
| 5 | function pcm(frames, value = i => [i, -i]) { |
| 6 | const data = new ArrayBuffer(frames * 4), view = new DataView(data); |
| 7 | for (let i = 0; i < frames; i++) { |
| 8 | const [left, right] = value(i); |
| 9 | view.setInt16(i * 4, left, true); |
| 10 | view.setInt16(i * 4 + 2, right, true); |
| 11 | } |
| 12 | return data; |
| 13 | } |
| 14 | test("PCM preserves signed stereo samples and silence before buffering", () => { |
| 15 | const q = new PCMQueue(), left = new Float32Array(128), right = new Float32Array(128); |
| 16 | q.push(pcm(960)); q.render(left, right, 48000); |
| 17 | assert.ok(left.every(v => v === 0)); |
| 18 | q.push(pcm(1920, () => [-32768, 32767])); |
| 19 | q.render(left, right, 48000); |
| 20 | assert.equal(left[40], 40 / 32768); |
| 21 | assert.equal(right[40], -40 / 32768); |
| 22 | for (let i = 0; i < 8; i++) q.render(left, right, 48000); |
| 23 | assert.equal(left[100], -1); |
| 24 | assert.equal(right[100], 32767 / 32768); |
| 25 | }); |
| 26 | test("PCM resamples to the host rate and returns silence on underrun", () => { |
| 27 | const q = new PCMQueue(), left = new Float32Array(441), right = new Float32Array(441); |
| 28 | q.push(pcm(4800)); q.render(left, right, 44100); |
| 29 | assert.ok(Math.abs(left[147] - 160 / 32768) < 1e-7); |
| 30 | assert.ok(Math.abs(right[294] + 320 / 32768) < 1e-7); |
| 31 | for (let i = 0; i < 12; i++) q.render(left, right, 44100); |
| 32 | assert.ok(left.every(v => v === 0)); |
| 33 | assert.ok(q.count < 2); |
| 34 | }); |
| 35 | test("late PCM is bounded and old audio is discarded", () => { |
| 36 | const q = new PCMQueue(), left = new Float32Array(128), right = new Float32Array(128); |
| 37 | q.push(pcm(11000, () => [100, 100])); |
| 38 | q.push(pcm(3000, () => [500, -500])); |
| 39 | assert.equal(q.count, 3000); |
| 40 | q.render(left, right, 48000); |
| 41 | assert.equal(left[0], 500 / 32768); |
| 42 | q.push(pcm(24000)); |
| 43 | assert.equal(q.count, q.capacity); |
| 44 | q.push(new ArrayBuffer(3)); |
| 45 | assert.equal(q.count, q.capacity); |
| 46 | }); |