Why do the tutorials show smoothing gain like this?

I wonder why some tutorials show storing a previousLevel variable and comparing it to see if it has changed, and then deciding whether to applyGain or applyGainRamp, like this:

        if (currentGain == previousGain)
        {
            buffer.applyGain (currentGain);
        }
        else
        {
            buffer.applyGainRamp (0, buffer.getNumSamples(), previousGain, currentGain);
            previousGain = currentGain;
        }

… when the applyGainRamp function checks to see if the startGain and endGain are the same and then just calls applyGain?:

    void applyGainRamp (int channel, int startSample, int numSamples,
                        Type startGain, Type endGain) noexcept
    {
        if (! isClear)
        {
            if (startGain == endGain)
            {
                applyGain (channel, startSample, numSamples, startGain);
            }
            else
            {
                jassert (isPositiveAndBelow (channel, numChannels));
                jassert (startSample >= 0 && numSamples >= 0 && startSample + numSamples <= size);

                const auto increment = (endGain - startGain) / (float) numSamples;
                auto* d = channels[channel] + startSample;

                while (--numSamples >= 0)
                {
                    *d++ *= startGain;
                    startGain += increment;
                }
            }
        }
    }

It seems you can just call applyGainRamp() with the previousLevel and level and let the function handle it.

Premature optimization, a mistake? Maybe some subtle detail involved? Are you having an actual problem with the code as it is? (Remember that the tutorials are just that, tutorials, and not explanations on how to write perfect, production-ready, code.)

It wasn’t written in one go, the check was added 7 years later (haven’t checked the full detail, there might have been more steps in the history)

Yeah, probably the tutorials are just old and maybe the function did not used to have that check… I wish sometimes they were more up to date on best examples of JUCE coding.

I’m not having “a problem” with the code; rather I’ve seen that in several tutorials and I was doing it that way myself until I checked the applyGainRamp code. I no longer see any reason for doing it the tutorial way. It’s not a big deal but I thought I would mention it in case anyone ever watches these threads about cleaning up tutorials.

1 Like