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 | 18x 18x 18x 18x 18x 18x 18x 18x 270x 270x 18x 215x 215x 1761280x 215x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 205x 1x 1x 1x 1x 1x 1x 1x 205x 96x 1x 910x 99x 99x 99x 13118x 13118x 13911x 70045440x 70045440x 833060x 833060x 833060x 69212380x 69212380x 41724x 41724x 41724x 52534080x 52534080x 273407x 273407x 236x 236x 61x 61x 13908x 13908x 13908x 13908x 13908x 13908x 17511360x 17511360x 14288x 14288x 14288x 18013084x 14288x 13911x 69546x 14288x 14288x 14288x 14288x 18013084x 18013084x 18013084x 18013084x 14288x 14288x 305x 305x 305x 125x 125x 125x 1x 125x 7x 505x 505x 7x 13x 5x 5x 5x 5x 8x 8x 8x 2x 6x 6x 6x 6x 4x 4x 302x 302x 302x 237x 237x 65x 302x 302x 171x 171x 131x 131x 66x 65x 50x 50x 50x 49x 94x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 38x 60x 59x 59x 236x 236x 236x 59x 59x 4x 3x 1x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 10x 1x 4x 4x 4x 4x 4x 4x 5x 5x 5x 5x 5x 748x 4x 4x 748x 748x 748x 748x 5x 3x 3x 3x 3x 2x 24x 24x 1x 1x | // 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;
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;
// 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);
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) {
if (this._onEvent) this._onEvent({ cycle: this.scheduler.epoch, kind, value });
}
/** 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) {
Eif (!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;
}
}
toneChannel(channel, out, offset, length) {
const reg = this.registers[channel] === 0 ? 1024 : this.registers[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.registers[channel - 1];
}
}
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;
}
}
debugPokeAll(c0, v0, c1, v1, c2, v2, c3, v3) {
this.catchUp();
this.registers[0] = c0 & 0xffffff;
this.registers[1] = c1 & 0xffffff;
this.registers[2] = c2 & 0xffffff;
this.registers[3] = c3 & 0xffffff;
this.volume[0] = volumeTable[v0];
this.volume[1] = volumeTable[v1];
this.volume[2] = volumeTable[v2];
this.volume[3] = volumeTable[v3];
this.noisePoked();
this._emit("state", this.snapshotState());
}
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) {
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;
}
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;
if (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 Iif (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,
};
}
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;
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.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);
if (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);
}
speakerReset() {
this._emit("speakerReset", true);
this.bitChange = [];
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;
if (this._onEvent) this._onEvent({ 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) {
if (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;
}
/** Get the captured writes without stopping. */
getCapturedWrites() {
return this._capturedWrites;
}
/** Clear captured writes. */
clearCapture() {
this._capturedWrites = [];
}
/** Track total cycles for timestamps. Called by the scheduler. */
advance(cycles) {
this._totalCycles += cycles;
super.advance(cycles);
}
/** 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._attenuationFromVolume(0),
this._attenuationFromVolume(1),
this._attenuationFromVolume(2),
this._attenuationFromVolume(3),
],
lfsr: this.lfsr,
latchedRegister: this.latchedRegister,
};
}
/** Convert internal float volume back to 0-15 attenuation. */
_attenuationFromVolume(channel) {
const v = this.volume[channel];
// volumeTable[15] = 0 (silent), volumeTable[0] = loudest
for (let i = 0; i < 16; i++) {
if (Math.abs(volumeTable[i] - v) < 0.001) return i;
}
return 15; // silent
}
}
export class FakeSoundChip {
reset() {}
enable() {}
catchUp() {}
mute() {}
unmute() {}
render() {}
updateSlowDataBus() {}
setScheduler() {}
constructor() {
this.toneGenerator = {
mute: () => {},
tone: () => {},
};
this.speakerGenerator = {
mute: () => {},
pushBit: () => {},
};
}
snapshotState() {
return {};
}
restoreState() {
this._speakerCycleOffset = 0;
}
}
|