All files / src tapes.js

58.22% Statements 138/237
48.92% Branches 68/139
82.35% Functions 14/17
59.81% Lines 128/214

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          641x                                 2x       14x 14x 14x 14x 14x       2x         5x 5x 5x       17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x   17x 17x 17x 17x   16x       26x 26x 26x                 678x     678x 528x 376x 376x   528x 528x 528x     150x 30x 4x 4x   26x       146x   3x 3x   133x 133x 13x 13x 13x 120x 108x   12x 12x   96x 96x 96x   108x   12x 12x 12x 12x 11x   1x 1x     133x 100x                                                                                                                                                                             7x 7x 7x     7x   7x 7x 7x 7x 7x 7x 4x                       2x 2x 2x 2x 2x   1x 1x   4x           33x 33x       108x       2x       8x 8x 8x       7x 7x 7x   7x     7x 7x                         6x       12x 11x 11x 5x 5x 1x 1x 4x 3x   3x 1x       7x 7x         24x 24x       24x 24x 8x 8x   16x 14x 14x   2x    
import { DataStream, stringToUint8Array } from "./binary.js";
import { ungzip } from "./archive.js";
import { hexword } from "./hex.js";
 
function secsToClocks(secs, cpuSpeed) {
    return (cpuSpeed * secs) | 0;
}
 
// Atom tape encoding: wavebits sent one per poll via receiveBit().
// '0' bit = 4 cycles at 1200 Hz (toggle every 2 wavebits).
// '1' bit = 8 cycles at 2400 Hz (toggle every 1 wavebit).
// Carrier = continuous '1' bits.
 
function parityOf(curByte) {
    let parity = false;
    while (curByte) {
        parity = !parity;
        curByte >>>= 1;
    }
    return parity;
}
 
const ParityN = "N".charCodeAt(0);
 
class UefTape {
    constructor(stream, model) {
        this.stream = stream;
        this.baseFrequency = 1200;
        this.isAtom = model.isAtom;
        this.cpuSpeed = model.cyclesPerSecond;
        this.rewind();
    }
 
    get name() {
        return this.stream.name;
    }
 
    /** @returns {Number} how far through the image the head is, 0 to 1 */
    get position() {
        const chunk = this.curChunk?.stream;
        const chunkLeft = chunk ? chunk.end - chunk.pos : 0;
        return (this.stream.pos - chunkLeft) / this.stream.end;
    }
 
    rewind() {
        this.dummyData = [false, false, true, false, true, false, true, false, true, true];
        this.state = -1;
        this.count = 0;
        this.curByte = 0;
        this.numDataBits = 8;
        this.parity = ParityN;
        this.numParityBits = 0;
        this.numStopBits = 1;
        this.carrierBefore = 0;
        this.carrierAfter = 0;
        this.shortWave = 0;
        this.atomPhase = 0;
        this.atomSubCount = 0;
        this.atomWavebitsLeft = 0;
        this.atomToggleEvery = 1;
 
        this.stream.seek(10);
        const minor = this.stream.readByte();
        const major = this.stream.readByte();
        if (major !== 0x00) throw "Unsupported UEF version " + major + "." + minor;
        // No chunk yet: the first poll reads one. null, later, means the tape has run off the end.
        this.curChunk = undefined;
    }
 
    readChunk() {
        const chunkId = this.stream.readInt16();
        const length = this.stream.readInt32();
        return {
            id: chunkId,
            stream: this.stream.substream(length),
        };
    }
 
    // On BBC, acia is the ACIA (6850); on Atom, it's the PPIA (8255).
    // Both provide setTapeCarrier(), tone(), and receive/receiveBit().
    poll(acia) {
        Iif (this.curChunk === null) return;
 
        // Atom: deliver one wavebit per poll.
        if (this.isAtom && this.atomWavebitsLeft > 0) {
            if (++this.atomSubCount >= this.atomToggleEvery) {
                this.atomPhase ^= 1;
                this.atomSubCount = 0;
            }
            acia.receiveBit(this.atomPhase);
            this.atomWavebitsLeft--;
            return secsToClocks(0.25 / this.baseFrequency, this.cpuSpeed);
        }
 
        if (this.state === -1) {
            if (this.stream.eof()) {
                this.curChunk = null;
                return;
            }
            this.curChunk = this.readChunk();
        }
 
        let gap;
        switch (this.curChunk.id) {
            case 0x0000:
                console.log("Origin: " + this.curChunk.stream.readNulString());
                break;
            case 0x0100:
                acia.setTapeCarrier(false);
                if (this.state === -1) {
                    this.state = 0;
                    this.curByte = this.curChunk.stream.readByte();
                    acia.tone(this.baseFrequency); // Start bit
                } else if (this.state < 9) {
                    if (this.state === 0) {
                        // Start bit
                        acia.tone(this.baseFrequency);
                        if (this.isAtom) this.queueAtomBit(false);
                    } else {
                        const bit = this.curByte & (1 << (this.state - 1));
                        acia.tone(bit ? 2 * this.baseFrequency : this.baseFrequency);
                        if (this.isAtom) this.queueAtomBit(!!bit);
                    }
                    this.state++;
                } else {
                    acia.receive(this.curByte);
                    acia.tone(2 * this.baseFrequency); // Stop bit
                    if (this.isAtom) this.queueAtomBit(true);
                    if (this.curChunk.stream.eof()) {
                        this.state = -1;
                    } else {
                        this.state = 0;
                        this.curByte = this.curChunk.stream.readByte();
                    }
                }
                if (this.isAtom) return 0; // wavebits queued, drained on next poll
                return this.cycles(1);
            case 0x0104: // Defined data
                acia.setTapeCarrier(false);
                if (this.state === -1) {
                    this.numDataBits = this.curChunk.stream.readByte();
                    this.parity = this.curChunk.stream.readByte();
                    this.numStopBits = this.curChunk.stream.readByte();
                    this.numParityBits = this.parity !== ParityN ? 1 : 0;
                    // Atom: negative stop bits (high bit set) means short wave
                    this.shortWave = 0;
                    if (this.isAtom && this.numStopBits & 0x80) {
                        this.numStopBits = Math.abs(this.numStopBits - 256);
                        this.shortWave = 1;
                    }
                    console.log(
                        `Defined data with ${this.numDataBits}${String.fromCharCode(this.parity)}${this.shortWave ? "-" : ""}${this.numStopBits}`,
                    );
                    this.state = 0;
                }
                if (this.state === 0) {
                    if (this.curChunk.stream.eof()) {
                        this.state = -1;
                    } else {
                        this.curByte = this.curChunk.stream.readByte() & ((1 << this.numDataBits) - 1);
                        acia.tone(this.baseFrequency); // Start bit
                        if (this.isAtom) this.queueAtomBit(false);
                        this.state++;
                    }
                } else if (this.state < 1 + this.numDataBits) {
                    const bit = this.curByte & (1 << (this.state - 1));
                    acia.tone(bit ? 2 * this.baseFrequency : this.baseFrequency);
                    if (this.isAtom) this.queueAtomBit(!!bit);
                    this.state++;
                } else if (this.state < 1 + this.numDataBits + this.numParityBits) {
                    let bit = parityOf(this.curByte);
                    if (this.parity === ParityN) bit = !bit;
                    acia.tone(bit ? 2 * this.baseFrequency : this.baseFrequency);
                    if (this.isAtom) this.queueAtomBit(!!bit);
                    this.state++;
                } else if (this.state < 1 + this.numDataBits + this.numParityBits + this.numStopBits) {
                    acia.tone(2 * this.baseFrequency); // Stop bits
                    if (this.isAtom) this.queueAtomBit(true);
                    this.state++;
                } else {
                    acia.receive(this.curByte);
                    this.state = 0;
                    return 0;
                }
                if (this.isAtom) return 0;
                return this.cycles(1);
            case 0x0111: // Carrier tone with dummy data
                if (this.state === -1) {
                    this.state = 0;
                    this.carrierBefore = this.curChunk.stream.readInt16();
                    this.carrierAfter = this.curChunk.stream.readInt16();
                    console.log("Carrier with", this.carrierBefore, this.carrierAfter);
                }
                if (this.state === 0) {
                    acia.setTapeCarrier(true);
                    acia.tone(2 * this.baseFrequency);
                    if (this.isAtom) this.queueAtomBit(true);
                    this.carrierBefore--;
                    if (this.carrierBefore <= 0) this.state = 1;
                } else if (this.state < 11) {
                    acia.setTapeCarrier(false);
                    acia.tone(this.dummyData[this.state - 1] ? this.baseFrequency : 2 * this.baseFrequency);
                    if (this.isAtom) this.queueAtomBit(!this.dummyData[this.state - 1]);
                    if (this.state === 10) {
                        acia.receive(0xaa);
                    }
                    this.state++;
                } else {
                    acia.setTapeCarrier(true);
                    acia.tone(2 * this.baseFrequency);
                    if (this.isAtom) this.queueAtomBit(true);
                    this.carrierAfter--;
                    if (this.carrierAfter <= 0) this.state = -1;
                }
                if (this.isAtom) return 0;
                return this.cycles(1);
            case 0x0114:
                console.log("Ignoring security cycles");
                break;
            case 0x0115:
                console.log("Ignoring polarity change");
                break;
            case 0x0110: // Carrier tone.
                Eif (this.state === -1) {
                    this.state = 0;
                    this.count = this.curChunk.stream.readInt16();
                    // Each Atom carrier cycle expands to 16 wavebits, so
                    // divide the count to avoid 16x too many cycles.
                    if (this.isAtom) this.count = Math.max(1, (this.count / 16) | 0);
                }
                acia.setTapeCarrier(true);
                acia.tone(2 * this.baseFrequency);
                if (this.isAtom) this.queueAtomBit(true);
                this.count--;
                Eif (this.count <= 0) this.state = -1;
                if (this.isAtom) return 0;
                return this.cycles(1);
            case 0x0113:
                this.baseFrequency = this.curChunk.stream.readFloat32();
                console.log("Frequency change ", this.baseFrequency);
                break;
            case 0x0112:
                acia.setTapeCarrier(false);
                gap = 1 / (2 * this.curChunk.stream.readInt16() * this.baseFrequency);
                console.log("Tape gap of " + gap + "s");
                acia.tone(0);
                return secsToClocks(gap, this.cpuSpeed);
            case 0x0116:
                acia.setTapeCarrier(false);
                gap = this.curChunk.stream.readFloat32();
                console.log("Tape gap of " + gap + "s");
                acia.tone(0);
                return secsToClocks(gap, this.cpuSpeed);
            default:
                console.log("Skipping unknown chunk " + hexword(this.curChunk.id));
                break;
        }
        return this.cycles(1);
    }
 
    // Queue 16 wavebits for an Atom tape bit. atomPhase and atomSubCount
    // carry across calls so bit boundaries don't break carrier detection.
    queueAtomBit(isOne) {
        this.atomWavebitsLeft = 16;
        this.atomToggleEvery = isOne ? 1 : 2;
    }
 
    cycles(count) {
        return secsToClocks(count / this.baseFrequency, this.cpuSpeed);
    }
}
 
const dividerTable = [1, 16, 64, -1];
 
class TapefileTape {
    constructor(stream, model) {
        this.count = 0;
        this.stream = stream;
        this.cpuSpeed = model.cyclesPerSecond;
    }
 
    rate(acia) {
        let bitsPerByte = 9;
        Eif (!(acia.cr & 0x80)) {
            bitsPerByte++; // Not totally correct if the AUG is to be believed.
        }
        const divider = dividerTable[acia.cr & 0x03];
        // http://beebwiki.mdfs.net/index.php/Serial_ULA says the serial rate is ignored
        // for cassette mode.
        const cpp = this.cpuSpeed / (19200 / divider);
        return Math.floor(bitsPerByte * cpp);
    }
 
    get name() {
        return this.stream.name;
    }
 
    /** @returns {Number} how far through the image the head is, 0 to 1 */
    get position() {
        return this.stream.pos / this.stream.end;
    }
 
    rewind() {
        this.stream.seek(10);
    }
 
    poll(acia) {
        if (this.stream.eof()) return 100000;
        let byte = this.stream.readByte();
        if (byte === 0xff) {
            byte = this.stream.readByte();
            if (byte === 0) {
                acia.setTapeCarrier(false);
                return 0;
            } else if (byte === 0x04) {
                acia.setTapeCarrier(true);
                // Simulate 5 seconds of carrier.
                return secsToClocks(5, this.cpuSpeed);
            } else Iif (byte !== 0xff) {
                throw "Got a weird byte in the tape";
            }
        }
        acia.receive(byte);
        return this.rate(acia);
    }
}
 
export async function loadTapeFromData(name, data, model) {
    const raw = stringToUint8Array(data);
    Iif (raw && raw.length > 4 && raw[0] === 0x1f && raw[1] === 0x8b) {
        console.log("Ungzipping " + name);
        data = await ungzip(raw);
    }
    const stream = new DataStream(name, data);
    if (stream.readByte(0) === 0xff && stream.readByte(1) === 0x04) {
        console.log("Detected a 'tapefile' tape");
        return new TapefileTape(stream, model);
    }
    if (stream.readNulString(0) === "UEF File!") {
        console.log("Detected a UEF tape");
        return new UefTape(stream, model);
    }
    throw new Error(`${name} is not a UEF or tapefile tape image`);
}