3 Commits

Author SHA1 Message Date
f88cba1843 fix: asserts && current note pointer 2023-07-14 00:20:43 +04:00
ce6a4d9ae5 wip: phase accumulated osc 2023-06-27 02:23:57 +04:00
2918cac022 feat: simple explanation given 2023-06-19 00:30:05 +04:00
5 changed files with 150 additions and 72 deletions

38
docs/Resources.md Normal file
View File

@@ -0,0 +1,38 @@
http://basicsynth.com/index.php?page=basic
Signal Generator
The most straightforward method of sound generation in software is to evaluate a periodic function for each sample time. A periodic function is any function that repeats at a constant interval, called the period. Consider the circle in the figure below. Starting at the 3:00 position and then sweeping around the circle counter-clockwise, we make a complete cycle in 2π radians and then the movement repeats. Thus the period is 2π radians. If we plot the points on the circumference over time we produce the waveform as shown below.
For audio signals, the period is the time it takes for the waveform to repeat and is thus the inverse of the frequency. In other words, a frequency of 100Hz repeats every 1/100 second. We need to generate an amplitude value for every sample time, thus the number of samples in one period is equal to the time of the period divided by the time of one sample. Since the time of one sample is the inverse of the sample rate, and the period is the inverse of the frequency, the number of samples is also the sample rate divided by the frequency: ((1/f) / (1/fs)) = (fs/f). Since our period is also equal to 2π radians, the phase increment for one sample time (φ) is 2π divided by the number of samples in one period:
where the frequency of the signal is f and the sample rate fs. The amplitude for any given sample is the y value of the phase at that point in time multiplied by the radius of the circle. In other words, the amplitude is the sine of the phase angle and we can also derive the phase increment from the sine function.
Signal Generation Equation
The value sn is the nth sample, An the peak amplitude (volume) at sample n, and θn the phase at sample n. To calculate θn for any sample n, we can multiply the phase increment for one sample time (φ) by the sample number. To calculate φ we need to determine the radians for one sample time at a given frequency. As there are 2π radians per cycle, we multiply the frequency by 2π to get the radians per second. The phase increment for one sample time is then the radians per second multiplied by the time for one sample. Substiting for θn in the original equation yields:
Signal Generation Equation
We can implement this as a program loop.
totalSamples = duration * sampleRate;
for (n = 0; n < totalSamples; n++)
sample[n] = sin((twoPI/sampleRate) * frequency * n);
Since /fs is constant through the loop, we can calculate it once. We can also replace the multiplication of the phase with a repeated addition.
phaseIncr = (twoPI/sampleRate) * frequency;
phase = 0;
totalSamples = duration * sampleRate;
for (n = 0; n < totalSamples; n++) {
sample[n] = sin(phase);
phase += phaseIncr;
if (phase >= twoPI)
phase -= twoPI;
}
We can replace the sin function with any periodic function that returns an amplitude for a given phase angle. Thus, this small piece of code can be used to produce a very wide range of sounds. Functionally, it is the software equivalent of an oscillator, the basic building block of almost all synthesizers.

34
main.c
View File

@@ -93,6 +93,8 @@ static OscillatorArray init_osc_array() {
};
Oscillator* oscArray = malloc(sizeof(Oscillator*) * 1);
assert(oscArray);
oscArray[0] = first;
OscillatorArray oscillators = {
@@ -109,7 +111,7 @@ SynthSound note(Synth* synth, int semitone, float beats) {
// will change after oscillator starts to be more autonomous
for (size_t i = 0; i < synth->oscillators.count; i++) {
synth->oscillators.array[i].freq = hz;
osc_set_freq(&synth->oscillators.array[i], hz);
}
return freq(duration, synth->oscillators);
@@ -160,6 +162,10 @@ size_t detect_note_pressed(Note* note) {
// GUI
//------------------------------------------------------------------------------------
void note_on(Synth *synth, Note *note) {
}
void DrawUi(Synth *synth) {
const int panel_x_start = 0;
const int panel_y_start = 0;
@@ -201,7 +207,11 @@ void DrawUi(Synth *synth) {
for (int ui_osc_i = 0; ui_osc_i < synth->oscillators.count; ui_osc_i++)
{
OscillatorUI* ui_osc = &synth->ui_oscillators[ui_osc_i];
assert(ui_osc);
Oscillator* osc = &synth->oscillators.array[ui_osc_i];
assert(osc);
const bool has_shape_param = (ui_osc->waveshape == Square);
// Draw Oscillator Panel
@@ -268,7 +278,11 @@ void DrawUi(Synth *synth) {
for (int ui_osc_i = 0; ui_osc_i < synth->oscillators.count; ui_osc_i += 1)
{
OscillatorUI* ui_osc = &synth->ui_oscillators[ui_osc_i];
assert(ui_osc);
Oscillator* osc = &synth->oscillators.array[ui_osc_i];
assert(osc);
// Shape select
int shape_index = (int)(ui_osc->waveshape);
bool is_dropdown_click = GuiDropdownBox(ui_osc->shape_dropdown_rect,
@@ -329,6 +343,8 @@ int main(int argc, char **argv) {
for (size_t i = 0; i < synth.oscillators.count; i++)
{
OscillatorUI* ui = &synth.ui_oscillators[i];
assert(ui);
ui->freq = synth.oscillators.array[i].freq;
ui->waveshape = synth.oscillators.array[i].osc;
ui->volume = synth.oscillators.array[i].volume;
@@ -353,9 +369,11 @@ int main(int argc, char **argv) {
//----------------------------------------------------------------------------------
// Fill ring buffer from current sound
SynthSound* sound = synth.out_signal;
assert(sound);
size_t size_for_buffer = 0;
if (!ring_buffer.is_full && sound->sample_count != sound_played_count) {
write_log("[INFO] IsFull:%d Samples:%zu Played:%zu\n",
write_log("[INFO] IsFull:%d Samples:%zu Played:%d\n",
ring_buffer.is_full,
sound->sample_count,
sound_played_count);
@@ -396,11 +414,11 @@ int main(int argc, char **argv) {
// Update On Input
//----------------------------------------------------------------------------------
Note current_note = synth.current_note;
if (detect_note_pressed(&current_note)) {
*sound = get_note_sound(&synth, current_note);
Note* current_note = &synth.current_note;
if (detect_note_pressed(current_note)) {
*sound = get_note_sound(&synth, *current_note);
sound_played_count = 0;
write_log("Note played: %s\n", current_note.name);
write_log("Note played: %s\n", current_note->name);
}
//----------------------------------------------------------------------------------
@@ -424,6 +442,8 @@ int main(int argc, char **argv) {
NoteArray note_array = parse_notes(buf, strlen(buf));
SynthSound* sounds = malloc(sizeof(SynthSound) * note_array.count);
assert(sounds);
for (size_t i = 0; i < note_array.count; i++) {
Note note = note_array.notes[i];
sounds[i] = get_note_sound(&synth, note);
@@ -431,6 +451,8 @@ int main(int argc, char **argv) {
SynthSound song = concat_sounds(sounds, note_array.count);
uint16_t* song_pcm = malloc(sizeof(uint16_t) * song.sample_count);
assert(song_pcm);
for (size_t i = 0; i < song.sample_count; i++) {
song_pcm[i] = toInt16Sample(song.samples[i]);
}

View File

@@ -3,6 +3,8 @@
#include "math.h"
#include "stdlib.h"
#define TWO_PI 2*SYNTH_PI
static SynthSound get_init_samples(float duration) {
size_t sample_count = (size_t)(duration * SAMPLE_RATE);
float* samples = malloc(sizeof(float) * sample_count);
@@ -23,42 +25,98 @@ static float pos(float hz, float x) {
return fmodf(hz * x / SAMPLE_RATE, 1);
}
static float sineosc(float hz, float x) {
return sinf(x * (2.f * SYNTH_PI * hz / SAMPLE_RATE));
static void sine_osc_phase_incr(Oscillator* osc) {
osc->phase += osc->phase_dt;
if (osc->phase >= TWO_PI)
osc->phase -= TWO_PI;
}
static void saw_osc_phase_incr(Oscillator* osc) {
osc->phase += osc->phase_dt;
if (osc->phase >= 1.0f)
osc->phase -= 1.0f;
}
static float calc_saw_phase_delta(float freq) {
return freq / SAMPLE_RATE;
}
static float calc_sine_phase_delta(float freq) {
return (TWO_PI * freq) / SAMPLE_RATE;
}
static float sineosc(Oscillator* osc) {
float result = sinf(osc->phase);
sine_osc_phase_incr(osc);
return result;
}
static float sign(float v) {
return (v > 0.0) ? 1.f : -1.f;
}
static float squareosc(float hz, float x) {
return sign(sineosc(hz, x));
static float squareosc(Oscillator* osc) {
return sign(sineosc(osc));
}
static float triangleosc(float hz, float x) {
return 1.f - fabsf(pos(hz, x) - 0.5f) * 4.f;
static float triangleosc(Oscillator* osc) {
float result = 1.f - fabsf(osc->phase - 0.5f) * 4.f;
saw_osc_phase_incr(osc);
return result;
}
static float sawosc(float hz, float x) {
return pos(hz, x) * 2.f - 1.f;
static float sawosc(Oscillator* osc) {
float result = osc->phase * 2.f - 1.f;
saw_osc_phase_incr(osc);
return result;
}
void osc_set_freq(Oscillator* osc, float freq) {
osc->freq = freq;
osc->phase = 0;
switch (osc->osc)
{
case Sine:
osc->phase_dt = calc_sine_phase_delta(freq);
break;
case Square:
osc->phase_dt = calc_sine_phase_delta(freq);
break;
case Triangle:
osc->phase_dt = calc_saw_phase_delta(freq);
break;
case Saw:
osc->phase_dt = calc_saw_phase_delta(freq);
break;
default:
break;
}
}
void osc_reset(Oscillator* osc) {
osc->volume = 0;
osc->phase = 0;
osc->phase_dt = 0;
}
float multiosc(OscillatorGenerationParameter param) {
float osc_sample = 0.f;
for (size_t i = 0; i < param.oscillators.count; i++) {
Oscillator osc = param.oscillators.array[i];
switch (osc.osc) {
Oscillator* osc = &param.oscillators.array[i];
assert(osc);
switch (osc->osc) {
case Sine:
osc_sample += sineosc(osc.freq, param.sample) * osc.volume;
osc_sample += sineosc(osc) * osc->volume;
break;
case Triangle:
osc_sample += triangleosc(osc.freq, param.sample) * osc.volume;
osc_sample += triangleosc(osc) * osc->volume;
break;
case Square:
osc_sample += squareosc(osc.freq, param.sample) * osc.volume;
osc_sample += squareosc(osc) * osc->volume;
break;
case Saw:
osc_sample += sawosc(osc.freq, param.sample) * osc.volume;
osc_sample += sawosc(osc) * osc->volume;
break;
}
}
@@ -67,63 +125,19 @@ float multiosc(OscillatorGenerationParameter param) {
}
SynthSound freq(float duration, OscillatorArray osc) {
SynthSound samples = get_init_samples(duration);
// SynthSound attack = get_attack_samples();
float* output = malloc(sizeof(float) * samples.sample_count);
for (int i = 0; i < samples.sample_count; i++) {
float sample = samples.samples[i];
size_t sample_count = (size_t)(duration * SAMPLE_RATE);
float* output = malloc(sizeof(float) * sample_count);
for (size_t i = 0; i < sample_count; i++) {
OscillatorGenerationParameter param = {
.oscillators = osc,
.sample = sample
.oscillators = osc
};
output[i] = multiosc(param);
}
// create attack and release
/*
let adsrLength = Seq.length output
let attackArray = attack |> Seq.take adsrLength
let release = Seq.rev attackArray
*/
/*
todo: I will change the ADSR approach to an explicit ADSR module(with it's own state)
size_t adsr_length = samples.sample_count;
float *attackArray = NULL, *releaseArray = NULL;
if (adsr_length > 0) {
//todo: calloc
attackArray = malloc(sizeof(float) * adsr_length);
size_t attack_length = attack.sample_count < adsr_length
? attack.sample_count
: adsr_length;
memcpy(attackArray, attack.samples, attack_length);
//todo: calloc
releaseArray = malloc(sizeof(float) * adsr_length);
memcpy(releaseArray, attackArray, attack_length);
reverse_array(releaseArray, 0, adsr_length);
}
*/
// if (samples.sample_count > 1024) {
// samples.sample_count = 1024;
// }
// //todo: move to somewhere
// for (size_t i = 0; i < 1024; i++) {
// synth_sound.samples[i] = 0.0f;
// }
// for (size_t i = 0; i < samples.sample_count; i++) {
// synth_sound.samples[i] = output[i];
// }
// synth_sound.sample_count = samples.sample_count;
// return zipped array
SynthSound res = {
.samples = output,
.sample_count = samples.sample_count
.sample_count = sample_count
};
return res;

View File

@@ -14,6 +14,8 @@ typedef struct Oscillator {
OscillatorType osc;
float freq;
float volume;
float phase;
float phase_dt;
} Oscillator;
typedef struct OscillatorArray {
@@ -23,9 +25,10 @@ typedef struct OscillatorArray {
typedef struct OscillatorGenerationParameter {
OscillatorArray oscillators;
float sample;
} OscillatorGenerationParameter;
void osc_set_freq(Oscillator* osc, float freq);
void osc_reset(Oscillator* osc);
float multiosc(OscillatorGenerationParameter param);
SynthSound freq(float duration, OscillatorArray osc);

View File

@@ -2,6 +2,7 @@
#define UTILS_H
#include "stdio.h"
#include "assert.h"
#define write_log(format,args...) do { \
printf(format, ## args); \