The best way to control Claude Code, Codex and more from any computer or phone

main
ts 54 lines 2.01 KB
Raw
1 const TARGET_RATE = 16_000;
2
3 /** Low-pass before downsampling, preserving filter and sample phase across capture blocks. */
4 export class PcmResampler {
5 private readonly coefficients: Float64Array;
6 private readonly history: Float32Array;
7 private position = 0;
8 private phase = 0;
9 private readonly ratio: number;
10
11 constructor(sampleRate: number) {
12 if (sampleRate < TARGET_RATE)
13 throw new Error("Microphone sample rate must be at least 16 kHz.");
14 this.ratio = sampleRate / TARGET_RATE;
15 this.coefficients = new Float64Array(sampleRate === TARGET_RATE ? 1 : 63);
16 this.history = new Float32Array(this.coefficients.length);
17 const middle = (this.coefficients.length - 1) / 2;
18 const cutoff = 7_200 / sampleRate;
19 let sum = 0;
20 for (let i = 0; i < this.coefficients.length; i++) {
21 const x = i - middle;
22 const sinc = x === 0 ? 2 * cutoff : Math.sin(2 * Math.PI * cutoff * x) / (Math.PI * x);
23 const window = middle === 0 ? 1 : 0.54 - 0.46 * Math.cos((Math.PI * i) / middle);
24 this.coefficients[i] = sinc * window;
25 sum += this.coefficients[i]!;
26 }
27 for (let i = 0; i < this.coefficients.length; i++) this.coefficients[i]! /= sum;
28 }
29
30 push(samples: Float32Array): Float32Array {
31 const output: number[] = [];
32 for (const sample of samples) {
33 this.history[this.position] = sample;
34 this.phase += 1;
35 if (this.phase >= this.ratio) {
36 this.phase -= this.ratio;
37 let value = 0;
38 for (let tap = 0; tap < this.coefficients.length; tap++) {
39 const index = (this.position - tap + this.history.length) % this.history.length;
40 value += this.history[index]! * this.coefficients[tap]!;
41 }
42 output.push(Math.max(-1, Math.min(1, value)));
43 }
44 this.position = (this.position + 1) % this.history.length;
45 }
46 return Float32Array.from(output);
47 }
48
49 flush(): Float32Array {
50 return this.coefficients.length === 1
51 ? new Float32Array()
52 : this.push(new Float32Array(this.history.length - 1));
53 }
54 }