Skip to main content

Crate bela_sys

Crate bela_sys 

Source
Expand description

Raw FFI bindings to the Bela core API (libbela) for Bela Gem.

This crate exposes the C surface of the Bela core API (Bela.h): BelaContext, BelaInitSettings, the Bela_* lifecycle and auxiliary-task functions, and rt_printf. Bindings are generated from vendored headers (see vendor/bela/SOURCE for where they came from) with cargo xtask bindgen; see the crate README for how to regenerate them.

It also exposes the sysfs GPIO and LED family that Bela.h includes from GPIOcontrol.h: the twelve gpio_* functions and led_set_trigger. That is file I/O under /sys/class/gpio and /sys/class/leds, one pin at a time, so it belongs where a Bela program puts file I/O — in setup, in cleanup, in an AuxiliaryTask or on a thread of its own — and never in render. It is a different mechanism from the digital channels of a BelaContext rather than a second spelling of them, and the only path this crate offers to a pin that is not one of those sixteen, or to any pin at all while no block is being rendered.

Four things about the signatures, which a caller has to honour to call these correctly at all:

  • The return value is not uniform, in three ways. gpio_setup and gpio_fd_open return a file descriptor, or a negative value if they could not open one. Ten of the others return 0 for success and a negative value for failure. gpio_dismiss returns 0 whatever happened and so can never report one. The idiom that suits the middle group, if ret != 0, therefore rejects every successful gpio_setup — a descriptor is rarely 0 — while reading either of those two as a status leaks the descriptor, and a gpio_setup that failed passes its -1 on to the next call, where it is a write(2) on a bad descriptor rather than anything to do with a pin.
  • writeFlag is not a flag. gpio_fd_open’s second argument is the second argument of open(2); gpio_setup passes O_RDWR, which is 2. This crate is no_std and depends on no libc, so that constant is the caller’s to bring.
  • The constants are the wrong integer type. PIN_DIRECTION and PIN_VALUE come out c_uint where every parameter that takes one is c_int, so gpio_set_dir(pin, OUTPUT_PIN as c_int) is the spelling that compiles.
  • The string arguments have to be NUL-terminated. gpio_set_edge and led_set_trigger write strlen(s) + 1 bytes, so both want a CStr: led_set_trigger(1, c"heartbeat".as_ptr()), and — because the header declares that one char * where it means const char * — gpio_set_edge(pin, c"rising".as_ptr().cast_mut()). Neither writes through the pointer.

And one that is a soundness condition rather than a signature: gpio_get_value and gpio_read leave their *mut c_uint untouched on every failure path, so handing either an uninitialised location and reading it back afterwards is unsound.

What the functions do is libbela’s, not this crate’s, and several of them do it surprisingly: an export is not owned by whoever made it, so gpio_unexport and gpio_dismiss will take a pin from another program; a second gpio_read on one descriptor succeeds and reports the pin high whatever it is doing, only the third failing; and led_set_trigger numbers the board’s LEDs from 1. docs/scope.md in the repository lists them beside the other bound calls that behave unexpectedly, and docs/board-facts.md has the measurements.

Two things here are neither the core API nor generated, and they are two different kinds of thing:

  • The bela_midi_* functions are a C surface this crate compiles (shim/midi.cpp) over Bela’s Midi class in libbelaextra. MIDI is what a Bela program reaches for first after audio, and the class is C++ with only half a C surface of its own.
  • The ne10_fft_* functions are plain C on the board, in libNE10.so.10, declared here by hand. They are the real-to-complex FFT, reached directly rather than through Bela’s Fft class, which wraps these same calls and little else; docs/fft.md in the repository records why. Nothing is compiled for them — the library is already on the board — but abi/ne10_abi.c asserts at build time that its headers still describe what is declared here.

Bela’s own higher-level C++ libraries (Scope, Trill, Fft, Gui) remain out of scope.

The setup / render / cleanup callbacks are not bound: they are either provided to Bela_initAudio via BelaInitSettings or defined as #[unsafe(no_mangle)] symbols by the linking crate.

Target platform is Bela Gem on PocketBeagle 2 (aarch64-unknown-linux-gnu). For a safe API, use the bela crate instead.

Structs§

BelaChannelGain
BelaChannelGainArray
BelaContext
\ingroup render \brief Structure holding audio and sensor settings and pointers to I/O data buffers.
BelaCpuData
BelaInitSettings
\ingroup control \brief Structure containing initialisation parameters for the real-time audio control system.
BelaMidi
An opened Midi object, as an opaque pointee.
_BelaHwConfig
ne10_fft_cpx_float32_t
One complex value, as NE10 lays it out: real part, then imaginary.
ne10_fft_r2c_state_float32_t
A real-to-complex plan, as an opaque pointee.
option
timespec

Constants§

BELA_AUDIO_PRIORITY
BELA_BUGFIX_VERSION
BELA_FLAG_ANALOG_OUTPUTS_PERSIST
BELA_FLAG_DETECT_UNDERRUNS
BELA_FLAG_INTERLEAVED
BELA_FLAG_OFFLINE
BELA_MAJOR_VERSION
BELA_MIDI_ALREADY_OPEN
That direction of this object is already open.
BELA_MIDI_MESSAGE_MAX
Bytes of the longest message bela_midi_get_message writes: a status byte and two data bytes.
BELA_MIDI_NO_SUCH_PORT
No port has the name that was given.
BELA_MINOR_VERSION
BelaHwDetectMode_Cache
< read cached value from /run/bela/belaconfig first. If it does not exist, fall back to #BelaHwDetectMode_Scan
BelaHwDetectMode_CacheOnly
<read cached value from /run/bela/belaconfig. If it does not exist, return #BelaHw_NoHw
BelaHwDetectMode_Scan
< perform an automatic detection by scanning the peripherals and busses available, and cache value in /run/bela/belaconfig
BelaHwDetectMode_User
<read user-specified value from ~/.bela/belaconfig. If it does not exist, fall back to #BelaHwDetectMode_Cache
BelaHwDetectMode_UserOnly
<read user-specified value from ~/.bela/belaconfig. If it does not exist, return #BelaHw_NoHw
BelaHw_Batch
< Dummy offline
BelaHw_Bela
< Bela
BelaHw_BelaEs9080
< A Bela cape with Es9080 EVB on top, all as audio
BelaHw_BelaMini
< Bela Mini
BelaHw_BelaMiniMultiAudio
< Bela Mini with extra codecs
BelaHw_BelaMiniMultiI2s
< Bela Mini with extra rx and tx I2S data lines.
BelaHw_BelaMiniMultiTdm
< Bela Mini with extra codecs and/or tdm devices
BelaHw_BelaMultiTdm
< Bela with extra codecs and/or tdm devices
BelaHw_BelaRevC
< A Bela cape rev C: Es9080 is used for analog outs
BelaHw_CtagBeast
< Ctag Beast
BelaHw_CtagBeastBela
< Ctag Beast and Bela cape
BelaHw_CtagFace
< Ctag Face
BelaHw_CtagFaceBela
< Ctag Face and Bela cape
BelaHw_GemMulti
< Gem Multi
BelaHw_GemStereo
< Gem Stereo
BelaHw_NoHw
< No hardware
BelaHw_Salt
< Salt
DEFAULT_HP_LEVEL
DEFAULT_LINE_OUT_LEVEL
DEFAULT_PGA_GAIN
HIGH
INPUT
INPUT_PIN
LOW
OUTPUT
OUTPUT_PIN

Functions§

Bela_HwConfig_delete⚠
Use this to delete a pointer returned by Bela_HwConfig_new()
Bela_HwConfig_new⚠
Returns the configuration for a given BelaHw or nullptr if hw is invalid.
Bela_InitSettings_alloc⚠
\brief Allocate the data structure containing settings for Bela.
Bela_InitSettings_free⚠
\brief De-allocate the data structure containing settings for Bela.
Bela_cleanupAudio⚠
\brief Clean up resources from audio and sensor processing.
Bela_clock_gettime⚠
Bela_cpuMonitoringGet⚠
Get stats about internal CPU monitoring.
Bela_cpuMonitoringInit⚠
Set internal CPU monitoring for the audio thread. @param count Number of samples (tic/toc pairs) in a acquisition cycle. Use 0 to disable. @return 0 on success, an error code otherwise.
Bela_cpuTic⚠
Start measuring CPU time. When data->currentCount reaches data->count, a acquisition cycle is completed. data->percentage gives the average CPU busy time during the latest completed acquisition cycle.
Bela_cpuToc⚠
Stop measuring CPU time.
Bela_createAuxiliaryTask⚠
\brief Create a new auxiliary task.
Bela_defaultSettings⚠
\brief Initialise the data structure containing settings for Bela.
Bela_deleteAllAuxiliaryTasks⚠
Bela_detectHw⚠
\brief Detect what hardware we are running on.
Bela_getVersion⚠
\brief Get the version of Bela you are running.
Bela_getopt_long⚠
\brief Get long options from command line argument list, including Bela standard options
Bela_gettime⚠
Bela_initAudio⚠
\brief Initialise audio and sensor rendering environment.
Bela_initRtBackend⚠
\defgroup warppers Wrappers for real-time functionalities.
Bela_muteSpeakers⚠
\brief Mute or unmute the onboard speaker amplifiers.
Bela_nanosleep⚠
Bela_printFlushBuffers⚠
Bela_printf⚠
Bela_requestStop⚠
\brief Tell the Bela program to stop.
Bela_runInSameThread⚠
\brief Begin processing audio and sensor data in the same thread as the caller.
Bela_scheduleAuxiliaryTask⚠
\brief Run an auxiliary task which has previously been created.
Bela_setADCLevel⚠
DEPRECATED.
Bela_setAdcLevel⚠
\brief Set the level of the audio ADC.
Bela_setAudioInputGain⚠
\brief Set the gain of the audio input preamplifier.
Bela_setDACLevel⚠
DEPRECATED.
Bela_setDacLevel⚠
\brief Set the level of the audio DAC.
Bela_setHeadphoneLevel⚠
DEPRECATED Equivalent to Bela_setHpLevel(-1, decibels);
Bela_setHpLevel⚠
\brief Set the level of the onboard headphone amplifier.
Bela_setLineOutLevel⚠
\brief Set the level of the audio line out.
Bela_setPgaGain⚠
DEPRECATED.
Bela_setUserData⚠
\brief Set the userData variable, which is passed to setup(), render() and cleanup().
Bela_setVerboseLevel⚠
\brief Set level of verbose (debugging) printing.
Bela_startAudio⚠
\brief Begin processing audio and sensor data.
Bela_stopAudio⚠
\brief Stop processing audio and sensor data.
Bela_stopRequested⚠
\brief Check whether the program should stop.
Bela_usage⚠
\brief Print usage information for Bela standard options.
Bela_userSettings⚠
\brief Initialise the data structure containing settings for Bela.
bela_midi_available_messages⚠
How many parsed messages are waiting. Reads two ring indices: no allocation, no system call — and no synchronisation either, the input thread writing them as plain unsigned ints. What that can cost is a count one message stale.
bela_midi_delete⚠
Destroys a Midi object, joining its input thread. Null is accepted. Blocks for as long as that thread takes to notice, which is up to its 50 ms poll timeout.
bela_midi_get_message⚠
Writes the oldest waiting message into buf, which must have room for BELA_MIDI_MESSAGE_MAX bytes, and returns how many bytes it wrote — 0 when nothing was waiting, leaving buf untouched. The status byte carries the channel in its low nibble, as on the wire.
bela_midi_list_ports⚠
Writes every MIDI port ALSA reports into buf as NUL-terminated names, one after another, and returns the bytes the whole list needs. A len shorter than that holds as many whole names as fit. buf may be null when len is 0, which is how to ask for the size before allocating.
bela_midi_new⚠
Creates a Midi object with its input parser enabled, opening no port. Returns null if it could not be created.
bela_midi_read_from⚠
Opens port for input and starts reading from it, once per object. Returns 0 when input is enabled afterwards, BELA_MIDI_NO_SUCH_PORT, BELA_MIDI_ALREADY_OPEN, or a negative value from Bela — -errno when ALSA refused the device.
bela_midi_write_output⚠
Hands length bytes to Bela’s output task. Returns 1, or 0 if output was never enabled — and 1 says the bytes were handed over, not that they were queued or sent. The -1 in the C++ is unreachable while commsSend reports success unconditionally, which is what makes 1 and 0 the whole range.
bela_midi_write_to⚠
Opens port for output, once per object, with the same return values as bela_midi_read_from and the same end after a failure.
gpio_dismiss⚠
gpio_export⚠
gpio_fd_close⚠
gpio_fd_open⚠
gpio_get_value⚠
gpio_read⚠
gpio_set_dir⚠
gpio_set_edge⚠
gpio_set_value⚠
gpio_setup⚠
gpio_functions
gpio_unexport⚠
gpio_write⚠
led_set_trigger⚠
ne10_fft_alloc_r2c_float32⚠
Allocates a plan for transforms of nfft real points, or returns null. One malloc: the twiddles and the scratch are offsets inside the block it returns.
ne10_fft_c2r_1d_float32_neon⚠
Transforms the nfft / 2 + 1 bins at fin back into the plan’s nfft real samples at fout.
ne10_fft_destroy_r2c_float32⚠
Frees a plan. Null is accepted.
ne10_fft_r2c_1d_float32_neon⚠
Transforms the plan’s nfft real samples at fin into the nfft / 2 + 1 bins at fout. Unscaled.
rt_printf⚠

Type Aliases§

AuxiliaryTask
\ingroup auxtask
BelaDigitalDirection
\defgroup iofunctions I/O functions and constants
BelaHw
A type of Bela hardware.
BelaHwConfig
BelaHwDetectMode
Arguments to be passed to Bela_detectHw()
PIN_DIRECTION
PIN_VALUE
__clockid_t
__syscall_slong_t
__time_t
clockid_t