EnvelopeGenerator.java

/**
 * This file is part of reSID, a MOS6581 SID emulator engine.
 * Copyright (C) 2004  Dag Lem <resid@nimrod.no>
 * Copyright 2011-2022 Leandro Nini <drfiemost@users.sourceforge.net>
 * Copyright 2018 VICE Project
 * 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;

/**
 * A 15-bit counter is used to implement the envelope rates, in effect dividing
 * the clock to the envelope counter by the currently selected rate period.
 * <p>
 * In addition, another counter is used to implement the exponential envelope
 * decay, in effect further dividing the clock to the envelope counter. The
 * period of this counter is set to 1, 2, 4, 8, 16, 30 at the envelope counter
 * values 255, 93, 54, 26, 14, 6, respectively.
 * <p>
 * Hardware behavior: GATE changes and rate comparisons have latency; their
 * overlap affects retriggered notes. Implementation: keep the inherited reSID/VICE
 * pipeline model, but skip settled intervals up to the next envelope change.
 * Evidence: VICE-testprogs SID/env_test/readme.txt records 6581/8580 hardware
 * checks. SIDDigitalBoundaryTest compares GATE/retrigger boundaries with independent
 * perfect6581 transistor traces. SIDEnvelopeTimingTest checks event skipping
 * against the literal pipeline; that establishes software equivalence only.
 *
 * @author Ken Händel
 *
 */
public final class EnvelopeGenerator {
    /**
     * The envelope state machine's distinct states. In addition to this, the envelope
     * has a hold mode, which freezes the envelope counter to zero.
     */
    private enum State {
        ATTACK, DECAY_SUSTAIN, RELEASE
    }

    /**
     * Whether hold is enabled. Only switching to ATTACK can release the envelope.
     */
    boolean hold;

    /**
     * Linearized phase of the hardware rate LFSR's 0x7fff-state sequence.
     * Integer comparison positions replace its bit patterns; wrapping skips zero
     * to preserve the reference model's period and ADSR delay.
     */
    private int rateCounter;

    /**
     * Comparison value (period) of the rate counter before the next event.
     */
    private int rateCounterPeriod;

    /**
     * During release mode, the SID approximates envelope decay via piecewise
     * linear decay rate.
     */
    private int exponentialCounter;

    /**
     * Comparison value (period) of the exponential decay counter before the next
     * decrement.
     */
    private int exponentialCounterPeriod;

    /**
     * Digital envelope value. $aa is the inherited deterministic power-on seed,
     * not a guarantee of the starting level of every physical SID.
     */
    private byte envelopeValue = (byte) 0xaa;

    /**
     * The current analog value of the envelope output.
     */
    private float envelopeValueDac;

    /**
     * Voice mute (kill envelope output)
     */
    private boolean muted;

    // Software mute and DAC-table changes latch on the next SID clock in this
    // backend, even at a held level. This is an API contract, not a hardware stage;
    // SIDEnvelopeTimingTest.powerOnResetAndDacLatchesMatch preserves its timing.
    private boolean dacDirty;

    /**
     * Attack register
     */
    private int attack;

    /**
     * Decay register
     */
    private int decay;

    /**
     * Sustain register
     */
    private int sustain;

    /**
     * Release register
     */
    private int release;

    /**
     * Gate bit
     */
    private boolean gate;

    /** Attack-rate latch; the counter uses its value from the preceding clock. */
    private boolean attackGate;

    /**
     * Current envelope state
     */
    private State state;

    // Countdown stages in the inherited reSID/VICE model. Their ordering matters
    // when a GATE write overlaps an outstanding envelope or divider operation.
    private State next_state = State.RELEASE;
    private int state_pipeline, exponential_pipeline, new_exponential_counter_period;
    private boolean reset_rate_counter;
    private byte env3;

    // Event skipping is an optimization of the per-clock model: rate/divider
    // phase and ENV3 sampling still evolve. Writes reconstruct that phase before
    // rescheduling; unsettled pipelines run literally. STEADY means a constant
    // envelope level, not stopped internal counters.
    private int cyclesUntilEvent = 1;
    private int eventInterval = 1;

    private static final int CLOCK_PIPELINES = 0, STEP_ATTACK = 1, STEP_DECAY = 2, STEADY = 3;
    private int scheduledAction;
    private int comparisonDelay;
    private int envelope_pipeline;


    /**
     * Rate-counter comparison positions for the attack, decay and release settings.
     * <p>
     * Rate counter periods are calculated from the Envelope Rates table in the
     * Programmer's Reference Guide; the inherited sampling method is described
     * below. A complete rate cycle includes the delayed reset clock, so its length
     * is the table value + 1. Exponential division and envelope pipelines add latency.
     * <p>
     * The rate counter is modeled as a linearized 15-bit LFSR phase. A comparison
     * match schedules its reset for the following clock; it does not immediately
     * change the envelope. Keeping that pending reset separate is necessary for
     * rate writes on a comparison boundary.
     * <p>
     * NB! Sampling ENV3 shows that the calculated values are not exact. It may seem
     * like most calculated values have been rounded (.5 is rounded down) and 1 has
     * been added to the result. A possible explanation for this is that the SID
     * designers have used the calculated values directly as rate counter comparison
     * values, not considering a one-cycle delay to zero the counter. This would
     * yield an actual period of comparison value + 1.
     * <p>
     * The time of the first envelope count cannot be exactly controlled, except
     * possibly by resetting the chip. Because of this we cannot do cycle exact
     * sampling and must devise another method to calculate the rate counter
     * periods.
     * <p>
     * The exact rate counter periods can be determined e.g., by counting the number
     * of cycles from envelope level 1 to envelope level 129, and dividing the
     * number of cycles by 128. CIA1 timer A and B in linked mode can perform the
     * cycle count. This is the method used to find the rates below.
     * <p>
     * To avoid the ADSR delay bug, sampling of ENV3 should be done using sustain =
     * release = 0. This ensures that the attack state will not lower the current
     * rate counter period.
     * <p>
     * The ENV3 sampling code below yields a maximum timing error of 14 cycles.
     *
     * <pre>
     *      lda #$01
     *  l1: cmp $d41c
     *      bne l1
     *      ...
     *      lda #$ff
     *  l2: cmp $d41c
     *      bne l2
     * </pre>
     * <p>
     * This yields a maximum error for the calculated rate period of 14/128 cycles.
     * The described method is thus enough for an exact calculation of the rate
     * periods.
     */
    private static final int[] ENVELOPE_PERIOD = {8, // 2ms*1.0MHz/256 = 7.81
            31, // 8ms*1.0MHz/256 = 31.25
            62, // 16ms*1.0MHz/256 = 62.50
            94, // 24ms*1.0MHz/256 = 93.75
            148, // 38ms*1.0MHz/256 = 148.44
            219, // 56ms*1.0MHz/256 = 218.75
            266, // 68ms*1.0MHz/256 = 265.63
            312, // 80ms*1.0MHz/256 = 312.50
            391, // 100ms*1.0MHz/256 = 390.63
            976, // 250ms*1.0MHz/256 = 976.56
            1953, // 500ms*1.0MHz/256 = 1953.13
            3125, // 800ms*1.0MHz/256 = 3125.00
            3906, // 1 s*1.0MHz/256 = 3906.25
            11719, // 3 s*1.0MHz/256 = 11718.75
            19531, // 5 s*1.0MHz/256 = 19531.25
            31250 // 8 s*1.0MHz/256 = 31250.00
    };

    /**
     * Decay/release division and sustain comparison: historical reSID measurements.
     * <P>
     * For decay and release, the clock to the envelope counter is sequentially
     * divided by 1, 2, 4, 8, 16, 30, 1 to create a piece-wise linear approximation
     * of an exponential. The exponential counter-period is loaded at the envelope
     * counter-values 255, 93, 54, 26, 14, 6, 0. The period can be different for the
     * same envelope counter-value, depending on whether the envelope has been
     * rising (attack -> release) or sinking (decay/release).
     * <P>
     * Since it is not possible to reset the rate counter (the test bit has no
     * influence on the envelope generator whatsoever) a method must be devised to
     * do cycle exact sampling of ENV3 to do the investigation. This is possible
     * with knowledge of the rate period for A=0, found above.
     * <P>
     * The CPU can be synchronized with ENV3 by first synchronizing with the rate
     * counter by setting A=0 and wait in a carefully timed loop for the envelope
     * counter _not_ to change for 9 cycles. We can then wait for a specific value
     * of ENV3 with another timed loop to fully synchronize with ENV3.
     * <P>
     * At the first period when an exponential counter-period larger than one is
     * used (decay or relase), one extra cycle is spent before the envelope is
     * decremented. The envelope output is then delayed one cycle until the state is
     * changed to attack. Now one cycle less will be spent before the envelope is
     * incremented, and the situation is normalized.
     * <P>
     * The delay is probably caused by the comparison with the exponential counter,
     * and does not seem to affect the rate counter. This has been verified by
     * timing 256 consecutive complete envelopes with A = D = R = 1, S = 0, using
     * CIA1 timer A and B in linked mode. If the rate counter is not affected, the
     * period of each complete envelope is
     * <P>
     * (255 + 162*1 + 39*2 + 28*4 + 12*8 + 8*16 + 6*30)*32 = 756*32 = 32352
     * <P>
     * which corresponds exactly to the timed value divided by the number of
     * complete envelopes.
     * <P>
     * <P>
     * From the sustain levels it follows that both the low and high 4 bits of the
     * envelope counter are compared to the 4-bit sustain value. This has been
     * verified by sampling ENV3.
     */

    /**
     * Emulated nonlinearity of the envelope DAC.
     *
     * @see SID#kinkedDac(int, float, int)
     */
    private final float[] dac = new float[256];

    /**
     * SID clocking - 1 cycle.
     */
    void clock() {
        if (--cyclesUntilEvent == 0) {
            clockEvent();
        }
    }

    /** Execute the reference clock at the next cycle that can change state. */
    private void clockEvent() {

        if (scheduledAction == STEP_ATTACK || scheduledAction == STEP_DECAY) {
            // With unchanged timing inputs, collapse the literal comparator,
            // reset and envelope stages. By this step the rate phase is already
            // 3, or 4 when the exponential divider contributes an extra stage.
            env3 = envelopeValue;
            exponentialCounter = 0;
            rateCounter = scheduledAction == STEP_ATTACK || exponentialCounterPeriod == 1 ? 3 : 4;
            if (scheduledAction == STEP_ATTACK) {
                if (++envelopeValue == (byte) 0xff) {
                    next_state = State.DECAY_SUSTAIN;
                    state_pipeline = 3;
                }
            } else if (--envelopeValue == 0) {
                hold = true;
            }
            set_exponential_counter();
            envelopeValueDac = muted ? 0 : dac[envelopeValue & 0xff];
            scheduleNextEvent();
            return;
        }
        advanceQuietClocks(eventInterval - 1);
        env3 = envelopeValue;
        if ((new_exponential_counter_period | state_pipeline | envelope_pipeline | exponential_pipeline) != 0
                || reset_rate_counter) {
            clockPipelines();
        }
        // The comparator is latched before the rate counter is reset.
        // A reduced ADSR rate must still wait for the 15-bit counter to wrap.
        if (rateCounter != rateCounterPeriod) {
            if ((++rateCounter & 0x8000) != 0) rateCounter = (rateCounter + 1) & 0x7fff;
        } else {
            reset_rate_counter = true;
        }
        if (dacDirty) {
            envelopeValueDac = muted ? 0 : dac[envelopeValue & 0xff];
            dacDirty = false;
        }
        scheduleNextEvent();
    }

    /** Literal reference path for overlapping phases that cannot be skipped. */
    private void clockPipelines() {
        boolean countUp = attackGate;
        if (new_exponential_counter_period != 0) {
            exponentialCounterPeriod = new_exponential_counter_period;
            new_exponential_counter_period = 0;
        }
        if (state_pipeline != 0) {
            --state_pipeline;
            switch (next_state) {
                case ATTACK:
                    // Retriggering briefly uses the decay comparator before attack.
                    // VICE SID/env_test covers this "single cycle at decay rate".
                    if (state_pipeline == 1) rateCounterPeriod = ENVELOPE_PERIOD[decay];
                    else if (state_pipeline == 0) {
                        state = State.ATTACK;
                        rateCounterPeriod = ENVELOPE_PERIOD[attack];
                        hold = false;
                    }
                    break;
                case DECAY_SUSTAIN:
                    if (state_pipeline == 0) {
                        state = State.DECAY_SUSTAIN;
                        rateCounterPeriod = ENVELOPE_PERIOD[decay];
                    }
                    break;
                case RELEASE:
                    if ((state == State.ATTACK && state_pipeline == 0)
                            || (state == State.DECAY_SUSTAIN && state_pipeline == 1)) {
                        state = State.RELEASE;
                        rateCounterPeriod = ENVELOPE_PERIOD[release];
                    }
                    break;
            }
        }
        // A short GATE pulse can drop this latch while the coarse state still
        // says ATTACK. Counter direction follows one clock after rate selection.
        attackGate = state == State.ATTACK && !(next_state == State.ATTACK && state_pipeline == 1);
        // The else-if priority is observable when GATE overlaps a pending step:
        // completing one stage must not also consume the next stage this clock.
        if (envelope_pipeline != 0 && --envelope_pipeline == 0) {
            if (!hold) {
                if (countUp) {
                    if (++envelopeValue == (byte) 0xff) {
                        next_state = State.DECAY_SUSTAIN;
                        state_pipeline = 3;
                    }
                } else if (--envelopeValue == 0) {
                    hold = true;
                }
                dacDirty = true;
                set_exponential_counter();
            }
        } else if (exponential_pipeline != 0 && --exponential_pipeline == 0) {
            exponentialCounter = 0;
            // Sustain inhibition follows GATE before the delayed attack latch.
            if (attackGate || !gate || envelopeValue != (byte) (sustain * 0x11)) {
                envelope_pipeline = 1;
            }
        } else if (reset_rate_counter) {
            rateCounter = 0;
            reset_rate_counter = false;
            if (attackGate) {
                exponentialCounter = 0;
                envelope_pipeline = 2;
            } else if (!hold && ++exponentialCounter == exponentialCounterPeriod) {
                exponential_pipeline = exponentialCounterPeriod != 1 ? 2 : 1;
            }
        }
    }

    /**
     * Set a nonlinearity parameter for imperfect analog DAC emulation. 1.0 means
     * perfect 8580-like linearity, values between 0.95 - 0.97 are probably
     * realistic 6581 nonlinearity values.
     *
     * @param nonLinearity non-linearity
     */
    void setNonLinearity(final float nonLinearity) {
        materialize();
        for (int i = 0; i < 256; i++) {
            dac[i] = SID.kinkedDac(i, nonLinearity, 8);
        }
        dacDirty = true;
        scheduleNextEvent();
    }

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

    /**
     * Latch the reference model's divider changes for the next clock. The period
     * reset at level zero retains the unverified corner noted by the integer
     * backend's set_exponential_counter(); reference agreement does not resolve it.
     */
    private void set_exponential_counter() {
        switch (envelopeValue & 0xff) {
            case 0xff: new_exponential_counter_period = 1; break;
            case 0x00:
                new_exponential_counter_period = 1;
                // Zero freezes the counter after an attack wrap as well as release.
                hold = true;
                break;
            case 0x5d: new_exponential_counter_period = 2; break;
            case 0x36: new_exponential_counter_period = 4; break;
            case 0x1a: new_exponential_counter_period = 8; break;
            case 0x0e: new_exponential_counter_period = 16; break;
            case 0x06: new_exponential_counter_period = 30; break;
        }
    }

    /** SID reset preserves the envelope counter. */
    void reset() {
        env3 = readENV();
        // Reset preserves the level; constructor initialization is a separate
        // model operation (SIDEnvelopeTimingTest.powerOnResetAndDacLatchesMatch).
        envelope_pipeline = 0;
        exponential_pipeline = 0;
        state_pipeline = 0;
        new_exponential_counter_period = 0;
        reset_rate_counter = true;
        attack = decay = sustain = release = 0;
        gate = false;
        attackGate = false;
        rateCounter = 0;
        exponentialCounter = 0;
        exponentialCounterPeriod = 1;
        state = next_state = State.RELEASE;
        rateCounterPeriod = ENVELOPE_PERIOD[release];
        hold = false;
        envelopeValueDac = muted ? 0 : dac[envelopeValue & 0xff];
        dacDirty = false;
        scheduleNextEvent();
    }

    /**
     * Software mute, latched next clock; the digital envelope keeps running.
     *
     * @param enable enable
     */
    void mute(final boolean enable) {
        materialize();
        muted = enable;
        dacDirty = true;
        scheduleNextEvent();
    }

    // ----------------------------------------------------------------------------
    // Register functions.
    // ----------------------------------------------------------------------------

    /**
     * @param control control register
     */
    void writeCONTROL_REG(final byte control) {
        boolean gate_next = (control & 1) != 0;
        if (gate_next != gate) {
            materialize();
            // GATE does not restart the rate counter. Outstanding stages decide
            // whether the new attack/release can take effect before a pending step.
            boolean peakReset = next_state == State.DECAY_SUSTAIN && state_pipeline == 3;
            gate = gate_next;
            if (gate_next && peakReset) {
                // The newly detected $ff edge resets attack on the next clock,
                // even when a GATE rise arrives during that same cycle.
                state_pipeline = 2;
            } else if (gate_next) {
                next_state = State.ATTACK;
                state_pipeline = 2;
                if (reset_rate_counter && exponentialCounterPeriod == 1) {
                    // A nonterminal exponential divider must finish normally;
                    // a GATE rise alone cannot generate an envelope count.
                    envelope_pipeline = state == State.ATTACK ? 2 : 3;
                } else if (exponential_pipeline == 2) {
                    // Preserve the pending divider count across the direction change.
                    envelope_pipeline = 3;
                    exponential_pipeline = 0;
                } else if (exponential_pipeline == 1) {
                    state_pipeline = 3;
                }
            } else {
                next_state = State.RELEASE;
                state_pipeline = envelope_pipeline > 0 ? 3 : 2;
            }
            scheduleNextEvent();
        }
    }

    /**
     * @param attack_decay attack/decay value
     */
    void writeATTACK_DECAY(final byte attack_decay) {
        attack = attack_decay >> 4 & 0x0f;
        decay = attack_decay & 0x0f;
        int nextPeriod = state == State.ATTACK ? ENVELOPE_PERIOD[attack]
                : state == State.DECAY_SUSTAIN ? ENVELOPE_PERIOD[decay] : rateCounterPeriod;
        if (nextPeriod != rateCounterPeriod) {
            materialize();
            rateCounterPeriod = nextPeriod;
            scheduleNextEvent();
        }
    }

    /**
     * @param sustain_release sustain/release value
     */
    void writeSUSTAIN_RELEASE(final byte sustain_release) {
        int nextSustain = sustain_release >> 4 & 0x0f;
        int nextRelease = sustain_release & 0x0f;
        int nextPeriod = state == State.RELEASE ? ENVELOPE_PERIOD[nextRelease] : rateCounterPeriod;
        if (nextPeriod != rateCounterPeriod || (state == State.DECAY_SUSTAIN && nextSustain != sustain)) {
            // Reconstruct a pending sustain comparison using the old level.
            materialize();
            sustain = nextSustain;
            release = nextRelease;
            rateCounterPeriod = nextPeriod;
            scheduleNextEvent();
        } else {
            sustain = nextSustain;
            release = nextRelease;
        }
    }

    /**
     * Read ENV3's sample from before this cycle's envelope step, without clocking.
     *
     * @return envelope counter
     */
    public byte readENV() {
        // On an event cycle ENV3 still holds the value sampled before that
        // event. The first skipped clock samples the unchanged current value.
        return cyclesUntilEvent == eventInterval ? env3 : envelopeValue;
    }

    /**
     * Return the analog value of the envelope.
     *
     * @return envelope analog output
     */
    /** Current envelope code for analogue DC modelling, distinct from the delayed ENV3 readback. */
    public int analogEnvelopeLevel() {
        return muted ? 0 : envelopeValue & 0xff;
    }

    public float output() {
        return envelopeValueDac;
    }


    /**
     * Reconstruct elapsed clocks under the old register values before a write.
     * This preserves pending comparisons even for multiple writes without a clock;
     * see SIDEnvelopeTimingTest.allRateChangesAroundPeriodBoundariesMatch.
     */
    private void materialize() {
        env3 = readENV();
        advanceQuietClocks(eventInterval - cyclesUntilEvent);
        eventInterval = cyclesUntilEvent;
    }

    private void advanceRateCounter(int cycles) {
        rateCounter += cycles;
        // This wraps the linearized LFSR sequence, not a binary 15-bit counter:
        // skip zero. Bounded intervals need at most one such wrap.
        if (rateCounter > 0x7fff) {
            rateCounter = (rateCounter + 1) & 0x7fff;
        }
    }

    /**
     * Count elapsed rate resets by quotient/remainder, then restore divider and
     * pipeline phase. Even at sustain these clocks affect the next GATE write;
     * see SIDEnvelopeTimingTest.longSteadyIntervalsAndSubsequentGateWritesMatch.
     */
    private void advanceQuietClocks(int cycles) {
        if (scheduledAction == CLOCK_PIPELINES || cycles < comparisonDelay) {
            advanceRateCounter(cycles);
            return;
        }
        rateCounter = rateCounterPeriod;
        reset_rate_counter = true;
        if (cycles == comparisonDelay) return;

        int afterReset = cycles - comparisonDelay - 1;
        int rateLength = rateCounterPeriod + 1;
        int resets = 1;
        int phase = afterReset;
        if (afterReset >= rateLength) {
            resets += afterReset / rateLength;
            phase = afterReset % rateLength;
        }
        rateCounter = Math.min(phase + 1, rateCounterPeriod);
        reset_rate_counter = phase == rateCounterPeriod;
        if (state == State.ATTACK) {
            exponentialCounter = 0;
            envelope_pipeline = Math.max(2 - phase, 0);
        } else if (!hold) {
            int remainder = (exponentialCounter + resets) % exponentialCounterPeriod;
            exponentialCounter = remainder;
            if (remainder == 0) {
                int delay = exponentialCounterPeriod == 1 ? 1 : 2;
                if (phase < delay) {
                    exponentialCounter = exponentialCounterPeriod;
                    exponential_pipeline = delay - phase;
                } else if (phase == delay && (state == State.RELEASE
                        || envelopeValue != (byte) (sustain * 0x11))) {
                    envelope_pipeline = 1;
                }
            }
        }
    }

    // Wait for the next comparison and any full rate cycles still needed by
    // the exponential divider. The final comparison then needs +3 pipeline
    // clocks for attack/period-one decay, or +4 with the extra exponential stage.
    private void scheduleNextEvent() {
        scheduledAction = CLOCK_PIPELINES;
        int delay = 1;
        if (!((new_exponential_counter_period | state_pipeline | envelope_pipeline | exponential_pipeline) != 0
                || reset_rate_counter || dacDirty)) {
            // Comparison precedes incrementing the counter. A pending reset
            // survives a subsequent CPU rate write, including an equal rate.
            comparisonDelay = rateCounterPeriod - rateCounter + 1;
            if (comparisonDelay <= 0) comparisonDelay += 0x7fff;
            if (hold || (state == State.DECAY_SUSTAIN
                    && envelopeValue == (byte) (sustain * 0x11) && exponentialCounter < exponentialCounterPeriod)) {
                // No observable change before a CPU write. Bound checkpoints
                // so elapsed arithmetic stays small for arbitrarily long playback.
                scheduledAction = STEADY;
                delay = 0x7fff;
            } else if (state == State.ATTACK) {
                scheduledAction = STEP_ATTACK;
                delay = comparisonDelay + 3;
            } else if (exponentialCounter < exponentialCounterPeriod) {
                scheduledAction = STEP_DECAY;
                delay = comparisonDelay + (exponentialCounterPeriod - exponentialCounter - 1) * (rateCounterPeriod + 1)
                        + (exponentialCounterPeriod == 1 ? 3 : 4);
            } else {
                // Keep the literal comparator path for an exponential counter
                // already beyond its comparison value.
                delay = comparisonDelay;
            }
        }
        eventInterval = cyclesUntilEvent = delay;
    }
}