/* This file was generated by scramble.py. */
#line 1 "src/sound.py"
#include "sound.h"
#line 12
static float wave_square(float x) {
    return 1 - 2 * ((int)(x * 2) & 1);
}
static float envelope(Envelope * e, float x) {
    float v = 0;
    if (x < e->attack) {
        v = e->volume * x / e->attack;
    }
#line 18
    else {
#line 20
        float x_ = x - e->attack;
        if (x_ < e->decay) {
            v = e->volume + (e->sustain - e->volume) * x_ / e->decay;
        }
#line 22
        else {
#line 24
            v = e->sustain;
            x_ -= e->decay;
            if (x_ > e->hold) {
                x_ -= e->hold;
                if (x_ < e->release) {
                    v = e->sustain - e->sustain * x_ / e->release;
                }
#line 29
                else {
#line 31
                    v = 0;
                }
            }
        }
    }
#line 33
    return v;
}
static int16_t float_to_signed_16(float s) {
    int c = (s + 1) * 32767.5 - 32768;
    if (c < - 32768) {
#line 37
        c = - 32768;
    }
#line 38
    else if (c > 32767) {
#line 38
        c = 32767;
    }
#line 39
    return c;
}
LandSound * sound_synthesize(Envelope * e, int note) {
    float duration = e->attack;
    duration += e->decay;
    duration += e->hold;
    duration += e->release;
#line 47
    float frequency = 48000;
#line 49
    int length = duration * frequency;
#line 51
    LandSound * sound = land_sound_new(length, frequency, 16, 2);
#line 53
    uint16_t * data = land_sound_sample_pointer(sound);
#line 55
    float x = 0;
    for (int i = 0; i < length; i++) {
        float t = i;
        t *= 1 / frequency /* Convert to seconds. */;
        float v = envelope(e, t);
#line 61
        float tone_frequency = 440 * pow(2.0, (note - 69) / 12.0);
#line 63
        float y = wave_square(x);
#line 65
        y *= v;
#line 67
        data [i * 2] = float_to_signed_16(y);
        data [i * 2 + 1] = float_to_signed_16(y);
#line 70
        x += tone_frequency / frequency;
    }
    return sound;
}
/* This file was generated by scramble.py. */
