STM32 Polyphonic MIDI MiniMoog

From Stm32World Wiki
Jump to navigation Jump to search

This is an ongoing project to build a polyphonic, multitimbral MIDI synthesizer on an STM32F407 that replicates the audio chain of the original Minimoog Model D. 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 Audio DAC Streamline Blade.

The original Minimoog is monophonic and has one set of panel settings. This one plays up to 8 voices on the F407, 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 the plan is to end up with a web page that simulates the Moog panel and talks to the synth directly through Web MIDI.

Signal chain

Each voice follows the Model D signal chain:

OSC 1 ─┐
OSC 2 ─┼──> MIXER ──> DRIVE ──> 24 dB LADDER FILTER ──> VCA ──> PAN ──> out
OSC 3 ─┤                         ^ cutoff                  ^
NOISE ─┘                         |                         |
                     FILTER CONTOUR (ADS)       LOUDNESS CONTOUR (ADS)
                     + keyboard control
                     + modulation (OSC 3 / noise, mod wheel)
  • 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.

Hardware

  • STM32F407VET6 at 168 MHz.
  • USB OTG FS as a USB MIDI device ("STM32World MiniMoog").
  • 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).

Firmware structure

The synth code is kept out of the CubeMX generated main.c in a synth folder in the project root, which is added to the build as a source folder and include path:

File Contents
synth/synth.c, synth/synth.h The engine: patches (one per channel), voices, oscillators, ladder filter, contours and rendering
synth/params.c, synth/params.h The parameter table mapping MIDI CCs to patch fields, with ranges and curves
synth/midi.c, synth/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().

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 of synth.c keeps the rest of the project debuggable. -O2 was a bit slower and -Os much slower.
  • No libm in the audio path. exp2f() and tanf() from newlib are slow. A polynomial 2^x (0.003 cent error) and a Padé approximation of tan() 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.

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:

STM32 MiniMoog Web Panel.png

  • 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 examples/sl_mcu_stm32f407_polyphonic_minimoog/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 "STM32World MiniMoog" 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.py plays 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.sh resets the board over SWD (back to the default patches), plays each demo while recording the PC's line input with parecord, checks for clipping, trims, normalises and encodes samples/<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 "STM32World MiniMoog" midi/bass.mid

Elsewhere import them into a DAW and set the track's MIDI output to "STM32World MiniMoog".

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.
  • Later: storing patches, 24-bit output, and porting to the STM32H723 for more voices and an oversampled nonlinear ladder.

Miscellaneous links