Somnia

Documentation

From first dream to your board.

Installation, command line, formats, firmware and APIs of Somnia 0.6.0 (npm 0.6.1).

Installation

Pick your system. The package is called somnia on Scoop and somnia-cli on Homebrew; the command is always somnia-cli.

# macOS, Linux
brew install sxnnyside-project/tap/somnia-cli

# Windows
scoop bucket add sxnnyside-project https://github.com/sxnnyside-project/scoop-bucket
scoop install somnia

Binaries downloaded by hand on macOS and Linux need execute permission (chmod +x) before they run.

See every install route and the downloads

Build from source

You need CMake 3.21 or newer and a C++20 compiler.

git clone https://github.com/core-red-project/somnia.git
cd somnia
cmake --preset release
cmake --build --preset release
./build/release/cli/somnia-cli --version

The command line tool lands in build/release/cli and the static and shared libraries in build/release/core.

Your first dream

Play, watch and export. Without --seed every run picks a random one.

somnia-cli play --scale hirajoshi --seed 42 -n 32
somnia-cli stream --scale dorian --bpm 96 --rests
somnia-cli generate -n 16 --scale blues --seed 7 --json

Commands

CommandWhat it doesExample
stream Live stream with a piano roll in the terminal.somnia-cli stream --scale blues
play Synthesizes the melody and plays it through the speakers.somnia-cli play --seed 42 -n 32
generate Writes events to standard output. It ignores -o: redirect the output to save it.somnia-cli generate -n 16 --json
export Saves MIDI, WAV, JSON or CSV files.somnia-cli export -o dream.mid
scales Lists the scales with their first notes.somnia-cli scales --root D
bench Measures generation latency on your machine.somnia-cli bench

When the first word is an option (for example somnia-cli --scale blues), stream runs.

Options

OptionWhat it doesDefault
-s, --scale Musical scale.lydian
-r, --root Root note: C, C#, D, Eb, F#, Bb…C
-b, --bpm Tempo. Accepts 1 to 999; the engine clamps it to 20–300.120
-n, --steps Number of events, above zero.16
--seed Unsigned 32-bit integer seed.random
--mode melody, arpeggio (or arp) and chords (or chord).melody
--meter 4/4, 3/4 or 7/8.4/4
--timestep How far the noise advances per event; above zero.0.25
--rests Adds rests.off
-f, --format text, json, jsonl, csv or pcm.text
--json Short for --format json.off
-o, --output Target file of export. The default applies when no target is given.somnia_output.mid
--midi, --wav, --json-out, --csv One target per format, to export several at once.—
-q, --quiet Leaves out the banner and messages.off
--no-color Output without ANSI colors.off
--no-delay Do not wait in real time between events.off

Errors and exit codes

The CLI exits with 0 on success and with 1 for an invalid command, option or value, or when a file cannot be written. The reason is printed to the terminal.

Keys in stream

KeyWhat it does
Space Pause or resume.
S Next scale.
R New seed.
Q / Esc Quit.

Scales

Semitones above the root and the other names the CLI accepts.

ScaleSemitonesAlso
lydian 0 · 2 · 4 · 6 · 7 · 9 · 11—
minor-pentatonic 0 · 3 · 5 · 7 · 10pentatonic
major-pentatonic 0 · 2 · 4 · 7 · 9—
dorian 0 · 2 · 3 · 5 · 7 · 9 · 10—
natural-minor 0 · 2 · 3 · 5 · 7 · 8 · 10minor, aeolian
major 0 · 2 · 4 · 5 · 7 · 9 · 11ionian
mixolydian 0 · 2 · 4 · 5 · 7 · 9 · 10—
phrygian 0 · 1 · 3 · 5 · 7 · 8 · 10—
blues 0 · 3 · 5 · 6 · 7 · 10—
hirajoshi 0 · 2 · 3 · 7 · 8—

Modes, meters and rests

The mode decides how each step picks its note inside the scale.

ModeWhat it does
melody The noise picks the scale degree directly.
arpeggio Adds a pattern of 0, 2, 4 and 7 degrees to the note.
chords Every four steps it moves up a degree and the noise picks root, third or fifth, one note at a time.

Note lengths per meter

MeterLengths at 120 BPM (ms)
4/4 125 · 250 · 500 · 1000
3/4 250 · 500 · 750
7/8 250 · 500 · 750

With --rests, a step becomes a rest when its noise sample falls under 0.18. The rest keeps its length.

Seeds and determinism

The same parameters give the same notes on the command line, the web lab, C, C++, Python and the npm package 0.6.1.

Each step reads two octaves of value noise at the current position, turns it into an index from 0 to 100 and quantizes it to the scale from C4 up, across at most four octaves. There is no hidden state: parameters and position are enough.

The firmware computes in Q8.8 fixed point. It is deterministic on the board but does not match the desktop surfaces note for note.

Output formats

generate writes to standard output. These are real outputs:

$ somnia-cli generate --scale dorian --seed 424242 -n 3 --rests -f csv
index,label,midi,frequency_hz,duration_ms,is_rest
0,D7,98,2349,500,0
1,D6,86,1175,500,0
2,D7,98,2349,500,0
$ somnia-cli generate --scale dorian --seed 424242 -n 2 --rests -f jsonl
{"index":0,"label":"D7","midi":98,"frequency":2349,"duration_ms":500,"is_rest":false}
{"index":1,"label":"D6","midi":86,"frequency":1175,"duration_ms":500,"is_rest":false}
FieldWhat it does
index Event number from zero.
label Note name, or REST.
midi MIDI note number.
frequency / frequency_hz Frequency in hertz; the long name is the CSV one.
duration_ms Length in milliseconds.
is_rest Whether the event is a rest.

JSON and CSV leave velocity out: use MIDI or the APIs when you need it. pcm gives raw signed 16-bit mono audio at 44.1 kHz.

Export

The file extension decides the format; an unknown extension gets MIDI. MIDI is format 0 at 480 PPQN and declares 4/4; WAV is 16-bit mono PCM at 44.1 kHz.

somnia-cli export --scale lydian --seed 42 -n 64 -o dream.mid
somnia-cli export --scale lydian --seed 42 -n 64 -o dream.wav

To write several formats of the same dream:

somnia-cli export --seed 42 -n 64 \
  --midi dream.mid --wav dream.wav --json-out dream.json --csv dream.csv

You can also pipe raw audio straight into a player (aplay, on Linux):

somnia-cli generate --format pcm | aplay -r 44100 -f S16_LE

Arduino, ESP32 and Pico

For your own project, install the library with PlatformIO. With C++17, apply the flag to the whole project, as here.

[env:uno]
platform = atmelavr
board = uno
framework = arduino
build_flags = -std=gnu++17 -O3
lib_deps = sxnnyside/somnia

A buzzer on pin 8, based on example 01:

#include <Arduino.h>
#include <Somnia.h>

ScaleEngine scaleEngine;
PatternEngine patternEngine;
SequenceEngine sequenceEngine(scaleEngine, patternEngine);
BuzzerAudioOutput audio(8);  // buzzer on pin 8
StreamStateQ8 state{};

void setup() {}

void loop() {
  audio.update(millis());
  if (audio.isBusy()) return;

  // state, step (64 = 0.25), scale, seed, root, bpm, rests
  NoteEvent note = sequenceEngine.nextEventQ8(
      state, 64, ScaleType::MinorPentatonic, 1337, 0, 120, true);

  if (note.is_rest) delay(note.duration_ms);
  else audio.playTone(note.frequency, note.duration_ms, note.velocity);
}

Included examples

ExampleBoardWhat it does
01_piezo_buzzer Uno, Nano, ESP32Buzzer melody with a serial trace.
02_usb_midi_player RP2040, ESP32-S2/S3; serial MIDI on AVRMIDI notes and clock. It does not compile on the classic ESP32.
03_i2s_ambient ESP32, RP2040Polyphonic ambient audio through an I2S DAC with an ADSR envelope.

See the examples on GitHub

Full firmware

firmware/firmware.ino is a standalone instrument with a button and potentiometers. From the repository root, with arduino-cli (use the port of your board):

arduino-cli compile --fqbn arduino:avr:uno firmware
arduino-cli upload -p /dev/ttyUSB0 --fqbn arduino:avr:uno firmware

Pins of the full firmware

BoardBuzzerButtonPotentiometers: tempo, scale, seed
Arduino Uno / Nano 82A0 · A1 · A2
ESP32 25434 · 35 · 32
Pico (RP2040) 15226 · 27 · 28

Controls

ControlWhat it does
Short press Mutates the seed.
Hold 1.5 s Saves seed, tempo and scale to EEPROM.
Tempo potentiometer From 60 to 180 BPM.
Scale potentiometer Walks through the scales.
Seed potentiometer Read at startup when no preset is saved.
ENABLE_MIDI_SERIAL At 1 it sends MIDI on TX at 31250 baud; at 0 (default) it prints the notes at 115200.

Example 03 uses an I2S DAC (MAX98357A or PCM5102A). On ESP32: BCLK 26, LRC 25, DOUT 22.

Pico: on the official PlatformIO raspberrypi platform the build fails because that core has no EEPROM.h.

C++ API

Use the core straight from C++20, without dynamic memory. Build the project first and link the library.

#include <cstdio>

#include "pattern_engine.hpp"
#include "scale_engine.hpp"
#include "sequence_engine.hpp"

int main() {
    ScaleEngine scales;
    PatternEngine patterns;
    SequenceEngine sequence(scales, patterns);
    StreamState state{};

    for (int i = 0; i < 8; ++i) {
        // state, timestep, scale, seed, root, bpm, rests
        NoteEvent note = sequence.nextEvent(state, 0.25f, ScaleType::Dorian, 424242, 0, 96, true);
        std::printf("%s %u Hz %u ms\n", note.label.data(), note.frequency, note.duration_ms);
    }
}
c++ -std=c++20 -Icore/include demo.cpp build/release/core/libsomnia_core.a -o demo
SymbolWhat it does
SequenceEngine::nextEvent Computes the next event with a floating-point phase.
SequenceEngine::nextEventQ8 The same in Q8.8 fixed point for microcontrollers; 256 is a step of 1.0.
StreamState / StreamStateQ8 Position of the stream; the caller keeps it.
ScaleEngine::parseScale Turns a name into a ScaleType; an unknown name gives Lydian.
AudioOutput Interface to plug in your own audio output.

C API

A stable ABI to link from other languages. In the example, scale 3 is dorian, mode 0 is melody and meter 0 is 4/4.

#include <stdio.h>
#include "somnia_c.h"

int main(void) {
    somnia_engine_t engine = somnia_create();
    /* engine, seed, scale, root, bpm, rests, mode, meter */
    somnia_c_note_event_t note =
        somnia_next_event(engine, 424242, 3, 0, 96, true, 0, 0);
    printf("%s %u Hz %u ms\n", note.label, note.frequency, note.duration_ms);
    somnia_destroy(engine);
    return 0;
}
# macOS and Linux, from the repository root
cc demo.c -Icore/include -Lbuild/release/core -lsomnia_core \
  -Wl,-rpath,"$PWD/build/release/core" -o demo
SymbolWhat it does
somnia_create(void) Creates an engine; returns NULL on failure.
somnia_destroy(engine) Frees the engine; accepts NULL.
somnia_next_event(engine, seed, scale_type, root_offset, bpm, allow_rests, play_mode, time_sig) Next event: frequency, length, name, MIDI note, velocity and rest.
somnia_export_midi(filepath, seed, scale_type, root_offset, bpm, steps) Writes a MIDI file. It takes no rests or mode.
somnia_export_wav(filepath, seed, scale_type, root_offset, bpm, steps) Writes a WAV file. It takes no rests or mode.
somnia_version(void) Library version.

Scale indexes

0 lydian · 1 minor-pentatonic · 2 major-pentatonic · 3 dorian · 4 natural-minor · 5 major · 6 mixolydian · 7 phrygian · 8 blues · 9 hirajoshi

Modes: 0 melody, 1 arpeggio, 2 chords. Meters: 0 is 4/4, 1 is 3/4, 2 is 7/8.

Python

The somnia-audio package uses ctypes over the native library, which is not included: build it first. On Linux the file ends in .so.

git clone https://github.com/core-red-project/somnia.git
cd somnia
cmake --preset release
cmake --build --preset release
export SOMNIA_LIB_PATH="$PWD/build/release/core/libsomnia_core.dylib"
pip install somnia-audio

Then use it. export_midi and export_wav always include rests.

from somnia import Somnia

engine = Somnia()
for _ in range(8):
    note = engine.next_event(seed=424242, scale="dorian", bpm=96, has_rests=True)
    print(note.label, note.frequency, note.duration_ms)

engine.export_midi("dream.mid", seed=424242, scale="dorian", bpm=96, steps=64)
SymbolWhat it does
Somnia(lib_path=None) Loads the library; raises RuntimeError when it cannot find it.
next_event(seed=12345, scale="lydian", root=0, bpm=120, has_rests=False, mode="melody") Next event, always in 4/4.
export_midi(filepath, seed, scale, root, bpm, steps=32) Writes a MIDI file and returns True on success.
export_wav(filepath, seed, scale, root, bpm, steps=32) Writes a WAV file and returns True on success.
version Version of the loaded library.
NoteEvent frequency, duration_ms, label, midi_note, velocity, is_rest

TypeScript and Web Audio

The npm package generates notes with no native dependency and can play them with Web Audio. Start audio from a user click.

npm install @sxnnyside/somnia
import { playNote, ScaleType, SomniaEngine } from '@sxnnyside/somnia';

const engine = new SomniaEngine(424242);

document.querySelector('button')?.addEventListener('click', () => {
  const context = new AudioContext();
  const next = () => {
    const note = engine.nextEvent(ScaleType.Dorian, 0, 96, true);
    playNote(context, note);
    setTimeout(next, note.durationMs);
  };
  next();
});
SymbolWhat it does
new SomniaEngine(seed = 424242) Creates a generator.
nextEvent(scale, rootNote, bpm = 120, hasRests = true, mode, timeSig, timeStep = 0.25) Next event. Throws RangeError when bpm is 0 or less. Rests are on by default.
reset(newSeed?) Rewinds, with another seed when given.
getState() Copy of the current position.
playNote(context, event, destination?) Plays the note and returns an object with stop(), or null for a rest.
ScaleType, PlayMode, TimeSignature Scale, mode and meter enumerations.
NoteEvent frequency, durationMs, label, midiNote, velocity, isRest

Troubleshooting

Unknown musical scale
Run somnia-cli scales and use one of those names or their aliases.
Python: libsomnia_core cannot be located
Build the library and set SOMNIA_LIB_PATH to the full path of the file.
The browser stays silent
Audio can only start after a click or key press by the user.
My board sounds different from my computer
That is expected: the firmware uses Q8.8 fixed point.
Arduino: undefined reference to operator delete
The C++17 flag reached only part of the build. Apply it to the whole project or keep the default settings.

Architecture

Seed → value noise and FBM → scale quantization with a 12-TET table → note event → audio or file. The core depends on no surface and allocates no memory while generating.