Sound Byte Libs 0.5.1-340-gab5b79a
C++ firmware library for audio applications on 32-bit ARM Cortex-M processors
Loading...
Searching...
No Matches
Hardware Source System

Sound Byte Libs uses a declarative hardware configuration system that separates MCU drivers from board definitions, enabling portable firmware across different hardware targets.

Overview

  1. The app's target file names one or more hardware sources and a device in one of them.
  2. sloth (Sound Byte Labs Open Tool for Hardware) loads the device's manifest chain - the main module and its MCU, the attached modules and the components they declare - and resolves every claim to an MCU port, pin or peripheral.
  3. sloth generates sbl/hw/config/*.hpp and shim.json into the build directory and, with -DSBL_LOCK=ON, records the resolution in locks/<target>.lock.
  4. The app uses the generated handles (sbl::hw::gpio::status_led, sbl::hw::adc::knob_1) and, when the hardware has components, the generated Board.

CMake runs sloth on every configure.

Quick Start

  1. Create a target file, targets/<name>.sbl.json, with sbl-hardware checked out beside the app:
{
"schemaVersion": "0.1",
"hardware": {
"sources": [
{ "name": "sbl", "path": "../../sbl-hardware" }
],
"target": "sbl:devices/patch-init"
},
"config": {
"sample_rate": 48000,
"block_size": 48
}
}
  1. Use the SBL hooks in your CMakeLists.txt:
cmake_minimum_required(VERSION 3.21)
include($ENV{SBL_PATH}/tools/cmake/SblHooks.cmake)
sbl_pre_project()
project(my_app C CXX ASM)
sbl_post_project()
add_executable(my_app src/main.cpp)
target_link_libraries(my_app PRIVATE sbl::driver)
sbl_finalize(my_app)
  1. Use generated handles in your code:
#include <sbl/hw/hw.hpp> // Drivers and generated config
auto led = sbl::hw::gpio::status_led;
// led.port, led.pin, led.active_low are resolved at build time
Umbrella header for the core MCU drivers and the generated configuration.

Hardware Hierarchy

Level Manifest Description Example
MCU mcu/<arch>/<name>/mcu.json Silicon: pins and their functions, capabilities, SDK, driver stm32h750, linux-arm-host
Main module modules/<name>/hardware.json The board with the MCU (FPU required): boot config, board-level claims, exposed pins daisy-patch-sm, daisy-seed
Attached module modules/<name>/hardware.json Claims pins the main module exposes, declares components patch-init, daisy-pod
Device devices/<name>/device.json A deployable target: one main module plus attached modules patch-init, virtual-patch-init
Component components/<name>.json or components/<name>/component.json Reusable part a module references: front-panel controls, ICs with drivers pot, button, pcm3060

Configuration Files

Target file (<tt>targets/<name>.sbl.json</tt>)

One per hardware target; sbl.json in the project root is the single-target form. It declares hardware sources, the device, and the target's system config:

{
"schemaVersion": "0.1",
"hardware": {
"sources": [
{ "name": "sbl", "github": "three-lakes/sbl-hardware", "ref": "main" },
{ "name": "local", "path": "./hardware" }
],
"target": "local:devices/my-panel"
},
"config": { "sample_rate": 48000, "block_size": 48 }
}

Sources can be:

  • Local: { "name": "local", "path": "./hardware" } - relative to the target file
  • GitHub: { "name": "sbl", "github": "owner/repo", "ref": "main" } - cloned into the build's cache; "ssh": true clones over SSH

Target uses source:path format: sbl:devices/patch-init.

A target file may also carry app_config overrides and a board section; see the sloth README for those and for app.sbl.json, the app's own declarations shared by every target.

MCU (<tt>mcu.json</tt>)

Defines the silicon, abridged from mcu/arm/stm32h750/mcu.json:

{
"schemaVersion": "0.1",
"mcu": "stm32h750",
"family": "stm32h7",
"vendor": "st",
"arch": "arm-cortex-m7",
"capabilities": {
"fpu": "fpv5-d16",
"usb": "tinyusb",
"filesystem": "sdmmc-fatfs"
},
"driver": "./driver",
"registers": "./reg",
"sdk": {
"type": "none",
"toolchain": { "system": "Generic", "processor": "arm", "compiler": "arm-none-eabi-gcc" },
"outputs": ["bin", "hex"]
},
"pins": {
"PA0": { "functions": { "gpio": { "port": 0, "pin": 0 }, "adc": { "peripheral": "ADC1", "channel": 16 } } }
}
}

Main module (<tt>hardware.json</tt>)

The board with the MCU: "main": true and a system section naming the MCU. It claims what the board itself uses and exposes the rest under logical names. Abridged from modules/daisy-patch-sm:

{
"schemaVersion": "0.1",
"module": {
"name": "daisy-patch-sm",
"revision": "1.0",
"main": true,
"system": { "mcu": "mcu/arm/stm32h750", "config": { "hse_mhz": 16 } }
},
"exposes": {
"gpio": { "b7": { "mcu_pin": "PB8", "functions": ["gpio"] } },
"adc": { "cv_in_1": { "mcu_pin": "PA3", "mcu_channel": "ADC1_IN15" } }
},
"claims": {
"pins": [{ "mcu_pin": "PC7", "function": "gpio", "direction": "out", "id": "status_led" }],
"i2c": [{ "id": "codec", "mcu_peripheral": "I2C2", "scl_pin": "PB10", "sda_pin": "PB11", "speed": 400000 }]
},
"uses": [
{ "ref": "sbl:components/pcm3060", "bindings": { "i2c": { "mcu_peripheral": "I2C2", "scl_pin": "PB10", "sda_pin": "PB11" } } }
]
}

uses binds an IC component (here the codec) to the board's buses; sloth adds the component's driver directory to the build.

Attached module (<tt>hardware.json</tt>)

Claims pins by the main module's logical names, never MCU pins, and declares the components on them. It names no parent, so one attached module can sit on a real and a virtual main module. Abridged from modules/patch-init:

{
"schemaVersion": "0.1",
"module": { "name": "patch-init", "revision": "1.0", "category": "boards" },
"claims": {
"pins": [{ "pin": "b7", "function": "gpio", "direction": "in", "pull": "up", "active_low": true, "id": "button1" }],
"adc": [{ "pin": "cv_in_1", "id": "knob_1" }]
},
"components": {
"button1": { "ref": "sbl:components/button", "pins": { "pin": "button1" } },
"knob1": { "ref": "sbl:components/pot", "pins": { "adc": "knob_1" } }
}
}

Device (<tt>device.json</tt>)

Names the main module and the attached modules that make up one target. A device is app-agnostic, and it may carry a board section binding board roles to its own types (see the sloth README).

{
"schemaVersion": "0.1",
"device": {
"name": "patch-init",
"main": "sbl:modules/daisy-patch-sm",
"modules": [{ "ref": "sbl:modules/patch-init" }]
}
}

Component

A front-panel component gives a type and its pin slots (components/button.json):

{ "component": { "name": "button", "type": "button", "pins": { "pin": null } } }

An IC component is a directory with component.json and a driver/; its claims are bound by the module that uses it.

Pin Resolution

The resolver checks each claim against the layer below it:

Pin Resolution Chain

Attached module -> main module -> MCU -> generated code, with validation at each step.

Resolution steps:

  1. The attached module claims logical pin b7 with function gpio
  2. The main module exposes b7 as MCU pin PB8 -> the requested function must be in its functions
  3. The MCU defines PB8 -> the pin must not already be claimed
  4. The generator emits a handle with the resolved port and pin

Pin conflicts are detected at resolution time. If the same MCU pin is claimed twice (even through different exposed names), the resolver fails with a conflict error.

Generated Code

sloth writes into <build>/generated/sbl/hw/config/:

File Contents
gpio.hpp GPIO handles (sbl::hw::gpio::)
adc.hpp ADC handles, if any ADC claims
uart.hpp UART handles, if any UART claims
i2c.hpp I2C handles, if any I2C claims
electrical.hpp Port electrics (jack-to-ADC circuit) and idle codes
mcu.hpp MCU metadata (sbl::hw::mcu::)
target.hpp Target config (sbl::hw::target::)
board.hpp The Board, if the hardware declares components
app.hpp App config (sbl::app::), if the app declares any
shim.json The SHIM: the app's ports, their electrics and the audio shape, for a host

meta.hpp (build metadata) goes one level up, in sbl/hw/.

Example gpio.hpp:

// sbl/hw/config/gpio.hpp - Generated by sloth
namespace sbl::hw::gpio {
inline constexpr sbl::GpioHandle button1{1, 8, true};
inline constexpr sbl::GpioHandle status_led{2, 7, false};
}
GPIO pin handle with port, pin number, and polarity.
Definition handle.hpp:28

Example mcu.hpp:

// sbl/hw/config/mcu.hpp - Generated by sloth
namespace sbl::hw::mcu {
inline constexpr const char* name = "stm32h750";
inline constexpr const char* family = "stm32h7";
inline constexpr const char* vendor = "st";
inline constexpr const char* arch = "arm-cortex-m7";
}

The <sbl/hw/hw.hpp> umbrella header includes the MCU drivers and every generated config header that exists.

Lock File

With -DSBL_LOCK=ON, CMake writes the resolved hardware to locks/<target>.lock beside the app (locks/patch-init.lock for targets/patch-init.sbl.json) and rewrites it only when the resolution changes. It is off by default, so a build leaves no lock. With -DSBL_LOCKED=ON, CMake verifies the lock instead and fails if it is missing or stale. Abridged:

{
"schemaVersion": "0.2",
"config_file": "patch-init.sbl.json",
"sources": { "sbl": { "path": "../../../../sbl-hardware" } },
"resolution": {
"target": "sbl:devices/patch-init",
"chain": ["sbl:modules/patch-init", "sbl:modules/daisy-patch-sm"],
"mcu": { "name": "stm32h750", "source": "sbl:mcu/arm/stm32h750" }
},
"resolved_claims": {
"gpio": { "status_led": { "port": 2, "pin": 7, "direction": "out", "pull": "none", "active_low": false } }
},
"config": { "hse_mhz": 16, "sysclk_mhz": 480, "sample_rate": 48000, "block_size": 48 },
"board_roles": {
"button": { "type": "sbl::control::input::Button", "include": "sbl/control/input/button.hpp", "source": "library" }
}
}

Paths in the lock are relative to it, so the lock does not change between checkouts.

Multiple Targets

Create one target file per hardware target under targets/:

targets/patch-init.sbl.json # Production hardware
targets/workbench.sbl.json # Virtual target on the RPi 5 workbench
app.sbl.json # The app's own declarations, shared by every target

Build with:

cmake -B build -DSBL_CONFIG=targets/workbench.sbl.json
cmake --build build

SBL_CONFIG is relative to the app's source directory. A CMakePresets.json with one preset per target sets it.

sbl-hardware Layout

Directory Contents
mcu/arm/<name>/ ARM Cortex-M MCUs (FPU required): mcu.json, driver/, reg/ (cecrops-generated registers), startup and linker script
mcu/linux-arm-host/ The Linux host MCU for the workbench and host builds
modules/<name>/ Main and attached modules (hardware.json)
devices/<name>/ Devices (device.json)
components/ Component definitions; IC components are directories with a driver

Schema Reference

The Pydantic models in sbl-schema/sbl_schema/models/ are the source of truth. sbl-schema generate writes the JSON schemas to sbl-schema/sbl_schema/schemas/:

Schema Purpose
sbl.schema.json Target files (and a single-target sbl.json)
mcu.schema.json MCU manifests
module.schema.json Attached module manifests
mainboard.schema.json The mainboard format; sloth validates main modules in it after reshaping them
shim.schema.json The SHIM

Device manifests are validated by their model when sloth loads them, and sloth checks app.sbl.json as it reads it. Devices, app.sbl.json and component files have no generated schema file. For detailed documentation, see the Hardware Schema Documentation.

CLI Tools (sloth)

CMake runs sloth with SBL_PYTHON if set, else the Python in a .venv beside sound-byte-libs or in tools/, else the system Python.

The sloth README (tools/sloth/README.md) lists the commands and their options from --help.

Template Packs

sloth uses template packs to decouple code generation from the core tool. This allows non-SBL projects to use sloth with their own output formats.

A template pack is a directory containing:

  • manifest.json - Defines outputs and template paths
  • Templates - Jinja2 templates at any path within the pack

Discovery order:

  1. -t/--templates CLI flag (highest priority)
  2. SLOTH_TEMPLATES environment variable
  3. The built-in SBL pack (tools/sloth/sloth/templates_sbl/)

Example manifest.json:

{
"name": "sbl",
"version": "1.0.0",
"description": "Sound Byte Labs C++ hardware configuration templates",
"outputs": {
"gpio": {
"template": "templates/config/gpio.hpp.j2",
"output": "gpio.hpp",
"required": true
},
"adc": {
"template": "templates/config/adc.hpp.j2",
"output": "adc.hpp",
"condition": "adc_claims"
}
}
}

Using custom templates:

# Via CLI flag
python -m sloth generate sbl.json --templates /path/to/my-templates
# Via environment variable
export SLOTH_TEMPLATES=/path/to/my-templates
python -m sloth generate sbl.json

Python API

from pathlib import Path
from sloth import HardwareResolver, HardwareGenerator, ResolverOptions
options = ResolverOptions(board_roles=Path("sound-byte-libs/src/sbl/control/board_roles.json"))
# Resolve hardware to frozen IR (preferred for code generation)
resolver = HardwareResolver(Path("targets/patch-init.sbl.json"), options)
result = resolver.resolve_to_ir()
print(f"MCU: {result.mcu.name}")
print(f"GPIO claims: {len(result.gpio_claims)}")
# Generate config headers to directory
generator = HardwareGenerator()
generator.generate(result, Path("build/generated/sbl/hw/config"))
# Write lock file (returns True when it changed)
resolver.write_lock(Path("locks/patch-init.lock"))

Two resolution methods:

  • resolve_to_ir() - Returns frozen ResolutionResult with flat access (preferred for generation)
  • resolve() - Returns mutable Resolution with manifest access (for debugging/introspection)

Design Decisions

Key principles:

  • Declarative over imperative: Hardware is described, not programmed
  • Composition over inheritance: Devices compose modules, main modules use MCUs
  • Build-time resolution: All pin mappings resolved before compilation
  • Reproducible builds: Lock file captures exact resolution state

CMake Integration

SBL provides optional CMake hooks that simplify SDK integration. See the examples for usage patterns.

Hook Lifecycle

CMake Hook Lifecycle

Three-phase lifecycle with SDK plugin branching. A user hook runs first in its phase and replaces the SDK step unless SBL_EXTEND_SDK_HOOKS is set.

Usage in CMakeLists.txt:

include($ENV{SBL_PATH}/tools/cmake/SblHooks.cmake)
sbl_pre_project() # 1. Resolve hardware, load SDK plugin
project(my_app C CXX ASM)
sbl_post_project() # 2. Initialize SDK, create sbl::driver target
add_executable(my_app src/main.cpp)
sbl_add_irq_sources(my_app dma) # IRQ source units, where the driver has them
target_link_libraries(my_app PRIVATE sbl::driver)
sbl_finalize(my_app) # 3. Copy the SHIM, generate output files (.bin, .hex)

SDK Plugin System

The hooks use a plugin system to support different SDKs. Plugins live in tools/cmake/sdk/:

Plugin When Used What It Does
none.cmake STM32, bare-metal, the Linux host Configures the toolchain from the MCU manifest's sdk.toolchain, generates the sdk.outputs formats (BIN/HEX; none for a native build)

The plugin is selected by the MCU manifest's sdk.type, which CMake reads as SBL_EXT_SDK.

User Hooks

Define any of these before sbl_pre_project() to customize a phase. By default a user hook replaces the SDK hook for that phase:

function(sbl_hook_pre_project)
message(STATUS "Custom pre-project hook")
endfunction()
function(sbl_hook_post_project)
message(STATUS "Custom post-project hook")
endfunction()
function(sbl_hook_finalize_target target)
message(STATUS "Custom finalize for ${target}")
endfunction()

Set SBL_EXTEND_SDK_HOOKS to run the user hook and then the SDK hook. SBL_SKIP_SDK_HOOKS, SBL_SKIP_PRE_PROJECT, SBL_SKIP_POST_PROJECT and SBL_SKIP_FINALIZE skip SDK hooks entirely.

Profiling

SBL_PROFILING (default OFF) is read when an app is configured. With it on, sbl_finalize() defines SBL_PROFILING_ENABLED for the app's target, which compiles in the code the library gates behind it: AudioBudget, SectionProfile, Counter, the registry they register in and the #PROF reporter in sbl/system/profiling/, the NaN counter in sbl/dsp/types/convert.hpp, the correction count in sbl/dsp/oscillators/blep_corrector.hpp and the profiling line of the boot banner. With it off, that code compiles to nothing.

cmake -B build -DSBL_CONFIG=targets/patch-init.sbl.json -DSBL_PROFILING=ON
cmake --build build

The option is the same for every target. The app starts the cycle counter with sbl::system::profiling::init() at startup; audio_budget.hpp has the usage. What an app registers is in one table at the symbol sbl_profiling_registry; registry.hpp documents its layout and how a tool reads it over SWD while the core runs.

Key Variables Set by Hooks

After sbl_pre_project(), these CMake variables are available:

Variable Example Description
SBL_MCU_NAME stm32h750 MCU identifier
SBL_MCU_DRIVER_PATH /path/to/driver Path to driver sources
SBL_MCU_USB tinyusb USB stack the driver provides (tinyusb, stub or empty)
SBL_MCU_FILESYSTEM sdmmc-fatfs Filesystem the driver provides (sdmmc-fatfs, posix or empty)
SBL_EXT_SDK none External SDK name; none is the only plugin today
SBL_DRIVER_LIB sbl_stm32h750_driver Driver library target name
SBL_GENERATED_DIR build/generated Generated headers directory
SBL_COMPONENT_DRIVER_PATHS IC component driver directories
SBL_BOARD_ROLE_INCLUDE_DIRS Include roots of the board role bindings the target uses

sbl_post_project() adds the MCU's driver directory and aliases its library as sbl::driver, which carries the include paths for the library, the generated headers and the board role bindings.