Your first driver
Read this page in the built book. Its code blocks come from the repository, and GitHub or an editor shows only the lines that include them. Read it on the website, at oscyl.github.io/oscyl/docs/tutorials/first-driver.html, or build the book yourself:
- Install mdBook. On x86_64 Linux,
scripts/docs-tools.sh ~/.local/bindownloads the version that CI uses.- Run
mdbook build docsin the repository.- Open
target/book/tutorials/first-driver.html.
In this tutorial you write a driver for the Tutorial Mono, a small synth that exists only in this tutorial. You build it one file at a time, test each file, and finish when the driver passes Oscyl’s conformance suite.
A driver teaches Oscyl one synth model. When a driver passes the suite, every app can read the synth, edit its programs, play them and write them back.
It takes about an hour.
What you need
- A clone of the repository that builds: Try Oscyl without a synth shows how.
- Some Rust. You copy every line of code from this page, but you read it too.
The Tutorial Mono
A synth maker publishes what its synth sends and answers, in a MIDI implementation chart. This is the chart of the Tutorial Mono.
- It has one bank of 16 program slots, numbered 0 to 15, and an edit buffer.
- A program is 14 bytes: an 8-character name in printable ASCII, padded with spaces, then one byte for each of six parameters.
- Every SysEx message starts with
F0 7D 54.7Dis the manufacturer ID that MIDI keeps for non-commercial use.54is the model.
The six parameters, in the order of their bytes after the name:
| Byte | Parameter | Group | Range | Control Change |
|---|---|---|---|---|
| 8 | Wave | Oscillator | 0 to 3: Saw, Square, Triangle, Noise | 70 |
| 9 | Glide | Oscillator | 0 (off) or 1 (on) | 65, sent as 0 or 127 |
| 10 | Cutoff | Filter | 0 to 127 | 74 |
| 11 | Resonance | Filter | 0 to 127 | 71 |
| 12 | Attack | Envelope | 0 to 127 | 73 |
| 13 | Release | Envelope | 0 to 127 | 72 |
The synth’s messages:
| Message | Bytes | Answer |
|---|---|---|
| Program request | F0 7D 54 01 slot F7 | A program dump of that slot |
| Program dump | F0 7D 54 02 slot program F7 | The synth stores it, then sends an acknowledgement |
| Edit buffer request | F0 7D 54 03 F7 | An edit buffer dump |
| Edit buffer dump | F0 7D 54 04 program F7 | The synth plays it, then sends an acknowledgement |
| Acknowledgement | F0 7D 54 7F slot F7 | Sent by the synth; slot is 7F for the edit buffer |
To the MIDI device inquiry (F0 7E 7F 06 01 F7), the synth answers
F0 7E channel 06 02 7D 54 4D 01 00 01 00 00 00 F7:
06 02: this is an identity reply;7D: the manufacturer;54 4D(“TM”): the family, the Tutorial Mono;01 00: the model in the family;01 00 00 00: the firmware version.
1. Start from an empty crate
The repository holds the finished driver in crates/drivers/tutorial-synth.
Delete it, so that you can rewrite it. Git keeps the finished files:
git restore crates/drivers/tutorial-synth brings them back at any time.
rm -r crates/drivers/tutorial-synth
mkdir -p crates/drivers/tutorial-synth/src crates/drivers/tutorial-synth/tests
The workspace includes every crate under crates/drivers/, so you do not
register the crate anywhere. The crate has three names, each for one use:
- the folder
tutorial-synth; - the package
oscyl-tutorial-synth, which you give to Cargo with-p; - the driver’s id
oscyl-tutorial-mono. The apps and--synthfind a driver by its id once it is inoscyl_midi::DRIVERS. The tutorial’s driver is not, so no app lists it: you run it through its tests. A real driver gets registered, as Add a driver for a new synth says.
Create crates/drivers/tutorial-synth/Cargo.toml:
[package]
name = "oscyl-tutorial-synth"
description = "The Tutorial Mono, an invented synth, and the driver that Oscyl's first-driver tutorial builds"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
authors.workspace = true
publish = false
[dependencies]
oscyl-driver = { path = "../../oscyl-driver" }
[dev-dependencies]
oscyl-conformance = { path = "../../oscyl-conformance" }
The driver depends only on oscyl-driver, the contract. The conformance
suite is a dev-dependency: only the tests use it.
Create src/lib.rs. It names the six files that you write in the next
steps:
//! The Tutorial Mono, a small invented synth, and its Oscyl driver.
//!
//! The tutorial "Your first driver" (docs/tutorials/first-driver.md) builds
//! this crate one file at a time. No app lists the Tutorial Mono, because
//! the crate is not in `oscyl_midi::DRIVERS`.
pub mod driver;
pub mod files;
pub mod msg;
pub mod program;
pub mod session;
pub mod sim;
Create the six files, empty for now, and build:
cd crates/drivers/tutorial-synth
touch src/driver.rs src/files.rs src/msg.rs src/program.rs src/session.rs src/sim.rs
cd ../../..
cargo build -p oscyl-tutorial-synth
Cargo builds the crate and prints Finished. The crate is empty, but it
compiles: Rust accepts an empty module. Each file stays empty until its
step.
2. The program
Oscyl treats a program as bytes that only the driver understands. The apps
read and change a program only through the driver. Open src/program.rs.
First, the fields. A FieldInfo gives a parameter’s name, the group that it
belongs to, and its smallest and largest raw value:
//! The Tutorial Mono's program: an 8-character name, then one byte for
//! each field. Every byte is 7-bit, so a SysEx dump carries the program
//! as it is.
use oscyl_driver::{DriverError, FieldInfo};
/// The program's parameters, in the order of their bytes after the name.
pub const FIELDS: [FieldInfo; 6] = [
field("Wave", "Oscillator", 3),
field("Glide", "Oscillator", 1),
field("Cutoff", "Filter", 127),
field("Resonance", "Filter", 127),
field("Attack", "Envelope", 127),
field("Release", "Envelope", 127),
];
/// The names of the values of field 0, Wave.
pub const WAVES: [&str; 4] = ["Saw", "Square", "Triangle", "Noise"];
/// The name's length in bytes: ASCII, padded with spaces.
pub const NAME_LEN: usize = 8;
/// A program's length in bytes.
pub const LEN: usize = NAME_LEN + FIELDS.len();
const fn field(name: &'static str, group: &'static str, max: u16) -> FieldInfo {
FieldInfo {
name,
group,
min: 0,
max,
}
}
Next, a check that refuses bytes that are not a whole program. Every other function calls it first, so bad bytes never go further:
/// Whether `c` can be part of a name: printable ASCII.
pub fn allowed(c: char) -> bool {
(' '..='~').contains(&c)
}
/// Refuses bytes that are not a whole program: a wrong length, a name
/// character that is not printable ASCII, or a field out of its range.
pub fn check(bytes: &[u8]) -> Result<(), DriverError> {
if bytes.len() != LEN {
return Err(DriverError(format!(
"a program has {LEN} bytes, not {}",
bytes.len()
)));
}
let (name, values) = bytes.split_at(NAME_LEN);
if !name.iter().all(|&b| allowed(char::from(b))) {
return Err(DriverError("the name is not printable ASCII".into()));
}
for (f, &v) in FIELDS.iter().zip(values) {
if u16::from(v) > f.max {
return Err(DriverError(format!("{} = {v} is out of range", f.name)));
}
}
Ok(())
}
Then the functions that make a program and read or change one field:
/// The new program: "Init", a saw with the filter open.
pub fn init() -> Vec<u8> {
let mut bytes = b"Init ".to_vec();
bytes.extend([0, 0, 127, 0, 0, 20]);
bytes
}
/// The value of field `i` in `bytes`.
pub fn get(bytes: &[u8], i: usize) -> Result<u16, DriverError> {
check(bytes)?;
let at = NAME_LEN + index(i)?;
Ok(u16::from(bytes[at]))
}
/// Sets field `i` in `bytes` to `value`, which must be in its range.
pub fn set(bytes: &mut [u8], i: usize, value: u16) -> Result<(), DriverError> {
check(bytes)?;
let f = &FIELDS[index(i)?];
if value > f.max {
return Err(DriverError(format!("{} = {value} is out of range", f.name)));
}
// The range check above keeps `value` at 127 or less.
bytes[NAME_LEN + i] = value as u8;
Ok(())
}
fn index(i: usize) -> Result<usize, DriverError> {
if i < FIELDS.len() {
Ok(i)
} else {
Err(DriverError(format!("no field {i}")))
}
}
Then the name:
/// The program's name, without the padding.
pub fn name(bytes: &[u8]) -> Result<String, DriverError> {
check(bytes)?;
let name = String::from_utf8_lossy(&bytes[..NAME_LEN]);
Ok(name.trim_end().to_string())
}
/// Sets the name: at most 8 printable ASCII characters.
pub fn set_name(bytes: &mut [u8], name: &str) -> Result<(), DriverError> {
check(bytes)?;
if name.len() > NAME_LEN || !name.chars().all(allowed) {
return Err(DriverError(format!(
"a name has at most {NAME_LEN} printable ASCII characters"
)));
}
let padded = format!("{name:<NAME_LEN$}");
bytes[..NAME_LEN].copy_from_slice(padded.as_bytes());
Ok(())
}
Last, a test at the end of the file:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_field_and_the_name_read_back() {
let mut p = init();
set(&mut p, 2, 64).unwrap();
set_name(&mut p, "Bass").unwrap();
assert_eq!(get(&p, 2), Ok(64));
assert_eq!(name(&p).as_deref(), Ok("Bass"));
assert!(set(&mut p, 0, 4).is_err(), "Wave has four values");
assert!(check(&p[1..]).is_err(), "a program has 14 bytes");
}
}
Run it:
cargo test -p oscyl-tutorial-synth program
test program::tests::a_field_and_the_name_read_back ... ok
3. The messages
Open src/msg.rs. One enum holds every message from the chart:
//! The Tutorial Mono's SysEx messages.
//!
//! Every message starts with `F0 7D 54`: `7D` is the manufacturer ID that
//! MIDI keeps for non-commercial use, and `54` is the model. The synth
//! answers a dump with an acknowledgement after it stores the dump.
use crate::program;
/// The number of program slots: 0 to 15.
pub const SLOTS: u16 = 16;
const HEADER: [u8; 3] = [0xF0, 0x7D, 0x54];
const PROGRAM_REQUEST: u8 = 0x01;
const PROGRAM_DUMP: u8 = 0x02;
const EDIT_REQUEST: u8 = 0x03;
const EDIT_DUMP: u8 = 0x04;
const ACK: u8 = 0x7F;
/// The slot byte of an acknowledgement for the edit buffer.
const EDIT_BUFFER: u8 = 0x7F;
/// One message to or from the synth.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Msg {
/// Asks for the program in a slot.
ProgramRequest(u16),
/// The program in a slot: to store it, or as an answer.
ProgramDump(u16, Vec<u8>),
/// Asks for the edit buffer: the program the synth plays now.
EditRequest,
/// The edit buffer: to play it, or as an answer.
EditDump(Vec<u8>),
/// The synth stored a dump: in slot `Some(n)`, or in the edit buffer.
Ack(Option<u16>),
}
encode turns a message into bytes. decode does the opposite, and gives
None for any message that is not one of the Tutorial Mono’s:
impl Msg {
/// The message as bytes, from `F0` to `F7`.
pub fn encode(&self) -> Vec<u8> {
let body = match self {
Msg::ProgramRequest(n) => vec![PROGRAM_REQUEST, slot_byte(*n)],
Msg::ProgramDump(n, p) => [&[PROGRAM_DUMP, slot_byte(*n)][..], p].concat(),
Msg::EditRequest => vec![EDIT_REQUEST],
Msg::EditDump(p) => [&[EDIT_DUMP][..], p].concat(),
Msg::Ack(Some(n)) => vec![ACK, slot_byte(*n)],
Msg::Ack(None) => vec![ACK, EDIT_BUFFER],
};
[&HEADER[..], &body, &[0xF7]].concat()
}
/// The message in `bytes`, or `None` when it is not one of ours.
pub fn decode(bytes: &[u8]) -> Option<Msg> {
let body = bytes.strip_prefix(&HEADER[..])?.strip_suffix(&[0xF7])?;
let slot = |b: u8| (u16::from(b) < SLOTS).then_some(u16::from(b));
let program = |p: &[u8]| (p.len() == program::LEN).then(|| p.to_vec());
match body {
[PROGRAM_REQUEST, n] => Some(Msg::ProgramRequest(slot(*n)?)),
[PROGRAM_DUMP, n, p @ ..] => Some(Msg::ProgramDump(slot(*n)?, program(p)?)),
[EDIT_REQUEST] => Some(Msg::EditRequest),
[EDIT_DUMP, p @ ..] => Some(Msg::EditDump(program(p)?)),
[ACK, EDIT_BUFFER] => Some(Msg::Ack(None)),
[ACK, n] => Some(Msg::Ack(Some(slot(*n)?))),
_ => None,
}
}
}
/// A slot as one 7-bit byte. Callers keep `n` below [`SLOTS`].
fn slot_byte(n: u16) -> u8 {
(n & 0x7F) as u8
}
Oscyl knows a synth by its answer to the device inquiry. Add the answer and a function that recognises it from any channel:
/// The start of the synth's answer to the MIDI device inquiry, after the
/// channel byte: manufacturer `7D`, family `54 4D`, member `01 00`. Four
/// version bytes and `F7` follow.
const IDENTITY: [u8; 7] = [0x06, 0x02, 0x7D, 0x54, 0x4D, 0x01, 0x00];
/// The synth's answer to the device inquiry, from channel `channel`.
pub fn identity_reply(channel: u8) -> Vec<u8> {
[&[0xF0, 0x7E, channel][..], &IDENTITY, &[1, 0, 0, 0, 0xF7]].concat()
}
/// Whether `bytes` is the Tutorial Mono's answer to the device inquiry,
/// from any channel.
pub fn is_identity(bytes: &[u8]) -> bool {
bytes.len() == 15 && bytes[..2] == [0xF0, 0x7E] && bytes[3..10] == IDENTITY
}
Add the test and run it:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn messages_round_trip() {
let p = program::init();
for m in [
Msg::ProgramRequest(15),
Msg::ProgramDump(3, p.clone()),
Msg::EditRequest,
Msg::EditDump(p),
Msg::Ack(Some(0)),
Msg::Ack(None),
] {
assert_eq!(Msg::decode(&m.encode()), Some(m));
}
assert_eq!(
Msg::ProgramRequest(2).encode(),
[0xF0, 0x7D, 0x54, 0x01, 0x02, 0xF7]
);
assert!(is_identity(&identity_reply(0x7F)));
}
}
cargo test -p oscyl-tutorial-synth msg
test msg::tests::messages_round_trip ... ok
4. The simulator
A simulator is the synth in code. The conformance suite talks to it, and so
does the apps’ demo mode. Open src/sim.rs. The synth’s memory is 16
programs and an edit buffer:
//! A simulated Tutorial Mono. It answers every message as the synth
//! would, with no sound and no MIDI port: the conformance suite and demo
//! mode talk to it.
use oscyl_driver::Simulator;
use oscyl_driver::sysex::DEVICE_INQUIRY;
use crate::msg::{Msg, SLOTS, identity_reply};
use crate::program;
/// The synth's memory: one program per slot, and the edit buffer.
pub struct Sim {
programs: Vec<Vec<u8>>,
edit: Vec<u8>,
/// The fault `lose_reply`: the synth answers nothing.
lose_reply: bool,
}
impl Default for Sim {
fn default() -> Sim {
Sim {
programs: vec![program::init(); usize::from(SLOTS)],
edit: program::init(),
lose_reply: false,
}
}
}
The synth’s answer to each message follows the chart. A dump that holds a bad program gets no answer, as on a real synth:
impl Sim {
/// The synth's answer to one of its own messages, if it answers.
fn answer(&mut self, bytes: &[u8]) -> Option<Msg> {
match Msg::decode(bytes)? {
Msg::ProgramRequest(n) => {
let p = self.programs[usize::from(n)].clone();
Some(Msg::ProgramDump(n, p))
}
Msg::EditRequest => Some(Msg::EditDump(self.edit.clone())),
Msg::ProgramDump(n, p) if program::check(&p).is_ok() => {
self.programs[usize::from(n)] = p;
Some(Msg::Ack(Some(n)))
}
Msg::EditDump(p) if program::check(&p).is_ok() => {
self.edit = p;
Some(Msg::Ack(None))
}
// A bad program, or a message only the synth sends.
_ => None,
}
}
}
The Simulator trait is what Oscyl sees. The fault lose_reply makes the
synth silent. The suite switches it on to check that a lost reply never
counts as success:
impl Simulator for Sim {
fn handle(&mut self, msg: &[u8]) -> Vec<Vec<u8>> {
let reply = if msg == DEVICE_INQUIRY {
Some(identity_reply(0x7F))
} else {
self.answer(msg).map(|m| m.encode())
};
if self.lose_reply {
return vec![];
}
reply.into_iter().collect()
}
/// The Tutorial Mono stores a dump at once: no work waits for idle time.
fn idle_tick(&mut self) {}
fn program(&self, slot: u16) -> Option<Vec<u8>> {
self.programs.get(usize::from(slot)).cloned()
}
fn edit_buffer(&self) -> Vec<u8> {
self.edit.clone()
}
fn is_settled(&self) -> bool {
true
}
fn faults(&self) -> &'static [&'static str] {
&["lose_reply"]
}
fn inject(&mut self, fault: &str) {
match fault {
"lose_reply" => self.lose_reply = true,
_ => panic!("unknown fault {fault:?}"),
}
}
}
Add the test and run it:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_dump_is_stored_and_acknowledged() {
let mut sim = Sim::default();
let mut p = program::init();
program::set_name(&mut p, "Stored").unwrap();
let reply = sim.handle(&Msg::ProgramDump(5, p.clone()).encode());
assert_eq!(reply, [Msg::Ack(Some(5)).encode()]);
assert_eq!(sim.program(5), Some(p));
}
}
cargo test -p oscyl-tutorial-synth sim
test sim::tests::a_dump_is_stored_and_acknowledged ... ok
5. The session
The session is the protocol. It decides what to send for each operation and which answer finishes it. It never touches a port or a clock: Oscyl gives it the bytes and the time. This is sans-IO. The same session runs on every platform and in tests.
The request engine in oscyl_driver::engine does the hard part. It keeps
one request in flight, times out a request whose reply does not come, and
reports progress. You describe the synth’s protocol to it with the trait
Protocol:
| Item | What it is |
|---|---|
expand(op) | Turns one operation, such as “read slots 3 and 4”, into its requests, in order. |
on_message(bytes, expect, what, index) | Says what one message from the synth means for the request in flight. |
Step | One request: msg, the bytes to send; expect, what completes it; timeout; what, its name in error messages (“program write”); index, its slot, also for error messages. |
Outcome::Done | The message completes the request, with an event for the apps or none. |
Outcome::Unrelated | The message does not answer the request. The engine keeps waiting. |
Outcome::Failed | The message fails the request, and the engine drops the rest of the operation. |
progress, done, failed | Make the events that the engine reports. |
Open src/session.rs. First, write the requests that make up each
operation:
//! The session: the Tutorial Mono's protocol, sans IO.
//!
//! The request engine of `oscyl_driver::engine` keeps one request in
//! flight and times it out. This file says what to send for each
//! operation and which reply completes each request. A write is done only
//! when the synth acknowledges it, so a lost reply is a failure.
use std::time::{Duration, Instant};
use oscyl_driver::engine::{Engine, OpError, Outcome, Protocol, Step};
use oscyl_driver::{DriverError, DriverSession, SessionEvent, SessionOp};
use crate::msg::{Msg, SLOTS};
use crate::program;
/// The reply that completes a request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Expect {
Program(u16),
EditBuffer,
Ack(Option<u16>),
}
/// How long to wait for a reply. It finds a dead link; it does not pace
/// the messages.
const TIMEOUT: Duration = Duration::from_secs(2);
/// The Tutorial Mono's rules for the request engine.
pub struct Mono;
impl Protocol for Mono {
type Op = SessionOp;
type Event = SessionEvent;
type Expect = Expect;
/// The requests that make up `op`, in order.
fn expand(&self, op: SessionOp) -> Vec<Step<Expect>> {
let step = |msg: Msg, expect, what, index| Step {
msg: msg.encode(),
expect,
timeout: TIMEOUT,
what,
index,
};
match op {
SessionOp::ReadCurrent => {
vec![step(
Msg::EditRequest,
Expect::EditBuffer,
"edit buffer read",
None,
)]
}
SessionOp::ReadPrograms(slots) => slots
.into_iter()
.map(|n| {
step(
Msg::ProgramRequest(n),
Expect::Program(n),
"program read",
Some(n),
)
})
.collect(),
SessionOp::WritePrograms(batch) => batch
.into_iter()
.map(|(n, p)| {
let expect = Expect::Ack(Some(n));
step(Msg::ProgramDump(n, p), expect, "program write", Some(n))
})
.collect(),
SessionOp::Audition(p) => {
vec![step(Msg::EditDump(p), Expect::Ack(None), "audition", None)]
}
}
}
Notice that a write waits for the acknowledgement. The program dump alone does not finish it.
Second, write what each message from the synth means for the request in
flight. on_message gets what and index so that an error can name
them. This driver’s one error names the step only, so it ignores index.
Add the rest of the impl block, and a helper after it:
/// What one message from the synth means for the request in flight.
fn on_message(
&self,
bytes: &[u8],
expect: Expect,
what: &'static str,
_index: Option<u16>,
) -> Outcome<SessionEvent> {
match (Msg::decode(bytes), expect) {
(Some(Msg::ProgramDump(n, p)), Expect::Program(m)) if n == m => {
whole(p, what, |p| SessionEvent::Program(n, p))
}
(Some(Msg::EditDump(p)), Expect::EditBuffer) => whole(p, what, SessionEvent::Current),
(Some(Msg::Ack(s)), Expect::Ack(t)) if s == t => Outcome::Done(None),
// Another message: an echo of our own, or a dump sent by hand.
_ => Outcome::Unrelated,
}
}
fn progress(done: usize, total: usize) -> SessionEvent {
SessionEvent::Progress { done, total }
}
fn done() -> SessionEvent {
SessionEvent::Done
}
fn failed(e: OpError) -> SessionEvent {
SessionEvent::Failed(e)
}
}
/// The request is done with the event `event(p)` when `p` is a whole
/// program. Bad bytes never reach the apps: the request fails.
fn whole(
p: Vec<u8>,
what: &'static str,
event: impl FnOnce(Vec<u8>) -> SessionEvent,
) -> Outcome<SessionEvent> {
match program::check(&p) {
Ok(()) => Outcome::Done(Some(event(p))),
Err(e) => Outcome::Failed(OpError::BadData { what, error: e.0 }),
}
}
A message that does not answer the request is Unrelated, and the engine
keeps waiting. If no answer comes, the request times out and fails.
The DriverSession trait is what Oscyl calls. The session checks every slot
and program before it queues anything, then passes each call to the engine:
/// A session with one Tutorial Mono.
pub struct Session(Engine<Mono>);
impl Default for Session {
fn default() -> Session {
Session(Engine::new(Mono))
}
}
/// Refuses a slot past the last one.
fn slot(n: u16) -> Result<(), DriverError> {
if n < SLOTS {
Ok(())
} else {
Err(DriverError(format!("the Tutorial Mono has no slot {n}")))
}
}
impl DriverSession for Session {
/// Checks every slot and program first: a bad operation sends nothing.
fn submit(&mut self, op: SessionOp) -> Result<(), DriverError> {
match &op {
SessionOp::ReadCurrent => {}
SessionOp::ReadPrograms(slots) => slots.iter().try_for_each(|&n| slot(n))?,
SessionOp::WritePrograms(batch) => batch
.iter()
.try_for_each(|(n, p)| slot(*n).and_then(|()| program::check(p)))?,
SessionOp::Audition(p) => program::check(p)?,
}
self.0.submit(op);
Ok(())
}
fn is_idle(&self) -> bool {
self.0.is_idle()
}
fn poll_transmit(&mut self, now: Instant) -> Option<Vec<u8>> {
self.0.poll_transmit(now)
}
fn next_deadline(&self) -> Option<Instant> {
self.0.next_deadline()
}
fn handle_timeout(&mut self, now: Instant) {
self.0.handle_timeout(now)
}
fn handle_input(&mut self, bytes: &[u8]) {
self.0.handle_input(bytes)
}
fn poll_event(&mut self) -> Option<SessionEvent> {
self.0.poll_event()
}
}
Add the test and run it:
#[cfg(test)]
mod tests {
use super::*;
use crate::sim::Sim;
use oscyl_driver::Simulator;
#[test]
fn a_write_ends_when_the_synth_acknowledges_it() {
let (mut s, mut sim) = (Session::default(), Sim::default());
s.submit(SessionOp::WritePrograms(vec![(4, program::init())]))
.unwrap();
let now = Instant::now();
let request = s.poll_transmit(now).unwrap();
assert!(s.poll_transmit(now).is_none(), "one request at a time");
for reply in sim.handle(&request) {
s.handle_input(&reply);
}
let events: Vec<_> = std::iter::from_fn(|| s.poll_event()).collect();
assert_eq!(events.last(), Some(&SessionEvent::Done));
assert!(s.submit(SessionOp::ReadPrograms(vec![16])).is_err());
}
}
cargo test -p oscyl-tutorial-synth session
test session::tests::a_write_ends_when_the_synth_acknowledges_it ... ok
6. Files
A driver reads and writes the synth’s own file formats, so that you can open
a file from the maker’s software. The Tutorial Mono’s .syx file is
program dumps, one after the other. Write src/files.rs:
//! `.syx` files: program dumps one after the other, as the synth sends
//! them. The format has no place for a program's author or comment.
use oscyl_driver::sysex::Framer;
use oscyl_driver::{DriverError, LibProgram, LibraryData};
use crate::msg::{Msg, SLOTS};
use crate::program;
/// Every program dump in `bytes`, in file order.
pub fn import(bytes: &[u8]) -> Result<LibraryData, DriverError> {
let mut programs = vec![];
for m in Framer::new().push(bytes) {
let Some(Msg::ProgramDump(_, data)) = Msg::decode(&m) else {
return Err(DriverError(
"the file holds a message that is not a program dump".into(),
));
};
program::check(&data)?;
programs.push(LibProgram {
data,
..LibProgram::default()
});
}
if programs.is_empty() {
return Err(DriverError(
"the file holds no Tutorial Mono programs".into(),
));
}
Ok(LibraryData {
programs,
extras: Default::default(),
})
}
/// The programs of `lib` as dumps for slots 0, 1, 2 and on.
pub fn export(lib: &LibraryData) -> Result<Vec<u8>, DriverError> {
if lib.programs.len() > usize::from(SLOTS) {
return Err(DriverError(format!(
"a file holds at most {SLOTS} programs"
)));
}
let mut out = vec![];
for (n, p) in (0..).zip(&lib.programs) {
program::check(&p.data)?;
out.extend(Msg::ProgramDump(n, p.data.clone()).encode());
}
Ok(out)
}
cargo build -p oscyl-tutorial-synth
7. The driver
The Driver trait is all that the apps see of a synth. Open
src/driver.rs. First, the facts: the synth’s identity, what it can do, and
its file format:
//! The Tutorial Mono behind the driver contract: what the apps see.
use oscyl_driver::{
Bank, Capabilities, Control, Curation, Driver, DriverError, DriverSession, FieldInfo,
FileFormat, Info, LibraryData, NameRules, Simulator, curation_by_group, format_raw_default,
};
use crate::msg::{SLOTS, is_identity};
use crate::program::{self, FIELDS, WAVES};
use crate::{files, session, sim};
/// The Tutorial Mono's driver. Apps see it as `&dyn Driver`.
pub struct TutorialMono;
pub static DRIVER: TutorialMono = TutorialMono;
static INFO: Info = Info {
id: "oscyl-tutorial-mono",
vendor: "Oscyl",
model: "Tutorial Mono",
};
/// One bank of 16 slots, all of them writable, and an edit buffer.
static CAPABILITIES: Capabilities = Capabilities {
banks: &[Bank {
name: "User",
first: 0,
len: SLOTS,
writable: true,
}],
edit_buffer: true,
live_changes: true,
units: &[],
};
const SYX: FileFormat = FileFormat {
ext: "syx",
name: "Tutorial Mono program dumps",
keeps_metadata: false,
};
Start the impl block. These methods hand the program work to
program.rs:
impl Driver for TutorialMono {
fn info(&self) -> &'static Info {
&INFO
}
fn capabilities(&self) -> &'static Capabilities {
&CAPABILITIES
}
fn fields(&self) -> &'static [FieldInfo] {
&FIELDS
}
fn name_rules(&self) -> NameRules {
NameRules {
max_len: program::NAME_LEN,
allowed: program::allowed,
}
}
fn init_program(&self) -> Vec<u8> {
program::init()
}
fn check_program(&self, bytes: &[u8]) -> Result<(), DriverError> {
program::check(bytes)
}
fn get(&self, bytes: &[u8], field: usize) -> Result<u16, DriverError> {
program::get(bytes, field)
}
fn set(&self, bytes: &mut [u8], field: usize, value: u16) -> Result<(), DriverError> {
program::set(bytes, field, value)
}
fn name(&self, bytes: &[u8]) -> Result<String, DriverError> {
program::name(bytes)
}
fn set_name(&self, bytes: &mut [u8], name: &str) -> Result<(), DriverError> {
program::set_name(bytes, name)
}
Add the file format:
fn file_formats(&self) -> &'static [FileFormat] {
&[SYX]
}
fn import(&self, ext: &str, bytes: &[u8]) -> Result<LibraryData, DriverError> {
syx(ext)?;
files::import(bytes)
}
fn export(&self, ext: &str, lib: &LibraryData) -> Result<Vec<u8>, DriverError> {
syx(ext)?;
files::export(lib)
}
Add the editor. curation puts the fields on pages. Here
curation_by_group makes one page for each group: Oscillator, Filter and
Envelope. control and format_raw give Wave its four names:
/// One editor page for each group of fields.
fn curation(&self) -> Curation {
curation_by_group(self.fields())
}
/// Wave picks one of four names. Glide is a switch.
fn control(&self, _bytes: &[u8], field: usize) -> Control {
match field {
0 => Control::Choice(&WAVES),
1 => Control::Toggle,
_ => Control::Continuous,
}
}
fn format_raw(&self, field: usize, raw: u16) -> String {
match (field, FIELDS.get(field)) {
(0, _) => WAVES.get(usize::from(raw)).copied().unwrap_or("?").into(),
(_, Some(f)) => format_raw_default(f, raw),
(_, None) => String::new(),
}
}
Add live edits. With Live on, an app sends this Control Change for each edit, so the change plays at once:
/// One Control Change for each field, so a change sounds at once on
/// the notes that play.
fn live_messages(&self, bytes: &[u8], field: usize, channel: u8) -> Option<Vec<Vec<u8>>> {
const CC: [u8; 6] = [70, 65, 74, 71, 73, 72];
let value = program::get(bytes, field).ok()?;
// Glide is a switch: MIDI reads 64 or more as on.
let value = if field == 1 { value * 127 } else { value };
Some(vec![vec![0xB0 | (channel & 0x0F), CC[field], value as u8]])
}
Last, the link to the synth: the session, the simulator, the port name and
the identity. Close the impl block:
/// The Tutorial Mono's SysEx has no channel byte, so `channel` is unused.
fn session(&self, _channel: u8) -> Box<dyn DriverSession> {
Box::new(session::Session::default())
}
fn simulator(&self) -> Box<dyn Simulator> {
Box::new(sim::Sim::default())
}
fn port_hint(&self) -> &'static [&'static str] {
&["Tutorial Mono"]
}
fn recognize(&self, identity_reply: &[u8]) -> bool {
is_identity(identity_reply)
}
}
/// Refuses every file extension but `syx`.
fn syx(ext: &str) -> Result<(), DriverError> {
if ext == SYX.ext {
Ok(())
} else {
Err(DriverError(format!(
"the Tutorial Mono has no .{ext} files"
)))
}
}
cargo build -p oscyl-tutorial-synth
8. Pass the conformance suite
Create tests/conformance.rs:
//! The checks every driver passes against its simulator.
#[test]
fn tutorial_mono_conforms() {
oscyl_conformance::run(&oscyl_tutorial_synth::driver::DRIVER);
}
Run it:
cargo test -p oscyl-tutorial-synth --test conformance
test tutorial_mono_conforms ... ok
The suite wrote programs to your simulator and read them back. It played a program in the edit buffer, lost every reply on purpose, and checked that nothing reported a false success. It also checked every field, every name, the file format, the editor pages and the live messages.
When a check fails, its message names the driver, the check and the
problem, for example oscyl-tutorial-mono: fields: Wave reads back wrong.
What you built
You wrote a complete driver:
- a program model;
- the synth’s messages;
- a simulator;
- a sans-IO session on the request engine;
- a file format;
- the
Driverthat the apps see.
It passes the same suite as every driver of a real synth.
To put the repository’s own copy back, run:
git restore crates/drivers/tutorial-synth
Next:
- Add a driver for a new synth: from the first SysEx dump of a real synth to its hardware check.
- The driver contract: every method, and the optional ones that this driver leaves out, such as graphs, help and Generate.
- Architecture: why drivers are sans-IO and compiled in.