All files / src/web audio-handler.js

77.22% Statements 139/180
76.13% Branches 67/88
69.44% Functions 25/36
78.57% Lines 121/154

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 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330                          1x       1x                                         31x 31x 31x 31x 31x 31x   31x 31x 31x 31x 31x 31x 31x 31x             31x 31x 31x 31x 26x 26x 7x 6x   26x       26x 26x 26x 26x 26x 3x     5x 5x 4x 4x 4x 4x   5x 5x 5x       31x   31x   31x 31x 31x       4x 4x 3x 3x 3x 3x         3x 3x 3x 3x         5x 5x 5x 5x 5x     4x       4x     1x 1x         5x                                         26x 21x                     21x 21x 21x 21x                                             26x       6x         2x 2x       1x                 1x 1x 1x 2x 1x                   3x 3x 3x 3x 3x 2x 2x                         18x   3x 3x       15x 6x 6x 6x   9x 2x 2x       9x         9x           2x 2x 2x             3x 2x 2x       6x 3x   3x   6x 1x       1x 1x         3x 3x 3x 3x       2x 2x 2x 2x      
import { FakeSoundChip, SoundChip, AtomSoundChip } from "../soundchip.js";
import { DdNoise, FakeDdNoise } from "../ddnoise.js";
import { RelayNoise, FakeRelayNoise } from "../relaynoise.js";
import { Music5000, FakeMusic5000 } from "../music5000.js";
import { DefaultTargetLatencyMs } from "../audio-latency.js";
import { createAudioContext } from "./audio-utils.js";
import { toggle, fadeIn, fadeOut } from "./dom-utils.js";
import { toast } from "./toast.js";
 
import rendererUrl from "./audio-renderer.js?worker&url";
import music5000WorkletUrl from "../music5000-worklet.js?worker&url";
 
// Skips plot as the milliseconds skipped, on the lead scale; stalls as a fixed spike.
const StallSpikeHeight = 20;
 
// Nobody is watching an unfocused window, so its sound can run far behind
// the picture, deep enough to ride out the browser starving the tab.
const UnfocusedLatencyMs = 200;
 
export class AudioHandler {
    /**
     * @param {object} options
     * @param {HTMLElement} [options.warningNode] where to say that the audio is suspended or could not start; without
     * one the handler says nothing, and `failure` is the only report of a failure
     */
    constructor({
        warningNode,
        statsNode,
        audioOutput,
        audioFilterFreq,
        audioFilterQ,
        speakerAmount,
        audioLatencyMs,
        noSeek,
        cpuSpeed,
        isAtom,
        hasMusic5000,
    }) {
        this.cpuSpeed = cpuSpeed;
        this.isAtom = isAtom;
        this.audioLatencyMs = audioLatencyMs ?? DefaultTargetLatencyMs;
        this.windowFocused = document.hasFocus();
        this.warningNode = warningNode ?? null;
        this.noAudio = false;
        /** Why there is no sound, set before `ready` resolves, or null; a context that is only suspended is not one. */
        this.failure = null;
        if (this.warningNode) toggle(this.warningNode, false);
        this.stats = {};
        this.eventCounts = { stall: 0, skip: 0, leadMinMs: Infinity };
        this._chipEvents = [];
        this._chipStateStale = false;
        this._channelMutes = null;
        Iif (statsNode) {
            this._initStats(statsNode).catch((error) => {
                console.error("Unable to initialise audio stats", error);
                this.stats = {};
                toggle(statsNode, false);
            });
        }
        this.audioContext = createAudioContext();
        this._jsAudioNode = null;
        let setup = Promise.resolve();
        if (this.audioContext && this.audioContext.audioWorklet) {
            this.audioContext.onstatechange = () => this.checkStatus();
            const onEvent = (event) => {
                if (event.kind === "progress") this.flushChipEvents();
                else this._chipEvents.push(event);
            };
            this.soundChip = this.isAtom
                ? new AtomSoundChip(null, { cpuSpeed: this.cpuSpeed, onEvent })
                : new SoundChip(null, { onEvent });
            // Master gain node for all sample-based audio (disc, relay, etc.).
            this.masterGain = this.audioContext.createGain();
            this.masterGain.connect(this.audioContext.destination);
            this.ddNoise = noSeek ? new FakeDdNoise() : new DdNoise(this.audioContext, this.masterGain);
            this.relayNoise = new RelayNoise(this.audioContext, this.masterGain);
            setup = this._setup({ audioOutput, audioFilterFreq, audioFilterQ, speakerAmount }).catch((error) =>
                this._audioUnavailable(error),
            );
        } else {
            if (!this.audioContext) this.failure = "This browser has no Web Audio";
            if (this.audioContext && !this.audioContext.audioWorklet) {
                this.audioContext = null;
                this.noAudio = true;
                console.log("Unable to initialise audio: no audio worklet API");
                this._warnNoWorklet();
            }
            this.soundChip = new FakeSoundChip();
            this.ddNoise = new FakeDdNoise();
            this.relayNoise = new FakeRelayNoise();
        }
 
        /** How the sound came up, `ok` or `unavailable`, once its output is set up or known never to be. */
        this.ready = setup.then(() => (this.noAudio || !this.audioContext ? "unavailable" : "ok"));
 
        this.warningNode?.addEventListener("mousedown", () => this.tryResume());
 
        this.audioContextM5000 = null;
        this._music5000workletnode = null;
        this.music5000 = hasMusic5000 ? this._createMusic5000() : new FakeMusic5000();
    }
 
    _warnNoWorklet() {
        this.failure = "No audio worklet API was found";
        if (!this.warningNode) return;
        const localhost = new URL(window.location);
        localhost.hostname = "localhost";
        this.warningNode.classList.add("alert-dismissible");
        this.warningNode.innerHTML = `No audio worklet API was found - there will be no audio.
            If you are running a local jsbeeb, you must either use a host of
            <a href="${localhost}">localhost</a>,
            or serve the content over <em>https</em>.
            <button type="button" class="btn-close" aria-label="Close"></button>`;
        const close = this.warningNode.querySelector(".btn-close");
        close.addEventListener("mousedown", (event) => event.preventDefault());
        close.addEventListener("click", () => toggle(this.warningNode, false));
        toggle(this.warningNode, true);
    }
 
    // The Music 5000 gets its own context, running at the board's own sample rate.
    _createMusic5000() {
        Iif (!this.audioContext?.audioWorklet) return new FakeMusic5000();
        const context = createAudioContext({ sampleRate: 46875 });
        this.audioContextM5000 = context;
        context.onstatechange = () => this.checkStatus();
        context.audioWorklet
            .addModule(music5000WorkletUrl)
            .then(() => {
                this._music5000workletnode = new AudioWorkletNode(context, "music5000", {
                    outputChannelCount: [2],
                    processorOptions: { targetLatencyMs: this._targetLatencyMs() },
                });
                this._music5000workletnode.connect(context.destination);
            })
            .catch((error) => {
                console.error("Unable to initialise Music 5000 audio", error);
                toast(
                    `The Music 5000 will be silent: its audio could not be started (${error?.message ?? error}). Reloading the page may help.`,
                    { title: "Music 5000", quietKey: "quietMusic5000Audio" },
                );
            });
        return new Music5000((buffer) => this._onBufferMusic5000(buffer));
    }
 
    // Lazily load smoothie and set up the audio stats chart.
    async _initStats(statsNode) {
        const { SmoothieChart, TimeSeries } = await import("smoothie");
        this._TimeSeries = TimeSeries;
        this.chart = new SmoothieChart({
            tooltip: true,
            labels: { precision: 0 },
            yRangeFunction: (range) => {
                return { min: 0, max: range.max };
            },
        });
        this._addStat("leadMs", { strokeStyle: "rgb(51,126,108)" });
        this._addStat("stall", { strokeStyle: "rgb(220,50,50)", lineWidth: 2 });
        this._addStat("skip", { strokeStyle: "rgb(120,80,200)", lineWidth: 2 });
        this.chart.streamTo(statsNode, 100);
    }
 
    async _setup({ audioOutput, audioFilterFreq, audioFilterQ, speakerAmount }) {
        await this.audioContext.audioWorklet.addModule(rendererUrl);
        this._jsAudioNode = new AudioWorkletNode(this.audioContext, "sound-chip-processor", {
            processorOptions: {
                targetLatencyMs: this._targetLatencyMs(),
                isAtom: this.isAtom,
                cpuSpeed: this.cpuSpeed,
                audioOutput,
                audioFilterFreq,
                audioFilterQ,
                speakerAmount,
            },
        });
        this._jsAudioNode.connect(this.audioContext.destination);
        if (!this.soundChip.enabled) this._setEnabled(false);
        if (this._channelMutes) this.setChannelMutes(this._channelMutes);
        this._jsAudioNode.port.onmessage = (event) => {
            const now = Date.now();
            if (event.data.event) {
                this._onAudioEvent(now, event.data);
                return;
            }
            this.eventCounts.leadMinMs = Math.min(this.eventCounts.leadMinMs, event.data.leadMinMs);
            for (const stat of Object.keys(event.data)) {
                if (this.stats[stat]) this.stats[stat].append(now, event.data[stat]);
            }
        };
    }
 
    _onAudioEvent(now, { event, count }) {
        this.eventCounts[event] += count;
        const series = this.stats[event];
        if (!series) return;
        series.append(now - 1, 0);
        series.append(now, event === "stall" ? StallSpikeHeight : count);
        series.append(now + 1, 0);
    }
 
    _targetLatencyMs() {
        return this.windowFocused ? this.audioLatencyMs : UnfocusedLatencyMs;
    }
 
    _setEnabled(enabled) {
        this._jsAudioNode?.port.postMessage({ command: "setEnabled", enabled });
    }
 
    /** Leaves the chip's channels muted out of what is heard, by channel: tones 0 to 2, then noise. */
    setChannelMutes(muted) {
        this._channelMutes = muted;
        this._jsAudioNode?.port.postMessage({ command: "setChannelMutes", muted });
    }
 
    setAudioOutput(audioOutput) {
        this._jsAudioNode?.port.postMessage({ command: "setAudioOutput", audioOutput });
    }
 
    setSpeakerAmount(speakerAmount) {
        this._jsAudioNode?.port.postMessage({ command: "setSpeakerAmount", speakerAmount });
    }
 
    // Returns how far ahead of the sound the picture should now run, in ms.
    setWindowFocused(focused) {
        this.windowFocused = focused;
        const targetLatencyMs = this._targetLatencyMs();
        for (const node of [this._jsAudioNode, this._music5000workletnode])
            node?.port.postMessage({ command: "setTargetLatency", targetLatencyMs });
        return targetLatencyMs - this.audioLatencyMs;
    }
 
    takeEventCounts() {
        const counts = this.eventCounts;
        this.eventCounts = { stall: 0, skip: 0, leadMinMs: Infinity };
        return counts;
    }
 
    _audioUnavailable(error) {
        console.error("Unable to initialise audio", error);
        this.noAudio = true;
        const reason = error?.message ?? error;
        this.failure = `The audio system could not be started (${reason})`;
        if (!this.warningNode) return;
        this.warningNode.textContent = `There will be no sound: the audio system could not be started (${reason}). Reloading the page may help.`;
        fadeIn(this.warningNode);
    }
 
    _addStat(stat, info) {
        const timeSeries = new this._TimeSeries();
        this.stats[stat] = timeSeries;
        info.tooltipLabel = stat;
        this.chart.addTimeSeries(timeSeries, info);
    }
 
    // Ships the chip's state changes since the last call, and how far the
    // emulator has got, so the worklet knows its lead even when nothing changed.
    flushChipEvents() {
        if (!this._jsAudioNode) {
            // Until the worklet is built its events wait for it, but one that could not be built never takes them.
            if (this.noAudio) this._chipEvents = [];
            return;
        }
        // A suspended worklet does not drain its port, so nothing is sent to it; the chip's registers go across whole
        // when it runs, in place of the events it missed.
        if (this.audioContext.state !== "running") {
            this._chipEvents = [];
            this._chipStateStale = true;
            return;
        }
        if (this._chipStateStale) {
            this._chipStateStale = false;
            this._chipEvents = [
                { cycle: this.soundChip.scheduler.epoch, kind: "state", value: this.soundChip.snapshotState() },
            ];
        }
        this._jsAudioNode.port.postMessage({
            command: "produced",
            upTo: this.soundChip.scheduler.epoch,
            events: this._chipEvents,
        });
        this._chipEvents = [];
    }
 
    // Recent browsers, particularly Safari and Chrome, require a user interaction in order to enable sound playback.
    // Errors are swallowed — resume() can fail due to autoplay policy and callers can't do anything about it.
    async tryResume() {
        try {
            if (this.audioContext) await this.audioContext.resume();
            Iif (this.audioContextM5000) await this.audioContextM5000.resume();
        } catch {
            // Autoplay policy prevented resume; will retry on next user gesture.
        }
    }
 
    _onBufferMusic5000(buffer) {
        if (this.audioContextM5000?.state !== "running") return;
        Eif (this._music5000workletnode)
            this._music5000workletnode.port.postMessage({ command: "samples", samples: buffer });
    }
 
    checkStatus() {
        if (this.noAudio || !this.warningNode) return;
        Iif (!this.audioContext && !this.audioContextM5000) return;
        const suspended =
            (this.audioContext && this.audioContext.state === "suspended") ||
            (this.audioContextM5000 && this.audioContextM5000.state === "suspended");
        if (suspended) fadeIn(this.warningNode);
        else fadeOut(this.warningNode);
    }
 
    async initialise() {
        await this.ddNoise.initialise();
        await this.relayNoise.initialise();
    }
 
    // The emulator is stopping, so no tick will ship its last writes; send them now.
    mute() {
        this.soundChip.mute();
        this._setEnabled(false);
        this.flushChipEvents();
        Eif (this.masterGain) this.masterGain.gain.value = 0;
    }
 
    unmute() {
        this.soundChip.unmute();
        this.flushChipEvents();
        this._setEnabled(true);
        Eif (this.masterGain) this.masterGain.gain.value = 1;
    }
}