Polyphonic MIDI Synthesizer
The cmsynth (CurrentMakers Synthesizer) is an ongoing project to build a polyphonic, multitimbral MIDI synthesizer for microcontrollers, inspired by the audio chain of the original Minimoog Model D. The first target was an STM32F407, the second is the RP2354 (RP2350). It builds on the earlier I2S Audio DAC MIDI Polyphonic Synthesizer and uses the same hardware: a USB MIDI device implemented with TinyUSB and audio out through the PCM5102 based Streamline IO Audio DAC blade.
The original Minimoog is monophonic and has one set of panel settings. This one plays up to 8 voices on the F407 and 32 on the RP2354, and each of the 16 MIDI channels has its own complete set of panel settings, so different channels can sound completely different at the same time. Every panel control is a MIDI CC, and a web page that simulates the Moog panel talks to the synth directly through Web MIDI.
The source is on GitHub in currentmakers/cmsynth. It started out as sl_mcu_stm32f407_polyphonic_minimoog in the stm32fun repository.
Video
Signal chain
Each voice follows the Model D signal chain. Everything in blue runs at the 48 kHz sample rate, the orange parts at the control rate of 3 kHz:
- Oscillators. Three oscillators with the Minimoog range switch (LO, 32', 16', 8', 4', 2') and waveforms triangle, triangle-saw, saw, square, wide and narrow pulse. Oscillator 3 has a reverse saw instead of the triangle-saw, and it can be disconnected from the keyboard to work as a low frequency oscillator. Oscillator 2 and 3 can be detuned by ±7 semitones (14-bit resolution). The saw and pulse waveforms are band limited with PolyBLEP to keep aliasing down.
- Mixer. A level and an on switch for each oscillator and for the noise source, which can be white or pink. A drive control emulates the classic trick of feeding the headphone output back into the external input to overdrive the filter.
- Filter. A 24 dB/octave transistor ladder filter, modelled as four zero delay feedback (TPT) one-pole stages with global feedback and a saturating input stage. Emphasis (resonance) makes it self-oscillate at the top of the range. The cutoff is set by the cutoff knob, the filter contour, keyboard control (off, 1/3, 2/3 or full) and the modulation.
- Contours. Attack, decay and sustain for both the filter and the loudness, with analog style exponential curves. As on the Minimoog the release uses the decay time when the decay switch is on, otherwise the release is fast.
- Controllers. Glide, and the modulation mix between oscillator 3 and noise, routed to the oscillator pitch and/or the filter cutoff and controlled by the mod wheel.
Pitch bend (±2 semitones), mod wheel and the sustain pedal are handled per channel as well.
Both contours have the same shape. The attack is an exponential curve aiming at 1.3 that stops at 1.0, like the charging capacitor in the analog original, and the decay gets 95% of the way to the sustain level in the decay time:
Hardware
The first target, examples/sl_mcu_stm32f407:
- STM32F407VET6 at 168 MHz.
- USB OTG FS as a USB MIDI device ("CurrentMakers cmsynth").
- I2S2 with DMA into the PCM5102 Audio DAC Streamline Blade, 16-bit stereo at 48 kHz.
- USART1 at 921600 baud for debug output (MIDI messages and CPU load).
The second, examples/sl_mcu_rp2354, is a Pico SDK project for VS Code on the sl_mcu_rp2354 Streamline board with the same audio blade:
- RP2354 (RP2350) overclocked to 320 MHz with the core voltage at 1.30 V, rendering on both Arm Cortex-M33 cores, the whole program running from SRAM.
- USB MIDI with the Pico SDK's TinyUSB.
- I2S from a PIO state machine fed by two chained DMA channels (BCK GPIO 3, LRCK GPIO 24, SD GPIO 21).
- UART0 at 921600 baud for the same debug output.
Firmware structure
The repository keeps the portable synth source in src and one firmware project per target in examples. Both projects, examples/sl_mcu_stm32f407 and examples/sl_mcu_rp2354, link src into the project folder as cmsynth, so the shared code can be opened and edited straight from STM32CubeIDE or VS Code. The STM32F407 project also links TinyUSB from the lib/tinyusb submodule; the RP2354 project uses the TinyUSB that comes with the Pico SDK. The synth code contains nothing MCU specific:
| File | Contents |
|---|---|
src/synth.c, src/synth.h |
The engine: patches (one per channel), voices, oscillators, ladder filter, contours and rendering |
src/params.c, src/params.h |
The parameter table mapping MIDI CCs to patch fields, with ranges and curves |
src/midi.c, src/midi.h |
The TinyUSB MIDI receive callback and message handling |
main.c only contains the glue: the I2S DMA half and full transfer callbacks set a pointer to the half buffer that needs refilling, and the main loop renders the next block of 64 frames (1.33 ms) with synth_process(). For more than one core the same work is available in steps: synth_block_begin() prepares the block (the shared noise), each core calls synth_render() for its share of the voices into its own mix, and synth_block_end() adds the mixes and converts them to 16-bit.
Multitimbral channels
Each MIDI channel has its own patch, a struct with every panel setting. The voices are shared: a note on channel 2 grabs a free voice and that voice reads channel 2's patch while it plays. A CC on channel 2 changes channel 2's patch only. When all voices are busy the oldest released voice is stolen first, otherwise the oldest playing voice.
MIDI CC map
Where General MIDI has a convention (volume, pan, portamento, resonance, cutoff, attack, decay) that number is used, the rest are undefined controllers. Parameters marked 14-bit also accept an LSB on CC + 32.
| Section | Parameter | CC | Range |
|---|---|---|---|
| Controllers | Glide time | 5 | 1 ms - 5 s |
| Glide on/off | 65 | switch | |
| Modulation mix | 82 | oscillator 3 - noise | |
| Oscillator modulation | 83 | switch | |
| Filter modulation | 84 | switch | |
| Oscillator bank | Osc 1 range | 14 | LO, 32', 16', 8', 4', 2' |
| Osc 1 waveform | 15 | 6 waveforms | |
| Osc 2 range | 16 | LO - 2' | |
| Osc 2 waveform | 17 | 6 waveforms | |
| Osc 2 detune | 18 (14-bit) | ±7 semitones | |
| Osc 3 range | 19 | LO - 2' | |
| Osc 3 waveform | 20 | 6 waveforms | |
| Osc 3 detune | 21 (14-bit) | ±7 semitones (±3 octaves without keyboard control) | |
| Osc 3 keyboard control | 22 | switch | |
| Mixer | Osc 1, 2, 3 level | 23, 24, 25 | 0 - 1 |
| Noise level | 26 | 0 - 1 | |
| Osc 1, 2, 3 on | 27, 28, 29 | switch | |
| Noise on | 30 | switch | |
| Noise white/pink | 31 | switch | |
| Drive | 81 | 0 - 1 | |
| Filter | Cutoff | 74 | 20 Hz - 20 kHz |
| Cutoff (14-bit) | 13 | 20 Hz - 20 kHz | |
| Emphasis | 71 | 0 - 1 | |
| Contour amount | 77 | 0 - 5 octaves | |
| Keyboard control | 78 | off, 1/3, 2/3, full | |
| Attack, decay, sustain | 85, 86, 87 | 1 ms - 10 s, 4 ms - 20 s, 0 - 1 | |
| Loudness contour | Attack, decay, sustain | 73, 75, 79 | 1 ms - 10 s, 4 ms - 20 s, 0 - 1 |
| Decay switch | 80 | switch | |
| Output | Volume | 7 | 0 - 1 |
| Pan | 10 | left - right | |
| Performance | Mod wheel | 1 (14-bit) | 0 - 1 |
| Sustain pedal | 64 | switch | |
| Pitch bend | ±2 semitones | ||
| All sound off, reset controllers, all notes off | 120, 121, 123 |
The ladder filter
The heart of the Moog sound is the transistor ladder. The model below is four one-pole low-pass stages in the zero delay feedback form described by Vadim Zavalishin. Because the feedback is instantaneous, the input to the first stage is solved for directly: every stage output is G·x + (1-G)·s, so the chain output is G⁴·x + S where S only depends on the stage states. The input is then saturated with a cheap cubic soft clipper, which keeps self-oscillation bounded. G is calculated at control rate from the cutoff and interpolated per sample.
for (int j = 0; j < SYNTH_CONTROL_RATE; j++) {
G += dG;
const float H = 1.0f - G;
const float S = G * (G * (G * H * s0 + H * s1) + H * s2) + H * s3;
float x = soft_clip((m[j] - k * S) * inv_den); // inv_den = 1 / (1 + k * G^4)
float vv, y;
vv = (x - s0) * G; y = vv + s0; s0 = y + vv; x = y;
vv = (x - s1) * G; y = vv + s1; s1 = y + vv; x = y;
vv = (x - s2) * G; y = vv + s2; s2 = y + vv; x = y;
vv = (x - s3) * G; y = vv + s3; s3 = y + vv; x = y;
// Loudness contour and VCA
loud += d_loud;
const float out = x * loud;
mix_l[base + j] += out * gain_l;
mix_r[base + j] += out * gain_r;
}
The feedback k goes from 0 to 4.15, and the filter self-oscillates at 4.
Performance
At 48 kHz the F407 has 3500 cycles per sample, and the CPU load is measured with the DWT cycle counter around every call to synth_process() and printed once per second:
Tick 6 (loop=235247) voices=8 cpu avg=53.4% max=53.6% (120156/224000 cycles) overruns=1
The first working version of the engine needed 175% of the CPU for 10 voices. Getting it to fit was mostly about what the Cortex-M4 FPU is slow at:
- Build the audio path optimised. The Debug configuration uses
-Og.#pragma GCC optimize ("O3", "fast-math")at the top ofsynth.ckeeps the rest of the project debuggable.-O2was a bit slower and-Osmuch slower. - No libm in the audio path.
exp2f()andtanf()from newlib are slow. A polynomial2^x(0.003 cent error) and a Padé approximation oftan()replace them. - Avoid divisions. A division is 14 cycles. PolyBLEP uses a reciprocal calculated at control rate, the ladder's
1 / (1 + k·G⁴)is calculated at control rate and the soft clipper is a cubic instead of a rational function. - Control rate. Pitch, glide, modulation, cutoff and both contours are calculated every 16 samples (3 kHz), the cutoff coefficient and loudness are interpolated per sample.
- Locals instead of struct members. The output pointers could alias the voice state, so the compiler reloaded everything from memory every sample. Copying the state to local variables (registers) for the inner loops was one of the biggest wins.
- Hoist the waveform switch. Each oscillator renders 16 samples in a loop specialised for its waveform instead of switching every sample.
- Skip what isn't used. Oscillators switched off in the mixer only advance their phase, and the noise generator only runs when a voice uses it.
- Voice state in CCM RAM. The 64K core coupled RAM has no wait states and isn't shared with the DMA.
Running the audio functions from SRAM (.RamFunc) was tried as well and was slower than running from flash with the ART accelerator.
Debug output turned out to matter as well. The original __io_putchar() used a blocking HAL_UART_Transmit(), and at 921600 baud a once per second status line blocks for over a millisecond, which together with rendering missed the 1.33 ms deadline and caused audible dropouts. printf() now writes into a 2 KB ring buffer that the USART1 TXE interrupt empties (characters are dropped if it ever fills up), so debug output never stalls the audio.
A benchmark runs at startup (SYNTH_BENCHMARK in main.c) and prints the cost of each stage:
bench osc triangle 22.8 cycles/sample bench osc tri-saw 35.8 cycles/sample bench osc saw 32.4 cycles/sample bench osc square 44.1 cycles/sample bench osc wide 50.2 cycles/sample bench osc narrow 47.7 cycles/sample bench voice_control 571 cycles/step (35/sample) bench voice_render 271 cycles/sample (whole voice) bench synth_process 120 cycles/sample (no voices)
| Patch | Voices | CPU load |
|---|---|---|
| Default (two saws, oscillator 3 off) | 8 | 53% |
| Default | 10 | 65% |
| Worst case (three narrow pulses, pink noise, filter and oscillator modulation) | 10 | 93% |
The F407 is therefore limited to 8 voices (about 75% in the worst case). MAX_VOICES can be defined higher for a faster MCU such as the STM32H723.
RP2354 compared
The RP2354 example was first built the same way, one core doing the rendering, USB MIDI and debug output, so the numbers compare directly. At 150 MHz it has 3125 cycles per sample:
| 8 voices | RP2354, 150 MHz | STM32F407, 168 MHz |
|---|---|---|
| Default patch | 48% (96k cycles per block) | 53% (120k cycles per block) |
| Three oscillators, noise, drive and high emphasis | 69% | |
| Idle | 2.1% |
The Cortex-M33 needs about 20% fewer cycles for the same work, so the RP2354 renders a block about 10% faster than the F407 despite the lower clock, and its second core is still free. The control rate code shows the biggest difference in the startup benchmark: 88 cycles per control step against 571, while a whole voice is 186 against 271 cycles per sample.
RP2354 on two cores at 320 MHz
The RP2354 runs reliably at 320 MHz with the core voltage raised from 1.10 V to 1.30 V, and the rendering is split over both cores. Core 0 renders the even voices and core 1 the odd ones, each into its own mix, and core 0 adds the two mixes together. Core 1 waits on the inter-core FIFO for a block and only runs while core 0 waits for its answer, and MIDI is handled by core 0 between blocks, so a voice is never changed while it is being rendered and no locking is needed:
static void core1_main(void) {
cycle_counter_init(); // Each core has its own DWT
while (true) {
multicore_fifo_pop_blocking();
uint32_t start = cycle_counter();
synth_render(&mixes[1], 1, SYNTH_CORES);
multicore_fifo_push_blocking(cycle_counter() - start);
}
}
static uint32_t render_block(int16_t *buf) {
synth_block_begin();
multicore_fifo_push_blocking(0); // Go, core 1
synth_render(&mixes[0], 0, SYNTH_CORES);
uint32_t core1_cycles = multicore_fifo_pop_blocking();
synth_block_end(buf, mixes, SYNTH_CORES);
...
}
The noise for the modulation source used to come from one shared generator; it is now one per voice so the two cores share no state while rendering. With MAX_VOICES at 32 and the worst case patch (three narrow pulses, pink noise, drive, high emphasis, oscillator and filter modulation) on every voice:
| Voices | CPU load (block time on core 0) | Core 1 |
|---|---|---|
| 0 | 1.4% | 0.1% |
| 8 | 19.3% | 16.9% |
| 16 | 36.5% | 33.8% |
| 24 | 53.4% | 50.7% |
| 32 | 70.5% | 67.6% |
That is four times the voices of the F407 with more headroom, and the two cores scale almost perfectly: a worst case voice costs about 2.15% of a block on each core at 320 MHz.
Measurements
The line out of the audio blade was recorded on a PC while sending MIDI to the synth:
- Pitch. A4 measures 440.0 Hz and A2 110.1 Hz.
- Self-oscillation and keyboard control. With the mixer off, emphasis at maximum and full keyboard control the filter produces a pure sine of 1304 Hz on note 57 (1303 Hz expected from the cutoff setting) and 2611 Hz on note 69, exactly one octave higher.
- Pan. A channel panned hard left gives 52 dB separation.
- Aliasing. A PolyBLEP saw at 4186 Hz (C6 on the 2' range) has the harmonics 34 dB above everything else, the strongest alias (the folded 7th harmonic at 18.7 kHz) at -36 dB.
Web panel
The web folder in the project is an HTML5 page with a Minimoog style panel and a keyboard. It talks to the synth directly through Web MIDI in the browser (Chrome, Edge, Opera or Firefox), so nothing but the USB MIDI connection is needed:
- Every knob and switch sends its CC to the selected channel as it moves, with 14-bit values for cutoff and detune. The knobs show the real values (Hz, ms, semitones) and the 0 to 10 scale of the original panel.
- The 16 channel buttons select which channel the panel and keyboard work on. The page keeps all 16 patches in the browser and sends a channel's patch when switching to it, so the synth and the panel stay in step even after a reset of the board.
- The keyboard plays with the mouse, touch or the computer keyboard, with octave buttons, sustain, pitch bend and mod wheel. As on the Model D the glide and decay switches sit to the left of the keyboard.
- A hardware MIDI keyboard can be selected as input and is forwarded to the selected channel.
- Patches can be saved and loaded as JSON files.
- CCs received from the synth update the panel, which is ready for when the firmware starts echoing parameter changes.
Web MIDI only works on a secure origin (https:// or http://localhost), so opening index.html straight from disk does not work. The web folder is served with a local web server instead, for example the one built into Python:
cd web python3 -m http.server 8000
On Windows the command is py -m http.server 8000. Then open http://localhost:8000 in Chrome, Edge or Opera (Firefox works too, but first asks to install a small site permission add-on for MIDI) and allow MIDI access. The page selects the "CurrentMakers cmsynth" MIDI port automatically and the dot next to it turns green.
If it stays on "No MIDI output", check that MIDI access is allowed for the page (the site settings icon in the address bar) and reload. On Windows only one program can use a MIDI port at a time, so a DAW that has the synth open blocks the page.
Demo recordings
The tools folder in the project has two small Linux scripts used to make demo recordings from the audio blade's line out:
tools/demos.pyplays demo sequences into the synth over raw MIDI. The patches are written in real units (seconds, Hz, levels) and converted to CCs, which also makes it a handy reference for the CC map.tools/record_demos.shresets the board over SWD (back to the default patches), plays each demo while recording the PC's line input withparecord, checks for clipping, trims, normalises and encodessamples/<demo>.mp3.
The demos recorded from the line out (MP3, they play directly in the browser):
- Bass - a 16th note riff on two saws and a square sub oscillator with some drive, the filter opens up in the last bar.
- Pad - a five note chord with high emphasis while the cutoff sweeps up and down, then a second chord.
- Lead - glide between legato notes, vibrato from oscillator 3 as LFO comes in on the mod wheel on the last note.
- Multitimbral - three channels with different patches at once: bass, a pad panned left and a resonant pluck arpeggio panned right.
With 7 to 8 voices playing the CPU load peaks at about 56%.
The same demos are in the midi folder as Standard MIDI Files (bass, pad, lead and multi), written from demos.py by tools/make_midis.py. Each file first sends the complete patch for every channel it uses, so it sounds the same whatever the synth was set to. On Linux they play with aplaymidi:
aplaymidi -l aplaymidi -p "CurrentMakers cmsynth" midi/bass.mid
Elsewhere import them into a DAW and set the track's MIDI output to "CurrentMakers cmsynth".
Songs from LMMS
tools/lmms2mid.py converts an LMMS project into a MIDI file for the synth. Every instrument track gets its own MIDI channel and a synth patch (bass, synth bass, acid, organ, pad, brass, reed, lead or pluck), with the track's volume and pan. Sound font tracks get the patch from their General MIDI program, LMMS's own synths (TripleOscillator, LB302, ZynAddSubFX and so on) from the track name, note range and note lengths, and samples from their file name. Beat/Bassline patterns are expanded wherever they are placed in the song. Tracks that need a specific sound can be given one per song in the script. Drums, both sound font kits and drum samples recognised by their file name, are split by drum over channels 10 to 14, because a channel has only one patch: kick and toms come from the self-oscillating filter swept down by the filter contour, snare, hats and cymbals from the noise source. Volume automation becomes CC 7.
tools/lmms2mid.py ~/lmms/projects/Popcorn2.mmpz aplaymidi -p "CurrentMakers cmsynth" midi/popcorn2.mid
Popcorn2 has nine tracks on 13 channels and plays on the 8 voices with voice stealing, peaking at 8 voices and about 60% CPU. Here is the recording from the line out (2:34) and the MIDI file.
Pachelbel's Canon in D, from a four voice LMMS arrangement, has three violins entering two bars apart over the cello's ground bass. Each violin has its own string lead voicing (two detuned saws, saw and wide pulse, tri-saw and saw) and its own place in the stereo picture (left, right and centre), so the canon is easy to follow. Here is the recording from the line out (11:42) and the MIDI file.
Six electronic tracks from the demo projects that come with LMMS are converted as well. They are published under free licences by their authors, and the converted versions keep those licences (credit the author when publishing a recording, and share recordings of Onion under CC BY-SA too). The original instruments, samples and effects are replaced by cmsynth patches, so the notes and rhythm are the originals but the sound is the synth's own. They use up to 16 channels and are written for the RP2354; on the F407's 8 voices many notes are stolen. Recorded from the line out of the RP2354 (32 voices, two cores at 320 MHz), with no overruns:
| Recording | MIDI file | Original | Author | Licence | Length | Peak voices | Peak CPU |
|---|---|---|---|---|---|---|---|
| farbro-tectonic.mp3 | farbro-tectonic.mid | Tectonic | Farbro | CC BY | 3:52 | 22 | 31% |
| skiessi-onion.mp3 | skiessi-onion.mid | Onion | Skiessi | CC BY-SA | 3:28 | 30 | 49% |
| momo64-esp.mp3 | momo64-esp.mid | esp | Momo64 | Artistic 2.0 | 5:07 | 31 | 48% |
| oglsdl-pptrip.mp3 | oglsdl-pptrip.mid | PpTrip | Oglsdl | Artistic 2.0 | 2:16 | 27 | 46% |
| socceroos-progress.mp3 | socceroos-progress.mid | Progress | Socceroos | Artistic 2.0 | 3:51 | 27 | 45% |
| esoxlb-cpu.mp3 | esoxlb-cpu.mid | CPU | E.SoX (lowbudget) | Artistic 2.0 | 3:46 | 16 | 26% |
Status and plans
- Done: the Minimoog voice architecture, 16 multitimbral channels, the MIDI CC map, CPU load measurement, demo recordings and the Web MIDI panel.
- Next: a second USB MIDI port for the panel (so a DAW and the web panel can both be connected on Windows, where MIDI ports are exclusive), and echoing parameter changes and a state dump from the synth so the panel follows changes made elsewhere.
- RP2354: done, 32 voices on both cores at 320 MHz.
- Later: storing patches, 24-bit output, and the STM32H723 for more voices and an oversampled nonlinear ladder.