All files / src soundchip.js

94.16% Statements 323/343
86.02% Branches 80/93
81.81% Functions 63/77
93.96% Lines 296/315

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 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685    91x     91x             91x       91x     91x   91x 91x 91x 91x 1365x 1365x   91x       251x 251x 2056192x   251x                             233x 233x   647x 233x   233x 233x   233x     233x   233x 233x   233x 233x 233x 233x   233x 233x               233x 233x 233x 233x   233x 233x   233x 233x 233x 233x   233x 233x 233x   233x 233x 233x   233x 233x 233x   233x   1x 1x 1x     2x 2x 2x 2x       233x   123x   4x           1021x               1025x 647x       647x   647x 647x         132x 132x 132x         15261x 15261x       16009x   7x 3086x 3086x   7x       82354755x 82354755x 934401x 934401x 934401x   81420354x 81420354x         47948x       47947x 47947x 47947x 61753399x 61753399x         314249x 314249x       3072x 3072x       66x   66x       15995x 15995x   15994x           1x         15995x 15995x 15995x 20601356x 20601356x         16462x 16462x 16462x 21203457x   16462x 16009x 80003x     16462x 16462x 16462x 16462x 21203457x 21203457x 21203457x 21203457x   16462x 16462x         64x 64x 64x 960x 64x       482x 482x 482x       123x 123x 123x 3x   123x 8x 505x 505x   8x         11x 11x 11x 506x   11x 11x 11x     11x 11x           33x 23x 23x 23x                 23x 38x 38x 38x 2x     36x 36x 36x   36x 16x 16x           407x 407x     407x 311x 311x   96x   407x   407x   200x 200x 207x   8x 8x 199x   104x     95x         31x 31x       31x 28x         114x                                       45x 45x 45x 45x 45x 45x 45x 45x 45x   45x 45x 45x 45x 45x   45x     45x 45x   45x 45x   45x 44x 44x 44x   45x 45x       59x 58x 58x 232x 232x   232x   58x 58x       6x       4x       2x                     18x 18x 18x     18x     18x   18x   1x 1x     15x 15x       18x 18x 18x 18x 18x 18x   18x 4x           2x 2x       30x 30x 30x       2x 2x       14x       7x 7x   7x 7x 7x 7x       3x 3x 3x 3x 3x 3x 3x       14x 14x 14x       14x   14x 1058x       12x 12x   1058x 1058x 1058x 1058x     14x 10x         19x 19x 19x 19x 15x                   1x 1x 1x 1x             2x 2x 2x   2x         1x 1x         1x 1x         2x 2x                                                                                                     126x       126x             171x          
// Atom speaker volume, scaled to be comparable with BBC tone channels.
// The BBC volumeTable[0] (loudest) is 0.25 (1.0 / 4 channels).
const speakerVolume = 0.5;
 
// Samples per output chunk handed to the onBuffer callback.
export const SoundBufferSamples = 512;
 
// The BBC's DC restoration circuit (Service Manual section 3.8: R8 10K, C2
// 4u7) cancels the SN76489's unipolar pedestal. Modelled as a first-order DC
// blocker with the same corner, 1/(2*pi*R*C). The generators must stay
// unipolar: sampled speech is amplitude modulation of a 125 kHz carrier's
// mean level, which a zero-mean output would silence (see issue #863).
const DcRestoreCornerHz = 1 / (2 * Math.PI * 10e3 * 4.7e-6);
 
// A chip with an event sink reports progress this often, so its events can
// stream through a long execute() rather than all arriving at its end.
const EventProgressCycles = 4000;
 
// The tone counters are 10 bits wide and wrap, so a period of 0 counts this many steps.
export const ToneCounterSteps = 1024;
 
export const volumeTable = new Float32Array(16);
(() => {
    let f = 1.0;
    for (let i = 0; i < 15; ++i) {
        volumeTable[i] = f / 4; // Bakes in the per channel volume
        f *= Math.pow(10, -0.1);
    }
    volumeTable[15] = 0;
})();
 
function makeSineTable(attenuation) {
    const sineTable = new Float32Array(8192);
    for (let i = 0; i < sineTable.length; ++i) {
        sineTable[i] = Math.sin((2 * Math.PI * i) / sineTable.length) * attenuation;
    }
    return sineTable;
}
 
export class SoundChip {
    /**
     * @param {function(Float32Array): void} onBuffer called with each full
     *     SoundBufferSamples-sized buffer of output. Receives the same buffer
     *     every call, overwritten afterwards: copy the contents if they are kept.
     * @param {object} [options]
     * @param {function(object): void} [options.onEvent] called with each
     *     change to the chip's state, stamped with the cycle it takes effect at.
     *     A chip with an event sink does not render; something else renders
     *     from the events (see audio-renderer.js).
     */
    constructor(onBuffer, { onEvent = null } = {}) {
        this._onBuffer = onBuffer;
        this._onEvent = onEvent;
        /** The CPU's `replaying`, which asReplay sets. */
        this.replaying = () => false;
        this._hostBehind = false;
        // 4MHz input signal. Internal divide-by-8
        this.soundchipFreq = 4000000.0 / 8;
        const sampleRate = this.soundchipFreq;
        // Square wave changes every time a counter hits zero: A full wave needs to be 2x counter zeros.
        this.waveDecrementPerSecond = this.soundchipFreq / 2;
        // Each sample in the buffer represents (1/sampleRate) time, so each time
        // we generate a sample, we need to decrement the counters by this amount:
        this.sampleDecrement = this.waveDecrementPerSecond / sampleRate;
        // How many samples are generated per CPU cycle.
        this.samplesPerCycle = sampleRate / 2000000;
        this.minCyclesWELow = 14; // Somewhat empirically derived; Repton 2 has only 14 cycles between WE low and WE high (@0x2caa)
 
        this.registers = new Uint16Array(4);
        this.counter = new Float32Array(4);
        this.outputBit = [false, false, false, false];
        this.volume = new Float32Array(4);
        /** By channel, tones 0 to 2 then noise: a muted one is not run, so it is silent and resumes where it stopped. */
        this.channelMuted = [false, false, false, false];
        this.generators = [
            this.toneChannel.bind(this),
            this.toneChannel.bind(this),
            this.toneChannel.bind(this),
            this.noiseChannel.bind(this),
            this.sineChannel.bind(this),
        ];
 
        this.sineTable = makeSineTable(1 / this.generators.length);
        this.sineStep = 0;
        this.sineOn = false;
        this.sineTime = 0;
 
        this.lfsr = 0;
        this.shiftLfsr = this.shiftLfsrWhiteNoise.bind(this);
 
        this.enabled = true;
        this.scheduler = { epoch: 0 };
        this.lastRunEpoch = 0;
        this.activeTask = null;
 
        this.residual = 0;
        this.position = 0;
        this.buffer = new Float32Array(SoundBufferSamples);
 
        this.dcAlpha = 1 - (2 * Math.PI * DcRestoreCornerHz) / sampleRate;
        this.dcPrevIn = 0;
        this.dcPrevOut = 0;
 
        this.latchedRegister = 0;
        this.slowDataBus = 0;
        this.active = false;
 
        this.toneGenerator = {
            mute: () => {
                this.catchUp();
                this.sineOn = false;
                this._emit("sine", 0);
            },
            tone: (freq) => {
                this.catchUp();
                this.sineOn = true;
                this.sineStep = (freq / sampleRate) * this.sineTable.length;
                this._emit("sine", freq);
            },
        };
 
        this.eventHandlers = {
            progress: () => {},
            poke: (value) => this.poke(value),
            sine: (freq) => (freq ? this.toneGenerator.tone(freq) : this.toneGenerator.mute()),
            state: (state) => this.restoreState(state),
            reset: (hard) => this.reset(hard),
        };
    }
 
    _emit(kind, value) {
        this._send({ cycle: this.scheduler.epoch, kind, value });
    }
 
    /**
     * Sends `event` to the host unless the machine is replaying. After a replay held some back, the chip as it stands
     * goes first, so that the host sounds on from where the replay left the machine.
     */
    _send(event) {
        if (!this._onEvent) return;
        Iif (this.replaying()) {
            this._hostBehind = true;
            return;
        }
        Iif (this._hostBehind && event.kind !== "state")
            this._onEvent({ cycle: this.scheduler.epoch, kind: "state", value: this.snapshotState() });
        this._hostBehind = false;
        this._onEvent(event);
    }
 
    /** Applies an event from another chip's onEvent, at the cycle this chip is rendering. */
    applyEvent(event) {
        const handler = this.eventHandlers[event.kind];
        Iif (!handler) throw new Error(`Unknown sound event ${event.kind}`);
        handler(event.value, event);
    }
 
    /** Renders `length` samples of output from `cycle`, for a chip that is driven by events. */
    renderAt(cycle, out, offset, length) {
        this.scheduler.epoch = this.lastRunEpoch = cycle;
        this.generate(out, offset, length);
    }
 
    sineChannel(channel, out, offset, length) {
        if (!this.sineOn) return;
 
        for (let i = 0; i < length; ++i) {
            out[i + offset] += this.sineTable[this.sineTime & (this.sineTable.length - 1)];
            this.sineTime += this.sineStep;
        }
        while (this.sineTime > this.sineTable.length) this.sineTime -= this.sineTable.length;
    }
 
    _doChannelStep(channel, addAmount) {
        const newValue = this.counter[channel] - this.sampleDecrement;
        if (newValue < 0) {
            this.counter[channel] = Math.max(0, newValue + addAmount);
            this.outputBit[channel] = !this.outputBit[channel];
            return this.outputBit[channel];
        } else {
            this.counter[channel] = newValue;
            return false;
        }
    }
 
    tonePeriod(channel) {
        return this.registers[channel] === 0 ? ToneCounterSteps : this.registers[channel];
    }
 
    toneChannel(channel, out, offset, length) {
        const reg = this.tonePeriod(channel);
        const vol = this.volume[channel];
        for (let i = 0; i < length; ++i) {
            this._doChannelStep(channel, reg);
            out[i + offset] += this.outputBit[channel] * vol;
        }
    }
 
    shiftLfsrWhiteNoise() {
        const bit = (this.lfsr & 1) ^ ((this.lfsr & (1 << 1)) >>> 1);
        this.lfsr = (this.lfsr >>> 1) | (bit << 14);
    }
 
    shiftLfsrPeriodicNoise() {
        this.lfsr >>= 1;
        if (this.lfsr === 0) this.lfsr = 1 << 14;
    }
 
    noisePoked() {
        this.shiftLfsr =
            this.registers[3] & 4 ? this.shiftLfsrWhiteNoise.bind(this) : this.shiftLfsrPeriodicNoise.bind(this);
        this.lfsr = 1 << 14;
    }
 
    addFor(channel) {
        channel = channel | 0;
        switch (this.registers[channel] & 3) {
            case 0:
                return 0x10;
            case 1:
                return 0x20;
            case 2:
                return 0x40;
            case 3:
                return this.tonePeriod(2);
        }
    }
 
    noiseChannel(channel, out, offset, length) {
        const add = this.addFor(channel),
            vol = this.volume[channel];
        for (let i = 0; i < length; ++i) {
            if (this._doChannelStep(channel, add)) this.shiftLfsr();
            out[i + offset] += (this.lfsr & 1) * vol;
        }
    }
 
    generate(out, offset, length) {
        offset = offset | 0;
        length = length | 0;
        for (let i = 0; i < length; ++i) {
            out[i + offset] = 0.0;
        }
        if (this.enabled) {
            for (let i = 0; i < this.generators.length; ++i) {
                if (!this.channelMuted[i]) this.generators[i](i, out, offset, length);
            }
        }
        const alpha = this.dcAlpha;
        let prevIn = this.dcPrevIn;
        let prevOut = this.dcPrevOut;
        for (let i = 0; i < length; ++i) {
            const x = out[i + offset];
            prevOut = x - prevIn + alpha * prevOut;
            prevIn = x;
            out[i + offset] = prevOut;
        }
        this.dcPrevIn = prevIn;
        this.dcPrevOut = prevOut;
    }
 
    /** The channel's attenuation as the chip was last told it, 0 (loudest) to 15 (silent). */
    attenuation(channel) {
        const volume = this.volume[channel];
        let nearest = 0;
        for (let i = 1; i < volumeTable.length; ++i)
            if (Math.abs(volumeTable[i] - volume) < Math.abs(volumeTable[nearest] - volume)) nearest = i;
        return nearest;
    }
 
    catchUp() {
        const cyclesPending = this.scheduler.epoch - this.lastRunEpoch;
        if (cyclesPending > 0) this.advance(cyclesPending);
        this.lastRunEpoch = this.scheduler.epoch;
    }
 
    setScheduler(scheduler_) {
        this.scheduler = scheduler_;
        this.lastRunEpoch = this.scheduler.epoch;
        this.activeTask = this.scheduler.newTask(() => {
            Eif (this.active) this.poke(this.slowDataBus);
        });
        if (this._onEvent) {
            this.progressTask = this.scheduler.newTask(() => {
                this._emit("progress", true);
                this.progressTask.schedule(EventProgressCycles);
            });
            this.progressTask.schedule(EventProgressCycles);
        }
    }
 
    render(out, offset, length) {
        this.catchUp();
        const fromBuffer = this.position > length ? length : this.position;
        for (let i = 0; i < fromBuffer; ++i) {
            out[offset + i] = this.buffer[i];
        }
        offset += fromBuffer;
        length -= fromBuffer;
        for (let i = fromBuffer; i < this.position; ++i) {
            this.buffer[i - fromBuffer] = this.buffer[i];
        }
        this.position -= fromBuffer;
        Iif (length !== 0) {
            this.generate(out, offset, length);
        }
    }
 
    advance(cycles) {
        if (this._onEvent) return;
        const num = cycles * this.samplesPerCycle + this.residual;
        let rounded = num | 0;
        this.residual = num - rounded;
        // The buffer is deliberately reused for the chip's whole life: the
        // previous transfer-then-reallocate pattern is miscompiled by a V8
        // optimiser bug (Chrome 150, crbug.com/537801199) which allocates the
        // replacement with length 0, even when the reallocation is reordered
        // before the transfer, wedging this loop forever. Reuse is also
        // cheaper, so this needn't be reverted once the crbug is fixed. The
        // guard fails loudly if the buffer is ever detached or the accounting
        // goes bad.
        while (rounded > 0) {
            const leftInBuffer = SoundBufferSamples - this.position;
            const numSamplesToGenerate = Math.min(rounded, leftInBuffer);
            if (numSamplesToGenerate <= 0 || this.buffer.length !== SoundBufferSamples)
                throw new Error(
                    `Sound buffer accounting error (buffer=${this.buffer.length}, position=${this.position}, rounded=${rounded})`,
                );
            this.generate(this.buffer, this.position, numSamplesToGenerate);
            this.position += numSamplesToGenerate;
            rounded -= numSamplesToGenerate;
 
            if (this.position === SoundBufferSamples) {
                this._onBuffer(this.buffer);
                this.position = 0;
            }
        }
    }
 
    poke(value) {
        this.catchUp();
        this._emit("poke", value);
 
        let command;
        if (value & 0x80) {
            this.latchedRegister = value & 0x70;
            command = value & 0xf0;
        } else {
            command = this.latchedRegister;
        }
        const channel = (command >> 5) & 0x03;
 
        if (command & 0x10) {
            // Volume setting
            const newVolume = value & 0x0f;
            this.volume[channel] = volumeTable[newVolume];
        } else if (channel === 3) {
            // For noise channel we always update the bottom bits.
            this.registers[channel] = value & 0x0f;
            this.noisePoked();
        } else if (command & 0x80) {
            // Low period bits.
            this.registers[channel] = (this.registers[channel] & ~0x0f) | (value & 0x0f);
        } else {
            // High period bits.
            this.registers[channel] = (this.registers[channel] & 0x0f) | ((value & 0x3f) << 4);
        }
    }
 
    updateSlowDataBus(slowDataBus, active) {
        this.slowDataBus = slowDataBus;
        this.active = active;
        // TODO(#835) this probably isn't modeled correctly. Currently the sound chip "notices" a new data bus value some
        // fixed number of cycles after WE (write enable) is triggered. In reality, the sound chip likely pulls data off
        // the bus at a fixed point in its cycle, iff WE is active.
        if (active) {
            this.activeTask.ensureScheduled(true, this.minCyclesWELow);
        }
    }
 
    snapshotState() {
        return {
            registers: this.registers.slice(),
            counter: this.counter.slice(),
            outputBit: [...this.outputBit],
            volume: this.volume.slice(),
            lfsr: this.lfsr,
            latchedRegister: this.latchedRegister,
            residual: this.residual,
            sineOn: this.sineOn,
            sineStep: this.sineStep,
            sineTime: this.sineTime,
            dcPrevIn: this.dcPrevIn,
            dcPrevOut: this.dcPrevOut,
            slowDataBus: this.slowDataBus,
            active: this.active,
            activeTaskOffset: this.activeTask?.offset() ?? null,
        };
    }
 
    restoreState(state) {
        this.registers.set(state.registers);
        this.counter.set(state.counter);
        this.outputBit[0] = state.outputBit[0];
        this.outputBit[1] = state.outputBit[1];
        this.outputBit[2] = state.outputBit[2];
        this.outputBit[3] = state.outputBit[3];
        this.volume.set(state.volume);
        this.lfsr = state.lfsr;
        this.latchedRegister = state.latchedRegister;
        // Sync to current scheduler epoch to avoid a catch-up burst
        this.lastRunEpoch = this.scheduler.epoch;
        this.residual = state.residual;
        this.sineOn = state.sineOn;
        this.sineStep = state.sineStep;
        this.sineTime = state.sineTime;
        // Rebind the LFSR function based on noise register
        this.shiftLfsr =
            this.registers[3] & 4 ? this.shiftLfsrWhiteNoise.bind(this) : this.shiftLfsrPeriodicNoise.bind(this);
        // Reset output buffer
        this.position = 0;
        this.buffer.fill(0);
        // Older snapshots predate the DC blocker
        this.dcPrevIn = state.dcPrevIn ?? 0;
        this.dcPrevOut = state.dcPrevOut ?? 0;
        // Older snapshots keep what the System VIA's restore drove onto the bus before this one ran.
        if (state.slowDataBus !== undefined) {
            this.slowDataBus = state.slowDataBus;
            this.active = state.active;
            this.activeTask?.restoreOffset(state.activeTaskOffset);
        }
        this.progressTask?.ensureScheduled(true, EventProgressCycles);
        this._emit("state", this.snapshotState());
    }
 
    reset(hard) {
        if (!hard) return;
        this._emit("reset", true);
        for (let i = 0; i < 4; ++i) {
            this.counter[i] = 0;
            this.registers[i] = 0;
            // Real hardware would be volumeTable[0] but that's really quite loud and surprising...
            this.volume[i] = volumeTable[8];
        }
        this.noisePoked();
        this.lastRunEpoch = this.scheduler.epoch;
    }
 
    enable(e) {
        this.enabled = e;
    }
 
    mute() {
        this.enable(false);
    }
 
    unmute() {
        this.enable(true);
    }
}
 
/**
 * AtomSoundChip -- Acorn Atom sound via a 1-bit speaker driven by the PPIA.
 * Uses only the sine channel (shared with BBC for tape tones) and a speaker
 * channel with DC-blocking filter.
 */
export class AtomSoundChip extends SoundChip {
    constructor(onBuffer, { cpuSpeed = 1000000, onEvent = null } = {}) {
        super(onBuffer, { onEvent });
        this.samplesPerCycle = this.soundchipFreq / cpuSpeed;
        this.secondsPerCycle = 1 / cpuSpeed;
 
        // Replace the BBC tone/noise generators with just sine + speaker.
        this.generators = [this.sineChannel.bind(this), this.speakerChannel.bind(this)];
        // Recompute sine attenuation for the Atom's 2-channel mix
        // (parent computed it for 5 BBC channels).
        this.sineTable = makeSineTable(1 / this.generators.length);
 
        this.speakerGenerator = {
            mute: () => {
                this.catchUp();
                this.speakerReset();
            },
            pushBit: (bit, cycles, seconds) => {
                this.catchUp();
                this.updateSpeaker(bit, cycles, seconds);
            },
        };
 
        this.bitChange = [];
        this.speakerBit = 0.0;
        this.currentSpeakerBit = 0.0;
        this._speakerPrevIn = 0;
        this._speakerPrevOut = 0;
        this._speakerCycleOffset = 0;
 
        Object.assign(this.eventHandlers, {
            bit: (bit, { cycle }) => this.bitChange.push({ bit, cycles: cycle }),
            speakerReset: () => this.speakerReset(),
        });
    }
 
    reset(hard) {
        super.reset(hard);
        Eif (hard) this.speakerReset();
    }
 
    catchUp() {
        this._speakerCycleOffset = 0;
        super.catchUp();
        this._speakerCycleOffset = 0;
    }
 
    renderAt(cycle, out, offset, length) {
        this._speakerCycleOffset = 0;
        super.renderAt(cycle, out, offset, length);
    }
 
    snapshotState() {
        return { ...super.snapshotState(), speakerBit: this.speakerBit };
    }
 
    restoreState(state) {
        this.bitChange = [];
        this.speakerBit = this.currentSpeakerBit = state.speakerBit ?? 0.0;
        // Held at its level, so the DC blocker has settled.
        this._speakerPrevIn = this.currentSpeakerBit * speakerVolume;
        this._speakerPrevOut = 0;
        this._speakerCycleOffset = 0;
        super.restoreState(state);
    }
 
    speakerReset() {
        this._emit("speakerReset", true);
        this.bitChange = [];
        this.speakerBit = 0.0;
        this.currentSpeakerBit = 0.0;
        this._speakerPrevIn = 0;
        this._speakerPrevOut = 0;
        this._speakerCycleOffset = 0;
    }
 
    speakerChannel(channel, out, offset, length) {
        const fromCycle = this.lastRunEpoch + this._speakerCycleOffset;
        this._speakerCycleOffset += length / this.samplesPerCycle;
        let bitIndex = 0;
        // DC-blocking high-pass filter: y[n] = x[n] - x[n-1] + alpha * y[n-1]
        // The SoundChip runs at 500 kHz (4 MHz / 8). For a ~20 Hz cutoff:
        // alpha = 1 - 2*pi*fc/fs = 1 - 2*pi*20/500000 ≈ 0.99975
        const alpha = 0.99975;
 
        for (let i = 0; i < length; ++i) {
            while (
                bitIndex < this.bitChange.length &&
                this.bitChange[bitIndex].cycles <= fromCycle + i / this.samplesPerCycle
            ) {
                this.currentSpeakerBit = this.bitChange[bitIndex].bit;
                bitIndex++;
            }
            const input = this.currentSpeakerBit * speakerVolume;
            this._speakerPrevOut = input - this._speakerPrevIn + alpha * this._speakerPrevOut;
            this._speakerPrevIn = input;
            out[i + offset] += this._speakerPrevOut;
        }
 
        if (bitIndex > 0) {
            this.bitChange.splice(0, bitIndex);
        }
    }
 
    updateSpeaker(value, microCycle, seconds) {
        const cycles = microCycle + seconds / this.secondsPerCycle;
        const bit = value ? 1.0 : 0.0;
        this.speakerBit = bit;
        if (this._onEvent) this._send({ cycle: cycles, kind: "bit", value: bit });
        else this.bitChange.push({ bit, cycles });
    }
}
 
/**
 * InstrumentedSoundChip - wraps a real SoundChip and captures all writes
 * for debugging purposes. Provides the same interface as SoundChip.
 */
export class InstrumentedSoundChip extends SoundChip {
    constructor() {
        super(() => {}); // no audio output callback needed in headless mode
        this._capturedWrites = [];
        this._capturing = false;
        this._totalCycles = 0;
    }
 
    poke(value) {
        // Bring _totalCycles up to now first: it only moves when the chip
        // catches up, so without this each write would carry the time of the
        // write before it.
        this.catchUp();
        Eif (this._capturing) {
            this._capturedWrites.push({ cycle: this._totalCycles, value });
        }
        super.poke(value);
    }
 
    /** Start capturing SN76489 writes. Clears any previous capture. */
    startCapture() {
        this._capturedWrites = [];
        this._capturing = true;
    }
 
    /** Stop capturing and return the captured writes. */
    stopCapture() {
        this._capturing = false;
        return this._capturedWrites;
    }
 
    /** Track total cycles for timestamps. Called by the scheduler. */
    advance(cycles) {
        this._totalCycles += cycles;
        super.advance(cycles);
    }
 
    /** Runs `run`, a replay of the machine's past, leaving out of the capture what it writes and the cycles it takes. */
    withoutCapturing(run) {
        // Caught up either side, so that the cycles owed to the chip are only those the machine runs forward.
        this.catchUp();
        const [writes, totalCycles] = [this._capturedWrites.length, this._totalCycles];
        try {
            return run();
        } finally {
            this.catchUp();
            this._capturedWrites.length = writes;
            this._totalCycles = totalCycles;
        }
    }
 
    /** Read current SN76489 register state in a friendly format. */
    getState() {
        return {
            tone: [this.registers[0], this.registers[1], this.registers[2]],
            noise: this.registers[3],
            volume: [this.attenuation(0), this.attenuation(1), this.attenuation(2), this.attenuation(3)],
            lfsr: this.lfsr,
            latchedRegister: this.latchedRegister,
        };
    }
}
 
export class FakeSoundChip {
    reset() {}
 
    enable() {}
 
    catchUp() {}
 
    mute() {}
 
    unmute() {}
 
    render() {}
 
    withoutCapturing(run) {
        return run();
    }
 
    updateSlowDataBus() {}
 
    setScheduler() {}
 
    constructor() {
        this.toneGenerator = {
            mute: () => {},
            tone: () => {},
        };
        this.speakerGenerator = {
            mute: () => {},
            pushBit: () => {},
        };
    }
 
    snapshotState() {
        return {};
    }
 
    restoreState() {}
}