CircuitFilter.java
/*
* Analogue filter ported from libresidfp (see src/test/resources/sid/circuit).
* Copyright 2004,2010 Dag Lem
* Copyright 2007-2010 Antti Lankila
* Copyright 2011-2026 Leandro Nini
* SPDX-License-Identifier: GPL-2.0-or-later
*/
package builder.resid.residfp.circuit;
import builder.resid.residfp.Filter;
import libsidplay.config.IFilterSection;
/** Filter/mixer/volume circuit with immutable shared tables and per-chip calibration. */
public final class CircuitFilter extends Filter {
private final CircuitModelConfig model;
private final Integrator first = new Integrator(), second = new Integrator();
private char[] summer, mixer, resonance;
private char[][] resonanceTables;
private int bandpass, lowpass, gateVoltage, currentFactor, cutoffVoltageSquared;
private double curve = 0.5, range = 0.5, capacitance = 470, resonanceScale = 1;
private double vcrMultiplier;
private char[] vcrCurrents;
private char[] cutoffDac;
public CircuitFilter(boolean mos6581) {
model = CircuitModelConfig.get(mos6581);
resonanceTables = model.resonance;
clockFrequency = 1e6;
updateCalibration();
updatedResonance();
updatedMixing();
}
public void configure(IFilterSection settings) {
setCurveProperties(settings.getCircuitCurve(), settings.getCircuitRange(),
settings.getCircuitCapacitance(), 0);
setDistortionProperties(0, 0, settings.getResonanceFactor());
}
@Override
public void setCurveAndDistortionDefaults() {
setCurveProperties(0.5f, 0.5f, 470, 0);
setDistortionProperties(0, 0, 1);
}
@Override
public float[] getCurveProperties() {
return new float[]{(float) curve, (float) range, (float) capacitance};
}
@Override
public void setCurveProperties(float curve, float range, float capacitance, float unused) {
unitInterval(curve, "curve");
unitInterval(range, "range");
if (!Float.isFinite(capacitance) || capacitance < 330 || capacitance > 2200)
throw new IllegalArgumentException("Circuit capacitance must be 330..2200 pF");
if (this.curve == curve && this.range == range && this.capacitance == capacitance) return;
this.curve = curve;
this.range = range;
this.capacitance = capacitance;
updateCalibration();
}
private static void unitInterval(float value, String name) {
if (!Float.isFinite(value) || value < 0 || value > 1)
throw new IllegalArgumentException("Circuit " + name + " must be 0..1");
}
@Override
public float[] getDistortionProperties() { return new float[]{0, 0, (float) resonanceScale}; }
@Override
public void setDistortionProperties(float unused, float unused2, float resonance) {
if (!Float.isFinite(resonance) || resonance < 0 || resonance > 2)
throw new IllegalArgumentException("Circuit resonance factor must be 0..2");
if (resonanceScale == resonance) return;
resonanceTables = model.resonanceTables(resonance);
resonanceScale = resonance;
updatedResonance();
}
@Override
protected void setClockFrequency(double clock) {
if (!Double.isFinite(clock) || clock <= 0) throw new IllegalArgumentException("Invalid SID clock");
clockFrequency = clock;
updateCalibration();
}
private void updateCalibration() {
if (model.mos6581) {
double ucox = (1 + 39 * range) * 1e-6;
double coefficient = model.voltageRange * ucox / (2 * clockFrequency * capacitance * 1e-12);
currentFactor = (int) (8192 * coefficient / 115) & 65535;
double multiplier = ucox * 470 / capacitance * 1e6 / clockFrequency;
if (vcrCurrents == null || vcrMultiplier != multiplier) {
vcrMultiplier = multiplier;
vcrCurrents = new char[65536];
for (int i = 0; i < vcrCurrents.length; i++)
vcrCurrents[i] = (char) (model.vcrCurrent[i] * multiplier);
}
cutoffDac = new char[2048];
double zero = 7.15 + 2 * curve - 1;
for (int i = 0; i < cutoffDac.length; i++)
cutoffDac[i] = (char) model.normalize(zero + model.cutoffDac[i] * 2.63);
} else {
gateVoltage = model.normalize(4.75 * 1.01 * (1.8 - curve * 3 / 5) - 0.8);
}
updatedCenterFrequency();
}
@Override
protected void updatedCenterFrequency() {
if (model.mos6581) {
int difference = model.nvddt - cutoffDac[fc];
cutoffVoltageSquared = difference * difference >>> 1;
} else {
double wl = 0, bit = 0.00615;
for (int i = 0; i < 11; i++, bit *= 2) if ((fc & (1 << i)) != 0) wl += bit;
if (fc == 0) wl = 0.00615 / 2;
currentFactor = (int) (131072 * model.voltageRange * 100e-6 / (2 * clockFrequency * 22e-9) * wl) & 65535;
}
}
@Override
protected void updatedResonance() { resonance = resonanceTables[res]; }
@Override
protected void updatedMixing() {
int inputs = (filt1 ? 1 : 0) + (filt2 ? 1 : 0) + (filt3 ? 1 : 0) + (filtE ? 1 : 0);
int outputs = 4 - inputs + (lp ? 1 : 0) + (bp ? 1 : 0) + (hp ? 1 : 0);
if (!voice3off && !filt3) outputs--;
summer = model.summer[inputs];
mixer = model.mixer[outputs];
}
@Override
protected void resetState() {
bandpass = lowpass = 0;
first.charge = first.input = second.charge = second.input = 0;
}
/** Normalized, centred waveform/envelope products; envelope codes select the 6581 DC offset. */
public int clockNormalized(float v1, float v2, float v3, float external, int env1, int env2, int env3) {
int input = 0, output = 0;
if (filt1) input += model.voice(v1, env1); else output += mixerVoice(v1, env1);
if (filt2) input += model.voice(v2, env2); else output += mixerVoice(v2, env2);
if (filt3) input += model.voice(v3, env3); else if (voice3off) output += mixerVoice(v3, env3);
if (filtE) input += model.voice(external, 0); else output += mixerVoice(external, 0);
int highpass = summer[input + lowpass + resonance[bandpass]];
bandpass = first.solve(highpass);
lowpass = second.solve(bandpass);
if (lp) output += lowpass;
if (bp) output += bandpass;
if (hp) output += highpass;
return model.volume[Math.round(vol * 15)][mixer[output]] - 32768;
}
private int mixerVoice(float value, int env) {
return model.voice(model.mos6581 ? value * 1.07f : value, env);
}
@Override
protected float clock(float v1, float v2, float v3, float external) {
return clockNormalized(v1, v2, v3, external, 0, 0, 0);
}
// The native model asserts at these table limits for some extreme calibrations.
// Saturate to the measured voltage range instead of reading outside a table.
private static int bounded(int value) { return Math.max(0, Math.min(65535, value)); }
private final class Integrator {
int input, charge;
int solve(int voltage) {
if (model.mos6581) {
int vgst = model.nvddt - input, vgdt = model.nvddt - voltage;
int square = vgdt * vgdt;
int snake = currentFactor * ((vgst * vgst - square) >> 15);
int gate = model.vcrGate[(cutoffVoltageSquared + (square >>> 1)) >>> 16];
int kVgt = gate - model.nvt - model.nvmin;
int source = kVgt - input + 32768, drain = kVgt - voltage + 32768;
int forward = vcrCurrents[bounded(source)] << 15;
int reverse = vcrCurrents[bounded(drain)] << 15;
charge += snake + forward - reverse;
} else {
int vgst = gateVoltage - input, vgdt = Math.max(gateVoltage - voltage, 0);
charge += currentFactor * ((vgst * vgst - vgdt * vgdt) >> 15) >> 4;
}
input = model.opampReverse[bounded((charge >> 15) + 32768)];
return bounded(input - (charge >> 14));
}
}
}