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.resid;
import libsidplay.common.ChipModel;
/**
* 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
* @author Dag Lem
* @author Antti Lankila
*/
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
}
/** Exact current DAC result; refreshed on counter or table changes. */
private int envelopeDac;
/**
* Whether hold is enabled. Only switching to ATTACK can release the envelope.
*/
private boolean hold_zero;
private int envelope_pipeline;
/**
* 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 rate_counter;
/**
* Comparison value (period) of the rate counter before the next event.
*/
private int rate_period;
/**
* During release mode, the SID approximates envelope decay via piecewise linear
* decay rate.
*/
private int exponential_counter;
/**
* Comparison value (period) of the exponential decay counter before the next
* decrement.
*/
private int exponential_counter_period;
/**
* Digital envelope value. $aa is the inherited deterministic power-on seed,
* not a guarantee of the starting level of every physical SID.
*/
private byte envelope_counter = (byte) 0xaa;
/**
* 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;
/**
* 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 release), 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(double[], double, boolean)
*/
private final short[] dac = new short[256];
/**
* Select the inherited chip-model approximation for envelope DAC bit weights.
* The cached level avoids repeated conversion and is refreshed immediately
* on a model change in this backend.
*
* @param chipModel The chip model to use.
*/
void setChipModel(final ChipModel chipModel) {
setDacNonlinearity(chipModel, chipModel == ChipModel.MOS6581 ? 2.20 : 2.00);
}
/** Refresh the analogue level without disturbing envelope timing or ENV3. */
void setDacNonlinearity(ChipModel chipModel, double ratio) {
final double[] dacBits = new double[8];
SID.kinkedDac(dacBits, ratio, chipModel == ChipModel.MOS8580);
for (int i = 0; i < 256; i++) {
double dacValue = 0;
for (int j = 0; j < 8; j++) {
if ((i & 1 << j) != 0) {
dacValue += dacBits[j];
}
}
dac[i] = (short) (dacValue + 0.5);
}
envelopeDac = dac[envelope_counter & 0xff];
}
/**
* 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 = envelope_counter;
exponential_counter = 0;
rate_counter = scheduledAction == STEP_ATTACK || exponential_counter_period == 1 ? 3 : 4;
if (scheduledAction == STEP_ATTACK) {
if (++envelope_counter == (byte) 0xff) {
next_state = State.DECAY_SUSTAIN;
state_pipeline = 3;
}
} else if (--envelope_counter == 0) {
hold_zero = true;
}
set_exponential_counter();
scheduleNextEvent();
return;
}
if (eventInterval > 1) advanceQuietClocks(eventInterval - 1);
env3 = envelope_counter;
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 (rate_counter != rate_period) {
if ((++rate_counter & 0x8000) != 0) rate_counter = (rate_counter + 1) & 0x7fff;
} else {
reset_rate_counter = true;
}
scheduleNextEvent();
}
/** Literal reference path for overlapping phases that cannot be skipped. */
private void clockPipelines() {
boolean countUp = attackGate;
if (new_exponential_counter_period != 0) {
exponential_counter_period = 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) rate_period = ENVELOPE_PERIOD[decay];
else if (state_pipeline == 0) {
state = State.ATTACK;
rate_period = ENVELOPE_PERIOD[attack];
hold_zero = false;
}
break;
case DECAY_SUSTAIN:
if (state_pipeline == 0) {
state = State.DECAY_SUSTAIN;
rate_period = ENVELOPE_PERIOD[decay];
}
break;
case RELEASE:
if ((state == State.ATTACK && state_pipeline == 0)
|| (state == State.DECAY_SUSTAIN && state_pipeline == 1)) {
state = State.RELEASE;
rate_period = 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_zero) {
if (countUp) {
if (++envelope_counter == (byte) 0xff) {
next_state = State.DECAY_SUSTAIN;
state_pipeline = 3;
}
} else if (--envelope_counter == 0) {
hold_zero = true;
}
set_exponential_counter();
}
} else if (exponential_pipeline != 0 && --exponential_pipeline == 0) {
exponential_counter = 0;
// Sustain inhibition follows GATE before the delayed attack latch.
if (attackGate || !gate || envelope_counter != (byte) (sustain * 0x11)) {
envelope_pipeline = 1;
}
} else if (reset_rate_counter) {
rate_counter = 0;
reset_rate_counter = false;
if (attackGate) {
exponential_counter = 0;
envelope_pipeline = 2;
} else if (!hold_zero && ++exponential_counter == exponential_counter_period) {
exponential_pipeline = exponential_counter_period != 1 ? 2 : 1;
}
}
}
int output() {
return envelopeDac;
}
private void set_exponential_counter() {
envelopeDac = dac[envelope_counter & 0xff];
// Check for change of an exponential counter-period.
switch (envelope_counter) {
case -1:
new_exponential_counter_period = 1;
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;
case 0x00:
// FIXME: Check whether 0x00 really changes the period.
// E.g. set R = 0xf, gate on to 0x06, gate off to 0x00, gate on to
// 0x04,
// gate off, sample.
new_exponential_counter_period = 1;
// When the envelope counter is changed to zero, it is frozen at
// zero.
// This has been verified by sampling ENV3.
hold_zero = true;
break;
}
}
/**
* Constructor.
*/
EnvelopeGenerator() {
}
/**
* SID reset.
*/
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;
rate_counter = 0;
exponential_counter = 0;
exponential_counter_period = 1;
state = next_state = State.RELEASE;
rate_period = ENVELOPE_PERIOD[release];
hold_zero = false;
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 && exponential_counter_period == 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;
}
// Revisit the pipeline next clock; GATE acceptance still takes the
// phase-dependent latency above, rather than changing state here.
scheduledAction = CLOCK_PIPELINES;
eventInterval = cyclesUntilEvent = 1;
}
}
/**
* @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] : rate_period;
if (nextPeriod != rate_period) {
materialize();
rate_period = 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] : rate_period;
if (nextPeriod != rate_period || (state == State.DECAY_SUSTAIN && nextSustain != sustain)) {
// Reconstruct a pending sustain comparison using the old level.
materialize();
sustain = nextSustain;
release = nextRelease;
rate_period = 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 : envelope_counter;
}
/**
* 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() {
// Consecutive register writes in one SID cycle already share this phase.
if (cyclesUntilEvent == eventInterval) return;
env3 = envelope_counter;
advanceQuietClocks(eventInterval - cyclesUntilEvent);
eventInterval = cyclesUntilEvent;
}
private void advanceRateCounter(int cycles) {
rate_counter += cycles;
// This wraps the linearized LFSR sequence, not a binary 15-bit counter:
// skip zero. Bounded intervals need at most one such wrap.
if (rate_counter > 0x7fff) {
rate_counter = (rate_counter + 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;
}
rate_counter = rate_period;
reset_rate_counter = true;
if (cycles == comparisonDelay) return;
int afterReset = cycles - comparisonDelay - 1;
int rateLength = rate_period + 1;
int resets = 1;
int phase = afterReset;
if (afterReset >= rateLength) {
resets += afterReset / rateLength;
phase = afterReset % rateLength;
}
rate_counter = Math.min(phase + 1, rate_period);
reset_rate_counter = phase == rate_period;
if (state == State.ATTACK) {
exponential_counter = 0;
envelope_pipeline = Math.max(2 - phase, 0);
} else if (!hold_zero) {
int remainder = (exponential_counter + resets) % exponential_counter_period;
exponential_counter = remainder;
if (remainder == 0) {
int delay = exponential_counter_period == 1 ? 1 : 2;
if (phase < delay) {
exponential_counter = exponential_counter_period;
exponential_pipeline = delay - phase;
} else if (phase == delay && (state == State.RELEASE
|| envelope_counter != (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;
if (state_pipeline != 0) {
eventInterval = cyclesUntilEvent = 1;
return;
}
int delay = 1;
if (!((new_exponential_counter_period | state_pipeline | envelope_pipeline | exponential_pipeline) != 0
|| reset_rate_counter)) {
// Comparison precedes incrementing the counter. A pending reset
// survives a subsequent CPU rate write, including an equal rate.
comparisonDelay = rate_period - rate_counter + 1;
if (comparisonDelay <= 0) comparisonDelay += 0x7fff;
if (hold_zero || (state == State.DECAY_SUSTAIN
&& envelope_counter == (byte) (sustain * 0x11) && exponential_counter < exponential_counter_period)) {
// 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 (exponential_counter < exponential_counter_period) {
scheduledAction = STEP_DECAY;
delay = comparisonDelay + (exponential_counter_period - exponential_counter - 1) * (rate_period + 1)
+ (exponential_counter_period == 1 ? 3 : 4);
} else {
// Keep the literal comparator path for an exponential counter
// already beyond its comparison value.
delay = comparisonDelay;
}
}
eventInterval = cyclesUntilEvent = delay;
}
}