WaveformGenerator.java

/**
 * This file is part of reSID, a MOS6581 SID emulator engine. Copyright (C) 2004  Dag Lem <resid@nimrod.no> Copyright
 * 2011-2025 Leandro Nini <drfiemost@users.sourceforge.net> Copyright 2007-2010 Antti Lankila
 * <p>
 * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation; either version 2 of the License or (at your option) any later
 * version.
 * <p>
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * <p>
 * You should have received a copy of the GNU General Public License along with this program; if not, write to the Free
 * Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 * @author Ken Händel
 *
 */
package builder.resid.resid;

import libsidplay.common.ChipModel;

/**
 * A 24-bit accumulator is the basis for waveform generation. FREQ is added to the lower 16 bits of the accumulator each
 * cycle. The accumulator is set to zero when TEST is set and starts counting when TEST is cleared. The noise waveform
 * is taken from intermediate bits of a 23-bit shift register. This register is clocked by bit 19 of the accumulator.
 * <p>
 * Java port of the reSID 1.0 waveformgenerator by Dag Lem.
 *
 * @author Ken Händel
 * @author Dag Lem
 * @author Antti Lankila
 */
public final class WaveformGenerator {
    private final short[][] model_wave = new short[8][];
    private final short[] dac = new short[4096];

    /**
     * Current phase and previous phase needed by noise/latch operations.
     * $555555 is deterministic initialization inherited from the reference, not
     * a simulated power-up process. SID reset preserves the running phase;
     * see SIDRegisterRegressionTest.resetPreservesOscillatorPhase.
     */
    int accumulator = 0x555555, accumulator_prev = 0x555555;

    // Tell whether the accumulator MSB was set high on this cycle.
    private boolean msb_rising;

    // Fout = (Fn*Fclk/16777216)Hz
    // reg16 freq;
    int freq;
    // PWout = (PWn/40.95)%
    private int pw;

    private int shift_register;

    // Remaining time to fully reset shift register.
    private int shift_register_reset;
    // Emulation of a pipeline causing bit 19 to clock the shift register.
    private int shift_pipeline;

    private int shift_latch;
    private int ring_msb_mask;
    private int no_noise;
    private int noise_output;
    private int no_noise_or_noise_output;
    private int no_pulse;
    private int pulse_output;

    /**
     * The control register right-shifted 4 bits; used for output function table lookup.
     */
    private int waveform;

    /**
     * The control register bits. Gate is handled by EnvelopeGenerator.
     */
    boolean test;
    boolean sync;

    private int floating_output_ttl;

    private short[] wave;

    private int waveform_output;
    private int osc3, tri_saw_pipeline;
    private ChipModel model = ChipModel.MOS6581;
    // Chosen on register/model changes; ordinary waves avoid the combined-waveform machinery.
    private static final int NOISE_OUTPUT_BITS = (1 << 20) | (1 << 18) | (1 << 14) | (1 << 11)
            | (1 << 9) | (1 << 5) | (1 << 2) | 1;
    // Renderer modes are software shortcuts, not additional SID states. Each
    // specializes the literal waveform/mask/feedback model; skipped latches must
    // be reconstructed before a CPU operation or noise/SYNC event uses them.
    // SIDWaveformTimingTest compares those boundaries with the literal reference.
    private static final int COMPLEX = 0, DIRECT = 1, DELAYED = 2, PULSE = 3, NOISE = 4,
            NOISE_ZERO = 5, NOISE_ZERO_FEEDBACK = 6, NOISE_ZERO_DELAYED = 7, READY_ZERO_DELAYED = 8, AFTER_SYNC = 9;
    private int waveformMode;
    private int noisePipelineRing;
    private boolean noisePulse, delayedTriSaw, topBitPulldown, holdNoiseStorage, shiftWritesNoise;
    private WaveformGenerator ringModulator = this;

    void setWaveformModels(short[][] models) {
        for (int i = 0; i < 8; i++) {
            model_wave[i] = new short[4096];
            System.arraycopy(models[i], 0, model_wave[i], 0, 4096);
        }
    }

    /**
     * Select the inherited chip-model approximation for waveform DAC weights
     * and offset; table conversion is separate from the digital OSC3 latch.
     *
     * @param chipModel The {@link ChipModel} to use.
     */
    void setChipModel(final ChipModel chipModel) {
        materializePulse();
        model = chipModel;
        configureWaveform();
        setDacNonlinearity(chipModel == ChipModel.MOS6581 ? 2.20 : 2.00);
    }

    /** Rebuild only the analogue DAC; digital latches, phase and noise state remain intact. */
    void setDacNonlinearity(double ratio) {
        final double[] dacBits = new double[12];
        SID.kinkedDac(dacBits, ratio, model == ChipModel.MOS8580);

        for (int i = 0; i < 4096; i++) {
            double dacValue = 0;
            for (int j = 0; j < 12; j++) {
                if ((i & 1 << j) != 0) {
                    dacValue += dacBits[j];
                }
            }
            dac[i] = (short) (dacValue + 0.5);
        }
        int offset = dac[model == ChipModel.MOS6581 ? 0x380 : 0x800];
        for (int i = 0; i < 4096; i++) {
            dac[i] -= offset;
        }
    }

    private void configureWaveform() {
        noisePulse = (waveform & 0xc) == 0xc;
        // Waveform C can mask the output between shifts without destroying the
        // stored register, on both chips. The older 8->C tests distinguish these
        // states; SIDNoiseWritebackTest also checks the real TEST rising edge.
        holdNoiseStorage = waveform == 0xc;
        shiftWritesNoise = waveform > 8;
        delayedTriSaw = (waveform & 3) != 0 && model == ChipModel.MOS8580;
        topBitPulldown = (waveform & 2) != 0 && (waveform & 0xd) != 0 && model == ChipModel.MOS6581;
        selectWaveformMode();
    }

    // Noise/SYNC events change the renderer, but not the model/waveform flags.
    private void selectWaveformMode() {
        if (waveformMode == AFTER_SYNC) return;
        waveformMode = waveform == 1 || waveform == 2 ? (delayedTriSaw ? DELAYED : DIRECT)
                : waveform == 4 ? PULSE : waveform == 8 ? NOISE
                : waveform > 8 && (test || holdNoiseStorage || (shift_register & NOISE_OUTPUT_BITS) == 0) && noise_output == 0
                        ? (delayedTriSaw ? NOISE_ZERO_DELAYED : topBitPulldown ? NOISE_ZERO_FEEDBACK : NOISE_ZERO) : COMPLEX;
    }

    /**
     * SID clocking - 1 cycle.
     */
    void clock() {
        materializePulse();
        waveformMode = COMPLEX;
        clockClocked();
        // Additional manual clocks retain the explicit latch until output().
        waveformMode = COMPLEX;
    }

    void clockClocked() {
        if (test) {
            if (shift_register_reset != 0 && --shift_register_reset == 0) resetNoise();
            pulse_output = 0xfff;
            return;
        }
        int previousAccumulator = accumulator;
        int nextAccumulator = (previousAccumulator + freq) & 0xffffff;
        int accumulatorBitsSet = ~previousAccumulator & nextAccumulator;
        int noiseEvent = (accumulatorBitsSet & 0x080000) | shift_pipeline;
        if (noiseEvent == 0) {
            // Noise events materialize the previous phase before its arithmetic use.
            accumulator = nextAccumulator;
            msb_rising = (accumulatorBitsSet & 0x800000) != 0;
        } else clockNoiseEvent(noiseEvent, previousAccumulator, nextAccumulator);
    }

    // TEST-held recovery uses the inherited staged fill-to-ones approximation.
    // Chip-specific delays are model parameters, not universal constants. See
    // SIDWaveformTimingTest.longTestIntervalsAndNoiseResetDecayMatch for equivalence.
    private void resetNoise() {
        shift_register = (shift_register | 1 | (shift_register << 1)) & 0x7fffff;
        shift_latch = shift_register;
        set_noise_output();
        if (shift_register != 0x7fffff) shift_register_reset = model == ChipModel.MOS6581 ? 1000 : 315000;
    }

    private void clockNoiseEvent(int event, int previousAccumulator, int nextAccumulator) {
        // A pending delayed sample uses the old pair of phases. Resolve it before
        // advancing them; ordinary clocks need no separate pipeline check.
        if (shift_pipeline == 1 && waveformMode == READY_ZERO_DELAYED) materializePulse();
        accumulator_prev = previousAccumulator;
        accumulator = nextAccumulator;
        msb_rising = (~previousAccumulator & nextAccumulator & 0x800000) != 0;
        if ((event & 0x080000) != 0) shift_pipeline = 2;
        else if (--shift_pipeline == 1) shift_latch = shift_register;
        else {
            // A noise shift can wake a zero mask; reconstruct the deferred pulse latch first.
            if ((waveformMode == NOISE_ZERO || waveformMode == NOISE_ZERO_FEEDBACK) && no_pulse == 0)
                pulse_output = (accumulator_prev >> 12) >= pw ? 0xfff : 0;
            shiftPhase2();
        }
    }

    /**
     * Synchronize oscillators. This must be done after all the oscillators have been clock()'ed, so that they are in
     * the same state.
     *
     * @param syncDest   The oscillator I am syncing
     * @param syncSource The oscillator syncing me.
     */
    void synchronize(final WaveformGenerator syncDest, final WaveformGenerator syncSource) {
        if (shouldSync(syncDest, syncSource)) syncDest.accumulator = 0;
    }

    /**
     * This backend batches SYNC after emitting its boundary sample. Materialize
     * pre-reset latches and force the next output through AFTER_SYNC, so deferred
     * pulse/tri-saw state is not reconstructed from the reset accumulator.
     * See SIDWaveformTimingTest.frequencyChangesAtNoiseEdgesAndSyncResetsMatch.
     */
    void synchronizeAfterOutput(final WaveformGenerator syncDest, final WaveformGenerator syncSource) {
        if (shouldSync(syncDest, syncSource)) {
            syncDest.materializePulse();
            syncDest.waveformMode = AFTER_SYNC;
            syncDest.accumulator = 0;
        }
    }

    // Inherited reSID rule: a source being synced on its own MSB rise does
    // not sync its destination. Evaluate the rises from all oscillators first.
    private boolean shouldSync(WaveformGenerator dest, WaveformGenerator source) {
        return msb_rising && dest.sync && !(sync && source.msb_rising);
    }

    /**
     * Hardware behavior: combining noise with other waveforms can destroy noise
     * state, affecting later samples. Implementation: the inherited phase model
     * latches stored bits one clock after a bit-19 rise, then commits the shift
     * here on the next clock. Stored, latched and output-masked bits are distinct.
     * Evidence: VICE-testprogs SID/noisewriteback/readme.txt describes this phase
     * interpretation; SID/wb_testsuite/samplings supplies chip captures for release
     * pairs. The literal WaveformGeneratorWritebackReference checks software
     * equivalence; src/test/resources/sid/writeback-reference.md records provenance
     * and the limits of the empirical rules.
     */
    private void shiftPhase2() {
        if (shiftWritesNoise && (shift_register | shift_latch | waveform_output) != 0) {
            // A fully zero register/latch/output is already the exact feedback result.
            shift_latch = (shift_register & ~NOISE_OUTPUT_BITS) | noiseWriteback();
        }
        int bit0 = ((shift_latch >> 22) ^ (shift_latch >> 17)) & 1;
        shift_register = ((shift_latch << 1) | bit0) & 0x7fffff;
        set_noise_output();
    }

    private void shiftTest(int previousWaveform) {
        writeTestFalling(previousWaveform, waveform);
        // TEST holds one feedback input high in the inherited model, so its
        // release shift differs from the normal bit-22 XOR bit-17 feedback.
        int bit0 = (1 ^ (shift_latch >> 17)) & 1;
        shift_register = ((shift_latch << 1) | bit0) & 0x7fffff;
        // The older 8580 C->C capture distinguishes feedback after the forced
        // shift from feedback into its input latch. Preserve the unexposed stages.
        if (model == ChipModel.MOS8580 && previousWaveform == 0xc && waveform == 0xc)
            shift_register &= ~NOISE_OUTPUT_BITS;
        set_noise_output();
    }

    /** Empirical TEST-release exceptions, separate from ordinary shift feedback. */
    private void writeTestFalling(int oldWaveform, int newWaveform) {
        // Every release exception also requires combined noise on both sides.
        if (oldWaveform <= 8 || newWaveform <= 8) return;
        // Feedback would assign zero again; the caller still performs the forced TEST shift.
        if ((shift_register | shift_latch | waveform_output) == 0) return;
        // Waveform nibbles exclude TEST. These release masks are empirical;
        // the older matrix supplies the separate E->D capture below.
        if (model == ChipModel.MOS6581
                && ((oldWaveform == 0xd && (newWaveform | 2) == 0xe)
                    || ((oldWaveform | 1) == 0xf && newWaveform == 0xc))) {
            // Measured release pairs: raw noise & $f80, not the feedback-masked output.
            // Clear only the lowest three mapped taps; the other stored stages
            // survive. See src/test/resources/sid/writeback-reference.md.
            shift_latch = shift_register & ~((1 << 5) | (1 << 2) | 1);
        } else if (model == ChipModel.MOS6581 && oldWaveform == 0xe && newWaveform == 0xd) {
            // Older E->D: raw noise & $e00, not the D->E $f80 mask.
            shift_latch = shift_register & ~((1 << 11) | (1 << 9) | (1 << 5) | (1 << 2) | 1);
        } else if (model == ChipModel.MOS8580 && oldWaveform == 0xc && newWaveform == 0xf) {
            // Separate measured 8580 C->F result: drive only the mapped taps low.
            shift_latch = shift_register & ~NOISE_OUTPUT_BITS;
        } else if (preWriteback(oldWaveform, newWaveform)) {
            shift_latch = (shift_register & ~NOISE_OUTPUT_BITS) | noiseWriteback();
        }
    }

    private int noiseWriteback() { return noiseWriteback(waveform_output); }

    private static int noiseWriteback(int value) {
        // Parallel form of eight independent bit copies: waveform bits 11..4
        // map to LFSR bits 20,18,14,11,9,5,2,0. Masks keep the groups separate;
        // callers merge these taps while preserving the other 15 stored stages.
        int bits = (value >>> 4) & 0xff;
        bits = (bits | (bits << 8)) & 0xe01f;
        bits = (bits | (bits << 4)) & 0xc2187;
        bits = (bits | (bits << 2)) & 0xc2613;
        return (bits | (bits << 1)) & NOISE_OUTPUT_BITS;
    }

    private void write_shift_register() {
        if (shift_pipeline != 1 && !test) {
            int mask = ~(1 << 20 | 1 << 18 | 1 << 14 | 1 << 11 | 1 << 9 | 1 << 5 | 1 << 2 | 1);
            // Pulse+noise output masking is distinct from stored bits. A noise
            // shift or a chip-specific TEST edge can still write storage.
            if (!holdNoiseStorage) shift_register &= mask | noiseWriteback();
            noise_output &= waveform_output;
        } else {
            // During the first shift phase the output drives the latched SRAM bits.
            noise_output = waveform_output;
        }
        no_noise_or_noise_output = no_noise | noise_output;
        // Only combined noise calls this method. A live mask keeps the complex
        // renderer; reselect when feedback makes its mapped output bits silent.
        if (noise_output == 0 && waveformMode != AFTER_SYNC
                && (test || holdNoiseStorage || (shift_register & NOISE_OUTPUT_BITS) == 0)) {
            waveformMode = delayedTriSaw ? NOISE_ZERO_DELAYED
                    : topBitPulldown ? NOISE_ZERO_FEEDBACK : NOISE_ZERO;
        }
    }

    private void set_noise_output() {
        finishNoisePipeline();
        // Inverse routing of noiseWriteback(): gather the eight taps into
        // waveform bits 11..4. The low four waveform bits have no noise taps.
        int bits = shift_register & NOISE_OUTPUT_BITS;
        bits = (bits | (bits >>> 1)) & 0xc2613;
        bits = (bits | (bits >>> 2)) & 0xc2187;
        bits = (bits | (bits >>> 4)) & 0xe01f;
        noise_output = ((bits | (bits >>> 8)) & 0xff) << 4;

        no_noise_or_noise_output = no_noise | noise_output;
        selectWaveformMode();
    }

    // Warm MOS8580 wf12nsr samples require an additional neighboring-line
    // pulldown at OSC3 ($FC -> $F8). Keep the feedback/DAC value separate:
    // feeding this readback into storage changes the otherwise exact noise tail.
    private int pulseNoiseReadback(int value) {
        return noisePulse && model == ChipModel.MOS8580 ? value & (value << 1) : value;
    }

    /**
     * 12-bit waveform output.
     *
     * @param ringModulator The oscillator ring-modulating me.
     */
    private void updateComplexWaveform(WaveformGenerator ringModulator) {
        if (waveform != 0) {
            int ix = (accumulator ^ (~ringModulator.accumulator & ring_msb_mask)) >> 12;
            waveform_output = wave[ix] & (no_pulse | pulse_output) & no_noise_or_noise_output;
            // Inherited digital approximation of coupled noise/pulse lines.
            // These feedback/DAC thresholds are separate from the clocked
            // MOS8580 OSC3 pulldown below; they are not a universal analog law.
            if (noisePulse) {
                waveform_output = model == ChipModel.MOS6581
                        ? (waveform_output < 0xf00 ? 0 : waveform_output & (waveform_output << 1) & (waveform_output << 2))
                        : (waveform_output < 0xfc0 ? waveform_output & (waveform_output << 1) : 0xfc0);
            }
            if (delayedTriSaw) {
                // Inherited 8580 readback uses the previous tri/saw stage but
                // this cycle's pulse/noise mask; audio uses the current waveform.
                osc3 = tri_saw_pipeline & (no_pulse | pulse_output) & no_noise_or_noise_output;
                tri_saw_pipeline = wave[ix];
            } else {
                osc3 = pulseNoiseReadback(waveform_output);
            }
            // Inherited 6581 combined-wave feedback also changes oscillator
            // phase, so even a silent renderer must preserve this MSB update.
            if (topBitPulldown) {
                accumulator &= (waveform_output << 12) | 0x7fffff;
            }
            if (waveform > 8) write_shift_register();
        } else if (floating_output_ttl != 0 && --floating_output_ttl == 0) {
            fadeWaveform();
        }
        pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    private void updateWaveform(WaveformGenerator ringModulator) {
        switch (waveformMode) {
            case DIRECT -> {
                waveform_output = osc3 = wave[(accumulator ^ (~ringModulator.accumulator & ring_msb_mask)) >> 12];
                return;
            }
            case DELAYED -> {
                waveform_output = wave[(accumulator ^ (~ringModulator.accumulator & ring_msb_mask)) >> 12];
                osc3 = tri_saw_pipeline;
                tri_saw_pipeline = waveform_output;
                return;
            }
            case PULSE -> waveform_output = osc3 = pulse_output;
            case NOISE -> { waveform_output = osc3 = noise_output; return; }
            case NOISE_ZERO -> { waveform_output = osc3 = 0; return; }
            case NOISE_ZERO_FEEDBACK -> { waveform_output = osc3 = 0; accumulator &= 0x7fffff; return; }
            // Mixed waveform history can leave even a tiny ring-capture helper out of line.
            case NOISE_ZERO_DELAYED -> {
                waveform_output = osc3 = 0;
                waveformMode = READY_ZERO_DELAYED;
                if (ring_msb_mask != 0) noisePipelineRing = ~ringModulator.accumulator & ring_msb_mask;
                return;
            }
            case READY_ZERO_DELAYED -> { if (ring_msb_mask != 0) noisePipelineRing = ~ringModulator.accumulator & ring_msb_mask; return; }
            case AFTER_SYNC -> {
                updateComplexWaveform(ringModulator);
                waveformMode = COMPLEX;
                selectWaveformMode();
                return;
            }
            default -> { updateComplexWaveform(ringModulator); return; }
        }
        pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    // Internal one-output-per-clock path; public/manual output() keeps literal
    // latch/feedback effects on extra calls (additionalPublicOutputsKeepTheReferenceSemantics).
    short outputClocked(final WaveformGenerator ringModulator) {
        if (this.ringModulator != ringModulator) this.ringModulator = ringModulator;
        updateWaveform(ringModulator);
        return dac[waveform_output];
    }

    /** Rare floating-output event; active-waveform rendering does no additional work. */
    private void fadeWaveform() {
        waveform_output &= waveform_output >> 1;
        osc3 = waveform_output;
        if (waveform_output != 0) floating_output_ttl = model == ChipModel.MOS6581 ? 1400 : 50000;
    }

    public short output(final WaveformGenerator ringModulator) {
        this.ringModulator = ringModulator;
        materializePulse();
        updateComplexWaveform(ringModulator);
        waveformMode = COMPLEX;
        selectWaveformMode();
        return dac[waveform_output];
    }

    /**
     * Read the cached OSC3 output without advancing waveform state.
     *
     * @return OSC3 value
     */
    public byte readOSC(int ringAccumulator, int myAccumulator) {
        // The phase arguments retain the legacy calling convention. This sample
        // is already latched; reads cannot clock pulse/noise or floating decay
        // (SIDWaveformTimingTest.oscReadsArePureForEveryVoiceAndWaveform).
        return (byte) (osc3 >> 4);
    }

    /**
     * Read the cached OSC3 output without advancing waveform state.
     *
     * @param ring_modulator The ring modulating partner of this waveform
     * @return OSC3 value
     */
    byte readOSC6581(final WaveformGenerator ring_modulator) {
        return readOSC(ring_modulator.accumulator, accumulator);
    }

    /**
     * Read the chip-specific sample already produced by the renderer. The inherited
     * 8580 tri/saw delay and noise shift timing are resolved there, not recomputed
     * from the previous-phase arguments passed through this legacy interface.
     *
     * @param ring_modulator The ring modulating partner of this waveform
     * @return OSC3 value
     */
    byte readOSC8580(final WaveformGenerator ring_modulator) {
        return readOSC(ring_modulator.accumulator_prev, accumulator_prev);
    }

    public byte readOSC(ChipModel model) {
        if (model == ChipModel.MOS6581) {
            return readOSC6581(this);
        } else {
            return readOSC6581(this);
        }
    }

    /**
     * Constructor.
     */
    WaveformGenerator() {
    }

    /**
     * Register functions.
     *
     * @param freq_lo low 8 bits of frequency
     */
    void writeFREQ_LO(final byte freq_lo) {
        freq = freq & 0xff00 | freq_lo & 0xff;
    }

    /**
     * Register functions.
     *
     * @param freq_hi high 8 bits of frequency
     */
    void writeFREQ_HI(final byte freq_hi) {
        freq = freq_hi << 8 & 0xff00 | freq & 0xff;
    }

    /**
     * Register functions.
     * <p>
     * A width write updates the pulse latch immediately in the reference model;
     * the next waveform update consumes it before latching the next comparison.
     * See SIDWaveformTimingTest.pulseWritesAndNoisePipelineBoundariesMatch.
     *
     * @param pw_lo low 8 bits of pulse width
     */
    void writePW_LO(final byte pw_lo) {
        pw = pw & 0xf00 | pw_lo & 0x0ff;
        pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    /**
     * Register functions.
     *
     * @param pw_hi high 8 bits of pulse width
     */
    void writePW_HI(final byte pw_hi) {
        pw = pw_hi << 8 & 0xf00 | pw & 0x0ff;
        pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    /**
     * Register functions.
     *
     * @param oldWaveform old waveform
     * @param newWaveform new waveform
     */
    private boolean preWriteback(int oldWaveform, int newWaveform) {
        // Inherited reSIDfp guards: source revisions and known conflicts are
        // recorded in src/test/resources/sid/writeback-reference.md.
        // noiselfsrinit's F->8 initialization is handled on TEST rising instead.
        if (oldWaveform <= 8 || newWaveform <= 8 || newWaveform == 0xc) return false;
        if (oldWaveform == 0xc && (model == ChipModel.MOS6581 || (newWaveform != 9 && newWaveform != 0xe)))
            return false;
        if (model == ChipModel.MOS6581 && (((oldWaveform & 3) == 1 && (newWaveform & 3) == 2)
                || ((oldWaveform & 3) == 2 && (newWaveform & 3) == 1))) return false;
        return true;
    }

    /**
     * A real TEST rise latches storage before resetting phase. Do not feed an
     * arbitrary newly selected T/S output into that storage: the older matrix
     * releases TEST once before selecting it. Its 8580 captures identify these
     * transient tap pulldowns; they are not a general analog waveform model.
     * Phase one excludes storage writes, and held TEST does not repeat them.
     * See SIDNoiseWritebackTest and sid/writeback-reference.md.
     */
    private void writeTestRising(int previousWaveform) {
        if (shift_pipeline == 1) return;
        if (model == ChipModel.MOS8580 && waveform == 9 && previousWaveform != waveform) {
            // Noise+triangle: OSC3 lines 10 and 5, stored taps 18 and 2.
            shift_register &= ~((1 << 18) | (1 << 2));
            set_noise_output();
            return;
        }
        if (model == ChipModel.MOS8580 && waveform == 0xc && previousWaveform != waveform) {
            // Pulse+noise: only line 5 is pulled down at this edge.
            shift_register &= ~(1 << 2);
            set_noise_output();
            return;
        }
        // Simultaneous triangle+saw+noise still captures the combined lines;
        // in particular F->8 must retain noiselfsrinit's fast zeroing sequence.
        // When the same combined waveform was already driving the lines,
        // capture it before TEST resets phase (notably wf12nsr's waveform C).
        if (waveform <= 8 || (waveform != previousWaveform && waveform != 0xb && waveform != 0xf)) return;
        // No tapped bit or output mask can change: preserve the already materialized CPU state.
        if ((shift_register & NOISE_OUTPUT_BITS) == 0 && noise_output == 0) return;
        int phase = (accumulator ^ (~ringModulator.accumulator & ring_msb_mask)) >> 12;
        int value = wave[phase] & (no_pulse | pulse_output) & no_noise_or_noise_output;
        if ((waveform & 0xc) == 0xc) {
            value = model == ChipModel.MOS6581
                    ? (value < 0xf00 ? 0 : value & (value << 1) & (value << 2))
                    : (value < 0xfc0 ? value & (value << 1) : 0xfc0);
        }
        shift_register &= ~NOISE_OUTPUT_BITS | noiseWriteback(value);
        set_noise_output();
    }

    void writeCONTROL_REG(final byte control) {
        materializePulse();
        int waveform_prev = waveform;
        boolean test_prev = test;
        test = (control & 8) != 0;
        sync = (control & 2) != 0;
        // The stored waveform already has the required value on unchanged writes.
        if ((control >> 4 & 15) != waveform_prev) {
            waveform = control >> 4 & 15;
            configureWaveform();
            no_noise = (waveform & 8) != 0 ? 0 : 0xfff;
            no_pulse = (waveform & 4) != 0 ? 0 : 0xfff;
            no_noise_or_noise_output = no_noise | noise_output;
        }
        // Table replacement still requires this refresh on an unchanged CONTROL write.
        wave = model_wave[waveform & 7];
        ring_msb_mask = (~control >> 5 & control >> 2 & 1) << 23;
        if (test != test_prev) changeTest(waveform_prev);
        updateAfterControl(waveform_prev);
    }

    private void changeTest(int previousWaveform) {
        if (test) {
            writeTestRising(previousWaveform);
            accumulator = accumulator_prev = 0;
            shift_pipeline = 0;
            shift_latch = shift_register;
            // Initial TEST-held recovery delay; resetNoise() models later filling.
            shift_register_reset = model == ChipModel.MOS6581 ? 35000 : 2519864;
            pulse_output = 0xfff;
        } else shiftTest(previousWaveform);
    }

    private void updateAfterControl(int previousWaveform) {
        if (waveform != 0) {
            if (waveformMode == AFTER_SYNC) {
                updateComplexWaveform(ringModulator);
                waveformMode = COMPLEX;
                selectWaveformMode();
            } else if (waveformMode == NOISE_ZERO_DELAYED) updateComplexWaveform(ringModulator);
            else updateWaveform(ringModulator);
        } else if (previousWaveform != 0) {
            // Warm-chip approximation from reSIDfp c1791383; revision/temperature
            // variation and physical evidence: sid/floating-output-evidence.md.
            floating_output_ttl = model == ChipModel.MOS6581 ? 54000 : 800000;
        }
    }

    // A masked-zero sample can still have live delayed OSC3 history. Resolve
    // its old phase/ring input before a noise event or CPU write replaces them.
    private void finishNoisePipeline() {
        if (waveformMode == READY_ZERO_DELAYED) {
            tri_saw_pipeline = wave[(accumulator ^ (noisePipelineRing & ring_msb_mask)) >> 12];
            waveformMode = NOISE_ZERO_DELAYED;
        }
    }

    /** Restore deferred pulse and 8580 samples before their old inputs change. */
    private void materializePulse() {
        finishNoisePipeline();
        if (waveformMode != COMPLEX && waveformMode != PULSE && waveformMode != AFTER_SYNC)
            pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    /**
     * SID reset.
     */
    void reset() {
        // Reset preserves phase; the constructor seed is not power-up simulation.
        accumulator_prev = accumulator;

        freq = 0;
        pw = 0;

        msb_rising = false;

        waveform = 0;
        waveformMode = COMPLEX;
        configureWaveform();
        test = false;
        sync = false;

        wave = model_wave[0];

        ring_msb_mask = 0;
        no_noise = 0xfff;
        no_pulse = 0xfff;
        pulse_output = 0xfff;

        // Reference reset seed: all ones followed by the forced release shift.
        // SIDRegisterRegressionTest.resetClocksNoiseRegisterOnce checks this contract.
        shift_latch = shift_register = 0x7ffffe;
        shift_register_reset = 0;
        set_noise_output();
        shift_pipeline = 0;

        waveform_output = osc3 = tri_saw_pipeline = 0;
        floating_output_ttl = 0;
    }
}