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())?; // …and the length is checked again after the read 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); } 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
strictquietly 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 when the next note uses them too.
- The previous note gives back time. Its release is
min(end, onset − need), whereneedis the re-press gap for the same button, the lead for a modifier change, or zero. - Too short: a note that can't get its 3 frames isn't played, and it is reported. Notes are removed one at a time, latest first, and Viterbi re-runs each time. The first version removed them all at once and dropped notes that would have fitted.
- Long notes: the game cuts a held note after about 6.5 s, so a longer note is split into re-presses.
The output is a Timeline: a list of (t_us, controller state) events, strictly increasing, below 2^31 µs, ending with a neutral END state, plus a CompileReport with the counts of played, too-short, re-pressed and dropped notes. The golden test plays all 19 pitches up and down, 37 notes at 90 bpm: 91 events, the last at 25 350 000 µs. Twelve of those 37 notes use non-chart fingerings with two modifiers. Their tuning is within about 11 cents on the measurements, but I haven't heard all of them on the console yet.
"This will end free play"
Here is a problem specific to this game. If the melody happens to contain the notes of one of the songs Link learns, the game recognises it and plays the song's effect, and that ends free play in the middle of my melody.
Story 5.6 adds the twelve official songs to the profile (not the Scarecrow's Song: the player composes that one). One is measured on the console; the other eleven come from a public reference and were cross-checked in review. Detection is a sliding window over the sounding pitches of what will actually be pressed:
for (i, window) in played.windows(n).enumerate() { if window.iter().map(|c| c.1).eq(song.pitches.iter().copied()) { hits.push((i, k, SongHit { title: song.title.clone(), notes: window.iter().map(|c| c.0).collect() })); } } app/core/src/pipeline/timing.rs, condensed.
It runs on presses, not notes, and that's a review finding. A note held for 7 seconds is split into two presses, and the game hears two notes. So a melody that holds one note long enough can turn into one of the official songs with no repeated note written in the score. The first version missed it.
The app only warns: Bonooru can't change the melody. A unit test also scans the app's source and fails if any song title appears in code. It found one: a title used as a typography sample in the design gallery.
Open, Roll, and a result that arrived too late
Stories 5.7 to 5.9 put all this on screen.
Open (5.7). Open…, Cmd/Ctrl+O or a drag and drop from the file manager. The file dialog is rfd with only the xdg-portal backend on Linux. Four public-domain examples are built in (Ode to Joy, Greensleeves, Frère Jacques, Twinkle Twinkle), and a test checks each one fits the range at 100 % with no too-short notes. Loading runs on a job thread, files are capped at 16 MiB, and MusicXML or ABC get "export it to MIDI".
The review found a race that came back in almost every GUI story after it:
The stale-result bug in Story 5.7. Without an id, the old song's late result overwrote the new one
The fix is a generation number. Every Open bumps it, every job carries the one it was asked with, and the UI throws away a result for an older generation (and logs stale=1). The same shape came back in 5.10 (a tempo edit during a track change), 5.11 (an old preview's events), 5.12 (settings saves) and 5.13 (profile writes). The retrospective turned it into a rule for Epic 6, which is built entirely out of results coming back from other threads.
The Roll (5.8) is a piano roll with the ocarina's 19 lanes, F6 at the top and B4 at the bottom. Each lane header shows the note and the fingering most of its presses use, like L+D↓+S↓, because Viterbi can pick different fingerings for the same pitch. Pan, zoom around the pointer, a ruler that sets the cursor. Only the bars in the window are drawn, found with a binary search (and a proptest checks that against a linear scan).
The frame time is measured over 600 frames of pan and zoom with 2,000 notes, UI pass plus tessellation, three runs on my Mac:
| Build | p50 | p95 | max |
|---|---|---|---|
| Debug (dry run) | 8.99 ms | ||
| Release, 5.8 | 0.23–0.24 ms | 0.48–0.50 ms | 0.81–0.83 ms |
| Release, 5.9 ghost-heavy case | 0.60–0.63 ms | 1.19 ms | 1.31–1.35 ms |
| Spike target from November | 1.5 ms |
Lesson: only release numbers count.
The fit proposal (5.9) shows what the range fit did. Notes that were out of range appear as dashed "ghosts" in zones above and below the lanes, with a dashed leader to the lane they were folded into. An official-song hit becomes an ember-coloured group with a tab: "Triggers Zelda's Lullaby". Dashed outlines are expensive: on a synthetic song where every third note is out of range, they became tens of thousands of segments and p95 went to 3.4 ms. Outlines narrower than 6 pt are now drawn plain, and leaders too close together are skipped: 1.19 ms.
My favourite finding there: the playhead line floated 6–30 pt below its handle, and the GUI test for it had been edited to expect the bug.
Transpose, tempo and the bench that found what tests can't
Story 5.10 adds the song panel controls: transpose by −12, −1, +1, +12 or Auto, tempo from 50 % to 150 % in 5 % steps or by typing a BPM, a fit summary ("N in range · N folded · N dropped") and the official-song warning. Every change is a SongEdit with an inverse, applied in one place: that is the seam for undo in Epic 9.
All the host tests were green. Then I ran the manual check (H.40) and saw the "BPM" caption sitting on top of the Reset button: on the 260 pt panel the tempo row needs about 266 pt and has 232. The fix moves the BPM field to its own row when it doesn't fit, and the GUI test now checks the overlap.
egui taught me a few things too: lost_focus() is true on two frames in a row, so the BPM commit ran twice; Esc in the field was STOP and committed the half-typed value; and Tab through the field changed the tempo, because 90 BPM at 55 % shows 50, and committing 50 gave 56 %.
Listen: an ocarina that isn't the game's
Story 5.11 is the one I'd been waiting for. Press Listen (or Space) and the song plays on the PC from the cursor, with the playhead moving along.
The sound can't be the game's: that's Nintendo's audio. So it's an original voice, synthesized from scratch in ocb_core::preview:
- a sine, plus a 2nd harmonic at 0.12 and a 3rd at 0.05;
- a 20 ms raised-cosine attack and a 40 ms release;
- vibrato as phase modulation, 5 Hz, ±0.25 %, starting after 150 ms and fading in over 250 ms;
- a breath noise at about −30 dB that fades out over the first 60 ms of each note.
// Vibrato as phase modulation, faded in after a delay. let depth = VIBRATO_DEPTH * ramp((tau - VIBRATO_DELAY_S) / VIBRATO_RAMP_S); let wobble = depth * voice.hz / VIBRATO_HZ * (TAU * VIBRATO_HZ * tau).sin(); let phase = TAU * voice.hz * tau + wobble; let tone = phase.sin() + H2 * (2.0 * phase).sin() + H3 * (3.0 * phase).sin(); let breath = BREATH * (1.0 - ramp(tau / BREATH_S)) * noise(voice.start ^ (k << 20)); GAIN * amp * (tone + breath) / (1.0 + H2 + H3) app/core/src/preview.rs. ramp is a raised cosine, 0.5 − 0.5·cos(πx).
Every sample is computed on its own from the time, with no running state, so playback starting from any cursor position is deterministic, and the noise is an integer hash of the note and the sample index rather than a random generator. The tones come from the compiled timeline, not from the score: dropped and too-short notes are silent, re-presses are audible. If it sounds wrong in the preview, it will be wrong on the Switch.
The audio output is rodio 0.23 (playback only, no decoders) on top of cpal, which uses ALSA on Linux. I didn't want ALSA anywhere near ocb-probe, the small diagnostic tool whose Linux binary is only allowed to link libudev and libc. So rodio lives in its own crate, ocb-audio, and nothing else depends on it. The output opens only on the first Listen, s...
