|
| 1 | +// SPDX-License-Identifier: Apache-2.0 |
| 2 | +// Copyright (C) 2024, Tiny Tapeout LTD |
| 3 | +// Author: Renaldas Zioma, Uri Shaked |
| 4 | + |
| 5 | +class AudioResamplerProcessor extends AudioWorkletProcessor { |
| 6 | + constructor() { |
| 7 | + super(); |
| 8 | + |
| 9 | + // Define buffer properties |
| 10 | + this.downsampleFactor = 1; |
| 11 | + this.ringBufferSize = 16_384 * this.downsampleFactor; // stores approximately 5 frames of audio data at 192 kHz |
| 12 | + this.ringBuffer = new Float32Array(this.ringBufferSize); // ring-buffer helps to amortise uneven framerate and |
| 13 | + // keeps re-sampler from starving or overflowing |
| 14 | + this.writeIndex = 0; // Index where new samples are written |
| 15 | + this.readIndex = 0; // Index where samples are read |
| 16 | + this.previousSample = 0.0; |
| 17 | + this.ringBuffer.fill(this.previousSample); |
| 18 | + |
| 19 | + this.downsampleBuffer = new Float32Array(128 * this.downsampleFactor); |
| 20 | + |
| 21 | + // Listen to messages from the main thread |
| 22 | + this.port.onmessage = this.handleMessage.bind(this); |
| 23 | + |
| 24 | + this.expectedFPS = 60.0; |
| 25 | + this.currentFPS = this.expectedFPS; |
| 26 | + console.log("Audio WebWorker started"); |
| 27 | + } |
| 28 | + |
| 29 | + handleMessage(event) { |
| 30 | + const data = event.data; |
| 31 | + |
| 32 | + // Handle incoming audio samples and write to the ring buffer |
| 33 | + if (data.type === 'samples') { |
| 34 | + this.currentFPS = data.fps; |
| 35 | + this.downsampleFactor = data.downsampleFactor; |
| 36 | + const samples = data.samples; |
| 37 | + for (let i = 0; i < samples.length; i++) { |
| 38 | + if ((this.writeIndex + 1) % this.ringBufferSize == this.readIndex) |
| 39 | + { |
| 40 | + this.port.postMessage([this.ringBufferSize, 1.0]); |
| 41 | + console.log("Buffer is full. Dropping", samples.length - i, "incomming samples!"); |
| 42 | + break; // Skip incomming samples when ring-buffer is full |
| 43 | + } |
| 44 | + if (this.writeIndex == this.readIndex) |
| 45 | + this.ringBuffer[(this.writeIndex - 1) % this.ringBufferSize] = samples[i]; |
| 46 | + this.ringBuffer[this.writeIndex] = samples[i]; |
| 47 | + this.writeIndex = (this.writeIndex + 1) % this.ringBufferSize; // Wrap around |
| 48 | + } |
| 49 | + |
| 50 | + const samplesAvailable = (this.writeIndex - this.readIndex + this.ringBufferSize) % this.ringBufferSize; |
| 51 | + this.port.postMessage([samplesAvailable, samplesAvailable / this.ringBufferSize]); |
| 52 | + } |
| 53 | + else if (data.type === 'reset') { |
| 54 | + this.ringBuffer.fill(this.previousSample); |
| 55 | + this.readIndex = 0; |
| 56 | + this.writeIndex = 0; |
| 57 | + } |
| 58 | + } |
| 59 | + |
| 60 | + // Linear interpolation for resampling |
| 61 | + interpolate(buffer, index1, index2, frac) { |
| 62 | + return (1 - frac) * buffer[index1] + frac * buffer[index2]; |
| 63 | + } |
| 64 | + |
| 65 | + // Process function that resamples the data from the ring buffer to match output size |
| 66 | + process(inputs, outputs) { |
| 67 | + const output = outputs[0]; // Mono output (1 channel) |
| 68 | + const outputData = output[0]; // Get the output data array |
| 69 | + |
| 70 | + const playbackRate = this.currentFPS / this.expectedFPS; |
| 71 | + const borderSamples = 2; |
| 72 | + const samplesRequired = Math.round(outputData.length * playbackRate * this.downsampleFactor) + borderSamples; |
| 73 | + |
| 74 | + // example when samplesRequired = 8 + 2 border samples |
| 75 | + // (border samples are marked as 'b' below) |
| 76 | + // |
| 77 | + // 3 subsequent invocations of process(): |
| 78 | + // |
| 79 | + // ringBuffer: b01234567b01234567b01234567b. |
| 80 | + // process#0 ^........^ | <- sampling window |
| 81 | + // process#1 ^........^ | <- sampling window |
| 82 | + // process#2 ^........^| <- sampling window |
| 83 | + // WRITE pointer--` |
| 84 | + |
| 85 | + // process#0 ^--READ pointer |
| 86 | + // process#1 ^--READ pointer |
| 87 | + // process#2 ^--READ pointer |
| 88 | + // after process#2 ^--READ pointer |
| 89 | + |
| 90 | + const samplesAvailable = (this.writeIndex - this.readIndex + this.ringBufferSize) % this.ringBufferSize; |
| 91 | + if (samplesAvailable < borderSamples) |
| 92 | + { |
| 93 | + for (let i = 0; i < outputData.length; i++) |
| 94 | + outputData[i] = this.previousSample; |
| 95 | + console.log("Buffer is empty. Using previous sample value " + this.previousSample.toFixed(3)); |
| 96 | + return true; |
| 97 | + } |
| 98 | + |
| 99 | + const samplesConsumed = Math.min(samplesRequired, samplesAvailable) - borderSamples; |
| 100 | + |
| 101 | + if (this.downsampleBuffer.length != outputData.length * this.downsampleFactor); |
| 102 | + this.downsampleBuffer = new Float32Array(outputData.length * this.downsampleFactor); |
| 103 | + |
| 104 | + // Calculate resampling ratio |
| 105 | + const ratio = samplesConsumed / this.downsampleBuffer.length; |
| 106 | + |
| 107 | + // Fill the output buffer by resampling from the ring buffer |
| 108 | + for (let i = 0; i < this.downsampleBuffer.length; i++) { |
| 109 | + const floatPos = 0.5 + ratio * (i + 0.5); // use sample centroids, thus +0.5 |
| 110 | + const intPos = Math.floor(floatPos); |
| 111 | + const nextIntPos = intPos + 1; |
| 112 | + const frac = floatPos - intPos; // fractional part for interpolation |
| 113 | + |
| 114 | + // Resample with linear interpolation |
| 115 | + this.downsampleBuffer[i] = this.interpolate(this.ringBuffer, |
| 116 | + (this.readIndex + intPos) % this.ringBufferSize, |
| 117 | + (this.readIndex + nextIntPos) % this.ringBufferSize, frac); |
| 118 | + } |
| 119 | + |
| 120 | + // Optional (if audio context does not support 192 kHz) downsample to output buffer |
| 121 | + const N = this.downsampleFactor; |
| 122 | + if (N > 1) { |
| 123 | + for (let i = 0; i < outputData.length; i++) { |
| 124 | + let acc = this.downsampleBuffer[i*N]; |
| 125 | + for (let j = 1; j < N; j++) |
| 126 | + acc += this.downsampleBuffer[i*N + j]; |
| 127 | + outputData[i] = acc / N; |
| 128 | + } |
| 129 | + } else { |
| 130 | + for (let i = 0; i < outputData.length; i++) |
| 131 | + outputData[i] = this.downsampleBuffer[i]; |
| 132 | + |
| 133 | + } |
| 134 | + |
| 135 | + // Store last sample as a future fallback value in case |
| 136 | + // if data would not be ready for the next process() call |
| 137 | + this.previousSample = outputData[outputData.length - 1]; |
| 138 | + |
| 139 | + // Update readIndex to match how many samples were consumed |
| 140 | + this.readIndex = (this.readIndex + samplesConsumed) % this.ringBufferSize; |
| 141 | + |
| 142 | + return true; // return true to keep the processor alive |
| 143 | + } |
| 144 | +} |
| 145 | + |
| 146 | +// Register the processor |
| 147 | +registerProcessor('resampler', AudioResamplerProcessor); |
| 148 | + |
0 commit comments