Bonooru Devlog #5: Teaching it to read music
DEV Community

Bonooru Devlog #5: Teaching it to read music

Bonooru can read music now. I drop a MIDI file on the window, it picks the melody track, moves it into the ocarina's nineteen notes, works out which buttons play each note and when to press them, warns me if a phrase would accidentally trigger one of the game's songs, and plays the whole thing back on my Mac with a soft, breathy tone.

Nothing goes to the Switch yet. That is the point: everything you hear in the preview is exactly what the console would get.

Bonooru is my side project to play arbitrary melodies on the ocarina in The Legend of Zelda: Ocarina of Time on Switch 2. It does that by pretending to be a wired controller. The chain is a desktop app on the PC, a "bridge" RP2040 board on USB, a UART link, and a "controller" RP2040 board that the Switch 2 sees as a Pro Controller. Devlog #0 explains the idea, #1 measures the ocarina, #2 is the controller firmware, #3 the bridge and the first melody end to end, #4 the desktop app with its status lights and on-screen gamepad.

A test score in the Roll after Epic 5. The song panel shows the auto transpose (0 st), the fit summary (13 in range ยท 4 folded ยท 0 dropped) and the official-song warning. In the Roll, each lane header shows the note and its fingering, and the ember group marks six notes that would trigger Zelda's Lullaby. Dashed ghosts in the zones above F6 and below B4 are the out-of-range notes, with leaders down to the octave they were folded into. No bridge plugged in: everything here happens on the PC.

Where we were

At the end of Epic 4 the app could drive the Switch, but it had nothing to play. Devlog #4 ended with a promise: "open a song, squeeze it into the ocarina's range, work out the fingering of every note, and play it back on the PC before anything gets near the console."

That is Epic 5, "Load a song and hear it on the PC". In the roadmap it is the first half of milestone M6; the second half, playing it on the console, is Epic 6. Fourteen stories (5.0 to 5.13), one PR each (#55 to #68), plus #54 for a Linux VM I'll come back to, and the retrospective (#70). From 28 to 30 November.

The firmware did not change at all: this whole epic is Rust on the PC, and almost all of it lives in ocb-core, the crate with no I/O, no threads and no clock.

The pipeline

Here is the whole thing on one page. Each box is a pure function in ocb-core; the GUI only calls them on a loader thread and draws the result. From a file to a timeline and a sound. Float seconds exist only inside the importers; everything after them is integer microseconds.

Every number the pipeline needs (the range, the 45 fingerings, the timing margins, the cost weights, the list of official songs) comes from one TOML file, the mapping profile. No game value is written in code. So that is where the epic started.

The mapping profile: one parser, and a FIFO

Story 5.1 made ocb_core::profile the only code in the app allowed to parse a profile. The path is short: TOML into a generic table, read the integer schema, run a chain of Nโ†’N+1 migrations, deserialize with deny_unknown_fields everywhere and no defaults, then validate. Errors are typed and point at the field, like fingerings[12].pitch.

Some of the validation rules matter later: every pitch from the low to the high end of the range must have at least one fingering; no duplicate fingering; the minimum press and the minimum gap between two presses of the same button must be at least 2 ร— max(report period, frame time) - two frames at load time. A press shorter than that could fall between two USB reports and never reach the game.

The bundled profile for Ocarina of Time on Switch 2 says this about the instrument, all measured in Devlog #1:

  • Range (sounding pitch) B4 (MIDI 71) to F6 (MIDI 89), 19 semitones
  • Note buttons L = D5, R = F5, A = A5, Y = B5, X = D6
  • Modifiers D-pad up/down = ยฑ1 semitone; left stick up/down = ยฑ2 semitones (full travel)
  • Fingerings 45 combinations (5 buttons ร— D-pad none/up/down ร— stick none/up/down), 19 of them in the community chart
  • Frame rate 60 fps

A user can drop a copy in the config folder to override the bundled one. That is where the review got interesting. A user copy is a file I don't control, so a reviewer tried a FIFO named p.toml: the app hung at start. A 200 MB file took 17 seconds and 426 MB of memory. The fix is boring and right: check it's a regular file before opening, and read through take(1 MiB + 1).

fn read_candidate(path: &Path) -> Result<String, String> {
  let meta = fs::metadata(path).map_err(|e| e.to_string())?;
  if !meta.is_file() {
    return Err("not a regular file".to_owned());
  }
  if meta.len() > MAX_PROFILE_BYTES {
    return Err(format!("larger than {MAX_PROFILE_BYTES} bytes"));
  }
  let mut text = String::new();
  fs::File::open(path)
    .and_then(|f| f.take(MAX_PROFILE_BYTES + 1).read_to_string(&mut text))
    .map_err(|e| e.to_string())?;

app/services/src/profiles.rs, trimmed. The type is checked before the file is opened, so a FIFO or a device never blocks.

Another one: a Unix file name containing a newline could forge a profile loaded โ€ฆ source=user line in the log. File names are now quoted and every control character is cleaned.

The core crate has a purity gate (C.4) that checks its Cargo.toml: only exact, allow-listed dependencies. The review broke it twice in this epic. First with toml = { package = "regex", โ€ฆ } and toml = "=1" (which Cargo reads as >=1, <2); then, in Story 5.3, with features = ["std", "parallel"] on midly. Now the gate wants exactly one version = "=X.Y.Z", refuses package, path, git and friends, and pins the feature list.

Writing a melody by hand

Story 5.2 is a small text format for melodies, so I can write a tune without a MIDI editor:

# title: Ode to Joy (excerpt)
tempo 120
E4/4 E4/4 F4/4 G4/4 | G4/4 F4/4 E4/4 D4/4 | C4/4 C4/4 D4/4 E4/4 | E4/4. D4/8 D4/2 |

A note is <name><#|b?><octave>/<1|2|4|8|16>, a trailing dot makes it 1.5 times longer, r/4 is a rest, E4:250 is a raw 250 ms note, | is a bar check, and tempo N can appear anywhere. The grammar is in the docs.

Two details I like. First, time never drifts. The parser counts in units of 1/64 of a whole note, and every position is computed from the start of its tempo segment in u128, never by adding up rounded durations:

const UNIT_US_AT_1_BPM: u128 = 3_750_000;
impl Clock {
  fn now(&self) -> u64 {
    let span = u128::from(self.seg_units) * UNIT_US_AT_1_BPM / u128::from(self.bpm.max(1));
    self.seg_start.saturating_add(u64::try_from(span).unwrap_or(u64::MAX))
  }
}

app/core/src/score/text.rs, simplified. A test plays 10 000 sixteenths at seven tempos and checks the drift is zero.

Second, errors are written for the editor that comes in Epic 9: each has a line, a column span, a message and a fix, like "Unknown note length โ€œqโ€." / "Use 1, 2, 4, 8 or 16, e.g. D5/4." The parser never stops at the first error, never panics (a proptest fuzz case checks that), and always returns the last valid parse.

The review found that bar checks blamed the wrong bar. The reference length was always bar 2, so a wrong bar 2 made bar 1 and every correct bar after it look wrong. Now the reference is the most common length among the closed bars, and bar 1 may be a pickup.

MIDI, and the files that try to hurt you

Story 5.3 imports .mid files with midly 0.5.3, alloc only: no file access, no rayon threads. Each (track, channel) pair with notes becomes a row in the track picker, in the form "name ยท ch N ยท N notes ยท N % in range". Channel 10, percussion, is skipped. A Note On with velocity 0 ends a note, and a re-trigger closes the note that is still sounding.

midly is released under the Unlicense, which my cargo deny config didn't allow. I allowed it: it is a public-domain dedication.

The fuzz test found the best bug of the epic. About 5-8 % of runs failed with "attempt to negate with overflow" inside midly. A division byte of 0x80 in the header is an SMPTE code the standard doesn't define, and midly negates i8::MIN on it, which panics in debug builds. Worse, four red proofs (more on those below) had recorded that random panic as their "failure", so they proved nothing. The fix refuses the byte before midly sees it:

// An SMPTE division with a code the standard does not define makes
// midly 0.5.3 negate an `i8::MIN` (a panic in debug builds): refuse it
// before midly sees it.
if let Some(&hi) = bytes.get(12) && hi & 0x80 != 0 && !SMPTE_CODES.contains(&hi) {
  return Err(MidiError::Damaged);
}

app/core/src/score/midi.rs

The other hostile inputs were about memory. A 7 MB file with a million tempo events spread over 1 000 tracks peaked at 16 GB of RAM, because the tempo map was copied per track. With 5 000 tracks, 21 GB and 13 seconds. Now tempo events count towards the 100 000-event budget, segments are found by binary search (partition_point), and the map is kept once.

Two more that taught me something: midly without strict quietly imports truncated files. A 170-byte test file cut at 100 bytes came back as "Ok, 5 notes". Every track must now end with its End of Track event. 29.97 fps SMPTE was timed as 29, so every time was 3.3 % too long. My own Dev Note claimed it was right.

One voice, nineteen notes

The ocarina plays one note at a time, in a 19-semitone window. A MIDI melody track can have chords and can sit anywhere on the keyboard. Story 5.4 deals with both.

Mono reduction is a skyline: sort by start, keep the highest pitch at each start, cut each note where the next one begins. A chord means exactly the same microsecond; a "near chord" a few ticks apart is an overlap, and the later note wins.

Range fit tries every shift from โˆ’24 to +24 semitones and keeps the best one by a lexicographic key:

( out, // notes still out of range: fewer is better
  std::cmp::Reverse(naturals), // more notes on white keys is better
  s.unsigned_abs(), // then the smallest shift
  std::cmp::Reverse(s), // then up rather than down
)

app/core/src/pipeline/fit.rs, comments added. Why naturals? The buttons sit on D, F, A, B, D, and every sharp or flat costs a modifier. The epic said "smallest shift" before "naturals", and I flipped it. With the literal order, Ode to Joy (written C4-G4) gets +11 semitones, which is B major with five sharps. With mine it gets +12: one octave up, no sharps at all.

Notes still out of range after the shift are folded by octaves into the range (or dropped if no octave fits, which can't happen with a 19-semitone range). The review found that no test told "fewest out" apart from "most naturals": swapping them kept all five tests green. A three-note case (Fโ™ฏ4 Gโ™ฏ4 C6) now expects +5, where the swapped version gives +11.

Fingering: Viterbi on a Pro Controller

Story 5.5 is my favourite. Each of the 19 pitches can be played by more than one combination of button, D-pad and stick: 45 fingerings in all. D5 is plain L, but it is also R + D-pad down + stick down. Which one to use depends on the notes around it: changing the D-pad is instant, but the stick glides (at Y + stick up, the first 30 ms sound about 29 cents flat, from the measurements in Devlog #1). So the cheapest fingering for a phrase is a shortest-path problem over a layered graph, and the classic answer is the Viterbi algorithm.

Viterbi over fingerings: one layer per note, one state per fingering that plays its pitch. The path with the lowest total cost wins.

The cost of a step between two fingerings:

fn transition_cost(a: &Fingering, b: &Fingering, p: &Profile) -> f64 {
  let mut c = 0.0;
  if a.dpad != b.dpad {
    c += p.cost.dpad_change; // 1
  }
  if a.stick != b.stick {
    c += p.cost.stick_change; // 2
    let through = matches!((a.stick, b.stick), (StickDir::Up, StickDir::Down) | (StickDir::Down, StickDir::Up));
    if through {
      c += p.cost.stick_through_centre; // +1
    }
  }
  if a.button == b.button {
    c += p.cost.same_button_retrigger; // +1: a re-press needs a release gap
  }
  c
}

app/core/src/pipeline/fingering.rs, weights from the profile shown as comments. A fingering outside the community chart costs 0.1 extra, only to break ties. I want to be honest about the weights: they are marked DESIGN DEFAULT (not measured) in the profile. The measurements only support the order: no change < D-pad change < stick change.

The first version ignored time, and the review caught it. Four A5 sixteenths at 120 bpm need four presses of A, and there isn't room for the release gap between them, so one note came out "too short". And the app refuses to Play a song with too-short notes. The fix puts timing into the graph: a step whose two onsets are closer than the minimum press plus the gap that step needs costs infinity, so Viterbi routes around it with an alternative fingering.

for (k, (g, c)) in prev_layer.iter().zip(&cost).enumerate() {
  let fits = gap.is_none_or(|(d, t)| d >= t.press + (t.need)(g, f));
  let step = if fits { transition_cost(g, f, p) } else { f64::INFINITY };
  let total = c + step;
  // Strictly better only: ties keep the earliest.
  if best.is_none_or(|(b, _)| total < b) {
    best = Some((total, k));
  }
}

app/core/src/pipeline/fingering.rs

Two A5s four frames apart now become Y + stick down, then A.

Timing rules

Once every note has a fingering, the timing rules turn notes into controller states on the console's 60 fps grid. They work in whole frames, and microseconds appear only at the end.

  • Value Setting Where it comes from Min press 3 frames (50 ms) measured 2, plus 1 frame of margin Gap before re-pressing the same button 5 frames (83.3 ms) my choice Modifier lead 1 frame measured 0, plus 1 frame of margin Max sustain 6000 ms measured 6500 ms, minus 500 ms of margin

The rules: Onsets never move. The rhythm is the song. Modifiers go down one frame early (the lead) and stay put between notes

Read on DEV Community ↗ ← Back to News

Comments

No comments yet. Start the discussion.