All files / src disc.js

92.22% Statements 652/707
81.22% Branches 238/293
97.41% Functions 113/116
93.18% Lines 574/616

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 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407            46x             13545x 13545x 13545x 13545x 13545x 13545x 13545x       3x       2x   2x 2x       275806x 275806x       41153125x   41153125x 41153125x 41153125x 41153125x       40889852x 40889852x       6137948x 539715x       13169x     13169x 13169x 13169x                 33698816x 131636x       275806x 275806x 275806x 12534x 12534x   263272x 263272x   275806x       2318750x   2318750x 2318750x 2318750x 2318750x 2318750x 2318750x 2318750x       2281142x 2281142x 2281142x 2281142x 2281142x       437824x 24439x       12534x 37602x 37602x   12534x       1476352x 5767x       371x     371x 302294x 371x               2x 2x 2x 27x     27x         2x       27x 27x 85x 85x 27x   85x 85x 2x 2x     27x                   24911x 24911x       3195909x 3195909x 3195909x 3195909x 3195909x       3195909x 3195909x   3195909x 623724x 623724x   3195909x                 109x       66x       109x 109x 109x 21922x 10961x   10961x   21922x   109x       109x 109x 109x 109x 109x                 24802x       12089x       24802x 24802x 24802x 3184948x 3184948x 3184948x 3184948x   24802x       24802x                       12846x 12846x 12846x 12846x 12846x 12846x 12846x 12846x 12846x 12846x   12846x 12846x 12846x 1x   12846x 12846x 12846x 12846x 12846x 12846x       24911x       12155x       19788x       16855x       7x             12044x 5x 5x     12039x 12039x     12044x   12044x       12044x   12044x   12044x 12065x 12065x 12065x 12034x 12034x 12034x 12034x   31x   12039x 1x         12065x 12065x 12065x 12065x 12065x     12065x       12039x 12039x 9x 6x 6x                   3921x 3921x               391270786x 391270786x 391270786x 391270786x             172999568x               25592x 25592x 204728x   204710x 25592x           46x 46x 46x   46x   46x     46x       43008x 43008x 43008x   43008x 43008x       7x                 1715x 1715x 12044x 12044x   1715x               1956x   1956x 1956x 1956x 1956x 1956x 1956x     1956x 1956x   1956x 1956x 195635104x 195635104x 195635104x 195635104x 195635104x 195635104x 195635104x 22635539x 22635539x 25587x 25587x 25587x 25587x     25587x 172999565x   100x 100x 100x 100x 100x 172999465x 100x 100x   172999365x   25687x   12846x 12846x 12846x 12846x 12846x       12841x         12841x 12841x 126x   12841x 12841x   12841x         1956x           512x 43008x         46x               256x 256x 256x           240289x       290896x       9779x       4576x           185x 21061405x 185x         46x 46x 46x 46x                     84x 84x 83x 83x 1x 82x 82x 82x 82x 9x 84x 7x       46x 46x 46x 46x   660x                     59x 59x   570x 570x   59x 59x 59x 56x 56x 55x 55x 55x       46x                       6x     6x 241x 241x 82x 169x   238x 1x 2x                     176x 176x 176x 24x 24x 24x 24x   176x 176x       176x 176x     176x         176x 176x 12803x 13163x   13163x       13163x   131630x                   131630x           131630x 131630x 131630x           131630x   118467x         13163x       176x         12x 12x 12x     10x 100x 10x         176x         11535x       6125x       290x                   5x 5x 5x     5x 5x       5x 5x 283x   280x   360x 360x 360x 5760x                       5760x       5760x 5760x 5760x               5760x   360x         5x         9493x   9490x 9489x 150x 9339x 9339x 9339x                       4379x 4379x                     7x 7x 560x 801x 5062x 5062x       7x 2x 4x                     7x 6x 6x 1x         6x 7x 7x 7x 479x 639x 639x 4331x 4280x 4280x       6x               7x                 256x   256x 256x 256x 256x 256x 256x   256x   256x 256x 256x       256x     256x     256x                   256x 256x   256x               117x 117x       206x         9x 9x         54x 4x 4x   54x                 90x                     8x 8x 1x           4x         2x       3x               1865987x       13545x 13545x       15314x 15314x       256x 256x   256x 256x       419298x                   33x 33x       33x       33x 33x 33x     33x 33x 33x 33x         405x 372x 372x     33x 33x 33x 33x 33x 33x 33x 33x 33x                   81x 81x 81x 81x 81x 81x 81x 81x                 25x     25x 25x 27x 2156x 2156x 2156x 2156x   1761x           395x         25x 25x   25x                                           11x 11x 11x 11x     11x 11x 11x 11x       11x 5x   6x       11x 11x 398x 398x 398x 398x 398x 398x 398x         11x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x                                                                                   247360x       44035x       22898846x       175929x       162191x       13052x       37602x       6x       263273x       13170x       131636x       118467x                 300735x       46655503x 373244024x 373244024x 373244024x 373244024x 373244024x   46655503x       3157048x 24911x       41339989x 41339989x 330719912x 330719912x 330719912x 330719912x 330719912x     41339989x       25829881x 25829881x 25829881x 25829881x 206639048x 206639048x 206639048x 206639048x   206639048x 206639048x   25829881x       2281148x 2281148x 18249184x 18249184x 18249184x 18249184x 15668824x 18249184x   2281148x       35957x 35957x 287656x 287656x 287656x   35957x       47x 41x 27x      
// Translated from beebjit by Chris Evans.
// https://github.com/scarybeasts/beebjit
 
import { crc32 } from "./archive.js";
import { hexbyte } from "./hex.js";
 
export const PulsesPerWord = 32;
 
class TrackBuilder {
    /**
     * @param {Track} track
     */
    constructor(track) {
        this._track = track;
        this._track.length = IbmDiscFormat.bytesPerTrack;
        this._index = 0;
        this._pulsesIndex = 0;
        this._lastMfmBit = 0;
        this._isMfm = false;
        this._crc = 0;
    }
 
    get track() {
        return this._track;
    }
 
    setTrackLength() {
        Iif (this._index > this._track.pulses2Us.length)
            throw new Error(`Track buffer overflow in ${this._track.description}`);
        Eif (this._index !== 0) this._track.length = this._index;
        return this;
    }
 
    resetCrc() {
        this._crc = IbmDiscFormat.crcInit(false);
        return this;
    }
 
    appendFmDataAndClocks(data, clocks) {
        Iif (this._index >= this._track.pulses2Us.length)
            throw new Error(`Track buffer overflow in ${this._track.description}`);
        this._track.pulses2Us[this._index++] = IbmDiscFormat.fmTo2usPulses(clocks, data);
        this._isMfm = false;
        this._crc = IbmDiscFormat.crcAddByte(this._crc, data);
        return this;
    }
 
    appendFmByte(data) {
        this.appendFmDataAndClocks(data, 0xff);
        return this;
    }
 
    appendRepeatFmByte(data, count) {
        for (let i = 0; i < count; ++i) this.appendFmByte(data);
        return this;
    }
 
    fillFmByte(data) {
        Iif (this._index >= this._track.pulses2Us.length)
            throw new Error(`Track buffer overflow in ${this._track.description}`);
        // Fill to standard track size or buffer capacity, whichever is smaller
        const fillCount = Math.min(IbmDiscFormat.bytesPerTrack, this._track.pulses2Us.length) - this._index;
        this.appendRepeatFmByte(data, fillCount);
        return this;
    }
 
    appendRepeatFmByteWithClocks(data, clocks, count) {
        for (let i = 0; i < count; ++i) this.appendFmDataAndClocks(data, clocks);
        return this;
    }
 
    appendFmChunk(bytes) {
        for (const byte of bytes) this.appendFmByte(byte);
        return this;
    }
 
    appendCrc() {
        const firstByte = (this._crc >>> 8) & 0xff;
        const secondByte = this._crc & 0xff;
        if (this._isMfm) {
            this.appendMfmByte(firstByte);
            this.appendMfmByte(secondByte);
        } else {
            this.appendFmByte(firstByte);
            this.appendFmByte(secondByte);
        }
        return this;
    }
 
    appendMfmPulses(pulses) {
        Iif (this._index >= this._track.pulses2Us.length)
            throw new Error(`Track buffer overflow in ${this._track.description}`);
        const existingPulses = this._track.pulses2Us[this._index];
        const mask = 0xffff << this._pulsesIndex;
        this._pulsesIndex = (this._pulsesIndex + 16) & 31;
        this._track.pulses2Us[this._index] = (existingPulses & mask) | (pulses << this._pulsesIndex);
        if (this._pulsesIndex === 0) this._index++;
        this._isMfm = true;
        return this;
    }
 
    appendMfmByte(data) {
        const { lastBit, pulses } = IbmDiscFormat.mfmTo2usPulses(this._lastMfmBit, data);
        this._lastMfmBit = lastBit;
        this.appendMfmPulses(pulses);
        this._crc = IbmDiscFormat.crcAddByte(this._crc, data);
        return this;
    }
 
    appendRepeatMfmByte(data, count) {
        for (let i = 0; i < count; ++i) this.appendMfmByte(data);
        return this;
    }
 
    appendMfm3xA1Sync() {
        for (let i = 0; i < 3; ++i) {
            this.appendMfmPulses(IbmDiscFormat.mfmA1Sync);
            this._crc = IbmDiscFormat.crcAddByte(this._crc, 0xa1);
        }
        return this;
    }
 
    appendMfmChunk(bytes) {
        for (const byte of bytes) this.appendMfmByte(byte);
        return this;
    }
 
    fillMfmByte(data) {
        Iif (this._index >= this._track.pulses2Us.length)
            throw new Error(`Track buffer overflow in ${this._track.description}`);
        // Fill to standard track size or buffer capacity, whichever is smaller
        const maxFill = Math.min(IbmDiscFormat.bytesPerTrack, this._track.pulses2Us.length);
        while (this._index < maxFill) this.appendMfmByte(data);
        return this;
    }
 
    /**
     * @param {number[]} pulseDeltas array of lengths between pulses
     * @param {boolean} isMfm whether this is an MFM track
     */
    buildFromPulses(pulseDeltas, isMfm) {
        this._isMfm = isMfm;
        let hasWarned = false;
        for (const pulse of pulseDeltas) {
            Iif (!IbmDiscFormat.checkPulse(pulse, isMfm)) {
                console.log(`Found a bad pulse for ${this.track.description}`);
            }
            Iif (!this.appendPulseDelta(pulse, isMfm) && !hasWarned) {
                console.log(`Truncated disc data for ${this.track.description}, ignoring the rest`);
                hasWarned = true;
            }
        }
        this.setTrackLength();
    }
 
    appendPulseDelta(deltaUs, quantizeMfm) {
        let num2UsUnits = quantizeMfm ? Math.round(deltaUs / 2) : 2 * Math.round(deltaUs / 4);
        while (num2UsUnits--) {
            Iif (this._index >= this._track.pulses2Us.length) return false;
            if (num2UsUnits === 0) {
                this._track.pulses2Us[this._index] |= 0x80000000 >>> this._pulsesIndex;
            }
            this._pulsesIndex++;
            if (this._pulsesIndex === 32) {
                this._pulsesIndex = 0;
                this._index++;
            }
        }
        return true;
    }
}
 
class RawDiscReader {
    /**
     * @param {Track} track
     * @param {Number} bitOffset
     */
    constructor(track, bitOffset) {
        this._track = track;
        this._pos = bitOffset;
    }
 
    readPulses() {
        let pulsesPos = this._pos >>> 5;
        const bitPos = this._pos & 0x1f;
        let sourcePulses = this._track.pulses2Us[pulsesPos];
        let pulses = (sourcePulses << bitPos) & 0xfffffffff;
        Iif (pulsesPos === this._track.length) {
            pulsesPos = 0;
            this._pos = bitPos;
        } else {
            pulsesPos++;
            this._pos += 32;
        }
        if (bitPos > 0) {
            sourcePulses = this._track.pulses2Us[pulsesPos];
            pulses |= sourcePulses >>> (32 - bitPos);
        }
        return pulses;
    }
}
 
class MfmReader {
    /**
     * @param {RawDiscReader} rawReader
     */
    constructor(rawReader) {
        this._rawReader = rawReader;
    }
 
    static get pulsesPerByte() {
        return 16;
    }
 
    read(numBytes) {
        const data = new Uint8Array(numBytes);
        let pulses = 0;
        for (let offset = 0; offset < numBytes; ++offset) {
            if ((offset & 1) === 0) {
                pulses = this._rawReader.readPulses();
            } else {
                pulses = (pulses << 16) & 0xffffffff;
            }
            data[offset] = IbmDiscFormat._2usPulsesToMfm(pulses >>> 16);
        }
        return { data, iffyPulses: false };
    }
 
    get initialCrc() {
        let crc = IbmDiscFormat.crcInit(false);
        crc = IbmDiscFormat.crcAddByte(crc, 0xa1);
        crc = IbmDiscFormat.crcAddByte(crc, 0xa1);
        crc = IbmDiscFormat.crcAddByte(crc, 0xa1);
        return crc;
    }
}
 
class FmReader {
    /**
     * @param {RawDiscReader} rawReader
     */
    constructor(rawReader) {
        this._rawReader = rawReader;
    }
 
    static get pulsesPerByte() {
        return 32;
    }
 
    read(numBytes) {
        const data = new Uint8Array(numBytes);
        let iffyPulses = false;
        for (let offset = 0; offset < numBytes; ++offset) {
            const pulses = this._rawReader.readPulses();
            const { data: dataByte, iffyPulses: iffy } = IbmDiscFormat._2usPulsesToFm(pulses);
            data[offset] = dataByte;
            iffyPulses |= iffy;
        }
        return { data, iffyPulses };
    }
 
    get initialCrc() {
        return IbmDiscFormat.crcInit(false);
    }
}
 
class Sector {
    /**
     * @param {Track} track
     * @param {boolean} isMfm
     * @param {Number} idPosBitOffset
     * @param {function(string): void} [warn] where to report anomalies; the console by default
     */
    constructor(track, isMfm, idPosBitOffset, warn = console.log) {
        this.track = track;
        this.isMfm = isMfm;
        this._readerType = isMfm ? MfmReader : FmReader;
        this._warn = warn;
        this.idPosBitOffset = idPosBitOffset;
        this.dataPosBitOffset = null;
        this.isDeleted = false;
        this.sectorData = null;
        this.hasDataCrcError = false;
        this.byteLength = null;
 
        const idReader = this._readerAt(this.idPosBitOffset);
        const { data: headerData, iffyPulses } = idReader.read(6);
        if (iffyPulses) {
            this._warn(`Iffy pulse in sector header ${this.description}`);
        }
        this.header = headerData;
        let crc = idReader.initialCrc;
        crc = IbmDiscFormat.crcAddByte(crc, IbmDiscFormat.idMarkDataPattern);
        crc = IbmDiscFormat.crcAddBytes(crc, this.header.slice(0, 4));
        const discCrc = (this.header[4] << 8) | this.header[5];
        this.hasHeaderCrcError = crc !== discCrc;
    }
 
    _readerAt(bitOffset) {
        return new this._readerType(new RawDiscReader(this.track, bitOffset));
    }
 
    get pulsesPerByte() {
        return this._readerType.pulsesPerByte;
    }
 
    get trackNumber() {
        return this.header ? this.header[0] : undefined;
    }
 
    get sectorNumber() {
        return this.header ? this.header[2] : undefined;
    }
 
    get description() {
        return `${this.track.description} idpos ${this.idPosBitOffset} idtrack ${this.trackNumber} idsector ${this.sectorNumber} datapos ${this.dataPosBitOffset}`;
    }
 
    /**
     * @param {Sector|undefined} nextSector
     */
    read(nextSector) {
        if (this.dataPosBitOffset === null) {
            this._warn(`Sector header without data ${this.description}`);
            return;
        }
 
        const { pulsesPerByte } = this;
        const dataMarker = this.isDeleted
            ? IbmDiscFormat.deletedDataMarkDataPattern
            : IbmDiscFormat.dataMarkDataPattern;
        const sectorStartByte = (this.dataPosBitOffset / pulsesPerByte) | 0;
        const sectorEndByte =
            (nextSector
                ? nextSector.idPosBitOffset / pulsesPerByte
                : (this.track.length * PulsesPerWord) / pulsesPerByte) | 0;
        // Account for CRC and sync bytes.
        let sectorSize = Sector.toSectorSize(sectorEndByte - sectorStartByte - 5);
 
        this.hasDataCrcError = true;
        let seenIffyData;
        do {
            const { crcOk, sectorData, iffyPulses } = this._tryLoadSectorData(dataMarker, sectorSize);
            seenIffyData = iffyPulses;
            if (crcOk) {
                this.byteLength = sectorSize;
                this.hasDataCrcError = false;
                this.sectorData = sectorData;
                break;
            }
            sectorSize = sectorSize >>> 1;
        } while (sectorSize >= 128);
        if (seenIffyData) {
            this._warn(`Iffy pulse in sector data ${this.description}`);
        }
    }
 
    _tryLoadSectorData(dataMarker, sectorSize) {
        const dataReader = this._readerAt(this.dataPosBitOffset);
        let crc = IbmDiscFormat.crcAddByte(dataReader.initialCrc, dataMarker);
        const { data: sectorData, iffyPulses } = dataReader.read(sectorSize + 2);
        crc = IbmDiscFormat.crcAddBytes(crc, sectorData.slice(0, sectorSize));
        const dataCrc = (sectorData[sectorSize] << 8) | sectorData[sectorSize + 1];
        // The CRC bytes are used for error-checking and are not part of the actual sector data payload.
        // Therefore, we exclude the last two bytes (CRC) from the returned `sectorData`.
        return { crcOk: dataCrc === crc, sectorData: sectorData.slice(0, sectorSize), iffyPulses };
    }
 
    static toSectorSize(size) {
        Iif (size < 256) return 128;
        if (size < 512) return 256;
        if (size < 1024) return 512;
        Iif (size < 2048) return 1024;
        return 2048;
    }
}
 
/**
 * A 64 bit shift register, held as a pair of unsigned 32 bit halves. BigInt would say this more
 * directly but costs an order of magnitude more per bit shifted.
 */
export class BitWindow64 {
    constructor() {
        this.hi = 0;
        this.lo = 0;
    }
 
    /**
     * @param {Number} bit 0 or 1, shifted into bit 0
     * @returns {Number} the bit shifted out of bit 63
     */
    shiftIn(bit) {
        const shiftedOut = this.hi >>> 31;
        this.hi = ((this.hi << 1) | (this.lo >>> 31)) >>> 0;
        this.lo = ((this.lo << 1) | bit) >>> 0;
        return shiftedOut;
    }
 
    /**
     * @returns {boolean} whether all 64 bits match the halves given
     */
    equals(hi, lo) {
        return this.hi === hi && this.lo === lo;
    }
 
    /**
     * @param {Number} nibble
     * @returns {Number} the length of the run of `nibble` ending at bit 0
     */
    countTrailingNibbles(nibble) {
        const nibblesPerHalf = 8;
        let count = 0;
        for (let bits = this.lo; (bits & 0xf) === nibble; bits >>>= 4) count++;
        // Only a low half that matched all the way up can have a run continuing into the high half.
        if (count === nibblesPerHalf) for (let bits = this.hi; (bits & 0xf) === nibble; bits >>>= 4) count++;
        return count;
    }
}
 
// What the mark detector holds at an address mark. The FM case only pins down the high half,
// the tail of the zero sync run; the low half is the marker byte itself, decoded separately.
const FmSyncHi = 0x88888888;
const MfmMarkerHi = 0xaaaa4489;
const MfmMarkerLo = 0x44894489;
// One data bit of zero, FM encoded with its clock, is the pulse nibble 0x8.
const FmZeroBitPulses = 0x8;
// FmSyncHi is eight of those, so a match has already seen this much of the sync run.
const FmSyncHiZeroBits = 8;
// Sync is counted in zero data bits, so a run no longer than two bytes' worth is short enough
// to be worth logging.
const ShortSyncZeros = 16;
 
class Track {
    constructor(upper, trackNum, initialByte) {
        this.length = IbmDiscFormat.bytesPerTrack; // Default size, will be updated when track is populated
        this.upper = upper;
        this.trackNum = trackNum;
        // Make room for any extra pulses that might come from non-standard discs.
        this.pulses2Us = new Uint32Array(IbmDiscFormat.bytesPerTrack * 2);
        this.pulses2Us.fill(initialByte | (initialByte << 8) | (initialByte << 16) | (initialByte << 24));
    }
 
    get description() {
        return `Track ${this.trackNum} ${this.upper ? "upper" : "lower"}`;
    }
 
    /**
     * Debug functionality to try and interpret the track.
     * @param {function(string): void} [warn] where to report anomalies; the console by default
     * @returns {Sector[]}
     */
    findSectors(warn = console.log) {
        const sectors = this.findSectorIds(warn);
        for (let sectorIndex = 0; sectorIndex !== sectors.length; ++sectorIndex) {
            const nextSector = sectors[sectorIndex + 1]; // Will be unset for last
            sectors[sectorIndex].read(nextSector);
        }
        return sectors;
    }
 
    /**
     * @param {function(string): void} [warn] where to report anomalies; the console by default
     * @returns {Sector[]}
     */
    findSectorIds(warn = console.log) {
        const sectors = [];
        // Pass 1: walk the track and find header and data markers.
        const bitLength = this.length * 32;
        let shiftRegister = 0;
        let numShifts = 0;
        let doMfmMarkerByte = false;
        let isMfm = false;
        let pulses = 0;
        // The mark detector is a 64 bit sliding window over the pulse stream; the bits leaving it
        // spill into a second window, which the sync run length is counted from.
        const markDetector = new BitWindow64();
        const markDetectorPrev = new BitWindow64();
        let dataByte;
        let sector = null;
        for (let pulseIndex = 0; pulseIndex < bitLength; ++pulseIndex) {
            if ((pulseIndex & 31) === 0) pulses = this.pulses2Us[pulseIndex >>> 5];
            const pulseBit = pulses >>> 31;
            markDetectorPrev.shiftIn(markDetector.shiftIn(pulseBit));
            shiftRegister = ((shiftRegister << 1) | pulseBit) & 0xffffffff;
            numShifts++;
            pulses = (pulses << 1) & 0xffffffff;
            if (markDetector.hi === FmSyncHi) {
                const { clocks, data, iffyPulses } = IbmDiscFormat._2usPulsesToFm(markDetector.lo);
                if (iffyPulses || clocks !== IbmDiscFormat.markClockPattern) continue;
                isMfm = false;
                doMfmMarkerByte = false;
                const num0s = FmSyncHiZeroBits + markDetectorPrev.countTrailingNibbles(FmZeroBitPulses);
                Iif (num0s <= ShortSyncZeros) {
                    warn(`Short zeros sync ${this.description}`);
                }
                dataByte = data;
            } else if (markDetector.equals(MfmMarkerHi, MfmMarkerLo)) {
                // Next byte is MFM marker.
                isMfm = true;
                doMfmMarkerByte = true;
                shiftRegister = 0;
                numShifts = 0;
                continue;
            } else if (doMfmMarkerByte && numShifts === 16) {
                dataByte = IbmDiscFormat._2usPulsesToMfm(shiftRegister);
                doMfmMarkerByte = false;
            } else {
                continue;
            }
            switch (dataByte) {
                case IbmDiscFormat.idMarkDataPattern: {
                    sector = new Sector(this, isMfm, pulseIndex + 1, warn);
                    sectors.push(sector);
                    shiftRegister = 0;
                    numShifts = 0;
                    break;
                }
                case IbmDiscFormat.dataMarkDataPattern:
                case IbmDiscFormat.deletedDataMarkDataPattern:
                    Iif (!sector || sector.dataPosBitOffset) {
                        warn(
                            `Sector data without header ${this.description}; mark bitpos ${pulseIndex}; previous good sector ${sector ? sector.description : "none"}`,
                        );
                    } else {
                        sector.dataPosBitOffset = pulseIndex + 1;
                        if (dataByte === IbmDiscFormat.deletedDataMarkDataPattern) {
                            sector.isDeleted = true;
                        }
                        shiftRegister = 0;
                        numShifts = 0;
                    }
                    break;
                default:
                    warn(`Unknown marker byte ${hexbyte(dataByte)} ${this.description}`);
            }
        }
        return sectors;
    }
}
 
class Side {
    constructor(upper, initialByte) {
        this.tracks = [];
        for (let i = 0; i < IbmDiscFormat.tracksPerDisc; ++i) this.tracks[i] = new Track(upper, i, initialByte);
    }
}
 
/** How an image's tracks are laid out on the surface, and whether that is for the loader to decide. */
export const DiscLayout = Object.freeze({
    auto: "auto",
    contiguous: "contiguous",
    expanded40: "expanded40",
});
 
export class DiscConfig {
    constructor() {
        this.expandTo80 = false;
        this.isSkipOddTracks = false;
        this.isSkipUpperSide = false;
    }
}
 
class SsdFormat {
    static get sectorSize() {
        return 256;
    }
 
    static get sectorsPerTrack() {
        return 10;
    }
 
    static get tracksPerDisc() {
        return 80;
    }
 
    static get trackSize() {
        return SsdFormat.sectorSize * SsdFormat.sectorsPerTrack;
    }
}
 
/** @returns {Number} how many logical tracks of `data` hold anything, ignoring a run of trailing zeros */
function tracksWithData(data, numSides) {
    let lastUsed = data.length - 1;
    while (lastUsed >= 0 && data[lastUsed] === 0) lastUsed--;
    return Math.floor(lastUsed / (SsdFormat.trackSize * numSides)) + 1;
}
 
// The DFS catalogue is the first two sectors of a side. Sector 1 holds how many files there are and
// how many sectors the disc has.
const DfsEntryCountOffset = 0x105;
const DfsSectorCountOffset = 0x106;
const DfsEntrySize = 8;
const DfsMaxEntries = 31;
 
/**
 * Whether an SSD or DSD image was written by a 40 track drive. Only its catalogue can say: images
 * are routinely padded out or cut short, so their size means nothing.
 *
 * @param {Uint8Array} data
 * @param {boolean} isDsd
 * @returns {{is40Track: boolean, reason: string}}
 */
export function sniffDfsLayout(data, isDsd) {
    const contiguous = (reason) => ({ is40Track: false, reason });
    if (data.length < 2 * SsdFormat.sectorSize) return contiguous("it is smaller than a catalogue");
    const entryBytes = data[DfsEntryCountOffset];
    if (entryBytes % DfsEntrySize !== 0 || entryBytes > DfsMaxEntries * DfsEntrySize)
        return contiguous(`its catalogue claims ${entryBytes} bytes of file entries`);
    const sectors = ((data[DfsSectorCountOffset] & 3) << 8) | data[DfsSectorCountOffset + 1];
    const reason = `its catalogue claims ${sectors} sectors`;
    const fortyTrackSectors = (SsdFormat.tracksPerDisc / 2) * SsdFormat.sectorsPerTrack;
    if (sectors === 0 || sectors > fortyTrackSectors) return contiguous(reason);
    const tracks = tracksWithData(data, isDsd ? 2 : 1);
    if (tracks > IbmDiscFormat.tracksPerDisc / 2) return contiguous(`it holds data as far as track ${tracks - 1}`);
    return { is40Track: true, reason };
}
 
// The title is split across the two catalogue sectors, and the cycle number follows its second half.
const DfsTitleFirstHalf = 8;
const DfsTitleSecondHalf = 4;
const DfsCycleOffset = 4;
const DfsEntryCountInSector1 = DfsEntryCountOffset - SsdFormat.sectorSize;
 
const isPrintableAscii = (byte) => byte >= 0x20 && byte < 0x7f;
 
/**
 * What the DFS catalogue on one side of a loaded disc says it is called, and how many times it
 * has been written to, which between them are what was on the sticker.
 *
 * @param {Disc} disc
 * @param {boolean} [isSideUpper]
 * @returns {{title: string, cycle: string}|null} null when the side holds no DFS catalogue
 */
export function dfsCatalogue(disc, isSideUpper = false) {
    const sectors = new Map();
    for (const sector of disc.getTrack(isSideUpper, 0).findSectors(() => {})) {
        const usable =
            !sector.hasHeaderCrcError && !sector.hasDataCrcError && sector.sectorData?.length === SsdFormat.sectorSize;
        if (usable && !sectors.has(sector.sectorNumber)) sectors.set(sector.sectorNumber, sector.sectorData);
    }
    const sector0 = sectors.get(0);
    const sector1 = sectors.get(1);
    if (!sector0 || !sector1) return null;
    const entryBytes = sector1[DfsEntryCountInSector1];
    if (entryBytes % DfsEntrySize !== 0 || entryBytes > DfsMaxEntries * DfsEntrySize) return null;
    const titleBytes = [...sector0.subarray(0, DfsTitleFirstHalf), ...sector1.subarray(0, DfsTitleSecondHalf)];
    const title = String.fromCharCode(...titleBytes.filter(isPrintableAscii)).trimEnd();
    return { title, cycle: hexbyte(sector1[DfsCycleOffset]) };
}
 
// One track could match by luck; a disc's worth of them could not.
const MinDoubleSteppedTracks = 4;
 
/**
 * Whether a surface holds a 40 track format, going by where its sectors say they are: a track
 * written by a 48 tpi head sits at twice the number its own headers claim, with nothing readable
 * on the tracks between. Only a flux image can be asked this, since for any other format the
 * layout is the loader's own doing.
 *
 * @param {Disc} disc
 * @returns {{is40Track: boolean, reason: string}}
 */
export function sniffSurfaceLayout(disc) {
    let doubleStepped = 0;
    // Both heads move together, so a disc has one pitch and the side that boots can speak for it.
    // Track 0 is where it claims to be at either pitch, so it says nothing.
    for (let trackNum = 1; trackNum < disc.tracksUsed; ++trackNum) {
        const sectors = disc.getTrack(false, trackNum).findSectorIds(() => {});
        if (!sectors.length) continue;
        if (trackNum & 1) return { is40Track: false, reason: `track ${trackNum} holds sectors of its own` };
        if (sectors.some((sector) => sector.trackNumber === trackNum / 2)) doubleStepped++;
    }
    if (doubleStepped < MinDoubleSteppedTracks)
        return { is40Track: false, reason: `only ${doubleStepped} tracks sit at twice their own number` };
    return { is40Track: true, reason: `${doubleStepped} tracks sit at twice the number their sectors claim` };
}
 
/**
 * Load a disc image in SSD (Single Sided Disc) or DSD (Double Sided Disc) format
 * @param {Disc} disc - The disc object to load into
 * @param {Uint8Array} data - The disc image data
 * @param {boolean} isDsd - True if loading a double-sided disc
 * @param {function(Uint8Array): void} onChange - Optional callback when disc content changes
 */
export function loadSsd(disc, data, isDsd, onChange) {
    const blankSector = new Uint8Array(SsdFormat.sectorSize);
    const numSides = isDsd ? 2 : 1;
    if (data.length % SsdFormat.sectorSize !== 0) {
        const paddedLength = Math.ceil(data.length / SsdFormat.sectorSize) * SsdFormat.sectorSize;
        const padded = new Uint8Array(paddedLength);
        padded.set(data);
        data = padded;
    }
    const maxSize = SsdFormat.sectorSize * SsdFormat.sectorsPerTrack * SsdFormat.tracksPerDisc * numSides;
    Iif (data.length > maxSize) {
        throw new Error("SSD file is too large");
    }
 
    disc.is40Track = disc.config.expandTo80;
    const trackStep = disc.is40Track ? 2 : 1;
    // Tracks twice as far apart are half as many, and an image can run past the last of them as
    // far as the surface has room for.
    const numTracks = Math.min(
        IbmDiscFormat.tracksPerDisc / trackStep,
        Math.max(SsdFormat.tracksPerDisc / trackStep, tracksWithData(data, numSides)),
    );
 
    let offset = 0;
    for (let track = 0; track < numTracks; ++track) {
        for (let side = 0; side < numSides; ++side) {
            const trackBuilder = disc.buildTrack(side === 1, track * trackStep);
            // Sync pattern at start of track, as the index pulse starts, aka GAP 5.
            trackBuilder
                .appendRepeatFmByte(0xff, IbmDiscFormat.stdGap1FFs)
                .appendRepeatFmByte(0x00, IbmDiscFormat.stdSync00s);
 
            for (let sector = 0; sector < SsdFormat.sectorsPerTrack; ++sector) {
                // Sector header, aka ID.
                trackBuilder
                    .resetCrc()
                    .appendFmDataAndClocks(IbmDiscFormat.idMarkDataPattern, IbmDiscFormat.markClockPattern)
                    .appendFmByte(track)
                    .appendFmByte(0)
                    .appendFmByte(sector)
                    .appendFmByte(1)
                    .appendCrc();
 
                // Sync pattern between sector header and sector data, aka GAP 2.
                trackBuilder
                    .appendRepeatFmByte(0xff, IbmDiscFormat.stdGap2FFs)
                    .appendRepeatFmByte(0x00, IbmDiscFormat.stdSync00s);
 
                // Sector data.
                const sectorData =
                    offset < data.length ? data.subarray(offset, offset + SsdFormat.sectorSize) : blankSector;
                offset += SsdFormat.sectorSize;
                trackBuilder
                    .resetCrc()
                    .appendFmDataAndClocks(IbmDiscFormat.dataMarkDataPattern, IbmDiscFormat.markClockPattern)
                    .appendFmChunk(sectorData)
                    .appendCrc();
 
                if (sector !== SsdFormat.sectorsPerTrack - 1) {
                    // Sync pattern between sectors, aka GAP 3.
                    trackBuilder
                        .appendRepeatFmByte(0xff, IbmDiscFormat.std10SectorGap3FFs)
                        .appendRepeatFmByte(0x00, IbmDiscFormat.stdSync00s);
                }
            }
            trackBuilder.fillFmByte(0xff);
        }
    }
 
    if (onChange) {
        // TODO(#822) maybe construct the disc directly with this stuff?
        // TODO(#822) maybe change this entirely and make it lazy; and have the onChange "pull" the disc as the format it wants
        // instead of doing this here. Most stuff doesn't care about changes and only needs the image on save.
        // Create a dataCopy large enough for all the sectors and tracks.
        const dataCopy = new Uint8Array(maxSize);
        dataCopy.set(data);
        disc.addTrackWriteListener(
            /** @param {Track} trackObj  */
            (side, _trackNum, trackObj) => {
                for (const sector of trackObj.findSectors())
                    if (!sectorShortfall(sector)) dataCopy.set(sector.sectorData, ssdOffsetOf(sector, side, numSides));
                onChange(dataCopy);
            },
            true,
        );
    }
    return disc;
}
 
class AdfFormat {
    static get sectorSize() {
        return 256;
    }
 
    static get sectorsPerTrack() {
        return 16;
    }
 
    static get tracksPerDisc() {
        return 80;
    }
}
 
/**
 * @param {Disc} disc
 * @param {Uint8Array} data
 * @param {boolean} isDsd
 */
export function loadAdf(disc, data, isDsd) {
    const blankSector = new Uint8Array(AdfFormat.sectorSize);
    const numSides = isDsd ? 2 : 1;
    Iif (data.length % AdfFormat.sectorSize !== 0) {
        throw new Error("ADF file size is not a multiple of sector size");
    }
    const maxSize = AdfFormat.sectorSize * AdfFormat.sectorsPerTrack * AdfFormat.tracksPerDisc * numSides;
    Iif (data.length > maxSize) {
        throw new Error("ADF file is too large");
    }
 
    let offset = 0;
    for (let track = 0; track < AdfFormat.tracksPerDisc; ++track) {
        if (offset >= data.length) break;
 
        for (let side = 0; side < numSides; ++side) {
            // Using recommended values from the 177x datasheet.
            const trackBuilder = disc.buildTrack(side === 1, track);
            trackBuilder.appendRepeatMfmByte(0x4e, 60);
            for (let sector = 0; sector < AdfFormat.sectorsPerTrack; ++sector) {
                trackBuilder
                    .appendRepeatMfmByte(0x00, 12)
                    .resetCrc()
                    .appendMfm3xA1Sync()
                    .appendMfmByte(IbmDiscFormat.idMarkDataPattern)
                    .appendMfmByte(track)
                    .appendMfmByte(0)
                    .appendMfmByte(sector)
                    .appendMfmByte(1)
                    .appendCrc();
 
                // Sync pattern between sector header and sector data, aka GAP 2.
                trackBuilder.appendRepeatMfmByte(0x4e, 22).appendRepeatMfmByte(0x00, 12);
 
                // Sector data.
                const sectorData =
                    offset < data.length ? data.subarray(offset, offset + AdfFormat.sectorSize) : blankSector;
                offset += AdfFormat.sectorSize;
                trackBuilder
                    .resetCrc()
                    .appendMfm3xA1Sync()
                    .appendMfmByte(IbmDiscFormat.dataMarkDataPattern)
                    .appendMfmChunk(sectorData)
                    .appendCrc();
 
                // Sync pattern between sectors, aka GAP 3.
                trackBuilder.appendRepeatMfmByte(0x4e, 24);
            }
            trackBuilder.fillMfmByte(0x4e);
        }
    }
 
    // TODO(#822) writeback
    return disc;
}
 
/** Why a sector will not fit in an SSD or DSD image, or null if it will. */
function sectorShortfall(sector) {
    if (sector.hasDataCrcError || sector.hasHeaderCrcError) return "with a CRC error";
    // A header whose data mark never arrives leaves the sector with nothing to write.
    if (!sector.sectorData) return "with no data";
    if (sector.sectorNumber >= SsdFormat.sectorsPerTrack)
        return `numbered past the ${SsdFormat.sectorsPerTrack} a track holds`;
    Iif (sector.sectorData.length !== SsdFormat.sectorSize) return `not ${SsdFormat.sectorSize} bytes`;
    Iif (sector.trackNumber >= SsdFormat.tracksPerDisc) return `past track ${SsdFormat.tracksPerDisc}`;
    return null;
}
 
/**
 * Where a sector belongs in an SSD or DSD image, which is the track its own header claims rather
 * than the one it sits on.
 *
 * @param {Sector} sector
 * @param {boolean} isSideUpper
 * @param {Number} numSides
 */
function ssdOffsetOf(sector, isSideUpper, numSides) {
    const track = sector.trackNumber * numSides + (isSideUpper ? 1 : 0);
    return track * SsdFormat.trackSize + sector.sectorNumber * SsdFormat.sectorSize;
}
 
/**
 * SSD and DSD images hold sector contents and nothing else, so anything a DFS sector could not
 * have held is lost. Copy protection usually shows up as one of these.
 *
 * @returns {string[]} what `disc` holds that an SSD or DSD cannot, worst first
 * @param {Disc} disc
 */
export function ssdOrDsdShortfalls(disc) {
    const counts = new Map();
    for (let trackNum = 0; trackNum < disc.tracksUsed; ++trackNum) {
        for (const upper of disc.isDoubleSided ? [false, true] : [false]) {
            for (const sector of disc.getTrack(upper, trackNum).findSectors()) {
                const shortfall = sectorShortfall(sector);
                if (shortfall) counts.set(shortfall, (counts.get(shortfall) ?? 0) + 1);
            }
        }
    }
    return [...counts]
        .sort(([, a], [, b]) => b - a)
        .map(([shortfall, count]) => `${count} sector${count === 1 ? "" : "s"} ${shortfall}`);
}
 
/**
 * @returns {Uint8Array}
 * @param {Disc} disc
 * @param {object} [options]
 * @param {boolean} [options.force] save what fits instead of refusing a disc that will not fit
 * @throws if the disc holds anything an SSD or DSD cannot, and `force` is not set
 */
export function toSsdOrDsd(disc, { force = false } = {}) {
    if (!force) {
        const shortfalls = ssdOrDsdShortfalls(disc);
        if (shortfalls.length)
            throw new Error(
                `This disc cannot be saved as SSD or DSD: it has ${shortfalls.join(", ")}. ` +
                    `Save it as HFE to keep everything.`,
            );
    }
    const numSides = disc.isDoubleSided ? 2 : 1;
    const result = new Uint8Array(numSides * SsdFormat.tracksPerDisc * SsdFormat.trackSize);
    let numTracks = 0;
    for (let trackNum = 0; trackNum < disc.tracksUsed; ++trackNum) {
        for (let side = 0; side < numSides; ++side) {
            const trackObj = disc.getTrack(side === 1, trackNum);
            for (const sector of trackObj.findSectors()) {
                if (sectorShortfall(sector)) continue;
                result.set(sector.sectorData, ssdOffsetOf(sector, side === 1, numSides));
                numTracks = Math.max(numTracks, sector.trackNumber + 1);
            }
        }
    }
    return result.slice(0, numTracks * numSides * SsdFormat.trackSize);
}
 
export class Disc {
    /**
     * @returns {Disc} a new blank disc
     */
    static createBlank() {
        return new Disc(true, new DiscConfig());
    }
 
    /**
     * @param {boolean} isWriteable
     * @param {DiscConfig} config
     * @param {string} name
     */
    constructor(isWriteable, config, name) {
        this.config = config;
 
        this.name = name;
        this.isDirty = false;
        this.dirtySide = -1;
        this.dirtyTrack = -1;
        this.tracksUsed = 0;
        this.isDoubleSided = false;
        // Whether the surface holds a 48 tpi layout, which a drive reads by double stepping.
        this.is40Track = false;
 
        this._trackWriteListeners = new Set();
        this._savingListeners = new Set();
        this.isWriteable = isWriteable;
 
        // Track which tracks have been written since the last snapshot.
        // Keys are numeric: (track | (isSideUpper ? 0x100 : 0)).
        this._snapshotDirtyTracks = new Set();
        // Cumulative set of all tracks ever written since disc load (never cleared by snapshots).
        // Same key encoding as _snapshotDirtyTracks.
        this._everDirtyTracks = new Set();
        // Cache of the previous snapshot's track data for structural sharing.
        // Keys are "side:trackNum" strings, values are {pulses2Us, length} objects.
        this._lastTrackSnapshots = Object.create(null);
 
        // Original disc image data, stored for embedding in save-to-file snapshots
        // and CRC32 verification on restore. _originalImageData is only set for
        // local-file discs (not URL-sourced ones). _originalImageCrc32 is the CRC
        // of the image bytes at load time — it is not updated if an onChange handler
        // mutates the backing store. This is fine because the CRC is compared against
        // the same source that would be reloaded (the original image or URL), not the
        // mutated copy. If a mutable source URL were added in future, CRC verification
        // should be skipped or the CRC updated accordingly.
        this._originalImageData = null;
        this._originalImageCrc32 = null;
 
        this.initSurface(0);
    }
 
    /**
     * @param {function(boolean, Number, Track): void} listener called once per flushed track
     * @param {boolean} [savesChanges] whether the listener puts the image somewhere it is read back from
     */
    addTrackWriteListener(listener, savesChanges = false) {
        this._trackWriteListeners.add(listener);
        if (savesChanges) this._savingListeners.add(listener);
    }
 
    get savesChanges() {
        return this._savingListeners.size > 0;
    }
 
    /** @param {function(boolean, Number, Track): void} listener */
    removeTrackWriteListener(listener) {
        this._trackWriteListeners.delete(listener);
        this._savingListeners.delete(listener);
    }
 
    /** @param {function(): void} listener called once, when a track is first written to this disc */
    notifyOnFirstTrackWrite(listener) {
        const onFirstWrite = () => {
            this.removeTrackWriteListener(onFirstWrite);
            listener();
        };
        this.addTrackWriteListener(onFirstWrite);
    }
 
    /**
     * Record the CRC32 of the original disc image for verification on restore.
     * Called by discFor() after loading. Does not retain the image bytes.
     * @param {Uint8Array} data - the raw disc image bytes (used only to compute CRC32)
     */
    setOriginalImageCrc32(data) {
        this._originalImageCrc32 = crc32(data);
    }
 
    /**
     * Store the original disc image bytes for embedding in snapshots.
     * Only call this for local-file discs — URL-sourced discs should use
     * setOriginalImageCrc32() instead to avoid retaining the full image.
     * Computes CRC32 only if not already set (e.g. by discFor).
     * @param {Uint8Array} data - the raw disc image bytes
     */
    setOriginalImage(data) {
        this._originalImageData = data;
        if (this._originalImageCrc32 == null) {
            this._originalImageCrc32 = crc32(data);
        }
    }
 
    /** @returns {Uint8Array|null} the original disc image bytes, or null if not set */
    get originalImageData() {
        return this._originalImageData;
    }
 
    /** @returns {number|null} CRC32 of the original disc image, or null if not set */
    get originalImageCrc32() {
        return this._originalImageCrc32;
    }
 
    get writeProtected() {
        return !this.isWriteable;
    }
 
    /**
     * @param {boolean} isSideUpper
     * @param {Number} trackNum
     * @returns {Track} */
    getTrack(isSideUpper, trackNum) {
        return isSideUpper ? this.upperSide.tracks[trackNum] : this.lowerSide.tracks[trackNum];
    }
 
    buildTrack(isSideUpper, trackNum) {
        this.setTrackUsed(isSideUpper, trackNum);
        return new TrackBuilder(this.getTrack(isSideUpper, trackNum));
    }
 
    setTrackUsed(isSideUpper, trackNum) {
        if (isSideUpper) this.isDoubleSided = true;
        this.tracksUsed = Math.max(this.tracksUsed, trackNum + 1);
    }
 
    initSurface(initialByte) {
        this.lowerSide = new Side(false, initialByte);
        this.upperSide = new Side(true, initialByte);
 
        this.tracksUsed = 0;
        this.isDoubleSided = false;
    }
 
    readPulses(isSideUpper, track, position) {
        return this.getTrack(isSideUpper, track).pulses2Us[position];
    }
 
    /**
     * @param {boolean} isSideUpper
     * @param {Number} track
     * @param {Number} position
     * @param {Number} pulses
     */
    writePulses(isSideUpper, track, position, pulses) {
        const trackObj = this.getTrack(isSideUpper, track);
        Iif (position >= trackObj.length)
            throw new Error(
                `Attempt to write off end of track ${track}: position ${position} >= length ${trackObj.length}`,
            );
        Iif (this.isDirty) {
            if (isSideUpper !== this.dirtySide || track !== this.dirtyTrack)
                throw new Error("Switched dirty track or side");
        }
        this.isDirty = true;
        this.dirtySide = isSideUpper;
        this.dirtyTrack = track;
        // Numeric key avoids string allocation on every pulse write.
        // Upper bit encodes side, lower 8 bits encode track number.
        const dirtyKey = track | (isSideUpper ? 0x100 : 0);
        this._snapshotDirtyTracks.add(dirtyKey);
        this._everDirtyTracks.add(dirtyKey);
        trackObj.pulses2Us[position] = pulses;
    }
 
    /** @returns {?{isSideUpper: boolean, trackNum: Number}} the track written, if there was one */
    flushWrites() {
        if (!this.isDirty) {
            Iif (this.dirtySide !== -1 || this.dirtyTrack !== -1) throw new Error("Bad state in disc dirty tracking");
            return null;
        }
 
        const dirtySide = this.dirtySide;
        const dirtyTrack = this.dirtyTrack;
        this.isDirty = false;
        this.dirtySide = -1;
        this.dirtyTrack = -1;
        const trackObj = this.getTrack(dirtySide, dirtyTrack);
        this.setTrackUsed(dirtySide, dirtyTrack);
        for (const listener of this._trackWriteListeners) listener(dirtySide, dirtyTrack, trackObj);
        return { isSideUpper: dirtySide, trackNum: dirtyTrack };
    }
 
    /**
     * Leave a track with no flux on it at all, as an erase head does.
     *
     * @param {boolean} isSideUpper
     * @param {Number} trackNum
     */
    eraseTrack(isSideUpper, trackNum) {
        const trackObj = this.getTrack(isSideUpper, trackNum);
        trackObj.pulses2Us.fill(0);
        trackObj.length = IbmDiscFormat.bytesPerTrack;
        const dirtyKey = trackNum | (isSideUpper ? 0x100 : 0);
        this._snapshotDirtyTracks.add(dirtyKey);
        this._everDirtyTracks.add(dirtyKey);
        this.setTrackUsed(isSideUpper, trackNum);
        for (const listener of this._trackWriteListeners) listener(isSideUpper, trackNum, trackObj);
    }
 
    /**
     * Create a snapshot of all track data with structural sharing.
     * Clean tracks reuse references from the previous snapshot;
     * dirty tracks get fresh copies.
     */
    snapshotState() {
        const numSides = this.isDoubleSided ? 2 : 1;
        // Use a plain object for JSON serialization compatibility.
        // Keys are "side:trackNum" strings.
        const tracks = Object.create(null);
        for (let side = 0; side < numSides; ++side) {
            for (let trackNum = 0; trackNum < this.tracksUsed; ++trackNum) {
                const key = `${side === 1}:${trackNum}`;
                const dirtyKey = trackNum | (side === 1 ? 0x100 : 0);
                const trackObj = this.getTrack(side === 1, trackNum);
                if (this._snapshotDirtyTracks.has(dirtyKey) || !this._lastTrackSnapshots[key]) {
                    // Dirty or first snapshot: copy the track data
                    tracks[key] = {
                        pulses2Us: trackObj.pulses2Us.slice(),
                        length: trackObj.length,
                    };
                } else {
                    // Clean: reuse the previous snapshot's reference
                    tracks[key] = this._lastTrackSnapshots[key];
                }
            }
        }
 
        this._snapshotDirtyTracks.clear();
        this._lastTrackSnapshots = tracks;
 
        return {
            tracksUsed: this.tracksUsed,
            isDoubleSided: this.isDoubleSided,
            isWriteable: this.isWriteable,
            name: this.name,
            tracks,
            // Expose for save-to-file snapshots to identify dirty tracks.
            // This is a Set and won't survive JSON serialization — it's only
            // used by createSnapshot() before the snapshot is serialized.
            _everDirtyTracks: new Set(this._everDirtyTracks),
            _originalImageData: this._originalImageData,
            _originalImageCrc32: this._originalImageCrc32,
        };
    }
 
    /**
     * Restore disc track data from a snapshot.
     * For save-to-file snapshots, `state.tracks` is empty and `state.dirtyTracks`
     * contains only the tracks modified since disc load. The base disc data must
     * already be loaded before calling this method.
     */
    restoreState(state) {
        this.tracksUsed = state.tracksUsed;
        this.isDoubleSided = state.isDoubleSided;
        this.isWriteable = state.isWriteable;
        this.name = state.name;
 
        // Reset write-in-progress state
        this.isDirty = false;
        this.dirtySide = -1;
        this.dirtyTrack = -1;
        this._snapshotDirtyTracks.clear();
        // Restore _everDirtyTracks from the snapshot if present (rewind path —
        // the Set is carried in-memory but won't survive JSON serialization).
        // For the save-to-file path, _everDirtyTracks is rebuilt from dirtyTracks below.
        if (state._everDirtyTracks instanceof Set) {
            this._everDirtyTracks = new Set(state._everDirtyTracks);
        } else {
            this._everDirtyTracks.clear();
        }
 
        // Restore full track data (rewind path — tracks contains all data)
        this._lastTrackSnapshots = state.tracks;
        for (const key of Object.keys(state.tracks)) {
            const trackData = state.tracks[key];
            const [sideStr, trackNumStr] = key.split(":");
            const isSideUpper = sideStr === "true";
            const trackNum = parseInt(trackNumStr, 10);
            const trackObj = this.getTrack(isSideUpper, trackNum);
            trackObj.pulses2Us.set(trackData.pulses2Us);
            trackObj.length = trackData.length;
        }
 
        // Apply dirty track overlays (save-to-file path — base disc already loaded,
        // overlay only the tracks that were written since disc load)
        if (state.dirtyTracks) {
            for (const key of Object.keys(state.dirtyTracks)) {
                const trackData = state.dirtyTracks[key];
                const [sideStr, trackNumStr] = key.split(":");
                const isSideUpper = sideStr === "true";
                const trackNum = parseInt(trackNumStr, 10);
                const trackObj = this.getTrack(isSideUpper, trackNum);
                trackObj.pulses2Us.set(trackData.pulses2Us);
                trackObj.length = trackData.length;
                this._everDirtyTracks.add(trackNum | (isSideUpper ? 0x100 : 0));
                // A disc that keeps its changes at its source takes the overlay there too.
                for (const listener of this._trackWriteListeners) listener(isSideUpper, trackNum, trackObj);
            }
        }
    }
 
    logSummary() {
        const maxTrack = this.tracksUsed;
        const numSides = this.isDoubleSided ? 2 : 1;
        for (let side = 0; side < numSides; ++side) {
            for (let trackNum = 0; trackNum < maxTrack; ++trackNum) {
                const track = this.getTrack(side === 1, trackNum);
                const sectors = track.findSectors();
                if (sectors.length) {
                    if (track.length >= IbmDiscFormat.bytesPerTrack * 1.015) {
                        console.log(`Long track ${track.description}, ${track.length} bytes`);
                    } else if (track.length <= IbmDiscFormat.bytesPerTrack * 0.985) {
                        console.log(`Short track ${track.description}, ${track.length} bytes`);
                    }
                    if (sectors[0].isMfm) {
                        if (sectors.length !== 16 && sectors.length !== 18) {
                            console.log(`Non-standard MFM sector count ${track.description} count ${sectors.length}`);
                        }
                    } else {
                        if (sectors.length !== 10) {
                            console.log(`Non-standard FM sector count ${track.description} count ${sectors.length}`);
                        }
                    }
                    for (const sector of sectors) {
                        if (sector.hasHeaderCrcError) console.log(`${sector.description} has bad header crc`);
                        if (sector.trackNumber !== trackNum) console.log(`${sector.description} has bad track id`);
                        if (sector.hasDataCrcError) console.log(`${sector.description} has bad data crc`);
                    }
                } else {
                    console.log(`"Unformatted track ${track.description}"`);
                }
            }
        }
    }
}
 
export class IbmDiscFormat {
    static get bytesPerTrack() {
        return 3125;
    }
 
    static get tracksPerDisc() {
        return 84;
    }
 
    static get markClockPattern() {
        return 0xc7;
    }
 
    static get idMarkDataPattern() {
        return 0xfe;
    }
 
    static get dataMarkDataPattern() {
        return 0xfb;
    }
 
    static get deletedDataMarkDataPattern() {
        return 0xf8;
    }
 
    static get mfmA1Sync() {
        return 0x4489;
    }
 
    static get mfmC2Sync() {
        return 0x5224;
    }
 
    static get stdSync00s() {
        return 6;
    }
 
    static get stdGap1FFs() {
        return 16;
    }
 
    static get stdGap2FFs() {
        return 11;
    }
 
    static get std10SectorGap3FFs() {
        return 21;
    }
 
    /**
     * @param {boolean} isMfm
     * @returns {Number} initial CRC for type
     */
    static crcInit(isMfm) {
        // MFM starts with 3x 0xA1 sync bytes added.
        return isMfm ? 0xcdb4 : 0xffff;
    }
 
    static crcAddByte(crc, byte) {
        for (let i = 0; i < 8; ++i) {
            const bit = byte & 0x80;
            const bitTest = (crc & 0x8000) ^ (bit << 8);
            crc = (crc << 1) & 0xffff;
            if (bitTest) crc ^= 0x1021;
            byte <<= 1;
        }
        return crc;
    }
 
    static crcAddBytes(crc, bytes) {
        for (const byte of bytes) crc = IbmDiscFormat.crcAddByte(crc, byte);
        return crc;
    }
 
    static fmTo2usPulses(clocks, data) {
        let ret = 0;
        for (let i = 0; i < 8; ++i) {
            ret <<= 4;
            if (clocks & 0x80) ret |= 0x08;
            if (data & 0x80) ret |= 0x02;
            clocks = (clocks << 1) & 0xff;
            data = (data << 1) & 0xff;
        }
        // Bit 7's clock lands in bit 31, so back to unsigned.
        return ret >>> 0;
    }
 
    static _2usPulsesToFm(pulses) {
        let clocks = 0;
        let data = 0;
        let iffyPulses = false;
        for (let i = 0; i < 8; ++i) {
            clocks <<= 1;
            data <<= 1;
            if (pulses & 0x80000000) clocks |= 0x01;
            if (pulses & 0x20000000) data |= 0x01;
            // Any pulses off the 2us clock are suspicious FM data.
            if (pulses & 0x50000000) iffyPulses = true;
            pulses = (pulses << 4) & 0xffffffff;
        }
        return { clocks, data, iffyPulses };
    }
 
    static mfmTo2usPulses(lastBit, data) {
        let pulses = 0;
        for (let i = 0; i < 8; ++i) {
            const bit = !!(data & 0x80);
            pulses = (pulses << 2) & 0xffff;
            data <<= 1;
            if (bit) pulses |= 0x01;
            else if (!lastBit) pulses |= 0x02;
            lastBit = bit;
        }
        return { lastBit, pulses };
    }
 
    static _2usPulsesToMfm(pulses) {
        let byte = 0;
        for (let i = 0; i < 8; ++i) {
            byte <<= 1;
            if ((pulses & 0xc000) === 0x4000) byte |= 1;
            pulses = (pulses << 2) & 0xffff;
        }
        return byte;
    }
 
    static checkPulse(pulseUs, isMfm) {
        if (pulseUs < 3.5 || pulseUs > 8.5) return false;
        if (isMfm && pulseUs > 5.5 && pulseUs < 6.5) return true;
        return !(pulseUs > 4.5 && pulseUs < 7.5);
    }
}