9 Commits

Author SHA1 Message Date
56b68bc963 wip: refactor out application methods 2023-08-07 15:01:35 +04:00
e3825b341d wip: application class 2023-08-07 13:27:25 +04:00
78c202a9d6 wip: logging 2023-08-07 12:05:06 +04:00
b02a5d2873 wip: templated ring buffer 2023-08-07 11:58:53 +04:00
64fa5c9271 wip: adder 2023-08-07 10:31:12 +04:00
6561666f7a fix: unitialized note struct 2023-08-07 02:32:34 +04:00
66c839e2ae wip: synth api && adder 2023-08-07 02:28:06 +04:00
d20dbd920f wip: synth class 2023-08-07 00:34:14 +04:00
850dedb319 wip: oscillator class 2023-08-06 23:33:51 +04:00
17 changed files with 747 additions and 0 deletions

22
inc/Adder.h Normal file
View File

@@ -0,0 +1,22 @@
#pragma once
#include <vector>
#include "Oscillator.h"
class Adder
{
private:
/* data */
public:
Adder(/* args */);
~Adder();
std::vector<float> & SumOscillators(const std::vector<Oscillator*> & oscillators, float duration);
};
Adder::Adder(/* args */)
{
}
Adder::~Adder()
{
}

29
inc/Application.h Normal file
View File

@@ -0,0 +1,29 @@
#pragma once
#include "Note.h"
#include "Synth.h"
#include "raylib.h"
#include "RingBuffer.h"
#include "Renderer.h"
class Application
{
private:
Synth m_synth;
RingBuffer<float>* m_ring_buffer;
AudioStream m_synth_stream;
int m_sound_played_count;
float* m_temp_buffer;
Note* m_current_note;
Renderer m_renderer;
std::size_t detect_note_pressed(Note* note);
void init_synth();
void init_audio();
void update_on_note_input();
void play_buffered_audio();
void fill_audio_buffer();
public:
Application(/* args */);
~Application();
void Run();
};

80
inc/KeyBoard.h Normal file
View File

@@ -0,0 +1,80 @@
#pragma once
#include "Settings.h"
#include <cmath>
#include <cstring>
#include <cstdlib>
#include <string>
class KeyBoard
{
private:
/* data */
static int get_semitone_shift_internal(char* root_note, char* target_note) {
char* pitch_classes[12] =
{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
// Extract the note number and pitch class for the root note
int root_note_num = (int)root_note[strlen(root_note) - 1] - '0';
char* root_pitch_class_str = (char*)malloc((strlen(root_note) - 1) * sizeof(char));
strncpy(root_pitch_class_str, root_note, strlen(root_note) - 1);
int root_pitch_class = -1;
for (int i = 0; i < 12; i++) {
if (strcmp(pitch_classes[i], root_pitch_class_str) == 0) {
root_pitch_class = i;
break;
}
}
free(root_pitch_class_str);
// Extract the note number and pitch class for the target note
int target_note_num = (int)target_note[strlen(target_note) - 1] - '0';
char* target_pitch_class_str =
(char*)malloc((strlen(target_note) - 1) * sizeof(char));
strncpy(target_pitch_class_str, target_note, strlen(target_note) - 1);
int target_pitch_class = -1;
for (int i = 0; i < 12; i++) {
if (strcmp(pitch_classes[i], target_pitch_class_str) == 0) {
target_pitch_class = i;
break;
}
}
free(target_pitch_class_str);
// Calculate the semitone shift using the formula
return (target_note_num - root_note_num) * 12 +
(target_pitch_class - root_pitch_class);
}
public:
KeyBoard(/* args */);
~KeyBoard();
static float GetHzBySemitone(int semitone) {
return PITCH_STANDARD * powf(powf(2.f, (1.f / 12.f)), semitone);
}
static int GetSemitoneShift(const std::string& target_note) {
char* target_note_cstr = new char[target_note.length() + 1];
strcpy(target_note_cstr, target_note.c_str());
int result = get_semitone_shift_internal("A4", target_note_cstr);
delete target_note_cstr;
return result;
}
};
KeyBoard::KeyBoard(/* args */)
{
}
KeyBoard::~KeyBoard()
{
}

6
inc/Logger.h Normal file
View File

@@ -0,0 +1,6 @@
#pragma once
#include "cstdio"
#define write_log(format,args...) do { \
printf(format, ## args); \
} while(0)

8
inc/Note.h Normal file
View File

@@ -0,0 +1,8 @@
#pragma once
#include <string>
struct Note {
std::string& name;
int length;
};

39
inc/Oscillator.h Normal file
View File

@@ -0,0 +1,39 @@
#pragma once
#include<vector>
#include "OscillatorType.h"
typedef float (Oscillator::*OscFunction)(void);
typedef float (Oscillator::*DtFunction)(float);
class Oscillator
{
private:
OscillatorType m_osc;
float m_freq;
float m_volume;
float m_phase;
float m_phase_dt;
OscFunction m_osc_function;
DtFunction m_dt_function;
void sine_osc_phase_incr();
void saw_osc_phase_incr();
float calc_saw_phase_delta(float freq);
float calc_sine_phase_delta(float freq);
float sawosc();
float triangleosc();
float squareosc();
float sign(float v);
float sineosc();
public:
Oscillator(OscillatorType osc, float freq, float volume);
~Oscillator();
OscillatorType GetType() { return m_osc; }
void SetType(OscillatorType osc);
float GetVolume() { return m_volume; }
void SetVolume(float volume) { m_volume = volume; }
float GetFreq() { return m_freq; }
void SetFreq(float freq);
void Reset();
float GenerateSample(float duration);
};

7
inc/OscillatorType.h Normal file
View File

@@ -0,0 +1,7 @@
#pragma once
typedef enum {
Sine,
Triangle,
Saw,
Square
} OscillatorType;

15
inc/Renderer.h Normal file
View File

@@ -0,0 +1,15 @@
#pragma once
class Renderer
{
private:
/* data */
public:
Renderer(/* args */);
~Renderer();
void Draw();
};

26
inc/RingBuffer.h Normal file
View File

@@ -0,0 +1,26 @@
#pragma once
#include <cstddef>
template <typename T>
class RingBuffer
{
private:
T* m_items; /* data */
std::size_t m_head;
std::size_t m_tail;
bool m_is_full;
bool m_is_empty;
std::size_t m_size;
void advance_pointer();
void retreat_pointer();
public:
RingBuffer(std::size_t size);
~RingBuffer();
bool IsFull() { return m_is_full; }
bool IsEmpty() { return m_is_empty; }
std::size_t GetSize();
std::size_t GetCapacity() { return m_size; }
void Reset();
void Write(T* data, size_t count);
bool Read(T* output, size_t count);
void Print();
};

16
inc/Settings.h Normal file
View File

@@ -0,0 +1,16 @@
#pragma once
#define SAMPLE_RATE 48000.f
#define BPM 120.f
#define BEAT_DURATION 60.f/BPM
#define PITCH_STANDARD 440.f
#define VOLUME 0.5f
#define ATTACK_MS 100.f
#define STREAM_BUFFER_SIZE 4096
#define SYNTH_PI 3.1415926535f
#define SYNTH_VOLUME 0.5f
#define WINDOW_WIDTH 640
#define WINDOW_HEIGHT 480
#define OSCILLATOR_PANEL_WIDTH 200

33
inc/Synth.h Normal file
View File

@@ -0,0 +1,33 @@
#pragma once
#include <vector>
#include "Oscillator.h"
#include "Note.h"
#include "Adder.h"
#include "Settings.h"
class Synth
{
private:
std::vector<Oscillator*> m_oscillators;
Adder m_adder;
//OscillatorUI* ui_oscillators;
//Note m_current_note;
std::vector<float> m_out_signal;
std::vector<float> & get_note(int semitone, float beats);
public:
Synth(/* args */);
~Synth();
void ProduceNoteSound(Note input);
const std::vector<float> & GetOutSignal() { return m_out_signal; }
};
Synth::Synth(/* args */)
{
m_oscillators.push_back(new Oscillator(OscillatorType::Sine, 440.f, VOLUME));
}
Synth::~Synth()
{
}

24
src/Adder.cpp Normal file
View File

@@ -0,0 +1,24 @@
#include "Adder.h"
#include "Settings.h"
#include <numeric>
std::vector<float> & Adder::SumOscillators(const std::vector<Oscillator*> & oscillators, float duration)
{
size_t sample_count = (size_t)(duration * SAMPLE_RATE);
std::vector<float> output;// = new std::vector<float>();
output.reserve(sample_count);
for (size_t i = 0; i < sample_count; i++)
{
float sample = 0.0f;
for (Oscillator* osc : oscillators)
{
sample += osc->GenerateSample(duration);
}
output.push_back(sample);
}
return output;
}

172
src/Application.cpp Normal file
View File

@@ -0,0 +1,172 @@
#include "Application.h"
#include "Settings.h"
#include "Logger.h"
#include <string>
Application::Application(/* args */)
{
m_ring_buffer = new RingBuffer<float>((std::size_t)STREAM_BUFFER_SIZE);
m_temp_buffer = new float[STREAM_BUFFER_SIZE];
init_synth();
init_audio();
}
Application::~Application()
{
delete m_ring_buffer;
delete m_temp_buffer;
}
void Application::init_audio()
{
m_sound_played_count = 0;
InitAudioDevice();
SetMasterVolume(SYNTH_VOLUME);
SetAudioStreamBufferSizeDefault(STREAM_BUFFER_SIZE);
m_synth_stream = LoadAudioStream(SAMPLE_RATE, sizeof(float) * 8, 1);
SetAudioStreamVolume(m_synth_stream, 0.5f);
PlayAudioStream(m_synth_stream);
}
void Application::init_synth()
{
//todo: move that variables to Synth declaration
std::string* nameString = new std::string(std::string(new char[3]));
m_current_note = new Note
{
.length = 1,
.name = (*nameString)
};
//todo: move somewhere in initialization
// synth.ui_oscillators = malloc(sizeof(OscillatorUI) * synth.oscillators.count);
// 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;
// }
}
std::size_t Application::detect_note_pressed(Note* note)
{
std::size_t is_pressed = 0;
note->length = 8;
if (IsKeyPressed(KEY_A))
{
note->name.assign("A4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_B))
{
note->name.assign("B4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_C))
{
note->name.assign("C4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_D))
{
note->name.assign("D4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_E))
{
note->name.assign("E4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_F))
{
note->name.assign("F4");
is_pressed = 1;
}
if (IsKeyPressed(KEY_G))
{
note->name.assign("G4");
is_pressed = 1;
}
return is_pressed;
}
// Update On Input
void Application::update_on_note_input()
{
if (detect_note_pressed(m_current_note))
{
m_synth.ProduceNoteSound((*m_current_note));
m_sound_played_count = 0;
write_log("Note played: %s\n", m_current_note->name);
}
}
// Play ring-buffered audio
void Application::play_buffered_audio()
{
if (IsAudioStreamProcessed(m_synth_stream) && !m_ring_buffer->IsEmpty())
{
std::size_t size_to_read = m_ring_buffer->GetSize();
write_log("Samples to play:%zu \n", size_to_read);
//todo: try to start reading directly from ring buffer, avoiding temp_buffer
m_ring_buffer->Read(m_temp_buffer, size_to_read);
// can try the SetAudioStreamCallback
UpdateAudioStream(m_synth_stream, m_temp_buffer, size_to_read);
// can overwrite the ring buffer to avoid that
if (m_synth.GetOutSignal().size() == m_sound_played_count)
{
m_ring_buffer->Reset();
}
}
}
// Fill ring buffer from current sound
void Application::fill_audio_buffer()
{
if (!m_ring_buffer->IsFull() && m_synth.GetOutSignal().size() != m_sound_played_count)
{
write_log("[INFO] IsFull:%d Samples:%zu Played:%d\n",
m_ring_buffer->IsFull(),
m_synth.GetOutSignal().size(),
m_sound_played_count);
// how many samples need write
std::size_t size_to_fill = 0;
if ((m_synth.GetOutSignal().size() - m_sound_played_count) > m_ring_buffer->GetCapacity())
{
size_to_fill = m_ring_buffer->GetCapacity();
} else
{
size_to_fill = m_synth.GetOutSignal().size() - m_sound_played_count;
}
write_log("[INFO] SizeToFill:%zu\n", size_to_fill);
for (size_t i = 0; i < size_to_fill; i++)
{
m_temp_buffer[i] = m_synth.GetOutSignal()[i];
}
m_ring_buffer->Write(m_temp_buffer, size_to_fill);
m_sound_played_count += size_to_fill;
}
}
void Application::Run()
{
// Main game loop
while (!WindowShouldClose()) // Detect window close button or ESC key
{
fill_audio_buffer();
play_buffered_audio();
update_on_note_input();
m_renderer.Draw();
}
}

112
src/Oscillator.cpp Normal file
View File

@@ -0,0 +1,112 @@
#include "Oscillator.h"
#include "Settings.h"
#define TWO_PI 2*SYNTH_PI
Oscillator::Oscillator(OscillatorType osc, float freq, float volume)
{
SetType(osc);
m_freq = freq;
m_volume = volume;
}
Oscillator::~Oscillator()
{
}
void Oscillator::Reset()
{
m_volume = 0;
m_phase = 0;
m_phase_dt = 0;
}
void Oscillator::SetType(OscillatorType osc)
{
m_osc = osc;
switch (m_osc) {
case Sine:
m_osc_function = &sineosc;
m_dt_function = &calc_sine_phase_delta;
break;
case Triangle:
m_osc_function = &triangleosc;
m_dt_function = &calc_saw_phase_delta;
break;
case Square:
m_osc_function = &squareosc;
m_dt_function = &calc_sine_phase_delta;
break;
case Saw:
m_osc_function = &sawosc;
m_dt_function = &calc_saw_phase_delta;
break;
}
}
void Oscillator::SetFreq(float freq)
{
m_freq = freq;
m_phase = 0;
m_phase_dt = m_dt_function(freq);
}
float Oscillator::GenerateSample(float duration)
{
return m_osc_function() * m_volume;
}
void Oscillator::sine_osc_phase_incr()
{
m_phase += m_phase_dt;
if (m_phase >= TWO_PI)
m_phase -= TWO_PI;
}
void Oscillator::saw_osc_phase_incr()
{
m_phase += m_phase_dt;
if (m_phase >= 1.0f)
m_phase -= 1.0f;
}
float Oscillator::calc_saw_phase_delta(float freq)
{
return freq / SAMPLE_RATE;
}
float Oscillator::calc_sine_phase_delta(float freq)
{
return (TWO_PI * freq) / SAMPLE_RATE;
}
float Oscillator::sineosc()
{
float result = sinf(m_phase);
sine_osc_phase_incr();
return result;
}
float Oscillator::sign(float v)
{
return (v > 0.0) ? 1.f : -1.f;
}
float Oscillator::squareosc()
{
return sign(sineosc());
}
float Oscillator::triangleosc()
{
float result = 1.f - fabsf(m_phase - 0.5f) * 4.f;
saw_osc_phase_incr();
return result;
}
float Oscillator::sawosc()
{
float result = m_phase * 2.f - 1.f;
saw_osc_phase_incr();
return result;
}

28
src/Renderer.cpp Normal file
View File

@@ -0,0 +1,28 @@
#include "Renderer.h"
#include "raylib.h"
#include "raygui.h"
#include "Settings.h"
Renderer::Renderer(/* args */)
{
InitWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "SeeSynth - v0.2");
SetTargetFPS(60);
}
Renderer::~Renderer()
{
}
void Renderer::Draw()
{
BeginDrawing();
ClearBackground(RAYWHITE);
//todo: implement renderer
//DrawUi(&synth);
//DrawSignal(&synth);
//DrawText("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY);
//DrawFPS(0,0);
EndDrawing();
}

106
src/RingBuffer.cpp Normal file
View File

@@ -0,0 +1,106 @@
#include "RingBuffer.h"
#include "Logger.h"
template <typename T> RingBuffer<T>::RingBuffer(std::size_t size)
{
m_items = new T[size];
m_head = 0;
m_tail = 0;
m_is_full = 0;
m_is_empty = 1;
m_size = size;
}
template <typename T> RingBuffer<T>::~RingBuffer()
{
delete m_items;
}
template <typename T> void RingBuffer<T>::Reset()
{
m_head = 0;
m_tail = 0;
m_is_full = 0;
}
template <typename T> void RingBuffer<T>::advance_pointer()
{
if (m_is_full) {
m_tail++;
if (m_tail == m_size) {
m_tail = 0;
}
}
m_head++;
if (m_head == m_size) {
m_head = 0;
}
std::size_t p_is_full = m_head == m_tail ? 1 : 0;
m_is_full = p_is_full;
}
template <typename T> void RingBuffer<T>::retreat_pointer()
{
m_is_full = 0;
m_tail++;
if (m_tail == m_size) {
m_tail = 0;
}
}
template <typename T> void RingBuffer<T>::Write(T* data, std::size_t count)
{
if (m_is_full || m_head + count > m_size) {
write_log("[WARN] Trying to overfill the ring buffer: \n\tIsFull:%d\n\tHead:%zu\n\tCount:%zu\n\t",
m_is_full,
m_head,
count);
return;
}
m_is_empty = 0;
for (std::size_t i = 0; i < count; i++) {
m_items[m_head] = data[i];
advance_pointer(buffer);
}
//m_is_empty = m_is_full && (m_head == m_tail);
}
template <typename T> bool RingBuffer<T>::Read(T* output, std::size_t count)
{
if (m_is_empty) {
write_log("[WARN] Trying to read empty buffer");
return 0;
}
for (std::size_t i = 0; i < count; i++) {
output[i] = m_items[m_tail];
retreat_pointer(buffer);
}
m_is_empty = !m_is_full && (m_head == m_tail);
return 1;
}
template <typename T> std::size_t RingBuffer<T>::GetSize()
{
size_t p_size = m_size;
if(!m_is_full) {
if(m_head >= m_tail) {
p_size = (m_head - m_tail);
}
else {
p_size = (m_size + m_head - m_tail);
}
}
return p_size;
}
template <typename T> void RingBuffer<T>::Print()
{
write_log("[INFO] The ring buffer: \n\tIsFull:%d\n\tIsEmpty:%d\n\tHead:%zu\n\tTail:%zu\n\t",
m_is_full,
m_is_empty,
m_head,
m_tail);
}

24
src/Synth.cpp Normal file
View File

@@ -0,0 +1,24 @@
#include "Synth.h"
#include "Settings.h"
#include "KeyBoard.h"
#include "OscillatorType.h"
std::vector<float> & Synth::get_note(int semitone, float beats)
{
float hz = KeyBoard::GetHzBySemitone(semitone);
float duration = beats * BEAT_DURATION;
// will change after oscillator starts to be more autonomous
for (Oscillator* osc : m_oscillators)
{
osc->SetFreq(hz);
}
return m_adder.SumOscillators(m_oscillators, duration); //todo: add other pipeline steps (e.g ADSR, Filters, FX);
}
void Synth::ProduceNoteSound(Note input) {
float length = 1.f / input.length;
int semitone_shift = KeyBoard::GetSemitoneShift(input.name);
m_out_signal = get_note(semitone_shift, length);
}