Compare commits
22 Commits
2.0.0
...
ed3283f645
| Author | SHA1 | Date | |
|---|---|---|---|
| ed3283f645 | |||
| 8983e8829e | |||
| e697789bd7 | |||
| 09fa4e8d4b | |||
| 37777826d1 | |||
| a1a7683bc9 | |||
| 3d67c7b450 | |||
| 551b650d45 | |||
| 7720fbec7b | |||
| 3228614071 | |||
| e207728a12 | |||
| e36074e9d3 | |||
| b29c8848ef | |||
| be0e3d118b | |||
| 5542ee5b5a | |||
| b0294612f8 | |||
| cc3a986cde | |||
| 5987ec7b78 | |||
| f61961b90b | |||
| 7e39842eb2 | |||
| 2772abdc56 | |||
| a33d5488c9 |
@@ -4,6 +4,97 @@ All notable changes to ShoeGaze are recorded here. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
||||
[semantic versioning](https://semver.org/spec/v2.0.0.html).
|
||||
|
||||
## [2.1.3] — 2026-07-13
|
||||
|
||||
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output —
|
||||
even with "Mute while tuning" on — until a steady note was detected.
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Tuner no longer leaks into the audio output.** The tuner's pitch-detection stage
|
||||
was mistakenly written to an audio output bus instead of its internal analysis bus,
|
||||
so the tracked frequency was summed onto an output channel — bypassing the rig mute
|
||||
and crackling while the pitch was still unstable (it stopped once a note locked). The
|
||||
tuner now writes only to its analysis bus; engaging it leaves the output untouched.
|
||||
|
||||
## [2.1.1] — 2026-07-12
|
||||
|
||||
A quieter, more predictable startup. The input feeding the pedals now has its own
|
||||
mute — separate from the rig-output mute — that arms every time you start the engine,
|
||||
so nothing squeals the instant it spins up. New rigs open listening to In 0 instead of
|
||||
the test-loop phrase, and your input choice and I/O channel counts now travel with the
|
||||
rig (and iCloud) instead of a separate local setting.
|
||||
|
||||
### Added
|
||||
|
||||
- **Input mute.** A hard kill-switch on the incoming guitar / mic signal, distinct from
|
||||
the rig-output mute. It arms automatically every time you press Start (so a fresh
|
||||
engine is silent until you're ready), sits next to the Start/Stop transport with a
|
||||
pulsing red glow while active, and is MIDI-mappable (footswitch or key), like Rig Mute.
|
||||
|
||||
### Changed
|
||||
|
||||
- **New rigs open on In 0** (live input) instead of the built-in test-loop phrase.
|
||||
- **Input & I/O persist with the rig.** The input selection and the engine's input /
|
||||
output channel counts are stored in the rig (and sync via iCloud), and are reapplied
|
||||
on launch — so a multi-channel setup and a chosen input channel survive a restart
|
||||
instead of reverting to the defaults. Replaces the previous local-only input setting.
|
||||
- The docked (macOS) transport shows the Bypass / Mute / Input toggles as icons so the
|
||||
row no longer crowds the sample-rate and channel controls.
|
||||
|
||||
### Fixed
|
||||
|
||||
- A muted input is now **exactly** silent from the first sample — no brief start-up
|
||||
transient when the engine begins rendering.
|
||||
- iOS: the app declares in-place document support, clearing a launch-time console warning.
|
||||
|
||||
### Compatibility
|
||||
|
||||
Additive: rigs saved before this release load unchanged (input defaults to In 0, or the
|
||||
test loop when no live input is available), and 2.1.1 rigs still open in older builds —
|
||||
the input-mute state isn't persisted and the extra I/O fields are ignored there.
|
||||
|
||||
## [2.1.0] — 2026-07-10
|
||||
|
||||
Tempo comes to the pedals. Delay times and modulation rates can lock to a note
|
||||
division of the live tempo — a quarter-note delay, a dotted-eighth, an eighth-triplet
|
||||
LFO — shown with real music-notation glyphs and following the tempo as it changes.
|
||||
Delays reach further, the BPM is directly editable, and every mappable control shows
|
||||
its MIDI / key binding right on the pedal.
|
||||
|
||||
### Added
|
||||
|
||||
- **Tempo-synced pedal parameters.** Lock a delay time or a modulation rate to a note
|
||||
division — whole down to sixteenth, including dotted and triplet values — and it is
|
||||
derived from the shared tempo, following tap tempo, the stepper, the BPM field, and
|
||||
MIDI. Delay time on Delay, Feedback Delay, Ping-Pong, Reverse Delay, and each of
|
||||
Multi-Tap's three taps; LFO rate on Tremolo, Vibrato, Chorus, Flanger, Phaser, and
|
||||
Modulation. A MIDI CC bound to a synced parameter is ignored while it stays synced
|
||||
(the tempo drives the value) and resumes control once the parameter is set to Free.
|
||||
- **Note-value glyphs.** The division picker uses drawn music-notation glyphs —
|
||||
noteheads, stems, flags, an augmentation dot for dotted values, and a bracketed "3"
|
||||
over triplets — instead of text labels.
|
||||
- **Editable BPM.** The tempo readout is now a text field: type a tempo directly
|
||||
(integer only, clamped to 30–300 BPM). The stepper and tap tempo still work, and a
|
||||
synced pedal follows a typed change immediately.
|
||||
- **In-context control mapping.** Each pedal draws a small badge on every mappable
|
||||
control showing its binding source — Program Change footswitch (PC), Control Change
|
||||
expression (CC), or letter Key (KEY) — with a legend above the board. Completes the
|
||||
computer-keyboard control mapping.
|
||||
|
||||
### Changed
|
||||
|
||||
- **Longer delays.** Maximum delay time raised to 5 seconds across the delay pedals
|
||||
(previously 1–2 s), so tempo-synced values at slow tempos (whole and half notes) fit.
|
||||
- Note divisions that would exceed a parameter's range at the current tempo are shown
|
||||
disabled in the picker, and an active sync that has to clamp shows a warning marker.
|
||||
|
||||
### Compatibility
|
||||
|
||||
Additive: rigs saved before this release load unchanged (every parameter defaults to
|
||||
"free"), and 2.1 rigs still open in older builds — the tempo-sync state is simply
|
||||
ignored there.
|
||||
|
||||
## [2.0.0] — 2026-07-05
|
||||
|
||||
Major release. Performance-focused: a visual metronome, a real rig mute with
|
||||
|
||||
@@ -100,7 +100,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2620;
|
||||
LastUpgradeCheck = 2660;
|
||||
TargetAttributes = {
|
||||
C3B100000000000000000014 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -163,10 +163,9 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 8;
|
||||
CURRENT_PROJECT_VERSION = 14;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||
@@ -176,7 +175,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 2.0.0;
|
||||
MARKETING_VERSION = 2.1.6;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -194,9 +193,8 @@
|
||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 8;
|
||||
CURRENT_PROJECT_VERSION = 14;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||
@@ -206,7 +204,7 @@
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
MARKETING_VERSION = 2.0.0;
|
||||
MARKETING_VERSION = 2.1.6;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
@@ -249,6 +247,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -311,6 +310,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
|
||||
"version" : "1.2.0"
|
||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
||||
"version" : "1.2.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
LastUpgradeVersion = "2660"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
@@ -95,6 +95,8 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
|
||||
override init() {
|
||||
let coreDriver: CoreAudioDriver = CoreAudioDriver()
|
||||
// The engine is built with the default layout; the autosaved rig's saved I/O layout (if any)
|
||||
// is applied by `RigStore.restore` below, so a multi-channel setup survives relaunch.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: AppDelegate.blockSize,
|
||||
sampleRate: AppDelegate.sampleRate,
|
||||
@@ -127,6 +129,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
|
||||
|
||||
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
|
||||
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
|
||||
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio,
|
||||
// so the app comes up listening to the instrument. A restored rig keeps its own saved input.
|
||||
if shoeGaze.engine.numInputChannels > 0 {
|
||||
shoeGaze.inputSource = .liveInput(channel: 0)
|
||||
}
|
||||
var created: PedalBoard?
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
|
||||
|
Before Width: | Height: | Size: 25 KiB After Width: | Height: | Size: 18 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 782 B After Width: | Height: | Size: 2.0 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 91 KiB After Width: | Height: | Size: 55 KiB |
|
Before Width: | Height: | Size: 345 KiB After Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 2.0 KiB After Width: | Height: | Size: 3.0 KiB |
|
Before Width: | Height: | Size: 6.9 KiB After Width: | Height: | Size: 6.6 KiB |
|
Before Width: | Height: | Size: 345 KiB After Width: | Height: | Size: 200 KiB |
|
Before Width: | Height: | Size: 1.2 MiB After Width: | Height: | Size: 643 KiB |
@@ -28,9 +28,9 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>2.0.0</string>
|
||||
<string>${MARKETING_VERSION}</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>7</string>
|
||||
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||
<key>LSApplicationCategoryType</key>
|
||||
<string>public.app-category.music</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
C3C10000000000000000000D /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001C /* LyrebirdUI */; };
|
||||
C3C10000000000000000001D /* Lyrebird in Frameworks */ = {isa = PBXBuildFile; productRef = C3C10000000000000000001E /* Lyrebird */; };
|
||||
C3C100000000000000000031 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C3C100000000000000000030 /* Assets.xcassets */; };
|
||||
C3C1000000000000000000B1 /* SplashView.swift in Sources */ = {isa = PBXBuildFile; fileRef = C3C1000000000000000000B0 /* SplashView.swift */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
@@ -22,6 +23,7 @@
|
||||
C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSApp.swift; sourceTree = "<group>"; };
|
||||
C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ShoeGazeBuilderiOSAppModel.swift; sourceTree = "<group>"; };
|
||||
C3C100000000000000000030 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
C3C1000000000000000000B0 /* SplashView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = SplashView.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
@@ -60,6 +62,7 @@
|
||||
children = (
|
||||
C3C100000000000000000007 /* ShoeGazeBuilderiOSApp.swift */,
|
||||
C3C100000000000000000008 /* ShoeGazeBuilderiOSAppModel.swift */,
|
||||
C3C1000000000000000000B0 /* SplashView.swift */,
|
||||
C3C100000000000000000030 /* Assets.xcassets */,
|
||||
C3C100000000000000000006 /* Info.plist */,
|
||||
);
|
||||
@@ -100,7 +103,7 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2620;
|
||||
LastUpgradeCheck = 2660;
|
||||
TargetAttributes = {
|
||||
C3C100000000000000000011 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
@@ -147,6 +150,7 @@
|
||||
files = (
|
||||
C3C100000000000000000009 /* ShoeGazeBuilderiOSApp.swift in Sources */,
|
||||
C3C10000000000000000000A /* ShoeGazeBuilderiOSAppModel.swift in Sources */,
|
||||
C3C1000000000000000000B1 /* SplashView.swift in Sources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
@@ -163,7 +167,6 @@
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
||||
@@ -192,7 +195,6 @@
|
||||
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
CURRENT_PROJECT_VERSION = 7;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
||||
@@ -246,6 +248,7 @@
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -308,6 +311,7 @@
|
||||
CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "032b7c39d351eba4029e8399e1ab1ee201e8bb5c",
|
||||
"version" : "1.2.0"
|
||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
||||
"version" : "1.2.3"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "2620"
|
||||
LastUpgradeVersion = "2660"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
|
||||
|
Before Width: | Height: | Size: 402 KiB After Width: | Height: | Size: 643 KiB |
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"colors" : [
|
||||
{
|
||||
"idiom" : "universal",
|
||||
"color" : {
|
||||
"color-space" : "srgb",
|
||||
"components" : { "red" : "0.080", "green" : "0.070", "blue" : "0.060", "alpha" : "1.000" }
|
||||
}
|
||||
}
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "idiom" : "universal", "filename" : "splashlogo.png", "scale" : "1x" },
|
||||
{ "idiom" : "universal", "filename" : "splashlogo@2x.png", "scale" : "2x" },
|
||||
{ "idiom" : "universal", "filename" : "splashlogo@3x.png", "scale" : "3x" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
After Width: | Height: | Size: 57 KiB |
|
After Width: | Height: | Size: 208 KiB |
|
After Width: | Height: | Size: 420 KiB |
@@ -17,6 +17,10 @@
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
<!-- Incoming .shoegaze files are read and imported into the rig library (a copy), never
|
||||
edited in place, so the app opens a copy rather than the original document. -->
|
||||
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||
<false/>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
@@ -55,7 +59,10 @@
|
||||
<false/>
|
||||
</dict>
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
<dict>
|
||||
<key>UIColorName</key>
|
||||
<string>LaunchBackground</string>
|
||||
</dict>
|
||||
<key>UIRequiresFullScreen</key>
|
||||
<true/>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
|
||||
@@ -20,21 +20,30 @@ import LyrebirdShoeGazeUI
|
||||
struct ShoeGazeBuilderiOSApp: App {
|
||||
|
||||
@State private var model: ShoeGazeBuilderiOSAppModel = ShoeGazeBuilderiOSAppModel()
|
||||
@State private var showSplash: Bool = true
|
||||
@Environment(\.scenePhase) private var scenePhase
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: model.shoeGaze,
|
||||
library: model.library,
|
||||
hardwareSampleRate: { model.hardwareSampleRate },
|
||||
onEnableLiveInput: { model.enableLiveInput() },
|
||||
midi: model.midi
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.task { await model.startLibrary() }
|
||||
.onDisappear { model.stop() }
|
||||
.onOpenURL { url in model.importDocument(at: url) }
|
||||
ZStack {
|
||||
ShoeGazeBuilderView(
|
||||
shoeGaze: model.shoeGaze,
|
||||
library: model.library,
|
||||
hardwareSampleRate: { model.hardwareSampleRate },
|
||||
onEnableLiveInput: { model.enableLiveInput() },
|
||||
midi: model.midi
|
||||
)
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.task { await model.startLibrary() }
|
||||
.onDisappear { model.stop() }
|
||||
.onOpenURL { url in model.importDocument(at: url) }
|
||||
|
||||
if showSplash {
|
||||
SplashView(isActive: $showSplash)
|
||||
.transition(.opacity)
|
||||
.zIndex(1)
|
||||
}
|
||||
}
|
||||
}
|
||||
.onChange(of: scenePhase) { _, phase in
|
||||
// Persist the rig whenever the app leaves the foreground.
|
||||
|
||||
@@ -34,12 +34,6 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
private static let numAudioBuses: Int = 256
|
||||
private static let seedPedalType: PedalType = .overdrive
|
||||
|
||||
/// UserDefaults key persisting the input selection. Must match the key written by the
|
||||
/// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`).
|
||||
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
|
||||
/// Persisted value meaning "live input, channel 0".
|
||||
private static let liveInputChannelZeroTag: Int = 0
|
||||
|
||||
// MARK: - Owned objects
|
||||
|
||||
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
|
||||
@@ -144,6 +138,8 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
|
||||
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
|
||||
let driver: iOSAudioDriver = iOSAudioDriver()
|
||||
// The engine is built with the default layout; the autosaved rig's saved I/O (if any) is
|
||||
// applied by `RigStore.restore`, so an output change survives relaunch.
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
|
||||
sampleRate: sampleRate,
|
||||
@@ -222,14 +218,12 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
if wasRunning { try? engine.start() }
|
||||
}
|
||||
|
||||
/// Selects live input on channel 0 and persists the choice for restore-on-relaunch.
|
||||
/// Selects live input on channel 0 and autosaves so the rig (the source of truth for the input
|
||||
/// selection) records it for restore-on-relaunch.
|
||||
private func selectLiveInputAndPersist() {
|
||||
do {
|
||||
try shoeGaze.setInputSource(.liveInput(channel: 0))
|
||||
UserDefaults.standard.set(
|
||||
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
|
||||
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
|
||||
)
|
||||
save()
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
|
||||
}
|
||||
@@ -237,6 +231,11 @@ final class ShoeGazeBuilderiOSAppModel {
|
||||
|
||||
/// Seeds a single default board so the rig is never empty after a failed restore.
|
||||
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
|
||||
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio.
|
||||
// A restored rig keeps its own saved input selection.
|
||||
if shoeGaze.engine.numInputChannels > 0 {
|
||||
shoeGaze.inputSource = .liveInput(channel: 0)
|
||||
}
|
||||
do {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
board.label = "Board 1"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
// SplashView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
|
||||
/// Animated launch splash shown over the app on cold start.
|
||||
///
|
||||
/// The native launch screen (`UILaunchScreen` → `LaunchBackground`) paints an instant dark
|
||||
/// backdrop with no visible jump; this view then fades and scales the ShoeGaze pedal logo in,
|
||||
/// holds briefly, and fades the whole overlay away to reveal ``ShoeGazeBuilderView``. Colors match
|
||||
/// the app background so the hand-off is seamless. Respects Reduce Motion by skipping the scale.
|
||||
struct SplashView: View {
|
||||
|
||||
/// Background matching the builder's app background (`0.08, 0.07, 0.06`).
|
||||
private static let backgroundColor: Color = Color(red: 0.08, green: 0.07, blue: 0.06)
|
||||
|
||||
private static let logoSize: CGFloat = 200
|
||||
private static let logoCornerRadius: CGFloat = 44
|
||||
private static let logoStartScale: CGFloat = 0.86
|
||||
private static let wordmarkKerning: CGFloat = 4
|
||||
|
||||
private static let logoFadeInDuration: Double = 0.55
|
||||
private static let wordmarkFadeInDelay: Double = 0.30
|
||||
private static let wordmarkFadeInDuration: Double = 0.45
|
||||
private static let holdDuration: Double = 0.85
|
||||
private static let fadeOutDuration: Double = 0.45
|
||||
|
||||
@Environment(\.accessibilityReduceMotion) private var reduceMotion
|
||||
|
||||
/// Set false to fade the overlay out; parent removes it when the fade completes.
|
||||
@Binding var isActive: Bool
|
||||
|
||||
@State private var logoOpacity: Double = 0
|
||||
@State private var logoScale: CGFloat = SplashView.logoStartScale
|
||||
@State private var wordmarkOpacity: Double = 0
|
||||
|
||||
var body: some View {
|
||||
ZStack {
|
||||
SplashView.backgroundColor
|
||||
.ignoresSafeArea()
|
||||
|
||||
VStack(spacing: 22) {
|
||||
Image("SplashLogo")
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(width: SplashView.logoSize, height: SplashView.logoSize)
|
||||
.clipShape(RoundedRectangle(cornerRadius: SplashView.logoCornerRadius,
|
||||
style: .continuous))
|
||||
.opacity(logoOpacity)
|
||||
.scaleEffect(logoScale)
|
||||
|
||||
Text("ShoeGaze")
|
||||
.font(.system(size: 34, weight: .semibold, design: .rounded))
|
||||
.kerning(SplashView.wordmarkKerning)
|
||||
.foregroundStyle(.white)
|
||||
.opacity(wordmarkOpacity)
|
||||
}
|
||||
}
|
||||
.onAppear { runSequence() }
|
||||
}
|
||||
|
||||
private func runSequence() {
|
||||
withAnimation(.easeOut(duration: SplashView.logoFadeInDuration)) {
|
||||
logoOpacity = 1
|
||||
if !reduceMotion { logoScale = 1 }
|
||||
}
|
||||
withAnimation(.easeOut(duration: SplashView.wordmarkFadeInDuration)
|
||||
.delay(SplashView.wordmarkFadeInDelay)) {
|
||||
wordmarkOpacity = 1
|
||||
}
|
||||
|
||||
let holdUntil: Double = SplashView.logoFadeInDuration + SplashView.holdDuration
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + holdUntil) {
|
||||
withAnimation(.easeIn(duration: SplashView.fadeOutDuration)) {
|
||||
isActive = false
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "8bbfcc5441e68d57cefd08aed960cbac3875af1e0f8b1d2d3fbdd4dadc0ac18c",
|
||||
"originHash" : "9365abc9e3bf41483a03dca1c6be0421a5ca41bff1a9db33c8ddc62b2de04ef1",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
||||
"version" : "1.2.3"
|
||||
"revision" : "d6875da2cb6628c4274454dd55a632dd76212759",
|
||||
"version" : "1.6.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -24,7 +24,7 @@ let package = Package(
|
||||
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
||||
],
|
||||
dependencies: [
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.2.3"),
|
||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.6.4"),
|
||||
],
|
||||
targets: [
|
||||
// The core target depends on LyrebirdUI as well as the synthesis core:
|
||||
|
||||
@@ -1,4 +1,64 @@
|
||||
# Releases
|
||||
## ShoeGaze 2.1.3
|
||||
|
||||
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even
|
||||
with "Mute while tuning" on — until you played a steady note.
|
||||
|
||||
### Fixed
|
||||
- **Tuner no longer leaks into the output.** The pitch-detection stage was written to an
|
||||
audio output bus instead of its internal analysis bus, so the tracked frequency was
|
||||
summed onto an output channel — bypassing the rig mute and crackling while the pitch was
|
||||
unstable (it stopped once a note locked). The tuner now writes only to its analysis bus.
|
||||
|
||||
## ShoeGaze 2.1.1
|
||||
|
||||
A quieter, more predictable startup. The signal feeding the pedals now has its own mute
|
||||
that arms every time you start the engine, new rigs open listening to your instrument,
|
||||
and your input and I/O settings travel with the rig instead of a local-only setting.
|
||||
|
||||
### Highlights
|
||||
- **Input mute** — a hard kill-switch on the incoming guitar / mic signal, separate from
|
||||
the rig-output mute. Arms automatically on every Start (silent until you're ready),
|
||||
sits by the Start/Stop transport with a pulsing red glow while active, and is
|
||||
MIDI-mappable like Rig Mute. A muted input is exactly silent from the first sample.
|
||||
- **Opens on In 0** — new rigs listen to live input instead of the test-loop phrase.
|
||||
- **Input & I/O persist with the rig** — the input selection and engine input/output
|
||||
channel counts are stored in the rig (and iCloud) and reapplied on launch, so a
|
||||
multi-channel setup and a chosen input survive a restart. Replaces the old local-only
|
||||
input setting.
|
||||
- **Tidier transport** — the docked macOS Bypass / Mute / Input toggles are icons so the
|
||||
row no longer crowds the rate and channel controls.
|
||||
|
||||
### Compatibility
|
||||
Additive: rigs saved before this release load unchanged, and 2.1.1 rigs still open in
|
||||
older builds (input-mute state isn't persisted; the extra I/O fields are ignored there).
|
||||
|
||||
## ShoeGaze 2.1.0
|
||||
|
||||
Tempo comes to the pedals. Delay times and LFO rates can lock to note divisions of the
|
||||
live tempo — shown with real music-notation glyphs and following the tempo as it
|
||||
changes — plus a directly-editable BPM, longer delays, and per-control MIDI/key mapping
|
||||
badges on every pedal.
|
||||
|
||||
### Highlights
|
||||
- **Tempo-synced parameters** — lock a delay time or a modulation rate to a note value
|
||||
(whole → sixteenth, dotted, triplet); it follows tap tempo, the stepper, the BPM
|
||||
field, and MIDI. Delay, Feedback Delay, Ping-Pong, Reverse, and Multi-Tap (per tap);
|
||||
Tremolo, Vibrato, Chorus, Flanger, Phaser, Modulation.
|
||||
- **Notation glyphs** — the picker draws real note glyphs (augmentation dot for dotted
|
||||
values, a bracketed "3" over triplets) instead of text.
|
||||
- **Editable BPM** — type a tempo directly (integer, 30–300); the stepper and tap still
|
||||
work, and synced pedals follow immediately.
|
||||
- **Longer delays** — maximum delay time raised to 5 s so slow synced values fit.
|
||||
- **Control mapping badges** — every pedal shows the PC (footswitch), CC (expression),
|
||||
or KEY (letter key) binding on each control, with a legend above the board.
|
||||
- **CC respects tempo sync** — a CC bound to a synced parameter is ignored while synced
|
||||
(the tempo drives it) and resumes control once the parameter is set back to Free.
|
||||
|
||||
### Compatibility
|
||||
Additive persistence — older rigs load unchanged (every parameter defaults to free),
|
||||
and 2.1 rigs open in older builds with the tempo-sync state ignored.
|
||||
|
||||
## ShoeGaze 2.0.0
|
||||
|
||||
Major release. Performance-focused: a visual metronome, a real rig mute with
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"originHash" : "39c6a5f1535f779ef8a83b5ea2ab6f965ee3b28ad8419b94679e422a92f75603",
|
||||
"originHash" : "6963980dd14bc118dfae577e57517f2776cb0d010d7b4ae798bdb57e4f0d2cb7",
|
||||
"pins" : [
|
||||
{
|
||||
"identity" : "linenoise-swift",
|
||||
@@ -15,8 +15,8 @@
|
||||
"kind" : "remoteSourceControl",
|
||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||
"state" : {
|
||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
||||
"version" : "1.2.3"
|
||||
"revision" : "d6875da2cb6628c4274454dd55a632dd76212759",
|
||||
"version" : "1.6.4"
|
||||
}
|
||||
},
|
||||
{
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
// OversampledRingModulator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import Darwin
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
|
||||
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let oversampledRingModZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// Ring modulator (`input × sine carrier`) evaluated at 2× or 4× the engine sample rate.
|
||||
///
|
||||
/// A ring modulator's product produces sum-and-difference sidebands at `f_in ± f_carrier`. The
|
||||
/// sum sideband can land above the engine Nyquist and fold back as an inharmonic alias —
|
||||
/// worst with a high carrier and bright input. Evaluating the multiply at an oversampled rate
|
||||
/// (the input upsampled through a halfband FIR, the carrier generated directly at the
|
||||
/// oversampled rate) pushes the sum term below the upsampled Nyquist, then the matching
|
||||
/// downsampler filters it out before returning to the engine rate.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to modulate.
|
||||
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public final class OversampledRingModulator: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal (classified once at `init`, never on the RT thread).
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
|
||||
/// Resolved carrier-frequency control. Read once per block.
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
|
||||
/// Oversampling factor — `2` or `4`, fixed at init.
|
||||
private let oversampleFactor: Int
|
||||
|
||||
/// Carrier phase in radians, advanced at the oversampled rate and wrapped to `[0, 2π)`.
|
||||
private var phase: Double = 0.0
|
||||
|
||||
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
|
||||
private var upsampler2x: HalfbandUpsampler2x
|
||||
private var downsampler2x: HalfbandDownsampler2x
|
||||
|
||||
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
|
||||
private var upsampler4x: HalfbandUpsampler4x
|
||||
private var downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
private let twoPi: Double = 2.0 * Double.pi
|
||||
|
||||
/// Creates an oversampled ring modulator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to modulate.
|
||||
/// - freq: Carrier frequency in Hz. Read once per block. Defaults to `220.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public init(
|
||||
_ input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput = 220.0,
|
||||
oversample: Int = 2
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"OversampledRingModulator: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedFreq: any ValidGeneratorInput = freq._resolvedInput()
|
||||
inputSource = resolvedInput
|
||||
freqInput = resolvedFreq
|
||||
oversampleFactor = oversample
|
||||
upsampler2x = HalfbandUpsampler2x()
|
||||
downsampler2x = HalfbandDownsampler2x()
|
||||
upsampler4x = HalfbandUpsampler4x()
|
||||
downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
?? oversampledRingModZeroBlock
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
// A degenerate sample rate would make phaseInc NaN/Inf and latch NaN into the
|
||||
// persisted phase; zero-fill and bail, matching MoogLadder's guard.
|
||||
guard sr >= 1.0 else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
let freq: Double = freqInput.floatValue(graph: graph)
|
||||
let inCount: Int = input.count
|
||||
let useFourX: Bool = oversampleFactor == 4
|
||||
// Phase increment per oversampled sample.
|
||||
let factor: Double = useFourX ? 4.0 : 2.0
|
||||
let phaseInc: Double = twoPi * freq / (sr * factor)
|
||||
|
||||
var localPhase: Double = phase
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if useFourX {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b, c, d) = upsampler4x.process(x)
|
||||
let ya: Double = a * sin(localPhase); localPhase += phaseInc
|
||||
let yb: Double = b * sin(localPhase); localPhase += phaseInc
|
||||
let yc: Double = c * sin(localPhase); localPhase += phaseInc
|
||||
let yd: Double = d * sin(localPhase); localPhase += phaseInc
|
||||
// Wrap both directions — a negative carrier frequency drives phaseInc
|
||||
// negative, so an upward-only wrap would let the phase grow unbounded.
|
||||
if localPhase >= twoPi || localPhase < 0 {
|
||||
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
|
||||
if localPhase < 0 { localPhase += twoPi }
|
||||
}
|
||||
dstP[i] = downsampler4x.process(ya, yb, yc, yd)
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b) = upsampler2x.process(x)
|
||||
let ya: Double = a * sin(localPhase); localPhase += phaseInc
|
||||
let yb: Double = b * sin(localPhase); localPhase += phaseInc
|
||||
// Wrap both directions (see 4× branch).
|
||||
if localPhase >= twoPi || localPhase < 0 {
|
||||
localPhase = localPhase.truncatingRemainder(dividingBy: twoPi)
|
||||
if localPhase < 0 { localPhase += twoPi }
|
||||
}
|
||||
dstP[i] = downsampler2x.process(ya, yb)
|
||||
}
|
||||
}
|
||||
}
|
||||
phase = localPhase
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// OversampledSaturator.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Shared zero-fill fallback block, allocated once at module load. Returned when an upstream
|
||||
/// input yields no channel for a `_computeSamples` call, so the RT path never allocates.
|
||||
private let oversampledSaturatorZeroBlock: [Double] = makeSampleBuffer()
|
||||
|
||||
/// A waveshaping saturator that evaluates its nonlinearity at 2× or 4× the engine sample
|
||||
/// rate to keep the harmonics it generates from folding back into the audible band as
|
||||
/// aliasing.
|
||||
///
|
||||
/// A hard or steep nonlinearity (`tanh` driven hard, a hard clipper) produces harmonics well
|
||||
/// above the engine Nyquist. Evaluated at the base rate those harmonics alias — an
|
||||
/// inharmonic, buzzy "crackle" that gets worse the louder and brighter the input and the
|
||||
/// harder the drive. This generator upsamples the input, applies the ``SaturationCurve``
|
||||
/// per oversampled sample, then downsamples with the matching halfband FIR, so the aliased
|
||||
/// content is filtered out before returning to the engine rate.
|
||||
///
|
||||
/// Linear stages (DC-block high-pass, tone low-pass, output trim) do **not** alias and should
|
||||
/// stay as ordinary graph nodes around this one — only the nonlinearity needs oversampling.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to saturate.
|
||||
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
|
||||
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Use `4` for hard-clipping curves whose
|
||||
/// harmonics extend furthest; `2` is enough for `tanh`-family soft saturation. Defaults to `2`.
|
||||
public final class OversampledSaturator: GeneratorBase, AudioGenerator {
|
||||
|
||||
/// Resolved input signal (classified once at `init`, never on the RT thread).
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
|
||||
/// Resolved drive control. Read once per block.
|
||||
private let driveInput: any ValidGeneratorInput
|
||||
|
||||
/// The waveshaping curve applied per oversampled sample.
|
||||
private let curve: SaturationCurve
|
||||
|
||||
/// Oversampling factor — `2` or `4`, fixed at init.
|
||||
private let oversampleFactor: Int
|
||||
|
||||
/// Lower bound on drive so `softClipNormalized`'s `tanh(drive)` denominator is never zero.
|
||||
private let minDrive: Double = 1.0e-4
|
||||
|
||||
/// 2× halfband oversampling state (used when `oversampleFactor == 2`).
|
||||
private var upsampler2x: HalfbandUpsampler2x
|
||||
private var downsampler2x: HalfbandDownsampler2x
|
||||
|
||||
/// 4× halfband oversampling state (used when `oversampleFactor == 4`).
|
||||
private var upsampler4x: HalfbandUpsampler4x
|
||||
private var downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
/// Creates an oversampled saturator.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to saturate.
|
||||
/// - drive: Drive amount fed to the curve. Clamped to a small positive floor. Defaults to `1.0`.
|
||||
/// - curve: The ``SaturationCurve`` to apply per oversampled sample.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `2`.
|
||||
public init(
|
||||
_ input: any ValidGeneratorInput,
|
||||
drive: any ValidGeneratorInput = 1.0,
|
||||
curve: SaturationCurve,
|
||||
oversample: Int = 2
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"OversampledSaturator: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput()
|
||||
inputSource = resolvedInput
|
||||
driveInput = resolvedDrive
|
||||
self.curve = curve
|
||||
oversampleFactor = oversample
|
||||
upsampler2x = HalfbandUpsampler2x()
|
||||
downsampler2x = HalfbandDownsampler2x()
|
||||
upsampler4x = HalfbandUpsampler4x()
|
||||
downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let input: [Double] = inputSource.calculatedSamples(graph: graph, count: count).first
|
||||
?? oversampledSaturatorZeroBlock
|
||||
let driveRaw: Double = driveInput.floatValue(graph: graph)
|
||||
let drive: Double = Swift.max(minDrive, driveRaw)
|
||||
let inCount: Int = input.count
|
||||
let useFourX: Bool = oversampleFactor == 4
|
||||
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
if useFourX {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b, c, d) = upsampler4x.process(x)
|
||||
dstP[i] = downsampler4x.process(
|
||||
curve.apply(a, drive: drive),
|
||||
curve.apply(b, drive: drive),
|
||||
curve.apply(c, drive: drive),
|
||||
curve.apply(d, drive: drive)
|
||||
)
|
||||
}
|
||||
} else {
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? input[i] : 0
|
||||
let (a, b) = upsampler2x.process(x)
|
||||
dstP[i] = downsampler2x.process(
|
||||
curve.apply(a, drive: drive),
|
||||
curve.apply(b, drive: drive)
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
// SaturationCurve.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// The waveshaping curve applied per (oversampled) sample by ``OversampledSaturator``.
|
||||
///
|
||||
/// Each case reproduces the nonlinearity a specific drive pedal used to build inline from
|
||||
/// stock generators, so moving that pedal onto the oversampled path is voicing-preserving:
|
||||
///
|
||||
/// - `tanhPreGain` — `tanh(drive · x)`. Symmetric soft saturation with the drive applied
|
||||
/// *before* the `tanh` (the fuzz voicing: hard pre-gain squares the wave off).
|
||||
/// - `softClipNormalized` — `tanh(drive · x) / tanh(drive)`. The same curve normalised so a
|
||||
/// unity-drive signal passes near-linearly (the overdrive voicing).
|
||||
/// - `tanhPostGainHardClip(low:high:)` — `clip(tanh(x) · drive, low, high)`. A gentle `tanh`
|
||||
/// stage, post-gained by drive into a hard clipper (the distortion voicing). The hard clip
|
||||
/// is the dominant harmonic source and the reason this curve wants the highest oversampling
|
||||
/// factor.
|
||||
public enum SaturationCurve: Sendable {
|
||||
case tanhPreGain
|
||||
case softClipNormalized
|
||||
case tanhPostGainHardClip(low: Double, high: Double)
|
||||
|
||||
/// Applies the curve to a single sample.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - x: Input sample (already at the oversampled rate).
|
||||
/// - drive: Drive amount. The caller clamps this to a small positive floor so
|
||||
/// `softClipNormalized`'s `tanh(drive)` denominator is never zero.
|
||||
/// - Returns: The shaped sample.
|
||||
@inline(__always)
|
||||
func apply(_ x: Double, drive: Double) -> Double {
|
||||
switch self {
|
||||
case .tanhPreGain:
|
||||
return tanh(drive * x)
|
||||
case .softClipNormalized:
|
||||
return tanh(drive * x) / tanh(drive)
|
||||
case .tanhPostGainHardClip(let low, let high):
|
||||
let shaped: Double = tanh(x) * drive
|
||||
return Swift.min(high, Swift.max(low, shaped))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Internal synthesizer that copies one hardware input bus to a board head bus.
|
||||
///
|
||||
@@ -18,6 +19,17 @@ import LyrebirdSynth
|
||||
/// `teardown()` releases the head bus back to the allocator.
|
||||
final class HardwareInputPassThrough: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Input mute — `0` = audible, `1` = muted (a hard gate on the incoming signal, distinct from
|
||||
/// the rig-output mute). Driven across every board input node by `ShoeGaze.setInputMuted(_:)`,
|
||||
/// which sets a newly-added node to the session's current mute state. Defaults audible so
|
||||
/// direct users (e.g. `ChainRouter`) that don't drive the mute pass the signal through.
|
||||
@UIParam var inputMute: Double = 0.0
|
||||
|
||||
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
|
||||
var inputMuteNode: UIParamNode { $inputMute }
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Index of the hardware input bus to read from (typically `engine.numOutputChannels`).
|
||||
@@ -43,6 +55,11 @@ final class HardwareInputPassThrough: SynthesizerBase {
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
|
||||
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
|
||||
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
|
||||
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
|
||||
// kill-switch mute is expected to be abrupt anyway.
|
||||
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
|
||||
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Internal synthesizer that copies the shared global test-loop bus to a board head bus.
|
||||
///
|
||||
@@ -19,6 +20,16 @@ import LyrebirdSynth
|
||||
/// - Note: Must be removed from the engine before the board's `teardown()` releases the head bus.
|
||||
final class TestLoopTap: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Input mute — `0` = audible, `1` = muted. Driven across every board input node by
|
||||
/// `ShoeGaze.setInputMuted(_:)`, which sets a newly-added node to the session's current mute
|
||||
/// state. Defaults audible so direct users that don't drive the mute pass the signal through.
|
||||
@UIParam var inputMute: Double = 0.0
|
||||
|
||||
/// The live `UIParamNode` backing `inputMute`, driven by `ShoeGaze.setInputMuted(_:)`.
|
||||
var inputMuteNode: UIParamNode { $inputMute }
|
||||
|
||||
// MARK: - Routing
|
||||
|
||||
/// Index of the shared global test-loop bus to read from.
|
||||
@@ -44,6 +55,11 @@ final class TestLoopTap: SynthesizerBase {
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
output(bus: outputBusIndex, source: input(bus: inputBusIndex))
|
||||
// Hard kill-switch gate: `1 − inputMute`, so mute 0 → gain 1 (audible), 1 → gain 0 (exactly
|
||||
// silent). Unlagged on purpose — a lagged gate never settles to exactly zero on its first
|
||||
// blocks and leaks a faint transient right when the mute is meant to keep things quiet; a
|
||||
// kill-switch mute is expected to be abrupt anyway.
|
||||
let muteGain: any ValidGeneratorInput = ($inputMute - 1.0) * -1.0
|
||||
output(bus: outputBusIndex, source: input(bus: inputBusIndex) * muteGain)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,6 +38,8 @@ public final class MIDIController {
|
||||
case cc(MIDIMap.CCTarget)
|
||||
/// A toggle action awaiting a Program Change.
|
||||
case action(MIDIMap.Action)
|
||||
/// A toggle action awaiting a computer key press.
|
||||
case key(MIDIMap.Action)
|
||||
}
|
||||
|
||||
/// The control currently armed for Learn, or `nil` when not learning. Observable so the UI can
|
||||
@@ -248,6 +250,14 @@ public final class MIDIController {
|
||||
continue
|
||||
}
|
||||
guard let resolved: ResolvedCC = resolveCC(binding.target) else { continue }
|
||||
// A parameter locked to a note division is driven by the tempo; a CC write would be
|
||||
// overwritten on the next tempo change, so ignore it here. The binding stays intact and
|
||||
// resumes control the moment the parameter is set back to Free.
|
||||
if case let .pedalControl(pedalID, _, _, _) = binding.target,
|
||||
let pedal: Pedal = pedal(id: pedalID),
|
||||
pedal.isNodeTempoSynced(resolved.node) {
|
||||
continue
|
||||
}
|
||||
let mapped: Double = resolved.range.lowerBound
|
||||
+ norm * (resolved.range.upperBound - resolved.range.lowerBound)
|
||||
resolved.node.update(mapped)
|
||||
@@ -350,6 +360,8 @@ public final class MIDIController {
|
||||
shoeGaze.toggleRigBypassed()
|
||||
case .rigMute:
|
||||
shoeGaze.toggleRigMuted()
|
||||
case .inputMute:
|
||||
shoeGaze.toggleInputMuted()
|
||||
case .allBoards:
|
||||
// One-shot: cancel any solo and bring every board back up.
|
||||
shoeGaze.selectAllBoards(crossfadeSeconds: boardActionCrossfade)
|
||||
@@ -412,7 +424,7 @@ public final class MIDIController {
|
||||
/// Not used for resolution (bindings resolve by UUID) — purely a human-readable snapshot.
|
||||
private func hint(for action: MIDIMap.Action) -> String? {
|
||||
switch action {
|
||||
case .rigBypass, .rigMute, .allBoards:
|
||||
case .rigBypass, .rigMute, .inputMute, .allBoards:
|
||||
return nil
|
||||
case .boardSolo(let boardID), .boardAudible(let boardID), .boardBypass(let boardID):
|
||||
return board(id: boardID)?.label
|
||||
@@ -438,6 +450,89 @@ public final class MIDIController {
|
||||
return nil
|
||||
}
|
||||
|
||||
// MARK: - Key learn + apply
|
||||
|
||||
/// Arms MIDI Learn for a toggle action awaiting a key: the next ingested key press binds to it.
|
||||
public func armKeyLearn(_ action: MIDIMap.Action) {
|
||||
learnTarget = .key(action)
|
||||
}
|
||||
|
||||
/// The key binding currently assigned to an action, or `nil` if unbound.
|
||||
public func keyBinding(for action: MIDIMap.Action) -> MIDIMap.KeyBinding? {
|
||||
shoeGaze?.midiMap?.keys.first { $0.action == action }
|
||||
}
|
||||
|
||||
/// Removes any key binding assigned to an action.
|
||||
public func clearKeyBinding(for action: MIDIMap.Action) {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze, var map: MIDIMap = shoeGaze.midiMap else { return }
|
||||
let before: Int = map.keys.count
|
||||
map.keys.removeAll { $0.action == action }
|
||||
guard map.keys.count != before else { return }
|
||||
shoeGaze.midiMap = map
|
||||
onMapChanged?()
|
||||
}
|
||||
|
||||
/// Normalizes a raw key string to the single lowercased character used for storage and matching,
|
||||
/// or `nil` when the input is not exactly one letter or digit. Restricting to alphanumerics keeps
|
||||
/// non-printing keys (Return, Tab, Escape, arrows — all single `Character`s) from being learned
|
||||
/// and then silently swallowed app-wide.
|
||||
private func normalizedKey(_ raw: String) -> String? {
|
||||
let lowered: String = raw.lowercased()
|
||||
guard lowered.count == 1, let character: Character = lowered.first, character.isASCII,
|
||||
character.isLetter || character.isNumber else { return nil }
|
||||
return lowered
|
||||
}
|
||||
|
||||
/// Routes a computer key press: captures a binding when armed for key Learn, otherwise performs
|
||||
/// every action bound to that key + modifier combination. Returns `true` when the press was
|
||||
/// consumed (learned or matched a binding) so the caller can swallow the event; `false` lets it
|
||||
/// fall through.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - rawKey: The pressed key; normalized to a single lowercased character.
|
||||
/// - modifiers: The modifier keys held with the press. `a` and `⇧a` bind independently.
|
||||
@discardableResult
|
||||
public func ingestKey(_ rawKey: String, modifiers: MIDIMap.KeyModifiers = []) -> Bool {
|
||||
guard let key: String = normalizedKey(rawKey) else { return false }
|
||||
if case .key(let action) = learnTarget {
|
||||
captureKey(key: key, modifiers: modifiers, action: action)
|
||||
return true
|
||||
}
|
||||
return applyKey(key, modifiers: modifiers)
|
||||
}
|
||||
|
||||
/// Captures a learned key binding for the armed action and clears the Learn state. One binding
|
||||
/// per action — re-learning replaces it — but a single key may drive multiple actions (a scene),
|
||||
/// so we do not steal by key.
|
||||
private func captureKey(key: String, modifiers: MIDIMap.KeyModifiers, action: MIDIMap.Action) {
|
||||
learnTarget = nil
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze else { return }
|
||||
let binding: MIDIMap.KeyBinding = MIDIMap.KeyBinding(
|
||||
key: key,
|
||||
modifiers: modifiers,
|
||||
action: action,
|
||||
displayNameHint: hint(for: action)
|
||||
)
|
||||
var map: MIDIMap = shoeGaze.midiMap ?? MIDIMap.empty
|
||||
map.keys.removeAll { $0.action == action }
|
||||
map.keys.append(binding)
|
||||
shoeGaze.midiMap = map
|
||||
onMapChanged?()
|
||||
}
|
||||
|
||||
/// Performs every action bound to a key + modifier combination. Returns `true` when at least one
|
||||
/// binding matched (key and modifiers both equal).
|
||||
private func applyKey(_ key: String, modifiers: MIDIMap.KeyModifiers) -> Bool {
|
||||
guard let shoeGaze: ShoeGaze = shoeGaze, let map: MIDIMap = shoeGaze.midiMap else { return false }
|
||||
var matched: Bool = false
|
||||
for binding: MIDIMap.KeyBinding in map.keys
|
||||
where binding.key == key && binding.modifiers == modifiers {
|
||||
perform(binding.action)
|
||||
matched = true
|
||||
}
|
||||
return matched
|
||||
}
|
||||
|
||||
// MARK: - Device detection
|
||||
|
||||
private func refreshDevices() {
|
||||
|
||||
@@ -24,6 +24,10 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
/// Control-Change → pedal-knob bindings (expression pedals).
|
||||
public var ccs: [CCBinding]
|
||||
|
||||
/// Computer letter/digit key → action bindings. Same toggle ``Action`` set as ``switches`` —
|
||||
/// a key press is a software footswitch — but keys never drive continuous CC targets.
|
||||
public var keys: [KeyBinding]
|
||||
|
||||
/// An empty map (no bindings).
|
||||
public static let empty: MIDIMap = MIDIMap()
|
||||
|
||||
@@ -32,12 +36,32 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
/// - Parameters:
|
||||
/// - switches: Program-Change bindings. Defaults to empty.
|
||||
/// - ccs: Control-Change bindings. Defaults to empty.
|
||||
/// - keys: Letter-key bindings. Defaults to empty.
|
||||
public init(
|
||||
switches: [SwitchBinding] = [],
|
||||
ccs: [CCBinding] = []
|
||||
ccs: [CCBinding] = [],
|
||||
keys: [KeyBinding] = []
|
||||
) {
|
||||
self.switches = switches
|
||||
self.ccs = ccs
|
||||
self.keys = keys
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case switches
|
||||
case ccs
|
||||
case keys
|
||||
}
|
||||
|
||||
/// Decodes a map, tolerating an absent `keys` list so a rig saved before keyboard mapping
|
||||
/// existed still decodes with its `switches` / `ccs` intact (synthesized Codable would fail
|
||||
/// the whole map on the missing key, silently dropping the MIDI bindings too). `encode(to:)`
|
||||
/// stays synthesized and always writes `keys` (empty when there are none).
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.switches = try container.decode([SwitchBinding].self, forKey: .switches)
|
||||
self.ccs = try container.decode([CCBinding].self, forKey: .ccs)
|
||||
self.keys = try container.decodeIfPresent([KeyBinding].self, forKey: .keys) ?? []
|
||||
}
|
||||
|
||||
// MARK: - Action
|
||||
@@ -48,6 +72,8 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
case rigBypass
|
||||
/// Mutes/unmutes the rig output (a hard silence, not a bypass).
|
||||
case rigMute
|
||||
/// Mutes/unmutes the input feeding every board (the incoming guitar / mic signal).
|
||||
case inputMute
|
||||
/// Cancels any solo and makes every board audible again (the "All" button).
|
||||
case allBoards
|
||||
case boardSolo(boardID: UUID)
|
||||
@@ -127,6 +153,86 @@ public struct MIDIMap: Codable, Equatable, Sendable {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Key modifiers
|
||||
|
||||
/// The modifier keys that qualify a ``KeyBinding``, so `a` and `⇧a` (and `⌃a`, `⌥a`) are
|
||||
/// distinct triggers. Shift is a modifier here rather than being folded into the key's case,
|
||||
/// which keeps the base key a single lowercased character on every platform. Command is
|
||||
/// deliberately absent — it is reserved for the app's menu keyboard shortcuts.
|
||||
public struct KeyModifiers: OptionSet, Codable, Equatable, Hashable, Sendable {
|
||||
|
||||
public let rawValue: Int
|
||||
|
||||
public init(rawValue: Int) {
|
||||
self.rawValue = rawValue
|
||||
}
|
||||
|
||||
/// The Shift key (`⇧`).
|
||||
public static let shift: KeyModifiers = KeyModifiers(rawValue: 1 << 0)
|
||||
/// The Control key (`⌃`).
|
||||
public static let control: KeyModifiers = KeyModifiers(rawValue: 1 << 1)
|
||||
/// The Option key (`⌥`).
|
||||
public static let option: KeyModifiers = KeyModifiers(rawValue: 1 << 2)
|
||||
}
|
||||
|
||||
// MARK: - Key binding
|
||||
|
||||
/// A computer letter/digit key bound to a toggle ``Action``. Fires on key-down when no text
|
||||
/// field is focused; the same latch semantics as a footswitch (booleans flip in software,
|
||||
/// `boardSolo` is exclusive). `key` is a single lowercased character; ``modifiers`` distinguish
|
||||
/// `a` from `⇧a`, `⌃a`, and `⌥a`.
|
||||
public struct KeyBinding: Codable, Equatable, Sendable {
|
||||
|
||||
/// The bound key as a single lowercased character (e.g. `"b"`, `"3"`).
|
||||
public var key: String
|
||||
|
||||
/// The modifier keys held with ``key``. Empty for an unmodified press.
|
||||
public var modifiers: KeyModifiers
|
||||
|
||||
/// The control to toggle.
|
||||
public var action: Action
|
||||
|
||||
/// The resolved control's display name at learn time, for stale-binding detection.
|
||||
public var displayNameHint: String?
|
||||
|
||||
/// Creates a key binding.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - key: The bound key, normalized to a single lowercased character.
|
||||
/// - modifiers: The qualifying modifier keys. Defaults to none.
|
||||
/// - action: The toggle action to perform.
|
||||
/// - displayNameHint: Resolved control name at learn time. Defaults to `nil`.
|
||||
public init(
|
||||
key: String,
|
||||
modifiers: KeyModifiers = [],
|
||||
action: Action,
|
||||
displayNameHint: String? = nil
|
||||
) {
|
||||
self.key = key
|
||||
self.modifiers = modifiers
|
||||
self.action = action
|
||||
self.displayNameHint = displayNameHint
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case key
|
||||
case modifiers
|
||||
case action
|
||||
case displayNameHint
|
||||
}
|
||||
|
||||
/// Decodes a key binding, defaulting `modifiers` to none when absent so a binding saved
|
||||
/// before modifiers existed still decodes (unmodified, as it was learned). `encode(to:)`
|
||||
/// stays synthesized.
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.key = try container.decode(String.self, forKey: .key)
|
||||
self.modifiers = try container.decodeIfPresent(KeyModifiers.self, forKey: .modifiers) ?? []
|
||||
self.action = try container.decode(Action.self, forKey: .action)
|
||||
self.displayNameHint = try container.decodeIfPresent(String.self, forKey: .displayNameHint)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - CC target
|
||||
|
||||
/// A continuous control an expression pedal can drive — either a specific pedal control (a knob
|
||||
|
||||
@@ -73,6 +73,16 @@ open class Pedal: SynthesizerBase {
|
||||
/// the engine owns the node tree, not the reverse.
|
||||
public internal(set) weak var hostEngine: SynthesisEngine?
|
||||
|
||||
// MARK: - Tempo sync
|
||||
|
||||
/// Sync state per tempo-syncable parameter, keyed by ``TempoSyncableParam/key``. A missing
|
||||
/// key means ``TempoSync/free``. Persisted in ``PedalState`` and restored on rig load.
|
||||
public internal(set) var tempoSync: [String: TempoSync] = [:]
|
||||
|
||||
/// Observable signal bumped on every ``tempoSync`` change so a SwiftUI badge re-renders when the
|
||||
/// sync state changes through any path (the picker, a preset load, or a lightweight recall).
|
||||
public let tempoSyncRevision: TempoSyncRevision = TempoSyncRevision()
|
||||
|
||||
// MARK: - Identity / routing
|
||||
|
||||
/// Stable identity for this pedal instance, persisted in ``PedalState`` and used by MIDI
|
||||
@@ -266,6 +276,60 @@ open class Pedal: SynthesizerBase {
|
||||
return knobControls + sliderControls
|
||||
}
|
||||
|
||||
// MARK: - Tempo sync
|
||||
|
||||
/// Parameters this pedal exposes to tempo sync (delay times, LFO rates). Empty by default —
|
||||
/// override in subclasses whose time- or rate-based parameters can lock to the tempo.
|
||||
///
|
||||
/// Each descriptor's ``TempoSyncableParam/key`` must be unique within the pedal and stable
|
||||
/// across versions (it is the persistence key). Order is the order the sync controls appear.
|
||||
open var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[]
|
||||
}
|
||||
|
||||
/// Recomputes and writes every parameter currently locked to a note division, from the shared
|
||||
/// clock's tempo. Main-thread only — writing a `@UIParam` is the same path as a knob turn.
|
||||
///
|
||||
/// A no-op when no clock is injected. Free parameters are left untouched. A synced value that
|
||||
/// falls outside the parameter's range (a long division past a delay's maximum time) is clamped.
|
||||
/// Called by `ShoeGaze` whenever the tempo changes and whenever a parameter's sync state changes.
|
||||
public func applyTempoSync() {
|
||||
guard let clock: LyrebirdClock = clock else { return }
|
||||
let bpm: Double = clock.bpm
|
||||
guard bpm > 0 else { return }
|
||||
for param: TempoSyncableParam in tempoSyncableParams {
|
||||
guard case .division(let division) = tempoSync[param.key] ?? .free else { continue }
|
||||
param.node.update(param.value(for: division, bpm: bpm).value)
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets one parameter's sync state and immediately recomputes it. Pass ``TempoSync/free`` to
|
||||
/// return the parameter to knob control (its value stays at the last synced number until the
|
||||
/// knob moves it), or `.division(_:)` to lock it to a note value of the live tempo.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sync: The new sync state.
|
||||
/// - key: The ``TempoSyncableParam/key`` of the parameter to update.
|
||||
public func setSync(_ sync: TempoSync, for key: String) {
|
||||
tempoSync[key] = sync
|
||||
tempoSyncRevision.bump()
|
||||
applyTempoSync()
|
||||
}
|
||||
|
||||
/// Whether `node` backs a tempo-syncable parameter currently locked to a note division.
|
||||
///
|
||||
/// Used by MIDI to leave a synced parameter alone: its value is derived from the tempo, so a CC
|
||||
/// write would be immediately overwritten on the next tempo change. Matches by node identity, so
|
||||
/// it stays correct regardless of control ordering. Returns `false` for a free or non-syncable node.
|
||||
public func isNodeTempoSynced(_ node: UIParamNode) -> Bool {
|
||||
for param: TempoSyncableParam in tempoSyncableParams where param.node === node {
|
||||
if case .division = tempoSync[param.key] ?? .free {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MARK: - Subclass hook
|
||||
|
||||
/// Returns the processed (wet) mono signal for this pedal.
|
||||
|
||||
@@ -61,6 +61,12 @@ public final class ChorusPedal: Pedal {
|
||||
private let rateRange: ClosedRange<Double> = 0.05 ... 6.0
|
||||
private let depthRange: ClosedRange<Double> = 0.0005 ... 0.008
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -32,6 +32,12 @@ import LyrebirdUI
|
||||
/// compressed. Range `[-40, 0]` dB. Defaults to `-12.0`.
|
||||
/// - ratio: Compression ratio `≥ 1.0`. `1.0` = bypass, `4.0` = 4:1 compression.
|
||||
/// Range `[1, 20]`. Defaults to `4.0`.
|
||||
///
|
||||
/// A feed-forward compressor can overshoot on fast transients (its attack is non-zero),
|
||||
/// so a hot input plus makeup gain can push peaks past full scale and clip the output.
|
||||
/// The **Safety** switch inserts a brick-wall `LookAheadLimiter` after the compressor to
|
||||
/// catch those peaks; it is off by default (leave adding a limiter to the user) and adds
|
||||
/// a short look-ahead output delay when engaged.
|
||||
public final class CompressorPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
@@ -50,6 +56,10 @@ public final class CompressorPedal: Pedal {
|
||||
/// Compression ratio. Range [1, 20].
|
||||
@UIParam public var ratio: Double = 4.0
|
||||
|
||||
/// Safety limiter engage state. `0` = off (compressor may overshoot), `1` = on
|
||||
/// (brick-wall look-ahead limiter catches transient peaks).
|
||||
@UIParam public var safetyLimiter: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the compressor is inserted in-line.
|
||||
@@ -71,6 +81,20 @@ public final class CompressorPedal: Pedal {
|
||||
/// Makeup gain in dB applied after compression to restore perceived loudness.
|
||||
private let makeupGainDB: Double = 4.0
|
||||
|
||||
/// Safety-limiter peak ceiling (linear amplitude), just below full scale.
|
||||
private let safetyCeiling: Double = 0.98
|
||||
|
||||
/// Safety-limiter look-ahead / output delay in seconds. Short enough to catch
|
||||
/// transients without smearing attack; only in circuit when Safety is engaged.
|
||||
private let safetyLookAheadTime: Double = 0.005
|
||||
|
||||
/// Safety-limiter gain-release time in seconds.
|
||||
private let safetyReleaseTime: Double = 0.05
|
||||
|
||||
/// Safety switch position values.
|
||||
private let safetyOffValue: Double = 0.0
|
||||
private let safetyOnValue: Double = 1.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Input-gain knob range in dB.
|
||||
@@ -90,6 +114,19 @@ public final class CompressorPedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Safety",
|
||||
node: $safetyLimiter,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Off", value: safetyOffValue),
|
||||
PedalSwitch.Option(title: "On", value: safetyOnValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a compressor pedal.
|
||||
@@ -121,7 +158,7 @@ public final class CompressorPedal: Pedal {
|
||||
// Convert the input-gain dB to a linear multiplier (10^(dB/20)) and apply before compression.
|
||||
let inputGainLinear: Exp.Audio = Exp.Audio($inputGain * dbToLinExpScale)
|
||||
let boosted: any ValidGeneratorInput = dry * inputGainLinear
|
||||
return Compressor.Audio(
|
||||
let compressed: Compressor.Audio = Compressor.Audio(
|
||||
in: boosted,
|
||||
threshold: $threshold,
|
||||
ratio: $ratio,
|
||||
@@ -130,5 +167,18 @@ public final class CompressorPedal: Pedal {
|
||||
kneeWidth: kneeWidth,
|
||||
makeupGain: makeupGainDB
|
||||
)
|
||||
// Brick-wall safety limiter after the compressor. Both branches are always built;
|
||||
// `Select` picks per the Safety switch (0 = compressor only, 1 = limited).
|
||||
let limited: LookAheadLimiter = LookAheadLimiter(
|
||||
in: compressed,
|
||||
maxAmplitude: safetyCeiling,
|
||||
lookAheadTime: safetyLookAheadTime,
|
||||
releaseTime: safetyReleaseTime,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
return Select.Audio(
|
||||
which: $safetyLimiter,
|
||||
inputs: [compressed, limited]
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ import LyrebirdUI
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - time: Delay time in seconds. Range `[0.01, 1.5]`. Defaults to `0.25`.
|
||||
/// - time: Delay time in seconds. Range `[0.01, 5.0]`. Defaults to `0.25`.
|
||||
/// - feedback: Feedback amount expressed as decay time in seconds — the time
|
||||
/// for echoes to fall to `targetAmp` (−60 dB). Longer values produce more
|
||||
/// repeats. Range `[0.05, 6.0]` seconds. Defaults to `1.0`.
|
||||
@@ -35,7 +35,7 @@ public final class DelayPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Delay time in seconds. Range [0.01, 1.5].
|
||||
/// Delay time in seconds. Range [0.01, 5.0].
|
||||
@UIParam public var time: Double = 0.25
|
||||
|
||||
/// Feedback decay time in seconds (time to reach −60 dB amplitude).
|
||||
@@ -44,7 +44,7 @@ public final class DelayPedal: Pedal {
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported delay time in seconds. Sizes the delay line buffer at init.
|
||||
private let maxDelayTime: Double = 1.5
|
||||
private let maxDelayTime: Double = 5.0
|
||||
|
||||
/// Amplitude target for the `decayTime` calculation (−60 dB).
|
||||
private let targetAmp: Double = 0.001
|
||||
@@ -55,7 +55,7 @@ public final class DelayPedal: Pedal {
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Delay-time knob range in seconds.
|
||||
private let timeRange: ClosedRange<Double> = 0.01 ... 1.5
|
||||
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
|
||||
|
||||
/// Feedback (decay-time) knob range in seconds.
|
||||
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
|
||||
@@ -86,6 +86,12 @@ public final class DelayPedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Effect
|
||||
|
||||
/// Applies a feedback delay line. Returns the pure wet (delayed) signal.
|
||||
|
||||
@@ -9,9 +9,10 @@ import LyrebirdUI
|
||||
|
||||
/// Mid-gain distortion — more saturated than `OverdrivePedal`, more controlled than `FuzzPedal`.
|
||||
///
|
||||
/// A DC-blocking high-pass feeds a `tanh` soft-clipper driven hard by the `Drive` knob; a
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip guarantees the
|
||||
/// output stays bounded.
|
||||
/// A DC-blocking high-pass feeds a `tanh` stage that is post-gained by the `Drive` knob into a
|
||||
/// hard clipper — both evaluated at 4× oversampling so the clipper's harmonics don't alias. A
|
||||
/// post-clip low-pass `Tone` control tames the harmonics, and a final hard clip re-bounds the
|
||||
/// output (the tone low-pass can ring slightly past the ceiling on transients).
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `drive`: Pre-clip gain into the `tanh` stage. Range `[1, 50]`.
|
||||
@@ -87,12 +88,24 @@ public final class DistortionPedal: Pedal {
|
||||
freq: dcBlockFreq,
|
||||
q: filterQ
|
||||
)
|
||||
let driven: Tanh.Audio = Tanh.Audio(dcBlocked, mul: $drive)
|
||||
// tanh soft stage → post-gain by drive → hard clip, all evaluated at 4× so the hard
|
||||
// clipper's harmonics settle above the upsampled Nyquist instead of aliasing back.
|
||||
// The tone low-pass now follows the clip (standard clip→tone order), which also
|
||||
// filters any residual high-band content the downsampler leaves.
|
||||
let clipped: OversampledSaturator = OversampledSaturator(
|
||||
dcBlocked,
|
||||
drive: $drive,
|
||||
curve: .tanhPostGainHardClip(low: clipLow, high: clipHigh),
|
||||
oversample: 4
|
||||
)
|
||||
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||
input: driven,
|
||||
input: clipped,
|
||||
freq: $tone,
|
||||
q: filterQ
|
||||
)
|
||||
// Final hard clip re-establishes the strict output bound: the tone low-pass is linear
|
||||
// and band-limited, so it can overshoot the ceiling slightly on transients, but
|
||||
// clipping its (already band-limited) output adds negligible new aliasing.
|
||||
return Clip.Audio(toned, lo: clipLow, hi: clipHigh)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ public final class FeedbackDelayPedal: Pedal {
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported delay time in seconds. Sizes the delay-line buffer at init.
|
||||
private let maxDelayTime: Double = 1.5
|
||||
private let maxDelayTime: Double = 5.0
|
||||
|
||||
/// Amplitude target for the `decayTime` calculation (−60 dB).
|
||||
private let targetAmp: Double = 0.001
|
||||
@@ -58,12 +58,18 @@ public final class FeedbackDelayPedal: Pedal {
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let timeRange: ClosedRange<Double> = 0.02 ... 1.5
|
||||
private let timeRange: ClosedRange<Double> = 0.02 ... 5.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.1 ... 8.0
|
||||
private let toneRange: ClosedRange<Double> = 500.0 ... 8000.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
|
||||
@@ -57,6 +57,12 @@ public final class FlangerPedal: Pedal {
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -105,11 +105,17 @@ public final class FuzzPedal: Pedal {
|
||||
/// - Returns: Fuzzed and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
// Pre-gain the signal hard, then saturate. `tanh` squares the waveform off as the
|
||||
// drive rises while keeping the level bounded — the hallmark of a fuzz.
|
||||
let driven: any ValidGeneratorInput = dry * $fuzz
|
||||
let saturated: Tanh.Audio = Tanh.Audio(driven, mul: outputTrim)
|
||||
// drive rises while keeping the level bounded — the hallmark of a fuzz. Evaluated at
|
||||
// 2× so the high harmonics the hard pre-gain generates don't fold back as aliasing.
|
||||
let saturated: OversampledSaturator = OversampledSaturator(
|
||||
dry,
|
||||
drive: $fuzz,
|
||||
curve: .tanhPreGain,
|
||||
oversample: 2
|
||||
)
|
||||
let trimmed: any ValidGeneratorInput = saturated * outputTrim
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
input: trimmed,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
|
||||
@@ -29,6 +29,9 @@ import LyrebirdUI
|
||||
/// drive harder into the limiter. Range `[1, 12]`. Defaults to `1.0`.
|
||||
/// - ceiling: Output peak ceiling as a linear amplitude in `[0, 1]`. The limited output
|
||||
/// never exceeds this absolute value. Range `[0.1, 1.0]`. Defaults to `0.95`.
|
||||
/// - release: Gain-release time in seconds. Too short a release modulates the gain
|
||||
/// within a waveform cycle and distorts low notes; longer is cleaner but lets the
|
||||
/// level swell back more slowly. Range `[0.01, 0.5]`. Defaults to `0.05`.
|
||||
public final class LimiterPedal: Pedal {
|
||||
|
||||
/// One-line description shown in the picker and info panel.
|
||||
@@ -44,6 +47,9 @@ public final class LimiterPedal: Pedal {
|
||||
/// Output peak ceiling (linear amplitude). Range [0.1, 1.0].
|
||||
@UIParam public var ceiling: Double = 0.95
|
||||
|
||||
/// Gain-release time in seconds. Range [0.01, 0.5].
|
||||
@UIParam public var release: Double = 0.05
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Default wet/dry blend — fully wet; the limiter sits in-line.
|
||||
@@ -61,10 +67,14 @@ public final class LimiterPedal: Pedal {
|
||||
/// Ceiling knob range (linear output peak).
|
||||
private let ceilingRange: ClosedRange<Double> = 0.1 ... 1.0
|
||||
|
||||
/// Release knob range in seconds.
|
||||
private let releaseRange: ClosedRange<Double> = 0.01 ... 0.5
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Boost", node: $boost, range: boostRange),
|
||||
PedalKnob(label: "Ceiling", node: $ceiling, range: ceilingRange),
|
||||
PedalKnob(label: "Release", node: $release, range: releaseRange),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -101,6 +111,7 @@ public final class LimiterPedal: Pedal {
|
||||
in: boosted,
|
||||
maxAmplitude: $ceiling,
|
||||
lookAheadTime: lookAheadTime,
|
||||
releaseTime: $release,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
}
|
||||
|
||||
@@ -90,6 +90,12 @@ public final class ModulationPedal: Pedal {
|
||||
)
|
||||
}
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -58,18 +58,26 @@ public final class MultiTapDelayPedal: Pedal {
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported per-tap delay time in seconds. Sizes each delay-line buffer at init.
|
||||
private let maxDelayTime: Double = 1.0
|
||||
private let maxDelayTime: Double = 5.0
|
||||
|
||||
/// Partial wet/dry blend so the dry note and its taps coexist.
|
||||
private static let defaultMix: Double = 0.4
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let timeRange: ClosedRange<Double> = 0.01 ... 1.0
|
||||
private let timeRange: ClosedRange<Double> = 0.01 ... 5.0
|
||||
private let volRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "time1", label: "Time 1", node: $time1, kind: .time, range: timeRange),
|
||||
TempoSyncableParam(key: "time2", label: "Time 2", node: $time2, kind: .time, range: timeRange),
|
||||
TempoSyncableParam(key: "time3", label: "Time 3", node: $time3, kind: .time, range: timeRange),
|
||||
]
|
||||
}
|
||||
|
||||
/// Two rows of three: the three tap times, then the three tap volumes.
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
|
||||
@@ -11,7 +11,7 @@ import LyrebirdUI
|
||||
///
|
||||
/// Signal chain (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry → SoftClip(drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// dry → OversampledSaturator(curve: .softClipNormalized, drive:) → RBJLowPass(freq: tone, q: 0.707) → mono out
|
||||
/// ```
|
||||
///
|
||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||
@@ -83,7 +83,14 @@ public final class OverdrivePedal: Pedal {
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: Saturated and tone-shaped mono output.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let saturated: SoftClip.Audio = SoftClip.Audio(dry, drive: $drive)
|
||||
// Same normalised soft-clip curve as before (`tanh(drive·x) / tanh(drive)`), but
|
||||
// evaluated at 2× so high-drive harmonics don't alias.
|
||||
let saturated: OversampledSaturator = OversampledSaturator(
|
||||
dry,
|
||||
drive: $drive,
|
||||
curve: .softClipNormalized,
|
||||
oversample: 2
|
||||
)
|
||||
return RBJLowPass.Audio(
|
||||
input: saturated,
|
||||
freq: $tone,
|
||||
|
||||
@@ -68,6 +68,12 @@ public final class PhaserPedal: Pedal {
|
||||
/// Feedback knob range (all-pass feedback gain).
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.9
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -32,7 +32,7 @@ import LyrebirdUI
|
||||
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - time: Delay time per tap in seconds. Range `[0.05, 1.0]`. Defaults to `0.3`.
|
||||
/// - time: Delay time per tap in seconds. Range `[0.05, 5.0]`. Defaults to `0.3`.
|
||||
/// - feedback: Feedback as decay time in seconds (time for echoes to fall to −60 dB).
|
||||
/// Range `[0.05, 6.0]`. Defaults to `1.2`.
|
||||
public final class PingPongDelayPedal: Pedal {
|
||||
@@ -44,7 +44,7 @@ public final class PingPongDelayPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Delay time per tap in seconds. Range [0.05, 1.0].
|
||||
/// Delay time per tap in seconds. Range [0.05, 5.0].
|
||||
@UIParam public var time: Double = 0.3
|
||||
|
||||
/// Feedback decay time in seconds (time to reach −60 dB amplitude). Range [0.05, 6.0].
|
||||
@@ -53,7 +53,7 @@ public final class PingPongDelayPedal: Pedal {
|
||||
// MARK: - Constants
|
||||
|
||||
/// Maximum supported delay time in seconds. Sizes both delay lines at init.
|
||||
private let maxDelayTime: Double = 1.0
|
||||
private let maxDelayTime: Double = 5.0
|
||||
|
||||
/// Amplitude target for the `decayTime` calculation (−60 dB).
|
||||
private let targetAmp: Double = 0.001
|
||||
@@ -67,7 +67,7 @@ public final class PingPongDelayPedal: Pedal {
|
||||
// MARK: - UI knobs
|
||||
|
||||
/// Delay-time knob range in seconds.
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 1.0
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
|
||||
|
||||
/// Feedback (decay-time) knob range in seconds.
|
||||
private let feedbackRange: ClosedRange<Double> = 0.05 ... 6.0
|
||||
@@ -96,6 +96,12 @@ public final class PingPongDelayPedal: Pedal {
|
||||
)
|
||||
}
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
|
||||
@@ -15,7 +15,7 @@ import LyrebirdUI
|
||||
/// so the pedal's `Mix` knob sets the wet/dry blend.
|
||||
///
|
||||
/// ## Knobs
|
||||
/// - `time`: Reverse segment length in seconds. Range `[0.05, 2.0]`.
|
||||
/// - `time`: Reverse segment length in seconds. Range `[0.05, 5.0]`.
|
||||
/// - `feedback`: Reverse-trail feedback. Range `[0, 0.95]`.
|
||||
public final class ReverseDelayPedal: Pedal {
|
||||
|
||||
@@ -26,7 +26,7 @@ public final class ReverseDelayPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Reverse segment length in seconds. Range [0.05, 2.0].
|
||||
/// Reverse segment length in seconds. Range [0.05, 5.0].
|
||||
@UIParam public var time: Double = 0.5
|
||||
|
||||
/// Reverse-trail feedback. Range [0, 0.95].
|
||||
@@ -38,15 +38,21 @@ public final class ReverseDelayPedal: Pedal {
|
||||
private static let defaultMix: Double = 0.5
|
||||
|
||||
/// Maximum segment length the buffers are allocated for, in seconds.
|
||||
private let maxDelayTime: Double = 2.0
|
||||
private let maxDelayTime: Double = 5.0
|
||||
|
||||
// MARK: - Ranges
|
||||
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 2.0
|
||||
private let timeRange: ClosedRange<Double> = 0.05 ... 5.0
|
||||
private let feedbackRange: ClosedRange<Double> = 0.0 ... 0.95
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||
|
||||
@@ -15,7 +15,7 @@ import LyrebirdUI
|
||||
///
|
||||
/// Signal path (inside `effect(_:)`):
|
||||
/// ```
|
||||
/// dry × OscSin(frequency) → wet
|
||||
/// dry → OversampledRingModulator(freq: frequency, oversample: 2) → wet
|
||||
/// ```
|
||||
///
|
||||
/// The wet/dry blend and bypass are handled by the `Pedal` base class.
|
||||
@@ -78,7 +78,8 @@ public final class RingModulatorPedal: Pedal {
|
||||
/// - Parameter dry: Dry mono input signal.
|
||||
/// - Returns: The ring-modulated wet signal.
|
||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||
let carrier: OscSin.Audio = OscSin.Audio(freq: $frequency)
|
||||
return dry * carrier
|
||||
// Oversampled multiply: the sum sideband (f_in + f_carrier) can exceed Nyquist and
|
||||
// fold back as an inharmonic alias, so do the product at 2× and filter on the way down.
|
||||
return OversampledRingModulator(dry, freq: $frequency, oversample: 2)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,6 +29,12 @@ import LyrebirdUI
|
||||
/// - sustain: Amount of sustain/compression. `0` = gentle, `10` = maximum squash and hold.
|
||||
/// Range `[0, 10]`. Defaults to `5.0`.
|
||||
/// - tone: Output low-pass cutoff in Hz. Range `[800, 8000]`. Defaults to `6000.0`.
|
||||
///
|
||||
/// At high sustain the compressor applies a low threshold, a high ratio, and up to +18 dB of
|
||||
/// makeup — a feed-forward compressor's non-zero attack lets transients overshoot before the
|
||||
/// gain clamps, so a hot pick can push the output past full scale and clip. The **Safety**
|
||||
/// switch inserts a brick-wall `LookAheadLimiter` after the compressor to catch those peaks;
|
||||
/// it is off by default and adds a short look-ahead output delay when engaged.
|
||||
public final class SustainerPedal: Pedal {
|
||||
|
||||
// MARK: - Parameters
|
||||
@@ -39,6 +45,10 @@ public final class SustainerPedal: Pedal {
|
||||
/// Output low-pass cutoff in Hz. Range [800, 8000].
|
||||
@UIParam public var tone: Double = 6000.0
|
||||
|
||||
/// Safety limiter engage state. `0` = off (compressor may overshoot), `1` = on
|
||||
/// (brick-wall look-ahead limiter catches transient peaks).
|
||||
@UIParam public var safetyLimiter: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
private static let defaultMix: Double = 1.0
|
||||
@@ -69,6 +79,19 @@ public final class SustainerPedal: Pedal {
|
||||
private let makeupAtMin: Double = 0.0
|
||||
private let makeupAtMax: Double = 18.0
|
||||
|
||||
/// Safety-limiter peak ceiling (linear amplitude), just below full scale.
|
||||
private let safetyCeiling: Double = 0.98
|
||||
|
||||
/// Safety-limiter look-ahead / output delay in seconds. Only in circuit when Safety is on.
|
||||
private let safetyLookAheadTime: Double = 0.005
|
||||
|
||||
/// Safety-limiter gain-release time in seconds.
|
||||
private let safetyReleaseTime: Double = 0.05
|
||||
|
||||
/// Safety switch position values.
|
||||
private let safetyOffValue: Double = 0.0
|
||||
private let safetyOnValue: Double = 1.0
|
||||
|
||||
// MARK: - UI knobs
|
||||
|
||||
private let sustainRange: ClosedRange<Double> = 0.0 ... 10.0
|
||||
@@ -81,6 +104,19 @@ public final class SustainerPedal: Pedal {
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectSwitches: [PedalSwitch] {
|
||||
[
|
||||
PedalSwitch(
|
||||
label: "Safety",
|
||||
node: $safetyLimiter,
|
||||
options: [
|
||||
PedalSwitch.Option(title: "Off", value: safetyOffValue),
|
||||
PedalSwitch.Option(title: "On", value: safetyOnValue),
|
||||
]
|
||||
)
|
||||
]
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a sustainer pedal.
|
||||
@@ -124,8 +160,22 @@ public final class SustainerPedal: Pedal {
|
||||
kneeWidth: kneeWidth,
|
||||
makeupGain: makeup
|
||||
)
|
||||
// Optional brick-wall safety limiter. Both branches are always built; `Select` picks
|
||||
// per the Safety switch (0 = compressor only, 1 = limited). Engaging it adds the
|
||||
// limiter's short look-ahead delay.
|
||||
let limited: LookAheadLimiter = LookAheadLimiter(
|
||||
in: compressed,
|
||||
maxAmplitude: safetyCeiling,
|
||||
lookAheadTime: safetyLookAheadTime,
|
||||
releaseTime: safetyReleaseTime,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
let guarded: Select.Audio = Select.Audio(
|
||||
which: $safetyLimiter,
|
||||
inputs: [compressed, limited]
|
||||
)
|
||||
return RBJLowPass.Audio(
|
||||
input: compressed,
|
||||
input: guarded,
|
||||
freq: $tone,
|
||||
q: toneQ
|
||||
)
|
||||
|
||||
@@ -63,6 +63,12 @@ public final class TremoloPedal: Pedal {
|
||||
/// Depth knob range (modulation fraction).
|
||||
private let depthRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -50,6 +50,12 @@ public final class VibratoPedal: Pedal {
|
||||
|
||||
// MARK: - Knobs
|
||||
|
||||
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||
[
|
||||
TempoSyncableParam(key: "rate", label: "Rate", node: $rate, kind: .rate, range: rateRange),
|
||||
]
|
||||
}
|
||||
|
||||
public override var effectKnobs: [PedalKnob] {
|
||||
[
|
||||
PedalKnob(label: "Rate", node: $rate, range: rateRange),
|
||||
|
||||
@@ -27,7 +27,8 @@ extension Pedal {
|
||||
switchValues: switchValues,
|
||||
sliderValues: sliderValues,
|
||||
selectorValues: selectorValues,
|
||||
bypass: bypass
|
||||
bypass: bypass,
|
||||
tempoSync: tempoSync.isEmpty ? nil : tempoSync
|
||||
)
|
||||
}
|
||||
|
||||
@@ -61,5 +62,9 @@ extension Pedal {
|
||||
selector.node.update(value)
|
||||
}
|
||||
bypass = state.bypass
|
||||
// Restore tempo-sync state. The synced values themselves are recomputed from the rig's
|
||||
// tempo by `ShoeGaze` after the rebuild, so no clock is required here.
|
||||
tempoSync = state.tempoSync ?? [:]
|
||||
tempoSyncRevision.bump()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,6 +45,11 @@ public struct PedalState: Codable, Equatable {
|
||||
/// Bypass parameter value. `0.0` = engaged, `1.0` = bypassed.
|
||||
public let bypass: Double
|
||||
|
||||
/// Tempo-sync state per syncable parameter, keyed by ``TempoSyncableParam/key``. `nil` for a
|
||||
/// pedal with no synced parameters, and for presets saved before tempo sync existed — both
|
||||
/// decode to "all parameters free".
|
||||
public let tempoSync: [String: TempoSync]?
|
||||
|
||||
/// Creates a pedal state snapshot.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -54,6 +59,7 @@ public struct PedalState: Codable, Equatable {
|
||||
/// - sliderValues: Current slider values in `Pedal.effectSliders` order. Defaults to empty.
|
||||
/// - selectorValues: Current selector values in `Pedal.effectSelectors` order. Defaults to empty.
|
||||
/// - bypass: Bypass parameter value (`0.0` = engaged, `1.0` = bypassed).
|
||||
/// - tempoSync: Tempo-sync state per syncable parameter, or `nil` for none. Defaults to `nil`.
|
||||
public init(
|
||||
id: UUID = UUID(),
|
||||
type: String,
|
||||
@@ -61,7 +67,8 @@ public struct PedalState: Codable, Equatable {
|
||||
switchValues: [Double] = [],
|
||||
sliderValues: [Double] = [],
|
||||
selectorValues: [Double] = [],
|
||||
bypass: Double
|
||||
bypass: Double,
|
||||
tempoSync: [String: TempoSync]? = nil
|
||||
) {
|
||||
self.id = id
|
||||
self.type = type
|
||||
@@ -70,6 +77,7 @@ public struct PedalState: Codable, Equatable {
|
||||
self.sliderValues = sliderValues
|
||||
self.selectorValues = selectorValues
|
||||
self.bypass = bypass
|
||||
self.tempoSync = tempoSync
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
@@ -80,10 +88,11 @@ public struct PedalState: Codable, Equatable {
|
||||
case sliderValues
|
||||
case selectorValues
|
||||
case bypass
|
||||
case tempoSync
|
||||
}
|
||||
|
||||
/// Decodes a snapshot, tolerating presets saved before `switchValues` / `sliderValues` /
|
||||
/// `selectorValues` existed by defaulting the missing keys to an empty array.
|
||||
/// `selectorValues` / `tempoSync` existed by defaulting the missing keys.
|
||||
public init(from decoder: any Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
self.id = try container.decodeIfPresent(UUID.self, forKey: .id) ?? UUID()
|
||||
@@ -93,5 +102,6 @@ public struct PedalState: Codable, Equatable {
|
||||
self.sliderValues = try container.decodeIfPresent([Double].self, forKey: .sliderValues) ?? []
|
||||
self.selectorValues = try container.decodeIfPresent([Double].self, forKey: .selectorValues) ?? []
|
||||
self.bypass = try container.decode(Double.self, forKey: .bypass)
|
||||
self.tempoSync = try container.decodeIfPresent([String: TempoSync].self, forKey: .tempoSync)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,15 +85,29 @@ public enum RigStore {
|
||||
do {
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
let decoder: JSONDecoder = JSONDecoder()
|
||||
let state: ShoeGazeState
|
||||
let rigID: UUID?
|
||||
if let envelope: AutosaveEnvelope = try? decoder.decode(AutosaveEnvelope.self, from: data) {
|
||||
try shoeGaze.loadRig(from: envelope.state)
|
||||
shoeGaze.currentRigID = envelope.currentRigID
|
||||
state = envelope.state
|
||||
rigID = envelope.currentRigID
|
||||
} else {
|
||||
// Pre-envelope autosave: a bare ShoeGazeState with no recorded source rig.
|
||||
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
try shoeGaze.loadRig(from: state)
|
||||
shoeGaze.currentRigID = nil
|
||||
state = try decoder.decode(ShoeGazeState.self, from: data)
|
||||
rigID = nil
|
||||
}
|
||||
// Unlike a mid-session rig load — where forcing the layout would fight the global engine
|
||||
// config and the iOS enable-live-input flow — a launch restore SHOULD reinstate the
|
||||
// rig's saved I/O layout so a multi-channel setup (and a saved live-input channel)
|
||||
// survives relaunch. Apply it first, while the engine is stopped, so `loadRig`'s
|
||||
// input-channel validation runs against the restored count. A failure here is
|
||||
// non-fatal — fall through to `loadRig`, which still rebuilds the boards.
|
||||
do {
|
||||
try shoeGaze.applyChannelLayout(from: state)
|
||||
} catch {
|
||||
print("[RigStore] channel-layout restore failed (continuing): \(error)")
|
||||
}
|
||||
try shoeGaze.loadRig(from: state)
|
||||
shoeGaze.currentRigID = rigID
|
||||
return !shoeGaze.boards.isEmpty
|
||||
} catch {
|
||||
print("[RigStore] restore failed: \(error)")
|
||||
|
||||
@@ -134,6 +134,12 @@ extension ShoeGaze {
|
||||
if let savedTempoEnabled: Bool = state.tempoEnabled {
|
||||
setTempoEnabled(savedTempoEnabled)
|
||||
}
|
||||
// Bring restored tempo-synced parameters in line with the loaded tempo. `setTempoEnabled`
|
||||
// already re-syncs when it runs and is enabled, but an older rig with no saved
|
||||
// `tempoEnabled` skips that path — recompute unconditionally so synced values are correct.
|
||||
if tempoEnabled {
|
||||
applyTempoSyncToAllPedals()
|
||||
}
|
||||
}
|
||||
|
||||
/// Rebuilds every board from a snapshot with all-or-nothing semantics.
|
||||
@@ -346,6 +352,12 @@ extension ShoeGaze {
|
||||
for (board, boardState) in zip(boards, state.boards) {
|
||||
applySegmentParams(boardState.segments, to: board.orderedSegments)
|
||||
}
|
||||
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is
|
||||
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
|
||||
// mirroring the full `loadRig(from:)` path.
|
||||
if tempoEnabled {
|
||||
applyTempoSyncToAllPedals()
|
||||
}
|
||||
}
|
||||
|
||||
/// Positionally applies segment parameter snapshots to live board segments, including
|
||||
|
||||
@@ -139,7 +139,11 @@ public final class ShoeGaze {
|
||||
/// control by forcing each ``PedalSwitch/tempoDependent`` switch to its first option.
|
||||
public func setTempoEnabled(_ enabled: Bool) {
|
||||
tempoEnabled = enabled
|
||||
guard !enabled else { return }
|
||||
guard !enabled else {
|
||||
// Re-enabling: bring every tempo-synced parameter back in line with the current tempo.
|
||||
applyTempoSyncToAllPedals()
|
||||
return
|
||||
}
|
||||
for pedal: Pedal in allPedals() {
|
||||
for pedalSwitch: PedalSwitch in pedal.effectSwitches where pedalSwitch.tempoDependent {
|
||||
if let off: PedalSwitch.Option = pedalSwitch.options.first {
|
||||
@@ -149,6 +153,27 @@ public final class ShoeGaze {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sets the shared clock's tempo and recomputes every tempo-synced pedal parameter to match.
|
||||
/// Route **all** BPM changes (stepper, tap tempo, MIDI) through here so synced delay times and
|
||||
/// LFO rates follow the tempo. Recompute is skipped while tempo is disabled.
|
||||
///
|
||||
/// - Parameter bpm: The new tempo in beats per minute. A non-positive value is ignored (the
|
||||
/// clock requires a positive tempo); callers that also want an upper bound clamp before calling.
|
||||
public func setBpm(_ bpm: Double) {
|
||||
guard bpm > 0 else { return }
|
||||
clock.bpm = bpm
|
||||
guard tempoEnabled else { return }
|
||||
applyTempoSyncToAllPedals()
|
||||
}
|
||||
|
||||
/// Recomputes every tempo-synced parameter on every live pedal from the current tempo.
|
||||
/// `internal` so the preset-restore path (`ShoeGaze+Preset.swift`) can re-sync after a rig load.
|
||||
internal func applyTempoSyncToAllPedals() {
|
||||
for pedal: Pedal in allPedals() {
|
||||
pedal.applyTempoSync()
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Scope state
|
||||
|
||||
/// Scope tap over the hardware input + output buses, feeding the debug scope view.
|
||||
@@ -276,6 +301,9 @@ public final class ShoeGaze {
|
||||
inputBusIndex: testBus.index,
|
||||
outputBusIndex: board.headBus.index
|
||||
)
|
||||
// Prime the mute gain before splicing the node in, so its very first render block
|
||||
// reflects the current mute state with no ramp (see `primeInputMute`).
|
||||
primeInputMute(tap.inputMuteNode, muted: inputMuted)
|
||||
try engine.add(tap, position: NodePosition.after(source))
|
||||
testLoopTaps.append(tap)
|
||||
// Record the tap as the head input node so PedalBoard.add(_:) can chain the first
|
||||
@@ -291,6 +319,8 @@ public final class ShoeGaze {
|
||||
inputBusIndex: hardwareInputBusIndex,
|
||||
outputBusIndex: board.headBus.index
|
||||
)
|
||||
// Prime the mute gain before splicing the node in (see `primeInputMute`).
|
||||
primeInputMute(passThrough.inputMuteNode, muted: inputMuted)
|
||||
try engine.add(passThrough)
|
||||
inputPassThroughs.append(passThrough)
|
||||
board.headInputNode = passThrough
|
||||
@@ -408,6 +438,13 @@ public final class ShoeGaze {
|
||||
/// `true` when the rig output is muted (hard-silenced, not bypassed). Survives a rebuild.
|
||||
public private(set) var rigMuted: Bool = false
|
||||
|
||||
/// `true` when the **input** feeding every board is muted — the incoming guitar / mic signal,
|
||||
/// distinct from ``rigMuted`` (the output). Defaults `false` (audible); the app re-asserts it
|
||||
/// muted on each user engine start (see `EngineConfigView`) so a fresh start is silent until the
|
||||
/// player un-mutes, without forcing silence on headless / offline library use. See
|
||||
/// ``setInputMuted(_:)``.
|
||||
public private(set) var inputMuted: Bool = false
|
||||
|
||||
/// Identities of boards currently in per-board full bypass. Observable so UI toggles refresh;
|
||||
/// authoritative bypass value lives on each board's `boardBypassNode`. Transient (not persisted).
|
||||
public private(set) var bypassedBoards: Set<ObjectIdentifier> = []
|
||||
@@ -560,6 +597,68 @@ public final class ShoeGaze {
|
||||
setRigMuted(!rigMuted)
|
||||
}
|
||||
|
||||
/// Mutes or un-mutes the **input** feeding every board — the incoming guitar / mic signal,
|
||||
/// distinct from the rig-output ``setRigMuted(_:)``. Applied to every board's input writer
|
||||
/// (test-loop tap or hardware pass-through) as an abrupt kill-switch gate (unlagged, so a
|
||||
/// muted input is exactly silent — see the note in `HardwareInputPassThrough.build()`).
|
||||
///
|
||||
/// The app re-asserts this muted on each user engine start (see `EngineConfigView`) so a fresh
|
||||
/// start is silent until the player un-mutes — preventing accidental input noise.
|
||||
///
|
||||
/// - Parameter muted: `true` to silence the input, `false` to let it through.
|
||||
public func setInputMuted(_ muted: Bool) {
|
||||
// Seed the ramp start only while the engine is stopped: then the next Start renders the new
|
||||
// mute state from block zero with no audible→muted (or muted→audible) ramp — which is exactly
|
||||
// what "muted on Start" needs. While the engine is running, seeding `previousOutputValue`
|
||||
// would race the RT thread; leaving it lets the one-block ramp act as a click-free toggle.
|
||||
let seedRamp: Bool = !engine.isRunning
|
||||
for tap: TestLoopTap in testLoopTaps {
|
||||
setInputMuteGain(tap.inputMuteNode, muted: muted, seedRamp: seedRamp)
|
||||
}
|
||||
for passThrough: HardwareInputPassThrough in inputPassThroughs {
|
||||
setInputMuteGain(passThrough.inputMuteNode, muted: muted, seedRamp: seedRamp)
|
||||
}
|
||||
inputMuted = muted
|
||||
}
|
||||
|
||||
/// Primes a freshly-created input-mute node (not yet spliced into the graph) to the given mute
|
||||
/// state so its first render block has no ramp. Race-free because the node is not yet evaluated
|
||||
/// by the RT thread. See ``setInputMuteGain(_:muted:seedRamp:)``.
|
||||
private func primeInputMute(_ node: UIParamNode, muted: Bool) {
|
||||
setInputMuteGain(node, muted: muted, seedRamp: true)
|
||||
}
|
||||
|
||||
/// Sets an input node's mute gain. `update` stores the atomic target the RT thread ramps toward
|
||||
/// from `previousOutputValue`; that seed is only advanced by RT render, so `update` alone leaves
|
||||
/// a one-block ramp from the node's prior value. When `seedRamp` is `true` (node not yet spliced,
|
||||
/// or engine stopped) we also seed `previousOutputValue` to the target so there is no ramp.
|
||||
private func setInputMuteGain(_ node: UIParamNode, muted: Bool, seedRamp: Bool) {
|
||||
let value: Double = muted ? 1.0 : 0.0
|
||||
node.update(value)
|
||||
if seedRamp { node.previousOutputValue = value }
|
||||
}
|
||||
|
||||
/// Toggles the input mute. See ``setInputMuted(_:)``.
|
||||
public func toggleInputMuted() {
|
||||
setInputMuted(!inputMuted)
|
||||
}
|
||||
|
||||
/// The live mute-gain values of every board input writer (test-loop taps and hardware
|
||||
/// pass-throughs). `1` = muted, `0` = audible. Exposed for tests to confirm the RT nodes are
|
||||
/// actually driven by ``setInputMuted(_:)``, not just the ``inputMuted`` flag.
|
||||
var inputMuteNodeValues: [Double] {
|
||||
testLoopTaps.map { $0.inputMuteNode.value }
|
||||
+ inputPassThroughs.map { $0.inputMuteNode.value }
|
||||
}
|
||||
|
||||
/// The `previousOutputValue` (ramp start) of every board input-mute node. Exposed for tests to
|
||||
/// confirm a stopped-engine mute is *primed* — ramp start equal to the target — so the next
|
||||
/// render can't ramp from the prior value and leak a block. See ``setInputMuteGain(_:muted:seedRamp:)``.
|
||||
var inputMutePreviousValues: [Double] {
|
||||
testLoopTaps.map { $0.inputMuteNode.previousOutputValue }
|
||||
+ inputPassThroughs.map { $0.inputMuteNode.previousOutputValue }
|
||||
}
|
||||
|
||||
/// Removes a single board and its associated input source and output master from
|
||||
/// the engine, then releases the board's buses. The other boards are unaffected.
|
||||
///
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// NoteDivision.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// A rhythmic note value, expressed as a fraction of a bar and measured in quarter-note beats.
|
||||
///
|
||||
/// Used to lock a tempo-syncable pedal parameter (a delay time, an LFO rate) to the shared
|
||||
/// ``ShoeGaze/clock``. The synced period in seconds is `(60 / bpm) * beats`; a delay time uses
|
||||
/// that period directly, an LFO rate uses its inverse (one cycle per division).
|
||||
///
|
||||
/// Cases are ordered longest-first so a stepped selector reads top-to-bottom from slow to fast.
|
||||
public enum NoteDivision: String, Codable, CaseIterable, Sendable {
|
||||
|
||||
/// Whole note — four quarter-note beats.
|
||||
case whole
|
||||
/// Dotted half note — three beats.
|
||||
case dottedHalf
|
||||
/// Half note — two beats.
|
||||
case half
|
||||
/// Dotted quarter note — one and a half beats.
|
||||
case dottedQuarter
|
||||
/// Quarter note — one beat.
|
||||
case quarter
|
||||
/// Dotted eighth note — three-quarters of a beat.
|
||||
case dottedEighth
|
||||
/// Quarter-note triplet — two-thirds of a beat.
|
||||
case quarterTriplet
|
||||
/// Eighth note — half a beat.
|
||||
case eighth
|
||||
/// Eighth-note triplet — one-third of a beat.
|
||||
case eighthTriplet
|
||||
/// Sixteenth note — a quarter of a beat.
|
||||
case sixteenth
|
||||
/// Sixteenth-note triplet — one-sixth of a beat.
|
||||
case sixteenthTriplet
|
||||
|
||||
/// Length of this division in quarter-note beats (a quarter note is `1`).
|
||||
public var beats: Double {
|
||||
switch self {
|
||||
case .whole: return 4.0
|
||||
case .dottedHalf: return 3.0
|
||||
case .half: return 2.0
|
||||
case .dottedQuarter: return 1.5
|
||||
case .quarter: return 1.0
|
||||
case .quarterTriplet: return 2.0 / 3.0
|
||||
case .dottedEighth: return 0.75
|
||||
case .eighth: return 0.5
|
||||
case .eighthTriplet: return 1.0 / 3.0
|
||||
case .sixteenth: return 0.25
|
||||
case .sixteenthTriplet: return 1.0 / 6.0
|
||||
}
|
||||
}
|
||||
|
||||
/// Short label for a selector stop (e.g. `"1/4"`, `"1/8."`, `"1/8T"`).
|
||||
public var label: String {
|
||||
switch self {
|
||||
case .whole: return "1/1"
|
||||
case .dottedHalf: return "1/2."
|
||||
case .half: return "1/2"
|
||||
case .dottedQuarter: return "1/4."
|
||||
case .quarter: return "1/4"
|
||||
case .quarterTriplet: return "1/4T"
|
||||
case .dottedEighth: return "1/8."
|
||||
case .eighth: return "1/8"
|
||||
case .eighthTriplet: return "1/8T"
|
||||
case .sixteenth: return "1/16"
|
||||
case .sixteenthTriplet: return "1/16T"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,6 @@ extension ShoeGaze {
|
||||
|
||||
let averageInterval: TimeInterval = intervals.reduce(0, +) / Double(intervals.count)
|
||||
let secondsPerMinute: Double = 60.0
|
||||
clock.bpm = secondsPerMinute / averageInterval
|
||||
setBpm(secondsPerMinute / averageInterval)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// TempoSync.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Sync state of one tempo-syncable pedal parameter.
|
||||
///
|
||||
/// `.free` leaves the parameter at its stored absolute value (seconds or Hz), controlled by the
|
||||
/// knob as usual. `.division` locks it to a ``NoteDivision`` of the shared ``ShoeGaze/clock`` —
|
||||
/// the value is derived from the current tempo and rewritten whenever the tempo or the division
|
||||
/// changes.
|
||||
public enum TempoSync: Codable, Equatable, Sendable {
|
||||
|
||||
/// Absolute value, knob-controlled. The default for every parameter.
|
||||
case free
|
||||
|
||||
/// Locked to a note division of the live tempo.
|
||||
case division(NoteDivision)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
// TempoSyncRevision.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Observation
|
||||
|
||||
/// An observable revision counter bumped whenever a pedal's ``Pedal/tempoSync`` state changes.
|
||||
///
|
||||
/// ``Pedal/tempoSync`` is a plain dictionary, not observable, so a SwiftUI view showing the sync
|
||||
/// state (the note-division badge) needs a signal to re-render when the state changes through any
|
||||
/// path — the knob's own picker, a preset load, or a lightweight recall. Reading ``value`` inside a
|
||||
/// view body subscribes it; ``Pedal/setSync(_:for:)`` and `Pedal.applyState(_:)` bump it.
|
||||
@Observable
|
||||
public final class TempoSyncRevision {
|
||||
|
||||
/// Incremented on every ``Pedal/tempoSync`` mutation. Its magnitude is meaningless — only the
|
||||
/// change matters, as an invalidation signal for observing views.
|
||||
public internal(set) var value: Int = 0
|
||||
|
||||
/// Creates a revision counter starting at zero.
|
||||
public init() {}
|
||||
|
||||
/// Bumps the counter, invalidating any view observing ``value``.
|
||||
func bump() {
|
||||
value &+= 1
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
// TempoSyncableParam.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import LyrebirdUI
|
||||
|
||||
/// Descriptor for one pedal parameter that can be locked to the tempo.
|
||||
///
|
||||
/// A ``Pedal`` publishes an array of these (via ``Pedal/tempoSyncableParams``) so the shared
|
||||
/// tempo-sync machinery can recompute and rewrite each synced parameter without knowing the
|
||||
/// concrete pedal type. The stable ``key`` doubles as the persistence key in ``PedalState``.
|
||||
public struct TempoSyncableParam {
|
||||
|
||||
/// How the synced period maps onto the parameter's value.
|
||||
public enum Kind {
|
||||
/// A duration in seconds — the value is the synced period `T` directly (delay time).
|
||||
case time
|
||||
/// A frequency in Hz — the value is `1 / T` (one LFO cycle per division).
|
||||
case rate
|
||||
}
|
||||
|
||||
/// Stable identifier for this parameter within its pedal (e.g. `"time"`, `"time1"`, `"rate"`).
|
||||
/// Used as the ``TempoSync`` dictionary key and the persistence key, so it must never change.
|
||||
public let key: String
|
||||
|
||||
/// Short display label, matching the parameter's knob label.
|
||||
public let label: String
|
||||
|
||||
/// The live parameter node the synced value is written to.
|
||||
public let node: UIParamNode
|
||||
|
||||
/// Whether the value is a duration (`.time`) or a frequency (`.rate`, inverse of the period).
|
||||
public let kind: Kind
|
||||
|
||||
/// Inclusive value range the parameter accepts, in its own units. A synced value outside this
|
||||
/// range is clamped (a long division can exceed a delay's maximum buffered time).
|
||||
public let range: ClosedRange<Double>
|
||||
|
||||
/// Creates a tempo-syncable parameter descriptor.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - key: Stable identifier and persistence key. Must be unique within the pedal and stable
|
||||
/// across versions.
|
||||
/// - label: Short display label, matching the knob label.
|
||||
/// - node: The live parameter node (`pedal.$time`, `pedal.$rate`, …).
|
||||
/// - kind: `.time` for a duration, `.rate` for a frequency (inverse of the period).
|
||||
/// - range: Inclusive value range in the parameter's units; the synced value is clamped to it.
|
||||
public init(
|
||||
key: String,
|
||||
label: String,
|
||||
node: UIParamNode,
|
||||
kind: Kind,
|
||||
range: ClosedRange<Double>
|
||||
) {
|
||||
self.key = key
|
||||
self.label = label
|
||||
self.node = node
|
||||
self.kind = kind
|
||||
self.range = range
|
||||
}
|
||||
|
||||
private static let secondsPerMinute: Double = 60.0
|
||||
|
||||
/// The unclamped parameter value for `division` at `bpm`. For `.time` this is the note's period
|
||||
/// in seconds; for `.rate` it is `1 / period` in Hz (one LFO cycle per division).
|
||||
public func rawValue(for division: NoteDivision, bpm: Double) -> Double {
|
||||
let period: Double = (TempoSyncableParam.secondsPerMinute / bpm) * division.beats
|
||||
switch kind {
|
||||
case .time:
|
||||
return period
|
||||
case .rate:
|
||||
return period > 0 ? 1.0 / period : range.upperBound
|
||||
}
|
||||
}
|
||||
|
||||
/// The value actually written for `division` at `bpm`, plus whether it had to be clamped to the
|
||||
/// parameter's range. A clamped result means the division can't be represented accurately at this
|
||||
/// tempo (e.g. a whole note longer than the maximum delay time) — the UI disables/flags it.
|
||||
public func value(for division: NoteDivision, bpm: Double) -> (value: Double, clamped: Bool) {
|
||||
let raw: Double = rawValue(for: division, bpm: bpm)
|
||||
let clampedValue: Double = min(max(raw, range.lowerBound), range.upperBound)
|
||||
return (clampedValue, clampedValue != raw)
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,12 @@ final class TunerTap: SynthesizerBase {
|
||||
)
|
||||
let capture: TunerPitchCapture = TunerPitchCapture(input: filtered)
|
||||
pitchCapture = capture
|
||||
output(bus: scratchControlBus, source: capture)
|
||||
// Route through `controlOutput` (Out.Control → control-bus memory), NOT `output`
|
||||
// (Out.Audio → *audio*-bus memory at the same index). The scratch bus exists only to give
|
||||
// the engine a reason to evaluate the capture generator; writing the capture's pitch signal
|
||||
// to an audio bus at the control-bus index would land it on a hardware output channel (a low
|
||||
// control index collides with the output buses) — audible as crackle while the pitch is
|
||||
// unstable — and, because this tap runs after `mainGroup`, would bypass the rig mute.
|
||||
controlOutput(bus: scratchControlBus, source: capture)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -51,6 +51,10 @@ public struct BoardFlowView: View {
|
||||
private static let splitToggleWidth: CGFloat = 200
|
||||
private static let emptyLaneOpacity: Double = 0.4
|
||||
|
||||
/// Extra height the content may exceed the viewport by before vertical scrolling turns on, so a
|
||||
/// sub-pixel rounding difference doesn't flip the axis set on and off.
|
||||
private static let verticalScrollSlack: CGFloat = 1
|
||||
|
||||
/// Signal-path accent (the pink/magenta connector colour).
|
||||
private static let flowColor: Color = Color(red: 0.92, green: 0.32, blue: 0.70)
|
||||
|
||||
@@ -62,6 +66,10 @@ public struct BoardFlowView: View {
|
||||
/// Identifier of the lane/card currently hovered as a drop target, for highlight.
|
||||
@State private var dropTarget: String?
|
||||
|
||||
/// Measured height of the flow content, used to enable vertical scrolling only when the stacked
|
||||
/// lanes exceed the viewport height (tall parallel splits). Otherwise scrolling stays horizontal.
|
||||
@State private var contentHeight: CGFloat = 0
|
||||
|
||||
public init(shoeGaze: ShoeGaze, boardIndex: Int) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self.boardIndex = boardIndex
|
||||
@@ -81,19 +89,55 @@ public struct BoardFlowView: View {
|
||||
|
||||
private func flow(board: PedalBoard) -> some View {
|
||||
let stages: [StageModel] = stageModels(board: board)
|
||||
return ScrollView([.horizontal, .vertical], showsIndicators: true) {
|
||||
HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) {
|
||||
endpoint("IN")
|
||||
ForEach(stages) { stage in
|
||||
connector(stereo: stage.stereoIn)
|
||||
stageView(stage)
|
||||
return GeometryReader { proxy in
|
||||
let viewportHeight: CGFloat = proxy.size.height
|
||||
// Lock to horizontal, adding the vertical axis only when the chain is taller than the
|
||||
// viewport (deep parallel splits) so it can be reached instead of clipped.
|
||||
let axes: Axis.Set = contentHeight > viewportHeight + BoardFlowView.verticalScrollSlack
|
||||
? [.horizontal, .vertical]
|
||||
: .horizontal
|
||||
ScrollView(axes, showsIndicators: true) {
|
||||
// The spacers centre the chain vertically when it is shorter than the viewport; when
|
||||
// it overflows, the min-height floor is already exceeded so they collapse to zero and
|
||||
// the chain scrolls. Pedals keep their intrinsic height either way — the window no
|
||||
// longer stretches them.
|
||||
VStack(spacing: 0) {
|
||||
Spacer(minLength: 0)
|
||||
chainRow(board: board, stages: stages)
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
connector(stereo: board.width == 2)
|
||||
endpoint(board.width == 2 ? "OUT ⇒" : "OUT")
|
||||
.frame(minHeight: viewportHeight)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
.onPreferenceChange(BoardFlowContentHeightKey.self) { height in
|
||||
contentHeight = height
|
||||
}
|
||||
.padding(.vertical, BoardFlowView.regionPadding)
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity)
|
||||
}
|
||||
|
||||
/// The left→right chain of endpoints, connectors and stage cards. Reports its own intrinsic
|
||||
/// height through `BoardFlowContentHeightKey` so `flow` can decide whether vertical scrolling is
|
||||
/// needed. Each pedal sizes to its own content, so the row is only as tall as its tallest card —
|
||||
/// a short pedal stays short next to a tall one.
|
||||
private func chainRow(board: PedalBoard, stages: [StageModel]) -> some View {
|
||||
HStack(alignment: .center, spacing: BoardFlowView.stageSpacing) {
|
||||
endpoint("IN")
|
||||
ForEach(stages) { stage in
|
||||
connector(stereo: stage.stereoIn)
|
||||
stageView(stage)
|
||||
}
|
||||
connector(stereo: board.width == 2)
|
||||
endpoint(board.width == 2 ? "OUT ⇒" : "OUT")
|
||||
}
|
||||
.padding(.vertical, BoardFlowView.regionPadding)
|
||||
.background(
|
||||
GeometryReader { contentProxy in
|
||||
Color.clear.preference(
|
||||
key: BoardFlowContentHeightKey.self,
|
||||
value: contentProxy.size.height
|
||||
)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
// MARK: - Stage model
|
||||
@@ -531,3 +575,12 @@ private extension String {
|
||||
return String(dropFirst(prefix.count))
|
||||
}
|
||||
}
|
||||
|
||||
/// Carries the measured height of the flow content up to `BoardFlowView`, which compares it to the
|
||||
/// viewport height to decide whether the vertical scroll axis is needed.
|
||||
private struct BoardFlowContentHeightKey: PreferenceKey {
|
||||
static let defaultValue: CGFloat = 0
|
||||
static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) {
|
||||
value = max(value, nextValue())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,253 @@
|
||||
// ControlMappingStrip.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
/// The rig's current control map, injected into the board view tree so each ``PedalView`` can draw
|
||||
/// its own mapping strip without every call site having to thread the map through. `nil` when the
|
||||
/// rig has no bindings. Set once high in the builder (`builderColumn`) from the observable
|
||||
/// `ShoeGaze.midiMap`, so learning or clearing a binding updates every strip live.
|
||||
private struct ControlMappingMapKey: EnvironmentKey {
|
||||
static let defaultValue: MIDIMap? = nil
|
||||
}
|
||||
|
||||
extension EnvironmentValues {
|
||||
/// The rig's control map for in-context mapping badges, or `nil` when unset / empty.
|
||||
var controlMappingMap: MIDIMap? {
|
||||
get { self[ControlMappingMapKey.self] }
|
||||
set { self[ControlMappingMapKey.self] = newValue }
|
||||
}
|
||||
}
|
||||
|
||||
/// The kind of trigger a mapping badge represents, and its colour.
|
||||
enum MappingBadgeKind {
|
||||
case programChange
|
||||
case controlChange
|
||||
case key
|
||||
|
||||
/// The badge fill colour (matches the mapping-sheet chip colours).
|
||||
var fill: Color {
|
||||
switch self {
|
||||
case .programChange: return MappingBadge.pcFill
|
||||
case .controlChange: return MappingBadge.ccFill
|
||||
case .key: return MappingBadge.keyFill
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One coloured pill — e.g. `CC11`, `PC3`, `⇧B` — marking a control's binding.
|
||||
struct MappingBadge: View {
|
||||
|
||||
// `nonisolated` so the nonisolated `MappingBadgeKind.fill` can read them — a SwiftUI `View`'s
|
||||
// statics are otherwise main-actor-isolated. The values are immutable `Sendable` colours.
|
||||
nonisolated static let pcFill: Color = Color(red: 0.11, green: 0.37, blue: 0.65)
|
||||
nonisolated static let ccFill: Color = Color(red: 0.33, green: 0.29, blue: 0.72)
|
||||
nonisolated static let keyFill: Color = Color(red: 0.73, green: 0.46, blue: 0.09)
|
||||
|
||||
private static let fontSize: CGFloat = 9
|
||||
private static let paddingH: CGFloat = 5
|
||||
private static let paddingV: CGFloat = 1
|
||||
private static let cornerRadius: CGFloat = 4
|
||||
|
||||
private let kind: MappingBadgeKind
|
||||
private let text: String
|
||||
|
||||
/// Creates a mapping badge.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - kind: The trigger kind (drives the fill colour).
|
||||
/// - text: The badge label (e.g. `"CC11"`, `"PC3"`, `"⇧B"`).
|
||||
init(kind: MappingBadgeKind, text: String) {
|
||||
self.kind = kind
|
||||
self.text = text
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
Text(text)
|
||||
.font(.system(size: MappingBadge.fontSize, weight: .medium))
|
||||
.foregroundStyle(Color.white)
|
||||
.padding(.horizontal, MappingBadge.paddingH)
|
||||
.padding(.vertical, MappingBadge.paddingV)
|
||||
.background(
|
||||
RoundedRectangle(cornerRadius: MappingBadge.cornerRadius)
|
||||
.fill(kind.fill)
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// A one-line legend keying the badge colours (`PC` footswitch, `CC` expression, `KEY` letter key),
|
||||
/// shown once above the board canvas.
|
||||
struct ControlMappingLegend: View {
|
||||
|
||||
private static let itemSpacing: CGFloat = 10
|
||||
private static let pairSpacing: CGFloat = 5
|
||||
private static let fontSize: CGFloat = 11
|
||||
|
||||
var body: some View {
|
||||
HStack(spacing: ControlMappingLegend.itemSpacing) {
|
||||
legendItem(kind: .programChange, badge: "PC", caption: "footswitch")
|
||||
legendItem(kind: .controlChange, badge: "CC", caption: "expression")
|
||||
legendItem(kind: .key, badge: "KEY", caption: "letter key")
|
||||
}
|
||||
.foregroundStyle(Color.white.opacity(0.55))
|
||||
}
|
||||
|
||||
private func legendItem(kind: MappingBadgeKind, badge: String, caption: String) -> some View {
|
||||
HStack(spacing: ControlMappingLegend.pairSpacing) {
|
||||
MappingBadge(kind: kind, text: badge)
|
||||
Text(caption)
|
||||
.font(.system(size: ControlMappingLegend.fontSize))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One row of a pedal's mapping strip: a control label and the badges bound to it.
|
||||
struct PedalMappingRow: Identifiable {
|
||||
let id: String
|
||||
let label: String
|
||||
let badges: [PedalMappingBadge]
|
||||
}
|
||||
|
||||
/// A single badge within a ``PedalMappingRow``.
|
||||
struct PedalMappingBadge: Identifiable {
|
||||
let id: String
|
||||
let kind: MappingBadgeKind
|
||||
let text: String
|
||||
}
|
||||
|
||||
/// The per-pedal mapping strip: a compact footer listing this pedal's mapped controls and the
|
||||
/// footswitch / expression / key bindings driving them. Renders nothing when the pedal has no
|
||||
/// mappings, so unmapped pedals gain no height.
|
||||
struct PedalMappingStrip: View {
|
||||
|
||||
private static let rowSpacing: CGFloat = 3
|
||||
private static let labelFontSize: CGFloat = 10
|
||||
private static let badgeSpacing: CGFloat = 4
|
||||
private static let topPadding: CGFloat = 6
|
||||
private static let dividerOpacity: Double = 0.18
|
||||
|
||||
private let rows: [PedalMappingRow]
|
||||
|
||||
/// Creates a mapping strip for a pedal against the current map.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - pedal: The pedal whose bindings are listed.
|
||||
/// - map: The rig's control map, or `nil` when there are no bindings.
|
||||
init(pedal: Pedal, map: MIDIMap?) {
|
||||
self.rows = PedalMappingStrip.rows(for: pedal, in: map)
|
||||
}
|
||||
|
||||
var body: some View {
|
||||
if rows.isEmpty {
|
||||
EmptyView()
|
||||
} else {
|
||||
VStack(spacing: PedalMappingStrip.rowSpacing) {
|
||||
Divider().overlay(Color.white.opacity(PedalMappingStrip.dividerOpacity))
|
||||
ForEach(rows) { row in
|
||||
HStack(spacing: PedalMappingStrip.badgeSpacing) {
|
||||
Text(row.label)
|
||||
.font(.system(size: PedalMappingStrip.labelFontSize))
|
||||
.foregroundStyle(Color.white.opacity(0.6))
|
||||
Spacer(minLength: 0)
|
||||
ForEach(row.badges) { badge in
|
||||
MappingBadge(kind: badge.kind, text: badge.text)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
.padding(.top, PedalMappingStrip.topPadding)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Row assembly
|
||||
|
||||
/// Builds the strip rows for a pedal from the map: one row per mapped CC control, one for a
|
||||
/// mapped bypass (footswitch + key), and one per mapped looper transport action.
|
||||
static func rows(for pedal: Pedal, in map: MIDIMap?) -> [PedalMappingRow] {
|
||||
guard let map: MIDIMap = map else { return [] }
|
||||
let pedalID: UUID = pedal.id
|
||||
var rows: [PedalMappingRow] = []
|
||||
|
||||
// Continuous controls driven by an expression pedal (CC).
|
||||
for controlPair: (offset: Int, element: PedalControl) in pedal.ccMappableControls.enumerated() {
|
||||
let target: MIDIMap.CCTarget = .pedalControl(
|
||||
pedalID: pedalID, controlIndex: controlPair.offset,
|
||||
pedalNameHint: nil, controlLabelHint: nil)
|
||||
guard let cc: MIDIMap.CCBinding = map.ccs.first(where: { $0.target.addresses(target) })
|
||||
else { continue }
|
||||
rows.append(PedalMappingRow(
|
||||
id: "cc-\(controlPair.offset)",
|
||||
label: controlPair.element.label,
|
||||
badges: [PedalMappingBadge(id: "cc", kind: .controlChange, text: "CC\(cc.controller)")]))
|
||||
}
|
||||
|
||||
// Bypass — a footswitch and/or a key.
|
||||
let bypassBadges: [PedalMappingBadge] = badges(for: .pedalBypass(pedalID: pedalID), in: map)
|
||||
if bypassBadges.isEmpty == false {
|
||||
rows.append(PedalMappingRow(id: "bypass", label: "Bypass", badges: bypassBadges))
|
||||
}
|
||||
|
||||
// Looper transport actions.
|
||||
if pedal is LooperPedal {
|
||||
for kind: MIDIMap.PedalActionKind in loopedActionOrder {
|
||||
let action: MIDIMap.Action = .pedalAction(pedalID: pedalID, kind: kind)
|
||||
let actionBadges: [PedalMappingBadge] = badges(for: action, in: map)
|
||||
if actionBadges.isEmpty { continue }
|
||||
rows.append(PedalMappingRow(
|
||||
id: "la-\(looperActionName(kind))",
|
||||
label: looperActionName(kind),
|
||||
badges: actionBadges))
|
||||
}
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
|
||||
/// The footswitch (PC) and key badges bound to a toggle action, in that order.
|
||||
private static func badges(for action: MIDIMap.Action, in map: MIDIMap) -> [PedalMappingBadge] {
|
||||
var badges: [PedalMappingBadge] = []
|
||||
if let pc: MIDIMap.SwitchBinding = map.switches.first(where: { $0.action == action }) {
|
||||
badges.append(PedalMappingBadge(id: "pc", kind: .programChange, text: "PC\(pc.program)"))
|
||||
}
|
||||
if let key: MIDIMap.KeyBinding = map.keys.first(where: { $0.action == action }) {
|
||||
badges.append(PedalMappingBadge(id: "key", kind: .key, text: keyLabel(key)))
|
||||
}
|
||||
return badges
|
||||
}
|
||||
|
||||
/// A key binding formatted with modifier glyphs (macOS order: control, option, shift).
|
||||
private static func keyLabel(_ binding: MIDIMap.KeyBinding) -> String {
|
||||
var prefix: String = ""
|
||||
if binding.modifiers.contains(.control) { prefix += "⌃" }
|
||||
if binding.modifiers.contains(.option) { prefix += "⌥" }
|
||||
if binding.modifiers.contains(.shift) { prefix += "⇧" }
|
||||
return prefix + binding.key.uppercased()
|
||||
}
|
||||
|
||||
/// The looper transport actions in the order they appear in the mapping sheet.
|
||||
private static let loopedActionOrder: [MIDIMap.PedalActionKind] = [
|
||||
.looperRecordStop, .looperOverdubToggle, .looperLoopToggle, .looperStop,
|
||||
.looperCueStop, .looperReverse, .looperSyncToggle, .looperReset,
|
||||
.looperTrack(index: 0), .looperTrack(index: 1),
|
||||
.looperTrack(index: 2), .looperTrack(index: 3),
|
||||
]
|
||||
|
||||
/// A short user-facing name for a looper transport action.
|
||||
private static func looperActionName(_ kind: MIDIMap.PedalActionKind) -> String {
|
||||
switch kind {
|
||||
case .looperRecordStop: return "Record"
|
||||
case .looperOverdubToggle: return "Overdub"
|
||||
case .looperLoopToggle: return "Loop"
|
||||
case .looperStop: return "Stop"
|
||||
case .looperCueStop: return "Cue Stop"
|
||||
case .looperReverse: return "Reverse"
|
||||
case .looperSyncToggle: return "Sync"
|
||||
case .looperReset: return "Reset"
|
||||
case .looperTrack(let index): return "Track \(LooperPedal.trackLabel(index))"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -193,6 +193,12 @@ public struct EngineConfigView: View {
|
||||
)
|
||||
}
|
||||
}
|
||||
// A deliberate user Start comes up with the input muted so accidental noise can't leak
|
||||
// the instant the engine spins up. Set it BEFORE start (engine is stopped here, so the
|
||||
// gain is seeded with no ramp) — asserting it after start would leave the first render
|
||||
// blocks unmuted. Transient stop/start-around-rebuild paths call `engine.start()`
|
||||
// directly and are unaffected — they preserve the current mute state.
|
||||
shoeGaze.setInputMuted(true)
|
||||
try shoeGaze.engine.start()
|
||||
} catch {
|
||||
handleStartError(error)
|
||||
|
||||
@@ -40,6 +40,9 @@ public struct HelpView: View {
|
||||
steps: [
|
||||
"Set the sample Rate and the input/output channel counts in the top-right controls.",
|
||||
"Press Start to run the engine; press again to Stop. Most controls stay live while running.",
|
||||
"Input starts MUTED every time you press Start — a safety default so nothing squeals "
|
||||
+ "the instant the engine spins up. The Input Mute button (microphone icon, left of "
|
||||
+ "the Start button) pulses red while muted; click it to let your instrument through.",
|
||||
"Bypass Rig compares your sound with and without the whole pedalboard.",
|
||||
]
|
||||
)
|
||||
@@ -63,11 +66,17 @@ public struct HelpView: View {
|
||||
topicSection(
|
||||
icon: "waveform",
|
||||
title: "Choosing an Input",
|
||||
intro: "Pick what feeds the board.",
|
||||
intro: "Pick what feeds the board, and mute it when you need silence.",
|
||||
steps: [
|
||||
"Input ▸ Test Loop plays a built-in phrase, so you can hear the rig with no guitar connected.",
|
||||
"Input ▸ In 0 (Live Input on iOS) uses your audio interface or mic. iOS asks for "
|
||||
+ "microphone access the first time you enable it.",
|
||||
+ "microphone access the first time you enable it. New rigs open on In 0.",
|
||||
"Input Mute (microphone icon, left of Start) is a hard gate on the incoming signal — "
|
||||
+ "distinct from Rig Mute, which silences the OUTPUT. Use it to stop feedback or "
|
||||
+ "handling noise while you set up. It pulses red while muted, and re-arms muted on "
|
||||
+ "every Start.",
|
||||
"The input mute is MIDI-mappable — bind it to a footswitch or key in MIDI / Control "
|
||||
+ "Mapping for a hands-free panic mute of your instrument.",
|
||||
]
|
||||
)
|
||||
topicSection(
|
||||
@@ -109,8 +118,9 @@ public struct HelpView: View {
|
||||
"Tracks A–D: tap a dot to select the track Record overdubs into; tap a selected, "
|
||||
+ "recorded track again to mute or unmute it.",
|
||||
"MIDI: Record, Stop, Cue Stop, Reverse, Sync, Reset, and each Track A–D map as "
|
||||
+ "footswitch (Program Change) actions in MIDI Mapping; the Crossfade / Playback / "
|
||||
+ "Overdub / Feedback knobs sweep from an expression pedal like any pedal knob.",
|
||||
+ "footswitch (Program Change) or key actions in MIDI / Control Mapping; the "
|
||||
+ "Crossfade / Playback / Overdub / Feedback knobs sweep from an expression pedal "
|
||||
+ "like any pedal knob.",
|
||||
]
|
||||
)
|
||||
topicSection(
|
||||
@@ -136,13 +146,20 @@ public struct HelpView: View {
|
||||
)
|
||||
topicSection(
|
||||
icon: "pianokeys",
|
||||
title: "MIDI Control",
|
||||
intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) for hands-free control.",
|
||||
title: "MIDI / Control",
|
||||
intro: "Map a MIDI foot controller (e.g. a Behringer FCB1010) or your computer keyboard for "
|
||||
+ "hands-free control.",
|
||||
steps: [
|
||||
"The keys icon in the top bar lights green when a device is connected. Tap it to open MIDI Mapping.",
|
||||
"Switches (Program Change): footswitches toggle Rig Bypass, All Boards, and each board's "
|
||||
+ "Solo / Audible / Bypass or a pedal's bypass. Tap Learn, then press the footswitch. "
|
||||
+ "One switch can drive several actions at once — a scene.",
|
||||
"The keys icon in the top bar lights green when a device is connected. Tap it to open "
|
||||
+ "MIDI / Control Mapping.",
|
||||
"Switches: footswitches and letter keys toggle Rig Bypass, Rig Mute, Input Mute, All "
|
||||
+ "Boards, and each board's Solo / Audible / Bypass or a pedal's bypass. Tap PC then "
|
||||
+ "press a footswitch, or Key then press a key. One switch or key can drive several "
|
||||
+ "actions at once — a scene.",
|
||||
"Keys fire only when you're not typing — while a text field (like a rig name) is focused, "
|
||||
+ "letters go to the field, not to your mappings.",
|
||||
"Hold Shift, Control, or Option while learning to bind a modified key — a and ⇧a are "
|
||||
+ "separate triggers. Command is reserved for the menu shortcuts.",
|
||||
"Expression (Control Change): an expression pedal sweeps any pedal knob or slider, or a "
|
||||
+ "board's Level. Tap Learn, then move the pedal. Invert reverses the sweep — map one "
|
||||
+ "CC to two controls and invert one for a crossfade.",
|
||||
|
||||
@@ -22,6 +22,7 @@ public struct MIDIMappingSheet: View {
|
||||
private static let sheetMinWidth: CGFloat = 460
|
||||
private static let sheetMinHeight: CGFloat = 520
|
||||
private static let rowVerticalPadding: CGFloat = 2
|
||||
private static let switchRowControlSpacing: CGFloat = 8
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
@@ -49,7 +50,7 @@ public struct MIDIMappingSheet: View {
|
||||
switchesSection
|
||||
expressionSection
|
||||
}
|
||||
.navigationTitle("MIDI Mapping")
|
||||
.navigationTitle("MIDI / Control Mapping")
|
||||
.toolbar {
|
||||
ToolbarItem(placement: .confirmationAction) {
|
||||
Button("Done") {
|
||||
@@ -100,6 +101,7 @@ public struct MIDIMappingSheet: View {
|
||||
var rows: [SwitchRowModel] = [
|
||||
SwitchRowModel(id: "sw-rig", action: .rigBypass, label: "Rig Bypass"),
|
||||
SwitchRowModel(id: "sw-mute", action: .rigMute, label: "Rig Mute"),
|
||||
SwitchRowModel(id: "sw-input-mute", action: .inputMute, label: "Input Mute"),
|
||||
SwitchRowModel(id: "sw-all", action: .allBoards, label: "All Boards On"),
|
||||
]
|
||||
for board: PedalBoard in shoeGaze.boards {
|
||||
@@ -174,30 +176,37 @@ public struct MIDIMappingSheet: View {
|
||||
// MARK: - Switches (Program Change)
|
||||
|
||||
private var switchesSection: some View {
|
||||
Section("Switches (Program Change)") {
|
||||
Section("Switches (footswitch / key)") {
|
||||
ForEach(switchRowModels) { row in
|
||||
switchRow(row)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A switch row carries two independent trigger sources for one toggle action: a MIDI Program
|
||||
/// Change (footswitch) and a computer key. Each has its own learn / clear; the detail line
|
||||
/// summarises whichever are bound, or the "Listening…" prompt for the armed source.
|
||||
private func switchRow(_ row: SwitchRowModel) -> some View {
|
||||
let isArmed: Bool = controller.learnTarget == .action(row.action)
|
||||
let binding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
|
||||
return HStack {
|
||||
let isArmedPC: Bool = controller.learnTarget == .action(row.action)
|
||||
let isArmedKey: Bool = controller.learnTarget == .key(row.action)
|
||||
let pcBinding: MIDIMap.SwitchBinding? = controller.switchBinding(for: row.action)
|
||||
let keyBinding: MIDIMap.KeyBinding? = controller.keyBinding(for: row.action)
|
||||
let isArmed: Bool = isArmedPC || isArmedKey
|
||||
return HStack(spacing: MIDIMappingSheet.switchRowControlSpacing) {
|
||||
VStack(alignment: .leading, spacing: 1) {
|
||||
Text(row.label)
|
||||
Text(switchBindingLabel(isArmed: isArmed, binding: binding))
|
||||
Text(switchBindingLabel(isArmedPC: isArmedPC, isArmedKey: isArmedKey,
|
||||
pc: pcBinding, key: keyBinding))
|
||||
.font(.caption)
|
||||
.foregroundStyle(isArmed ? Color.orange : .secondary)
|
||||
}
|
||||
Spacer()
|
||||
if binding != nil {
|
||||
Button("Clear") { controller.clearSwitchBinding(for: row.action) }
|
||||
if pcBinding != nil {
|
||||
Button("Clear PC") { controller.clearSwitchBinding(for: row.action) }
|
||||
.buttonStyle(.borderless)
|
||||
}
|
||||
Button(isArmed ? "Cancel" : "Learn") {
|
||||
if isArmed {
|
||||
Button(isArmedPC ? "Cancel" : "PC") {
|
||||
if isArmedPC {
|
||||
controller.cancelLearn()
|
||||
} else {
|
||||
controller.armSwitchLearn(row.action)
|
||||
@@ -205,15 +214,50 @@ public struct MIDIMappingSheet: View {
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.orange)
|
||||
if keyBinding != nil {
|
||||
Button("Clear Key") { controller.clearKeyBinding(for: row.action) }
|
||||
.buttonStyle(.borderless)
|
||||
}
|
||||
Button(isArmedKey ? "Cancel" : "Key") {
|
||||
if isArmedKey {
|
||||
controller.cancelLearn()
|
||||
} else {
|
||||
controller.armKeyLearn(row.action)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(.orange)
|
||||
}
|
||||
.padding(.vertical, MIDIMappingSheet.rowVerticalPadding)
|
||||
}
|
||||
|
||||
private func switchBindingLabel(isArmed: Bool, binding: MIDIMap.SwitchBinding?) -> String {
|
||||
if isArmed { return "Listening — press a footswitch…" }
|
||||
guard let binding: MIDIMap.SwitchBinding = binding else { return "Unassigned" }
|
||||
let channelText: String = binding.channel.map { " · ch \($0 + 1)" } ?? ""
|
||||
return "PC \(binding.program)\(channelText)"
|
||||
private func switchBindingLabel(
|
||||
isArmedPC: Bool,
|
||||
isArmedKey: Bool,
|
||||
pc: MIDIMap.SwitchBinding?,
|
||||
key: MIDIMap.KeyBinding?
|
||||
) -> String {
|
||||
if isArmedPC { return "Listening — press a footswitch…" }
|
||||
if isArmedKey { return "Listening — press a key…" }
|
||||
var parts: [String] = []
|
||||
if let pc: MIDIMap.SwitchBinding = pc {
|
||||
let channelText: String = pc.channel.map { " · ch \($0 + 1)" } ?? ""
|
||||
parts.append("PC \(pc.program)\(channelText)")
|
||||
}
|
||||
if let key: MIDIMap.KeyBinding = key {
|
||||
parts.append("Key \(keyLabel(key))")
|
||||
}
|
||||
return parts.isEmpty ? "Unassigned" : parts.joined(separator: " · ")
|
||||
}
|
||||
|
||||
/// A key binding formatted with its modifier glyphs, e.g. `A`, `⇧A`, `⌃A` (macOS modifier order:
|
||||
/// control, option, shift).
|
||||
private func keyLabel(_ binding: MIDIMap.KeyBinding) -> String {
|
||||
var prefix: String = ""
|
||||
if binding.modifiers.contains(.control) { prefix += "⌃" }
|
||||
if binding.modifiers.contains(.option) { prefix += "⌥" }
|
||||
if binding.modifiers.contains(.shift) { prefix += "⇧" }
|
||||
return prefix + binding.key.uppercased()
|
||||
}
|
||||
|
||||
// MARK: - Expression (CC)
|
||||
|
||||
@@ -0,0 +1,244 @@
|
||||
// NoteGlyphView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdShoeGaze
|
||||
|
||||
// MARK: - Notation spec
|
||||
|
||||
/// The notation elements that make up one ``NoteDivision`` glyph. Derived purely from the division;
|
||||
/// consumed by ``NoteGlyphView`` to draw the note.
|
||||
private struct NoteGlyphSpec {
|
||||
|
||||
/// `true` for a solid notehead (quarter and shorter), `false` for an open ring (whole, half).
|
||||
let filledHead: Bool
|
||||
/// `true` when the note has a vertical stem (everything except the whole note).
|
||||
let hasStem: Bool
|
||||
/// Number of flags on the stem (`0` = quarter/half, `1` = eighth, `2` = sixteenth).
|
||||
let flags: Int
|
||||
/// `true` for a dotted value — adds an augmentation dot right of the head.
|
||||
let dotted: Bool
|
||||
/// `true` for a triplet — adds a bracket with a "3" above the note.
|
||||
let triplet: Bool
|
||||
|
||||
init(_ division: NoteDivision) {
|
||||
switch division {
|
||||
case .whole:
|
||||
self.init(filledHead: false, hasStem: false, flags: 0, dotted: false, triplet: false)
|
||||
case .dottedHalf:
|
||||
self.init(filledHead: false, hasStem: true, flags: 0, dotted: true, triplet: false)
|
||||
case .half:
|
||||
self.init(filledHead: false, hasStem: true, flags: 0, dotted: false, triplet: false)
|
||||
case .dottedQuarter:
|
||||
self.init(filledHead: true, hasStem: true, flags: 0, dotted: true, triplet: false)
|
||||
case .quarter:
|
||||
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: false)
|
||||
case .dottedEighth:
|
||||
self.init(filledHead: true, hasStem: true, flags: 1, dotted: true, triplet: false)
|
||||
case .quarterTriplet:
|
||||
self.init(filledHead: true, hasStem: true, flags: 0, dotted: false, triplet: true)
|
||||
case .eighth:
|
||||
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: false)
|
||||
case .eighthTriplet:
|
||||
self.init(filledHead: true, hasStem: true, flags: 1, dotted: false, triplet: true)
|
||||
case .sixteenth:
|
||||
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: false)
|
||||
case .sixteenthTriplet:
|
||||
self.init(filledHead: true, hasStem: true, flags: 2, dotted: false, triplet: true)
|
||||
}
|
||||
}
|
||||
|
||||
private init(filledHead: Bool, hasStem: Bool, flags: Int, dotted: Bool, triplet: Bool) {
|
||||
self.filledHead = filledHead
|
||||
self.hasStem = hasStem
|
||||
self.flags = flags
|
||||
self.dotted = dotted
|
||||
self.triplet = triplet
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - NoteGlyphView
|
||||
|
||||
/// Draws a single music-notation glyph for a ``NoteDivision`` — notehead, stem, flags, an
|
||||
/// augmentation dot for dotted values, and a bracketed "3" for triplets — with `Canvas`.
|
||||
///
|
||||
/// Drawn in solid black so the rasterized image can be used as a **template** in a menu (only the
|
||||
/// alpha channel matters; the system tints it to the menu's foreground colour). See
|
||||
/// ``NoteGlyphImageCache``.
|
||||
struct NoteGlyphView: View {
|
||||
|
||||
// Logical drawing box. The note sits in the lower portion; the triplet bracket uses the top,
|
||||
// which is left clear on every glyph so the note baseline stays consistent across the menu.
|
||||
private static let boxWidth: CGFloat = 18
|
||||
private static let boxHeight: CGFloat = 26
|
||||
|
||||
// Notehead.
|
||||
private static let headCenterX: CGFloat = 6.5
|
||||
private static let headCenterY: CGFloat = 19.0
|
||||
private static let headRadiusX: CGFloat = 4.3
|
||||
private static let headRadiusY: CGFloat = 3.0
|
||||
private static let wholeHeadRadiusX: CGFloat = 5.0
|
||||
private static let openHeadLineWidth: CGFloat = 1.5
|
||||
|
||||
// Stem.
|
||||
private static let stemLineWidth: CGFloat = 1.3
|
||||
private static let stemTopY: CGFloat = 8.0
|
||||
|
||||
// Flags.
|
||||
private static let flagLineWidth: CGFloat = 1.5
|
||||
private static let flagSpread: CGFloat = 5.5
|
||||
private static let flagDrop: CGFloat = 6.0
|
||||
private static let flagGap: CGFloat = 3.5
|
||||
|
||||
// Augmentation dot — pushed clear of the notehead's right edge.
|
||||
private static let dotRadius: CGFloat = 1.5
|
||||
private static let dotGap: CGFloat = 3.8
|
||||
|
||||
// Triplet bracket + numeral. The "3" is centred in the bracket gap; `bracketTopY` leaves room
|
||||
// above it so the numeral is never clipped by the raster bounds.
|
||||
private static let bracketTopY: CGFloat = 4.0
|
||||
private static let bracketTickHeight: CGFloat = 2.0
|
||||
private static let bracketInsetX: CGFloat = 1.5
|
||||
private static let bracketLineWidth: CGFloat = 1.0
|
||||
private static let bracketNumberGap: CGFloat = 3.0
|
||||
private static let bracketNumberSize: CGFloat = 6.0
|
||||
|
||||
let division: NoteDivision
|
||||
|
||||
var body: some View {
|
||||
Canvas { context, size in
|
||||
let scaleX: CGFloat = size.width / NoteGlyphView.boxWidth
|
||||
let scaleY: CGFloat = size.height / NoteGlyphView.boxHeight
|
||||
let s: CGFloat = min(scaleX, scaleY)
|
||||
context.scaleBy(x: s, y: s)
|
||||
draw(NoteGlyphSpec(division), in: &context)
|
||||
}
|
||||
.frame(width: NoteGlyphView.boxWidth, height: NoteGlyphView.boxHeight)
|
||||
}
|
||||
|
||||
private func draw(_ spec: NoteGlyphSpec, in context: inout GraphicsContext) {
|
||||
let ink: GraphicsContext.Shading = .color(.black)
|
||||
|
||||
// Stem — draw before the head so the head overlaps its lower end cleanly.
|
||||
let stemX: CGFloat = NoteGlyphView.headCenterX + NoteGlyphView.headRadiusX - 0.3
|
||||
if spec.hasStem {
|
||||
var stem: Path = Path()
|
||||
stem.move(to: CGPoint(x: stemX, y: NoteGlyphView.headCenterY))
|
||||
stem.addLine(to: CGPoint(x: stemX, y: NoteGlyphView.stemTopY))
|
||||
context.stroke(stem, with: ink, lineWidth: NoteGlyphView.stemLineWidth)
|
||||
}
|
||||
|
||||
// Flags — hooks off the top of the stem, one per flag, stacked downward.
|
||||
for flagIndex: Int in 0 ..< spec.flags {
|
||||
let startY: CGFloat = NoteGlyphView.stemTopY + CGFloat(flagIndex) * NoteGlyphView.flagGap
|
||||
var flag: Path = Path()
|
||||
flag.move(to: CGPoint(x: stemX, y: startY))
|
||||
flag.addQuadCurve(
|
||||
to: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY + NoteGlyphView.flagDrop),
|
||||
control: CGPoint(x: stemX + NoteGlyphView.flagSpread, y: startY)
|
||||
)
|
||||
context.stroke(flag, with: ink, lineWidth: NoteGlyphView.flagLineWidth)
|
||||
}
|
||||
|
||||
// Notehead.
|
||||
let headRadiusX: CGFloat = spec.hasStem ? NoteGlyphView.headRadiusX : NoteGlyphView.wholeHeadRadiusX
|
||||
let headRect: CGRect = CGRect(
|
||||
x: NoteGlyphView.headCenterX - headRadiusX,
|
||||
y: NoteGlyphView.headCenterY - NoteGlyphView.headRadiusY,
|
||||
width: headRadiusX * 2,
|
||||
height: NoteGlyphView.headRadiusY * 2
|
||||
)
|
||||
let headPath: Path = Path(ellipseIn: headRect)
|
||||
if spec.filledHead {
|
||||
context.fill(headPath, with: ink)
|
||||
} else {
|
||||
context.stroke(headPath, with: ink, lineWidth: NoteGlyphView.openHeadLineWidth)
|
||||
}
|
||||
|
||||
// Augmentation dot, right of the head.
|
||||
if spec.dotted {
|
||||
let dotX: CGFloat = NoteGlyphView.headCenterX + headRadiusX + NoteGlyphView.dotGap
|
||||
let dotRect: CGRect = CGRect(
|
||||
x: dotX - NoteGlyphView.dotRadius,
|
||||
y: NoteGlyphView.headCenterY - NoteGlyphView.dotRadius,
|
||||
width: NoteGlyphView.dotRadius * 2,
|
||||
height: NoteGlyphView.dotRadius * 2
|
||||
)
|
||||
context.fill(Path(ellipseIn: dotRect), with: ink)
|
||||
}
|
||||
|
||||
// Triplet bracket with a centred "3".
|
||||
if spec.triplet {
|
||||
drawTripletBracket(in: &context, ink: ink)
|
||||
}
|
||||
}
|
||||
|
||||
private func drawTripletBracket(in context: inout GraphicsContext, ink: GraphicsContext.Shading) {
|
||||
let leftX: CGFloat = NoteGlyphView.bracketInsetX
|
||||
let rightX: CGFloat = NoteGlyphView.boxWidth - NoteGlyphView.bracketInsetX
|
||||
let midX: CGFloat = (leftX + rightX) / 2
|
||||
let topY: CGFloat = NoteGlyphView.bracketTopY
|
||||
let tickBottomY: CGFloat = topY + NoteGlyphView.bracketTickHeight
|
||||
let gap: CGFloat = NoteGlyphView.bracketNumberGap
|
||||
|
||||
var bracket: Path = Path()
|
||||
// Left tick down, then horizontal to the number gap.
|
||||
bracket.move(to: CGPoint(x: leftX, y: tickBottomY))
|
||||
bracket.addLine(to: CGPoint(x: leftX, y: topY))
|
||||
bracket.addLine(to: CGPoint(x: midX - gap, y: topY))
|
||||
// Right side: horizontal from the gap out to the right tick, then down.
|
||||
bracket.move(to: CGPoint(x: midX + gap, y: topY))
|
||||
bracket.addLine(to: CGPoint(x: rightX, y: topY))
|
||||
bracket.addLine(to: CGPoint(x: rightX, y: tickBottomY))
|
||||
context.stroke(bracket, with: ink, lineWidth: NoteGlyphView.bracketLineWidth)
|
||||
|
||||
let numeral: GraphicsContext.ResolvedText = context.resolve(
|
||||
Text("3")
|
||||
.font(.system(size: NoteGlyphView.bracketNumberSize, weight: .semibold, design: .rounded))
|
||||
.foregroundColor(.black)
|
||||
)
|
||||
context.draw(numeral, at: CGPoint(x: midX, y: topY), anchor: .center)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Rasterization cache
|
||||
|
||||
/// Renders each ``NoteDivision`` glyph to a template `Image` once and caches it, so the tempo-sync
|
||||
/// menu can show notation icons without re-rasterizing on every render. Template images tint to the
|
||||
/// menu's foreground colour automatically.
|
||||
@MainActor
|
||||
enum NoteGlyphImageCache {
|
||||
|
||||
private static let renderScale: CGFloat = 3.0
|
||||
private static var cache: [NoteDivision: Image] = [:]
|
||||
|
||||
/// The cached notation glyph for `division`, rendered on first request.
|
||||
static func image(for division: NoteDivision) -> Image {
|
||||
if let existing: Image = cache[division] {
|
||||
return existing
|
||||
}
|
||||
let rendered: Image = render(division)
|
||||
cache[division] = rendered
|
||||
return rendered
|
||||
}
|
||||
|
||||
private static func render(_ division: NoteDivision) -> Image {
|
||||
let renderer: ImageRenderer = ImageRenderer(content: NoteGlyphView(division: division))
|
||||
renderer.scale = renderScale
|
||||
#if os(macOS)
|
||||
if let nsImage = renderer.nsImage {
|
||||
nsImage.isTemplate = true
|
||||
return Image(nsImage: nsImage)
|
||||
}
|
||||
#else
|
||||
if let uiImage = renderer.uiImage {
|
||||
return Image(uiImage: uiImage.withRenderingMode(.alwaysTemplate))
|
||||
}
|
||||
#endif
|
||||
// Fallback to the division's text label if rasterization ever fails.
|
||||
return Image(systemName: "music.note")
|
||||
}
|
||||
}
|
||||
@@ -180,6 +180,189 @@ struct FootswitchButton: View {
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Tempo-sync knob
|
||||
|
||||
/// A knob that can be locked to a note division of the live tempo.
|
||||
///
|
||||
/// When free, it is an ordinary ``ParameterKnob``. A compact menu below the dial lets the user
|
||||
/// pick `Free` or a ``NoteDivision``; once a division is chosen the knob is driven by the tempo
|
||||
/// (its dial shows the derived value but is disabled, since the number is computed). The menu is
|
||||
/// shown only while tempo is enabled — the enclosing view gates on `shoeGazeTempoEnabled`.
|
||||
struct TempoSyncKnobView: View {
|
||||
|
||||
private static let cellSpacing: CGFloat = 4
|
||||
private static let syncedDialOpacity: Double = 0.55
|
||||
private static let menuFontSize: CGFloat = 10
|
||||
private static let labelGlyphSpacing: CGFloat = 3
|
||||
private static let warningIconSize: CGFloat = 8
|
||||
/// Height of the glyph in the collapsed menu button, and of the whole menu row, so the row is the
|
||||
/// same height whether it shows the "Free" text or a note glyph — the pedal card never grows.
|
||||
private static let labelGlyphHeight: CGFloat = 18
|
||||
private static let menuRowHeight: CGFloat = 20
|
||||
private static let freeKey: String = "free"
|
||||
|
||||
// Division-picker popover: a height-capped scroll list the system keeps on-screen (it flips
|
||||
// above the button near the bottom edge) rather than a native menu that can run off-screen.
|
||||
private static let pickerMaxHeight: CGFloat = 260
|
||||
private static let pickerGlyphHeight: CGFloat = 22
|
||||
private static let pickerRowSpacing: CGFloat = 2
|
||||
private static let pickerPadding: CGFloat = 8
|
||||
private static let pickerRowMinWidth: CGFloat = 84
|
||||
private static let checkmarkFontSize: CGFloat = 11
|
||||
|
||||
let pedal: Pedal
|
||||
let knob: PedalKnob
|
||||
let param: TempoSyncableParam
|
||||
|
||||
/// Presentation flag for the division-picker popover.
|
||||
@State private var showDivisionPicker: Bool = false
|
||||
|
||||
var body: some View {
|
||||
// Observe the pedal's sync-revision so the badge refreshes when `tempoSync` changes through
|
||||
// any path — this view's picker, a preset load, or a lightweight recall.
|
||||
let _ = pedal.tempoSyncRevision.value
|
||||
let currentKey: String = keyForCurrentSync()
|
||||
let isSynced: Bool = currentKey != TempoSyncKnobView.freeKey
|
||||
let currentBpm: Double? = pedal.clock?.bpm
|
||||
// Reading the live parameter value subscribes this view to Observation, so a tempo change
|
||||
// (which rewrites the node via `applyTempoSync`) re-renders the clamp warning without polling.
|
||||
let liveValue: Double = param.node.value
|
||||
let activeDivision: NoteDivision? = NoteDivision(rawValue: currentKey)
|
||||
let activeClamped: Bool = {
|
||||
_ = liveValue
|
||||
guard isSynced, let bpm: Double = currentBpm, let division: NoteDivision = activeDivision else {
|
||||
return false
|
||||
}
|
||||
return param.value(for: division, bpm: bpm).clamped
|
||||
}()
|
||||
|
||||
VStack(spacing: TempoSyncKnobView.cellSpacing) {
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
.foregroundStyle(Color.white)
|
||||
.disabled(isSynced)
|
||||
.opacity(isSynced ? TempoSyncKnobView.syncedDialOpacity : 1.0)
|
||||
|
||||
Button {
|
||||
showDivisionPicker = true
|
||||
} label: {
|
||||
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
|
||||
if isSynced, let division: NoteDivision = activeDivision {
|
||||
NoteGlyphImageCache.image(for: division)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(height: TempoSyncKnobView.labelGlyphHeight)
|
||||
.accessibilityLabel(Text(labelForKey(currentKey)))
|
||||
} else {
|
||||
Text("Free")
|
||||
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
|
||||
}
|
||||
if activeClamped {
|
||||
Image(systemName: "exclamationmark.triangle.fill")
|
||||
.font(.system(size: TempoSyncKnobView.warningIconSize))
|
||||
}
|
||||
Image(systemName: "chevron.down")
|
||||
.font(.system(size: TempoSyncKnobView.warningIconSize))
|
||||
.opacity(0.6)
|
||||
}
|
||||
.frame(height: TempoSyncKnobView.menuRowHeight)
|
||||
.foregroundStyle(activeClamped ? Color.orange : Color.white.opacity(isSynced ? 1.0 : 0.65))
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.fixedSize()
|
||||
.help(activeClamped
|
||||
? "This note can't be represented at the current tempo — \(knob.label) is clamped to its limit."
|
||||
: "Sync \(knob.label) to the tempo, or set it freely")
|
||||
.popover(isPresented: $showDivisionPicker) {
|
||||
divisionPicker
|
||||
.presentationCompactAdaptation(.popover)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Height-capped, scrollable list of `Free` + every note division. Presented as a popover so the
|
||||
/// system keeps it on-screen (flipping above the button near the bottom edge) and it scrolls when
|
||||
/// taller than ``pickerMaxHeight`` — unlike a native menu, which ran off the bottom on iOS.
|
||||
private var divisionPicker: some View {
|
||||
let currentBpm: Double? = pedal.clock?.bpm
|
||||
let currentKey: String = keyForCurrentSync()
|
||||
return ScrollView {
|
||||
VStack(alignment: .leading, spacing: TempoSyncKnobView.pickerRowSpacing) {
|
||||
pickerRow(
|
||||
key: TempoSyncKnobView.freeKey,
|
||||
glyph: nil,
|
||||
disabled: false,
|
||||
selected: currentKey == TempoSyncKnobView.freeKey
|
||||
)
|
||||
ForEach(NoteDivision.allCases, id: \.self) { division in
|
||||
// A division whose value clamps at the current tempo (e.g. a note longer than the
|
||||
// maximum delay time) can't be represented accurately, so it is shown but disabled.
|
||||
let unavailable: Bool = currentBpm.map { param.value(for: division, bpm: $0).clamped } ?? false
|
||||
pickerRow(
|
||||
key: division.rawValue,
|
||||
glyph: division,
|
||||
disabled: unavailable,
|
||||
selected: currentKey == division.rawValue
|
||||
)
|
||||
}
|
||||
}
|
||||
.padding(TempoSyncKnobView.pickerPadding)
|
||||
}
|
||||
.frame(maxHeight: TempoSyncKnobView.pickerMaxHeight)
|
||||
}
|
||||
|
||||
/// One selectable row in ``divisionPicker`` — a note glyph (or "Free" text), a trailing checkmark
|
||||
/// when it is the current selection, and a disabled state for divisions that clamp at this tempo.
|
||||
@ViewBuilder
|
||||
private func pickerRow(key: String, glyph: NoteDivision?, disabled: Bool, selected: Bool) -> some View {
|
||||
Button {
|
||||
select(key)
|
||||
showDivisionPicker = false
|
||||
} label: {
|
||||
HStack(spacing: TempoSyncKnobView.labelGlyphSpacing) {
|
||||
if let glyph: NoteDivision = glyph {
|
||||
NoteGlyphImageCache.image(for: glyph)
|
||||
.resizable()
|
||||
.scaledToFit()
|
||||
.frame(height: TempoSyncKnobView.pickerGlyphHeight)
|
||||
} else {
|
||||
Text("Free")
|
||||
.font(.system(size: TempoSyncKnobView.menuFontSize, weight: .semibold, design: .rounded))
|
||||
}
|
||||
Spacer(minLength: TempoSyncKnobView.labelGlyphSpacing)
|
||||
if selected {
|
||||
Image(systemName: "checkmark")
|
||||
.font(.system(size: TempoSyncKnobView.checkmarkFontSize, weight: .semibold))
|
||||
}
|
||||
}
|
||||
.frame(minWidth: TempoSyncKnobView.pickerRowMinWidth, alignment: .leading)
|
||||
.contentShape(Rectangle())
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.disabled(disabled)
|
||||
.accessibilityLabel(Text(glyph?.label ?? "Free"))
|
||||
}
|
||||
|
||||
private func keyForCurrentSync() -> String {
|
||||
if case .division(let division) = pedal.tempoSync[param.key] ?? .free {
|
||||
return division.rawValue
|
||||
}
|
||||
return TempoSyncKnobView.freeKey
|
||||
}
|
||||
|
||||
private func labelForKey(_ key: String) -> String {
|
||||
key == TempoSyncKnobView.freeKey ? "Free" : (NoteDivision(rawValue: key)?.label ?? key)
|
||||
}
|
||||
|
||||
private func select(_ key: String) {
|
||||
// `setSync` bumps `pedal.tempoSyncRevision`, which this view observes — no local flag needed.
|
||||
if key == TempoSyncKnobView.freeKey {
|
||||
pedal.setSync(.free, for: param.key)
|
||||
} else if let division: NoteDivision = NoteDivision(rawValue: key) {
|
||||
pedal.setSync(.division(division), for: param.key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - PedalView
|
||||
|
||||
/// A stompbox-style enclosure view that renders all controls for a single `Pedal`.
|
||||
@@ -266,6 +449,13 @@ public struct PedalView: View {
|
||||
/// Presentation flag for the pedal info panel (description + control ranges).
|
||||
@State private var showInfo: Bool = false
|
||||
|
||||
/// The rig's control map, injected by the builder so the pedal can draw a mapping strip. `nil`
|
||||
/// when the rig has no bindings (or in contexts that don't set it) — the strip renders nothing.
|
||||
@Environment(\.controlMappingMap) private var controlMappingMap: MIDIMap?
|
||||
|
||||
/// Mirrors ``ShoeGaze/tempoEnabled`` so tempo-sync knob affordances hide when tempo is off.
|
||||
@Environment(\.shoeGazeTempoEnabled) private var tempoEnabled: Bool
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a stompbox pedal view for the given pedal.
|
||||
@@ -284,7 +474,20 @@ public struct PedalView: View {
|
||||
// the enclosure-width calculation consume the same array.
|
||||
let sliders: [PedalSlider] = pedal.effectSliders
|
||||
|
||||
ZStack(alignment: .topLeading) {
|
||||
// Content is the sizing layer so the enclosure hugs it vertically — a short pedal stays
|
||||
// short. The gradient fill and border/screw strokes are attached as background/overlay so
|
||||
// they conform to the content height instead of a greedy `RoundedRectangle` in a ZStack
|
||||
// dictating (and stretching) the height to fill the row.
|
||||
Group {
|
||||
if let looper: LooperPedal = pedal as? LooperPedal {
|
||||
looperColumnarContent(looper)
|
||||
} else {
|
||||
defaultContent(sliders: sliders)
|
||||
}
|
||||
}
|
||||
.padding(PedalView.enclosurePadding)
|
||||
.frame(width: enclosureWidth(for: sliders))
|
||||
.background(
|
||||
// Enclosure fill with top-to-bottom gradient
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius)
|
||||
.fill(
|
||||
@@ -294,38 +497,28 @@ public struct PedalView: View {
|
||||
endPoint: .bottom
|
||||
)
|
||||
)
|
||||
|
||||
// Outer border
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius)
|
||||
.stroke(Color.black.opacity(PedalView.outerBorderOpacity),
|
||||
lineWidth: PedalView.outerBorderLineWidth)
|
||||
|
||||
)
|
||||
.overlay(
|
||||
// Inner highlight rim (subtle bevel)
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius - PedalView.innerHighlightPadding)
|
||||
.stroke(Color.white.opacity(PedalView.innerHighlightOpacity),
|
||||
lineWidth: PedalView.innerHighlightLineWidth)
|
||||
.padding(PedalView.innerHighlightPadding)
|
||||
|
||||
// Content stack — the looper uses a wide, columnar layout to stay short; every other
|
||||
// pedal uses the default single-column section stack.
|
||||
Group {
|
||||
if let looper: LooperPedal = pedal as? LooperPedal {
|
||||
looperColumnarContent(looper)
|
||||
} else {
|
||||
defaultContent(sliders: sliders)
|
||||
}
|
||||
}
|
||||
.padding(PedalView.enclosurePadding)
|
||||
|
||||
// Corner screws — overlaid at the four corners
|
||||
screwCorners
|
||||
|
||||
// Info button, tucked just under the top-left corner screw.
|
||||
)
|
||||
.overlay(
|
||||
// Outer border
|
||||
RoundedRectangle(cornerRadius: PedalView.enclosureCornerRadius)
|
||||
.stroke(Color.black.opacity(PedalView.outerBorderOpacity),
|
||||
lineWidth: PedalView.outerBorderLineWidth)
|
||||
)
|
||||
// Corner screws — overlaid at the four corners.
|
||||
.overlay { screwCorners }
|
||||
// Info button, tucked just under the top-left corner screw.
|
||||
.overlay(alignment: .topLeading) {
|
||||
infoButton
|
||||
.padding(.leading, PedalView.infoButtonLeading)
|
||||
.padding(.top, PedalView.infoButtonTop)
|
||||
}
|
||||
.frame(width: enclosureWidth(for: sliders))
|
||||
.shadow(
|
||||
color: Color.black.opacity(PedalView.shadowOpacity),
|
||||
radius: PedalView.shadowRadius,
|
||||
@@ -353,8 +546,8 @@ public struct PedalView: View {
|
||||
.id(ObjectIdentifier(pedal))
|
||||
buttonRow
|
||||
sliderBank(sliders)
|
||||
Spacer(minLength: 0)
|
||||
bottomControls
|
||||
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -388,7 +581,7 @@ public struct PedalView: View {
|
||||
looperTransportGrid(columns: 2)
|
||||
.id(ObjectIdentifier(pedal))
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -522,12 +715,12 @@ public struct PedalView: View {
|
||||
let rowItemSpacing: CGFloat = row.count >= columns
|
||||
? PedalView.knobSpacing
|
||||
: PedalView.knobRowItemSpacing
|
||||
HStack(spacing: rowItemSpacing) {
|
||||
// Top-align so every dial pins to the row's top edge — a tempo-sync cell grows taller
|
||||
// below the dial (glyph menu, warning) without dragging its neighbours' dials down.
|
||||
HStack(alignment: .top, spacing: rowItemSpacing) {
|
||||
Spacer(minLength: 0)
|
||||
ForEach(Array(row.enumerated()), id: \.offset) { knobPair in
|
||||
let knob: PedalKnob = knobPair.element
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
.foregroundStyle(Color.white)
|
||||
knobCell(knobPair.element)
|
||||
}
|
||||
Spacer(minLength: 0)
|
||||
}
|
||||
@@ -535,6 +728,25 @@ public struct PedalView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Renders one effect knob — a tempo-sync knob when the parameter is syncable and tempo is
|
||||
/// enabled, otherwise a plain ``ParameterKnob``. Syncable knobs are matched by node identity
|
||||
/// against `pedal.tempoSyncableParams`.
|
||||
@ViewBuilder
|
||||
private func knobCell(_ knob: PedalKnob) -> some View {
|
||||
if tempoEnabled, let param: TempoSyncableParam = syncableParam(for: knob) {
|
||||
TempoSyncKnobView(pedal: pedal, knob: knob, param: param)
|
||||
} else {
|
||||
ParameterKnob(knob.label, node: knob.node, range: knob.range)
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
}
|
||||
|
||||
/// The tempo-syncable descriptor whose parameter node backs `knob`, or `nil` if the knob is
|
||||
/// not syncable. Matched by `UIParamNode` identity so it is robust to label changes.
|
||||
private func syncableParam(for knob: PedalKnob) -> TempoSyncableParam? {
|
||||
pedal.tempoSyncableParams.first { $0.node === knob.node }
|
||||
}
|
||||
|
||||
/// Row of stepped selector knobs drawn from `pedal.effectSelectors`, beneath the knob grid.
|
||||
/// Renders nothing when the pedal publishes no selectors.
|
||||
@ViewBuilder
|
||||
|
||||
@@ -59,8 +59,6 @@ public struct ShoeGazeBuilderView: View {
|
||||
private static let backgroundGreen: Double = 0.07
|
||||
private static let backgroundBlue: Double = 0.06
|
||||
private static let testLoopTag: Int = -1
|
||||
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
|
||||
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
|
||||
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
|
||||
private static let maxCrossfadeSeconds: Double = 10.0
|
||||
/// Highest board reachable via a ⌘-number switch shortcut.
|
||||
@@ -185,6 +183,16 @@ public struct ShoeGazeBuilderView: View {
|
||||
@State private var showRecordingFolderImporter: Bool = false
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
/// The AppKit local key-down monitor that routes bare letter/digit keys to `midi.ingestKey`,
|
||||
/// or `nil` when not installed. Stored so it can be removed on disappear.
|
||||
@State private var keyMonitor: Any?
|
||||
#else
|
||||
/// Whether the builder root holds keyboard focus, so `.onKeyPress` delivers hardware-keyboard
|
||||
/// presses to the key bindings. Held `true` except while a text field is being edited.
|
||||
@FocusState private var keyboardFocused: Bool
|
||||
#endif
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Creates a builder view.
|
||||
@@ -232,7 +240,10 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
|
||||
|
||||
public var body: some View {
|
||||
// The builder body is split across `layoutChrome` → `presentationChrome` → `body` because the
|
||||
// full modifier chain (layout + lifecycle + every sheet / dialog / alert + key capture) is too
|
||||
// large for the Swift expression type-checker as a single expression.
|
||||
private var layoutChrome: some View {
|
||||
rootContent
|
||||
.padding(ShoeGazeBuilderView.outerPadding)
|
||||
// A large min width is a macOS window sizing hint; on iPad it would force content wider than
|
||||
@@ -268,12 +279,26 @@ public struct ShoeGazeBuilderView: View {
|
||||
restoreInputSelection()
|
||||
syncIdleTimer()
|
||||
maybeWarnICloudUnavailable()
|
||||
#if os(macOS)
|
||||
installKeyMonitor()
|
||||
#else
|
||||
keyboardFocused = true
|
||||
#endif
|
||||
}
|
||||
.onDisappear {
|
||||
releaseIdleTimer()
|
||||
#if os(macOS)
|
||||
removeKeyMonitor()
|
||||
#endif
|
||||
}
|
||||
.onDisappear { releaseIdleTimer() }
|
||||
.onChange(of: transportTick) { syncIdleTimer() }
|
||||
.onChange(of: library.isLoaded) {
|
||||
maybeWarnICloudUnavailable()
|
||||
}
|
||||
}
|
||||
|
||||
private var presentationChrome: some View {
|
||||
layoutChrome
|
||||
.background(boardsSheetAnchor)
|
||||
.background(rigExportAnchor)
|
||||
.background(rigImportAnchor)
|
||||
@@ -367,6 +392,136 @@ public struct ShoeGazeBuilderView: View {
|
||||
.overlay(alignment: .top) { midiLearnBanner }
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
presentationChrome
|
||||
// Letter/digit keys drive bound rig actions. macOS uses an AppKit key monitor (installed in
|
||||
// onAppear) because SwiftUI's `.onKeyPress` only delivers to the focused view, and the builder
|
||||
// root is rarely the focused view. iOS routes hardware-keyboard presses through `.onKeyPress`,
|
||||
// which requires the root to be focusable AND focused — so the root claims focus on appear and
|
||||
// reclaims it whenever a modal that stole focus (a text-field sheet) closes. A focused
|
||||
// `TextField` still wins while open, so typing is never hijacked.
|
||||
#if !os(macOS)
|
||||
.modifier(KeyboardCaptureModifier(
|
||||
keyboardFocused: $keyboardFocused,
|
||||
modalOpen: anyFocusStealingModalOpen,
|
||||
onKeyPress: handleKeyPress
|
||||
))
|
||||
#endif
|
||||
}
|
||||
|
||||
#if !os(macOS)
|
||||
/// Whether any modal that can take keyboard focus from the builder root is currently open. When
|
||||
/// it closes, the root reclaims focus so hardware-keyboard bindings keep firing. Text-field-
|
||||
/// bearing sheets (rig rename, board editor) are the ones that matter, but covering the main
|
||||
/// content sheets keeps focus robust across all of them.
|
||||
private var anyFocusStealingModalOpen: Bool {
|
||||
showMIDISheet || showHelpSheet || showRigsSheet || showPaletteSheet
|
||||
|| showSettingsSheet || showBoardsSheet || namePrompt != nil
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(macOS)
|
||||
/// Routes a bare key press to the MIDI controller's key bindings, ignoring modified presses so
|
||||
/// `⌘`-shortcuts still work. Returns `.handled` when a binding consumed the key, else `.ignored`.
|
||||
/// A focused text field consumes keys first via the responder chain, so this only fires when the
|
||||
/// user is not typing.
|
||||
private func handleKeyPress(_ keyPress: KeyPress) -> KeyPress.Result {
|
||||
guard let midi: MIDIController = midi else { return .ignored }
|
||||
// Command chords belong to the menu shortcuts; shift / control / option qualify the binding.
|
||||
guard keyPress.modifiers.contains(.command) == false else { return .ignored }
|
||||
var modifiers: MIDIMap.KeyModifiers = []
|
||||
if keyPress.modifiers.contains(.shift) { modifiers.insert(.shift) }
|
||||
if keyPress.modifiers.contains(.control) { modifiers.insert(.control) }
|
||||
if keyPress.modifiers.contains(.option) { modifiers.insert(.option) }
|
||||
// `key.character` is the unshifted base key, so shift stays represented in `modifiers` only.
|
||||
let base: String = String(keyPress.key.character)
|
||||
return midi.ingestKey(base, modifiers: modifiers) ? .handled : .ignored
|
||||
}
|
||||
#endif
|
||||
|
||||
#if !os(macOS)
|
||||
/// The iOS/iPadOS key-capture modifiers, factored into a `ViewModifier` so the (large) builder
|
||||
/// body stays under the Swift expression type-checker's complexity limit. Makes the root
|
||||
/// focusable and focused so `.onKeyPress` receives hardware-keyboard presses, and reclaims focus
|
||||
/// whenever a focus-stealing modal closes.
|
||||
private struct KeyboardCaptureModifier: ViewModifier {
|
||||
|
||||
@FocusState.Binding var keyboardFocused: Bool
|
||||
let modalOpen: Bool
|
||||
let onKeyPress: (KeyPress) -> KeyPress.Result
|
||||
|
||||
func body(content: Content) -> some View {
|
||||
content
|
||||
.focusable()
|
||||
.focusEffectDisabled()
|
||||
.focused($keyboardFocused)
|
||||
.onKeyPress(phases: .down) { keyPress in onKeyPress(keyPress) }
|
||||
.onChange(of: modalOpen) { _, isOpen in
|
||||
if isOpen == false { keyboardFocused = true }
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
#if os(macOS)
|
||||
/// Installs an AppKit local key-down monitor that routes bare letter/digit keys to the MIDI
|
||||
/// controller's key bindings. Unlike SwiftUI `.onKeyPress`, a local monitor sees every key-down
|
||||
/// regardless of which view holds SwiftUI focus, so mapped keys fire even when the board — not a
|
||||
/// text field — is what the user is looking at. Keys are swallowed only when a binding consumes
|
||||
/// them; text entry and menu shortcuts pass through untouched.
|
||||
private func installKeyMonitor() {
|
||||
guard keyMonitor == nil else { return }
|
||||
keyMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown) { event in
|
||||
let flags: NSEvent.ModifierFlags = event.modifierFlags
|
||||
// Command chords belong to the menu keyboard shortcuts; key-repeat would toggle
|
||||
// repeatedly while a key is held. Filter both before touching any binding.
|
||||
//
|
||||
// Derive the base key with *no* modifiers applied, not `charactersIgnoringModifiers`
|
||||
// (which still bakes in Shift — `⇧2` → `"@"` — and mangles Control into a C0 code). This
|
||||
// matches the iOS path's `keyPress.key.character`, so the same physical chord stores the
|
||||
// same base key on both platforms and a rig stays portable across an iCloud sync.
|
||||
guard flags.contains(.command) == false,
|
||||
event.isARepeat == false,
|
||||
let characters: String = event.characters(byApplyingModifiers: []) else { return event }
|
||||
let modifiers: MIDIMap.KeyModifiers = ShoeGazeBuilderView.keyModifiers(from: flags)
|
||||
// Local monitors are delivered on the main thread; hop the actor with only Sendable
|
||||
// values (NSEvent itself is not Sendable and must not cross the boundary).
|
||||
let consumed: Bool = MainActor.assumeIsolated { routeMonitoredKey(characters, modifiers) }
|
||||
return consumed ? nil : event
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps AppKit modifier flags to the persisted ``MIDIMap/KeyModifiers`` set (shift / control /
|
||||
/// option; command is reserved for menu shortcuts and never reaches here).
|
||||
private static func keyModifiers(from flags: NSEvent.ModifierFlags) -> MIDIMap.KeyModifiers {
|
||||
var modifiers: MIDIMap.KeyModifiers = []
|
||||
if flags.contains(.shift) { modifiers.insert(.shift) }
|
||||
if flags.contains(.control) { modifiers.insert(.control) }
|
||||
if flags.contains(.option) { modifiers.insert(.option) }
|
||||
return modifiers
|
||||
}
|
||||
|
||||
/// Applies a monitored key press to the MIDI controller's key bindings, returning `true` when a
|
||||
/// binding consumed it. A field editor holding first responder means the user is typing, so the
|
||||
/// key is let through untouched — a rig-name or board-label edit is never hijacked into a toggle.
|
||||
@MainActor
|
||||
private func routeMonitoredKey(_ characters: String, _ modifiers: MIDIMap.KeyModifiers) -> Bool {
|
||||
guard let midi: MIDIController = midi else { return false }
|
||||
if let responder: NSResponder = NSApp.keyWindow?.firstResponder, responder is NSText {
|
||||
return false
|
||||
}
|
||||
return midi.ingestKey(characters, modifiers: modifiers)
|
||||
}
|
||||
|
||||
/// Removes the local key-down monitor installed by ``installKeyMonitor()``.
|
||||
private func removeKeyMonitor() {
|
||||
if let monitor: Any = keyMonitor {
|
||||
NSEvent.removeMonitor(monitor)
|
||||
keyMonitor = nil
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
/// Hosts the compact rig-library sheet on its own node.
|
||||
private var rigsSheetAnchor: some View {
|
||||
Color.clear
|
||||
@@ -413,8 +568,8 @@ public struct ShoeGazeBuilderView: View {
|
||||
/// A banner shown while a control is armed for MIDI Learn, prompting the user to move it.
|
||||
@ViewBuilder
|
||||
private var midiLearnBanner: some View {
|
||||
if let midi: MIDIController = midi, midi.learnTarget != nil {
|
||||
Text("MIDI Learn — press a footswitch or move an expression pedal to assign it")
|
||||
if let midi: MIDIController = midi, let target: MIDIController.LearnTarget = midi.learnTarget {
|
||||
Text(midiLearnBannerText(for: target))
|
||||
.font(.callout.weight(.semibold))
|
||||
.foregroundStyle(Color.black)
|
||||
.padding(.horizontal, 14)
|
||||
@@ -424,6 +579,18 @@ public struct ShoeGazeBuilderView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Banner copy tailored to what the armed Learn target is waiting for.
|
||||
private func midiLearnBannerText(for target: MIDIController.LearnTarget) -> String {
|
||||
switch target {
|
||||
case .key:
|
||||
return "Learn — press a key to assign it"
|
||||
case .action:
|
||||
return "Learn — press a footswitch to assign it"
|
||||
case .cc:
|
||||
return "Learn — move an expression pedal to assign it"
|
||||
}
|
||||
}
|
||||
|
||||
/// The rig library listing on the far left: every saved rig plus new/save/duplicate/rename/
|
||||
/// delete/erase and archive import/export. Selecting a rig replaces the current session.
|
||||
private var rigSidebar: some View {
|
||||
@@ -495,10 +662,14 @@ public struct ShoeGazeBuilderView: View {
|
||||
topSection
|
||||
}
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
ControlMappingLegend()
|
||||
boardArea
|
||||
}
|
||||
.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .topLeading)
|
||||
.environment(\.shoeGazeTempoEnabled, shoeGaze.tempoEnabled)
|
||||
// Feed the rig's control map into the board tree so each pedal can draw its mapping strip.
|
||||
// Reading `shoeGaze.midiMap` here (observable) refreshes every strip when a binding changes.
|
||||
.environment(\.controlMappingMap, shoeGaze.midiMap)
|
||||
}
|
||||
|
||||
// MARK: - Compact layout (iPhone / narrow iPad)
|
||||
@@ -572,7 +743,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
EngineConfigView(
|
||||
shoeGaze: shoeGaze,
|
||||
hardwareSampleRate: hardwareSampleRate,
|
||||
onConfigApplied: { transportTick.toggle() },
|
||||
onConfigApplied: { transportTick.toggle(); autosave() },
|
||||
transportOnly: true
|
||||
)
|
||||
#if !os(macOS)
|
||||
@@ -587,6 +758,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
HStack(spacing: ShoeGazeBuilderView.rowSpacing) {
|
||||
rigBypassButton
|
||||
rigMuteButton
|
||||
inputMuteButton
|
||||
helpButton
|
||||
if let midi: MIDIController = midi {
|
||||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||||
@@ -718,7 +890,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
EngineConfigView(
|
||||
shoeGaze: shoeGaze,
|
||||
hardwareSampleRate: hardwareSampleRate,
|
||||
onConfigApplied: { transportTick.toggle() }
|
||||
onConfigApplied: { transportTick.toggle(); autosave() }
|
||||
)
|
||||
|
||||
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
|
||||
@@ -942,12 +1114,19 @@ public struct ShoeGazeBuilderView: View {
|
||||
MIDIIndicatorView(controller: midi) { showMIDISheet = true }
|
||||
}
|
||||
helpButton
|
||||
rigBypassButton
|
||||
rigMuteButton
|
||||
// Icon-only in the docked desktop cluster so the four toggles + Rate picker +
|
||||
// I/O steppers + Start never overrun the row and clip the pickers. Each button
|
||||
// keeps its `.help` tooltip; the compact layout still shows the text labels.
|
||||
Group {
|
||||
rigBypassButton
|
||||
rigMuteButton
|
||||
inputMuteButton
|
||||
}
|
||||
.labelStyle(.iconOnly)
|
||||
EngineConfigView(
|
||||
shoeGaze: shoeGaze,
|
||||
hardwareSampleRate: hardwareSampleRate,
|
||||
onConfigApplied: { transportTick.toggle() }
|
||||
onConfigApplied: { transportTick.toggle(); autosave() }
|
||||
)
|
||||
}
|
||||
.frame(height: TempoView.enabledHeight)
|
||||
@@ -1029,6 +1208,75 @@ public struct ShoeGazeBuilderView: View {
|
||||
.help("Mute the entire rig output — silences all sound")
|
||||
}
|
||||
|
||||
/// Input-mute toggle, shown beside the Start/Stop transport. Silences the incoming guitar / mic
|
||||
/// signal (distinct from the rig-output mute). Comes up muted on each engine start, with a
|
||||
/// pulsing red glow while muted so new users spot why they hear nothing.
|
||||
private var inputMuteButton: some View {
|
||||
InputMuteButton(shoeGaze: shoeGaze)
|
||||
}
|
||||
|
||||
/// The input-mute toggle with a pulsing red glow while active. Its own view so it can own the
|
||||
/// repeating-animation state; the glow reads `pulse`, which oscillates under a `repeatForever`
|
||||
/// animation only while the input is muted.
|
||||
private struct InputMuteButton: View {
|
||||
|
||||
let shoeGaze: ShoeGaze
|
||||
|
||||
/// Oscillates 0↔1 under a repeating animation while muted, driving the glow's radius/opacity.
|
||||
@State private var pulse: Bool = false
|
||||
|
||||
private static let glowCornerRadius: CGFloat = 6
|
||||
private static let glowLineWidth: CGFloat = 1.5
|
||||
private static let glowRadiusLow: CGFloat = 2
|
||||
private static let glowRadiusHigh: CGFloat = 9
|
||||
private static let glowOpacityLow: Double = 0.35
|
||||
private static let glowOpacityHigh: Double = 0.95
|
||||
private static let pulseDuration: Double = 0.85
|
||||
private static let pulseSettleDuration: Double = 0.2
|
||||
|
||||
var body: some View {
|
||||
let muted: Bool = shoeGaze.inputMuted
|
||||
return Button {
|
||||
shoeGaze.toggleInputMuted()
|
||||
} label: {
|
||||
Label(muted ? "Input Muted" : "Mute Input",
|
||||
systemImage: muted ? "mic.slash.fill" : "mic.fill")
|
||||
.font(.subheadline)
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(muted ? .red : .gray)
|
||||
.overlay(glow(muted: muted))
|
||||
.help("Mute the input feeding the pedals — silences the incoming guitar / mic signal")
|
||||
.onChange(of: muted) { _, nowMuted in startOrStopPulse(muted: nowMuted) }
|
||||
.onAppear { startOrStopPulse(muted: muted) }
|
||||
}
|
||||
|
||||
/// A red ring + shadow that pulses while muted, and is invisible otherwise. Non-interactive
|
||||
/// so it never intercepts the button's taps.
|
||||
private func glow(muted: Bool) -> some View {
|
||||
RoundedRectangle(cornerRadius: InputMuteButton.glowCornerRadius, style: .continuous)
|
||||
.strokeBorder(Color.red, lineWidth: InputMuteButton.glowLineWidth)
|
||||
.shadow(
|
||||
color: Color.red,
|
||||
radius: pulse ? InputMuteButton.glowRadiusHigh : InputMuteButton.glowRadiusLow
|
||||
)
|
||||
.opacity(muted ? (pulse ? InputMuteButton.glowOpacityHigh : InputMuteButton.glowOpacityLow) : 0)
|
||||
.allowsHitTesting(false)
|
||||
}
|
||||
|
||||
/// Starts the forever-repeating pulse when muted, or settles it back to rest when not.
|
||||
private func startOrStopPulse(muted: Bool) {
|
||||
if muted {
|
||||
pulse = false
|
||||
withAnimation(.easeInOut(duration: InputMuteButton.pulseDuration).repeatForever(autoreverses: true)) {
|
||||
pulse = true
|
||||
}
|
||||
} else {
|
||||
withAnimation(.easeOut(duration: InputMuteButton.pulseSettleDuration)) { pulse = false }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Board area
|
||||
|
||||
private var boardArea: some View {
|
||||
@@ -1179,7 +1427,7 @@ public struct ShoeGazeBuilderView: View {
|
||||
if wasRunning { shoeGaze.engine.stop() }
|
||||
do {
|
||||
try shoeGaze.setInputSource(source)
|
||||
persistInputSelection(source)
|
||||
autosave() // the rig is the source of truth for the input selection; record it now
|
||||
} catch {
|
||||
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
|
||||
}
|
||||
@@ -1189,43 +1437,26 @@ public struct ShoeGazeBuilderView: View {
|
||||
transportTick.toggle()
|
||||
}
|
||||
|
||||
// MARK: - Input persistence
|
||||
// MARK: - Input restore
|
||||
|
||||
/// Saves the current input choice so it is restored on the next launch.
|
||||
private func persistInputSelection(_ source: InputSource) {
|
||||
let value: Int
|
||||
switch source {
|
||||
case .testLoop:
|
||||
value = ShoeGazeBuilderView.testLoopTag
|
||||
case .liveInput(let channel):
|
||||
value = channel
|
||||
}
|
||||
UserDefaults.standard.set(value, forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
|
||||
}
|
||||
|
||||
/// Restores the saved input choice once on appear. With no saved choice, defaults to live
|
||||
/// input when the microphone is already authorised and the engine has an input channel —
|
||||
/// otherwise stays on the test loop. A saved live channel that no longer fits the engine, or
|
||||
/// a since-revoked permission, falls back to the test loop via `switchInput(to:)`.
|
||||
/// Reconciles the microphone permission with the input source the rig already restored.
|
||||
///
|
||||
/// The rig (autosave envelope / library entry) is the single source of truth for the input
|
||||
/// selection — `RigStore.restore` / `loadRig` set `shoeGaze.inputSource` before this view
|
||||
/// appears, and a fresh-launch seed defaults it to live In 0. This runs once on appear only to
|
||||
/// make a restored live-input selection actually audible: it requests mic access (surfacing the
|
||||
/// prompt at launch rather than at the first Start) and falls back to the test loop on denial.
|
||||
/// A restored test-loop selection is honoured untouched.
|
||||
private func restoreInputSelection() {
|
||||
guard !didRestoreInput else { return }
|
||||
didRestoreInput = true
|
||||
|
||||
let defaults: UserDefaults = UserDefaults.standard
|
||||
if defaults.object(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey) != nil {
|
||||
let stored: Int = defaults.integer(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
|
||||
if stored >= 0, stored < shoeGaze.engine.numInputChannels {
|
||||
switchInput(to: .liveInput(channel: stored))
|
||||
} else if stored >= 0, shoeGaze.engine.numInputChannels == 0,
|
||||
MicrophonePermission.isAuthorized, let onEnableLiveInput {
|
||||
// iOS: a live choice was saved and the mic is already authorised — rebuild the
|
||||
// engine with an input channel silently (no prompt, since access is granted).
|
||||
onEnableLiveInput()
|
||||
guard case .liveInput = shoeGaze.inputSource else { return }
|
||||
MicrophonePermission.request { granted in
|
||||
if !granted {
|
||||
showMicDeniedAlert = true
|
||||
applyInputSource(.testLoop)
|
||||
}
|
||||
// A test-loop choice (or live with no host hook / no permission) leaves the test loop.
|
||||
} else if MicrophonePermission.isAuthorized, shoeGaze.engine.numInputChannels > 0 {
|
||||
// First launch with no saved choice but mic already granted → default to live input.
|
||||
switchInput(to: .liveInput(channel: 0))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ public struct TempoView: View {
|
||||
private static let minBpm: Double = 30.0
|
||||
private static let maxBpm: Double = 300.0
|
||||
private static let bpmStep: Double = 1.0
|
||||
/// Width of the editable BPM text field — fits three digits at the readout font.
|
||||
private static let bpmFieldWidth: CGFloat = 44
|
||||
private static let bpmFontSize: CGFloat = 18
|
||||
/// Maximum digits accepted in the BPM field (max 300 BPM is three digits).
|
||||
private static let bpmMaxDigits: Int = 3
|
||||
private static let rowSpacing: CGFloat = 10
|
||||
|
||||
// Metronome track: a dot swings wall-to-wall once per beat, pausing at each wall (the beat)
|
||||
@@ -56,12 +61,18 @@ public struct TempoView: View {
|
||||
/// Continuous beat position, polled from the clock; drives the metronome dot.
|
||||
@State private var beat: Double = 0.0
|
||||
|
||||
/// The editable BPM text. Kept in sync with `displayedBpm` while the field isn't focused; on
|
||||
/// commit it is validated (integer only), clamped to `[minBpm, maxBpm]`, and applied.
|
||||
@State private var bpmText: String
|
||||
@FocusState private var bpmFieldFocused: Bool
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameter shoeGaze: The session whose ``ShoeGaze/clock`` this view displays and drives.
|
||||
public init(shoeGaze: ShoeGaze) {
|
||||
self.shoeGaze = shoeGaze
|
||||
self._displayedBpm = State(initialValue: shoeGaze.clock.bpm)
|
||||
self._bpmText = State(initialValue: String(Int(shoeGaze.clock.bpm.rounded())))
|
||||
}
|
||||
|
||||
// MARK: - Body
|
||||
@@ -78,18 +89,12 @@ public struct TempoView: View {
|
||||
|
||||
if shoeGaze.tempoEnabled {
|
||||
metronome
|
||||
Text("\(Int(displayedBpm.rounded())) BPM")
|
||||
.font(.system(size: 18, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
bpmField
|
||||
Stepper(
|
||||
"",
|
||||
value: Binding(
|
||||
get: { displayedBpm },
|
||||
set: { newValue in
|
||||
let clamped: Double = min(max(newValue, TempoView.minBpm), TempoView.maxBpm)
|
||||
shoeGaze.clock.bpm = clamped
|
||||
displayedBpm = clamped
|
||||
}
|
||||
set: { newValue in applyBpm(newValue) }
|
||||
),
|
||||
in: TempoView.minBpm ... TempoView.maxBpm,
|
||||
step: TempoView.bpmStep
|
||||
@@ -106,11 +111,78 @@ public struct TempoView: View {
|
||||
while shoeGaze.tempoEnabled && !Task.isCancelled {
|
||||
beat = shoeGaze.clock.currentBeat
|
||||
displayedBpm = shoeGaze.clock.bpm
|
||||
// Don't overwrite the field mid-edit — only reflect external tempo changes when the
|
||||
// field isn't focused (tap tempo, stepper, MIDI, rig load).
|
||||
if !bpmFieldFocused {
|
||||
bpmText = String(Int(displayedBpm.rounded()))
|
||||
}
|
||||
try? await Task.sleep(nanoseconds: TempoView.pollIntervalNanoseconds)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - BPM field
|
||||
|
||||
/// Editable BPM readout. Accepts integer input, validated and clamped on commit (Return, or the
|
||||
/// keyboard's Done, or focus loss). Non-numeric or empty input reverts to the current tempo.
|
||||
private var bpmField: some View {
|
||||
HStack(spacing: TempoView.rowSpacing / 2) {
|
||||
TextField("", text: $bpmText)
|
||||
.textFieldStyle(.plain)
|
||||
.multilineTextAlignment(.trailing)
|
||||
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
.frame(width: TempoView.bpmFieldWidth)
|
||||
.fixedSize()
|
||||
.focused($bpmFieldFocused)
|
||||
.onSubmit { commitBpm() }
|
||||
#if os(iOS)
|
||||
.keyboardType(.numberPad)
|
||||
.toolbar {
|
||||
ToolbarItemGroup(placement: .keyboard) {
|
||||
Spacer()
|
||||
Button("Done") { bpmFieldFocused = false }
|
||||
}
|
||||
}
|
||||
#endif
|
||||
Text("BPM")
|
||||
.font(.system(size: TempoView.bpmFontSize, weight: .semibold, design: .rounded))
|
||||
.foregroundStyle(Color.white)
|
||||
}
|
||||
.onChange(of: bpmText) { _, newValue in
|
||||
// Reject non-numeric input as it is typed, and cap at three digits (max 300 BPM).
|
||||
let filtered: String = String(newValue.filter { $0.isNumber }.prefix(TempoView.bpmMaxDigits))
|
||||
if filtered != newValue {
|
||||
bpmText = filtered
|
||||
}
|
||||
}
|
||||
.onChange(of: bpmFieldFocused) { _, focused in
|
||||
// Commit when focus leaves the field (tap away / Done), the counterpart to onSubmit.
|
||||
if !focused {
|
||||
commitBpm()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates and applies the typed BPM: integers only, clamped to `[minBpm, maxBpm]`. Non-numeric
|
||||
/// or empty input reverts the field to the current tempo without changing it.
|
||||
private func commitBpm() {
|
||||
let digits: String = bpmText.filter { $0.isNumber }
|
||||
if let value: Int = Int(digits) {
|
||||
applyBpm(Double(value))
|
||||
} else {
|
||||
bpmText = String(Int(displayedBpm.rounded()))
|
||||
}
|
||||
}
|
||||
|
||||
/// Clamps `bpm` to the allowed range, applies it to the session, and syncs the field text.
|
||||
private func applyBpm(_ bpm: Double) {
|
||||
let clamped: Double = min(max(bpm, TempoView.minBpm), TempoView.maxBpm)
|
||||
shoeGaze.setBpm(clamped)
|
||||
displayedBpm = clamped
|
||||
bpmText = String(Int(clamped.rounded()))
|
||||
}
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
/// Horizontal pendulum: the dot maps `beat` through a cosine so it eases to a stop at each
|
||||
|
||||
@@ -105,6 +105,82 @@ struct CompressorPedalTests {
|
||||
#expect(labels == ["Input", "Threshold", "Ratio"])
|
||||
}
|
||||
|
||||
@Test func exposesSafetySwitch() throws {
|
||||
let pedal: CompressorPedal = CompressorPedal()
|
||||
let switchLabels: [String] = pedal.effectSwitches.map { $0.label }
|
||||
#expect(switchLabels == ["Safety"])
|
||||
let optionTitles: [String] = pedal.effectSwitches.first?.options.map { $0.title } ?? []
|
||||
#expect(optionTitles == ["Off", "On"])
|
||||
}
|
||||
|
||||
@Test func safetyLimiterCapsPeaks() throws {
|
||||
// Drive the compressor hard (hot input + makeup gain) so its non-zero attack lets
|
||||
// transients overshoot. With the safety limiter engaged the output peak must stay
|
||||
// near full scale; the two switch states must also produce different output.
|
||||
let renderDuration: Double = 0.1
|
||||
let sampleRate: Double = 44100.0
|
||||
|
||||
func render(safety: Double) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: renderDuration,
|
||||
sampleRate: sampleRate
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer {
|
||||
engine.busAllocator.releaseAudioBus(srcBus)
|
||||
engine.busAllocator.releaseAudioBus(dstBus)
|
||||
}
|
||||
|
||||
let source: TestLoopSource = TestLoopSource(targetBus: srcBus.index)
|
||||
let pedal: CompressorPedal = CompressorPedal(
|
||||
inputBus: srcBus.index,
|
||||
outputBus: dstBus.index
|
||||
)
|
||||
pedal.sampleRate = sampleRate
|
||||
pedal.inputGain = 24.0
|
||||
pedal.threshold = -30.0
|
||||
pedal.ratio = 8.0
|
||||
pedal.safetyLimiter = safety
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(source)
|
||||
try engine.add(pedal, position: NodePosition.after(source))
|
||||
try engine.add(master, position: NodePosition.after(pedal))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
let off: [Float] = try render(safety: 0.0)
|
||||
let on: [Float] = try render(safety: 1.0)
|
||||
|
||||
#expect(hasNonSilentOutput(off), "safety-off render was silent")
|
||||
#expect(hasNonSilentOutput(on), "safety-on render was silent")
|
||||
|
||||
// Skip the safety limiter's look-ahead fill window before measuring the peak.
|
||||
let lookAheadFillSamples: Int = 2048
|
||||
guard on.count > lookAheadFillSamples else { return }
|
||||
let onWindow: ArraySlice<Float> = on[lookAheadFillSamples...]
|
||||
let onPeak: Float = onWindow.reduce(0) { Swift.max($0, abs($1)) }
|
||||
|
||||
// Safety ceiling is just under full scale; downstream master only attenuates.
|
||||
let ceilingTolerance: Float = 0.05
|
||||
#expect(onPeak <= 1.0 + ceilingTolerance, "safety limiter failed to cap peak: \(onPeak)")
|
||||
|
||||
// The two switch positions must differ.
|
||||
let skip: Int = lookAheadFillSamples
|
||||
let window: Int = 2048
|
||||
guard off.count >= skip + window, on.count >= skip + window else { return }
|
||||
let offWindow: [Float] = Array(off[skip..<(skip + window)])
|
||||
let onWindow2: [Float] = Array(on[skip..<(skip + window)])
|
||||
let ssd: Double = zip(offWindow, onWindow2).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
#expect(ssd > 0, "safety switch had no effect on output")
|
||||
}
|
||||
|
||||
@Test func inputGainChangesOutput() throws {
|
||||
// The pre-compression input gain stage must alter the output: boosting the input
|
||||
// drives more of the signal past the threshold, changing the compressed result.
|
||||
|
||||
@@ -84,6 +84,16 @@ struct DistortionPedalTests {
|
||||
#expect(labels == ["Drive", "Tone"])
|
||||
}
|
||||
|
||||
@Test func outputStaysBoundedAtHighDrive() throws {
|
||||
// The final hard clip (after the tone low-pass) must re-establish the ±1 output bound
|
||||
// even at extreme drive, despite the oversampled clip sitting before the low-pass.
|
||||
let samples: [Float] = try render { pedal in pedal.drive = 50.0; pedal.tone = 6000.0 }
|
||||
let skip: Int = 2048
|
||||
guard samples.count > skip else { return }
|
||||
let peak: Float = samples[skip...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(peak <= 1.05, "distortion output exceeded the clip ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func registeredInBuiltInRegistry() throws {
|
||||
let pedal: Pedal? = PedalRegistry.makePedal(type: "Distortion")
|
||||
#expect(pedal is DistortionPedal)
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
// InputMuteTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
/// Tests for the input mute — the hard gate on the signal feeding every board, distinct from the
|
||||
/// rig-output mute.
|
||||
@MainActor
|
||||
@Suite("InputMute")
|
||||
struct InputMuteTests {
|
||||
|
||||
/// A fresh session defaults audible at the library level (the app mutes on engine Start), and
|
||||
/// muting drives every board's input writer to the silent gain.
|
||||
@Test func defaultsAudibleThenMuteDrivesInputNodes() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
|
||||
#expect(!sg.inputMuted)
|
||||
let audible: Double = 0.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == audible })
|
||||
#expect(!sg.inputMuteNodeValues.isEmpty)
|
||||
|
||||
sg.setInputMuted(true)
|
||||
let muted: Double = 1.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == muted })
|
||||
}
|
||||
}
|
||||
|
||||
/// `setInputMuted(false)` un-mutes every input node and clears the flag; re-muting restores it.
|
||||
@Test func setInputMutedDrivesAllNodes() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
|
||||
sg.setInputMuted(false)
|
||||
#expect(!sg.inputMuted)
|
||||
let audible: Double = 0.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == audible })
|
||||
|
||||
sg.toggleInputMuted()
|
||||
#expect(sg.inputMuted)
|
||||
let muted: Double = 1.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == muted })
|
||||
}
|
||||
}
|
||||
|
||||
/// A board added while the input is un-muted comes up audible — the current mute state is
|
||||
/// applied to newly-wired input nodes, not just the ones present when the toggle flipped.
|
||||
@Test func newBoardAdoptsCurrentMuteState() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let first: PedalBoard = try sg.addBoard()
|
||||
try first.add(VolumePedal())
|
||||
try sg.finalizeBoard(first)
|
||||
|
||||
sg.setInputMuted(false)
|
||||
|
||||
let second: PedalBoard = try sg.addBoard()
|
||||
try second.add(VolumePedal())
|
||||
try sg.finalizeBoard(second)
|
||||
|
||||
let audible: Double = 0.0
|
||||
#expect(sg.inputMuteNodeValues.count == 2)
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == audible })
|
||||
}
|
||||
}
|
||||
|
||||
/// A muted input renders **exactly** silent through a full render — the kill-switch gate reaches
|
||||
/// zero with no residual. A lagged gate leaked a faint transient on its first blocks; the hard
|
||||
/// gate does not.
|
||||
@Test func mutedInputRendersSilent() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.25, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
sg.setInputMuted(true) // mute explicitly before Start (library default is audible)
|
||||
|
||||
try engine.start()
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(!hasNonSilentOutput(samples),
|
||||
"a muted input must render silent — the kill-switch gate leaves no residual")
|
||||
}
|
||||
}
|
||||
|
||||
/// Muting while the engine is stopped **primes** every input node — its ramp start (`previous
|
||||
/// OutputValue`) equals the muted target — so the next Start renders muted from block zero with no
|
||||
/// audible→muted ramp. Guards against the `UIParamNode` one-block ramp leaking a fresh node's
|
||||
/// prior (audible) value. A freshly-added board is primed the same way.
|
||||
@Test func stoppedMutePrimesNodesSoTheresNoStartRamp() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
|
||||
// Default audible: node value and ramp start both at 0 (no pending ramp).
|
||||
let audible: Double = 0.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == audible })
|
||||
#expect(sg.inputMutePreviousValues.allSatisfy { $0 == audible })
|
||||
|
||||
// Mute while stopped: both the target and the ramp start move to 1 → no leak on Start.
|
||||
sg.setInputMuted(true)
|
||||
let muted: Double = 1.0
|
||||
#expect(sg.inputMuteNodeValues.allSatisfy { $0 == muted })
|
||||
#expect(sg.inputMutePreviousValues.allSatisfy { $0 == muted },
|
||||
"a stopped-engine mute must prime the ramp start so the first render can't ramp")
|
||||
|
||||
// A board added while muted comes up primed muted too.
|
||||
let second: PedalBoard = try sg.addBoard()
|
||||
try second.add(VolumePedal())
|
||||
try sg.finalizeBoard(second)
|
||||
#expect(sg.inputMutePreviousValues.allSatisfy { $0 == muted })
|
||||
#expect(sg.inputMuteNodeValues.count == 2)
|
||||
}
|
||||
}
|
||||
|
||||
/// Un-muting the input lets the test-loop signal through — the gate opens fully.
|
||||
@Test func unmutedInputRendersSignal() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.25, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
sg.setInputMuted(false)
|
||||
|
||||
try engine.start()
|
||||
let samples: [Float] = readStereoCAF(url: url)
|
||||
#expect(hasNonSilentOutput(samples),
|
||||
"an un-muted input must pass the test-loop signal through")
|
||||
}
|
||||
}
|
||||
|
||||
/// The live-input pass-through path is driven by `setInputMuted` identically to the test-loop tap.
|
||||
@Test func liveInputPassThroughIsMuted() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 1,
|
||||
numAudioBuses: 256
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .liveInput(channel: 0))
|
||||
|
||||
try withExtendedLifetime(sg) {
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
|
||||
let audible: Double = 0.0
|
||||
#expect(!sg.inputMuted)
|
||||
#expect(sg.inputMuteNodeValues == [audible])
|
||||
|
||||
sg.setInputMuted(true)
|
||||
let muted: Double = 1.0
|
||||
#expect(sg.inputMuteNodeValues == [muted])
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ struct LimiterPedalTests {
|
||||
private func render(
|
||||
boost: Double,
|
||||
ceiling: Double,
|
||||
release: Double = 0.05,
|
||||
sampleRate: Double = 44100.0
|
||||
) throws -> [Float] {
|
||||
let renderDuration: Double = 0.1
|
||||
@@ -43,6 +44,7 @@ struct LimiterPedalTests {
|
||||
pedal.sampleRate = sampleRate
|
||||
pedal.boost = boost
|
||||
pedal.ceiling = ceiling
|
||||
pedal.release = release
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
|
||||
try engine.add(source)
|
||||
@@ -78,4 +80,32 @@ struct LimiterPedalTests {
|
||||
let tolerance: Float = 0.05
|
||||
#expect(peak <= Float(ceiling) + tolerance, "Limiter overshot ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func exposesBoostCeilingReleaseKnobs() throws {
|
||||
let pedal: LimiterPedal = LimiterPedal()
|
||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
||||
#expect(labels == ["Boost", "Ceiling", "Release"])
|
||||
}
|
||||
|
||||
@Test func releaseChangesOutput() throws {
|
||||
// Same drive and ceiling, different release times: the gain recovers between peaks
|
||||
// at different rates, so the limited output differs. Ceiling still holds for both.
|
||||
let ceiling: Double = 0.4
|
||||
let fast: [Float] = try render(boost: 12.0, ceiling: ceiling, release: 0.01)
|
||||
let slow: [Float] = try render(boost: 12.0, ceiling: ceiling, release: 0.5)
|
||||
|
||||
#expect(hasNonSilentOutput(fast), "fast-release render was silent")
|
||||
#expect(hasNonSilentOutput(slow), "slow-release render was silent")
|
||||
|
||||
let skip: Int = 2048
|
||||
let window: Int = 2048
|
||||
guard fast.count >= skip + window, slow.count >= skip + window else { return }
|
||||
let fastWindow: [Float] = Array(fast[skip..<(skip + window)])
|
||||
let slowWindow: [Float] = Array(slow[skip..<(skip + window)])
|
||||
let ssd: Double = zip(fastWindow, slowWindow).reduce(0.0) { acc, pair in
|
||||
let diff: Double = Double(pair.0 - pair.1)
|
||||
return acc + diff * diff
|
||||
}
|
||||
#expect(ssd > 0, "release time had no effect on limiter output")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -181,6 +181,42 @@ struct MIDIControllerCCTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func ccIsIgnoredWhileParameterIsTempoSynced() throws {
|
||||
// A CC bound to a parameter that is locked to a note division must be ignored — the value is
|
||||
// tempo-derived and a CC write would be overwritten on the next tempo change. The binding
|
||||
// stays intact and resumes control once the parameter is set back to Free.
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 128)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
sg.clock.bpm = 120.0
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
let delay: DelayPedal = DelayPedal()
|
||||
try board.add(delay)
|
||||
try sg.finalizeBoard(board)
|
||||
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// Bind CC 21 to Time (control 0 on a Delay pedal).
|
||||
controller.armCCLearn(pedalControl(delay.id, 0))
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 0))
|
||||
|
||||
// Lock Time to a quarter note — 0.5 s at 120 BPM.
|
||||
delay.setSync(.division(.quarter), for: "time")
|
||||
let syncedValue: Double = delay.$time.value
|
||||
#expect(abs(syncedValue - 0.5) < 1e-9)
|
||||
|
||||
// A CC while synced must not move the value.
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
|
||||
#expect(abs(delay.$time.value - syncedValue) < 1e-9, "CC must not drive a tempo-synced parameter")
|
||||
|
||||
// Back to Free — the same binding drives the control again.
|
||||
delay.setSync(.free, for: "time")
|
||||
let timeMax: Double = delay.ccMappableControls[0].range.upperBound
|
||||
controller.ingestForTesting(.controlChange(channel: 0, controller: 21, value: 127))
|
||||
#expect(abs(delay.$time.value - timeMax) < 1e-9, "CC resumes control once the parameter is Free")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func unboundCCIsIgnored() throws {
|
||||
let (controller, sg, board, url): (MIDIController, ShoeGaze, PedalBoard, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// MIDIControllerKeyTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("MIDIController key bindings")
|
||||
struct MIDIControllerKeyTests {
|
||||
|
||||
/// Builds an engine + a one-board rig (a single Volume pedal) + a controller.
|
||||
private func makeRig() throws -> (MIDIController, ShoeGaze, URL) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
board.label = "Board 1"
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
let controller: MIDIController = MIDIController(engine: engine, shoeGaze: sg)
|
||||
return (controller, sg, url)
|
||||
}
|
||||
|
||||
@Test func learnCapturesKeyAndFiresCallback() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
var changed: Bool = false
|
||||
controller.onMapChanged = { changed = true }
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
let consumed: Bool = controller.ingestKey("b")
|
||||
|
||||
#expect(consumed, "the learn press is consumed")
|
||||
#expect(controller.learnTarget == nil)
|
||||
#expect(changed)
|
||||
#expect(controller.keyBinding(for: .rigBypass)?.key == "b")
|
||||
#expect(sg.midiMap?.keys.count == 1)
|
||||
#expect(sg.rigBypassed == false, "learn must not toggle")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func keyLatchesOnEachPress() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b") // learn only
|
||||
#expect(sg.rigBypassed == false)
|
||||
|
||||
#expect(controller.ingestKey("b"))
|
||||
#expect(sg.rigBypassed == true, "first press engages")
|
||||
#expect(controller.ingestKey("b"))
|
||||
#expect(sg.rigBypassed == false, "second press releases")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func caseInsensitiveMatch() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b")
|
||||
#expect(controller.ingestKey("B"), "an uppercase press matches a lowercase binding")
|
||||
#expect(sg.rigBypassed == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func shiftDistinguishesTwoBindingsOnTheSameKey() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b", modifiers: [])
|
||||
controller.armKeyLearn(.rigMute)
|
||||
_ = controller.ingestKey("b", modifiers: [.shift])
|
||||
|
||||
#expect(sg.midiMap?.keys.count == 2, "b and ⇧b are independent bindings")
|
||||
|
||||
#expect(controller.ingestKey("b", modifiers: []))
|
||||
#expect(sg.rigBypassed == true, "unmodified b drives bypass")
|
||||
#expect(sg.rigMuted == false, "unmodified b must not fire the ⇧b binding")
|
||||
|
||||
#expect(controller.ingestKey("b", modifiers: [.shift]))
|
||||
#expect(sg.rigMuted == true, "⇧b drives mute")
|
||||
#expect(sg.rigBypassed == true, "⇧b must not re-fire the plain-b binding")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func modifierMismatchIsNotConsumed() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b", modifiers: [.shift]) // learn ⇧b
|
||||
#expect(controller.ingestKey("b", modifiers: []) == false, "plain b does not match ⇧b")
|
||||
#expect(controller.ingestKey("b", modifiers: [.control]) == false, "⌃b does not match ⇧b")
|
||||
#expect(sg.rigBypassed == false)
|
||||
#expect(controller.ingestKey("b", modifiers: [.shift]), "⇧b matches")
|
||||
#expect(sg.rigBypassed == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func unboundKeyIsNotConsumed() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b")
|
||||
#expect(controller.ingestKey("z") == false, "an unbound key falls through")
|
||||
#expect(sg.rigBypassed == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func digitKeyBinds() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("3")
|
||||
#expect(controller.keyBinding(for: .rigBypass)?.key == "3")
|
||||
#expect(controller.ingestKey("3"))
|
||||
#expect(sg.rigBypassed == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func nonAlphanumericKeyRejected() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
// Return, Tab, and Escape are single Characters but not letters/digits — they must not be
|
||||
// learnable, or binding one would silently swallow it everywhere in the app.
|
||||
#expect(controller.ingestKey("\r") == false)
|
||||
#expect(controller.ingestKey("\t") == false)
|
||||
#expect(controller.ingestKey("\u{1B}") == false)
|
||||
#expect(controller.ingestKey(" ") == false)
|
||||
#expect(controller.learnTarget != nil, "a rejected press leaves learn armed")
|
||||
#expect(sg.midiMap?.keys.isEmpty ?? true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func multiCharacterInputRejected() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
#expect(controller.ingestKey("ab") == false, "a multi-character press is ignored")
|
||||
#expect(controller.learnTarget != nil, "an ignored press leaves learn armed")
|
||||
#expect(sg.midiMap?.keys.isEmpty ?? true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func keyBindingSurvivesSaveLoadAndStillFires() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let preset: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".json")
|
||||
defer { try? FileManager.default.removeItem(at: preset) }
|
||||
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b")
|
||||
|
||||
try sg.saveRig(to: preset)
|
||||
try sg.loadRig(from: preset)
|
||||
|
||||
#expect(sg.midiMap?.keys.first?.key == "b", "the key binding survives a file round-trip")
|
||||
#expect(controller.ingestKey("b"), "the restored binding still fires")
|
||||
#expect(sg.rigBypassed == true)
|
||||
withExtendedLifetime(sg) { }
|
||||
}
|
||||
|
||||
@Test func clearRemovesBinding() throws {
|
||||
let (controller, sg, url): (MIDIController, ShoeGaze, URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
controller.armKeyLearn(.rigBypass)
|
||||
_ = controller.ingestKey("b")
|
||||
#expect(controller.keyBinding(for: .rigBypass) != nil)
|
||||
|
||||
controller.clearKeyBinding(for: .rigBypass)
|
||||
#expect(controller.keyBinding(for: .rigBypass) == nil)
|
||||
#expect(controller.ingestKey("b") == false, "a cleared key no longer fires")
|
||||
#expect(sg.rigBypassed == false)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -80,6 +80,26 @@ struct MIDIControllerPCTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func inputMuteLatchesOnEachPressAndIsSeparateFromRigMute() throws {
|
||||
let (controller, sg, _, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
withExtendedLifetime(sg) {
|
||||
// A fresh library session starts audible (the app mutes on engine Start).
|
||||
#expect(sg.inputMuted == false, "input defaults audible at the library level")
|
||||
|
||||
controller.armSwitchLearn(.inputMute)
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 2)) // learn only
|
||||
#expect(sg.inputMuted == false, "learn must not toggle")
|
||||
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 2))
|
||||
#expect(sg.inputMuted == true, "first press mutes the input")
|
||||
#expect(sg.rigMuted == false, "input mute must not touch the rig-output mute")
|
||||
controller.ingestForTesting(.programChange(channel: 0, program: 2))
|
||||
#expect(sg.inputMuted == false, "second press un-mutes the input")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func pedalBypassLatches() throws {
|
||||
let (controller, sg, boards, url): (MIDIController, ShoeGaze, [PedalBoard], URL) = try makeRig()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
@@ -44,6 +44,16 @@ struct MIDIMapCodableTests {
|
||||
channel: 0,
|
||||
target: .boardLevel(boardID: Self.boardID, boardLabelHint: "Board 1")
|
||||
),
|
||||
],
|
||||
keys: [
|
||||
MIDIMap.KeyBinding(key: "b", action: .rigBypass, displayNameHint: "Rig"),
|
||||
MIDIMap.KeyBinding(key: "b", modifiers: [.shift], action: .rigMute),
|
||||
MIDIMap.KeyBinding(
|
||||
key: "r",
|
||||
modifiers: [.control, .option],
|
||||
action: .pedalAction(pedalID: Self.looperID, kind: .looperRecordStop),
|
||||
displayNameHint: "Looper"
|
||||
),
|
||||
]
|
||||
)
|
||||
}
|
||||
@@ -79,4 +89,43 @@ struct MIDIMapCodableTests {
|
||||
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
|
||||
#expect(decoded.midiMap == nil, "legacy rig JSON should decode with a nil midiMap")
|
||||
}
|
||||
|
||||
@Test func keyBindingsSurviveArchiveDocumentRoundTrip() throws {
|
||||
// The `.shoegaze` archive / share path wraps a RigEntry → ShoeGazeState → MIDIMap. Verify a
|
||||
// key binding survives a full document encode/decode, not just a bare MIDIMap round-trip.
|
||||
let state: ShoeGazeState = ShoeGazeState(boards: [], midiMap: sampleMap())
|
||||
let entry: RigEntry = RigEntry(name: "Keys", state: state)
|
||||
let document: ShoeGazeDocument = ShoeGazeDocument(rig: entry)
|
||||
let data: Data = try document.data()
|
||||
let decoded: ShoeGazeDocument = try ShoeGazeDocument.decoded(from: data)
|
||||
let restored: MIDIMap? = decoded.rigEntries?.first?.state.midiMap
|
||||
#expect(restored?.keys == sampleMap().keys)
|
||||
}
|
||||
|
||||
@Test func keyBindingWithoutModifiersDecodesUnmodified() throws {
|
||||
// A key binding saved before modifiers existed has a `key` + `action` but no `modifiers`.
|
||||
// It must decode as an unmodified binding, not fail and drop the map.
|
||||
let json: String = #"""
|
||||
{"switches":[],"ccs":[],"keys":[{"key":"b","action":{"rigBypass":{}}}]}
|
||||
"""#
|
||||
let data: Data = Data(json.utf8)
|
||||
let decoded: MIDIMap = try JSONDecoder().decode(MIDIMap.self, from: data)
|
||||
#expect(decoded.keys.count == 1)
|
||||
#expect(decoded.keys.first?.key == "b")
|
||||
#expect(decoded.keys.first?.modifiers == [])
|
||||
}
|
||||
|
||||
@Test func mapWithoutKeysDecodesWithEmptyKeysNotDropped() throws {
|
||||
// A rig saved before keyboard mapping existed has a midiMap with switches/ccs but no `keys`.
|
||||
// It must decode with keys == [] AND keep its switch/cc bindings (a missing-key failure that
|
||||
// fell through to the malformed path would silently drop the whole map).
|
||||
let json: String = #"""
|
||||
{"version":1,"boards":[],"midiMap":{"switches":[{"program":3,"action":{"rigBypass":{}}}],"ccs":[]}}
|
||||
"""#
|
||||
let data: Data = Data(json.utf8)
|
||||
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
|
||||
#expect(decoded.midiMap?.keys == [], "absent keys should decode to an empty array")
|
||||
#expect(decoded.midiMap?.switches.count == 1, "switch bindings must survive the missing keys")
|
||||
#expect(decoded.midiMap?.switches.first?.program == 3)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
// NoteDivisionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@Suite("NoteDivision")
|
||||
struct NoteDivisionTests {
|
||||
|
||||
private let tolerance: Double = 1e-9
|
||||
|
||||
@Test func beatsMatchMusicalValues() {
|
||||
#expect(NoteDivision.whole.beats == 4.0)
|
||||
#expect(NoteDivision.dottedHalf.beats == 3.0)
|
||||
#expect(NoteDivision.half.beats == 2.0)
|
||||
#expect(NoteDivision.dottedQuarter.beats == 1.5)
|
||||
#expect(NoteDivision.quarter.beats == 1.0)
|
||||
#expect(abs(NoteDivision.quarterTriplet.beats - 2.0 / 3.0) < tolerance)
|
||||
#expect(NoteDivision.dottedEighth.beats == 0.75)
|
||||
#expect(NoteDivision.eighth.beats == 0.5)
|
||||
#expect(abs(NoteDivision.eighthTriplet.beats - 1.0 / 3.0) < tolerance)
|
||||
#expect(NoteDivision.sixteenth.beats == 0.25)
|
||||
#expect(abs(NoteDivision.sixteenthTriplet.beats - 1.0 / 6.0) < tolerance)
|
||||
}
|
||||
|
||||
@Test func dottedIsHalfAgainThePlainValue() {
|
||||
#expect(NoteDivision.dottedQuarter.beats == NoteDivision.quarter.beats * 1.5)
|
||||
#expect(NoteDivision.dottedEighth.beats == NoteDivision.eighth.beats * 1.5)
|
||||
}
|
||||
|
||||
@Test func casesAreOrderedSlowToFast() {
|
||||
let beats: [Double] = NoteDivision.allCases.map { $0.beats }
|
||||
#expect(beats == beats.sorted(by: >), "cases must be ordered longest (slowest) first")
|
||||
}
|
||||
|
||||
@Test func labelsAreUnique() {
|
||||
let labels: [String] = NoteDivision.allCases.map { $0.label }
|
||||
#expect(Set(labels).count == labels.count)
|
||||
}
|
||||
|
||||
@Test func codableRoundTrips() throws {
|
||||
for division: NoteDivision in NoteDivision.allCases {
|
||||
let data: Data = try JSONEncoder().encode(division)
|
||||
let decoded: NoteDivision = try JSONDecoder().decode(NoteDivision.self, from: data)
|
||||
#expect(decoded == division)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// OversampledRingModulatorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("OversampledRingModulator")
|
||||
struct OversampledRingModulatorTests {
|
||||
|
||||
private let sampleRate: Double = 44100.0
|
||||
|
||||
/// Minimal synth: a sine through an `OversampledRingModulator`, written to a mono bus.
|
||||
private final class RingSynth: SynthesizerBase {
|
||||
private let inFreq: Double
|
||||
private let carrierFreq: Double
|
||||
private let factor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(inFreq: Double, carrierFreq: Double, factor: Int, outBus: Int) {
|
||||
self.inFreq = inFreq
|
||||
self.carrierFreq = carrierFreq
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: inFreq)
|
||||
output(bus: outBus, source: OversampledRingModulator(
|
||||
osc, freq: carrierFreq, oversample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(inFreq: Double, carrierFreq: Double, factor: Int) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: RingSynth = RingSynth(
|
||||
inFreq: inFreq, carrierFreq: carrierFreq, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
|
||||
var out: [Double] = []
|
||||
var i: Int = skip * 2
|
||||
while i < samples.count {
|
||||
out.append(Double(samples[i]))
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
|
||||
let omega: Double = 2.0 * Double.pi * cyclesPerSample
|
||||
let cosine: Double = cos(omega)
|
||||
let sine: Double = sin(omega)
|
||||
let coeff: Double = 2.0 * cosine
|
||||
var s1: Double = 0.0
|
||||
var s2: Double = 0.0
|
||||
for v: Double in x {
|
||||
let s0: Double = v + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
let real: Double = s1 - s2 * cosine
|
||||
let imag: Double = s2 * sine
|
||||
return (real * real + imag * imag).squareRoot()
|
||||
}
|
||||
|
||||
private func naiveRingMod(inFreq: Double, carrierFreq: Double, count: Int) -> [Double] {
|
||||
let inCps: Double = inFreq / sampleRate
|
||||
let cCps: Double = carrierFreq / sampleRate
|
||||
var out: [Double] = []
|
||||
out.reserveCapacity(count)
|
||||
for n: Int in 0..<count {
|
||||
let x: Double = sin(2.0 * Double.pi * inCps * Double(n))
|
||||
let c: Double = sin(2.0 * Double.pi * cCps * Double(n))
|
||||
out.append(x * c)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test func reducesSumSidebandAliasVersusNaive() throws {
|
||||
// in = 0.20·Fs, carrier = 0.35·Fs. Difference sideband = 0.15·Fs (legit, below Nyquist);
|
||||
// sum sideband = 0.55·Fs, which folds to a 0.45·Fs alias at the base rate. Measure the
|
||||
// alias relative to the legit difference sideband (self-normalising).
|
||||
let inHz: Double = 0.20 * sampleRate
|
||||
let carrierHz: Double = 0.35 * sampleRate
|
||||
let diffBin: Double = 0.15 // |0.35 − 0.20|
|
||||
let aliasBin: Double = 0.45 // |1 − 0.55|
|
||||
|
||||
let os: [Float] = try render(inFreq: inHz, carrierFreq: carrierHz, factor: 2)
|
||||
let osLeft: [Double] = leftChannel(os, skip: 2048)
|
||||
#expect(osLeft.count > 2048)
|
||||
|
||||
let osDiff: Double = goertzelMagnitude(osLeft, cyclesPerSample: diffBin)
|
||||
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
|
||||
let osRatio: Double = osAlias / osDiff
|
||||
|
||||
let naive: [Double] = naiveRingMod(inFreq: inHz, carrierFreq: carrierHz, count: osLeft.count)
|
||||
let nDiff: Double = goertzelMagnitude(naive, cyclesPerSample: diffBin)
|
||||
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
|
||||
let naiveRatio: Double = nAlias / nDiff
|
||||
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(
|
||||
osRatio < naiveRatio * 0.5,
|
||||
"oversampling did not reduce ring-mod aliasing: os=\(osRatio) naive=\(naiveRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func producesNonSilentOutput() throws {
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: 220.0, factor: 2)
|
||||
#expect(hasNonSilentOutput(os), "ring modulator produced silence")
|
||||
}
|
||||
|
||||
@Test func negativeCarrierStaysFiniteAndBounded() throws {
|
||||
// A negative carrier frequency drives the phase increment negative; the phase must wrap
|
||||
// both directions rather than growing unbounded and pushing sin() out of accurate range.
|
||||
let os: [Float] = try render(inFreq: 440.0, carrierFreq: -220.0, factor: 2)
|
||||
let left: [Double] = leftChannel(os, skip: 1024)
|
||||
#expect(!left.isEmpty)
|
||||
#expect(left.allSatisfy { $0.isFinite }, "negative carrier produced non-finite output")
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "negative carrier output was not bounded: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
// OversampledSaturatorTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("OversampledSaturator")
|
||||
struct OversampledSaturatorTests {
|
||||
|
||||
private let sampleRate: Double = 44100.0
|
||||
|
||||
/// Minimal synth: a sine through an `OversampledSaturator`, written to a mono bus.
|
||||
private final class SaturatorSynth: SynthesizerBase {
|
||||
private let freq: Double
|
||||
private let drive: Double
|
||||
private let curve: SaturationCurve
|
||||
private let factor: Int
|
||||
private let outBus: Int
|
||||
|
||||
init(freq: Double, drive: Double, curve: SaturationCurve, factor: Int, outBus: Int) {
|
||||
self.freq = freq
|
||||
self.drive = drive
|
||||
self.curve = curve
|
||||
self.factor = factor
|
||||
self.outBus = outBus
|
||||
super.init()
|
||||
}
|
||||
|
||||
override func build() {
|
||||
let osc: OscSin.Audio = OscSin.Audio(freq: freq)
|
||||
output(bus: outBus, source: OversampledSaturator(
|
||||
osc, drive: drive, curve: curve, oversample: factor))
|
||||
}
|
||||
}
|
||||
|
||||
private func render(
|
||||
freq: Double,
|
||||
drive: Double,
|
||||
curve: SaturationCurve,
|
||||
factor: Int
|
||||
) throws -> [Float] {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.15, numAudioBuses: 64)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||
defer { engine.busAllocator.releaseAudioBus(dstBus) }
|
||||
let synth: SaturatorSynth = SaturatorSynth(
|
||||
freq: freq, drive: drive, curve: curve, factor: factor, outBus: dstBus.index)
|
||||
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||
try engine.add(synth)
|
||||
try engine.add(master, position: NodePosition.after(synth))
|
||||
try engine.start()
|
||||
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
}
|
||||
|
||||
/// Left channel (interleaved stereo), warm-up frames skipped.
|
||||
private func leftChannel(_ samples: [Float], skip: Int) -> [Double] {
|
||||
var out: [Double] = []
|
||||
var i: Int = skip * 2
|
||||
while i < samples.count {
|
||||
out.append(Double(samples[i]))
|
||||
i += 2
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
/// Goertzel magnitude at normalised frequency `cyclesPerSample`.
|
||||
private func goertzelMagnitude(_ x: [Double], cyclesPerSample: Double) -> Double {
|
||||
let omega: Double = 2.0 * Double.pi * cyclesPerSample
|
||||
let cosine: Double = cos(omega)
|
||||
let sine: Double = sin(omega)
|
||||
let coeff: Double = 2.0 * cosine
|
||||
var s1: Double = 0.0
|
||||
var s2: Double = 0.0
|
||||
for v: Double in x {
|
||||
let s0: Double = v + coeff * s1 - s2
|
||||
s2 = s1
|
||||
s1 = s0
|
||||
}
|
||||
let real: Double = s1 - s2 * cosine
|
||||
let imag: Double = s2 * sine
|
||||
return (real * real + imag * imag).squareRoot()
|
||||
}
|
||||
|
||||
/// A naive base-rate hard clipper on the same sine — the alias-generating baseline the
|
||||
/// oversampled path is meant to beat.
|
||||
private func naiveHardClip(
|
||||
freq: Double,
|
||||
drive: Double,
|
||||
low: Double,
|
||||
high: Double,
|
||||
count: Int
|
||||
) -> [Double] {
|
||||
let cyclesPerSample: Double = freq / sampleRate
|
||||
var out: [Double] = []
|
||||
out.reserveCapacity(count)
|
||||
for n: Int in 0..<count {
|
||||
let x: Double = sin(2.0 * Double.pi * cyclesPerSample * Double(n))
|
||||
let shaped: Double = tanh(x) * drive
|
||||
out.append(Swift.min(high, Swift.max(low, shaped)))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@Test func reducesAliasingVersusNaiveHardClip() throws {
|
||||
// 13230 Hz = 0.3·Fs. A symmetric clipper's dominant 3rd harmonic lands at 0.9·Fs,
|
||||
// which folds to a 0.1·Fs (4410 Hz) alias at the base rate. Measure the alias energy
|
||||
// RELATIVE to the fundamental (self-normalising, so downstream routing gain cancels).
|
||||
let fundamentalHz: Double = 0.3 * sampleRate
|
||||
let aliasHz: Double = 0.1 * sampleRate // |3·0.3 − 1|·Fs
|
||||
let drive: Double = 5.0
|
||||
let low: Double = -1.0
|
||||
let high: Double = 1.0
|
||||
|
||||
let os: [Float] = try render(
|
||||
freq: fundamentalHz, drive: drive,
|
||||
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
|
||||
let osLeft: [Double] = leftChannel(os, skip: 2048)
|
||||
#expect(osLeft.count > 2048)
|
||||
|
||||
let fundamentalBin: Double = fundamentalHz / sampleRate
|
||||
let aliasBin: Double = aliasHz / sampleRate
|
||||
|
||||
let osFund: Double = goertzelMagnitude(osLeft, cyclesPerSample: fundamentalBin)
|
||||
let osAlias: Double = goertzelMagnitude(osLeft, cyclesPerSample: aliasBin)
|
||||
let osRatio: Double = osAlias / osFund
|
||||
|
||||
let naive: [Double] = naiveHardClip(
|
||||
freq: fundamentalHz, drive: drive, low: low, high: high, count: osLeft.count)
|
||||
let nFund: Double = goertzelMagnitude(naive, cyclesPerSample: fundamentalBin)
|
||||
let nAlias: Double = goertzelMagnitude(naive, cyclesPerSample: aliasBin)
|
||||
let naiveRatio: Double = nAlias / nFund
|
||||
|
||||
// The naive clipper must actually alias (sanity), and oversampling must cut the
|
||||
// alias-to-fundamental ratio by at least half. In practice the 4× halfband path
|
||||
// attenuates it far more; 0.5 is a conservative, non-flaky bound.
|
||||
#expect(naiveRatio > 0.05, "baseline did not alias as expected (ratio=\(naiveRatio))")
|
||||
#expect(
|
||||
osRatio < naiveRatio * 0.5,
|
||||
"oversampling did not reduce aliasing: os=\(osRatio) naive=\(naiveRatio)"
|
||||
)
|
||||
}
|
||||
|
||||
@Test func hardClipCurveRespectsBounds() throws {
|
||||
// With a hard-clip curve the output must stay within [low, high] (plus a small margin
|
||||
// for halfband ripple / routing) regardless of how hard it is driven.
|
||||
let low: Double = -0.5
|
||||
let high: Double = 0.5
|
||||
let samples: [Float] = try render(
|
||||
freq: 2000.0, drive: 10.0,
|
||||
curve: .tanhPostGainHardClip(low: low, high: high), factor: 4)
|
||||
let left: [Double] = leftChannel(samples, skip: 2048)
|
||||
#expect(!left.isEmpty)
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
let margin: Double = 0.1
|
||||
#expect(peak <= high + margin, "hard-clip curve exceeded its ceiling: peak=\(peak)")
|
||||
}
|
||||
|
||||
@Test func softCurvesStayBounded() throws {
|
||||
// tanh-family curves saturate toward ±1; output must stay bounded well under runaway.
|
||||
let samples: [Float] = try render(
|
||||
freq: 2000.0, drive: 30.0, curve: .tanhPreGain, factor: 2)
|
||||
let left: [Double] = leftChannel(samples, skip: 2048)
|
||||
#expect(!left.isEmpty)
|
||||
let peak: Double = left.map { abs($0) }.max() ?? 0
|
||||
#expect(peak <= 1.2, "tanh saturator output was not bounded near ±1: peak=\(peak)")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// PedalMappingStripTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
@testable import LyrebirdShoeGaze
|
||||
@testable import LyrebirdShoeGazeUI
|
||||
|
||||
@MainActor
|
||||
@Suite("Pedal mapping strip")
|
||||
struct PedalMappingStripTests {
|
||||
|
||||
/// Builds an engine + a one-board rig with a single Volume pedal, returning the pedal.
|
||||
private func makePedal() throws -> (Pedal, ShoeGaze, URL) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.05, numAudioBuses: 256)
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try sg.finalizeBoard(board)
|
||||
guard let pedal: Pedal = board.pedals.first else {
|
||||
throw ShoeGazeTestError.noPedal
|
||||
}
|
||||
return (pedal, sg, url)
|
||||
}
|
||||
|
||||
private enum ShoeGazeTestError: Error { case noPedal }
|
||||
|
||||
@Test func emptyMapYieldsNoRows() throws {
|
||||
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
withExtendedLifetime(sg) {
|
||||
#expect(PedalMappingStrip.rows(for: pedal, in: nil).isEmpty)
|
||||
#expect(PedalMappingStrip.rows(for: pedal, in: .empty).isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
@Test func ccAndBypassRowsBuiltFromMap() throws {
|
||||
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
withExtendedLifetime(sg) {
|
||||
#expect(pedal.ccMappableControls.isEmpty == false, "Volume exposes a CC-mappable control")
|
||||
let controlLabel: String = pedal.ccMappableControls[0].label
|
||||
|
||||
let map: MIDIMap = MIDIMap(
|
||||
switches: [MIDIMap.SwitchBinding(program: 4, action: .pedalBypass(pedalID: pedal.id))],
|
||||
ccs: [MIDIMap.CCBinding(
|
||||
controller: 11,
|
||||
target: .pedalControl(
|
||||
pedalID: pedal.id, controlIndex: 0,
|
||||
pedalNameHint: nil, controlLabelHint: nil))],
|
||||
keys: [MIDIMap.KeyBinding(key: "b", modifiers: [.shift],
|
||||
action: .pedalBypass(pedalID: pedal.id))]
|
||||
)
|
||||
|
||||
let rows: [PedalMappingRow] = PedalMappingStrip.rows(for: pedal, in: map)
|
||||
#expect(rows.count == 2, "one CC control row + one bypass row")
|
||||
|
||||
let ccRow: PedalMappingRow? = rows.first { $0.label == controlLabel }
|
||||
#expect(ccRow?.badges.map(\.text) == ["CC11"])
|
||||
|
||||
let bypassRow: PedalMappingRow? = rows.first { $0.label == "Bypass" }
|
||||
#expect(bypassRow?.badges.map(\.text) == ["PC4", "⇧B"], "footswitch then key, shift glyph")
|
||||
}
|
||||
}
|
||||
|
||||
@Test func unmappedControlsProduceNoRows() throws {
|
||||
let (pedal, sg, url): (Pedal, ShoeGaze, URL) = try makePedal()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
withExtendedLifetime(sg) {
|
||||
// A map that only binds a DIFFERENT pedal's control must not surface rows for this pedal.
|
||||
let otherID: UUID = UUID()
|
||||
let map: MIDIMap = MIDIMap(
|
||||
ccs: [MIDIMap.CCBinding(
|
||||
controller: 5,
|
||||
target: .pedalControl(
|
||||
pedalID: otherID, controlIndex: 0,
|
||||
pedalNameHint: nil, controlLabelHint: nil))]
|
||||
)
|
||||
#expect(PedalMappingStrip.rows(for: pedal, in: map).isEmpty)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -83,6 +83,41 @@ struct RigStoreTests {
|
||||
#expect(b.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it")
|
||||
}
|
||||
|
||||
/// A launch restore reinstates the rig's saved I/O layout so a multi-channel setup survives
|
||||
/// relaunch, and a saved live-input channel that only fits the wider layout stays selected
|
||||
/// (rather than falling back to the test loop against the fresh engine's default count).
|
||||
@Test func restoreAppliesSavedChannelLayoutAndInput() throws {
|
||||
let autosave: URL = try isolateAutosave()
|
||||
defer {
|
||||
RigStore.autosaveURLOverride = nil
|
||||
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
|
||||
}
|
||||
RigStore.clear()
|
||||
|
||||
// Save a rig on a 2-in / 2-out engine with live input on channel 1.
|
||||
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05, numOutputChannels: 2, numInputChannels: 2, numAudioBuses: 64
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: urlA) }
|
||||
let a: ShoeGaze = ShoeGaze(engine: engineA, inputSource: .liveInput(channel: 1))
|
||||
let board: PedalBoard = try a.addBoard()
|
||||
try a.appendPedal(.overdrive, to: board)
|
||||
try a.finalizeBoard(board)
|
||||
#expect(RigStore.save(a))
|
||||
|
||||
// Restore into a fresh engine built with the default single input channel.
|
||||
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
|
||||
duration: 0.05, numOutputChannels: 2, numInputChannels: 1, numAudioBuses: 64
|
||||
)
|
||||
defer { try? FileManager.default.removeItem(at: urlB) }
|
||||
let b: ShoeGaze = ShoeGaze(engine: engineB)
|
||||
#expect(RigStore.restore(into: b))
|
||||
|
||||
#expect(b.engine.numInputChannels == 2, "restore must reapply the rig's saved input count")
|
||||
#expect(b.inputSource == .liveInput(channel: 1),
|
||||
"the saved live-input channel must survive because the layout was restored first")
|
||||
}
|
||||
|
||||
@Test func restoreReturnsFalseWhenNoAutosave() throws {
|
||||
let autosave: URL = try isolateAutosave()
|
||||
defer {
|
||||
|
||||
@@ -61,4 +61,35 @@ struct SustainerPedalTests {
|
||||
}
|
||||
#expect(ssd > 0, "sustain knob had no effect on output")
|
||||
}
|
||||
|
||||
@Test func exposesSafetySwitch() throws {
|
||||
let pedal: SustainerPedal = SustainerPedal()
|
||||
#expect(pedal.effectSwitches.map { $0.label } == ["Safety"])
|
||||
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Off", "On"])
|
||||
}
|
||||
|
||||
@Test func safetyLimiterCapsPeaks() throws {
|
||||
// Max sustain drives a low threshold, high ratio, and +18 dB makeup — the compressor's
|
||||
// non-zero attack lets transients overshoot. With Safety on, the output peak must stay
|
||||
// near full scale, and the two switch states must differ.
|
||||
let off: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 0.0
|
||||
}
|
||||
let on: [Float] = try render {
|
||||
$0.sampleRate = 44100.0; $0.sustain = 10.0; $0.safetyLimiter = 1.0
|
||||
}
|
||||
#expect(hasNonSilentOutput(off) && hasNonSilentOutput(on))
|
||||
|
||||
let fill: Int = 2048
|
||||
guard on.count > fill else { return }
|
||||
let onPeak: Float = on[fill...].reduce(0) { Swift.max($0, abs($1)) }
|
||||
#expect(onPeak <= 1.05, "safety limiter failed to cap peak: \(onPeak)")
|
||||
|
||||
let window: Int = 2048
|
||||
guard off.count >= fill + window, on.count >= fill + window else { return }
|
||||
let ssd: Double = zip(off[fill..<(fill + window)], on[fill..<(fill + window)]).reduce(0.0) { acc, pair in
|
||||
let d: Double = Double(pair.0 - pair.1); return acc + d * d
|
||||
}
|
||||
#expect(ssd > 0, "safety switch had no effect on output")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// TempoSyncTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdShoeGaze
|
||||
|
||||
@MainActor
|
||||
@Suite("Tempo sync")
|
||||
struct TempoSyncTests {
|
||||
|
||||
/// A rig with a single `DelayPedal` on a finalized board, so the pedal has a real clock and
|
||||
/// engine injected by `board.add(_:)`. Returns the session (kept alive for its clock), the
|
||||
/// temp render URL, and the pedal.
|
||||
private func makeRigWithDelay(bpm: Double = 120.0) throws -> (ShoeGaze, URL, DelayPedal) {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
sg.clock.bpm = bpm
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
let delay: DelayPedal = DelayPedal()
|
||||
try board.add(delay)
|
||||
try sg.finalizeBoard(board)
|
||||
return (sg, url, delay)
|
||||
}
|
||||
|
||||
private let tolerance: Double = 1e-6
|
||||
|
||||
@Test func timeDivisionDerivesSecondsFromTempo() throws {
|
||||
// `sg` owns the clock (the pedal holds it weakly), so it must outlive the assertions.
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
// 120 BPM → 0.5 s per beat. Eighth = 0.5 beat → 0.25 s.
|
||||
delay.setSync(.division(.eighth), for: "time")
|
||||
#expect(abs(delay.$time.value - 0.25) < tolerance)
|
||||
|
||||
// Quarter = 1 beat → 0.5 s.
|
||||
delay.setSync(.division(.quarter), for: "time")
|
||||
#expect(abs(delay.$time.value - 0.5) < tolerance)
|
||||
}
|
||||
|
||||
@Test func freeParameterIsLeftUntouched() throws {
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay()
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
let original: Double = delay.$time.value
|
||||
delay.applyTempoSync() // nothing is synced → value unchanged
|
||||
#expect(delay.$time.value == original)
|
||||
}
|
||||
|
||||
@Test func longDivisionClampsToParameterRange() throws {
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 40.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
// Whole note at 40 BPM = 4 beats × 1.5 s = 6.0 s, past the Delay's 5.0 s maximum.
|
||||
delay.setSync(.division(.whole), for: "time")
|
||||
#expect(abs(delay.$time.value - 5.0) < tolerance, "synced value must clamp to the time range")
|
||||
}
|
||||
|
||||
@Test func valueReportsWhenADivisionClamps() throws {
|
||||
let delay: DelayPedal = DelayPedal()
|
||||
let param: TempoSyncableParam = try #require(delay.tempoSyncableParams.first)
|
||||
|
||||
// Fits within [0.01, 5.0]: quarter @ 120 BPM = 0.5 s, not clamped.
|
||||
let quarter: (value: Double, clamped: Bool) = param.value(for: .quarter, bpm: 120.0)
|
||||
#expect(abs(quarter.value - 0.5) < tolerance)
|
||||
#expect(!quarter.clamped)
|
||||
|
||||
// Whole @ 40 BPM = 6.0 s, past the 5.0 s max → clamped and flagged.
|
||||
let whole: (value: Double, clamped: Bool) = param.value(for: .whole, bpm: 40.0)
|
||||
#expect(abs(whole.value - 5.0) < tolerance)
|
||||
#expect(whole.clamped)
|
||||
}
|
||||
|
||||
@Test func setBpmBroadcastsToSyncedParameters() throws {
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
delay.setSync(.division(.quarter), for: "time")
|
||||
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
|
||||
|
||||
// Halving the tempo doubles a beat's length → quarter now 1.0 s.
|
||||
sg.setBpm(60.0)
|
||||
#expect(abs(delay.$time.value - 1.0) < tolerance, "setBpm must recompute synced parameters")
|
||||
}
|
||||
|
||||
@Test func rateParameterUsesInverseOfPeriod() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
sg.clock.bpm = 120.0
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
let tremolo: TremoloPedal = TremoloPedal()
|
||||
try board.add(tremolo)
|
||||
try sg.finalizeBoard(board)
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
// 120 BPM → 0.5 s per beat. A quarter-note LFO = one cycle per 0.5 s → 2 Hz.
|
||||
tremolo.setSync(.division(.quarter), for: "rate")
|
||||
#expect(abs(tremolo.$rate.value - 2.0) < tolerance)
|
||||
|
||||
// Eighth = 0.25 s period → 4 Hz.
|
||||
tremolo.setSync(.division(.eighth), for: "rate")
|
||||
#expect(abs(tremolo.$rate.value - 4.0) < tolerance)
|
||||
}
|
||||
|
||||
@Test func multiTapSyncsEachTapIndependently() throws {
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let sg: ShoeGaze = ShoeGaze(engine: engine)
|
||||
sg.clock.bpm = 120.0
|
||||
let board: PedalBoard = try sg.addBoard()
|
||||
let multiTap: MultiTapDelayPedal = MultiTapDelayPedal()
|
||||
try board.add(multiTap)
|
||||
try sg.finalizeBoard(board)
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
let freeTime3: Double = multiTap.$time3.value
|
||||
multiTap.setSync(.division(.quarter), for: "time1") // 0.5 s
|
||||
multiTap.setSync(.division(.eighth), for: "time2") // 0.25 s
|
||||
|
||||
#expect(abs(multiTap.$time1.value - 0.5) < tolerance)
|
||||
#expect(abs(multiTap.$time2.value - 0.25) < tolerance)
|
||||
#expect(multiTap.$time3.value == freeTime3, "an unsynced tap is left free")
|
||||
}
|
||||
|
||||
@Test func lightweightRecallRecomputesSyncedValuesAtCurrentTempo() throws {
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
defer { withExtendedLifetime(sg) {} }
|
||||
|
||||
delay.setSync(.division(.quarter), for: "time")
|
||||
#expect(abs(delay.$time.value - 0.5) < tolerance) // quarter @ 120 BPM
|
||||
|
||||
// Capture at 120 BPM (time = 0.5 s), then change tempo so a recall must recompute.
|
||||
let snapshot: ShoeGazeState = sg.captureState()
|
||||
sg.setBpm(60.0)
|
||||
#expect(abs(delay.$time.value - 1.0) < tolerance) // quarter @ 60 BPM
|
||||
|
||||
// Recall the 120-BPM snapshot onto the (now 60-BPM) rig. The restored division must be
|
||||
// recomputed against the current tempo — 1.0 s — not left at the captured 0.5 s.
|
||||
sg.applyState(snapshot)
|
||||
#expect(delay.tempoSync["time"] == .division(.quarter))
|
||||
#expect(abs(delay.$time.value - 1.0) < tolerance, "recall must recompute synced values at the current tempo")
|
||||
}
|
||||
|
||||
@Test func syncStatePersistsThroughCaptureAndApply() throws {
|
||||
let delay: DelayPedal = DelayPedal()
|
||||
delay.setSync(.division(.dottedEighth), for: "time")
|
||||
|
||||
let data: Data = try JSONEncoder().encode(delay.captureState())
|
||||
let restored: PedalState = try JSONDecoder().decode(PedalState.self, from: data)
|
||||
|
||||
let rebuilt: DelayPedal = DelayPedal()
|
||||
rebuilt.applyState(restored)
|
||||
#expect(rebuilt.tempoSync["time"] == .division(.dottedEighth))
|
||||
}
|
||||
|
||||
@Test func presetWithoutTempoSyncDecodesToFree() throws {
|
||||
// A rig saved before tempo sync has no `tempoSync` key — it must decode to "all free".
|
||||
let legacy: String = """
|
||||
{"type":"Delay","knobValues":[0.25,1.0,0.35,1.0],"bypass":0.0}
|
||||
"""
|
||||
let state: PedalState = try JSONDecoder().decode(PedalState.self, from: Data(legacy.utf8))
|
||||
#expect(state.tempoSync == nil)
|
||||
|
||||
let delay: DelayPedal = DelayPedal()
|
||||
delay.applyState(state)
|
||||
#expect(delay.tempoSync.isEmpty, "a legacy preset leaves every parameter free")
|
||||
}
|
||||
|
||||
@Test func disablingTempoStopsRecompute() throws {
|
||||
let (sg, url, delay): (ShoeGaze, URL, DelayPedal) = try makeRigWithDelay(bpm: 120.0)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
delay.setSync(.division(.quarter), for: "time")
|
||||
let syncedValue: Double = delay.$time.value // 0.5 s
|
||||
|
||||
sg.setTempoEnabled(false)
|
||||
sg.setBpm(60.0) // tempo disabled → no recompute
|
||||
#expect(delay.$time.value == syncedValue, "a disabled tempo must not drive synced parameters")
|
||||
|
||||
// Re-enabling re-syncs to the current (60 BPM) tempo → quarter = 1.0 s.
|
||||
sg.setTempoEnabled(true)
|
||||
#expect(abs(delay.$time.value - 1.0) < tolerance)
|
||||
}
|
||||
}
|
||||
@@ -120,4 +120,45 @@ struct TunerTests {
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.rigMuted, "Second engageTuner() call while already engaged must be a no-op")
|
||||
}
|
||||
|
||||
/// With the rig muted, an engaged tuner must leave the audio output silent. Guards against the
|
||||
/// tuner's pitch-capture signal leaking into a hardware output channel: its scratch bus is a
|
||||
/// *control* bus, but writing it through the audio-rate `output(bus:)` helper would treat that
|
||||
/// index as an *audio* bus (colliding with the low output-bus indices) and, since the tap runs
|
||||
/// after `mainGroup`, bypass the rig mute — audible as crackle while the pitch is unstable.
|
||||
@Test func engagedTunerDoesNotLeakIntoOutput() throws {
|
||||
let renderDuration: Double = 0.4
|
||||
let sampleRate: Double = 44100.0
|
||||
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration, numAudioBuses: 256)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let shoeGaze: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
|
||||
|
||||
try withExtendedLifetime(shoeGaze) {
|
||||
let board: PedalBoard = try shoeGaze.addBoard()
|
||||
try board.add(VolumePedal())
|
||||
try shoeGaze.finalizeBoard(board)
|
||||
|
||||
// Feed the test-loop signal so the pitch tracker produces a real (non-zero) estimate —
|
||||
// the value that would leak if the scratch write hit an audio bus.
|
||||
shoeGaze.setInputMuted(false)
|
||||
shoeGaze.tunerMutesRig = true
|
||||
shoeGaze.engageTuner()
|
||||
#expect(shoeGaze.rigMuted)
|
||||
|
||||
try engine.start()
|
||||
let samples: [Float] = readStereoCAF(url: url, sampleRate: sampleRate)
|
||||
|
||||
// Ignore the opening window: the rig-mute gain ramps up over its first blocks (a separate,
|
||||
// pre-existing BoardOutputMaster behaviour), briefly passing the test-loop signal. Once it
|
||||
// settles the output must be exactly silent — the tuner leak, if present, persists for the
|
||||
// whole render (it bypasses the mute), so the settled tail catches it.
|
||||
let channels: Int = 2
|
||||
let settleSeconds: Double = 0.15
|
||||
let tailStart: Int = Int(settleSeconds * sampleRate) * channels
|
||||
let tail: [Float] = Array(samples[min(tailStart, samples.count)...])
|
||||
#expect(!tail.isEmpty)
|
||||
#expect(!hasNonSilentOutput(tail),
|
||||
"once the rig mute settles, an engaged tuner must not leak its pitch signal into the output")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
# Keyboard control mapping + unified mapping sheet
|
||||
|
||||
Bind computer letter keys to the same rig actions MIDI footswitches drive, and rework the
|
||||
MIDI mapping sheet so each rig action shows **all** of its trigger sources (footswitch,
|
||||
expression pedal, letter key) on one row.
|
||||
|
||||
## Goals
|
||||
|
||||
- A letter key (e.g. `b`) can toggle rig bypass / mute, a board solo/bypass, a pedal bypass,
|
||||
a looper transport action, the tuner, or tap tempo — exactly the toggle actions a
|
||||
Program-Change footswitch already drives.
|
||||
- Keys fire **only** when no text field is focused (rig rename, board label). Typing a rig
|
||||
name must never trip a bypass.
|
||||
- One mapping sheet row per action, showing its PC chip, KEY chip, and per-source learn.
|
||||
- Keys persist with the rig (travel in `ShoeGazeState`), like MIDI bindings.
|
||||
- macOS + iOS hardware keyboard.
|
||||
|
||||
## Non-goals
|
||||
|
||||
- Keys driving continuous CC targets (knobs / levels). Keys are momentary → toggle actions
|
||||
only. CC rows in the sheet are unchanged.
|
||||
- `⌘`-modified bindings. Shift / Control / Option qualify a key binding (`a` vs `⇧a` vs `⌃a`),
|
||||
but Command is reserved for the existing menu `⌘`-shortcuts and is never bindable.
|
||||
|
||||
## Design
|
||||
|
||||
Reuse the existing controller. `MIDIController` already owns the shared `perform(_:)` action
|
||||
dispatch, the `learnTarget` state, the weak `shoeGaze`, and `onMapChanged`. Key learn and key
|
||||
apply reuse all of it — a separate controller would duplicate that. Key **event capture** is
|
||||
the only platform piece and lives in the UI module (SwiftUI `.onKeyPress`), per the module
|
||||
layering rule; the controller exposes a pure `ingestKey` entry point that the UI calls.
|
||||
|
||||
### Model — `MIDIMap`
|
||||
|
||||
Add a third binding list beside `switches` / `ccs`:
|
||||
|
||||
```swift
|
||||
public var keys: [KeyBinding]
|
||||
|
||||
public struct KeyBinding: Codable, Equatable, Sendable {
|
||||
public var key: String // single lowercased character
|
||||
public var action: Action
|
||||
public var displayNameHint: String?
|
||||
}
|
||||
```
|
||||
|
||||
`MIDIMap` gains a custom `init(from:)` that decodes `keys` with `decodeIfPresent ?? []`, so a
|
||||
rig saved before this feature (a `midiMap` with `switches`/`ccs` but no `keys`) still decodes
|
||||
— without it, synthesized Codable would fail the whole map and `ShoeGazeState` would silently
|
||||
drop existing MIDI bindings. `encode(to:)` stays synthesized.
|
||||
|
||||
### Controller — `MIDIController`
|
||||
|
||||
- `LearnTarget` gains `.key(MIDIMap.Action)`.
|
||||
- `armKeyLearn(_ action:)`, `keyBinding(for:)`, `clearKeyBinding(for:)` — mirror the switch API.
|
||||
- `ingestKey(_ key: String) -> Bool` — if armed for key learn, capture + clear learn; else run
|
||||
every action bound to that key via the shared `perform(_:)`. Returns `true` when the key was
|
||||
consumed (learned or matched a binding) so the UI can swallow the event; `false` lets the key
|
||||
fall through. Normalizes to a single lowercased letter/digit (non-printing keys rejected).
|
||||
`ingestKey` is `public` (no DEBUG gate needed — unlike MIDI messages there is no background-queue
|
||||
hop to bypass, so tests call it directly).
|
||||
|
||||
### UI capture — `ShoeGazeBuilderView`
|
||||
|
||||
Attach a focus-gated `.onKeyPress(phases: .down)` on the builder root. Handler:
|
||||
- Ignores repeats (hold = one toggle) and anything with command/control/option modifiers.
|
||||
- Extracts the single character, calls `controller.ingestKey`.
|
||||
- Returns `.handled` when consumed, else `.ignored`.
|
||||
|
||||
Focus gate: a focused `TextField` consumes keys first via the responder chain, so a root
|
||||
`.onKeyPress` never sees them while the user types. Sheets (rig rename, board editor) present
|
||||
their own text fields and take focus. No extra `@FocusState` plumbing needed for v1.
|
||||
|
||||
### UI sheet — `MIDIMappingSheet`
|
||||
|
||||
Switch rows gain a KEY chip (showing the bound letter, or nothing) and a keyboard-learn button
|
||||
beside the existing footswitch learn. Armed key-learn shows "Listening — press a key…". CC rows
|
||||
unchanged. Learn buttons: piano icon = MIDI learn, keyboard icon = key learn.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Change |
|
||||
|---|---|
|
||||
| `Sources/LyrebirdShoeGaze/MIDI/MIDIMap.swift` | `KeyBinding` type, `keys` array, custom `init(from:)`. |
|
||||
| `Sources/LyrebirdShoeGaze/MIDI/MIDIController.swift` | `.key` learn target, key learn/apply API, `ingestKey`. |
|
||||
| `Sources/LyrebirdShoeGazeUI/ShoeGazeBuilderView.swift` | focus-gated `.onKeyPress` root modifier. |
|
||||
| `Sources/LyrebirdShoeGazeUI/MIDIMappingSheet.swift` | KEY chip + keyboard-learn on switch rows. |
|
||||
| `Tests/LyrebirdShoeGazeTests/MIDIMapCodableTests.swift` | `keys` round-trip + old-rig (no `keys`) decode. |
|
||||
| `Tests/LyrebirdShoeGazeTests/MIDIControllerKeyTests.swift` | key learn / apply / clear / latch. |
|
||||
|
||||
## Test plan
|
||||
|
||||
- `MIDIMap` with `keys` encodes + decodes equal; a `midiMap` JSON lacking `keys` decodes with
|
||||
`keys == []` and its `switches`/`ccs` intact.
|
||||
- `armKeyLearn` + `ingestKey("b")` captures a `KeyBinding`, clears learn, fires `onMapChanged`,
|
||||
does not perform the action on the learn press.
|
||||
- A subsequent `ingestKey("b")` latches the action (e.g. rig bypass on/off).
|
||||
- `ingestKey` returns `false` for an unbound key; `clearKeyBinding` removes it.
|
||||
- Case/whitespace normalization: `ingestKey("B")` matches a binding learned as `b`.
|
||||
@@ -0,0 +1,93 @@
|
||||
# 2.1.1 — Input mute + I/O persistence
|
||||
|
||||
Two small, related fixes to cut down accidental noise at engine start and make the
|
||||
input configuration survive relaunch.
|
||||
|
||||
## (a) Input mute toggle
|
||||
|
||||
A hard mute on the **input** feeding every board (the guitar / mic signal), distinct
|
||||
from the existing rig-**output** mute. Goals:
|
||||
|
||||
- The app **re-asserts it muted every time the engine is (user-)started**, so a fresh start
|
||||
is silent until the player un-mutes — kills accidental ruckus. (The library-level default is
|
||||
*audible*; muting is the app's Start-time policy, so headless / offline library use isn't
|
||||
forced silent.)
|
||||
- A toggle button sits **next to the Start/Stop transport**.
|
||||
- **MIDI mappable** (Program Change + computer key), like Rig Mute.
|
||||
- Also default the input source to **In 0** (live input) instead of the test-loop arpeggio.
|
||||
|
||||
### RT graph
|
||||
|
||||
Each board's input writer (`TestLoopTap` in test-loop mode, `HardwareInputPassThrough`
|
||||
in live mode) gains an `@UIParam inputMute` (0 = audible, 1 = muted). `build()` multiplies
|
||||
the copied signal by a **hard** gain `(inputMute − 1)·−1` — an un-lagged kill switch. (A lagged
|
||||
gate never settles to exactly zero on its first blocks and leaks a faint transient at the very
|
||||
moment the mute is meant to keep things quiet; a kill-switch mute is expected to be abrupt.)
|
||||
|
||||
### ShoeGaze
|
||||
|
||||
- `public private(set) var inputMuted: Bool = false` (app mutes on Start)
|
||||
- `setInputMuted(_:)` drives every `testLoopTaps` + `inputPassThroughs` mute node; `toggleInputMuted()`.
|
||||
- `addBoard()` sets each new input node's mute to the current `inputMuted` so rebuilds stay consistent.
|
||||
|
||||
### Engine start
|
||||
|
||||
`EngineConfigView.startEngine()` calls `shoeGaze.setInputMuted(true)` **before**
|
||||
`engine.start()`, while the engine is stopped — so the gain is seeded (`previousOutputValue`
|
||||
primed to the target, no ramp) and the very first render block is already muted. Asserting it
|
||||
after start would leave the opening blocks unmuted. Transient stop/start-around-rebuild paths
|
||||
(`applyInputSource`, `performClear`) call `engine.start()` directly and are unaffected — they
|
||||
preserve the current mute state. Nodes are also primed at creation in `addBoard()` (before the
|
||||
node is spliced into the graph), so a board added while muted has no first-block leak either.
|
||||
|
||||
### MIDI
|
||||
|
||||
- `MIDIMap.Action.inputMute`
|
||||
- `MIDIController.perform` → `toggleInputMuted()`; `hint` → nil.
|
||||
- `MIDIMappingSheet` switch row "Input Mute".
|
||||
|
||||
### Default to In 0
|
||||
|
||||
`ShoeGazeBuilderView.restoreInputSelection()` first-launch (no saved choice) branch requests
|
||||
mic access and selects `.liveInput(channel: 0)` (falling back to test loop on denial / no
|
||||
input), instead of only auto-selecting when already authorised.
|
||||
|
||||
## (b) Persist In/Out + input via the rig (iCloud), not UserDefaults
|
||||
|
||||
The rig snapshot (`ShoeGazeState`) **already** persists `inputSource`, `numInputChannels`,
|
||||
and `numOutputChannels`, and the autosave envelope + rig library (iCloud) already carry
|
||||
them. Two problems remained:
|
||||
|
||||
1. `loadRig(from:)` deliberately does **not** apply the saved channel layout (forcing it on
|
||||
every mid-session load would fight the global engine config / the iOS live-input rebuild).
|
||||
So at **launch**, the engine kept the app default (1 in / 2 out); a saved live-input
|
||||
channel `>=` that count failed validation and fell back to the test loop — the "In
|
||||
doesn't persist" bug.
|
||||
2. A **second, competing** persistence path (`ShoeGazeBuilderView`'s UserDefaults
|
||||
`ShoeGaze.inputSelection`, plus the iOS model's copy) fought the rig's own `inputSource`.
|
||||
|
||||
Fix — make the rig the single source of truth:
|
||||
|
||||
- **Launch applies the saved layout.** `RigStore.restore` calls
|
||||
`applyChannelLayout(from: state)` **before** `loadRig`, while the engine is stopped, so the
|
||||
input-channel validation runs against the restored count. A launch restore is exactly the
|
||||
place this is wanted (unlike a mid-session load), so the general `loadRig` policy is
|
||||
unchanged.
|
||||
- **Input changes autosave.** `applyInputSource` / the engine-config `onConfigApplied` call
|
||||
`autosave()`, so a changed input or I/O layout is captured into the rig immediately.
|
||||
- **No UserDefaults path.** The `ShoeGaze.inputSelection` key and its read/write sites (builder
|
||||
view + iOS model) are removed; the engine channel counts are never persisted to UserDefaults at
|
||||
all. The app targets build the engine at the default layout; `RigStore.restore` supplies the
|
||||
rig's saved layout.
|
||||
- **Fresh-launch default.** When there is no autosaved rig, the seed paths
|
||||
(`AppDelegate.seedInitialBoard` / iOS `seedFallbackBoard`) set `inputSource = .liveInput(0)`
|
||||
when the engine has an input channel, so a first launch listens to the instrument rather
|
||||
than the test loop. A restored rig keeps its own saved input. The builder view's on-appear
|
||||
hook now only requests mic access for a restored live-input selection (falling back to the
|
||||
test loop on denial).
|
||||
|
||||
## Tests
|
||||
|
||||
- `InputMuteTests` — `HardwareInputPassThrough` / `TestLoopTap` mute gain; `ShoeGaze.setInputMuted`
|
||||
drives all input nodes; `addBoard` brings a new board up at the current mute state.
|
||||
- `MIDIController` — an `inputMute` switch action toggles `shoeGaze.inputMuted`.
|
||||
@@ -0,0 +1,221 @@
|
||||
# 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 — implemented (inert while synced)
|
||||
|
||||
A synced param's value is derived, so a CC bound to it would be overwritten on the next
|
||||
tempo/division change. Rather than drop `.division`-synced params from `ccMappableControls` —
|
||||
which is addressed by a *stable index* (persisted CC bindings resolve by position), so filtering it
|
||||
live would shift indices and break existing bindings — the exclusion is **index-stable**: the slot
|
||||
stays, and the CC *write* is skipped while the target parameter is division-synced.
|
||||
`MIDIController.applyCC` checks `Pedal.isNodeTempoSynced(_:)` (node-identity match against
|
||||
`tempoSyncableParams`) and ignores the incoming CC for a synced control; the binding stays intact and
|
||||
resumes control the moment the parameter is set back to Free. Learning/binding a CC to a synced
|
||||
param is still allowed — the tempo simply wins while synced.
|
||||
|
||||
## 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.
|
||||