Emulator
This commit is contained in:
parent
34d15a7f1c
commit
2b6e1d2c6b
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
noicesynth_linux
|
||||
miniaudio.h
|
||||
43
EMULATOR.md
Normal file
43
EMULATOR.md
Normal file
@ -0,0 +1,43 @@
|
||||
# NoiceSynth Linux Emulator
|
||||
|
||||
This folder contains a Linux-based prototype for the NoiceSynth engine. It allows you to develop and visualize the DSP code on a desktop computer before deploying it to the RP2040 hardware.
|
||||
|
||||
## Architecture
|
||||
|
||||
* **Engine (`synth_engine.cpp`):** The exact same C++ code used on the microcontroller. It uses fixed-point math (or integer-based phase accumulation) to generate audio.
|
||||
* **Host (`main.cpp`):** A Linux wrapper that uses:
|
||||
* **Miniaudio:** For cross-platform audio output.
|
||||
* **SDL2:** For real-time oscilloscope visualization.
|
||||
|
||||
## Quick Start (Distrobox)
|
||||
|
||||
If you don't want to install dependencies manually, use the included script. It creates a lightweight container, installs the tools, and compiles the project.
|
||||
|
||||
1. Ensure you have `distrobox` and a container engine (Docker or Podman) installed.
|
||||
2. Run the build script:
|
||||
```bash
|
||||
./compile_with_distrobox.sh
|
||||
```
|
||||
3. Run the synthesizer:
|
||||
```bash
|
||||
./noicesynth_linux
|
||||
```
|
||||
|
||||
## Manual Build
|
||||
|
||||
If you prefer to build directly on your host machine:
|
||||
|
||||
1. **Install Dependencies:**
|
||||
* **Debian/Ubuntu:** `sudo apt install build-essential libsdl2-dev wget`
|
||||
* **Fedora:** `sudo dnf install gcc-c++ SDL2-devel wget`
|
||||
* **Arch:** `sudo pacman -S base-devel sdl2 wget`
|
||||
|
||||
2. **Download Miniaudio:**
|
||||
```bash
|
||||
wget https://raw.githubusercontent.com/mackron/miniaudio/master/miniaudio.h
|
||||
```
|
||||
|
||||
3. **Compile:**
|
||||
```bash
|
||||
make
|
||||
```
|
||||
18
Makefile
Normal file
18
Makefile
Normal file
@ -0,0 +1,18 @@
|
||||
# Compiler and flags
|
||||
CXX = g++
|
||||
CXXFLAGS = -std=c++17 -Wall -Wextra -I. $(shell sdl2-config --cflags)
|
||||
LDFLAGS = -ldl -lm -lpthread $(shell sdl2-config --libs)
|
||||
|
||||
# Source files
|
||||
SRCS = main.cpp synth_engine.cpp
|
||||
|
||||
# Output binary
|
||||
TARGET = noicesynth_linux
|
||||
|
||||
all: $(TARGET)
|
||||
|
||||
$(TARGET): $(SRCS)
|
||||
$(CXX) $(CXXFLAGS) -o $(TARGET) $(SRCS) $(LDFLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(TARGET)
|
||||
44
compile_with_distrobox.sh
Executable file
44
compile_with_distrobox.sh
Executable file
@ -0,0 +1,44 @@
|
||||
#!/bin/bash
|
||||
set -e
|
||||
|
||||
# Configuration
|
||||
CONTAINER_NAME="noicesynth-builder"
|
||||
IMAGE="archlinux:latest"
|
||||
|
||||
# 1. Check for Distrobox
|
||||
if ! command -v distrobox &> /dev/null; then
|
||||
echo "Error: distrobox is not installed on your system."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. Create Container (if it doesn't exist)
|
||||
# We use Arch Linux for easy access to latest toolchains and SDL2
|
||||
if ! distrobox list | grep -q "$CONTAINER_NAME"; then
|
||||
echo "Creating container '$CONTAINER_NAME'..."
|
||||
distrobox create --image "$IMAGE" --name "$CONTAINER_NAME" --yes
|
||||
fi
|
||||
|
||||
# 3. Execute Build Inside Container
|
||||
PROJECT_DIR=$(pwd)
|
||||
echo "Entering container to build..."
|
||||
distrobox enter "$CONTAINER_NAME" --additional-flags "--workdir $PROJECT_DIR" -- sh -c '
|
||||
set -e # Ensure script exits on error inside the container too
|
||||
# A. Install Dependencies (only if missing)
|
||||
# We check for sdl2-config and wget to see if dev tools are present
|
||||
if ! command -v sdl2-config &> /dev/null || ! command -v wget &> /dev/null; then
|
||||
echo "Installing compiler and libraries..."
|
||||
sudo pacman -Syu --noconfirm base-devel sdl2 wget
|
||||
fi
|
||||
|
||||
# B. Download miniaudio.h (if missing)
|
||||
if [ ! -f miniaudio.h ]; then
|
||||
echo "Downloading miniaudio.h..."
|
||||
wget https://raw.githubusercontent.com/mackron/miniaudio/master/miniaudio.h
|
||||
fi
|
||||
|
||||
# C. Compile
|
||||
echo "Compiling Project..."
|
||||
make
|
||||
'
|
||||
|
||||
echo "Build Success! Run ./noicesynth_linux to start the synth."
|
||||
150
main.cpp
Normal file
150
main.cpp
Normal file
@ -0,0 +1,150 @@
|
||||
#define MINIAUDIO_IMPLEMENTATION
|
||||
#include "miniaudio.h"
|
||||
#include <SDL2/SDL.h>
|
||||
#include <vector>
|
||||
#include <atomic>
|
||||
#include "synth_engine.h" // Include our portable engine
|
||||
|
||||
#include <stdio.h>
|
||||
|
||||
// --- Configuration ---
|
||||
const uint32_t SAMPLE_RATE = 44100;
|
||||
const uint32_t CHANNELS = 1; // Mono
|
||||
const int WINDOW_WIDTH = 800;
|
||||
const int WINDOW_HEIGHT = 600;
|
||||
|
||||
// --- Visualization Buffer ---
|
||||
const size_t VIS_BUFFER_SIZE = 8192;
|
||||
std::vector<int16_t> vis_buffer(VIS_BUFFER_SIZE, 0);
|
||||
std::atomic<size_t> vis_write_index{0};
|
||||
|
||||
// --- Global Synth Engine Instance ---
|
||||
// The audio callback needs access to our synth, so we make it global.
|
||||
SynthEngine engine(SAMPLE_RATE);
|
||||
|
||||
/**
|
||||
* @brief The audio callback function that miniaudio will call.
|
||||
*
|
||||
* This function acts as the bridge between the audio driver and our synth engine.
|
||||
* It asks the engine to fill the audio buffer provided by the driver.
|
||||
*/
|
||||
void data_callback(ma_device* pDevice, void* pOutput, const void* pInput, ma_uint32 frameCount) {
|
||||
(void)pDevice; // Unused
|
||||
(void)pInput; // Unused
|
||||
|
||||
// Cast the output buffer to the format our engine expects (int16_t).
|
||||
int16_t* pOutputS16 = (int16_t*)pOutput;
|
||||
|
||||
// Tell our engine to process `frameCount` samples and fill the buffer.
|
||||
engine.process(pOutputS16, frameCount);
|
||||
|
||||
// Copy to visualization buffer
|
||||
size_t idx = vis_write_index.load(std::memory_order_relaxed);
|
||||
for (ma_uint32 i = 0; i < frameCount; ++i) {
|
||||
vis_buffer[idx] = pOutputS16[i];
|
||||
idx = (idx + 1) % VIS_BUFFER_SIZE;
|
||||
}
|
||||
vis_write_index.store(idx, std::memory_order_relaxed);
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
(void)argc; (void)argv;
|
||||
|
||||
// --- Init SDL ---
|
||||
if (SDL_Init(SDL_INIT_VIDEO) < 0) {
|
||||
printf("SDL could not initialize! SDL_Error: %s\n", SDL_GetError());
|
||||
return -1;
|
||||
}
|
||||
|
||||
SDL_Window* window = SDL_CreateWindow("NoiceSynth Scope", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, WINDOW_WIDTH, WINDOW_HEIGHT, SDL_WINDOW_SHOWN);
|
||||
if (!window) return -1;
|
||||
|
||||
SDL_Renderer* renderer = SDL_CreateRenderer(window, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
|
||||
if (!renderer) return -1;
|
||||
|
||||
ma_device_config config = ma_device_config_init(ma_device_type_playback);
|
||||
config.playback.format = ma_format_s16; // Must match our engine's output format
|
||||
config.playback.channels = CHANNELS;
|
||||
config.sampleRate = SAMPLE_RATE;
|
||||
config.dataCallback = data_callback;
|
||||
|
||||
ma_device device;
|
||||
if (ma_device_init(NULL, &config, &device) != MA_SUCCESS) {
|
||||
printf("Failed to initialize playback device.\n");
|
||||
SDL_DestroyRenderer(renderer);
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
return -1;
|
||||
}
|
||||
|
||||
printf("Device Name: %s\n", device.playback.name);
|
||||
|
||||
ma_device_start(&device);
|
||||
|
||||
// --- Main Loop ---
|
||||
bool quit = false;
|
||||
SDL_Event e;
|
||||
|
||||
while (!quit) {
|
||||
while (SDL_PollEvent(&e) != 0) {
|
||||
if (e.type == SDL_QUIT) {
|
||||
quit = true;
|
||||
}
|
||||
}
|
||||
|
||||
// Clear screen
|
||||
SDL_SetRenderDrawColor(renderer, 0, 0, 0, 255);
|
||||
SDL_RenderClear(renderer);
|
||||
|
||||
// Draw Waveform
|
||||
SDL_SetRenderDrawColor(renderer, 0, 255, 0, 255); // Green
|
||||
|
||||
// Determine read position (snapshot atomic write index)
|
||||
size_t write_idx = vis_write_index.load(std::memory_order_relaxed);
|
||||
|
||||
// Find trigger (zero crossing) to stabilize the display
|
||||
// Look back from write_idx to find a stable point
|
||||
size_t search_start_offset = 2000;
|
||||
size_t read_idx = (write_idx + VIS_BUFFER_SIZE - search_start_offset) % VIS_BUFFER_SIZE;
|
||||
|
||||
// Simple trigger search: find crossing from negative to positive
|
||||
for (size_t i = 0; i < 1000; ++i) {
|
||||
int16_t s1 = vis_buffer[read_idx];
|
||||
size_t next_idx = (read_idx + 1) % VIS_BUFFER_SIZE;
|
||||
int16_t s2 = vis_buffer[next_idx];
|
||||
|
||||
if (s1 <= 0 && s2 > 0) {
|
||||
read_idx = next_idx; // Found trigger
|
||||
break;
|
||||
}
|
||||
read_idx = next_idx;
|
||||
}
|
||||
|
||||
// Draw points
|
||||
int prev_x = 0;
|
||||
int prev_y = WINDOW_HEIGHT / 2;
|
||||
|
||||
for (int x = 0; x < WINDOW_WIDTH; ++x) {
|
||||
int16_t sample = vis_buffer[read_idx];
|
||||
read_idx = (read_idx + 1) % VIS_BUFFER_SIZE;
|
||||
|
||||
// Map 16-bit sample (-32768 to 32767) to screen height
|
||||
// Invert Y because screen Y grows downwards
|
||||
int y = WINDOW_HEIGHT / 2 - (sample * (WINDOW_HEIGHT / 2) / 32768);
|
||||
|
||||
if (x > 0) {
|
||||
SDL_RenderDrawLine(renderer, prev_x, prev_y, x, y);
|
||||
}
|
||||
prev_x = x;
|
||||
prev_y = y;
|
||||
}
|
||||
|
||||
SDL_RenderPresent(renderer);
|
||||
}
|
||||
|
||||
ma_device_uninit(&device);
|
||||
SDL_DestroyRenderer(renderer);
|
||||
SDL_DestroyWindow(window);
|
||||
SDL_Quit();
|
||||
return 0;
|
||||
}
|
||||
35
synth_engine.cpp
Normal file
35
synth_engine.cpp
Normal file
@ -0,0 +1,35 @@
|
||||
#include "synth_engine.h"
|
||||
|
||||
SynthEngine::SynthEngine(uint32_t sampleRate)
|
||||
: _sampleRate(sampleRate),
|
||||
_phase(0),
|
||||
_increment(0)
|
||||
{
|
||||
// Initialize with a default frequency
|
||||
setFrequency(440.0f);
|
||||
}
|
||||
|
||||
void SynthEngine::setFrequency(float freq) {
|
||||
// Calculate the phase increment for a given frequency.
|
||||
// The phase accumulator is a 32-bit unsigned integer (0 to 2^32 - 1).
|
||||
// One full cycle of the accumulator represents one cycle of the waveform.
|
||||
// increment = (frequency * 2^32) / sampleRate
|
||||
// We use a 64-bit intermediate calculation to prevent overflow.
|
||||
_increment = static_cast<uint32_t>((static_cast<uint64_t>(freq) << 32) / _sampleRate);
|
||||
}
|
||||
|
||||
void SynthEngine::process(int16_t* buffer, uint32_t numFrames) {
|
||||
for (uint32_t i = 0; i < numFrames; ++i) {
|
||||
// 1. Advance the phase. Integer overflow automatically wraps it,
|
||||
// which is exactly what we want for a continuous oscillator.
|
||||
_phase += _increment;
|
||||
|
||||
// 2. Generate the sample. For a sawtooth wave, the sample value is
|
||||
// directly proportional to the phase. We take the top 16 bits
|
||||
// of the 32-bit phase accumulator to get a signed 16-bit sample.
|
||||
int16_t sample = static_cast<int16_t>(_phase >> 16);
|
||||
|
||||
// 3. Write the sample to the buffer.
|
||||
buffer[i] = sample;
|
||||
}
|
||||
}
|
||||
45
synth_engine.h
Normal file
45
synth_engine.h
Normal file
@ -0,0 +1,45 @@
|
||||
#ifndef SYNTH_ENGINE_H
|
||||
#define SYNTH_ENGINE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* @class SynthEngine
|
||||
* @brief A portable, platform-agnostic synthesizer engine.
|
||||
*
|
||||
* This class contains the core digital signal processing (DSP) logic.
|
||||
* It has no dependencies on any specific hardware, OS, or audio API.
|
||||
* It works by filling a provided buffer with 16-bit signed audio samples.
|
||||
*
|
||||
* The oscillator uses a 32-bit unsigned integer as a phase accumulator,
|
||||
* which is highly efficient and avoids floating-point math in the audio loop,
|
||||
* making it ideal for the RP2040.
|
||||
*/
|
||||
class SynthEngine {
|
||||
public:
|
||||
/**
|
||||
* @brief Constructs the synthesizer engine.
|
||||
* @param sampleRate The audio sample rate in Hz (e.g., 44100).
|
||||
*/
|
||||
SynthEngine(uint32_t sampleRate);
|
||||
|
||||
/**
|
||||
* @brief Fills a buffer with audio samples. This is the main audio callback.
|
||||
* @param buffer Pointer to the output buffer to be filled.
|
||||
* @param numFrames The number of audio frames (samples) to generate.
|
||||
*/
|
||||
void process(int16_t* buffer, uint32_t numFrames);
|
||||
|
||||
/**
|
||||
* @brief Sets the frequency of the oscillator.
|
||||
* @param freq The frequency in Hz.
|
||||
*/
|
||||
void setFrequency(float freq);
|
||||
|
||||
private:
|
||||
uint32_t _sampleRate;
|
||||
uint32_t _phase; // Phase accumulator for the oscillator.
|
||||
uint32_t _increment; // Phase increment per sample, determines frequency.
|
||||
};
|
||||
|
||||
#endif // SYNTH_ENGINE_H
|
||||
Loading…
Reference in New Issue
Block a user