bela-sys 0.8.0

Raw FFI bindings to the Bela core API (libbela) for Bela Gem
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! 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/COMMIT` for the pinned
//! upstream commit) with `cargo xtask bindgen`; see the crate README
//! for how to regenerate them.
//!
//! Two things here are neither the core API nor generated, and they
//! are two different kinds of thing:
//!
//! - The [`bela_midi_*`](bela_midi_new) 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_*`](ne10_fft_alloc_r2c_float32) 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.
//!
//! [Bela Gem]: https://bela.io
#![no_std]

#[allow(
    missing_docs,
    nonstandard_style,
    unsafe_op_in_unsafe_fn,
    unused,
    clippy::all,
    clippy::pedantic,
    clippy::nursery,
    clippy::restriction,
    rustdoc::all,
    reason = "generated by bindgen; regenerate with `cargo xtask bindgen`"
)]
mod bindings;
mod midi;
mod ne10;

pub use bindings::*;
pub use midi::{
    BELA_MIDI_ALREADY_OPEN, BELA_MIDI_MESSAGE_MAX, BELA_MIDI_NO_SUCH_PORT, BelaMidi,
    bela_midi_available_messages, bela_midi_delete, bela_midi_get_message, bela_midi_list_ports,
    bela_midi_new, bela_midi_read_from, bela_midi_write_output, bela_midi_write_to,
};
pub use ne10::{
    ne10_fft_alloc_r2c_float32, ne10_fft_c2r_1d_float32_neon, ne10_fft_cpx_float32_t,
    ne10_fft_destroy_r2c_float32, ne10_fft_r2c_1d_float32_neon, ne10_fft_r2c_state_float32_t,
};

// The build script's toolchain logic, tested where a build script
// cannot be: `cargo test` builds this crate, not `build.rs`. See
// ../shim_compiler.rs.
#[cfg(test)]
mod shim_compiler {
    extern crate std;

    use std::borrow::ToOwned;
    use std::format;
    use std::string::String;

    include!("../shim_compiler.rs");

    #[test]
    fn bela_cxx_is_taken_as_it_stands() {
        assert_eq!(
            shim_compiler_from(
                "clang++",
                "aarch64-unknown-linux-gnu-gcc",
                "aarch64-linux-gnu-gcc"
            ),
            Ok("clang++".to_owned()),
            "an explicit C++ compiler outranks anything derived, even a resolved linker"
        );
    }

    #[test]
    fn a_c_compiler_ending_in_gcc_answers_for_both() {
        // The two cases docs/cross-compile.md documents, driven
        // through the legacy BELA_CC path (no linker resolved).
        assert_eq!(
            shim_compiler_from("", "", "aarch64-linux-gnu-gcc"),
            Ok("aarch64-linux-gnu-g++".to_owned())
        );
        assert_eq!(shim_compiler_from("", "", "gcc"), Ok("g++".to_owned()));
    }

    #[test]
    fn neither_set_is_the_tap_default() {
        assert_eq!(
            shim_compiler_from("", "", ""),
            Ok(DEFAULT_CXX.to_owned()),
            "the same default scripts/aarch64-bela-linker.sh has"
        );
    }

    #[test]
    fn a_c_compiler_nothing_follows_from_is_refused() {
        // Deriving `ar`, or a C++ name, from this would mix
        // toolchains silently, which the build script fails on
        // instead.
        let error = shim_compiler_from("", "", "clang").unwrap_err();
        assert!(
            error.contains("BELA_CXX"),
            "the message should say what to set, got: {error}"
        );
    }

    #[test]
    fn a_resolved_gcc_linker_answers_for_the_shim_too() {
        // The direct-linker path (docs/cross-compile.md): Cargo
        // resolved a compiler driver directly, so no BELA_CC is
        // needed at all.
        assert_eq!(
            shim_compiler_from("", "aarch64-unknown-linux-gnu-gcc", ""),
            Ok("aarch64-unknown-linux-gnu-g++".to_owned())
        );
        assert_eq!(shim_compiler_from("", "gcc", ""), Ok("g++".to_owned()));
    }

    #[test]
    fn a_resolved_linker_outranks_a_stale_bela_cc() {
        // RUSTC_LINKER reflects the toolchain that will actually link
        // the binary; a leftover BELA_CC from before migrating off the
        // wrapper must not silently win and build the shim with a
        // different one.
        assert_eq!(
            shim_compiler_from("", "aarch64-unknown-linux-gnu-gcc", "gcc"),
            Ok("aarch64-unknown-linux-gnu-g++".to_owned())
        );
    }

    #[test]
    fn the_wrapper_as_the_resolved_linker_falls_through_to_bela_cc() {
        // .cargo/config.toml still names the wrapper: RUSTC_LINKER is
        // set, but to something that names no C++ compiler on its own,
        // so BELA_CC answers as it always has.
        assert_eq!(
            shim_compiler_from("", "scripts/aarch64-bela-linker.sh", "gcc"),
            Ok("g++".to_owned())
        );
        assert_eq!(
            shim_compiler_from(
                "",
                "/Users/dev/bela-rs/scripts/aarch64-bela-linker.sh",
                "aarch64-linux-gnu-gcc"
            ),
            Ok("aarch64-linux-gnu-g++".to_owned()),
            "an absolute path still matches by its last segment"
        );
        assert_eq!(
            shim_compiler_from("", "scripts/aarch64-bela-linker.sh", ""),
            Ok(DEFAULT_CXX.to_owned()),
            "and with BELA_CC unset too, the tap default"
        );
    }

    #[test]
    fn the_abi_check_takes_the_c_compiler_as_it_stands() {
        // BELA_CC already names a C compiler, and the assertions in
        // abi/ne10_abi.c are C: nothing to derive.
        assert_eq!(
            abi_compiler_from("aarch64-linux-gnu-gcc", "", "clang++"),
            Some("aarch64-linux-gnu-gcc".to_owned())
        );
    }

    #[test]
    fn the_abi_check_follows_the_resolved_linker() {
        // The direct-linker path: what Cargo resolved is a compiler
        // driver, which is what should read the headers.
        assert_eq!(
            abi_compiler_from("", "aarch64-unknown-linux-gnu-gcc", ""),
            Some("aarch64-unknown-linux-gnu-gcc".to_owned())
        );
        assert_eq!(
            abi_compiler_from("gcc", "scripts/aarch64-bela-linker.sh", ""),
            Some("gcc".to_owned()),
            "the wrapper names no compiler of its own, so BELA_CC answers"
        );
    }

    #[test]
    fn the_abi_check_derives_a_c_compiler_from_a_cxx_one() {
        // Only BELA_CXX is set, which is the shim's variable: the C
        // compiler beside it reads the same headers with the same
        // defines.
        assert_eq!(
            abi_compiler_from("", "", "aarch64-linux-gnu-g++"),
            Some("aarch64-linux-gnu-gcc".to_owned())
        );
        assert_eq!(
            abi_compiler_from("", "", "clang++"),
            Some("clang".to_owned())
        );
        assert_eq!(
            abi_compiler_from("", "", ""),
            Some("aarch64-unknown-linux-gnu-gcc".to_owned()),
            "with nothing set, the tap's C compiler beside DEFAULT_CXX"
        );
    }

    #[test]
    fn a_cxx_compiler_nothing_follows_from_skips_the_abi_check() {
        // No error: the check is a guard against a board image moving
        // NE10, and a build that cannot run it links exactly as it did
        // before the check existed. build.rs warns instead.
        assert_eq!(abi_compiler_from("", "", "my-cross-compiler"), None);
    }

    #[test]
    fn the_abi_archiver_follows_a_gcc_name() {
        assert_eq!(
            abi_archiver("aarch64-linux-gnu-gcc"),
            Some("aarch64-linux-gnu-ar".to_owned())
        );
        assert_eq!(abi_archiver("gcc"), Some("ar".to_owned()));
        assert_eq!(
            abi_archiver("clang"),
            None,
            "clang wants llvm-ar, not an ar beside it; cc resolves that"
        );
    }

    #[test]
    fn a_resolved_linker_nothing_follows_from_is_refused() {
        // A directly configured non-GNU linker (clang, lld, mold, ...)
        // names no C++ compiler to derive, and BELA_CC is the legacy
        // path's variable, not this one's — guessing here would risk
        // the same toolchain mismatch BELA_CC guards against.
        let error = shim_compiler_from("", "clang", "").unwrap_err();
        assert!(
            error.contains("BELA_CXX"),
            "the message should say what to set, got: {error}"
        );
    }

    #[test]
    fn the_archiver_follows_the_compiler_it_belongs_to() {
        assert_eq!(
            shim_archiver("aarch64-unknown-linux-gnu-g++"),
            Some("aarch64-unknown-linux-gnu-ar".to_owned()),
            "cc would otherwise look for one named after the target triple"
        );
        assert_eq!(shim_archiver("g++"), Some("ar".to_owned()));
    }

    #[test]
    fn an_archiver_that_does_not_follow_is_left_to_cc() {
        // `clang++` wants llvm-ar, and it also ends in the letters
        // `g++`: deriving from it would name `clanar`. AR is the way
        // out for those, and cc reads it.
        assert_eq!(shim_archiver("clang++"), None);
        assert_eq!(shim_archiver("aarch64-linux-gnu-clang++"), None);
    }

    #[test]
    fn a_compiler_named_by_its_path_is_still_one() {
        // docs/cross-compile.md allows an absolute path, and
        // /usr/bin/gcc is the board's own compiler.
        assert_eq!(
            shim_compiler_from("", "", "/usr/bin/gcc"),
            Ok("/usr/bin/g++".to_owned())
        );
        assert_eq!(
            shim_compiler_from("", "", "/opt/tc/bin/aarch64-linux-gnu-gcc"),
            Ok("/opt/tc/bin/aarch64-linux-gnu-g++".to_owned())
        );
        assert_eq!(
            shim_archiver("/usr/bin/g++"),
            Some("/usr/bin/ar".to_owned()),
            "and the archiver beside it"
        );
    }

    #[test]
    fn a_compiler_that_merely_ends_in_gcc_is_not_one() {
        // Same trap on the compiler side: only a bare `gcc` or a
        // `<triple>-gcc` names a toolchain to follow.
        assert!(shim_compiler_from("", "", "notgcc").is_err());
        assert_eq!(shim_archiver("notg++"), None);
        assert_eq!(
            shim_archiver("/usr/bin/clang++"),
            None,
            "a path does not make it one"
        );
    }
}

// The metadata encoding build.rs publishes so `bela` can relay device
// link arguments to its own dependents; tested here for the same
// reason as shim_compiler above. See link_args.rs and bela/link_args.rs.
#[cfg(test)]
mod link_args {
    extern crate std;

    use std::borrow::ToOwned;
    use std::format;
    use std::string::{String, ToString};
    use std::vec;
    use std::vec::Vec;

    include!("../link_args.rs");

    fn args(values: &[&str]) -> Vec<String> {
        values.iter().map(|value| (*value).to_owned()).collect()
    }

    #[test]
    fn no_arguments_still_publishes_a_zero_count() {
        assert_eq!(
            encode_link_args(&[]),
            vec![("LINK_ARGS_COUNT".to_owned(), "0".to_owned())],
            "a dependent has to see a count of zero, not an absent key, \
             to tell \"nothing to add\" apart from \"never ran\""
        );
    }

    #[test]
    fn arguments_are_indexed_from_zero_in_order() {
        assert_eq!(
            encode_link_args(&args(&["--sysroot=/opt/bela", "-Bfoo"])),
            vec![
                ("LINK_ARGS_COUNT".to_owned(), "2".to_owned()),
                ("LINK_ARGS_0".to_owned(), "--sysroot=/opt/bela".to_owned()),
                ("LINK_ARGS_1".to_owned(), "-Bfoo".to_owned()),
            ]
        );
    }

    #[test]
    fn whitespace_in_an_argument_survives_uninterpreted() {
        // The reason for a count-plus-index encoding over one joined
        // string: a BELA_SYSROOT with a space in it must not need a
        // shell-style parser on the reading side.
        let value = "--sysroot=/Volumes/Bela Sysroot";
        assert_eq!(
            encode_link_args(&args(&[value])),
            vec![
                ("LINK_ARGS_COUNT".to_owned(), "1".to_owned()),
                ("LINK_ARGS_0".to_owned(), value.to_owned()),
            ]
        );
    }
}

// The shim's header and the declarations mirroring it are edited by
// hand, and a value that drifts between them is not a compile error —
// it is a safe API that reads one failure as another. This is the
// cheap half of the guard: the numbers.
#[cfg(test)]
mod shim_header {
    extern crate std;

    use std::format;

    /// `shim/midi.h`, read at compile time from the crate this
    /// declares the shim for.
    const HEADER: &str = include_str!("../shim/midi.h");

    /// The value of `#define <name> ...`, with one level of
    /// parentheses taken off — the header writes negative constants as
    /// `(-1000)`, as a C header should.
    fn defined(name: &str) -> i64 {
        let line = HEADER
            .lines()
            .find(|line| line.starts_with(&format!("#define {name} ")))
            .unwrap_or_else(|| panic!("{name} is not defined in shim/midi.h"));
        let value = line.split_whitespace().nth(2).expect("a value");
        value
            .trim_start_matches('(')
            .trim_end_matches(')')
            .parse()
            .expect("a number")
    }

    #[test]
    fn the_constants_match_the_header() {
        assert_eq!(
            defined("BELA_MIDI_MESSAGE_MAX"),
            i64::try_from(super::BELA_MIDI_MESSAGE_MAX).expect("a small buffer size")
        );
        assert_eq!(
            defined("BELA_MIDI_NO_SUCH_PORT"),
            i64::from(super::BELA_MIDI_NO_SUCH_PORT)
        );
        assert_eq!(
            defined("BELA_MIDI_ALREADY_OPEN"),
            i64::from(super::BELA_MIDI_ALREADY_OPEN)
        );
    }
}