summaryrefslogtreecommitdiff
path: root/Core/Src/Effects/ringmod.c
blob: 1b411dc9b6b78e9fceb6c4d6f4257ee026c617c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
 * ringmod.c
 *
 *  Created on: Aug 19, 2026
 *      Author: ozpv
 */

#include "cs4272.h"
#include "ringmod.h"
#include <math.h>
#include <float.h>

/* MF-102S ring modulator */
void ringmod(float *samples, const size_t range_min, const size_t range_max, const struct RingModParams *params) {
    static float lfo_phase = 0.0f;
    static float carrier_phase = 0.0f;

    const float sample_rate = (float)SAMPLE_RATE;
    const float inverse_sample_rate = 1.0f / sample_rate;

    /* samples are interleaved */
    for (size_t i = range_min; i < range_max; i += 2) {
        float frequency_lfo = 0.0f;

        if (params->square_lfo) {
            frequency_lfo = (lfo_phase < 0.5f) ? params->lfo_amount : -params->lfo_amount;
        } else {
            frequency_lfo = params->lfo_amount * sinf(M_TWOPI * lfo_phase);
        }

        float carrier = sinf(M_TWOPI * carrier_phase);

        samples[i] = (samples[i] * (1.0f - params->mix)) + (samples[i] * carrier * params->mix);

        lfo_phase += params->lfo_rate * inverse_sample_rate;
        lfo_phase = fmod(lfo_phase, 1.0f);

        carrier_phase += (params->frequency + frequency_lfo) * inverse_sample_rate;
        carrier_phase = fmod(carrier_phase, 1.0f);
    }
}