All files / src/web audio-renderer.js

97.91% Statements 141/144
95.12% Branches 39/41
89.28% Functions 25/28
98.49% Lines 131/133

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266                              1x 1x 1x   1x 119x               46x                 46x 46x 46x 46x 46x 46x 46x       46x 46x 46x 46x 46x 46x 46x 46x   46x 46x 46x 46x 46x   4x 2x   2x 3x   46x 46x       12x 12x 11x       49x 49x       3x 2x 2x       50x 50x 50x 50x       96x       15295x       15285x             3606x 3606x 119x 3x 3x 3x 3x 3x 3x     3606x 32x 32x   3606x 3606x       15245x 36x 36x                   36x       15x       13369x 13369x 13369x 13369x 13369x 13369x       116x           7x 5x 5x       42x 42x 5x 5x   42x       1565x 10x 10x 10x   1565x           13811x 13811x 13811x       15246x 1555x 1555x   13691x 13811x 13811x 13692x 13692x 13692x 13692x 13692x   119x 119x 10x 10x   109x               13650x 13650x 13650x 2x 2x         15245x 15245x 15245x 1595x   13650x     15245x 15245x         15245x 15245x 15245x 15245x 15245x 15245x 59086x 15245x 15245x 15245x 15245x 15245x 15245x       1x  
/* global sampleRate, currentTime, registerProcessor, AudioWorkletProcessor */
import { SoundChip, AtomSoundChip } from "../soundchip.js";
import { PolyphaseResampler } from "../resampler.js";
import {
    AudioOutputs,
    DefaultAudioOutput,
    ResamplerCutoffOfOutputRate,
    ResamplerTaps,
    outputStages,
} from "../audio-output.js";
import { ExcessLeadMs, PersistentExcessSeconds, validTargetLatencyMs } from "../audio-latency.js";
 
// Smoothing rejects the producer's per-tick bursts. Proportional only, as the
// lead already integrates rate error. A change of rate of at most 0.05% covers
// clock skew and is too small to hear as a change of pitch.
const LeadSmoothingTau = 0.5;
const ProportionalGain = 0.2;
const MaxAdjustFraction = 0.0005;
 
const ResyncKinds = new Set(["state", "reset"]);
const isResync = (event) => ResyncKinds.has(event.kind);
 
// Renders the chip from its timestamped state changes, so a producer that
// falls behind leaves the chip sounding its current state (a stall) rather
// than silent; the missed time is skipped once the producer is ahead again,
// as is the excess of one that stays too far ahead.
class SoundChipProcessor extends AudioWorkletProcessor {
    constructor(options) {
        super(options);
        const {
            isAtom = false,
            cpuSpeed = 1000000,
            targetLatencyMs,
            audioOutput = DefaultAudioOutput,
            audioFilterFreq,
            audioFilterQ,
            speakerAmount,
        } = options?.processorOptions ?? {};
        this.chip = isAtom ? new AtomSoundChip(null, { cpuSpeed }) : new SoundChip(null);
        this.inputSampleRate = this.chip.soundchipFreq;
        this.samplesPerCycle = this.chip.samplesPerCycle;
        this.boardFilter = { filterHz: audioFilterFreq, filterQ: audioFilterQ, speakerAmount };
        this.setAudioOutput(audioOutput);
        this.resampler = new PolyphaseResampler(this.inputSampleRate, ResamplerCutoffOfOutputRate * sampleRate, {
            taps: ResamplerTaps,
        });
 
        this.events = [];
        this.eventsHead = 0;
        this.clock = 0;
        this.upTo = 0;
        this.stalled = true;
        this.stalls = 0;
        this.skippedMs = 0;
        this.minLeadMs = Infinity;
 
        this._phase = 0;
        this.smoothedLeadError = 0;
        this.setTargetLatency(targetLatencyMs);
        this.excessLeadCycles = this._cycles(ExcessLeadMs);
        this.commands = {
            produced: (m) => this.onProduced(m.upTo, m.events),
            setEnabled: (m) => (this.chip.enabled = m.enabled),
            setChannelMutes: (m) => (this.chip.channelMuted = m.muted),
            setTargetLatency: (m) => this.setTargetLatency(m.targetLatencyMs),
            setAudioOutput: (m) => this.setAudioOutput(m.audioOutput),
            setSpeakerAmount: (m) => this.setSpeakerAmount(m.speakerAmount),
        };
        this.port.onmessage = (event) => this.onMessage(event.data);
        this.nextStats = 0;
    }
 
    onMessage(message) {
        const command = this.commands[message.command];
        if (!command) throw new Error(`Unknown sound command ${message.command}`);
        command(message);
    }
 
    setAudioOutput(audioOutput) {
        this.audioOutput = audioOutput;
        this.outputFilters = outputStages(this.inputSampleRate, audioOutput, this.boardFilter);
    }
 
    setSpeakerAmount(speakerAmount) {
        if (speakerAmount === this.boardFilter.speakerAmount) return;
        this.boardFilter.speakerAmount = speakerAmount;
        if (this.audioOutput === AudioOutputs.speaker) this.setAudioOutput(this.audioOutput);
    }
 
    setTargetLatency(ms) {
        this.targetLatencyMs = validTargetLatencyMs(ms);
        this.targetLeadCycles = this._cycles(this.targetLatencyMs);
        this.smoothedLeadError = 0;
        this.excessSeconds = 0;
    }
 
    _cycles(ms) {
        return ((ms / 1000) * this.inputSampleRate) / this.samplesPerCycle;
    }
 
    _ms(cycles) {
        return (1000 * cycles * this.samplesPerCycle) / this.inputSampleRate;
    }
 
    leadMs() {
        return this._ms(this.upTo - this.clock);
    }
 
    // A resync (restore or reset) starts a new timeline; anything queued
    // before it belongs to the old one. The clock moves to it on arrival, as a
    // stalled renderer waits for a lead measured from the clock.
    onProduced(upTo, events) {
        let from = 0;
        for (let i = events.length - 1; i >= 0; --i) {
            if (isResync(events[i])) {
                from = i + 1;
                this.events = [];
                this.eventsHead = 0;
                this.clock = events[i].cycle;
                this.chip.applyEvent(events[i]);
                break;
            }
        }
        if (this.eventsHead > 0) {
            this.events = this.events.slice(this.eventsHead);
            this.eventsHead = 0;
        }
        for (let i = from; i < events.length; ++i) this.events.push(events[i]);
        this.upTo = upTo;
    }
 
    stats(sampleRatio) {
        if (currentTime < this.nextStats) return;
        this.nextStats = currentTime + 0.25;
        this.port.postMessage({
            sampleRate: sampleRate,
            inputSampleRate: this.inputSampleRate,
            stalls: this.stalls,
            skippedMs: this.skippedMs,
            leadMs: this.leadMs(),
            leadMinMs: this.minLeadMs,
            queuedEvents: this.events.length - this.eventsHead,
            sampleRatio: sampleRatio,
        });
        this.minLeadMs = Infinity;
    }
 
    _notify(event, count) {
        this.port.postMessage({ event, count });
    }
 
    _effectiveSampleRate(dtSeconds) {
        const error = this.upTo - this.clock - this.targetLeadCycles;
        const alpha = Math.min(1, dtSeconds / LeadSmoothingTau);
        this.smoothedLeadError += alpha * (error - this.smoothedLeadError);
        const adjustment = ProportionalGain * this.smoothedLeadError * this.samplesPerCycle;
        const maxAdjust = this.inputSampleRate * MaxAdjustFraction;
        return this.inputSampleRate + Math.min(maxAdjust, Math.max(-maxAdjust, adjustment));
    }
 
    _applyHead() {
        this.chip.applyEvent(this.events[this.eventsHead++]);
    }
 
    // Applies every queued change up to `cycle` at once and moves the clock
    // there, so the sound continues from the producer's state without a gap.
    _skipTo(cycle) {
        while (this.eventsHead < this.events.length && this.events[this.eventsHead].cycle <= cycle) this._applyHead();
        this.skippedMs += this._ms(cycle - this.clock);
        this.clock = cycle;
    }
 
    _restart() {
        const skipTo = this.upTo - this.targetLeadCycles;
        if (skipTo > this.clock) {
            this._notify("skip", this._ms(skipTo - this.clock));
            this._skipTo(skipTo);
        }
        this.stalled = false;
    }
 
    _stall(out, offset, length) {
        if (!this.stalled) {
            this.stalled = true;
            this.stalls++;
            this._notify("stall", 1);
        }
        this.chip.renderAt(this.clock, out, offset, length);
    }
 
    // Input samples before the next change of state: the head event, or
    // the producer's position, whichever the clock reaches first.
    _samplesUntilNextChange() {
        const head = this.events[this.eventsHead];
        const boundary = head === undefined ? this.upTo : Math.min(head.cycle, this.upTo);
        return Math.floor((boundary - this.clock) * this.samplesPerCycle);
    }
 
    _renderInput(out, offset, length) {
        if (this.stalled) {
            this._stall(out, offset, length);
            return;
        }
        while (length > 0) {
            const n = Math.min(length, this._samplesUntilNextChange());
            if (n > 0) {
                this.chip.renderAt(this.clock, out, offset, n);
                this.clock += n / this.samplesPerCycle;
                offset += n;
                length -= n;
                continue;
            }
            const head = this.events[this.eventsHead];
            if (head === undefined) {
                this._stall(out, offset, length);
                return;
            }
            this._applyHead();
        }
    }
 
    // Rate control, held to MaxAdjustFraction, would take half an hour to play off a second of excess
    // lead; a fall in the target drains its excess well inside PersistentExcessSeconds, as the producer
    // waits for it.
    _skipPersistentExcess(dtSeconds) {
        const excess = this.upTo - this.clock > this.targetLeadCycles + this.excessLeadCycles;
        this.excessSeconds = excess ? this.excessSeconds + dtSeconds : 0;
        if (this.excessSeconds >= PersistentExcessSeconds) {
            this.excessSeconds = 0;
            this._restart();
        }
    }
 
    process(inputs, outputs) {
        const channel = outputs[0][0];
        const dtSeconds = channel.length / sampleRate;
        if (this.stalled) {
            if (this.upTo - this.clock >= this.targetLeadCycles) this._restart();
        } else {
            this._skipPersistentExcess(dtSeconds);
        }
 
        const effectiveSampleRate = this._effectiveSampleRate(dtSeconds);
        const sampleRatio = effectiveSampleRate / sampleRate;
 
        // The fractional read position carries across quanta, so consumption
        // averages exactly sampleRatio and the pitch never steps at a rounding
        // boundary.
        const end = this._phase + channel.length * sampleRatio;
        const numInputSamples = Math.floor(end);
        const resampler = this.resampler;
        resampler.reserve(numInputSamples);
        this._renderInput(resampler.buffer, resampler.inputOffset, numInputSamples);
        for (const filter of this.outputFilters)
            filter.process(resampler.buffer, resampler.inputOffset, numInputSamples);
        resampler.read(channel, this._phase, sampleRatio);
        resampler.commit();
        this._phase = end - numInputSamples;
        this.minLeadMs = Math.min(this.minLeadMs, this.leadMs());
        this.stats(sampleRatio);
        return true;
    }
}
 
registerProcessor("sound-chip-processor", SoundChipProcessor);