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.residfp;

import libsidplay.common.ChipModel;
import java.util.HashMap;
import java.util.Map;

/**
 * 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.
 *
 * @author Ken Händel
 *
 */
public final class WaveformGenerator {
    private static final int NOISE_OUTPUT_BITS = (1 << 20) | (1 << 18) | (1 << 14) | (1 << 11)
            | (1 << 9) | (1 << 5) | (1 << 2) | 1;
    private float[][] wftable;
    private byte[][] wfdigital;
    private static final float[] EMPTY_DAC = new float[4096];
    private static final Map<float[][], float[]> DIGITAL_DAC_CACHE = new HashMap<>();
    private float[] digitalDac = EMPTY_DAC;
    private float[] analogLow, analogHigh;
    private byte[] digitalLow, digitalHigh;
    private int basicWaveform;
    private boolean noisePulse, delayedTriSaw, topBitPulldown;
    private boolean simpleWaveform;
    // 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, PREPARE_SIMPLE = 1, PREPARE_PULSE = 2, PREPARE_NOISE = 3,
            CACHED_OUTPUT = 4, NOISE_ZERO_FEEDBACK = 5, READY_ZERO_DELAYED = 6, NOISE_ZERO_DELAYED = 7,
            PREPARE_DIRECT = 8, COMBINED_FEEDBACK = 9, PULSE_TRIANGLE = 10, COMBINED_DELAYED = 11,
            READY_PULSE = 12;
    private int outputMode;
    private int simplePhase, previousSimplePhase;
    private float noiseDac, pulseLowDac, pulseHighDac;
    private boolean zeroRendered, noisePipelinePending;
    private int noisePipelinePhase;
    private int noisePipelineRing;
    private boolean noisePipelineHigh;

    void setWftable(final float[][] newWftable, final float[] newDac, final byte[][] newWfdigital) {
        materialize();
        wftable = newWftable;
        wfdigital = newWfdigital;
        digitalDac = cachedDac(newWftable, newDac);
        selectWaveformTables();
        noiseDac = digitalDac[noise_output];
        pulseLowDac = wftable[3][0];
        pulseHighDac = wftable[7][0];
        simplePhase = -1;
        zeroRendered = false;
        selectOutputMode();
    }

    /**
     * Precompute the sum of twelve DAC bit weights in the reference's low-to-high
     * floating-point order. Table identity shares this work between voices and
     * assumes unchanged table/weight contents for that model/nonlinearity identity.
     */
    private static float[] cachedDac(float[][] tables, float[] bits) {
        synchronized (DIGITAL_DAC_CACHE) {
            float[] values = DIGITAL_DAC_CACHE.get(tables);
            if (values == null) {
                values = new float[4096];
                for (int value = 0; value < values.length; value++) {
                    float sample = tables[0][0];
                    for (int bit = 0; bit < 12; bit++) {
                        if ((value & (1 << bit)) != 0) sample += bits[bit];
                    }
                    values[value] = sample;
                }
                DIGITAL_DAC_CACHE.put(tables, values);
            }
            return values;
        }
    }

    private int digitalValue(int phase, boolean pulseHigh) {
        return switch (basicWaveform) {
            case 0 -> 0xfff;
            case 1 -> (phase & 0x800) == 0 ? phase << 1 : (phase ^ 0xfff) << 1;
            case 2 -> phase;
            case 4 -> pulseHigh ? 0xfff : 0;
            default -> combinedDigitalValue(phase, pulseHigh);
        };
    }

    private int combinedDigitalValue(int phase, boolean pulseHigh) {
        return ((pulseHigh ? digitalHigh : digitalLow)[phase] & 255) << 4;
    }

    /**
     * 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.
     */
    private int accumulator = 0x555555, accumulator_prev = 0x555555;

    /**
     * Value in noise XOR register.
     */
    private int shift_register, shift_register_reset;
    // 0: idle, 2/1: the two shift phases, 8: TEST. One load serves both clock decisions.
    private static final int TEST_CLOCK = 8;
    private static final int TEST_PREPARE = 13, TEST_RESTORE = 14, TEST_RING_STABLE = 15;
    private static final int READY_SIMPLE = 16, READY_DIRECT = 17;
    private int testRingInput;
    private int testWaveform, testPipeline;
    private int noiseClockState;
    private boolean legacyClockPrepared;
    private int noise_output, no_noise, no_noise_or_noise_output, no_pulse;
    private int pulse_output = 0xfff;
    private int waveform_output, osc3, tri_saw_pipeline, floating_output_ttl;
    private ChipModel model = ChipModel.MOS6581;
    private int shift_latch;
    private int ring_msb_mask;

    void setChipModel(ChipModel model) {
        materialize();
        this.model = model;
        configureWaveform();
        selectOutputMode();
        simplePhase = -1;
    }

    private void configureWaveform() {
        basicWaveform = waveform & 7;
        simpleWaveform = waveform == 1 || waveform == 2;
        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;
    }

    private void selectBaseOutputMode() {
        outputMode = simpleWaveform ? (model == ChipModel.MOS6581 && ring_msb_mask == 0 ? PREPARE_DIRECT : PREPARE_SIMPLE)
                : waveform == 4 ? PREPARE_PULSE : waveform == 8 ? PREPARE_NOISE
                : waveform != 0 && waveform <= 7 ? (topBitPulldown ? COMBINED_FEEDBACK : delayedTriSaw ? COMBINED_DELAYED : PULSE_TRIANGLE)
                : waveform > 8 && (holdNoiseStorage || (shift_register & NOISE_OUTPUT_BITS) == 0) && noise_output == 0 && zeroRendered
                        ? (delayedTriSaw ? NOISE_ZERO_DELAYED : topBitPulldown ? NOISE_ZERO_FEEDBACK : CACHED_OUTPUT) : COMPLEX;
        if (outputMode == NOISE_ZERO_DELAYED && no_pulse != 0) noisePipelineHigh = false;
    }

    private void selectOutputMode() {
        selectBaseOutputMode();
        if (test && waveform != 0) outputMode = TEST_PREPARE;
    }

    private void selectWaveformTables() {
        int low = basicWaveform == 0 ? 0 : basicWaveform - 1;
        int high = basicWaveform >= 4 ? basicWaveform + 3 : low;
        digitalLow = wfdigital[low];
        digitalHigh = wfdigital[high];
        if (basicWaveform != 0) {
            analogLow = wftable[low];
            analogHigh = wftable[high];
        }
    }

    /**
     * Held analog audio output, distinct from digital OSC3. CONTROL preserves it
     * while updating digital latches; ordinary SID rendering refreshes it next clock.
     * see SIDWaveformTimingTest.additionalPublicOutputsKeepTheReferenceSemantics.
     */
    private float previous_dac;

    /**
     * Fout = (Fn*Fclk/16777216)Hz
     */
    private int freq;

    /**
     * PWout = (PWn/40.95)%
     */
    private int pw;

    /**
     * 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.
     */
    private boolean test, sync;
    // Field order is retained as a performance precaution; Java does not
    // guarantee field offsets. This layout is not part of the SID model.
    private boolean holdNoiseStorage, shiftWritesNoise;

    /**
     * SID clocking - 1 cycle.
     */
    /** Legacy/manual clocking retains the explicit pulse latch used by public output(). */
    void clock() {
        if (!legacyClockPrepared) {
            materialize();
            selectBaseOutputMode();
        }
        clockCore(true);
        legacyClockPrepared = true;
    }

    int clockClocked() { return clockCore(false); }

    private int clockCore(boolean forcePulse) {
        int state = noiseClockState;
        if (state == TEST_CLOCK) {
            if (shift_register_reset != 0 && --shift_register_reset == 0) resetNoise();
            if (forcePulse) pulse_output = 0xfff;
            return 0;
        }
        // The second noise phase may expose the last sample's delayed waveform.
        // Resolve it before this clock overwrites the two accumulator phases.
        if (state == 1 && outputMode == READY_ZERO_DELAYED) finishNoisePipeline();
        accumulator_prev = accumulator;
        accumulator = (accumulator + freq) & 0xffffff;
        int rising = ~accumulator_prev & accumulator;
        int noiseEvent = (rising & 0x080000) | state;
        if (noiseEvent != 0) clockNoiseEvent(noiseEvent, !forcePulse);
        return rising;
    }

    // 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, boolean renderEachClock) {
        if ((event & 0x080000) != 0) noiseClockState = 2;
        else if (--noiseClockState == 1) shift_latch = shift_register;
        else {
            // A noise shift can wake a zero mask. Restore the previous cycle's
            // deferred pulse comparison before the new noise bits reach its input.
            if (renderEachClock && (outputMode == CACHED_OUTPUT || outputMode == NOISE_ZERO_FEEDBACK) && no_pulse == 0)
                pulse_output = pulseComparison(accumulator_prev);
            shiftPhase2();
        }
    }

    /**
     * Synchronize oscillators. This must be done after all the oscillators have been clock()'ed since the oscillators
     * operate in parallel. Note that the oscillators must be clocked exactly on the cycle when the MSB is set high for
     * hard sync to operate correctly. See SID.clock().
     *
     * @param syncDest   The oscillator I am syncing
     * @param syncSource The oscillator syncing me.
     */
    void synchronize(final WaveformGenerator syncDest, final WaveformGenerator syncSource) {
        // A special case occurs when a sync source is synced itself on the same
        // cycle as when its MSB is set high. In this case the destination will
        // not be synced. This has been verified by sampling OSC3.
        if (syncDest.sync && (~accumulator_prev & accumulator & 0x800000) != 0
                && !(sync && (~syncSource.accumulator_prev & syncSource.accumulator & 0x800000) != 0)) {
            syncDest.accumulator = 0;
        }
    }

    // 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. Select one of 16 possible combinations of waveforms.
     *
     * @param phase Phase before waveform feedback changes the accumulator.
     * @param pulseHigh Pulse comparison latched before this update.
     */
    private void updateWaveform(int phase, boolean pulseHigh) {
        if (waveform != 0) {
            int waveValue = digitalValue(phase, pulseHigh);
            waveform_output = waveValue & (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 = waveValue;
            } else {
                osc3 = pulseNoiseReadback(waveform_output);
            }
            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;
    }

    float outputClocked(final WaveformGenerator ring_modulator) {
        if (outputMode == CACHED_OUTPUT) return previous_dac;
        if (outputMode == READY_ZERO_DELAYED) {
            if (ring_msb_mask != 0) noisePipelineRing = ~ring_modulator.accumulator & ring_msb_mask;
            return previous_dac;
        }
        if (outputMode >= READY_SIMPLE) {
            if (outputMode == READY_DIRECT) return analogLow[accumulator >> 12];
            int phase = (accumulator ^ (~ring_modulator.accumulator & ring_msb_mask)) >> 12;
            if (delayedTriSaw) previousSimplePhase = simplePhase;
            simplePhase = phase;
            return analogLow[phase];
        }
        switch (outputMode) {
            case READY_PULSE:
                // Recreate the previous clock's pulse latch; using current phase
                // here would expose the new comparison one clock too early.
                waveform_output = (accumulator_prev >> 12) >= pw ? 0xfff : 0;
                return waveform_output != 0 ? pulseHighDac : pulseLowDac;
            case NOISE_ZERO_FEEDBACK:
                accumulator &= 0x7fffff;
                return previous_dac;
            case COMBINED_FEEDBACK:
                return outputFeedback();
            case PULSE_TRIANGLE:
                return outputPulseTriangle(ring_modulator);
            case COMBINED_DELAYED:
                return outputDelayedCombined(ring_modulator);
            case TEST_RESTORE:
                return restoreTest(ring_modulator);
            case TEST_RING_STABLE:
                return (ring_modulator.accumulator & ring_msb_mask) == testRingInput
                        ? previous_dac : outputTest(ring_modulator);
            default:
                return outputFirstSample(ring_modulator);
        }
    }

    /** Keep first-sample setup separate so mixed playback can inline the steady renderer. */
    private float outputFirstSample(WaveformGenerator ring) {
        return switch (outputMode) {
            case PREPARE_SIMPLE -> { outputMode = READY_SIMPLE; yield outputSimple(ring); }
            case PREPARE_PULSE -> { outputMode = READY_PULSE; yield outputPulseClocked(); }
            case PREPARE_NOISE -> { outputMode = CACHED_OUTPUT; yield previous_dac = noiseDac; }
            case NOISE_ZERO_DELAYED -> { outputMode = READY_ZERO_DELAYED; yield outputSilentDelayed(ring); }
            case PREPARE_DIRECT -> { outputMode = READY_DIRECT; yield analogLow[accumulator >> 12]; }
            case TEST_PREPARE -> outputTest(ring);
            default -> outputComplex(ring);
        };
    }

    private float outputSimple(WaveformGenerator ring) {
        int phase = ringPhase(ring);
        if (delayedTriSaw) previousSimplePhase = simplePhase;
        simplePhase = phase;
        return analogLow[phase];
    }

    // Keep these phase/latch operations small enough to inline after mixed-waveform playback.
    private int ringPhase(WaveformGenerator ring) {
        return (accumulator ^ (~ring.accumulator & ring_msb_mask)) >> 12;
    }

    private int pulseComparison(int accumulator) {
        return (accumulator >> 12) >= pw ? 0xfff : 0;
    }

    private void latchPulse() {
        pulse_output = pulseComparison(accumulator);
    }

    private boolean pulseHigh() {
        return pulse_output != 0;
    }

    private float rememberAnalog(int phase, boolean high) {
        return previous_dac = (high ? analogHigh : analogLow)[phase];
    }

    private void setDigitalOutput(int value) {
        waveform_output = value;
        osc3 = pulseNoiseReadback(value);
    }

    private float outputPulseClocked() {
        // The previous accumulator is the pulse comparison latched before this clock, including SYNC resets.
        waveform_output = pulseComparison(accumulator_prev);
        return waveform_output != 0 ? pulseHighDac : pulseLowDac;
    }

    private float outputSilentDelayed(WaveformGenerator ring) {
        if (ring_msb_mask != 0) noisePipelineRing = ~ring.accumulator & ring_msb_mask;
        return previous_dac;
    }

    private float outputFeedback() {
        int phase = accumulator >> 12; // Sawtooth disables ring modulation.
        boolean high = pulseHigh();
        updateFeedback(phase, high);
        return rememberAnalog(phase, high);
    }

    private void updateFeedback(int phase, boolean high) {
        setDigitalOutput(combinedDigitalValue(phase, high) & (no_pulse | pulse_output));
        applyFeedback();
        latchEnabledPulse();
    }

    // The inherited 6581 combined-wave model feeds its top bit back into phase;
    // a zero output therefore still has an oscillator side effect.
    private void applyFeedback() {
        accumulator &= (waveform_output << 12) | 0x7fffff;
    }

    private void latchEnabledPulse() {
        if (no_pulse == 0) latchPulse();
    }

    private float outputPulseTriangle(WaveformGenerator ring) {
        int phase = ringPhase(ring);
        boolean high = pulseHigh();
        updatePulseTriangle(phase, high);
        return rememberAnalog(phase, high);
    }

    private void updatePulseTriangle(int phase, boolean high) {
        setDigitalOutput(combinedDigitalValue(phase, high) & pulse_output);
        latchPulse();
    }

    private float outputDelayedCombined(WaveformGenerator ring) {
        int phase = ringPhase(ring);
        boolean high = pulseHigh();
        updateDelayedCombined(phase, high);
        return rememberAnalog(phase, high);
    }

    private void updateDelayedCombined(int phase, boolean high) {
        int raw = combinedDigitalValue(phase, high);
        setDelayedOutput(raw);
        latchEnabledPulse();
    }

    private void setDelayedOutput(int raw) {
        int mask = no_pulse | pulse_output;
        waveform_output = raw & mask;
        osc3 = tri_saw_pipeline & mask;
        tri_saw_pipeline = raw;
    }

    /** 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;
    }

    // Explicit/manual output retains literal latch/feedback operations on extra
    // calls; only SID.clock() promises the optimized one-output-per-clock pattern.
    public float output(final WaveformGenerator ring_modulator) {
        if (legacyClockPrepared) legacyClockPrepared = false;
        else materialize();
        float sample = renderLiteral(ring_modulator);
        if (simpleWaveform) simplePhase = (accumulator ^ (~ring_modulator.accumulator & ring_msb_mask)) >> 12;
        selectOutputMode();
        return sample;
    }

    private float outputComplex(WaveformGenerator ring_modulator) {
        if (waveform > 8 && noise_output == 0) return outputZeroNoise(ring_modulator);
        return renderLiteral(ring_modulator);
    }

    private float renderLiteral(WaveformGenerator ring_modulator) {
        if (waveform == 0) {
            int oldOutput = waveform_output;
            int oldTtl = floating_output_ttl;
            updateWaveform(0, false);
            if (waveform_output != oldOutput || oldTtl == 1) previous_dac = digitalDac[waveform_output];
        } else {
            int phase = (accumulator ^ (~ring_modulator.accumulator & ring_msb_mask)) >> 12;
            boolean pulseHigh = pulse_output != 0;
            updateWaveform(phase, pulseHigh);
            // Preserve the floating-point backend's analog combined-waveform model.
            previous_dac = waveform <= 7 ? (pulseHigh ? analogHigh : analogLow)[phase]
                    : digitalDac[waveform_output];
        }
        return previous_dac;
    }

    private float outputTest(WaveformGenerator ring) {
        pulse_output = 0xfff;
        float sample = renderLiteral(ring);
        // At the fixed TEST phase, masking noise twice is idempotent. Noise+pulse's
        // extra pulldowns instead converge to zero (or the 8580's $fc0 cap).
        // The delayed OSC latch must also have caught up before reusing the sample.
        // Noise-reset decay invalidates this cache before its next output.
        if ((!noisePulse || waveform_output == 0 || (model == ChipModel.MOS8580 && waveform_output == 0xfc0))
                && (!delayedTriSaw || osc3 == waveform_output)) {
            testRingInput = ring.accumulator & ring_msb_mask;
            outputMode = fixedTestMode();
        } else outputMode = TEST_PREPARE;
        return sample;
    }

    private boolean testUsesRing() {
        return ring_msb_mask != 0 && basicWaveform != 0 && basicWaveform != 4;
    }

    private int fixedTestMode() {
        return testUsesRing() ? TEST_RING_STABLE : CACHED_OUTPUT;
    }

    private float restoreTest(WaveformGenerator ring) {
        if (ring_msb_mask != 0 && basicWaveform != 0 && basicWaveform != 4
                && (ring.accumulator & ring_msb_mask) != testRingInput) return outputTest(ring);
        waveform_output = testWaveform;
        osc3 = delayedTriSaw ? tri_saw_pipeline & no_noise_or_noise_output : pulseNoiseReadback(testWaveform);
        tri_saw_pipeline = testPipeline;
        pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
        outputMode = delayedTriSaw && osc3 != waveform_output ? TEST_RESTORE
                : ring_msb_mask == 0 || basicWaveform == 0 || basicWaveform == 4 ? CACHED_OUTPUT : TEST_RING_STABLE;
        return previous_dac;
    }

    /**
     * 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) {
        beforePulseWrite();
        pw = pw & 0xf00 | pw_lo & 0x0ff;
        latchPulse();
    }

    /**
     * Register functions.
     *
     * @param pw_hi high 8 bits of pulse width
     */
    void writePW_HI(final byte pw_hi) {
        beforePulseWrite();
        pw = pw_hi << 8 & 0xf00 | pw & 0x0ff;
        latchPulse();
    }

    private void beforePulseWrite() {
        if (outputMode == READY_ZERO_DELAYED) finishNoisePipeline();
    }

    /**
     * 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, WaveformGenerator ring) {
        if (noiseClockState == 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 ^ (~ring.accumulator & ring_msb_mask)) >> 12;
        int value = digitalValue(phase, pulse_output != 0) & (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 WaveformGenerator ring_modulator, final byte control) {
        if (test && (control & 8) != 0 && waveform == (control >> 4 & 15)
                && (outputMode == CACHED_OUTPUT || outputMode == TEST_RING_STABLE)
                && ring_msb_mask == ((~control >> 5 & control >> 2 & 1) << 23)) {
            writeFixedTestControl(ring_modulator, control);
        } else writeControl(ring_modulator, control);
    }

    private void writeFixedTestControl(WaveformGenerator ring, byte control) {
        if (no_pulse != 0 && (ring_msb_mask == 0 || basicWaveform == 0 || basicWaveform == 4
                || (ring.accumulator & ring_msb_mask) == testRingInput)) {
            // No selected pulse line: this unchanged TEST input is already the CPU-visible fixed point.
            sync = (control & 2) != 0;
            latchPulse();
            return;
        }
        if (waveform > 8 && noise_output == 0) {
            int oldPipeline = tri_saw_pipeline;
            sync = (control & 2) != 0;
            setDigitalOutput(0);
            if (delayedTriSaw) tri_saw_pipeline = digitalValue(ringPhase(ring), pulseHigh());
            latchPulse();
            testWaveform = 0;
            testPipeline = oldPipeline;
            outputMode = TEST_RESTORE;
            return;
        }
        int oldNoise = noise_output, oldWaveform = waveform_output, oldPipeline = tri_saw_pipeline;
        sync = (control & 2) != 0;
        int phase = ringPhase(ring);
        updateWaveform(phase, pulseHigh());
        simplePhase = phase;
        zeroRendered = false;
        // CONTROL still updates the visible latches immediately. If its TEST input
        // is unchanged, the next clock can restore the already-rendered fixed point.
        if (noise_output == oldNoise) {
            testWaveform = oldWaveform;
            testPipeline = oldPipeline;
            outputMode = TEST_RESTORE;
        } else selectOutputMode();
    }

    private void writeControl(final WaveformGenerator ring_modulator, final byte control) {
        if (waveform > 8 && noise_output == 0 && waveform == (control >> 4 & 15)
                && test == ((control & 8) != 0)) {
            writeZeroNoiseControl(ring_modulator, control);
            return;
        }
        materialize();
        float heldDac = previous_dac;
        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();
            selectWaveformTables();
            no_noise = (waveform & 8) != 0 ? 0 : 0xfff;
            no_pulse = (waveform & 4) != 0 ? 0 : 0xfff;
            no_noise_or_noise_output = no_noise | noise_output;
        }
        ring_msb_mask = (~control >> 5 & control >> 2 & 1) << 23;
        if (test != test_prev) changeTest(waveform_prev, ring_modulator);
        updateAfterControl(ring_modulator, waveform_prev);
        previous_dac = heldDac;
    }

    /** Same-waveform CONTROL writes cannot lift a zero noise mask or change the held DAC. */
    private void writeZeroNoiseControl(WaveformGenerator ring, byte control) {
        if (zeroRendered) latchPulse();
        // The old delayed value is masked to zero; CONTROL replaces its next-stage value.
        noisePipelinePending = false;
        ring_msb_mask = (~control >> 5 & control >> 2 & 1) << 23;
        sync = (control & 2) != 0;
        setDigitalOutput(0);
        if (delayedTriSaw) tri_saw_pipeline = digitalValue(ringPhase(ring), pulseHigh());
        if (topBitPulldown) applyFeedback();
        if (!holdNoiseStorage && !test && noiseClockState != 1) shift_register &= ~NOISE_OUTPUT_BITS;
        latchPulse();
        zeroRendered = Float.floatToRawIntBits(previous_dac) == Float.floatToRawIntBits(digitalDac[0]);
        selectOutputMode();
    }

    private void changeTest(int previousWaveform, WaveformGenerator ring) {
        if (test) {
            writeTestRising(previousWaveform, ring);
            accumulator = accumulator_prev = 0;
            noiseClockState = TEST_CLOCK;
            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 {
            noiseClockState = 0;
            shiftTest(previousWaveform);
        }
    }

    private void updateAfterControl(WaveformGenerator ring, int previousWaveform) {
        if (waveform != 0) {
            int phase = (accumulator ^ (~ring.accumulator & ring_msb_mask)) >> 12;
            updateWaveform(phase, pulse_output != 0);
            simplePhase = phase;
            if (waveform == 8) noiseDac = digitalDac[noise_output];
            zeroRendered = false;
        } 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;
        }
        selectOutputMode();
    }

    /**
     * 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 readOSC8580(this);
        }
    }

    /**
     * Reconstruct already elapsed digital state and read its OSC3 latch.
     * This does not clock pulse/noise or floating expiry; see
     * SIDWaveformTimingTest.oscReadsArePureForEveryVoiceAndWaveform.
     */
    private byte readOSC(int ringAccumulator, int myAccumulator) {
        materialize();
        return (byte) (osc3 >> 4);
    }

    /**
     * Restore the literal model's deferred digital/analog latches from saved
     * phases, without advancing time. CPU reads and configuration changes can
     * then observe the same state as an always-rendered oscillator.
     */
    private void materialize() {
        finishNoisePipeline();
        if (outputMode == READY_SIMPLE || outputMode == READY_DIRECT) {
            int phase = outputMode == READY_DIRECT ? accumulator >> 12 : simplePhase;
            previous_dac = analogLow[phase];
            waveform_output = digitalValue(phase, false);
            if (delayedTriSaw) {
                osc3 = previousSimplePhase < 0 ? tri_saw_pipeline : digitalValue(previousSimplePhase, false);
                tri_saw_pipeline = waveform_output;
            } else osc3 = waveform_output;
            pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
            outputMode = outputMode == READY_DIRECT ? PREPARE_DIRECT : PREPARE_SIMPLE;
        } else if (outputMode == READY_PULSE) {
            previous_dac = waveform_output != 0 ? pulseHighDac : pulseLowDac;
            osc3 = waveform_output;
            pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
        } else if (waveform == 8) {
            waveform_output = osc3 = noise_output;
            pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
        } else if ((zeroRendered && waveform > 8 && noise_output == 0)
                || ((outputMode == COMBINED_FEEDBACK || outputMode == COMBINED_DELAYED) && no_pulse != 0)) {
            pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
        }
    }

    /** Once the noise outputs are zero, their mask makes the complete output zero. */
    private float outputZeroNoise(WaveformGenerator ring) {
        if (!zeroRendered) {
            waveform_output = osc3 = 0;
            previous_dac = digitalDac[0];
            zeroRendered = true;
        }
        // Unselected LFSR bits can remain alive: their next shift still clocks normally
        // and reselects the renderer. Until then, writing zero to zero output bits is a no-op.
        // See SIDWaveformTimingTest.combinedNoiseRecoversAfterLongQuietPeriods.
        if (holdNoiseStorage || (shift_register & NOISE_OUTPUT_BITS) == 0) {
            selectBaseOutputMode();
            if (!delayedTriSaw) {
                if (topBitPulldown) accumulator &= 0x7fffff;
                return previous_dac;
            }
            noisePipelinePending = false;
            outputMode = READY_ZERO_DELAYED;
            return outputSilentDelayed(ring);
        }
        if (delayedTriSaw) {
            noisePipelinePhase = (accumulator ^ (~ring.accumulator & ring_msb_mask)) >> 12;
            noisePipelineHigh = pulse_output != 0;
            noisePipelinePending = true;
        }
        if (topBitPulldown) accumulator &= 0x7fffff;
        if (!holdNoiseStorage && !test && noiseClockState != 1) shift_register &= ~NOISE_OUTPUT_BITS;
        if ((waveform & 4) != 0) pulse_output = (accumulator >> 12) >= pw ? 0xfff : 0;
        return previous_dac;
    }

    // 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 (outputMode == READY_ZERO_DELAYED) {
            int phase = (accumulator ^ (noisePipelineRing & ring_msb_mask)) >> 12;
            tri_saw_pipeline = digitalValue(phase, no_pulse == 0 && pulseComparison(accumulator_prev) != 0);
            latchPulse();
            outputMode = NOISE_ZERO_DELAYED;
        } else if (noisePipelinePending) {
            tri_saw_pipeline = digitalValue(noisePipelinePhase, noisePipelineHigh);
            noisePipelinePending = false;
        }
    }

    /**
     * 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() {
        zeroRendered = false;
        if (noiseClockState != 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;
    }

    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;
        noiseDac = digitalDac[noise_output];
        if (noise_output != 0) zeroRendered = false;
        if (waveform >= 8) selectOutputMode();
        if (waveform == 8) {
            previous_dac = noiseDac;
            if (!test) outputMode = CACHED_OUTPUT;
        }
    }

    /**
     * SID reset.
     */
    void reset() {
        // Power-on accumulator survives SID reset.
        accumulator_prev = accumulator;
        waveform_output = osc3 = tri_saw_pipeline = 0;
        legacyClockPrepared = false;
        zeroRendered = noisePipelinePending = false;
        outputMode = COMPLEX;
        previous_dac = 0;
        // Reference reset seed: all ones followed by the forced release shift.
        // SIDRegisterRegressionTest.resetClocksNoiseRegisterOnce checks this contract.
        shift_latch = shift_register = 0x7ffffe;
        shift_register_reset = noiseClockState = 0;
        no_noise = no_pulse = pulse_output = 0xfff;
        set_noise_output();
        freq = pw = waveform = floating_output_ttl = ring_msb_mask = 0;
        configureWaveform();
        selectOutputMode();
        test = sync = false;
        previous_dac = 0;
    }

    /**
     * Return the waveform offset. The zero level is ideally 0x800.
     *
     * @return the waveform offset
     */
    public float getZeroLevel() {
        return wftable[0][0];
    }
}