Need some help with adding gain in a waveshaper plugin

So Ive made a basic waveshaper, but Im having an issue correctly applying gain. So for example, if I used a tanh(x) soft clip as my waveshaper, since the function limits at -1 and 1, no matter how much pregain I apply, Im never getting an absurd amount of output difference. But if I use a polynomial or any formula not limited at -+1, when applying gain I start to get some absurd output levels well beyond 50db clipping. Currently Im using the the “setGainDecibles” method used in the waveshaper JUCE tutorial as such


So my 2 questions are ,

  1. Is there a better way to apply gain in this situation? Or do I need to more carefully choose my formulas so that they limit at -+1? How would I do asymmetrical wavehshaping in this case?

  2. How do mainstream plugins implement this? For example, decapitator or saturn. Though you can distort it quite a bit the output volume difference is not that great, even with the auto output turned off.

Indeed you have to make sure that the output signal amplitude of your plugin lies in between -1.0 and 1.0., everything else is digital clipping and might create unpleasant results when the following plugin doesn’t handle bigger values correctly or the output is converted back to 24Bit integer values and is then sent out to your audio interface.

But, you can still exceed these values in internal computation stages. And this constraint doesn’t stop you from creating asymetric waveshapers, just create a function that softly hits the +/-1 line at it’s edges. You can have a look at the asymetric waveshaper implementation of a guitar distortion plugin I’m currently building:, with some math you can create shapers that consist of multiple part-functions that have an exactly same slope at the points where they meet, so just define the part of the asymetrical shape you are looking for and try to find some function that smoothes out the edges

Hey thank you so much for your reply and sharing some sample code! Writing different functions for different values seems like a good solution. I don’t know why I didn’t try that I think I just thought it wouldn’t be cpu friendly lol. Thanks again

@PluginPenguin would you mind explaining the logic of oversampling before waveshaping? I am pretty new to this :slight_smile:

Edit: thinking about it more, I suppose it’s because the waveshaping introduces aliasing.

Yes exactly, if you take at the spectrum that results from a sine wave being clipped by a wave shaper you’ll see a rich overtone spectrum arise above the fundamental frequency you fed into it. High frequencies then would lead to aliasing which means that these frequencies begin to occur on the low end of the spectrum which sounds really strange. The higher sample rate makes “room” for these overtones and the filter prior to the downsampling will remove these inaudible high frequencies safely again.

1 Like