All files / src via.js

97.86% Statements 641/655
92.37% Branches 303/328
96.25% Functions 77/80
98.63% Lines 577/585

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 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078    137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x       137x 137x 137x 137x 137x 137x 137x 137x 137x 137x 137x     137x 137x       137x     137x       137x 137x 137x     137x 137x       1818x 1818x 1818x   1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x 1818x   8654x 1818x 1818x 1818x 1818x           2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x 2745x       7101427x       7100930x       140x       930x       29x 29x 29x         4x       6625921x 6625921x 519x 370x 370x   6625402x 6625921x       8654x       6622999x 6622999x 6622999x 6622999x       72715x 72715x 72715x 72715x 70535x   72715x 318x 72397x 36636x 36636x 35757x         2180x 1090x 202x 202x 202x 202x   1090x   2180x 2180x           318x 318x 318x 286x 286x 286x 286x 10x 10x 10x 10x   286x   318x 318x       881x 4x 4x 4x 4x   881x 881x                   50x 50x 50x 50x 5x 5x   45x 29x 4x 4x   25x   25x 25x       2797x 2797x         56x       251x               450x 450x 3x 3x   447x 447x 447x 447x 397x 200x 200x 197x 23x 12x 12x   11x   50x 24x 24x 3x 3x     432x         75x 30x 15x   45x 23x   38x 3x 3x         215x 215x 215x 215x 79x 79x       47x       18x 18x       71648x 819x 819x   70829x 70829x         202154x   202154x 202154x   15x 15x   15x   15x       15x 15x   15x 15x   1x 14x   3x 3x   15x     66840x 66840x 66840x     2043x 2043x   2043x   2043x   2043x 2043x   2043x 2043x   1x 2042x   3x 3x   2043x     744x 744x 744x     61x 61x 61x     76x 76x 76x 52x 52x   76x 76x 76x 76x 48x   76x 43x 43x 15x 15x 28x 1x     76x 76x       131224x 131224x 65636x 131224x 131224x 131224x     29x 29x 29x       18x 18x 18x     6x 6x 6x 6x 6x   6x     18x 18x 18x 18x 18x 18x 18x   18x 18x 18x     56x 56x 56x 56x     56x 56x 56x 27x 27x 27x   29x 29x   56x 56x 56x   56x 56x 56x     81x 45x 81x 81x     887x 887x 887x 887x 887x         2110x 2110x   17x 17x 17x     422x 422x   32x 32x 32x 32x 32x   18x 18x 18x   18x   44x 43x 43x   44x   21x 21x   2110x         6409631x 6409631x         4422x 1474x                 6411741x           800513x     400082x 400082x 400082x     400082x         400082x     400059x   400060x   401533x   401533x     401538x     401534x     401562x     401550x 401540x     400078x   400059x   400095x   400535x   401010x                               35x       70604x 70604x 70604x 70604x       2434x 2434x   2434x 2434x   21x 1x         1x             2434x       440x                                                                         368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 1x   368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x       134383x 134383x 134383x 67186x 67186x 67186x 67186x   1x     134383x       138998x 131331x 131331x 131331x 131331x 133x 133x 88x 88x         447x 446x 446x 221x 221x 221x 221x   2x     446x 446x       20x 12x 12x 12x 12x 4x 4x 2x 2x             896x   896x 896x 896x 896x 896x 896x 896x 896x 896x 896x 896x 896x 896x   896x       1358x 1358x   1358x       5057x 5057x 5057x       1872x 1872x 1872x 1872x       220x                 184x 184x 184x 184x 5x     184x       5x       5x       897x       3194x         60x 60x       11502x 3703x 30241x   1627x 266x 266x 1361x 5x   1627x     2076x 2076x 2076x   7799x         7799x 7799x 7799x 7799x 7582x 217x 217x     7799x 975x 975x     6824x               284x 283x 283x       6929x 20x           1480x               25x 25x 25x 25x 25x 25x 129x 129x 25x 25x   104x         38194x 34672x 34672x 234806x   32042x       4967x 4967x       2399x 2398x       2399x 2399x 2399x 891x   2399x   2399x   2399x     2399x               6325x 6325x 6325x 6325x                           153x 153x 4x 4x                 298x 298x 298x 298x         382x 191x         3x           922x 922x 922x       35x       35x      
import { BBC, getKeyMap, WithKeyMatrix } from "./keymap.js";
 
const ORB = 0x0,
    ORA = 0x1,
    DDRB = 0x2,
    DDRA = 0x3,
    T1CL = 0x4,
    T1CH = 0x5,
    T1LL = 0x6,
    T1LH = 0x7,
    T2CL = 0x8,
    T2CH = 0x9,
    SR = 0xa,
    ACR = 0xb,
    PCR = 0xc,
    IFR = 0xd,
    IER = 0xe,
    ORAnh = 0xf,
    TIMER1INT = 0x40,
    TIMER2INT = 0x20,
    INT_CA1 = 0x02,
    INT_CA2 = 0x01,
    INT_CB1 = 0x10,
    INT_CB2 = 0x08,
    INT_SR = 0x04;
 
// The shift register's modes, ACR bits 2 to 4. Bit 2 of the mode is set for the shifts out, and modes 3 and 7 take
// their clock from CB1.
const ShiftDisabled = 0,
    ShiftInT2 = 1,
    ShiftOutFreeRunningT2 = 4,
    ShiftOutT2 = 5,
    ShiftOut = 4,
    AcrShiftModeShift = 2,
    AcrShiftMode = 0x1c,
    AcrShiftExternal = 0x0c;
const T2ClockedShiftModes = (1 << ShiftInT2) | (1 << ShiftOutFreeRunningT2) | (1 << ShiftOutT2);
const BitsPerShift = 8;
const TicksPerViaCycle = 2;
// The first edge of a φ2-clocked shift comes two cycles after the SR access, and a shift in sets its flag a cycle
// after its last rising edge. Both from MAME's 6522via.cpp, as beebjit models only the free-running mode.
const Phi2FirstEdgeTicks = 2 * TicksPerViaCycle;
const ShiftInFlagDelayTicks = TicksPerViaCycle;
 
// Pulse mode holds CA2/CB2 low for one 1MHz VIA cycle, here in the scheduler's 2MHz ticks.
// Figures 3-4 and 3-6 of https://6502.org/documents/datasheets/wdc/wdc_w65c22s_mar_2004.pdf
const PulseWidthCycles = 2;
 
// Reset makes every pin an input, and undriven inputs float high.
const IdlePins = 0xff;
 
// The autoscan counter steps through 16 columns, one per 1MHz cycle (two 2MHz scheduler ticks), of which the keyboard
// wires 10 on a B and 13 on a Master.
const ScanCounterColumns = 16;
const TicksPerScanColumn = 2;
const KeyboardColumns = 13;
 
// The joystick FIRE buttons pull PB4 and PB5 low (AUG p418).
const JoystickFire1 = 1 << 4;
const JoystickFire2 = 1 << 5;
 
class Via {
    constructor(cpu, scheduler, irq) {
        this.cpu = cpu;
        this.irq = irq;
        this.scheduler = scheduler;
 
        this.ora = 0;
        this.orb = 0;
        this.ira = 0;
        this.irb = 0;
        this.ddra = 0;
        this.ddrb = 0;
        this.sr = 0;
        this.t1l = 0;
        this.t2l = 0;
        this.t1c = 0;
        this.t2c = 0;
        this.acr = 0;
        this.pcr = 0;
        this.ifr = 0;
        this.ier = 0;
        this.t1hit = false;
        this.t2hit = false;
        this.t2High = 0;
        this.portapins = IdlePins;
        this.portbpins = IdlePins;
        this.ca1 = false;
        this.ca2 = false;
        this.cb1 = false;
        this.cb2 = false;
        this.ca2changecallback = null;
        this.cb2changecallback = null;
        this.justhit = 0;
        this.t1_pb7 = 0;
        this.shiftBits = BitsPerShift;
 
        this.task = this.scheduler.newTask(() => this._onTimeout());
        this.shiftTask = this.scheduler.newTask(() => this._onShiftEdge());
        this.ca2PulseTask = this.scheduler.newTask(() => this.setca2(true));
        this.cb2PulseTask = this.scheduler.newTask(() => this.setcb2(true));
        this.lastPolltime = 0;
    }
 
    reset() {
        // http://archive.6502.org/datasheets/mos_6522_preliminary_nov_1977.pdf
        // "Reset sets all registers to zero except t1 t2 and sr"
        this.ora = this.orb = 0x00;
        this.ddra = this.ddrb = 0x00;
        this.ifr = this.ier = 0x00;
        this.t1c = this.t1l = this.t2c = this.t2l = 0x1fffe;
        this.t1hit = this.t2hit = true;
        this.acr = this.pcr = 0;
        this.t2High = 0;
        this.t1_pb7 = 1;
        this.portapins = this.portbpins = IdlePins;
        this.ca2PulseTask.cancel();
        this.cb2PulseTask.cancel();
        this._stopShiftClockAtRest();
        this.shiftBits = BitsPerShift;
        this.updateNextTime();
    }
 
    _shiftMode() {
        return (this.acr & AcrShiftMode) >>> AcrShiftModeShift;
    }
 
    _t2ClocksShifter() {
        return !!((T2ClockedShiftModes >>> this._shiftMode()) & 1);
    }
 
    _t2CountsPulses() {
        return !!(this.acr & 0x20) && !this._t2ClocksShifter();
    }
 
    _t2ShiftPeriod() {
        return (this.t2l & 0x1fe) + 4;
    }
 
    _splitT2ForShifting() {
        const count = this.t2c + 1;
        this.t2High = (count >>> 9) & 0xff;
        this.t2c = (count & 0x1ff) - 1;
    }
 
    // Between an underflow and its relatch, t2High has already stepped down for it.
    _joinT2FromShifting() {
        this.t2c += (this.t2High + (this.t2c < -2 ? 1 : 0)) << 9;
    }
 
    updateNextTime() {
        let nextTimer = this.t1c;
        if (this._t2ClocksShifter()) {
            if (!this.t2hit) {
                const underflowsToWrap = this.t2High + (this.t2c < -2 ? 1 : 0);
                nextTimer = Math.min(this.t2c + underflowsToWrap * this._t2ShiftPeriod(), nextTimer);
            }
        } else if (!(this.acr & 0x20)) nextTimer = Math.min(this.t2c, nextTimer);
        this.task.reschedule(Math.max(1, nextTimer));
    }
 
    _onTimeout() {
        this._catchUp();
    }
 
    _catchUp() {
        const cycles = this.scheduler.epoch - this.lastPolltime;
        if (cycles) this._polltime(cycles);
        this.lastPolltime = this.scheduler.epoch;
        this.updateNextTime();
    }
 
    _polltime(cycles) {
        cycles |= 0;
        this.justhit = 0;
        const newT1c = this.t1c - cycles;
        if (newT1c < -2) this.t1c = this._handleT1c(newT1c);
        else this.t1c = newT1c;
 
        if (this._t2ClocksShifter()) {
            this._pollT2Shifting(cycles);
        } else if (!(this.acr & 0x20)) {
            const newT2c = this.t2c - cycles;
            if (newT2c < -2) this.t2c = this._handleT2c(newT2c);
            else this.t2c = newT2c;
        }
    }
 
    _handleT1c(newT1c) {
        if (newT1c < -2 && this.t1c > -3) {
            if (!this.t1hit) {
                this.ifr |= TIMER1INT;
                this.updateIFR();
                Eif (newT1c === -3) this.justhit |= 1;
                this.t1_pb7 = !this.t1_pb7;
            }
            if (!(this.acr & 0x40)) this.t1hit = true;
        }
        while (newT1c < -3) newT1c += this.t1l + 4;
        return newT1c;
    }
 
    // T2 high steps down as T2 low reaches FF (-3, as in 16-bit mode), and the relatch lands a cycle later. See
    // beebjit via.c via_shift_fired and make_timing_rom.c.
    _pollT2Shifting(cycles) {
        const period = this._t2ShiftPeriod();
        let newT2c = this.t2c - cycles;
        if (newT2c <= -3) {
            const firstUnderflow = this.t2c > -3 ? 0 : 1;
            const lastUnderflow = Math.floor((-3 - newT2c) / period);
            const underflows = lastUnderflow - firstUnderflow + 1;
            if (underflows > this.t2High && !this.t2hit) {
                this.ifr |= TIMER2INT;
                this.updateIFR();
                Eif (newT2c === -3 - (firstUnderflow + this.t2High) * period) this.justhit |= 2;
                this.t2hit = true;
            }
            this.t2High = (this.t2High - underflows) & 0xff;
        }
        if (newT2c < -4) newT2c += Math.ceil((-4 - newT2c) / period) * period;
        this.t2c = newT2c;
    }
 
    _handleT2c(newT2c) {
        if (!this.t2hit) {
            this.ifr |= TIMER2INT;
            this.updateIFR();
            Eif (newT2c === -3) this.justhit |= 2;
            this.t2hit = true;
        }
        newT2c += 0x20000;
        return newT2c;
    }
 
    /**
     * Reading or writing SR clears its flag, restarts an external clock's count of eight, and starts an internally
     * clocked shift unless one is under way. A write to one under way restarts its count without moving its clock,
     * and a read leaves it alone, as MAME's 6522via.cpp has it. The free-running mode, once started, runs until the
     * mode changes.
     */
    _accessShiftRegister(isWrite) {
        this.ifr &= ~INT_SR;
        this.updateIFR();
        const mode = this._shiftMode();
        if ((this.acr & AcrShiftExternal) === AcrShiftExternal) {
            this.shiftBits = BitsPerShift;
            return;
        }
        if (mode === ShiftDisabled) return;
        if (this._shiftUnderWay()) {
            if (isWrite) this.shiftBits = BitsPerShift;
            return;
        }
        this.shiftBits = BitsPerShift;
        // CB1 is the shift clock's output, which rests high.
        this.cb1 = true;
        this.shiftTask.reschedule(this._t2ClocksShifter() ? this._ticksToT2Underflow() : Phi2FirstEdgeTicks);
    }
 
    _stopShiftClockAtRest() {
        if (this.shiftTask.scheduled()) this.cb1 = true;
        this.shiftTask.cancel();
    }
 
    // Once a shift in's last bit is in, its task waits only to set the flag.
    _shiftUnderWay() {
        return this.shiftTask.scheduled() && !(this.shiftBits === 0 && this.cb1);
    }
 
    _ticksToT2Underflow() {
        return this.t2c + 3 + (this.t2c > -3 ? 0 : this._t2ShiftPeriod());
    }
 
    /**
     * An edge of an internal shift clock: T2's low byte reaching FF, as beebjit's via_shift_fired, or each φ2 cycle.
     * Bits go out on CB2 on the falling edge and come in from CB2 on the rising one, as in the 6522 datasheets.
     */
    _onShiftEdge() {
        this._catchUp();
        if (!this.shiftBits && this.cb1) {
            this._raiseShiftFlag();
            return;
        }
        const rising = !this.cb1;
        this.cb1 = rising;
        const mode = this._shiftMode();
        if (mode & ShiftOut) {
            if (!rising) {
                this._shiftOut();
                --this.shiftBits;
            } else if (!this.shiftBits) {
                if (mode !== ShiftOutFreeRunningT2) {
                    this._raiseShiftFlag();
                    return;
                }
                this.shiftBits = BitsPerShift;
            }
        } else if (rising) {
            this._shiftIn();
            if (!--this.shiftBits) {
                this.shiftTask.schedule(ShiftInFlagDelayTicks);
                return;
            }
        }
        this.shiftTask.schedule(this._t2ClocksShifter() ? this._ticksToT2Underflow() : TicksPerViaCycle);
    }
 
    /** Modes 3 and 7: an external clock on CB1 shifts in on its rising edges and out on its falling ones. */
    _clockShiftFromCb1(rising) {
        if (this.acr & (ShiftOut << AcrShiftModeShift)) {
            if (rising) return;
            this._shiftOut();
        } else {
            if (!rising) return;
            this._shiftIn();
        }
        if (!--this.shiftBits) {
            this.shiftBits = BitsPerShift;
            this._raiseShiftFlag();
        }
    }
 
    _shiftOut() {
        const bit = this.sr >>> 7;
        this.sr = ((this.sr << 1) | bit) & 0xff;
        const level = !!bit;
        if (level === this.cb2) return;
        this.cb2 = level;
        if (this.cb2changecallback) this.cb2changecallback(level, true);
    }
 
    _shiftIn() {
        this.sr = ((this.sr << 1) | (this.cb2 ? 1 : 0)) & 0xff;
    }
 
    _raiseShiftFlag() {
        this.ifr |= INT_SR;
        this.updateIFR();
    }
 
    updateIFR() {
        if (this.ifr & this.ier & 0x7f) {
            this.ifr |= 0x80;
            this.cpu.interrupt |= this.irq;
        } else {
            this.ifr &= ~0x80;
            this.cpu.interrupt &= ~this.irq;
        }
    }
 
    write(addr, val) {
        this._catchUp();
        let mode;
        val |= 0;
        switch (addr & 0xf) {
            case ORA:
                this.ifr &= ~INT_CA1;
                Eif ((this.pcr & 0x0a) !== 0x02) {
                    // b-em: Not independent interrupt for CA2
                    this.ifr &= ~INT_CA2;
                }
                this.updateIFR();
 
                // The strobe is "data ready": the port settles before CA2 falls.
                // http://archive.6502.org/datasheets/wdc_w65c22s_mar_2004.pdf figures 3-6 and 3-7.
                this.ora = val;
                this.recalculatePortAPins();
 
                mode = this.pcr & 0x0e;
                if (mode === 8) {
                    // Handshake mode
                    this.setca2(false);
                } else if (mode === 0x0a) {
                    // Pulse mode
                    this.setca2(false);
                    this.ca2PulseTask.reschedule(PulseWidthCycles);
                }
                break;
 
            case ORAnh:
                this.ora = val;
                this.recalculatePortAPins();
                break;
 
            case ORB:
                this.ifr &= ~INT_CB1;
                Eif ((this.pcr & 0xa0) !== 0x20) {
                    // b-em: Not independent interrupt for CB2
                    this.ifr &= ~INT_CB2;
                }
                this.updateIFR();
 
                this.orb = val;
                this.recalculatePortBPins();
 
                mode = (this.pcr & 0xe0) >>> 4;
                if (mode === 8) {
                    // Handshake mode
                    this.setcb2(false);
                } else if (mode === 0x0a) {
                    // Pulse mode
                    this.setcb2(false);
                    this.cb2PulseTask.reschedule(PulseWidthCycles);
                }
                break;
 
            case DDRA:
                this.ddra = val;
                this.recalculatePortAPins();
                break;
 
            case DDRB:
                this.ddrb = val;
                this.recalculatePortBPins();
                break;
 
            case ACR: {
                const wasShifting = this._t2ClocksShifter();
                const wasCountingPulses = this._t2CountsPulses();
                if ((this.acr ^ val) & AcrShiftMode) {
                    this._stopShiftClockAtRest();
                    this.shiftBits = BitsPerShift;
                }
                this.acr = val;
                Iif (this.justhit & 1 && !(val & 0x40)) this.t1hit = true;
                const isShifting = this._t2ClocksShifter();
                if (!wasShifting && isShifting) this._splitT2ForShifting();
                else if (wasShifting && !isShifting) this._joinT2FromShifting();
                // T2 ticks once more before freezing, and resumes a tick late. See beebjit via.c via_write_ACR.
                if (!isShifting) {
                    const isCountingPulses = this._t2CountsPulses();
                    if (!wasCountingPulses && isCountingPulses) {
                        this.t2c -= 2;
                        if (this.t2c < -2) this.t2c = this._handleT2c(this.t2c);
                    } else if (wasCountingPulses && !isCountingPulses) {
                        this.t2c += 2;
                    }
                }
                this.updateNextTime();
                break;
            }
 
            case PCR:
                this.pcr = val;
                if ((val & 0xe) === 0xc) this.setca2(false);
                else if (val & 0x08) this.setca2(true);
                Iif ((val & 0xe0) === 0xc0) this.setcb2(false);
                else if (val & 0x80) this.setcb2(true);
                break;
 
            case SR:
                this.sr = val;
                this._accessShiftRegister(true);
                break;
 
            case T1LL:
            case T1CL:
                this.t1l &= 0x1fe00;
                this.t1l |= val << 1;
                break;
 
            case T1LH:
                this.t1l &= 0x1fe;
                this.t1l |= val << 9;
                Eif (!(this.justhit & 1)) {
                    this.ifr &= ~TIMER1INT;
                    this.updateIFR();
                }
                break;
 
            case T1CH:
                this.t1l &= 0x1fe;
                this.t1l |= val << 9;
                this.t1c = this.t1l + 1;
                this.t1hit = false;
                Eif (!(this.justhit & 1)) {
                    this.ifr &= ~TIMER1INT;
                    this.updateIFR();
                }
                this.t1_pb7 = 0;
                this.updateNextTime();
                break;
 
            case T2CL:
                this.t2l &= 0x1fe00;
                this.t2l |= val << 1;
                if (this._t2ClocksShifter()) this.updateNextTime();
                break;
 
            case T2CH:
                this.t2l &= 0x1fe;
                this.t2l |= val << 9;
                if (this._t2ClocksShifter()) {
                    this.t2High = val;
                    this.t2c = (this.t2l & 0x1fe) + 1;
                    if (this._shiftUnderWay()) this.shiftTask.reschedule(this._ticksToT2Underflow());
                } else {
                    this.t2c = this.t2l + 1;
                    if (this.acr & 0x20) this.t2c -= 2;
                }
                Eif (!(this.justhit & 2)) {
                    this.ifr &= ~TIMER2INT;
                    this.updateIFR();
                }
                this.t2hit = false;
                this.updateNextTime();
                break;
 
            case IER:
                if (val & 0x80) this.ier |= val & 0x7f;
                else this.ier &= ~(val & 0x7f);
                this.updateIFR();
                break;
 
            case IFR:
                this.ifr &= ~(val & 0x7f);
                Iif (this.justhit & 1) this.ifr |= TIMER1INT;
                if (this.justhit & 2) this.ifr |= TIMER2INT;
                this.updateIFR();
                break;
        }
    }
 
    read(addr) {
        this._catchUp();
        switch (addr & 0xf) {
            case ORA:
                this.ifr &= ~INT_CA1;
                Eif ((this.pcr & 0xa) !== 0x2) this.ifr &= ~INT_CA2;
                this.updateIFR();
            /* falls through */
            case ORAnh:
                Eif (!(this.acr & 1)) this.recalculatePortAPins();
                break;
            case ORB:
                this.ifr &= ~INT_CB1;
                Eif ((this.pcr & 0xa0) !== 0x20) this.ifr &= ~INT_CB2;
                this.updateIFR();
                this.recalculatePortBPins();
                break;
            case T1CL:
                Eif (!(this.justhit & 1)) {
                    this.ifr &= ~TIMER1INT;
                    this.updateIFR();
                }
                break;
            case T2CL:
                if (!(this.justhit & 2)) {
                    this.ifr &= ~TIMER2INT;
                    this.updateIFR();
                }
                break;
            case SR:
                this._accessShiftRegister(false);
                break;
        }
        return this._registerValue(addr);
    }
 
    /** Reads a register as the CPU would, without clearing flags or driving the ports: the pins are as last driven. */
    peek(addr) {
        this._catchUp();
        return this._registerValue(addr);
    }
 
    /** The timers as 16-bit values, read as {@link peek} would; T2L, which no register reads back, as last written. */
    peekTimers() {
        const word = (low, high) => (this.peek(high) << 8) | this.peek(low);
        return {
            t1c: word(T1CL, T1CH),
            t1l: word(T1LL, T1LH),
            t2c: word(T2CL, T2CH),
            t2l: (this.t2l >>> 1) & 0xffff,
        };
    }
 
    _registerValue(addr) {
        switch (addr & 0xf) {
            case ORA:
            case ORAnh:
                // Reading ORA reads pin levels regardless of DDRA.
                // Of the various 6522 datasheets, this one is clear:
                // http://archive.6502.org/datasheets/wdc_w65c22s_mar_2004.pdf
                return this.acr & 1 ? this.ira : this.portapins;
 
            case ORB: {
                let temp = this.orb & this.ddrb;
                Iif (this.acr & 2) temp |= this.irb & ~this.ddrb;
                else temp |= this.portbpins & ~this.ddrb;
                // If PB7 is active, it is mixed in regardless of
                // whether bit 7 is an input or output.
                Iif (this.acr & 0x80) {
                    temp &= 0x7f;
                    temp |= this.t1_pb7 << 7;
                }
 
                return temp;
            }
            case DDRA:
                return this.ddra;
            case DDRB:
                return this.ddrb;
            case T1LL:
                return ((this.t1l & 0x1fe) >>> 1) & 0xff;
            case T1LH:
                return (this.t1l >>> 9) & 0xff;
 
            case T1CL:
                return ((this.t1c + 1) >>> 1) & 0xff;
 
            case T1CH:
                return ((this.t1c + 1) >>> 9) & 0xff;
 
            case T2CL:
                return ((this.t2c + 1) >>> 1) & 0xff;
 
            case T2CH:
                if (this._t2ClocksShifter()) return this.t2High;
                return ((this.t2c + 1) >>> 9) & 0xff;
 
            case SR:
                return this.sr;
            case ACR:
                return this.acr;
            case PCR:
                return this.pcr;
            case IER:
                return this.ier | 0x80;
            case IFR:
                return this.ifr;
            default:
                throw new Error("Unknown VIA read");
        }
    }
 
    // May be overridden in subclasses
    drivePortA() {}
 
    portAUpdated() {}
 
    drivePortB() {}
 
    portBUpdated() {}
 
    rawPortB() {
        return 0xff;
    }
 
    recalculatePortAPins() {
        this.portapins = this.ora & this.ddra;
        this.portapins |= ~this.ddra & 0xff;
        this.drivePortA();
        this.portAUpdated();
    }
 
    recalculatePortBPins() {
        const prevPb6 = !!(this.portbpins & 0x40);
        this.portbpins = (this.orb & this.ddrb) | (~this.ddrb & this.rawPortB());
 
        this.drivePortB();
        if (prevPb6 && !(this.portbpins & 0x40)) {
            // If we see a high to low transition on pb6, and we are in timer2 pulse counting mode, count a pulse.
            if (this._t2CountsPulses()) {
                this.t2c -= 2;
                // Not clear what happens here. Docs say:
                // "When the T2 counter reaches a count of zero, IFR5 is set and the counter continues to decrement with
                // each pulse on PB6. To enable IFR5 for subsequent countdowns, it is necessary to reload high order T2
                // counter."
                Iif (this.t2c < 0) {
                    this.t2c = 0xffff;
                    this.ifr |= TIMER2INT;
                    this.updateIFR();
                }
            }
        }
        this.portBUpdated();
    }
 
    snapshotState() {
        return {
            ora: this.ora,
            orb: this.orb,
            ira: this.ira,
            irb: this.irb,
            ddra: this.ddra,
            ddrb: this.ddrb,
            sr: this.sr,
            t1l: this.t1l,
            t2l: this.t2l,
            t1c: this.t1c,
            t2c: this.t2c,
            acr: this.acr,
            pcr: this.pcr,
            ifr: this.ifr,
            ier: this.ier,
            t1hit: this.t1hit,
            t2hit: this.t2hit,
            t2High: this.t2High,
            portapins: this.portapins,
            portbpins: this.portbpins,
            ca1: this.ca1,
            ca2: this.ca2,
            cb1: this.cb1,
            cb2: this.cb2,
            justhit: this.justhit,
            t1_pb7: this.t1_pb7,
            shiftBits: this.shiftBits,
            lastPolltime: this.lastPolltime,
            taskOffset: this.task.offset(),
            shiftTaskOffset: this.shiftTask.offset(),
            ca2PulseTaskOffset: this.ca2PulseTask.offset(),
            cb2PulseTaskOffset: this.cb2PulseTask.offset(),
        };
    }
 
    restoreState(state) {
        this.ora = state.ora;
        this.orb = state.orb;
        this.ira = state.ira;
        this.irb = state.irb;
        this.ddra = state.ddra;
        this.ddrb = state.ddrb;
        this.sr = state.sr;
        this.t1l = state.t1l;
        this.t2l = state.t2l;
        this.t1c = state.t1c;
        this.t2c = state.t2c;
        this.acr = state.acr;
        this.pcr = state.pcr;
        this.ifr = state.ifr;
        this.ier = state.ier;
        this.t1hit = state.t1hit;
        this.t2hit = state.t2hit;
        if (state.t2High !== undefined) this.t2High = state.t2High;
        else if (this._t2ClocksShifter()) this._splitT2ForShifting();
        else Ethis.t2High = 0;
        this.portapins = state.portapins;
        this.portbpins = state.portbpins;
        this.ca1 = state.ca1;
        this.ca2 = state.ca2;
        this.cb1 = state.cb1;
        this.cb2 = state.cb2;
        this.justhit = state.justhit;
        this.t1_pb7 = state.t1_pb7;
        this.shiftBits = state.shiftBits ?? BitsPerShift;
        this.lastPolltime = state.lastPolltime;
        this.updateIFR();
        this.task.restoreOffset(state.taskOffset);
        this.ca2PulseTask.restoreOffset(state.ca2PulseTaskOffset);
        this.cb2PulseTask.restoreOffset(state.cb2PulseTaskOffset);
        this.shiftTask.restoreOffset(state.shiftTaskOffset);
    }
 
    setca1(level) {
        Iif (level === this.ca1) return;
        const pcrSet = !!(this.pcr & 1);
        if (pcrSet === level) {
            if (this.acr & 1) this.ira = this.portapins;
            this.ifr |= INT_CA1;
            this.updateIFR();
            if ((this.pcr & 0xc) === 0x8) {
                // handshaking
                this.setca2(true);
            }
        }
        this.ca1 = level;
    }
 
    setca2(level) {
        if (level === this.ca2) return;
        this.ca2 = level;
        const output = !!(this.pcr & 0x08);
        if (this.ca2changecallback) this.ca2changecallback(level, output);
        if (output) return;
        const pcrSet = !!(this.pcr & 4);
        if (pcrSet === level) {
            this.ifr |= INT_CA2;
            this.updateIFR();
        }
    }
 
    setcb1(level) {
        if (level === this.cb1) return;
        const pcrSet = !!(this.pcr & 0x10);
        if (pcrSet === level) {
            if (this.acr & 2) this.irb = this.portbpins;
            this.ifr |= INT_CB1;
            this.updateIFR();
            if ((this.pcr & 0xc0) === 0x80) {
                // handshaking
                this.setcb2(true);
            }
        }
        this.cb1 = level;
        if ((this.acr & AcrShiftExternal) === AcrShiftExternal) this._clockShiftFromCb1(level);
    }
 
    setcb2(level) {
        if (level === this.cb2) return;
        this.cb2 = level;
        const output = !!(this.pcr & 0x80);
        if (this.cb2changecallback) this.cb2changecallback(level, output);
        if (output) return;
        const pcrSet = !!(this.pcr & 0x40);
        if (pcrSet === level) {
            this.ifr |= INT_CB2;
            this.updateIFR();
        }
    }
}
 
export class SysVia extends WithKeyMatrix(Via) {
    constructor(cpu, scheduler, { video, soundChip, cmos, isMaster, initialLayout } = {}) {
        super(cpu, scheduler, 0x01);
 
        this.IC32 = 0;
        this._initKeyMatrix(BBC.SHIFT, KeyboardColumns);
        this.gamepadFire = 0;
        this.mouseFire = 0;
        this.fireHeld = false;
        this.keyChanges = 0;
        this.setKeyLayout(initialLayout);
        this.video = video;
        this.soundChip = soundChip;
        this.cmos = cmos;
        cmos.replaying = () => cpu.replaying;
        this.isMaster = isMaster;
        this.keyScanTask = this.scheduler.newTask(() => this.scanPassesHeldKey());
 
        this.reset();
    }
 
    reset() {
        super.reset();
        this.keyScanTask.cancel();
        // The keyboard and CMOS drive port A whatever the VIA does, as restoreState() recomputes it.
        this.drivePortA();
    }
 
    write(addr, val) {
        const ca2WasFlagged = this.ifr & INT_CA2;
        super.write(addr, val);
        this._scanAfterCa2Cleared(ca2WasFlagged);
    }
 
    read(addr) {
        const ca2WasFlagged = this.ifr & INT_CA2;
        const result = super.read(addr);
        this._scanAfterCa2Cleared(ca2WasFlagged);
        return result;
    }
 
    snapshotState() {
        return {
            ...super.snapshotState(),
            IC32: this.IC32,
            keyScanTaskOffset: this.keyScanTask.offset(),
            ...(this.isMaster && { cmos: this.cmos.snapshotState() }),
        };
    }
 
    restoreState(state) {
        super.restoreState(state);
        this.keyScanTask.restoreOffset(state.keyScanTaskOffset);
        this.IC32 = state.IC32;
        if (this.isMaster) {
            if (state.cmos) this.cmos.restoreState(state.cmos);
            else Ethis.cmos.followLines(this.portbpins, this.IC32);
        }
        this.recalculatePortAPins();
    }
 
    get capsLockLight() {
        return !(this.IC32 & 0x40);
    }
 
    get shiftLockLight() {
        return !(this.IC32 & 0x80);
    }
 
    setKeyLayout(map) {
        this.keycodeToRowCol = getKeyMap(map);
    }
 
    setVBlankInt(level) {
        this.setca1(level);
    }
 
    /** Counted for `machineMoment`. */
    _keysChanged() {
        ++this.keyChanges;
        super._keysChanged();
    }
 
    updateKeys() {
        if (this.IC32 & 8) {
            for (let column = 0; column < KeyboardColumns; ++column) {
                if (this._columnHasScannedKey(column)) {
                    // ca2 stands for the whole pulse train here, so a snapshot keeps whether it is running.
                    if (!this.ca2) {
                        this.ca2 = true;
                        this.scanPassesHeldKey();
                    } else if (this.keyScanTask.scheduled()) {
                        this._scheduleScanEdge();
                    }
                    return;
                }
            }
            this.keyScanTask.cancel();
            this.ca2 = false;
            return;
        } else {
            this.keyScanTask.cancel();
            // Keyboard sets bit 7 to 0 or 1, and testing shows it always
            // "wins" vs. CMOS.
            // At 0 also wins against an output pin.
 
            const portapins = this.portapins;
            const keyrow = (portapins >>> 4) & 7;
            const keycol = portapins & 0xf;
            if (!this.keys[keycol][keyrow]) {
                this.portapins &= 0x7f;
            } else Eif (!(this.ddra & 0x80)) {
                this.portapins |= 0x80;
            }
 
            if (this._columnHasScannedKey(keycol)) {
                this.setca2(true);
                return;
            }
        }
        this.setca2(false);
    }
 
    /**
     * The autoscan putting an edge on CA2 for a held key. A press sets the flag at once whichever edge the PCR selects,
     * as the scan's pulses have both.
     */
    scanPassesHeldKey() {
        if (this.pcr & 0x08) return;
        this.ifr |= INT_CA2;
        this.updateIFR();
    }
 
    _scanAfterCa2Cleared(ca2WasFlagged) {
        if (ca2WasFlagged && !(this.ifr & INT_CA2) && this.IC32 & 8 && this.ca2) {
            this._scheduleScanEdge();
        }
    }
 
    /** The column the autoscan counter is on. Its power-on phase is arbitrary, so it is taken from the scheduler epoch. */
    scanColumn() {
        return Math.floor(this.scheduler.epoch / TicksPerScanColumn) % ScanCounterColumns;
    }
 
    /**
     * Schedules the flag for the scan's next edge of the kind the PCR selects: rising as the counter moves from a column
     * with no key held onto one with a key held, falling the other way.
     */
    _scheduleScanEdge() {
        this.keyScanTask.cancel();
        const epoch = this.scheduler.epoch;
        const column = this.scanColumn();
        const risingEdge = !!(this.pcr & 0x04);
        let leavingHeld = this._columnHasScannedKey(column);
        for (let step = 1; step <= ScanCounterColumns; ++step) {
            const enteringHeld = this._columnHasScannedKey((column + step) % ScanCounterColumns);
            if (enteringHeld !== leavingHeld && enteringHeld === risingEdge) {
                this.keyScanTask.schedule(step * TicksPerScanColumn - (epoch % TicksPerScanColumn));
                return;
            }
            leavingHeld = enteringHeld;
        }
    }
 
    _columnHasScannedKey(column) {
        if (column >= KeyboardColumns) return false;
        const rows = this.keys[column];
        for (let row = 1; row < 8; ++row) {
            if (rows[row]) return true;
        }
        return false;
    }
 
    portAUpdated() {
        this.updateKeys();
        this.soundChip.updateSlowDataBus(this.portapins, !(this.IC32 & 1));
    }
 
    rawPortB() {
        if (this.fireHeld) return 0xff;
        return ~(this.gamepadFire | this.mouseFire) & 0xff;
    }
 
    portBUpdated() {
        const portbpins = this.portbpins;
        const wasAutoscanning = this.IC32 & 8;
        if (portbpins & 8) this.IC32 |= 1 << (portbpins & 7);
        else this.IC32 &= ~(1 << (portbpins & 7));
        // CA2 rests low between the scan's pulses, so switching scan mode starts from there.
        if ((wasAutoscanning ^ this.IC32) & 8) this.ca2 = false;
 
        this.video.setScreenHwScroll((this.IC32 >> 4) & 3);
 
        if (this.isMaster) this.cmos.writeControl(portbpins, this.portapins, this.IC32);
 
        // Updating IC32 may have enabled peripherals attached to port A.
        this.recalculatePortAPins();
    }
 
    drivePortA() {
        // For experiments where we tested these behaviors, see:
        // https://stardot.org.uk/forums/viewtopic.php?f=4&t=17597
        // If either keyboard or CMOS pulls a given pin low, it "wins"
        // vs. via output.
        let busval = 0xff;
        if (this.isMaster) busval &= this.cmos.read(this.IC32);
        this.portapins &= busval;
        this.updateKeys();
    }
 
    drivePortB() {
        // Nothing driving here.
        // Note that if speech were fitted, it drives bit 7 low.
    }
 
    /**
     * Latches the gamepads' FIRE buttons, which the page reads once a frame.
     * @param {boolean} button1
     * @param {boolean} button2
     */
    setGamepadFire(button1, button2) {
        const fire = (button1 ? JoystickFire1 : 0) | (button2 ? JoystickFire2 : 0);
        if (fire === this.gamepadFire) return;
        this.gamepadFire = fire;
        this.inputLog?.record({ kind: "gamepadFire", button1, button2 });
    }
 
    /**
     * Set joystick button state (for mouse joystick)
     * @param {number} buttonNumber - Button number (0 for button1, 1 for button2)
     * @param {boolean} pressed - Whether the button is pressed
     */
    setJoystickButton(buttonNumber, pressed) {
        const bit = buttonNumber === 0 ? JoystickFire1 : JoystickFire2;
        this.mouseFire = pressed ? this.mouseFire | bit : this.mouseFire & ~bit;
        this.recalculatePortBPins();
        this.inputLog?.record({ kind: "joystickButton", button: buttonNumber, pressed });
    }
 
    /** Which FIRE buttons the host holds, as `setGamepadFire` and `setJoystickButton` (by button number) set them. */
    fireButtons() {
        const held = (bits) => [!!(bits & JoystickFire1), !!(bits & JoystickFire2)];
        return { gamepad: held(this.gamepadFire), mouse: held(this.mouseFire) };
    }
 
    /** @param {boolean} held whether the FIRE buttons read released whatever is pressed */
    holdFireButtons(held) {
        this.fireHeld = held;
    }
}
 
export class UserVia extends Via {
    constructor(cpu, scheduler, userPortPeripheral) {
        super(cpu, scheduler, 0x02);
        this.userPortPeripheral = userPortPeripheral;
        this.reset();
    }
 
    portBUpdated() {
        this.userPortPeripheral.write(this.portbpins);
    }
 
    drivePortB() {
        this.portbpins &= this.userPortPeripheral.read();
    }
}