Skip to content

Latest commit

 

History

49 Commits

Folders and files

Repository files navigation

fluidsynth-scripts

CI License: MIT FluidSynth NumPy FFmpeg Python 3 Ruff ShellCheck Conventional Commits

Music written as code. Python scripts turn a text notation into MIDI, FluidSynth plays it with General MIDI instruments, NumPy masters the sound, and a shell script encodes it with FFmpeg into WAV, FLAC, MP3, Opus, MP4 video and 17 other formats. Eight arrangements of classical music: Beethoven's Für Elise and the seven movements of Holst's The Planets.

Waveform of Für Elise; click to watch and listen

▶ beethoven-fur-elise.mp4 (2:56), exported with ./project.sh simplified/beethoven-fur-elise mp4 and the FluidR3_GM soundfont.

Gallery

The loudest 45 seconds of each movement of The Planets, as videos with a scrolling spectrogram above the waveform of each channel. Click a picture to watch and listen. They were rendered with the FluidR3_GM soundfont and the settings of the mp4 format, at a lower video bitrate; ./project.sh <project> mp4 makes the whole movement.

Mars, the Bringer of War
Mars, the Bringer of War, from 1:12 of 6:21
Venus, the Bringer of Peace
Venus, the Bringer of Peace, from 2:37 of 8:14
Mercury, the Winged Messenger
Mercury, the Winged Messenger, from 1:14 of 4:01
Jupiter, the Bringer of Jollity
Jupiter, the Bringer of Jollity, from 2:06 of 8:28
Saturn, the Bringer of Old Age
Saturn, the Bringer of Old Age, from 4:45 of 10:23
Uranus, the Magician
Uranus, the Magician, from 4:32 of 7:20
Neptune, the Mystic
Neptune, the Mystic, from 0:59 of 7:16
Für Elise, complete, above

Features

  • 8 projects. Für Elise and Holst's The Planets in simplified arrangements, for piano and for orchestra.
  • A text notation for music. Notes, chords, ties, staccato, accents, dynamics with hairpins, meters and pedal changes, written bar by bar as text and played through FluidSynth.
  • Expressive orchestration. Each part has its own instrument, channel and pan. Sustained instruments follow the dynamics through MIDI expression, struck and plucked ones through velocity.
  • Mastered to one loudness. Every project plays at -16 LUFS and stays below -1 dBTP, so it sounds right on small speakers.
  • 22 outputs. PCM, lossless and lossy formats encoded by FFmpeg from 48 kHz stereo floats, an MP4 video of the spectrogram and waveform, and the raw NumPy array for further processing.
  • Reproducible. Each project starts with its random seed, so it renders the same notes every time.

Quick start

git clone https://github.com/aljazmc/fluidsynth-scripts.git
cd fluidsynth-scripts
./project.sh simplified/beethoven-fur-elise mp3

The audio is written to build/beethoven-fur-elise.mp3.

Requirements

Requirement Notes
Python 3 with NumPy
FluidSynth fluidsynth on the PATH
A General MIDI soundfont by default /usr/share/sounds/sf2/FluidR3_GM.sf2 (on Debian and Ubuntu, the fluid-soundfont-gm package); set SOUNDFONT to use another one
FFmpeg ffmpeg on the PATH, built with the encoders of the formats you want (libmp3lame, libvorbis, libopus, libx264, …)

Usage

./project.sh new <project>               # make a project from a template
./project.sh <project> <format>          # build one format
./project.sh <project> all               # build every format
./project.sh all <format>                # build every project
./project.sh <group> all <format>        # build every project of a group
./project.sh <project> <format> clean    # remove one output
./project.sh <project> clean             # remove all outputs of a project
./project.sh clean                       # remove build/ and npy/

For example:

./project.sh simplified/beethoven-fur-elise mp3
./project.sh simplified all flac
SOUNDFONT=/usr/share/sounds/sf2/TimGM6mb.sf2 ./project.sh simplified/beethoven-fur-elise wav

A project is named by its path inside scripts/, and a group is a folder of projects, such as simplified. Outputs stay flat: simplified/<name> goes to build/<name>.<format>, and other groups keep their name as a prefix, e.g. transcribed/<name> would go to build/transcribed-<name>.<format>. Existing outputs are skipped, so clean them to rebuild. Run ./project.sh from the repository root. Without arguments, it prints the usage with every format, group and project.

Formats

All audio is rendered as 48 kHz stereo floats and encoded by FFmpeg:

Kind Formats
PCM wav and au (16-bit), aiff, caf and w64 (24-bit)
Lossless compressed flac (24-bit), mka (FLAC in Matroska), alac, tta, wv
Lossy aac and m4a (AAC), ac3, dts, eac3, mp2, mp3, ogg (Vorbis), opus, wma
Video mp4 (H.264 spectrogram and waveform, AAC audio)
Raw npy
  • mp4 is a 640x360 video at 15 fps: a scrolling spectrogram above the waveform of each channel, with the audio as 96 kbit/s AAC. The video bitrate is capped by the length, so a file of up to three minutes stays under about 5 MB; longer ones grow by about 1.5 MB a minute, up to 15 MB for Saturn.
  • alac is written as build/<name>-alac.m4a, so it doesn't clash with m4a.
  • npy saves the raw float32 array of shape (frames, 2) to npy/<name>.npy, to load it with numpy.load() and process it further.

How it works

project.sh ──> python3 scripts/export<format>.py <project>
                                    │
                                    ▼
                             scripts/common.py
                                    │ load_project()
                                    ▼
    scripts/<project>/<name>.py: <name>() -> float array (frames, 2)
       │ Score: MIDI events ──> fluidsynth -F raw ──> NumPy
       │ and NumPy for timing, velocities and fades
                                    │ master(): -16 LUFS, -1 dBTP
                                    │ ffmpeg_export()
                                    ▼
                  ffmpeg -f f32le -i pipe:0 -c:a <codec> ...
  • project.sh checks the arguments and runs scripts/export<format>.py (or scripts/savenpy.py) with the project as its argument.
  • scripts/common.py imports the project, calls its function, checks the shape of the audio and masters it with master(): it brings the audio to an integrated loudness of -16 LUFS (ITU-R BS.1770, gated as in EBU R128) and limits its true peak, 4 times oversampled, with a look-ahead limiter, so every project plays at the same loudness and stays below -1 dBTP. It also holds the shared tools: Score, which collects notes and controller changes in seconds, writes them as a MIDI file and renders it offline with FluidSynth through the soundfont, and fit() and normalize() for NumPy audio.
  • Each scripts/export<format>.py pipes the audio into FFmpeg with the codec and quality settings of one format.

Projects

A project is a folder holding <name>.py with a function <name>(), where <name> is the part of the folder name after its last hyphen. It returns a float array of shape (frames, 2) at 48 kHz. A project needs nothing outside its folder, apart from scripts/common.py.

./project.sh new example-tune00 starts a project: it makes scripts/example-tune00/ with a minimal tune00.py that builds right away (a few piano notes), to be changed into the real thing. A group can be named too, e.g. ./project.sh new simplified/example-tune00. The tests ask for every project to be listed here, so add it to a table and to the counts in this README.

Simplified

Simplified arrangements of classical music in the public domain, played by FluidSynth's General MIDI instruments:

scripts/simplified/beethoven-fur-elise/
├── elise.py   # elise(): tempi, dynamics and the order of the passages
├── piano.py   # a small text notation for piano music, played through Score
└── score.py   # the music, one notation string per bar
Project Played by
beethoven-fur-elise piano
holst-the-planets-01-mars-the-bringer-of-war orchestra
holst-the-planets-02-venus-the-bringer-of-peace orchestra
holst-the-planets-03-mercury-the-winged-messenger orchestra
holst-the-planets-04-jupiter-the-bringer-of-jollity orchestra
holst-the-planets-05-saturn-the-bringer-of-old-age orchestra
holst-the-planets-06-uranus-the-magician orchestra
holst-the-planets-07-neptune-the-mystic orchestra

The notation (see the docstring of piano.py) writes notes, chords, rests, ties, staccato, accents, dynamics with hairpins, meters and pedal changes as text, e.g. !mf c4 eb4:1/2 f#3+a3+d4:1.5 |. The scores were transcribed bar by bar from braille music. orchestra.py gives each part its own General MIDI instrument, channel and pan; sustained instruments follow the dynamics through MIDI expression (CC11), struck and plucked ones through note velocity.

Troubleshooting

soundfont not found: /usr/share/sounds/sf2/FluidR3_GM.sf2 (set SOUNDFONT). The default is where Debian and Ubuntu put it: install fluid-soundfont-gm there. Elsewhere, point SOUNDFONT at any General MIDI soundfont, as under Usage. Another soundfont sounds different, and outputs don't record which one made them.

not a SoundFont or MIDI file, then Created, and the output is silent. SOUNDFONT names a file that FluidSynth can't read. FluidSynth only warns, so project.sh still reports success. Fix the path, clean the output and build it again.

Skipping build/beethoven-fur-elise.mp3 (already exists), and nothing is built. Existing outputs are kept, with exit code 0, even after their scripts or the soundfont change. Clean the output first:

./project.sh simplified/beethoven-fur-elise mp3 clean
./project.sh simplified/beethoven-fur-elise mp3

numpy is required but was not found. The python3 on the PATH has no NumPy, as in a virtual environment without it. On Debian and Ubuntu install python3-numpy, or run pip install numpy inside the environment. Likewise, fluidsynth is required or ffmpeg is required means that the program is not on the PATH.

The usage is printed instead of building. Name a project with its group, simplified/beethoven-fur-elise rather than beethoven-fur-elise. If it also says find: 'scripts': No such file or directory, run it from the repository root.

AttributeError: module 'simplified' has no attribute 'simplified'. A group is not a project: build it with ./project.sh simplified all mp3.

Unknown encoder 'libopus', or another encoder. FFmpeg was built without it. ffmpeg -encoders lists what yours has; install a full build or choose another format.

It takes long. A project is rendered again for every format. Für Elise takes about 20 seconds and a movement of The Planets a minute or more per format, so ./project.sh all all takes hours; build one format first.

Tests

for test in tests/sh/test_*.sh; do bash "$test"; done   # project.sh
python3 -m unittest discover tests/py           # the Python scripts
RENDER=all python3 tests/py/test_audio.py       # render every project and check how it sounds
RENDER='simplified/holst-*' python3 tests/py/test_audio.py

The tests need bash, Python and NumPy, and the loudness and frequency tests need FFmpeg too. None of them writes outputs, and only the loudness and frequency tests on the projects render anything.

Two more checks render for real, so they are not among the tests above:

  • bash tests/sh/exports.sh [project...] exports every format of a project in a temporary copy and checks each file with ffprobe.
  • python3 tests/py/readme_commands.py runs the commands of this README in temporary clones of the last commit.

The tests of project.sh run it in a temporary sandbox, with a few fake projects and stand-ins for python3, fluidsynth and ffmpeg (see tests/sh/lib.sh), so they never touch build/ or npy/:

  • tests/sh/test_project.sh checks that project.sh rejects bad arguments with its usage and exit code 1.
  • tests/sh/test_new.sh checks that project.sh new makes a valid project and rejects names that can't be one.
  • tests/sh/test_formats.sh checks that the formats of project.sh, the exporters in scripts/ and the Formats table of this README agree, and that each exporter writes its own extension.
  • tests/sh/test_outputs.sh checks the names of the outputs, as described under Usage, through the clean commands.
  • tests/sh/test_run.sh checks that project.sh runs the right exporter for a project, a group and all, skips existing outputs, reports a failed export with exit code 1 and stops when a program is missing.

The Python tests:

  • tests/py/test_projects.py reads every project without running it: each has its <name>() function and its SEED, imports only the standard library, NumPy, common and its own modules, and takes its randomness from default_rng(seed) alone. It also checks that this README counts the projects right, lists each of them and links to every file of gallery/.

  • tests/py/test_notation.py checks the notation of piano.py (pitches, chords, durations, ties, dynamics, meters, tempo), and plays every arrangement with FluidSynth swapped for a recorder of the MIDI events: every bar must fill its meter, and every event must be valid MIDI with each note started and stopped. It needs neither FluidSynth nor a soundfont.

  • tests/py/test_midi.py reads back the files write_midi() writes, with a small parser of the Standard MIDI File format, and checks the events of Score.

  • tests/py/test_common.py checks varlen(), the MIDI variable-length numbers, against the examples in the Standard MIDI File specification, and the mastering: loudness() against the levels of test tones in ITU-R BS.1770, and that limit() and master() keep the true peak below the ceiling.

  • tests/py/test_audio.py checks that a project suits typical laptop speakers. It measures it with FFmpeg's EBU R128 meter (ITU-R BS.1770), first as it is and then through filters that drop what small drivers can't play, below 150 Hz and above 16 kHz (24 dB per octave):

    Check Limit
    Integrated loudness -20 to -12 LUFS
    True peak at most -1 dBTP
    Loudness range at most 15 LU
    Loudness lost without the bass below 150 Hz at most 6 LU
    Loudness lost without what lies above 16 kHz at most 0.5 LU

    The checks on the meter itself, with test tones, always run. The checks on the projects render them, so they only run with RENDER set to all or to a pattern of projects; JOBS sets how many render at once. Six of the Planets, all but Neptune, go beyond the loudness range for now.

Lint the code with ShellCheck and Ruff:

shellcheck project.sh tests/sh/*.sh .github/*.sh
ruff check .

GitHub Actions runs the linters, the tests, both checks and the rendering of Für Elise and Neptune on every push and pull request, see .github/workflows/ci.yml, and builds every project once a week, see .github/workflows/build.yml.

CI on localhost

act runs the same jobs on localhost, e.g. as the gh act extension of the GitHub CLI:

gh act                    # in the Alpine images
gh act -j test-python     # one job
.github/act.sh            # in the Alpine images and, if they fail, in the Debian ones

The jobs that need FluidSynth run in aljazmc/fluidsynth-alpine or aljazmc/fluidsynth-debian, the others in aljazmc/actions-alpine or aljazmc/actions-debian (see .actrc). act can't fall back to another image, so only .github/act.sh tries Debian. On GitHub every job runs on ubuntu-latest.

License

The scripts are licensed under the MIT License. The files in gallery/ were made with them and are under the same license. The music they arrange (Beethoven, Holst) is in the public domain.

The scripts drive software and use sounds that are not part of this repository and have licenses of their own:

  • FluidSynth is licensed under the GNU Lesser General Public License, version 2.1 or later. The scripts only run it as a separate program.
  • Soundfonts: the default FluidR3_GM soundfont by Frank Wen is licensed under the MIT license. Other soundfonts have their own licenses, e.g. TimGM6mb is under the GNU GPL, version 2; check the license of the soundfont you use before you publish what you render with it.
  • NumPy is licensed under the BSD 3-Clause license.

Releases

Packages

Contributors

Languages