havSF2 v0.1.0 Released
Today I'm releasing the first version of havSF2, a single-header C++23 library that loads SoundFont 2 (.sf2) files. In my previous news entry about Reckless Road, I mentioned havMusicGen, the procedural MIDI producer I used for the game's music. Its built-in synthesizer plays songs with a SoundFont, and now that I've let people know the app exists, I figured I could share the part that loads SoundFonts as a library of its own, since it could be useful to other people as well.
The format goes back to the Sound Blaster AWE32 and is still the most common way to share sampled instrument sets, such as the General MIDI sets that software synthesizers and source ports of DOS-era games use to play MIDI music. A SoundFont describes its instruments in several layers: presets are made of instruments, instruments are made of samples, and each layer can set and override values for ranges of keys and velocities. havSF2 resolves all of that into flat regions. For any preset, key, and velocity, it tells you which samples to play, where their loops are, and the final value of every setting, combined as the specification says. Turning those regions into sound is up to you, so the library works with any synthesizer or audio API.
havSF2 was written from the SoundFont 2.04 specification. The library trusts nothing in the file: every size and table index is checked before it is used. Damaged or truncated files are refused with a message you can show to a user. Anything the loader has to leave out of an otherwise usable file is listed in a note instead of failing the whole file over one bad entry.
Features- Single header without dependencies
- Loading from a file path or any seekable stream
- Presets and instruments resolved into regions with the final value of every generator
- Modulators resolved the same way on top of the specification's default modulators
- 24-bit sample data where the file provides it
- A lookup that finds the regions to play for a note in a given bank and program
- Clear error messages and notes on anything left out
- Conversions from the specification's units to seconds, gain, and pitch ratios
- An example that renders a note into a WAV file to show how regions become sound
- Tests and CMake presets for Visual Studio 2022, MinGW, and Linux
havSF2 is released under the MIT license. Its source code and documentation are available on GitHub.