Files
ShoeGaze/docs/plans/2.2-tempo-synced-parameters.md
T
josh 2772abdc56 Release 2.1.0: tempo-synced pedal parameters, editable BPM, control mapping badges
Tempo sync
- Lock a delay time or modulation LFO rate to a note division (whole..sixteenth,
  dotted, triplet) of the shared clock. Value is derived from the tempo and follows
  tap tempo, the stepper, the editable BPM field, and MIDI.
- Delay time: Delay, FeedbackDelay, PingPong, ReverseDelay, MultiTap (per tap).
  LFO rate (inverse mapping): Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
- Core types NoteDivision / TempoSync / TempoSyncableParam; Pedal.tempoSyncableParams /
  tempoSync / applyTempoSync / setSync; ShoeGaze.setBpm broadcast recomputes all pedals;
  tempoSync persisted in PedalState (lenient decode) and recomputed on load + recall.
- Observable TempoSyncRevision so the sync badge refreshes on any state-change path.

UI
- Division picker with drawn music-notation glyphs (NoteGlyphView + rasterized cache):
  noteheads, stems, flags, augmentation dot, bracketed 3 for triplets. Presented as a
  height-capped popover so it stays on-screen on iOS.
- Editable BPM text field: integer-only, live-filtered, clamped 30-300, commit on
  return / Done / blur.
- Divisions that clamp at the current tempo are disabled in the picker; an active
  clamped sync shows a warning marker.
- In-context control mapping badges (PC / CC / KEY) per pedal control, with a legend.

Delays
- Maximum delay time raised to 5 s across the delay pedals (was 1-2 s).

Docs: CHANGELOG.md, RELEASES.md, docs/plans/2.2-tempo-synced-parameters.md.
All 454 tests pass; passed lyrebird_external_review (RT-safe, main-thread param writes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-10 08:47:22 -07:00

220 lines
8.7 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Tempo-synced pedal parameters
Let a time- or rate-based pedal parameter be locked to a **note division of the live
tempo** (quarter, dotted-eighth, eighth-triplet, …) instead of an absolute value. A delay
time set to "quarter note" tracks the shared clock; change BPM (stepper, tap, MIDI) and the
echo follows. Setting stays "free" (absolute seconds / Hz, as today) unless the user opts a
param into sync.
## Goals
- Any delay **time** param can be marked as a note division; its seconds are derived from
`clock.bpm`.
- Any modulation **rate** param (LFO Hz) can be marked as a note division; its frequency is
the inverse of the synced period (a "quarter-note" LFO = one cycle per quarter note).
- MultiTapDelay's three tap times each sync independently to their own division.
- Sync state travels with the rig (persists in `PedalState`), decoded leniently so older
rigs still load.
- Gated on the existing `tempoEnabled` flag — when tempo is off, sync affordances hide and
synced params fall back to their stored absolute value.
- macOS + iOS.
## Non-goals
- Sample-accurate tempo-ramp tracking (Option B, a clock-backed core Generator). BPM here
changes only at discrete events — stepper, tap, MIDI — so a recompute-on-change ("Push")
model loses nothing. The state format is designed so a Pull generator can back it later
without a migration.
- Syncing envelope- or expression-driven params (AutoWah, Mutant, Wah) — no fixed rate.
- Syncing Rotary `speed` — bimodal slow/fast horn, not a free rate.
- Auto-extending delay buffers to fit long divisions. Buffers are sized at init; a division
whose period exceeds a param's range is **clamped** to the range.
## Which params
**Time family** (synced value = period `T`):
| Pedal | param(s) |
|---|---|
| DelayPedal | `time` |
| FeedbackDelayPedal | `time` |
| PingPongDelayPedal | `time` |
| ReverseDelayPedal | `time` |
| MultiTapDelayPedal | `time1`, `time2`, `time3` |
**Rate family** (synced value = `1/T`, Hz):
| Pedal | param |
|---|---|
| TremoloPedal | `rate` |
| VibratoPedal | `rate` |
| ChorusPedal | `rate` |
| FlangerPedal | `rate` |
| PhaserPedal | `rate` |
| ModulationPedal | `rate` |
## Design
Approach: **Push / recompute-on-change**. When a param is synced, its `@UIParam` value is
recomputed and written whenever BPM or the chosen division changes. Generators are untouched
— they keep reading `$time` / `$rate` exactly as now. Writing a `@UIParam` from the main
thread is identical to a knob turn, so there is no RT concern.
Synced period, given beats-per-division `d` and tempo `bpm`:
```
T = (60 / bpm) * d // seconds
value = kind == .rate ? 1 / T : T
value = min(max(value, range.lowerBound), range.upperBound) // clamp
```
### Core types — new files in `Sources/LyrebirdShoeGaze/Tempo/`
One public type per file (repo rule).
`NoteDivision.swift`:
```swift
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
case whole, dottedHalf, half, dottedQuarter, quarter, quarterTriplet
case dottedEighth, eighth, eighthTriplet, sixteenth, sixteenthTriplet
/// Beats (quarter-note = 1) this division spans.
public var beats: Double { ... } // whole = 4, quarter = 1, eighth = 0.5,
// dottedEighth = 0.75, eighthTriplet = 1/3, ...
public var label: String { ... } // "1/4", "1/8.", "1/8T", ...
}
```
`TempoSync.swift`:
```swift
public enum TempoSync: Codable, Equatable, Sendable {
case free
case division(NoteDivision)
}
```
`TempoSyncableParam.swift` — descriptor a pedal publishes, one per syncable param:
```swift
public struct TempoSyncableParam {
public enum Kind { case time, rate } // rate ⇒ inverse (Hz = 1/T)
public let key: String // stable id, persistence key (e.g. "time", "time1")
public let label: String
public let node: UIParamNode
public let kind: Kind
public let range: ClosedRange<Double>
}
```
### `Pedal` base additions
```swift
/// Params this pedal exposes to tempo sync. Empty for pedals that can't sync.
open var tempoSyncableParams: [TempoSyncableParam] { [] }
/// Per-param sync state, keyed by TempoSyncableParam.key. Default .free.
public internal(set) var tempoSync: [String: TempoSync] = [:]
/// Recompute + write every synced param from the current clock BPM. Main-thread only.
public func applyTempoSync() { ... } // no-op when no clock, or tempo disabled
/// Set one param's sync state and immediately recompute it.
public func setSync(_ sync: TempoSync, for key: String) { ... }
```
`applyTempoSync()` iterates `tempoSyncableParams`, looks up each key's state, and for a
`.division` writes the clamped `T` (or `1/T`). `.free` leaves the param at its stored value.
Each candidate pedal overrides `tempoSyncableParams` — e.g. DelayPedal:
```swift
public override var tempoSyncableParams: [TempoSyncableParam] {
[TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange)]
}
```
### `ShoeGaze` broadcast — the Push trigger
BPM is currently mutated in three places that set `clock.bpm` directly (TempoView stepper,
`tapTempo()`, MIDI). Funnel them through one entry point:
```swift
public func setBpm(_ bpm: Double) {
clock.bpm = bpm
board.forEachPedal { $0.applyTempoSync() }
}
```
- `TempoView` stepper `set:` → `shoeGaze.setBpm(clamped)` (was `clock.bpm = clamped`).
- `tapTempo()` → compute then `setBpm(...)` (was `clock.bpm = ...`).
- MIDI tempo path → `setBpm`.
- Rig load (BPM restored from `ShoeGazeState`) → call `applyTempoSync()` across the board
after the clock is set, so restored synced params match the loaded tempo.
- `setTempoEnabled(false)` → params keep their last absolute value (no recompute); re-enable
→ `applyTempoSync()`.
(If `board.forEachPedal` doesn't exist, add a thin iterator over the board's pedals.)
### Persistence — `PedalState`
Add one field, decoded leniently (same pattern the tempo/BPM fields already use):
```swift
public let tempoSync: [String: TempoSync]? // param key → sync state; nil for old rigs
```
Custom `init(from:)` decodes with `decodeIfPresent`; absent ⇒ `nil` ⇒ all params `.free`.
`Pedal+Preset` captures `pedal.tempoSync` on save and restores it on load, then calls
`applyTempoSync()` so values line up with the rig's restored BPM.
### UI — `PedalView`
For each param that appears in `tempoSyncableParams`:
- Show a small **Sync** toggle beside/under the knob.
- Sync **off** → render the existing `PedalKnob` rotary, unchanged.
- Sync **on** → replace the rotary with a `PedalSelectorKnob` (already exists: a knob that
snaps to labelled stops) bound to the `NoteDivision` list; changing it calls
`pedal.setSync(.division(sel), for: key)`.
- Gate the whole affordance on the `shoeGazeTempoEnabled` environment flag — when tempo is
off, only the plain knob shows.
### MIDI — deferred
A synced param's value is derived, so a CC bound to it is overwritten on the next tempo/division
change. The obvious fix — dropping `.division`-synced params from `ccMappableControls` — is
**deferred**: that list is addressed by a *stable index* (persisted CC bindings resolve by position),
so filtering it live would shift indices and silently re-point or break existing bindings. A correct
implementation needs an index-stable exclusion (e.g. keep the slot but mark it inert while synced),
which is out of scope for this change. Until then, binding a CC to a synced param is allowed but the
tempo wins — documented here as a known limitation, not an oversight.
## Testing
One `@Suite` per file (repo rule):
- `NoteDivisionTests` — `beats` values (whole = 4, quarter = 1, dottedEighth = 0.75,
eighthTriplet ≈ 0.3333, …) and `label`s.
- `TempoSyncTests` — `applyTempoSync` for a `.time` param (period), a `.rate` param
(inverse), and range-clamp (whole note @ 60 BPM = 4 s clamps to Delay's 1.5 s max).
- `ShoeGazeTempoBroadcastTests` — `setBpm` recomputes a synced param across the board;
changing division recomputes; `.free` params untouched.
- `PedalStatePersistenceTests` (extend existing) — `tempoSync` round-trips; a rig saved
without the field decodes to all-`.free`.
## Build order
Vertical slice first to validate the whole path end to end, then fan out:
1. Core types (`NoteDivision`, `TempoSync`, `TempoSyncableParam`).
2. `Pedal` hooks (`tempoSyncableParams`, `tempoSync`, `applyTempoSync`, `setSync`).
3. `ShoeGaze.setBpm` broadcast + reroute the three BPM writers + rig-load hook.
4. **DelayPedal** override + its `PedalView` sync UI.
5. Tests for 1–4.
6. Persistence (`PedalState.tempoSync`, `Pedal+Preset`).
7. Fan out to the remaining delays, then the modulation (rate) pedals, then MultiTap's
three taps.
8. `lyrebird_external_review` (ShoeGaze is out-of-tree) before merge.