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 | 9x 9x 9x 9x 9x 9x 9x 9x 55x 55x 55x 55x 55x 55x 55x 55x 632x 632x 632x 8x 8x 8x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 55x 519x 30x 1x 1x 57x 6x 32x 32x 95x 95x 95x 95x 95x 32x 63x 61x 2x 3x 190x 269x 187x 187x 187x 187x 186x 185x 154x 153x 153x 153x 153x 121x 121x 121x 121x 153x 153x 153x 9x 1x 1x 8x 8x 9x 9x 14x 14x 636x 831x 831x 714x 831x 831x 544x 544x 544x 157x 157x 5x 4x 4x 4x 4x 683x 676x 696x 18x 18x 678x 678x 678x 678x 696x 680x 680x 680x 680x 680x 633x 499x 499x 499x 134x 633x 633x 633x 2x 632x 632x 632x 632x 632x 632x 632x 632x 632x 290x 290x 290x 5x 5x 290x 632x 1x 1x 1x 632x 679x 679x 5x 4x 4x 4x 3x 3x 1x 533x 533x 533x 533x 175x 358x 175x 175x | import { FramesPerSecond, TickMs } from "../emulation-tick.js";
import { noteError, noteFeature } from "./analytics.js";
import { toast } from "./toast.js";
import { shortcutLabel } from "./shortcuts.js";
export const RewindCaptureInterval = 50; // emulated frames, ~1 second
/**
* Why the machine is or is not running: stopped until it is first started, then
* running, paused, debugging (the debugger is shown exactly then; a breakpoint or
* an error lands here too) or stepping (one frame, then paused again).
*/
export const RunMode = Object.freeze({
stopped: "stopped",
running: "running",
paused: "paused",
debugging: "debugging",
stepping: "stepping",
});
// Under ?audioDebug, one console line per second in which the emulator sat
// idle between ticks or a tick ran long, or the audio queue underran or
// dropped, so a click can be matched to a cause. The sound chip posts samples
// throughout execute(), so only the idle time starves the audio queue.
const AudioDebugLogIntervalMs = 1000;
const AudioDebugSlowTickMs = 30;
const AudioDebugSlowPresentMs = 30;
const VirtualMhzUpdateMs = 3333;
const DefaultBenchmarkCycles = 10 * 1000 * 1000;
const BenchmarkFrameSkip = 1000000;
class VirtualSpeedUpdater {
constructor(cpuSpeed) {
this.cpuSpeed = cpuSpeed;
this.cycles = 0;
this.time = 0;
this.v = document.querySelector(".virtualMHz");
this.normalIcon = document.getElementById("speed-normal");
this.turboIcon = document.getElementById("speed-turbo");
this.speedy = false;
this.display();
}
update(cycles, time, speedy) {
this.cycles += cycles;
this.time += time;
if (speedy === this.speedy) return;
this.speedy = speedy;
this.normalIcon.hidden = speedy;
this.turboIcon.hidden = !speedy;
}
display() {
Iif (this.cycles) {
const thisMHz = this.cycles / this.time / 1000;
this.v.textContent = thisMHz.toFixed(1);
if (this.cycles >= 10 * this.cpuSpeed) {
this.cycles = this.time = 0;
}
}
setTimeout(() => this.display(), VirtualMhzUpdateMs);
}
}
/**
* Runs the machine in real time: the tick that turns wall-clock time into
* cycles, starting and stopping, the audio lead, fast-forward and the speed
* readout. Owns `running`, and dispatches a "running" event whenever it
* changes hands, "tick" on every timer tick and on every vsync that runs the
* machine (the first tick only takes the time), "frame-capture" after a tick
* that ends an emulated frame's worth of cycles (at most one a tick), and
* "rewind-capture" straight after one that ends RewindCaptureInterval frames'
* worth, for whoever keeps the machine's history.
*
* `mode` is a RunMode. Anything that needs the machine held still while it
* works (a dialog, a snapshot, the rewind panel, a hidden tab) takes a `hold()`,
* which stops it without changing the mode; it runs again once every hold has
* let go, if the mode still wants it running.
*/
export class EmulationLoop extends EventTarget {
constructor({
processor,
display,
audioHandler,
dbgr,
gamepad,
clocksPerSecond,
cpuSpeed,
fastTape,
audioStatsNode,
}) {
super();
this.processor = processor;
this.display = display;
this.audioHandler = audioHandler;
this.dbgr = dbgr;
this.gamepad = gamepad;
this.clocksPerSecond = clocksPerSecond;
this.maxCyclesPerTick = clocksPerSecond / 10;
this.frameCycles = clocksPerSecond / FramesPerSecond;
this.rewindCaptureCycles = RewindCaptureInterval * this.frameCycles;
this.fastTape = fastTape;
this.audioStatsNode = audioStatsNode;
this.mode = RunMode.stopped;
this.running = false;
this.fastAsPossible = false;
this.emulatedTo = 0;
this.lastEnd = 0;
this.nextTickDue = 0;
this.tickToken = null;
this.vsyncToken = null;
this.emulationLeadMs = 0;
this.frameCycleCounter = 0;
this.rewindCycleCounter = 0;
this.holds = new Set();
this.resumeOnVisible = null;
this.lockstep = null;
this.virtualSpeedUpdater = new VirtualSpeedUpdater(cpuSpeed);
this.audioDebugLog = { start: 0, ticks: 0, cycles: 0, maxIdle: 0, maxExecute: 0, maxPaint: 0, maxSnapshot: 0 };
document.addEventListener("visibilitychange", () => this.holdWhileHidden(), false);
}
isRunning() {
return this.running;
}
/**
* The machine's state is being replaced or previewed, so neither a debugger run to a stop nor the frames
* captured before ("replacing-state") apply.
*/
replacingState() {
this.dbgr.replacingState();
this.dispatchEvent(new Event("replacing-state"));
}
go() {
this.setMode(RunMode.running);
}
/** Runs one frame from a pause, then pauses again. */
step() {
this.setMode(RunMode.stepping);
}
stop(debug) {
this.setMode(debug ? RunMode.debugging : RunMode.paused);
if (debug) this.dbgr.debug(this.processor.pc);
}
setMode(mode) {
const wasPaused = this.isPaused();
this.mode = mode;
if (this.isPaused() !== wasPaused) noteFeature("pause", wasPaused ? "leave" : "enter");
if (mode !== RunMode.debugging) this.dbgr.hide();
if (!this.wanted()) {
if (this.running) this.halt();
} else if (this.holds.size === 0) {
this.start();
} else {
console.warn(
`Emulator held by ${[...this.holds].map((hold) => hold.reason).join(", ")}; it runs when they let go`,
);
}
}
// A step is taken inside a pause, not out of it.
isPaused() {
return this.mode === RunMode.paused || this.mode === RunMode.stepping;
}
wanted() {
return this.mode === RunMode.running || this.mode === RunMode.stepping;
}
/**
* Holds the machine stopped until the returned function is called. Holds
* nest, and letting go twice counts once. `reason` names the holder when a
* go() has to wait, so a hold that is never released can be found.
*/
hold(reason) {
if (this.holds.size === 0 && this.running) this.halt();
const hold = { reason };
this.holds.add(hold);
return () => {
if (!this.holds.delete(hold)) return;
if (this.holds.size === 0 && this.wanted()) this.start();
};
}
start() {
if (this.running) return;
this.audioHandler.unmute();
this.running = true;
this.dispatchEvent(new Event("running"));
this.run();
}
halt() {
this.running = false;
this.dispatchEvent(new Event("running"));
this.processor.stop();
this.audioHandler.mute();
}
run() {
this.nextTickDue = 0;
this.scheduleTick(0);
this.scheduleVsyncTick();
}
toggleFastAsPossible() {
if (this.lockstep) {
toast("Turbo is not available in a shared session.", { title: "Turbo" });
return;
}
this.fastAsPossible = !this.fastAsPossible;
noteFeature("turbo", this.fastAsPossible ? "enter" : "leave");
const [now, next] = this.fastAsPossible ? ["on", "off"] : ["off", "on"];
toast(`Turbo is ${now}. ${shortcutLabel("Alt-T")} turns it ${next}.`, { title: "Turbo" });
}
/**
* Hands the running of the machine to a shared session's lockstep
* (src/lockstep.js), whose `execute(cycles)` stands in for the processor's, or
* back with null. While it lasts the loop runs nothing only this machine would:
* no speedy frame skip, no gamepad keys, and no pause in a hidden tab.
*/
setLockstep(lockstep) {
this.lockstep = lockstep;
this.holdWhileHidden();
}
execute(cycles) {
return this.lockstep ? this.lockstep.execute(cycles) : this.processor.execute(cycles);
}
// A user-blocking task runs ahead of rendering and ordinary timers, so a stuck
// compositor does not hold the tick off too.
scheduleTick(delayMs) {
const token = (this.tickToken = {});
const fire = () => {
if (this.tickToken === token) this.tick();
};
Iif (window.scheduler?.postTask) window.scheduler.postTask(fire, { delay: delayMs, priority: "user-blocking" });
else window.setTimeout(fire, delayMs);
}
// Booked from the previous due time, not from now, so the period averages
// TickMs and a flyback lands at the same point of a tick every frame. A tick
// a whole period late starts afresh rather than a burst of catch-up ticks.
nextTickDelay(now) {
if (now - this.nextTickDue > TickMs) this.nextTickDue = now;
this.nextTickDue += TickMs;
return this.nextTickDue - now;
}
scheduleVsyncTick() {
const token = (this.vsyncToken = {});
window.requestAnimationFrame((vsyncTime) => {
if (this.vsyncToken !== token || !this.running) return;
this.scheduleVsyncTick();
this.vsyncTick(vsyncTime);
});
}
// Emulates up to the vsync and presents at once, so a flyback is shown at the
// first vsync after it; two share a refresh only if a timer tick reached the
// next flyback before this callback ran.
vsyncTick(vsyncTime) {
// While speedy the timer ticks run flat out.
if (this.emulatedTo !== 0 && !this.isSpeedy() && vsyncTime > this.emulatedTo) this.advance(vsyncTime, false);
this.display.present(vsyncTime);
}
isSpeedy() {
if (this.lockstep) return false;
return this.fastAsPossible || (this.fastTape && this.processor.tapeInterface.motorOn);
}
tick() {
if (!this.running) {
this.emulatedTo = 0;
return;
}
const now = performance.now();
const speedy = this.isSpeedy();
this.display.setSpeedy(speedy);
this.scheduleTick(speedy ? 0 : this.nextTickDelay(now));
this.advance(now, speedy);
}
advance(now, speedy) {
// now can be a vsync timestamp, before this ran; the timings use start.
const start = performance.now();
const { processor, display, audioHandler } = this;
if (!this.lockstep) this.gamepad.update(processor);
this.dispatchEvent(new Event("tick"));
if (this.emulatedTo !== 0) {
let cycles;
if (!speedy) {
const sinceLast = Math.max(0, now - this.emulatedTo);
cycles = (sinceLast * this.clocksPerSecond) / 1000;
cycles = Math.min(cycles, this.maxCyclesPerTick);
} else {
cycles = this.frameCycles;
}
cycles |= 0;
try {
if (!this.execute(cycles)) {
this.stop(true);
}
audioHandler.flushChipEvents();
const end = performance.now();
this.virtualSpeedUpdater.update(cycles, end - start, speedy);
const paintMs = display.takePaintMs();
let snapshotMs = 0;
this.frameCycleCounter += cycles;
this.rewindCycleCounter += cycles;
const rewindDue = this.rewindCycleCounter >= this.rewindCaptureCycles;
if (rewindDue || this.frameCycleCounter >= this.frameCycles) {
// A tick of several frames captures once, and leaves no backlog of frames behind it.
this.frameCycleCounter %= this.frameCycles;
this.dispatchEvent(new Event("frame-capture"));
if (rewindDue) {
this.rewindCycleCounter -= this.rewindCaptureCycles;
this.dispatchEvent(new Event("rewind-capture"));
}
snapshotMs = performance.now() - end;
}
Iif (this.audioStatsNode)
this.logAudioDebugTick(
start,
cycles,
speedy ? 0 : start - this.lastEnd,
end - start,
paintMs,
snapshotMs,
);
} catch (e) {
noteError("loop", e);
this.stop(true);
throw e;
}
if (this.mode === RunMode.stepping) this.stop(false);
}
this.emulatedTo = Math.max(this.emulatedTo, now);
this.lastEnd = performance.now();
}
// A change of audio buffer depth is taken by the picture, not the sound:
// gaining lead emulates ahead at once; losing it moves `emulatedTo` forward
// so the ticks emulate nothing until the queue has drained by that much.
setEmulationLead(leadMs) {
if (!this.running) return;
const aheadMs = leadMs - this.emulationLeadMs;
this.emulationLeadMs = leadMs;
if (aheadMs > 0) {
Iif (!this.execute((aheadMs * this.clocksPerSecond) / 1000)) this.stop(true);
this.audioHandler.flushChipEvents();
} else {
this.emulatedTo -= aheadMs;
}
}
holdWhileHidden() {
const { processor } = this;
const motorOn = processor.tapeInterface.motorOn || processor.fdc.motorOn[0] || processor.fdc.motorOn[1];
const holdWanted = document.visibilityState === "hidden" && !this.lockstep && !motorOn;
if (holdWanted && !this.resumeOnVisible) {
this.resumeOnVisible = this.hold("the hidden tab");
} else if (!holdWanted && this.resumeOnVisible) {
this.resumeOnVisible();
this.resumeOnVisible = null;
}
}
logAudioDebugTick(now, cycles, idleMs, executeMs, paintMs, snapshotMs) {
const log = this.audioDebugLog;
if (log.start === 0) log.start = now;
log.ticks++;
log.cycles += cycles;
log.maxIdle = Math.max(log.maxIdle, idleMs);
log.maxExecute = Math.max(log.maxExecute, executeMs);
log.maxPaint = Math.max(log.maxPaint, paintMs);
log.maxSnapshot = Math.max(log.maxSnapshot, snapshotMs);
if (now - log.start < AudioDebugLogIntervalMs) return;
const audio = this.audioHandler.takeEventCounts();
const present = this.display.takePresentMs();
const leadMin = Number.isFinite(audio.leadMinMs) ? `${audio.leadMinMs.toFixed(1)}ms` : "(no stats)";
if (
log.maxIdle > AudioDebugSlowTickMs ||
log.maxExecute > AudioDebugSlowTickMs ||
present > AudioDebugSlowPresentMs ||
audio.stall ||
audio.skip
) {
console.log(
`${(now / 1000).toFixed(0)}s: ${log.ticks} ticks emulating ${((1000 * log.cycles) / this.clocksPerSecond).toFixed(0)}ms, ` +
`idle max ${log.maxIdle.toFixed(0)}ms, ` +
`execute max ${log.maxExecute.toFixed(0)}ms (paint ${log.maxPaint.toFixed(1)}ms), ` +
`present max ${present.toFixed(0)}ms, snapshot ${log.maxSnapshot.toFixed(1)}ms; ` +
`audio lead min ${leadMin}, stalls ${audio.stall}, skipped ${audio.skip.toFixed(0)}ms`,
);
}
log.start = now;
log.ticks = log.cycles = log.maxIdle = log.maxExecute = log.maxPaint = log.maxSnapshot = 0;
}
benchmarkCpu(numCycles) {
this._timeCycles("cycles", numCycles, (cycles) => this.processor.execute(cycles));
}
benchmarkVideo(numCycles) {
this._timeCycles("video cycles", numCycles, (cycles) => this.display.video.polltime(cycles));
}
_timeCycles(label, numCycles, run) {
numCycles = numCycles || DefaultBenchmarkCycles;
const oldFS = this.display.frameSkip;
this.display.frameSkip = BenchmarkFrameSkip;
const startTime = performance.now();
run(numCycles);
const msTaken = performance.now() - startTime;
this.display.frameSkip = oldFS;
console.log(`Took ${msTaken}ms to execute ${numCycles} ${label}`);
console.log(`Virtual ${(numCycles / msTaken / 1000).toFixed(2)}MHz`);
}
profileCpu(arg) {
console.profile("CPU");
this.benchmarkCpu(arg);
console.profileEnd();
}
profileVideo(arg) {
console.profile("Video");
this.benchmarkVideo(arg);
console.profileEnd();
}
}
|