electro-smith / DaisySP

A Powerful DSP Library in C++
https://www.electro-smith.com/daisy
Other
882 stars 139 forks source link

Envelope timings incorrect #185

Open fhoenig opened 1 year ago

fhoenig commented 1 year ago

Looks like attack is in seconds but decay and release are off by a factor of ~5 w.r.t. them being seconds. Is this a know issue / intended?

#include <daisysp.h>
#include <chrono>
#include <thread>

daisysp::Oscillator osc;
daisysp::Metro      tick;
daisysp::Adsr       env;
bool gate = false;

void testaudio(void *userData, Uint8 *buffer, int length)
{
    memset(buffer, 0, length);
    int numToWrite = length / (sizeof(float) * 2);
    float *sampleBuffer = (float*)buffer;
    float osc_out, env_out;
    for (int sample = 0; sample < numToWrite; sample++)
    {
        // When the metro ticks, trigger the envelope to start.
        //if (tick.Process())
        //{
        //    gate = !gate;
        //}

        // Use envelope to control the amplitude of the oscillator.
        env_out = env.Process(true);
        osc.SetAmp(env_out);
        osc_out = osc.Process();

        *sampleBuffer++ = osc_out; // Left channel value
        *sampleBuffer++ = osc_out; // Right channel value
    }
}

int main(int argc, char* argv[])
{
    SDL_Init(SDL_INIT_AUDIO);
    SDL_AudioSpec requested = {};
    requested.freq = 48000;
    requested.samples = 2048;
    requested.format = AUDIO_F32;
    requested.channels = 2;
    requested.callback = testaudio;

    SDL_AudioSpec obtained = {};
    int deviceId = SDL_OpenAudioDevice(nullptr, 0, &requested, &obtained, 0);

    osc.Init(obtained.freq);
    osc.SetFreq(440);
    tick.Init(1.0f, obtained.freq);
    env.Init(obtained.freq);
    env.SetTime(daisysp::ADSR_SEG_ATTACK, 0.0);
    env.SetTime(daisysp::ADSR_SEG_DECAY, 1.0);
    env.SetTime(daisysp::ADSR_SEG_RELEASE, 1.0);
    env.SetSustainLevel(0);

    SDL_PauseAudioDevice(deviceId, false);
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::microseconds(100));
    }
    return 0;
}
takumi-ogata commented 1 year ago

Hi Florian,

The ADSR is ported from here (https://paulbatchelor.github.io/res/soundpipe/docs/adsr.html). Here's a note about it on that page:

NOTE: The attack, decay, and release parameters are "fuzzy" values that don't exactly correspond to duration in seconds. More accurately, they are special tau constant units that feed into the filter used to generate the envelope. The attack value specificly undergoes some "creative" modificiations in order to create snappier attack times. It is highly recommend to tune parameters by ear rather than to read the values literally.

For more reference: https://ccrma.stanford.edu/~jos/mdft/Exponentials.html https://ccrma.stanford.edu/~jos/mdft/Audio_Decay_Time_T60.html

We could clarify all of this in a documentation, comments in the example code, and etc. Thank you for bringing this topic up. We can look into this more and have a discussion.