felixroos / kabelsalat

live coding audio graphs
https://kabel.salat.dev
GNU Affero General Public License v3.0
24 stars 5 forks source link

oscillator aliasing #28

Open felixroos opened 2 months ago

felixroos commented 2 months ago

sawtooth could be implemented with polyBLeP to remove aliasing:

float polyBLEP(float t, float dt) {
    if (t < dt) {
        float x = t / dt;
        return x + x - x * x - 1.0f;
    } else if (t > 1.0f - dt) {
        float x = (t - 1.0f) / dt;
        return x * x + x + x + 1.0f;
    } else {
        return 0.0f;
    }
}

float saw(float t, float freq, float dt) {
    t = fmod(t * freq, 1.0f);
    float output = 2.0f * t - 1.0f;
    output -= polyBLEP(t, dt);
    return output;
}

maybe square triangle as well?

felixroos commented 1 month ago

this works:

let sawblep = addUgen(
  "sawblep",
  class SawBlep {
    constructor() {
      this.phase = Math.random();
    }
    polyBlep(phase, dt) {
      // 0 <= phase < 1
      if (phase < dt) {
        phase /= dt;
        // 2 * (phase - phase^2/2 - 0.5)
        return phase + phase - phase * phase - 1;
      }
      // -1 < phase < 0
      else if (phase > 1 - dt) {
        phase = (phase - 1) / dt;
        // 2 * (phase^2/2 + phase + 0.5)
        return phase * phase + phase + phase + 1;
      }
      // 0 otherwise
      else {
        return 0;
      }
    }
    update(freq) {
      const dt = freq / sampleRate;
      let p = this.polyBlep(this.phase, dt);
      let s = 2 * this.phase - 1 - p;
      this.phase += dt;
      if (this.phase > 1) {
        this.phase -= 1;
      }
      return s;
    }
  }
);

pulse and triangle should get a similar treatment. more info here: https://www.martin-finke.de/articles/audio-plugins-018-polyblep-oscillator/