Compare commits
35 Commits
v3.0.0
..
0a8a8e549f
| Author | SHA1 | Date | |
|---|---|---|---|
| 0a8a8e549f | |||
| 3e3f86b737 | |||
| 097c38283e | |||
| 89a34016de | |||
| d1f823e54c | |||
| 75de04160b | |||
| 74227400ad | |||
| 243be726ea | |||
| 20b2034fed | |||
| 3edd64e782 | |||
| 53b506adeb | |||
| 4e8f6e280c | |||
| a434b14f4b | |||
| 0ddf350f1f | |||
| f8926ecfb8 | |||
| 9873dd258b | |||
| fc6ddb8d9a | |||
| 812a240e55 | |||
| 93ca9076d2 | |||
| 4a9bf0fb30 | |||
| 850b86209a | |||
| 2aea609f34 | |||
| 44e6c35550 | |||
| 5decdd8693 | |||
| 132515b4cd | |||
| 392ae1525a | |||
| ad6ed41674 | |||
| fba32ff0aa | |||
| 2c970aa344 | |||
| 7dccf596f4 | |||
| 75b99a547b | |||
| 965633de34 | |||
| 779c55493d | |||
| bb418ca2e8 | |||
| 4eb1cbdd61 |
@@ -23,3 +23,4 @@ review.diff
|
|||||||
|
|
||||||
# Local working plan (not shared)
|
# Local working plan (not shared)
|
||||||
docs/plans/amp-expansion-plan.md
|
docs/plans/amp-expansion-plan.md
|
||||||
|
docs/plans/pedal-expansion-plan.md
|
||||||
|
|||||||
@@ -4,6 +4,68 @@ 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
|
[Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and the project uses
|
||||||
[semantic versioning](https://semver.org/spec/v2.0.0.html).
|
[semantic versioning](https://semver.org/spec/v2.0.0.html).
|
||||||
|
|
||||||
|
## [3.1.1] — 2026-08-13
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **Mutant switch captions no longer wrap.** The envelope filter's three segmented switches
|
||||||
|
(Direction / Mode / Range — seven segments in all) were crammed into a single-width pedal,
|
||||||
|
wrapping the "Down" caption to "Do wn". Mutant is now double-width, like the Cabinet and amp
|
||||||
|
pedals, so the switch captions have room.
|
||||||
|
|
||||||
|
## [3.1.0] — 2026-08-13
|
||||||
|
|
||||||
|
Starter rigs and a deeper envelope filter. ShoeGaze now ships a library of ready-to-play
|
||||||
|
rigs grouped by style, two new pedals, and a much more expressive Mutant envelope filter —
|
||||||
|
plus a batch of rig-switching and reverb fixes.
|
||||||
|
|
||||||
|
### Added
|
||||||
|
|
||||||
|
- **18 built-in starter rigs**, seeded into the library on first launch and grouped by
|
||||||
|
style — **Shoegaze Walls**, **Dreampop**, **Classic**, **Ambient**, and **Experimental**.
|
||||||
|
A **Mine / Starters** toggle at the top of the rig sidebar switches between your own rigs
|
||||||
|
and the shipped ones (grouped under category headers); the sidebar opens on whichever
|
||||||
|
group holds the current rig. A **Restore Starter Rigs** action (rig-library menu, or the
|
||||||
|
Starters empty state) reinstalls the shipped rigs at any time.
|
||||||
|
- **Two-board starter rig** — a Garcia-style clean/effects split across two boards, switched
|
||||||
|
with the board Solo / Blend control, showing off multi-board rigs.
|
||||||
|
- **Vibe pedal** — a photocell "vibe": four staggered all-pass stages swept by one LFO, with
|
||||||
|
**Chorus** and **Vibrato** modes and Speed / Intensity controls.
|
||||||
|
- **Sustain Fuzz pedal** — a mid-scooped, high-sustain fuzz (two cascaded soft-clip stages),
|
||||||
|
distinct from the brighter single-stage Fuzz. Sustain / Tone / Scoop controls.
|
||||||
|
- **Mutant (envelope filter) controls** — a **Range** switch (Lo / Hi) that shifts the whole
|
||||||
|
sweep band, matching the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release**
|
||||||
|
in the advanced pop-over. Sweep sets how far your picking drives the cutoff; Attack /
|
||||||
|
Release shape how quickly the filter follows.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
|
||||||
|
- **Switching rigs keeps your current input.** Loading a rig from the library no longer snaps
|
||||||
|
the input back to the test loop (or the input a rig was saved with) — your live guitar (or
|
||||||
|
whatever input you have selected) carries across the switch. Opening or restoring a rig
|
||||||
|
file still applies its saved input.
|
||||||
|
- **Shimmer Reverb backed off.** The regenerating loop gain is roughly `decay + shimmer`, so
|
||||||
|
the old defaults (0.8 + 0.5) self-oscillated into a screech with little or no input.
|
||||||
|
Defaults are now decay 0.5 / shimmer 0.25 / damp 0.5, and the starter rigs that use it were
|
||||||
|
re-tuned to stay well below self-oscillation.
|
||||||
|
- **Mutant sweep defaults tamed** — resting cutoff 80 → 120 Hz and sweep span 40× → 20×, so
|
||||||
|
the filter is neither muted at rest nor extreme when it opens.
|
||||||
|
- **Starter rigs refresh on update.** Shipped rigs install (and refresh to their current
|
||||||
|
form) by catalog version, so a corrected starter reaches libraries that were seeded
|
||||||
|
earlier — without touching your own rigs.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
|
||||||
|
- **No more spurious "Save changes?" prompt when switching rigs.** The unsaved-changes check
|
||||||
|
compared live session settings (input source, engine channel counts) that legitimately
|
||||||
|
differ from a rig's saved values; it now compares rig content only.
|
||||||
|
- **Starter rigs can't be overwritten by accident.** A built-in starter rig is managed content
|
||||||
|
(refreshed to the shipped version on updates), so saving over a loaded starter offers **Save
|
||||||
|
as New Rig** or **Cancel** — your changes are kept as your own rig rather than replacing the
|
||||||
|
shipped one.
|
||||||
|
- **Multi-board signal-router rigs now save and load.** Routed A/B rigs were previously lost
|
||||||
|
on save; their branch chains and blend now persist.
|
||||||
|
|
||||||
## [3.0.0] — 2026-08-04
|
## [3.0.0] — 2026-08-04
|
||||||
|
|
||||||
The big one: ShoeGaze becomes an amp-modeling rig. This release adds a full lineup of
|
The big one: ShoeGaze becomes an amp-modeling rig. This release adds a full lineup of
|
||||||
|
|||||||
@@ -100,7 +100,7 @@
|
|||||||
attributes = {
|
attributes = {
|
||||||
BuildIndependentTargetsInParallel = 1;
|
BuildIndependentTargetsInParallel = 1;
|
||||||
LastSwiftUpdateCheck = 1600;
|
LastSwiftUpdateCheck = 1600;
|
||||||
LastUpgradeCheck = 2660;
|
LastUpgradeCheck = 2700;
|
||||||
TargetAttributes = {
|
TargetAttributes = {
|
||||||
C3B100000000000000000014 = {
|
C3B100000000000000000014 = {
|
||||||
CreatedOnToolsVersion = 16.0;
|
CreatedOnToolsVersion = 16.0;
|
||||||
@@ -163,7 +163,7 @@
|
|||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 15;
|
CURRENT_PROJECT_VERSION = 23;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
@@ -175,7 +175,7 @@
|
|||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
MARKETING_VERSION = 3.0.0;
|
MARKETING_VERSION = 3.3;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
@@ -193,7 +193,7 @@
|
|||||||
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
"CODE_SIGN_IDENTITY[sdk=macosx*]" = "Apple Development";
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
COMBINE_HIDPI_IMAGES = YES;
|
COMBINE_HIDPI_IMAGES = YES;
|
||||||
CURRENT_PROJECT_VERSION = 15;
|
CURRENT_PROJECT_VERSION = 23;
|
||||||
DEAD_CODE_STRIPPING = YES;
|
DEAD_CODE_STRIPPING = YES;
|
||||||
ENABLE_HARDENED_RUNTIME = YES;
|
ENABLE_HARDENED_RUNTIME = YES;
|
||||||
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
INFOPLIST_FILE = ShoeGazeBuilder/Info.plist;
|
||||||
@@ -204,7 +204,7 @@
|
|||||||
"@executable_path/../Frameworks",
|
"@executable_path/../Frameworks",
|
||||||
);
|
);
|
||||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||||
MARKETING_VERSION = 3.0.0;
|
MARKETING_VERSION = 3.3;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilder;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
@@ -216,6 +216,7 @@
|
|||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||||
@@ -279,6 +280,7 @@
|
|||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||||
@@ -366,7 +368,8 @@
|
|||||||
isa = XCRemoteSwiftPackageReference;
|
isa = XCRemoteSwiftPackageReference;
|
||||||
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
||||||
requirement = {
|
requirement = {
|
||||||
kind = upToNextMajorVersion;
|
kind = versionRange;
|
||||||
|
maximumVersion = 3.0.0;
|
||||||
minimumVersion = 1.2.0;
|
minimumVersion = 1.2.0;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
|||||||
+2
-2
@@ -15,8 +15,8 @@
|
|||||||
"kind" : "remoteSourceControl",
|
"kind" : "remoteSourceControl",
|
||||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||||
"state" : {
|
"state" : {
|
||||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7",
|
||||||
"version" : "1.2.3"
|
"version" : "2.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Scheme
|
<Scheme
|
||||||
LastUpgradeVersion = "2660"
|
LastUpgradeVersion = "2700"
|
||||||
version = "1.7">
|
version = "1.7">
|
||||||
<BuildAction
|
<BuildAction
|
||||||
parallelizeBuildables = "YES"
|
parallelizeBuildables = "YES"
|
||||||
|
|||||||
@@ -103,7 +103,7 @@
|
|||||||
attributes = {
|
attributes = {
|
||||||
BuildIndependentTargetsInParallel = 1;
|
BuildIndependentTargetsInParallel = 1;
|
||||||
LastSwiftUpdateCheck = 1600;
|
LastSwiftUpdateCheck = 1600;
|
||||||
LastUpgradeCheck = 2660;
|
LastUpgradeCheck = 2700;
|
||||||
TargetAttributes = {
|
TargetAttributes = {
|
||||||
C3C100000000000000000011 = {
|
C3C100000000000000000011 = {
|
||||||
CreatedOnToolsVersion = 16.0;
|
CreatedOnToolsVersion = 16.0;
|
||||||
@@ -165,7 +165,7 @@
|
|||||||
CODE_SIGNING_REQUIRED = NO;
|
CODE_SIGNING_REQUIRED = NO;
|
||||||
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 8;
|
CURRENT_PROJECT_VERSION = 10;
|
||||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||||
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
||||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||||
@@ -175,11 +175,13 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 3.0.0;
|
MARKETING_VERSION = 1.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SDKROOT = iphoneos;
|
SDKROOT = iphoneos;
|
||||||
|
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||||
SUPPORTS_MACCATALYST = NO;
|
SUPPORTS_MACCATALYST = NO;
|
||||||
|
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
SWIFT_VERSION = 6.0;
|
SWIFT_VERSION = 6.0;
|
||||||
TARGETED_DEVICE_FAMILY = 2;
|
TARGETED_DEVICE_FAMILY = 2;
|
||||||
@@ -194,7 +196,7 @@
|
|||||||
CODE_SIGNING_REQUIRED = NO;
|
CODE_SIGNING_REQUIRED = NO;
|
||||||
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
CODE_SIGN_ENTITLEMENTS = ShoeGazeBuilderiOS/ShoeGazeBuilderiOS.entitlements;
|
||||||
CODE_SIGN_STYLE = Automatic;
|
CODE_SIGN_STYLE = Automatic;
|
||||||
CURRENT_PROJECT_VERSION = 8;
|
CURRENT_PROJECT_VERSION = 10;
|
||||||
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
INFOPLIST_FILE = ShoeGazeBuilderiOS/Info.plist;
|
||||||
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
INFOPLIST_KEY_CFBundleDisplayName = ShoeGaze;
|
||||||
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.music";
|
||||||
@@ -203,11 +205,13 @@
|
|||||||
"$(inherited)",
|
"$(inherited)",
|
||||||
"@executable_path/Frameworks",
|
"@executable_path/Frameworks",
|
||||||
);
|
);
|
||||||
MARKETING_VERSION = 3.0.0;
|
MARKETING_VERSION = 1.0;
|
||||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.ShoeGazeBuilderiOS;
|
||||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||||
SDKROOT = iphoneos;
|
SDKROOT = iphoneos;
|
||||||
|
SUPPORTED_PLATFORMS = "iphoneos iphonesimulator";
|
||||||
SUPPORTS_MACCATALYST = NO;
|
SUPPORTS_MACCATALYST = NO;
|
||||||
|
SUPPORTS_XR_DESIGNED_FOR_IPHONE_IPAD = NO;
|
||||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||||
SWIFT_VERSION = 6.0;
|
SWIFT_VERSION = 6.0;
|
||||||
TARGETED_DEVICE_FAMILY = 2;
|
TARGETED_DEVICE_FAMILY = 2;
|
||||||
@@ -218,6 +222,7 @@
|
|||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||||
@@ -281,6 +286,7 @@
|
|||||||
isa = XCBuildConfiguration;
|
isa = XCBuildConfiguration;
|
||||||
buildSettings = {
|
buildSettings = {
|
||||||
ALWAYS_SEARCH_USER_PATHS = NO;
|
ALWAYS_SEARCH_USER_PATHS = NO;
|
||||||
|
ASSETCATALOG_COMPILER_GENERATE_SWIFT_ASSET_SYMBOL_EXTENSIONS = YES;
|
||||||
CLANG_ANALYZER_NONNULL = YES;
|
CLANG_ANALYZER_NONNULL = YES;
|
||||||
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
|
||||||
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
CLANG_CXX_LANGUAGE_STANDARD = "gnu++20";
|
||||||
@@ -368,8 +374,9 @@
|
|||||||
isa = XCRemoteSwiftPackageReference;
|
isa = XCRemoteSwiftPackageReference;
|
||||||
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
repositoryURL = "https://realizedsound.mooo.com/josh/Lyrebird";
|
||||||
requirement = {
|
requirement = {
|
||||||
kind = upToNextMajorVersion;
|
kind = versionRange;
|
||||||
minimumVersion = 1.2.0;
|
maximumVersion = 3.0.0;
|
||||||
|
minimumVersion = 1.7.2;
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
/* End XCRemoteSwiftPackageReference section */
|
/* End XCRemoteSwiftPackageReference section */
|
||||||
|
|||||||
+2
-2
@@ -15,8 +15,8 @@
|
|||||||
"kind" : "remoteSourceControl",
|
"kind" : "remoteSourceControl",
|
||||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||||
"state" : {
|
"state" : {
|
||||||
"revision" : "c058493a9853695c441895a12e9f4a5dbc7295b0",
|
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54",
|
||||||
"version" : "1.2.3"
|
"version" : "2.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
<?xml version="1.0" encoding="UTF-8"?>
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
<Scheme
|
<Scheme
|
||||||
LastUpgradeVersion = "2660"
|
LastUpgradeVersion = "2700"
|
||||||
version = "1.7">
|
version = "1.7">
|
||||||
<BuildAction
|
<BuildAction
|
||||||
parallelizeBuildables = "YES"
|
parallelizeBuildables = "YES"
|
||||||
|
|||||||
@@ -17,10 +17,6 @@
|
|||||||
</array>
|
</array>
|
||||||
</dict>
|
</dict>
|
||||||
</array>
|
</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>
|
<key>CFBundleExecutable</key>
|
||||||
<string>$(EXECUTABLE_NAME)</string>
|
<string>$(EXECUTABLE_NAME)</string>
|
||||||
<key>CFBundleIdentifier</key>
|
<key>CFBundleIdentifier</key>
|
||||||
@@ -32,11 +28,13 @@
|
|||||||
<key>CFBundlePackageType</key>
|
<key>CFBundlePackageType</key>
|
||||||
<string>APPL</string>
|
<string>APPL</string>
|
||||||
<key>CFBundleShortVersionString</key>
|
<key>CFBundleShortVersionString</key>
|
||||||
<string>1.4.0</string>
|
<string>${MARKETING_VERSION}</string>
|
||||||
<key>CFBundleVersion</key>
|
<key>CFBundleVersion</key>
|
||||||
<string>1</string>
|
<string>${CURRENT_PROJECT_VERSION}</string>
|
||||||
<key>LSRequiresIPhoneOS</key>
|
<key>LSRequiresIPhoneOS</key>
|
||||||
<true/>
|
<true/>
|
||||||
|
<key>LSSupportsOpeningDocumentsInPlace</key>
|
||||||
|
<false/>
|
||||||
<key>NSHumanReadableCopyright</key>
|
<key>NSHumanReadableCopyright</key>
|
||||||
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
|
<string>Copyright © 2026 realizedsound. All rights reserved.</string>
|
||||||
<key>NSMicrophoneUsageDescription</key>
|
<key>NSMicrophoneUsageDescription</key>
|
||||||
|
|||||||
+3
-3
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"originHash" : "eed06b1870eecb6b28d2417331f105ea1cc25e9d6fe588c9d2eff8ca3af096f0",
|
"originHash" : "c8855e41a403b5b1fccd9ccb4b3ef4d75c4307590ae6a0b8e985e71c41011e09",
|
||||||
"pins" : [
|
"pins" : [
|
||||||
{
|
{
|
||||||
"identity" : "linenoise-swift",
|
"identity" : "linenoise-swift",
|
||||||
@@ -15,8 +15,8 @@
|
|||||||
"kind" : "remoteSourceControl",
|
"kind" : "remoteSourceControl",
|
||||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||||
"state" : {
|
"state" : {
|
||||||
"revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
|
"revision" : "24ea32e47cecff8efec9720546ed068b4efef2f7",
|
||||||
"version" : "1.7.2"
|
"version" : "2.2.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
+9
-6
@@ -24,14 +24,16 @@ let package = Package(
|
|||||||
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
.library(name: "LyrebirdShoeGazeUI", targets: ["LyrebirdShoeGazeUI"]),
|
||||||
],
|
],
|
||||||
dependencies: [
|
dependencies: [
|
||||||
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "1.7.2"),
|
.package(url: "https://realizedsound.mooo.com/josh/Lyrebird", from: "2.0.0"),
|
||||||
],
|
],
|
||||||
targets: [
|
targets: [
|
||||||
// The core target depends on LyrebirdUI as well as the synthesis core:
|
// Both targets depend on the core `Lyrebird` product AND `LyrebirdUI`.
|
||||||
// pedals expose their knobs as `@UIParam`, whose projected `UIParamNode`
|
// Pedals expose their knobs as `@UIParam`, whose projected `UIParamNode`
|
||||||
// (the type `ParameterKnob` binds to) lives in LyrebirdUI. Importing
|
// lives in the core `LyrebirdSynth` module (the `Lyrebird` product) as of
|
||||||
// LyrebirdUI here does not pull SwiftUI into ShoeGaze's own sources —
|
// Lyrebird 2.0 — `LyrebirdUI` no longer re-exports it — so any file using
|
||||||
// it only makes the `@UIParam` wrapper and `UIParamNode` visible.
|
// `@UIParam` / `UIParamNode` needs `import LyrebirdSynth`, which requires
|
||||||
|
// the `Lyrebird` product as a direct dependency. Importing these does not
|
||||||
|
// pull SwiftUI into ShoeGaze's own core sources.
|
||||||
.target(
|
.target(
|
||||||
name: "LyrebirdShoeGaze",
|
name: "LyrebirdShoeGaze",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
@@ -44,6 +46,7 @@ let package = Package(
|
|||||||
name: "LyrebirdShoeGazeUI",
|
name: "LyrebirdShoeGazeUI",
|
||||||
dependencies: [
|
dependencies: [
|
||||||
"LyrebirdShoeGaze",
|
"LyrebirdShoeGaze",
|
||||||
|
.product(name: "Lyrebird", package: "Lyrebird"),
|
||||||
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
.product(name: "LyrebirdUI", package: "Lyrebird"),
|
||||||
],
|
],
|
||||||
path: "Sources/LyrebirdShoeGazeUI"
|
path: "Sources/LyrebirdShoeGazeUI"
|
||||||
|
|||||||
@@ -11,8 +11,13 @@ signal (no hardware needed) or on live guitar through an audio input.
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **36 modeled pedals** across gain, dynamics, EQ/filter, modulation, pitch, delay, reverb, and
|
- **67 modeled pedals** — effects across gain, dynamics, EQ/filter, modulation, pitch, delay,
|
||||||
texture — see the catalog below.
|
reverb, and texture, plus **26 tube-amp models** with their own tone stacks and a deep
|
||||||
|
speaker-cabinet / microphone section. All original DSP built on the Lyrebird engine — no
|
||||||
|
third-party captures or IR packs. See the catalog below.
|
||||||
|
- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style
|
||||||
|
(Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) and reachable from a **Mine /
|
||||||
|
Starters** toggle in the rig sidebar.
|
||||||
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
|
- **Multi-board rigs** — build several boards and a board-mixer bar to **Solo** one (amp-channel
|
||||||
style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a
|
style) or **Blend** any subset, each with its own level and a click-free crossfade, plus a
|
||||||
rig-wide **output volume and mute** on top.
|
rig-wide **output volume and mute** on top.
|
||||||
@@ -21,8 +26,9 @@ signal (no hardware needed) or on live guitar through an audio input.
|
|||||||
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig.
|
volume, with per-binding invert for crossfades. MIDI Learn, one binding per rig.
|
||||||
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
|
- **Signal-flow editor** — drag pedals in from the palette; reorder, split into parallel or
|
||||||
stereo lanes, and merge back to mono.
|
stereo lanes, and merge back to mono.
|
||||||
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar; synced across
|
- **Rig library** — name, save, duplicate, and switch between rigs from a sidebar (your own rigs
|
||||||
your devices and both apps via iCloud.
|
and the shipped starters on separate tabs); synced across your devices and both apps via iCloud.
|
||||||
|
Switching rigs keeps your current input, and saving over a starter rig asks first.
|
||||||
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share
|
- **Sharing** — send a rig or a saved board to anyone as a `.shoegaze` file via the system share
|
||||||
sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
|
sheet (AirDrop, Mail, Messages, Files); export/import the whole library the same way.
|
||||||
- **Recording** — capture your output to timestamped files.
|
- **Recording** — capture your output to timestamped files.
|
||||||
@@ -37,14 +43,16 @@ signal (no hardware needed) or on live guitar through an audio input.
|
|||||||
|
|
||||||
| Category | Pedals |
|
| Category | Pedals |
|
||||||
|---|---|
|
|---|---|
|
||||||
| Gain | Overdrive, Distortion, Fuzz |
|
| Gain | Overdrive, Distortion, Fuzz, Sustain Fuzz |
|
||||||
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate |
|
| Dynamics | Compressor, Sustainer, Limiter, Noise Gate, Volume |
|
||||||
| EQ & filter | Graphic EQ, Auto-Wah, Mutant, Cabinet |
|
| EQ & filter | Graphic EQ, Auto-Wah, Wah, Mutant |
|
||||||
| Modulation | Tremolo, Phaser, Modulation, Chorus, Flanger, Vibrato, Rotary, Ring Modulator |
|
| Modulation | Tremolo, Phaser, Script Phaser, Modulation, Chorus, Flanger, Vibrato, Vibe, Rotary, Ring Modulator |
|
||||||
| Pitch | Bass Octaver, Octave Splitter, Harmonizer |
|
| Pitch | Bass Octaver, Octave Splitter, Harmonizer, Whammy, Poly Octave |
|
||||||
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay |
|
| Delay | Delay, Feedback Delay, Multi-Tap Delay, Ping-Pong, Reverse Delay, DL4 |
|
||||||
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb |
|
| Reverb | Reverb, Shimmer Reverb, Plate Reverb, Room Reverb, Spring Reverb, Reverse Reverb, Granular Reverb |
|
||||||
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator |
|
| Texture | Diffuser, Bitcrusher, Granulator, Auto Granulator, Karplus Resonator, Looper, Tape Looper |
|
||||||
|
| Amp Model | Fullerton Reverb / Deluxe / Ivy League / Drive, California, Jazz Clean, British / Plexi / JTM / Bluesbreaker / Master / Dual, Chime / Chime Top Boost / 15 / Normal / Baby, Boutique Lead / OD, Cali Hi-Gain, Modern High-Gain, Command, Citrus, Sixties Combo, Magna Vibrato, Anaheim |
|
||||||
|
| Cabinet | Cabinet (speaker-voice + microphone modeling) |
|
||||||
|
|
||||||
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
|
Every pedal exposes its parameters as knobs/switches and round-trips through the rig save format.
|
||||||
|
|
||||||
@@ -52,7 +60,7 @@ Every pedal exposes its parameters as knobs/switches and round-trips through the
|
|||||||
|
|
||||||
- macOS 15+ / iPadOS 18+ (iPad, landscape)
|
- macOS 15+ / iPadOS 18+ (iPad, landscape)
|
||||||
- Swift 6.0 toolchain / Xcode 16+
|
- Swift 6.0 toolchain / Xcode 16+
|
||||||
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.2.0+
|
- [Lyrebird](https://realizedsound.mooo.com/josh/Lyrebird) 1.7.0+
|
||||||
|
|
||||||
## Packages
|
## Packages
|
||||||
|
|
||||||
|
|||||||
+73
@@ -1,4 +1,77 @@
|
|||||||
# Releases
|
# Releases
|
||||||
|
## ShoeGaze 3.3.0
|
||||||
|
|
||||||
|
Noise-gate and output-level fixes, on Lyrebird 2.2.0.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Noise Gate now respects its threshold after loading a rig.** A gate restored from a saved
|
||||||
|
rig could latch open and ignore its Threshold knob — the gate's open level is derived from the
|
||||||
|
threshold, and that value swept up from a default on the first audio block, tripping the gate
|
||||||
|
on the transient. Fixed upstream in Lyrebird 2.2.0 (a live parameter set before the first
|
||||||
|
render is now delivered flat), so the gate reads its real threshold from the first block.
|
||||||
|
- **Mono rigs come out at the level they went in.** A mono board was written through a centre
|
||||||
|
pan that dropped both channels ~3 dB; it now copies the mono signal to both outputs at unity.
|
||||||
|
|
||||||
|
### Changed
|
||||||
|
- **Noise Gate detector: Peak / RMS, defaulting to RMS.** RMS follows perceived loudness, so the
|
||||||
|
gate's threshold decision tracks how loud the note actually is instead of riding the waveform
|
||||||
|
peaks. A gate saved before this switch existed loads on RMS. (Peak remains available.)
|
||||||
|
- Updated to **Lyrebird 2.2.0**.
|
||||||
|
|
||||||
|
## ShoeGaze 3.1.1
|
||||||
|
|
||||||
|
A small fix for the Mutant envelope filter's control panel.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- **Mutant switch captions no longer wrap.** Its three segmented switches (Direction / Mode /
|
||||||
|
Range) were cramped into a single-width pedal, wrapping "Down" to "Do wn". Mutant is now
|
||||||
|
double-width — like the Cabinet and amp pedals — so the captions fit.
|
||||||
|
|
||||||
|
## ShoeGaze 3.1.0
|
||||||
|
|
||||||
|
Starter rigs, two new pedals, and a deeper envelope filter — plus smoother rig switching.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
- **Starter rigs** — a library of ready-to-play rigs ships with the app, grouped by style
|
||||||
|
(Shoegaze Walls, Dreampop, Classic, Ambient, Experimental) behind a **Mine / Starters** toggle
|
||||||
|
in the rig sidebar. Includes a two-board clean/effects split. **Restore Starter Rigs** reinstalls
|
||||||
|
them any time.
|
||||||
|
- **Vibe** — a photocell "vibe" (four staggered all-pass stages swept by one LFO) with Chorus and
|
||||||
|
Vibrato modes.
|
||||||
|
- **Sustain Fuzz** — a mid-scooped, high-sustain fuzz, distinct from the brighter single-stage Fuzz.
|
||||||
|
- **A deeper Mutant envelope filter** — a **Range** switch (Lo / Hi) that shifts the whole sweep
|
||||||
|
band like the original Mu-Tron III, plus **Sweep**, **Attack**, and **Release** in the advanced
|
||||||
|
pop-over.
|
||||||
|
- **Rig switching keeps your input** — your live guitar stays selected across a rig change instead
|
||||||
|
of snapping back to the test loop.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- No more spurious "Save changes?" prompt when switching between rigs.
|
||||||
|
- Shimmer Reverb no longer self-oscillates into a screech at its defaults.
|
||||||
|
- Saving over a starter rig asks first (Overwrite / Save as New Rig / Cancel).
|
||||||
|
- Multi-board signal-router rigs now save and load.
|
||||||
|
|
||||||
|
## ShoeGaze 3.0.0
|
||||||
|
|
||||||
|
The big one: ShoeGaze becomes an amp-modeling rig — a full lineup of tube-amp voices plus a deep
|
||||||
|
speaker-cabinet and microphone section, all original DSP built from the Lyrebird engine with no
|
||||||
|
third-party captures or IR packs.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
- **26 amp-model pedals** in their own **Amp Model** palette category — Fullerton blackface combos,
|
||||||
|
California and Jazz Clean cleans, British stack / combo voices, the Chime top-boost family,
|
||||||
|
Boutique and high-gain amps, and character amps (Command, Citrus, Sixties Combo, Magna Vibrato,
|
||||||
|
Anaheim). Each has its own tone stack, a selectable speaker cabinet, and a real master volume that
|
||||||
|
drives the power-amp stage.
|
||||||
|
- **Speaker-cabinet + microphone section** on the Cabinet pedal — eight speaker voicings, mic
|
||||||
|
modeling (Dynamic / Ribbon / Condenser), placement and proximity, and a dual-mic blend.
|
||||||
|
- **Power-amp feel controls** — Sag, Bias, and Bias X in an advanced pop-over — and analog-style
|
||||||
|
soft limiting, so a driven amp compresses toward its ceiling instead of clipping harshly.
|
||||||
|
- **Gain and Drive read 1–11** with a musical taper.
|
||||||
|
|
||||||
|
### Fixed
|
||||||
|
- Noise Gate no longer pops as a note decays.
|
||||||
|
|
||||||
## ShoeGaze 2.1.3
|
## ShoeGaze 2.1.3
|
||||||
|
|
||||||
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even
|
A tuner fix. Engaging the chromatic tuner could crackle or pop through the output — even
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
{
|
{
|
||||||
"originHash" : "9ce521e7cebf3eed8e20837aba069e3f0c5484a64130b1791e8e6fdb7874b9f0",
|
"originHash" : "13b4323e9d41dfdff1c6aeac595cff272eb4eee9cc1a3146483bdaf8543bc103",
|
||||||
"pins" : [
|
"pins" : [
|
||||||
{
|
{
|
||||||
"identity" : "linenoise-swift",
|
"identity" : "linenoise-swift",
|
||||||
@@ -15,8 +15,8 @@
|
|||||||
"kind" : "remoteSourceControl",
|
"kind" : "remoteSourceControl",
|
||||||
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
"location" : "https://realizedsound.mooo.com/josh/Lyrebird",
|
||||||
"state" : {
|
"state" : {
|
||||||
"revision" : "77580ee98e05cb4a94aac367097d27b91d3776c0",
|
"revision" : "b6fdee8bfc7c44d31a0a8cfe6fbd53f352dfad54",
|
||||||
"version" : "1.7.2"
|
"version" : "2.0.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -82,9 +82,6 @@ final class BoardOutputMaster: SynthesizerBase {
|
|||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
|
|
||||||
/// Pan position for the board in the stereo field. Centre = 0.0. Used only for a mono board.
|
|
||||||
private let stereoPan: Double = 0.0
|
|
||||||
|
|
||||||
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
|
/// Lag time constant in seconds for the bypass crossfades — smooths engaged ↔ bypassed
|
||||||
/// transitions to prevent clicks. Matches the per-pedal bypass lag.
|
/// transitions to prevent clicks. Matches the per-pedal bypass lag.
|
||||||
private let bypassLagTime: Double = 0.02
|
private let bypassLagTime: Double = 0.02
|
||||||
@@ -137,8 +134,12 @@ final class BoardOutputMaster: SynthesizerBase {
|
|||||||
output(bus: 0, source: gainedLeft)
|
output(bus: 0, source: gainedLeft)
|
||||||
output(bus: 1, source: gainedRight)
|
output(bus: 1, source: gainedRight)
|
||||||
} else {
|
} else {
|
||||||
// Mono board: Pan2 spreads the mono output to stereo hardware buses 0 + 1.
|
// Mono board: write the mono signal to both hardware buses at unity (0 dB). Using an
|
||||||
output(bus: 0, source: Pan2(input: gainedLeft, pan: stereoPan))
|
// equal-power `Pan2` to centre would drop each channel by 3 dB (×0.707) — power-correct
|
||||||
|
// for a true pan, but a mono guitar rig should come out at the same level it went in, so
|
||||||
|
// the signal is copied to left and right directly instead.
|
||||||
|
output(bus: 0, source: gainedLeft)
|
||||||
|
output(bus: 1, source: gainedLeft)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,7 +19,7 @@ import LyrebirdUI
|
|||||||
/// inputBus → dry → effect(_:) → wet
|
/// inputBus → dry → effect(_:) → wet
|
||||||
/// ↕ mix (equal-power crossfade)
|
/// ↕ mix (equal-power crossfade)
|
||||||
/// blended
|
/// blended
|
||||||
/// ↕ bypass (lagged equal-power crossfade with dry)
|
/// ↕ bypass (linear equal-power crossfade with dry)
|
||||||
/// switched → × level → outputBus
|
/// switched → × level → outputBus
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
@@ -32,7 +32,7 @@ import LyrebirdUI
|
|||||||
///
|
///
|
||||||
/// - `mix`: Wet/dry blend in `[0, 1]`. `0` = fully dry, `1` = fully wet.
|
/// - `mix`: Wet/dry blend in `[0, 1]`. `0` = fully dry, `1` = fully wet.
|
||||||
/// - `bypass`: Bypass state. `0` = engaged (effect active), `1` = bypassed (pure dry).
|
/// - `bypass`: Bypass state. `0` = engaged (effect active), `1` = bypassed (pure dry).
|
||||||
/// Transitions are smoothed with a 20 ms lag to avoid clicks.
|
/// Transitions are smoothed with a linear crossfade (see ``bypassFadeTime``) to avoid clicks.
|
||||||
/// - `level`: Output gain as a linear multiplier. `1.0` = unity gain.
|
/// - `level`: Output gain as a linear multiplier. `1.0` = unity gain.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -47,7 +47,7 @@ open class Pedal: SynthesizerBase {
|
|||||||
@UIParam public var mix: Double = 1.0
|
@UIParam public var mix: Double = 1.0
|
||||||
|
|
||||||
/// Bypass state. `0` = engaged (effect active), `1` = bypassed (dry signal only).
|
/// Bypass state. `0` = engaged (effect active), `1` = bypassed (dry signal only).
|
||||||
/// Transitions are smoothed by `bypassLagTime` seconds to prevent clicks.
|
/// Transitions are smoothed by a linear crossfade over ``bypassFadeTime`` seconds to prevent clicks.
|
||||||
@UIParam public var bypass: Double = 0.0
|
@UIParam public var bypass: Double = 0.0
|
||||||
|
|
||||||
/// Output gain as a linear multiplier. `1.0` = unity gain.
|
/// Output gain as a linear multiplier. `1.0` = unity gain.
|
||||||
@@ -156,9 +156,22 @@ open class Pedal: SynthesizerBase {
|
|||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
|
|
||||||
/// Lag time constant in seconds (60 dB convergence) for the bypass crossfade.
|
/// Duration in seconds of the engaged ↔ bypassed crossfade. The bypass control is slewed
|
||||||
/// Smooths engaged ↔ bypassed transitions to prevent audible clicks.
|
/// **linearly** and at **audio rate** from `0` to `1` (or back) over this time, so the
|
||||||
private let bypassLagTime: Double = 0.02
|
/// equal-power crossfade sweeps smoothly, one step per sample. Two earlier approaches clicked
|
||||||
|
/// here when the crossfade legs are decorrelated and full-scale (a wet-only pitch shifter such as
|
||||||
|
/// the Whammy swapping against the dry note; masked when wet ≈ dry): a one-pole `Lag`, whose
|
||||||
|
/// exponential curve is front-loaded (steepest slope at the very start); and a block-rate slew,
|
||||||
|
/// which steps only once per audio block — at the engine's 512-sample block a short fade is just
|
||||||
|
/// a few coarse jumps, each its own click. An audio-rate linear slew has neither flaw.
|
||||||
|
/// Overridable for pedals needing a gentler fade.
|
||||||
|
open var bypassFadeTime: Double { 0.03 }
|
||||||
|
|
||||||
|
/// Lower bound the effective fade time is clamped to before taking its reciprocal for the slew
|
||||||
|
/// rate. Guards against an override returning `0` (reciprocal `.infinity` → instantaneous slew,
|
||||||
|
/// which reintroduces the click this fade removes) or a negative value (which would invert the
|
||||||
|
/// slew). One sample at 48 kHz, so a legitimate small fade is left untouched.
|
||||||
|
private let minBypassFadeTime: Double = 1.0 / 48_000.0
|
||||||
|
|
||||||
// Bipolar-span constant used to remap a [0, 1] value to [-1, +1]
|
// Bipolar-span constant used to remap a [0, 1] value to [-1, +1]
|
||||||
// for CrossFade's equal-power pan parameter.
|
// for CrossFade's equal-power pan parameter.
|
||||||
@@ -421,7 +434,7 @@ open class Pedal: SynthesizerBase {
|
|||||||
/// Builds the signal graph for one channel: dry → wet/dry blend → bypass switch → × level.
|
/// Builds the signal graph for one channel: dry → wet/dry blend → bypass switch → × level.
|
||||||
///
|
///
|
||||||
/// Returns the final post-`level` source for the channel. The `mix`, `bypass`, and `level`
|
/// Returns the final post-`level` source for the channel. The `mix`, `bypass`, and `level`
|
||||||
/// `@UIParam` nodes are shared across channels; each channel gets its own `Lag.Control`
|
/// `@UIParam` nodes are shared across channels; each channel gets its own `Slew.Audio`
|
||||||
/// for the bypass crossfade so smoothing is per-channel state driven by the same target.
|
/// for the bypass crossfade so smoothing is per-channel state driven by the same target.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -442,14 +455,25 @@ open class Pedal: SynthesizerBase {
|
|||||||
pan: mixPan
|
pan: mixPan
|
||||||
)
|
)
|
||||||
|
|
||||||
// Smooth bypass transitions with a 20 ms lag to prevent clicks.
|
// Smooth bypass transitions with a linear crossfade to prevent clicks. The slew runs at
|
||||||
let bypassLagged: Lag.Control = Lag.Control(
|
// AUDIO rate, not control rate: a block-rate smoother takes one step per audio block, so at
|
||||||
|
// the engine's 512-sample block a short fade is only a handful of coarse steps — each a
|
||||||
|
// click of its own. `Slew.Audio` ramps per sample, so the fade is smooth regardless of
|
||||||
|
// block size. Linear slope (not a front-loaded one-pole lag) keeps it click-free even when
|
||||||
|
// the two legs are decorrelated and full-scale, as for a wet-only pitch shifter.
|
||||||
|
// Rate is in bypass-units per second: 0 → 1 traverses in exactly `bypassFadeTime` seconds.
|
||||||
|
// Clamp to a positive floor first — a subclass override returning 0 or negative would
|
||||||
|
// otherwise yield an infinite or inverted slew rate (see `minBypassFadeTime`).
|
||||||
|
let effectiveFadeTime: Double = max(bypassFadeTime, minBypassFadeTime)
|
||||||
|
let bypassFadeRate: Double = 1.0 / effectiveFadeTime
|
||||||
|
let bypassSlewed: Slew.Audio = Slew.Audio(
|
||||||
input: $bypass,
|
input: $bypass,
|
||||||
time: bypassLagTime
|
up: bypassFadeRate,
|
||||||
|
dn: bypassFadeRate
|
||||||
)
|
)
|
||||||
|
|
||||||
// Map bypass [0, 1] → pan [-1, +1]: −1 = blended (engaged), +1 = dry (bypassed).
|
// Map bypass [0, 1] → pan [-1, +1]: −1 = blended (engaged), +1 = dry (bypassed).
|
||||||
let bypassPan: any ValidGeneratorInput = (bypassLagged * bipolarSpan) - bipolarOffset
|
let bypassPan: any ValidGeneratorInput = (bypassSlewed * bipolarSpan) - bipolarOffset
|
||||||
|
|
||||||
// Equal-power crossfade: engaged → blended; bypassed → dry.
|
// Equal-power crossfade: engaged → blended; bypassed → dry.
|
||||||
let switched: CrossFade.Audio = CrossFade.Audio(
|
let switched: CrossFade.Audio = CrossFade.Audio(
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
|
/// A UI-agnostic description of one pedal button — a momentary action trigger or a
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A continuous pedal control that can be driven by a MIDI Control Change — the common shape of a
|
/// A continuous pedal control that can be driven by a MIDI Control Change — the common shape of a
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A UI-agnostic description of one controllable pedal knob.
|
/// A UI-agnostic description of one controllable pedal knob.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops.
|
/// A UI-agnostic description of a knob that snaps to a fixed set of labelled stops.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A UI-agnostic description of one continuous vertical pedal fader.
|
/// A UI-agnostic description of one continuous vertical pedal fader.
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// A UI-agnostic description of one multi-position pedal switch.
|
/// A UI-agnostic description of one multi-position pedal switch.
|
||||||
|
|||||||
@@ -74,6 +74,7 @@ public extension PedalType {
|
|||||||
static let overdrive = PedalType("Overdrive")
|
static let overdrive = PedalType("Overdrive")
|
||||||
static let distortion = PedalType("Distortion")
|
static let distortion = PedalType("Distortion")
|
||||||
static let fuzz = PedalType("Fuzz")
|
static let fuzz = PedalType("Fuzz")
|
||||||
|
static let sustainFuzz = PedalType("Sustain Fuzz")
|
||||||
static let compressor = PedalType("Compressor")
|
static let compressor = PedalType("Compressor")
|
||||||
static let limiter = PedalType("Limiter")
|
static let limiter = PedalType("Limiter")
|
||||||
static let noiseGate = PedalType("Noise Gate")
|
static let noiseGate = PedalType("Noise Gate")
|
||||||
@@ -92,12 +93,15 @@ public extension PedalType {
|
|||||||
static let chorus = PedalType("Chorus")
|
static let chorus = PedalType("Chorus")
|
||||||
static let flanger = PedalType("Flanger")
|
static let flanger = PedalType("Flanger")
|
||||||
static let vibrato = PedalType("Vibrato")
|
static let vibrato = PedalType("Vibrato")
|
||||||
|
static let vibe = PedalType("Vibe")
|
||||||
static let rotary = PedalType("Rotary")
|
static let rotary = PedalType("Rotary")
|
||||||
static let ringModulator = PedalType("Ring Modulator")
|
static let ringModulator = PedalType("Ring Modulator")
|
||||||
|
static let scriptPhaser = PedalType("Script Phaser")
|
||||||
static let diffuser = PedalType("Diffuser")
|
static let diffuser = PedalType("Diffuser")
|
||||||
static let bitcrusher = PedalType("Bitcrusher")
|
static let bitcrusher = PedalType("Bitcrusher")
|
||||||
static let granulator = PedalType("Granulator")
|
static let granulator = PedalType("Granulator")
|
||||||
static let autoGranulator = PedalType("Auto Granulator")
|
static let autoGranulator = PedalType("Auto Granulator")
|
||||||
|
static let karplusResonator = PedalType("Karplus Resonator")
|
||||||
|
|
||||||
// Dynamics (additional)
|
// Dynamics (additional)
|
||||||
static let sustainer = PedalType("Sustainer")
|
static let sustainer = PedalType("Sustainer")
|
||||||
@@ -111,17 +115,23 @@ public extension PedalType {
|
|||||||
static let multiTapDelay = PedalType("Multi-Tap Delay")
|
static let multiTapDelay = PedalType("Multi-Tap Delay")
|
||||||
static let pingPong = PedalType("Ping-Pong")
|
static let pingPong = PedalType("Ping-Pong")
|
||||||
static let reverseDelay = PedalType("Reverse Delay")
|
static let reverseDelay = PedalType("Reverse Delay")
|
||||||
|
static let dl4 = PedalType("DL4")
|
||||||
static let reverb = PedalType("Reverb")
|
static let reverb = PedalType("Reverb")
|
||||||
static let shimmerReverb = PedalType("Shimmer Reverb")
|
static let shimmerReverb = PedalType("Shimmer Reverb")
|
||||||
static let plateReverb = PedalType("Plate Reverb")
|
static let plateReverb = PedalType("Plate Reverb")
|
||||||
static let roomReverb = PedalType("Room Reverb")
|
static let roomReverb = PedalType("Room Reverb")
|
||||||
static let springReverb = PedalType("Spring Reverb")
|
static let springReverb = PedalType("Spring Reverb")
|
||||||
|
static let reverseReverb = PedalType("Reverse Reverb")
|
||||||
|
static let granularReverb = PedalType("Granular Reverb")
|
||||||
|
|
||||||
// Pitch & octave
|
// Pitch & octave
|
||||||
static let octaveSplitter = PedalType("Octave Splitter")
|
static let octaveSplitter = PedalType("Octave Splitter")
|
||||||
static let bassOctaver = PedalType("Bass Octaver")
|
static let bassOctaver = PedalType("Bass Octaver")
|
||||||
static let harmonizer = PedalType("Harmonizer")
|
static let harmonizer = PedalType("Harmonizer")
|
||||||
|
static let whammy = PedalType("Whammy")
|
||||||
|
static let polyOctave = PedalType("Poly Octave")
|
||||||
|
|
||||||
// Looper
|
// Looper
|
||||||
static let looper = PedalType("Looper")
|
static let looper = PedalType("Looper")
|
||||||
|
static let tapeLooper = PedalType("Tape Looper")
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,296 @@
|
|||||||
|
// DL4Pedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// An umbrella multi-model delay in the mould of the classic green four-knob delay modeller: one
|
||||||
|
/// pedal, a **Model** selector, and four shared controls (**Time**, **Repeats**, **Tone**, **Mod**)
|
||||||
|
/// whose character changes with the chosen model. This is the delay-models side only — no looper.
|
||||||
|
///
|
||||||
|
/// Each model is a distinct delay recipe built from Lyrebird primitives:
|
||||||
|
/// - **Tube** — a driven, warm echo (soft-clipped input into a filtered delay).
|
||||||
|
/// - **Tape** — a tape echo with slow wow modulating the delay time and a tape-style HF rolloff.
|
||||||
|
/// - **Analog** — a dark bucket-brigade voice (heavily low-passed, gently saturated repeats).
|
||||||
|
/// - **Analog Mod** — the analog voice with a chorus-rate wobble on the delay time.
|
||||||
|
/// - **Multi-Head** — three fixed delay taps plus a feedback repeat, à la a multi-head tape unit.
|
||||||
|
/// - **Sweep** — a delay fed through a sweeping all-pass for a phased, resonant echo.
|
||||||
|
/// - **Lo-Res** — a down-sampled, gritty lo-fi delay.
|
||||||
|
/// - **Reverse** — backward echo segments (the ``ReverseDelay`` generator).
|
||||||
|
///
|
||||||
|
/// `effect` returns the pure wet signal; the base `Pedal` `mix` sets the wet/dry blend.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `time`: Delay time in seconds. Range `[0.02, 2.0]`. Tempo-syncable.
|
||||||
|
/// - `repeats`: Feedback, as the decay time in seconds for echoes to fall to −60 dB. Range `[0.05, 8.0]`.
|
||||||
|
/// - `tone`: Repeat brightness — a low-pass cutoff in Hz. Range `[500, 12000]`.
|
||||||
|
/// - `mod`: Modulation amount in `[0, 1]` for the models that modulate — delay-time wow depth for
|
||||||
|
/// Tape and Analog Mod, and the sweep rate for Sweep; inert for the others.
|
||||||
|
///
|
||||||
|
/// ## Selectors
|
||||||
|
/// - `model`: The delay model (rebuilds on change).
|
||||||
|
public final class DL4Pedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Multi-model delay: tube, tape, analog, multi-head, sweep, lo-res, and reverse voices."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Delay time in seconds. Range `[0.02, 2.0]`.
|
||||||
|
@UIParam public var time: Double = 0.4
|
||||||
|
|
||||||
|
/// Feedback as decay time in seconds (−60 dB). Range `[0.05, 8.0]`.
|
||||||
|
@UIParam public var repeats: Double = 1.5
|
||||||
|
|
||||||
|
/// Repeat brightness — low-pass cutoff in Hz. Range `[500, 12000]`.
|
||||||
|
@UIParam public var tone: Double = 6000.0
|
||||||
|
|
||||||
|
/// Modulation amount in `[0, 1]` — Tape wow depth, Analog Mod wobble depth, or Sweep rate.
|
||||||
|
@UIParam public var mod: Double = 0.3
|
||||||
|
|
||||||
|
/// Selected model index into ``models``. A knob-picker selector; rebuilds on change.
|
||||||
|
@UIParam public var model: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Models
|
||||||
|
|
||||||
|
/// The ordered model list. The index is written to ``model`` by the selector and read at build
|
||||||
|
/// time by ``effect(_:)`` to pick the recipe.
|
||||||
|
private static let models: [String] = [
|
||||||
|
"Tube", "Tape", "Analog", "Analog Mod", "Multi-Head", "Sweep", "Lo-Res", "Reverse",
|
||||||
|
]
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — a partial mix so dry and echoes coexist.
|
||||||
|
private static let defaultMix: Double = 0.35
|
||||||
|
|
||||||
|
/// Maximum delay time in seconds. Sizes every delay line; kept above `timeRange.upperBound` so
|
||||||
|
/// the modulated models can push the delay time a little past the knob maximum without wrapping.
|
||||||
|
private let maxDelayTime: Double = 2.2
|
||||||
|
|
||||||
|
/// Amplitude target for the feedback `decayTime` calculation (−60 dB).
|
||||||
|
private let targetAmp: Double = 0.001
|
||||||
|
|
||||||
|
/// Butterworth Q (no resonant peak) for the tone low-pass.
|
||||||
|
private let filterQ: Double = 0.707
|
||||||
|
|
||||||
|
// Tube
|
||||||
|
private let tubeDrive: Double = 2.0
|
||||||
|
|
||||||
|
// Tape
|
||||||
|
private let tapeWowRate: Double = 0.7 // Hz
|
||||||
|
private let tapeWowDepth: Double = 0.003 // seconds at mod = 1
|
||||||
|
private let tapeToneScale: Double = 0.8 // tape HF rolloff
|
||||||
|
|
||||||
|
// Analog
|
||||||
|
private let analogToneScale: Double = 0.5 // dark BBD voice
|
||||||
|
private let analogDrive: Double = 1.3
|
||||||
|
|
||||||
|
// Analog Mod
|
||||||
|
private let analogModRate: Double = 1.6 // Hz
|
||||||
|
private let analogModDepth: Double = 0.0025 // seconds at mod = 1
|
||||||
|
|
||||||
|
// Multi-Head
|
||||||
|
private let headBFraction: Double = 0.5 // second tap at half the time
|
||||||
|
private let headCFraction: Double = 0.75 // third tap at three-quarters
|
||||||
|
private let headGain: Double = 0.2 // per-tap level (3 taps → 0.6)
|
||||||
|
private let repeatGain: Double = 0.4 // feedback-repeat level (sum 3·0.2 + 0.4 = 1.0)
|
||||||
|
|
||||||
|
// Sweep
|
||||||
|
private let sweepRateMin: Double = 0.05 // Hz at mod = 0
|
||||||
|
private let sweepRateSpan: Double = 1.45 // + span at mod = 1 → up to 1.5 Hz
|
||||||
|
private let sweepDepth: Double = 0.8
|
||||||
|
private let sweepCenterFreq: Double = 900.0
|
||||||
|
private let sweepFeedback: Double = 0.3
|
||||||
|
private let sweepStages: Int = 4
|
||||||
|
private let sweepInternalMix: Double = 1.0
|
||||||
|
|
||||||
|
// Lo-Res
|
||||||
|
private let loResDownsample: Double = 4.0 // hold length in samples
|
||||||
|
private let loResToneScale: Double = 0.6
|
||||||
|
|
||||||
|
// Reverse
|
||||||
|
private let reverseFeedbackScale: Double = 0.95 / 8.0 // maps repeats (≤ 8 s) → [0, 0.95]
|
||||||
|
private let reverseFeedbackMax: Double = 0.95
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let timeRange: ClosedRange<Double> = 0.02 ... 2.0
|
||||||
|
private let repeatsRange: ClosedRange<Double> = 0.05 ... 8.0
|
||||||
|
private let toneRange: ClosedRange<Double> = 500.0 ... 12000.0
|
||||||
|
private let modRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Time", node: $time, range: timeRange),
|
||||||
|
PedalKnob(label: "Repeats", node: $repeats, range: repeatsRange),
|
||||||
|
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||||
|
PedalKnob(label: "Mod", node: $mod, range: modRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||||
|
[
|
||||||
|
TempoSyncableParam(key: "time", label: "Time", node: $time, kind: .time, range: timeRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Selectors
|
||||||
|
|
||||||
|
public override var effectSelectors: [PedalSelectorKnob] {
|
||||||
|
let stops: [PedalSelectorKnob.Stop] = DL4Pedal.models.enumerated().map { index, name in
|
||||||
|
PedalSelectorKnob.Stop(title: name, value: Double(index))
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
// Each model is a different delay topology read at build time, so switching rebuilds.
|
||||||
|
PedalSelectorKnob(label: "Model", node: $model, stops: stops, rebuildsOnChange: true),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a multi-model delay pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "DL4",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: DL4Pedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// `model` is read as a plain value at build time; the board rebuilds when it changes (each
|
||||||
|
// model is a different delay topology). Time / Repeats / Tone / Mod stay live.
|
||||||
|
let index: Int = min(max(0, Int(model.rounded())), DL4Pedal.models.count - 1)
|
||||||
|
switch index {
|
||||||
|
case 0: return makeTube(dry: dry)
|
||||||
|
case 1: return makeTape(dry: dry)
|
||||||
|
case 2: return makeAnalog(dry: dry)
|
||||||
|
case 3: return makeAnalogMod(dry: dry)
|
||||||
|
case 4: return makeMultiHead(dry: dry)
|
||||||
|
case 5: return makeSweep(dry: dry)
|
||||||
|
case 6: return makeLoRes(dry: dry)
|
||||||
|
default: return makeReverse(dry: dry)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Model builders
|
||||||
|
|
||||||
|
/// A feedback delay line on `input` at the current Time / Repeats.
|
||||||
|
private func feedbackDelay(input: any ValidGeneratorInput, delay: any ValidGeneratorInput) -> DelayLineFeedback {
|
||||||
|
DelayLineFeedback(
|
||||||
|
input: input,
|
||||||
|
maxDelay: maxDelayTime,
|
||||||
|
delay: delay,
|
||||||
|
decayTime: $repeats,
|
||||||
|
targetAmp: targetAmp,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
interpolation: .linear
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tone low-pass at the given cutoff.
|
||||||
|
private func toned(_ input: any ValidGeneratorInput, cutoff: any ValidGeneratorInput) -> RBJLowPass.Audio {
|
||||||
|
RBJLowPass.Audio(input: input, freq: cutoff, q: filterQ)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tube: soft-clipped input into a filtered feedback delay — a driven, warm echo.
|
||||||
|
private func makeTube(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let driven: SoftClip.Audio = SoftClip.Audio(dry, drive: tubeDrive)
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: driven, delay: $time)
|
||||||
|
return toned(fb, cutoff: $tone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tape: slow wow modulates the delay time, with a tape-style HF rolloff.
|
||||||
|
private func makeTape(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let wow: OscSin.Audio = OscSin.Audio(freq: tapeWowRate, mul: $mod * tapeWowDepth)
|
||||||
|
let delay: any ValidGeneratorInput = $time + wow
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: delay)
|
||||||
|
return toned(fb, cutoff: $tone * tapeToneScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Analog: dark, gently saturated bucket-brigade voice.
|
||||||
|
private func makeAnalog(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
|
||||||
|
let dark: RBJLowPass.Audio = toned(fb, cutoff: $tone * analogToneScale)
|
||||||
|
return SoftClip.Audio(dark, drive: analogDrive)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Analog Mod: the analog voice with a chorus-rate wobble on the delay time.
|
||||||
|
private func makeAnalogMod(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let wobble: OscSin.Audio = OscSin.Audio(freq: analogModRate, mul: $mod * analogModDepth)
|
||||||
|
let delay: any ValidGeneratorInput = $time + wobble
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: delay)
|
||||||
|
return toned(fb, cutoff: $tone * analogToneScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Multi-Head: three fixed delay taps plus a feedback repeat, like a multi-head tape unit.
|
||||||
|
private func makeMultiHead(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let tapA: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time, sampleRate: sampleRate)
|
||||||
|
let tapB: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time * headBFraction, sampleRate: sampleRate)
|
||||||
|
let tapC: DelayLine = DelayLine(input: dry, maxDelay: maxDelayTime, delay: $time * headCFraction, sampleRate: sampleRate)
|
||||||
|
let repeatsTap: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
|
||||||
|
let sum: any ValidGeneratorInput =
|
||||||
|
(tapA * headGain) + (tapB * headGain) + (tapC * headGain) + (repeatsTap * repeatGain)
|
||||||
|
return toned(sum, cutoff: $tone)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sweep: a filtered delay fed through a sweeping all-pass for a phased, resonant echo.
|
||||||
|
private func makeSweep(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
|
||||||
|
let base: RBJLowPass.Audio = toned(fb, cutoff: $tone)
|
||||||
|
let sweepRate: any ValidGeneratorInput = ($mod * sweepRateSpan) + sweepRateMin
|
||||||
|
return Phaser.Audio(
|
||||||
|
input: base,
|
||||||
|
rate: sweepRate,
|
||||||
|
depth: sweepDepth,
|
||||||
|
centerFreq: sweepCenterFreq,
|
||||||
|
feedback: sweepFeedback,
|
||||||
|
stages: sweepStages,
|
||||||
|
mix: sweepInternalMix,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Lo-Res: a down-sampled, gritty lo-fi delay.
|
||||||
|
private func makeLoRes(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let fb: DelayLineFeedback = feedbackDelay(input: dry, delay: $time)
|
||||||
|
let crushed: SampleRateDecimate = SampleRateDecimate(input: fb, downsample: loResDownsample)
|
||||||
|
return toned(crushed, cutoff: $tone * loResToneScale)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Reverse: backward echo segments at the current Time, with Repeats mapped to the reverse-trail
|
||||||
|
/// feedback factor.
|
||||||
|
private func makeReverse(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
let revFeedback: Clip.Audio = Clip.Audio(
|
||||||
|
$repeats * reverseFeedbackScale,
|
||||||
|
lo: 0.0,
|
||||||
|
hi: reverseFeedbackMax
|
||||||
|
)
|
||||||
|
let rev: ReverseDelay = ReverseDelay(
|
||||||
|
input: dry,
|
||||||
|
maxDelay: maxDelayTime,
|
||||||
|
delay: $time,
|
||||||
|
feedback: revFeedback,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
return toned(rev, cutoff: $tone)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,208 @@
|
|||||||
|
// GranularReverbPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Granular-cloud reverb — a diffuse, blooming wash built from a cloud of pitch-scattered grains,
|
||||||
|
/// then reverberated.
|
||||||
|
///
|
||||||
|
/// The dry signal feeds an `InputGrain` cloud: short grains are sprayed from a rolling capture of
|
||||||
|
/// the input at a chosen `density`, each smeared slightly in time and given a random pitch offset
|
||||||
|
/// (`scatter`) around a center `pitch`. That cloud then drives a `GVerb` room tank, folded
|
||||||
|
/// stereo→mono, so the grains bloom into a reverberant pad.
|
||||||
|
///
|
||||||
|
/// This is deliberately **unlike** the ``ShimmerReverbPedal``: Shimmer is a tuned feedback tank
|
||||||
|
/// regenerating a clean, coherent octave-up tail; this is an incoherent grain cloud whose defining
|
||||||
|
/// control is the **random** per-grain pitch `scatter`. At `pitch = 0, scatter = 0` the cloud
|
||||||
|
/// tracks the input's pitch; raising `scatter` smears it into a broadband haze — a grain cloud, not
|
||||||
|
/// an ascending shimmer. Set `pitch` for a tuned (e.g. octave-up) cloud, or leave it at `0` for an
|
||||||
|
/// untuned ambient bloom.
|
||||||
|
///
|
||||||
|
/// The base `Pedal` `mix` sets the wet/dry blend.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`.
|
||||||
|
/// - `density`: Grain cloud density in grains per second. Range `[5, 80]`.
|
||||||
|
/// - `grain`: Grain duration in seconds. Range `[0.02, 0.3]`.
|
||||||
|
/// - `pitch`: Cloud center pitch in semitones. Range `[-24, 24]`; `0` = unpitched (tracks input).
|
||||||
|
/// - `scatter`: Random per-grain pitch spread (± ratio around center). Range `[0, 0.5]`.
|
||||||
|
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
|
||||||
|
public final class GranularReverbPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"A cloud of pitch-scattered grains blooming into reverb — a diffuse, incoherent wash."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// GVerb reverb time (T60) in seconds. Range [0.2, 12.0].
|
||||||
|
@UIParam public var decay: Double = 4.0
|
||||||
|
|
||||||
|
/// Grain cloud density in grains per second. Range [5, 80].
|
||||||
|
@UIParam public var density: Double = 25.0
|
||||||
|
|
||||||
|
/// Grain duration in seconds. Range [0.02, 0.3].
|
||||||
|
@UIParam public var grain: Double = 0.12
|
||||||
|
|
||||||
|
/// Cloud center pitch in semitones. Range [-24, 24]; 0 = unpitched (tracks input).
|
||||||
|
@UIParam public var pitch: Double = 0.0
|
||||||
|
|
||||||
|
/// Random per-grain pitch spread, as a fraction of the center ratio (`0.5` = ±50% of the shifted
|
||||||
|
/// speed), added bipolar per grain. Range [0, 0.5]. Scaling by the center keeps the spread
|
||||||
|
/// proportional, so a down-shifted cloud doesn't send grains to a negative (reverse) ratio. The
|
||||||
|
/// defining control — higher = more smeared and incoherent.
|
||||||
|
@UIParam public var scatter: Double = 0.15
|
||||||
|
|
||||||
|
/// High-frequency damping in [0, 1]. Higher = darker tail.
|
||||||
|
@UIParam public var damp: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — the cloud wash sits under the dry note.
|
||||||
|
private static let defaultMix: Double = 0.4
|
||||||
|
|
||||||
|
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio` to turn
|
||||||
|
/// the `pitch` knob into a `pitchRatio` for the grain cloud.
|
||||||
|
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
|
||||||
|
|
||||||
|
/// Grain read position in the rolling capture, `[0, 1]` (0 = newest). Slightly into the past so
|
||||||
|
/// each grain has recorded material to read even at the lowest density.
|
||||||
|
private let cloudPosition: Double = 0.1
|
||||||
|
|
||||||
|
/// Random spread applied to the read position per grain — a small time smear that keeps the
|
||||||
|
/// cloud diffuse rather than a tight repeat.
|
||||||
|
private let cloudPositionSpread: Double = 0.1
|
||||||
|
|
||||||
|
/// Reference output gain on the grain cloud before the tank, applied after density
|
||||||
|
/// normalisation (see ``effect(_:)``). `InputGrain` sums every active grain, so the raw cloud
|
||||||
|
/// level scales with the grain overlap (`density · grain`); without normalisation the extremes
|
||||||
|
/// of those knobs (and correlated grains at low scatter) could sum to several times the input
|
||||||
|
/// and clip. The cloud is divided by `sqrt(overlap)` (power normalisation), so turning density
|
||||||
|
/// up thickens the texture at a roughly constant level instead of raising the peak toward
|
||||||
|
/// clipping.
|
||||||
|
private let cloudGain: Double = 0.5
|
||||||
|
|
||||||
|
/// Lower bound on the overlap estimate (`density · grain`) before the `sqrt` normalisation, so a
|
||||||
|
/// sparse cloud (overlap < 1) is not boosted by dividing by a fraction.
|
||||||
|
private let minOverlap: Double = 1.0
|
||||||
|
|
||||||
|
/// Fixed PRNG seed for the grain scheduling and pitch scatter, so a given setting renders
|
||||||
|
/// identically every time (reproducible audio and tests).
|
||||||
|
private let cloudSeed: UInt64 = 0x3C6E_F372_FE94_F82B
|
||||||
|
|
||||||
|
/// GVerb room size in metres (fixed; the grain/reverb controls shape the character instead).
|
||||||
|
private let roomSizeMeters: Double = 40.0
|
||||||
|
|
||||||
|
/// GVerb early-reflection level. Low, so the wash favours the diffuse grain tail over discrete
|
||||||
|
/// reflections.
|
||||||
|
private let reverbEarlyLevel: Double = 0.2
|
||||||
|
|
||||||
|
/// GVerb late-reverb (tail) level.
|
||||||
|
private let reverbTailLevel: Double = 0.6
|
||||||
|
|
||||||
|
/// GVerb dry level — how much of the grain cloud passes through the tank's dry path, keeping the
|
||||||
|
/// grain texture itself present under its reverb.
|
||||||
|
private let reverbDryLevel: Double = 0.3
|
||||||
|
|
||||||
|
/// Gain folding a decorrelated stereo pair to mono. A conservative trim leaving output headroom.
|
||||||
|
private let stereoSumGain: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let decayRange: ClosedRange<Double> = 0.2 ... 12.0
|
||||||
|
private let densityRange: ClosedRange<Double> = 5.0 ... 80.0
|
||||||
|
private let grainRange: ClosedRange<Double> = 0.02 ... 0.3
|
||||||
|
private let pitchRange: ClosedRange<Double> = -24.0 ... 24.0
|
||||||
|
private let scatterRange: ClosedRange<Double> = 0.0 ... 0.5
|
||||||
|
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Decay", node: $decay, range: decayRange),
|
||||||
|
PedalKnob(label: "Density", node: $density, range: densityRange),
|
||||||
|
PedalKnob(label: "Grain", node: $grain, range: grainRange),
|
||||||
|
PedalKnob(label: "Pitch", node: $pitch, range: pitchRange),
|
||||||
|
PedalKnob(label: "Scatter", node: $scatter, range: scatterRange),
|
||||||
|
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a granular-reverb pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Granular Reverb",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: GranularReverbPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Center pitch (semitones → ratio); per-grain scatter is added bipolar around it inside
|
||||||
|
// InputGrain.
|
||||||
|
let centerRatio: Exp.Audio = Exp.Audio($pitch * semitoneToRatioScale)
|
||||||
|
|
||||||
|
// Density normalisation: divide the cloud by sqrt(grain overlap = density·grain), clamped so
|
||||||
|
// a sparse cloud isn't boosted. Keeps the level roughly constant across the density/grain
|
||||||
|
// knobs and bounds the peak away from clipping even with correlated grains at low scatter.
|
||||||
|
let overlap: any ValidGeneratorInput = Max.Audio($density * $grain, minOverlap)
|
||||||
|
let cloudNormGain: any ValidGeneratorInput = Reciprocal.Audio(Sqrt.Audio(overlap)) * cloudGain
|
||||||
|
|
||||||
|
// Scatter scaled by the center ratio, so the per-grain spread is proportional (±scatter of
|
||||||
|
// the shifted speed). This keeps a down-shifted cloud off a negative/reverse ratio, which an
|
||||||
|
// absolute offset would reach at low pitch + high scatter.
|
||||||
|
let scaledScatter: any ValidGeneratorInput = centerRatio * $scatter
|
||||||
|
|
||||||
|
// The grain cloud (native stereo via per-grain pan).
|
||||||
|
let cloud: InputGrain = InputGrain(
|
||||||
|
input: dry,
|
||||||
|
position: cloudPosition,
|
||||||
|
positionSpread: cloudPositionSpread,
|
||||||
|
duration: $grain,
|
||||||
|
pitchRatio: centerRatio,
|
||||||
|
pitchDispersion: scaledScatter,
|
||||||
|
density: $density,
|
||||||
|
seed: cloudSeed,
|
||||||
|
mul: cloudNormGain
|
||||||
|
)
|
||||||
|
// Fold the cloud to mono for the tank source.
|
||||||
|
let cloudMono: SumChannels.Audio = SumChannels.Audio(
|
||||||
|
input: cloud,
|
||||||
|
mul: stereoSumGain
|
||||||
|
)
|
||||||
|
// Reverberate the cloud (native stereo); `dryLevel` keeps the grain texture present.
|
||||||
|
let stereoVerb: GVerb.Audio = GVerb.Audio(
|
||||||
|
source: cloudMono,
|
||||||
|
roomSize: roomSizeMeters,
|
||||||
|
reverbTime: $decay,
|
||||||
|
damping: $damp,
|
||||||
|
earlyLevel: reverbEarlyLevel,
|
||||||
|
tailLevel: reverbTailLevel,
|
||||||
|
dryLevel: reverbDryLevel,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
// Fold the reverb output stereo → mono.
|
||||||
|
return SumChannels.Audio(
|
||||||
|
input: stereoVerb,
|
||||||
|
mul: stereoSumGain
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,345 @@
|
|||||||
|
// KarplusResonatorPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Sympathetic-string resonator — a bank of tuned Karplus-Strong strings the guitar excites.
|
||||||
|
///
|
||||||
|
/// A sitar's or a sarangi's sympathetic strings are always coupled to the played note: pluck, and
|
||||||
|
/// a fixed set of tuned strings sing along, ringing on after each note. This pedal models that with
|
||||||
|
/// four `KarplusStrong` strings tuned to a chord above a **Tune** root. An amplitude envelope of
|
||||||
|
/// your playing drives a Schmitt gate whose rising edge plucks the whole bank — capturing the loud
|
||||||
|
/// note onset — and the strings then ring on at their own tuned pitches with their own decay: the
|
||||||
|
/// sympathetic shimmer blooming out of the note's tail.
|
||||||
|
///
|
||||||
|
/// Distinct from a reverb or a delay: the tails are **pitched** to the Tune root's chord, not a
|
||||||
|
/// diffuse wash or a repeat of what you played. Distinct from the ``PolyOctavePedal`` (which pitch-
|
||||||
|
/// shifts your note in real time): here the resonators have their own fixed tuning and their own
|
||||||
|
/// decay, so holding a drone root under a moving line is the whole point.
|
||||||
|
///
|
||||||
|
/// Wraps Lyrebird's `KarplusStrong` run fully wet; the base `Pedal` `mix` sets the blend of the
|
||||||
|
/// ringing bank against the dry note (an even mix by default).
|
||||||
|
///
|
||||||
|
/// The root can be set two ways, chosen by the **Tuning** switch: **Free** sweeps the continuous
|
||||||
|
/// **Tune** Hz knob; **Pitched** tunes the root to a musical note chosen with a single **Root**
|
||||||
|
/// selector that steps through every semitone from E1 up to E5 (the top of the treble staff),
|
||||||
|
/// captioned by name and octave (`E1`, `A3`, `E5`) in equal temperament (A4 = 440 Hz, so A3 = 220).
|
||||||
|
/// In **Pitched** the Tune Hz knob is ignored; in **Free** the Root selector is hidden.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `tune`: Root frequency of the string bank in Hz (used in **Free** tuning). Range `[40, 660]`
|
||||||
|
/// (up to E5, the top of the treble staff).
|
||||||
|
/// - `sustain`: Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`.
|
||||||
|
/// - `tone`: Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic.
|
||||||
|
/// - `sensitivity`: How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger
|
||||||
|
/// threshold, so quieter notes still excite the bank.
|
||||||
|
///
|
||||||
|
/// ## Switch
|
||||||
|
/// - `tuning`: Root source — **Free** (the Tune Hz knob) or **Pitched** (the Root selector). Rebuilds.
|
||||||
|
///
|
||||||
|
/// ## Selectors (all rebuild on change)
|
||||||
|
/// - `voicing`: Chord the four strings are tuned to: Drone, Octaves, Shimmer.
|
||||||
|
/// - `pitchedNote`: Root note in **Pitched** tuning — a chromatic stop from E1 to E5 (shown only in
|
||||||
|
/// **Pitched** mode). The value is the MIDI note number; A3 (MIDI 57) = 220 Hz.
|
||||||
|
public final class KarplusResonatorPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"A bank of tuned strings that ring along with your note — sympathetic sitar shimmer."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Root frequency of the string bank in Hz (Free tuning). Range `[40, 660]` — up to E5.
|
||||||
|
@UIParam public var tune: Double = 82.41
|
||||||
|
|
||||||
|
/// Ring length — the string feedback. Range `[0, 1]` → feedback `[0.9, 0.999]`.
|
||||||
|
@UIParam public var sustain: Double = 0.7
|
||||||
|
|
||||||
|
/// Brightness of the strings. Range `[0, 1]`: `0` = dark/woody, `1` = bright/metallic.
|
||||||
|
@UIParam public var tone: Double = 0.4
|
||||||
|
|
||||||
|
/// How readily playing plucks the strings. Range `[0, 1]`: higher = lower trigger threshold.
|
||||||
|
@UIParam public var sensitivity: Double = 0.5
|
||||||
|
|
||||||
|
/// Selected voicing index into ``voicings``. A knob-picker selector; rebuilds on change.
|
||||||
|
@UIParam public var voicing: Double = 0.0
|
||||||
|
|
||||||
|
/// Root-tuning source: `0` = Free (the Tune Hz knob), `1` = Pitched (the Root selector). A
|
||||||
|
/// two-position switch; rebuilds on change.
|
||||||
|
@UIParam public var tuning: Double = 0.0
|
||||||
|
|
||||||
|
/// Root note in Pitched tuning, as a MIDI note number. A chromatic selector stepping E1 (MIDI 28)
|
||||||
|
/// to E5 (MIDI 76); rebuilds on change. Defaults to A3 (MIDI 57) = 220 Hz.
|
||||||
|
@UIParam public var pitchedNote: Double = 57.0 // A3 = 220 Hz by default
|
||||||
|
|
||||||
|
// MARK: - Voicings
|
||||||
|
|
||||||
|
/// A named chord the four strings are tuned to, as frequency ratios of the Tune root.
|
||||||
|
private struct Voicing {
|
||||||
|
let title: String
|
||||||
|
let ratios: [Double]
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fixed string tunings. Each has exactly ``stringCount`` ratios of the Tune root.
|
||||||
|
/// - Drone: root, fifth, octave, octave+fifth — the classic sympathetic drone.
|
||||||
|
/// - Octaves: two octaves down through two up — a wide octave stack.
|
||||||
|
/// - Shimmer: two octave pairs detuned a few cents apart — slow beating for a chorused ring.
|
||||||
|
private static let voicings: [Voicing] = [
|
||||||
|
Voicing(title: "Drone", ratios: [1.0, 1.5, 2.0, 3.0]),
|
||||||
|
Voicing(title: "Octaves", ratios: [0.5, 1.0, 2.0, 4.0]),
|
||||||
|
Voicing(title: "Shimmer", ratios: [1.0, 1.005, 2.0, 1.99]),
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Number of strings in the bank — fixed, so the delay-line allocation is structural.
|
||||||
|
private static let stringCount: Int = 4
|
||||||
|
|
||||||
|
// MARK: - Note tuning
|
||||||
|
|
||||||
|
/// Tuning-source values written by the ``tuning`` switch.
|
||||||
|
private static let tuningFreeValue: Double = 0.0
|
||||||
|
private static let tuningPitchedValue: Double = 1.0
|
||||||
|
|
||||||
|
/// Pitch-class captions, index `0 … 11` (C … B).
|
||||||
|
private static let pitchClassNames: [String] = [
|
||||||
|
"C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
|
||||||
|
]
|
||||||
|
|
||||||
|
/// Equal-temperament reference: A4 = 440 Hz is MIDI note 69, 12 semitones per octave.
|
||||||
|
private static let referenceFrequency: Double = 440.0
|
||||||
|
private static let referenceMidiNote: Int = 69
|
||||||
|
private static let semitonesPerOctave: Int = 12
|
||||||
|
|
||||||
|
/// Lowest Pitched root — E1 (MIDI 28, ≈ 41 Hz), a low bass E mirroring the Free knob's floor.
|
||||||
|
private static let lowestMidiNote: Int = 28
|
||||||
|
/// Highest Pitched root — E5 (MIDI 76, ≈ 659 Hz), the top space of the treble staff.
|
||||||
|
private static let highestMidiNote: Int = 76
|
||||||
|
|
||||||
|
/// Equal-tempered frequency in Hz for a MIDI note number, using A4 = 440 Hz (MIDI 69). A3
|
||||||
|
/// (MIDI 57) → 220 Hz; C4 (middle C, MIDI 60) → 261.63 Hz.
|
||||||
|
///
|
||||||
|
/// - Parameter midi: MIDI note number.
|
||||||
|
/// - Returns: The note's frequency in Hz.
|
||||||
|
static func frequency(forMidiNote midi: Int) -> Double {
|
||||||
|
let semitonesFromReference: Double = Double(midi - referenceMidiNote) / Double(semitonesPerOctave)
|
||||||
|
return referenceFrequency * pow(2.0, semitonesFromReference)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Name-plus-octave caption for a MIDI note number in scientific-pitch convention (MIDI 60 = C4),
|
||||||
|
/// e.g. MIDI 57 → `"A3"`, MIDI 76 → `"E5"`.
|
||||||
|
///
|
||||||
|
/// - Parameter midi: MIDI note number (expected `lowestMidiNote … highestMidiNote`).
|
||||||
|
/// - Returns: The note's caption.
|
||||||
|
static func caption(forMidiNote midi: Int) -> String {
|
||||||
|
let pitchClass: Int = ((midi % semitonesPerOctave) + semitonesPerOctave) % semitonesPerOctave
|
||||||
|
let octaveNumber: Int = midi / semitonesPerOctave - 1
|
||||||
|
return pitchClassNames[pitchClass] + String(octaveNumber)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Pedal returns the bank fully wet; the base `mix` blends it against the dry note. An even mix
|
||||||
|
/// so the sympathetic ring sits under the dry signal rather than replacing it.
|
||||||
|
private static let defaultMix: Double = 0.5
|
||||||
|
|
||||||
|
/// Maximum delay time for each string, in seconds — sizes the Karplus delay line. Covers the
|
||||||
|
/// lowest resonator across both tuning modes: the lowest root is ≈ 40 Hz (Free floor, or the
|
||||||
|
/// Pitched E1 ≈ 41 Hz), and the Octaves voicing drops a string a full octave below that
|
||||||
|
/// (ratio 0.5 → ≈ 20 Hz, a ~0.05 s period), so `0.08 s` leaves margin. `KarplusStrong` clamps any lower
|
||||||
|
/// frequency to the line length anyway.
|
||||||
|
private let maxStringDelayTime: Double = 0.08
|
||||||
|
|
||||||
|
/// Feedback (ring length) mapped from `sustain = 0`: a short, plucky decay.
|
||||||
|
private let feedbackMin: Double = 0.9
|
||||||
|
|
||||||
|
/// Feedback mapped from `sustain = 1`: a very long, near-infinite ring. Kept just under `1.0`
|
||||||
|
/// so the bank always decays rather than running away.
|
||||||
|
private let feedbackMax: Double = 0.999
|
||||||
|
|
||||||
|
/// One-pole coefficient mapped from `tone = 0`: classic Karplus averaging — dark and woody.
|
||||||
|
private let coefDark: Double = 0.5
|
||||||
|
|
||||||
|
/// One-pole coefficient mapped from `tone = 1`: negative, for a bright, metallic sitar-like
|
||||||
|
/// timbre. Kept well inside `|coef| < 1` so the feedback path never grows.
|
||||||
|
private let coefBright: Double = -0.2
|
||||||
|
|
||||||
|
/// Schmitt switch-on threshold on the input envelope at `sensitivity = 0` — the least sensitive
|
||||||
|
/// setting, where only loud notes feed the strings.
|
||||||
|
private let gateHiThresholdLow: Double = 0.25
|
||||||
|
|
||||||
|
/// Schmitt switch-on threshold at `sensitivity = 1` — the most sensitive setting, where even
|
||||||
|
/// quiet notes feed the strings.
|
||||||
|
private let gateHiThresholdHigh: Double = 0.01
|
||||||
|
|
||||||
|
/// Fraction of the switch-on threshold used for the switch-off threshold, giving the gate
|
||||||
|
/// hysteresis so it doesn't chatter around a single level.
|
||||||
|
private let gateLoFactor: Double = 0.5
|
||||||
|
|
||||||
|
/// Envelope-follower attack for the gate detector, in seconds — fast, to catch note onsets.
|
||||||
|
private let envAttackTime: Double = 0.005
|
||||||
|
|
||||||
|
/// Envelope-follower release for the gate detector, in seconds — slow enough that the gate holds
|
||||||
|
/// through a note and only drops once it has genuinely decayed, at which point the bank rings.
|
||||||
|
private let envReleaseTime: Double = 0.08
|
||||||
|
|
||||||
|
/// Output scale on the summed four-string bank — `1/stringCount`, the fully-coherent-sum bound.
|
||||||
|
/// The Octaves and Shimmer voicings share string periods, so a full-scale pluck can momentarily
|
||||||
|
/// align all four; this ceiling keeps the summed bank at or below the dry peak with no limiter.
|
||||||
|
private let bankGain: Double = 0.25
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
/// Free-mode root range in Hz. Upper bound reaches E5 (≈ 659 Hz, the top of the treble staff);
|
||||||
|
/// lower bound sits around a low bass E.
|
||||||
|
private let tuneRange: ClosedRange<Double> = 40.0 ... 660.0
|
||||||
|
private let unitRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Tune", node: $tune, range: tuneRange),
|
||||||
|
PedalKnob(label: "Sustain", node: $sustain, range: unitRange),
|
||||||
|
PedalKnob(label: "Tone", node: $tone, range: unitRange),
|
||||||
|
PedalKnob(label: "Sensitivity", node: $sensitivity, range: unitRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Switch
|
||||||
|
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
// Picks the root source. Rebuilds: it swaps the build-time root (live Tune knob vs a fixed
|
||||||
|
// note Hz) and toggles whether the Root selector is shown.
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Tuning",
|
||||||
|
node: $tuning,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Free", value: KarplusResonatorPedal.tuningFreeValue),
|
||||||
|
PedalSwitch.Option(title: "Pitched", value: KarplusResonatorPedal.tuningPitchedValue),
|
||||||
|
],
|
||||||
|
rebuildsOnChange: true
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Selectors
|
||||||
|
|
||||||
|
public override var effectSelectors: [PedalSelectorKnob] {
|
||||||
|
let voicingStops: [PedalSelectorKnob.Stop] = KarplusResonatorPedal.voicings.enumerated().map { index, voicing in
|
||||||
|
PedalSelectorKnob.Stop(title: voicing.title, value: Double(index))
|
||||||
|
}
|
||||||
|
// Voicing always shows and stays at selector index 0 — so a preset's positional selector
|
||||||
|
// values line up regardless of tuning mode. The Root selector is appended only in Pitched
|
||||||
|
// mode (and `tuning` is restored in the switch pass before this one, so the count matches).
|
||||||
|
var selectors: [PedalSelectorKnob] = [
|
||||||
|
// Voicing ratios size each string's delay line, so it is a build-time structural choice.
|
||||||
|
PedalSelectorKnob(label: "Voicing", node: $voicing, stops: voicingStops, rebuildsOnChange: true),
|
||||||
|
]
|
||||||
|
if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) {
|
||||||
|
let rootStops: [PedalSelectorKnob.Stop] =
|
||||||
|
(KarplusResonatorPedal.lowestMidiNote ... KarplusResonatorPedal.highestMidiNote).map { midi in
|
||||||
|
PedalSelectorKnob.Stop(title: KarplusResonatorPedal.caption(forMidiNote: midi), value: Double(midi))
|
||||||
|
}
|
||||||
|
// The chosen note sets a fixed root Hz folded into the graph at build time, so it rebuilds.
|
||||||
|
selectors.append(
|
||||||
|
PedalSelectorKnob(label: "Root", node: $pitchedNote, stops: rootStops, rebuildsOnChange: true)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
return selectors
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a Karplus-Strong sympathetic-resonator pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Karplus Resonator",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: KarplusResonatorPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// `voicing` is read as a plain value at build time; the board rebuilds when it changes (the
|
||||||
|
// ratios size each string's delay line). All other controls stay live.
|
||||||
|
let index: Int = min(max(0, Int(voicing.rounded())), KarplusResonatorPedal.voicings.count - 1)
|
||||||
|
let ratios: [Double] = KarplusResonatorPedal.voicings[index].ratios
|
||||||
|
|
||||||
|
// Root source (read at build time, so switching rebuilds). Free: the live Tune Hz knob.
|
||||||
|
// Pitched: a fixed equal-tempered frequency from the Root note selector.
|
||||||
|
let rootFreq: any ValidGeneratorInput
|
||||||
|
if Int(tuning.rounded()) == Int(KarplusResonatorPedal.tuningPitchedValue) {
|
||||||
|
let midiNote: Int = min(
|
||||||
|
max(KarplusResonatorPedal.lowestMidiNote, Int(pitchedNote.rounded())),
|
||||||
|
KarplusResonatorPedal.highestMidiNote
|
||||||
|
)
|
||||||
|
rootFreq = KarplusResonatorPedal.frequency(forMidiNote: midiNote)
|
||||||
|
} else {
|
||||||
|
rootFreq = $tune
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pluck trigger: track the input envelope, then a Schmitt trigger turns it into a 0/1 play
|
||||||
|
// detector. Its rising edge (you start a note) plucks the whole bank — Karplus fills each
|
||||||
|
// delay line from the loud onset — and the strings then ring on at their tuned pitches. The
|
||||||
|
// hysteresis means the gate must fall back below the off-threshold before the next note can
|
||||||
|
// re-pluck, so a single sustained note plucks once rather than chattering.
|
||||||
|
let env: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||||
|
in: dry,
|
||||||
|
attackTime: envAttackTime,
|
||||||
|
releaseTime: envReleaseTime
|
||||||
|
)
|
||||||
|
// sensitivity [0, 1] → switch-on threshold [gateHiThresholdLow, gateHiThresholdHigh]
|
||||||
|
// (higher sensitivity = lower threshold); switch-off threshold is a fixed fraction below it.
|
||||||
|
let hiSpan: Double = gateHiThresholdHigh - gateHiThresholdLow
|
||||||
|
let hiThreshold: any ValidGeneratorInput = ($sensitivity * hiSpan) + gateHiThresholdLow
|
||||||
|
let loThreshold: any ValidGeneratorInput = hiThreshold * gateLoFactor
|
||||||
|
let trigger: Schmidt.Audio = Schmidt.Audio(input: env, lo: loThreshold, hi: hiThreshold)
|
||||||
|
|
||||||
|
// sustain [0, 1] → feedback [feedbackMin, feedbackMax]; tone [0, 1] → coef [coefDark, coefBright].
|
||||||
|
let feedbackSpan: Double = feedbackMax - feedbackMin
|
||||||
|
let voicedFeedback: any ValidGeneratorInput = ($sustain * feedbackSpan) + feedbackMin
|
||||||
|
let coefSpan: Double = coefBright - coefDark
|
||||||
|
let voicedCoef: any ValidGeneratorInput = ($tone * coefSpan) + coefDark
|
||||||
|
|
||||||
|
// Four tuned strings, each a KarplusStrong plucked by the shared trigger from the dry onset.
|
||||||
|
var bank: any ValidGeneratorInput = KarplusStrong.Audio(
|
||||||
|
exciter: dry,
|
||||||
|
trigger: trigger,
|
||||||
|
freq: rootFreq * ratios[0],
|
||||||
|
feedback: voicedFeedback,
|
||||||
|
coef: voicedCoef,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
maxDelayTime: maxStringDelayTime
|
||||||
|
)
|
||||||
|
for stringIndex: Int in 1 ..< KarplusResonatorPedal.stringCount {
|
||||||
|
let string: KarplusStrong.Audio = KarplusStrong.Audio(
|
||||||
|
exciter: dry,
|
||||||
|
trigger: trigger,
|
||||||
|
freq: rootFreq * ratios[stringIndex],
|
||||||
|
feedback: voicedFeedback,
|
||||||
|
coef: voicedCoef,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
maxDelayTime: maxStringDelayTime
|
||||||
|
)
|
||||||
|
bank = bank + string
|
||||||
|
}
|
||||||
|
|
||||||
|
return bank * bankGain
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -17,6 +17,13 @@ import LyrebirdUI
|
|||||||
/// keeps every filter state warmed so switch changes are click-free (SuperCollider
|
/// keeps every filter state warmed so switch changes are click-free (SuperCollider
|
||||||
/// `Select` semantics: every input advances each block).
|
/// `Select` semantics: every input advances each block).
|
||||||
///
|
///
|
||||||
|
/// The cutoff sweeps exponentially from a resting frequency (`freqLo`) up to a peak
|
||||||
|
/// (`freqHi`) as the envelope opens: `cutoff = freqLo·(freqHi/freqLo)^envelope`. The
|
||||||
|
/// **Range** switch shifts that whole window low (rhythm / bass) or high (harmonics /
|
||||||
|
/// solos), matching the original pedal; the **Sweep** knob sets how far above the resting
|
||||||
|
/// frequency the envelope drives the cutoff (its "openness"), and **Attack** / **Release**
|
||||||
|
/// shape how quickly the filter follows the input dynamics.
|
||||||
|
///
|
||||||
/// ## Knobs
|
/// ## Knobs
|
||||||
/// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes.
|
/// - `sensitivity`: Drive into the envelope follower; higher values open the filter on quieter notes.
|
||||||
/// - `resonance`: Filter peak emphasis at the swept cutoff.
|
/// - `resonance`: Filter peak emphasis at the swept cutoff.
|
||||||
@@ -24,6 +31,12 @@ import LyrebirdUI
|
|||||||
/// ## Switches
|
/// ## Switches
|
||||||
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
|
/// - `direction` (two-state): `0` = Down (louder closes the filter), `1` = Up (louder opens it).
|
||||||
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
|
/// - `mode` (three-state): `0` = lowpass, `1` = bandpass (classic vowel wah), `2` = highpass.
|
||||||
|
/// - `range` (two-state): `0` = Low band (rhythm / bass), `1` = High band (harmonics / solos).
|
||||||
|
///
|
||||||
|
/// ## Advanced
|
||||||
|
/// - `sweep`: How far the envelope drives the cutoff above its resting frequency (peak = resting × sweep).
|
||||||
|
/// - `attack`: Envelope attack time in seconds — how fast the filter opens on a transient.
|
||||||
|
/// - `release`: Envelope release time in seconds — how fast it closes after a note.
|
||||||
public final class MutantPedal: Pedal {
|
public final class MutantPedal: Pedal {
|
||||||
|
|
||||||
/// One-line description shown in the picker and info panel.
|
/// One-line description shown in the picker and info panel.
|
||||||
@@ -45,19 +58,29 @@ public final class MutantPedal: Pedal {
|
|||||||
/// Filter resonance (Chamberlin SVF peak emphasis). Clamped to `≥ 1.0` internally.
|
/// Filter resonance (Chamberlin SVF peak emphasis). Clamped to `≥ 1.0` internally.
|
||||||
@UIParam public var resonance: Double = 4.0
|
@UIParam public var resonance: Double = 4.0
|
||||||
|
|
||||||
|
/// Frequency-band selector. `0` = Low band, `1` = High band. Shifts the resting cutoff (and with
|
||||||
|
/// it the whole sweep window) up or down. Driven by a two-state switch.
|
||||||
|
@UIParam public var range: Double = 0.0
|
||||||
|
|
||||||
|
/// Sweep amount: the peak cutoff is `restingCutoff × sweep`, so higher values open the filter
|
||||||
|
/// further as the input drives it. Advanced knob.
|
||||||
|
@UIParam public var sweep: Double = 20.0
|
||||||
|
|
||||||
|
/// Envelope attack time in seconds — how fast the filter opens on a transient. Advanced knob.
|
||||||
|
@UIParam public var attack: Double = 0.008
|
||||||
|
|
||||||
|
/// Envelope release time in seconds — how fast the filter closes after a note. Advanced knob.
|
||||||
|
@UIParam public var release: Double = 0.14
|
||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
|
|
||||||
private static let defaultMix: Double = 1.0
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
/// Cutoff at zero envelope, in Hz.
|
/// Resting cutoff (in Hz) at `range == Low`.
|
||||||
private let freqLo: Double = 80.0
|
private let rangeLowBaseFreq: Double = 120.0
|
||||||
|
|
||||||
/// Cutoff at maximum envelope, in Hz (≈40× sweep over `freqLo`).
|
/// Resting cutoff (in Hz) at `range == High`.
|
||||||
private let freqHi: Double = 3200.0
|
private let rangeHighBaseFreq: Double = 380.0
|
||||||
|
|
||||||
/// Envelope attack/release times, in seconds.
|
|
||||||
private let attackTime: Double = 0.005
|
|
||||||
private let releaseTime: Double = 0.15
|
|
||||||
|
|
||||||
/// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a
|
/// Half-step bias added before each `Select`'s truncate-toward-zero index, turning a
|
||||||
/// switch parameter into a round-to-nearest position selector.
|
/// switch parameter into a round-to-nearest position selector.
|
||||||
@@ -69,11 +92,17 @@ public final class MutantPedal: Pedal {
|
|||||||
private let modeHighpassValue: Double = 2.0
|
private let modeHighpassValue: Double = 2.0
|
||||||
private let directionDownValue: Double = 0.0
|
private let directionDownValue: Double = 0.0
|
||||||
private let directionUpValue: Double = 1.0
|
private let directionUpValue: Double = 1.0
|
||||||
|
private let rangeLowValue: Double = 0.0
|
||||||
|
private let rangeHighValue: Double = 1.0
|
||||||
|
|
||||||
// MARK: - Ranges
|
// MARK: - Ranges
|
||||||
|
|
||||||
private let sensitivityRange: ClosedRange<Double> = 0.0 ... 4.0
|
private let sensitivityRange: ClosedRange<Double> = 0.0 ... 4.0
|
||||||
private let resonanceRange: ClosedRange<Double> = 1.0 ... 12.0
|
private let resonanceRange: ClosedRange<Double> = 1.0 ... 12.0
|
||||||
|
/// Sweep multiplier: peak cutoff = resting × sweep. `1` = no sweep; `50` ≈ 5.6 octaves.
|
||||||
|
private let sweepRange: ClosedRange<Double> = 1.0 ... 50.0
|
||||||
|
private let attackRange: ClosedRange<Double> = 0.001 ... 0.08
|
||||||
|
private let releaseRange: ClosedRange<Double> = 0.02 ... 0.6
|
||||||
|
|
||||||
// MARK: - Knobs
|
// MARK: - Knobs
|
||||||
|
|
||||||
@@ -84,12 +113,20 @@ public final class MutantPedal: Pedal {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public override var advancedKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Sweep", node: $sweep, range: sweepRange),
|
||||||
|
PedalKnob(label: "Attack", node: $attack, range: attackRange),
|
||||||
|
PedalKnob(label: "Release", node: $release, range: releaseRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Switches
|
// MARK: - Switches
|
||||||
|
|
||||||
public override var effectSwitches: [PedalSwitch] {
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
[
|
[
|
||||||
PedalSwitch(
|
PedalSwitch(
|
||||||
label: "Sweep",
|
label: "Direction",
|
||||||
node: $direction,
|
node: $direction,
|
||||||
options: [
|
options: [
|
||||||
PedalSwitch.Option(title: "Down", value: directionDownValue),
|
PedalSwitch.Option(title: "Down", value: directionDownValue),
|
||||||
@@ -105,9 +142,22 @@ public final class MutantPedal: Pedal {
|
|||||||
PedalSwitch.Option(title: "HP", value: modeHighpassValue),
|
PedalSwitch.Option(title: "HP", value: modeHighpassValue),
|
||||||
]
|
]
|
||||||
),
|
),
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Range",
|
||||||
|
node: $range,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Lo", value: rangeLowValue),
|
||||||
|
PedalSwitch.Option(title: "Hi", value: rangeHighValue),
|
||||||
|
]
|
||||||
|
),
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Double-width so the three segmented switches (Direction / Mode / Range — seven segments in
|
||||||
|
/// all) have room for their captions instead of wrapping ("Do wn"), the same reason the Cabinet
|
||||||
|
/// and amp pedals are double-width.
|
||||||
|
public override var widthUnits: Int { 2 }
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
|
|
||||||
public init(inputBus: Int = 0, outputBus: Int = 0) {
|
public init(inputBus: Int = 0, outputBus: Int = 0) {
|
||||||
@@ -122,23 +172,29 @@ public final class MutantPedal: Pedal {
|
|||||||
// MARK: - Effect
|
// MARK: - Effect
|
||||||
|
|
||||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Resting cutoff shifts with the Range switch (Low band vs High band); the peak the envelope
|
||||||
|
// reaches is `restingCutoff × sweep`. Both feed all six warmed filters (fan-out).
|
||||||
|
let restingFreq: any ValidGeneratorInput =
|
||||||
|
$range * (rangeHighBaseFreq - rangeLowBaseFreq) + rangeLowBaseFreq
|
||||||
|
let peakFreq: any ValidGeneratorInput = restingFreq * $sweep
|
||||||
|
|
||||||
// Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch
|
// Inner mode selectors per sweep direction. `Select` rounds the [0, 2] mode switch
|
||||||
// to the nearest position and advances all three filters each block (warmed state).
|
// to the nearest position and advances all three filters each block (warmed state).
|
||||||
let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias
|
let modeWhich: any ValidGeneratorInput = $mode + selectRoundingBias
|
||||||
let downModes: Select.Audio = Select.Audio(
|
let downModes: Select.Audio = Select.Audio(
|
||||||
which: modeWhich,
|
which: modeWhich,
|
||||||
inputs: [
|
inputs: [
|
||||||
makeFilter(dry, mode: .lowpass, direction: .down),
|
makeFilter(dry, mode: .lowpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
makeFilter(dry, mode: .bandpass, direction: .down),
|
makeFilter(dry, mode: .bandpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
makeFilter(dry, mode: .highpass, direction: .down),
|
makeFilter(dry, mode: .highpass, direction: .down, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
let upModes: Select.Audio = Select.Audio(
|
let upModes: Select.Audio = Select.Audio(
|
||||||
which: modeWhich,
|
which: modeWhich,
|
||||||
inputs: [
|
inputs: [
|
||||||
makeFilter(dry, mode: .lowpass, direction: .up),
|
makeFilter(dry, mode: .lowpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
makeFilter(dry, mode: .bandpass, direction: .up),
|
makeFilter(dry, mode: .bandpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
makeFilter(dry, mode: .highpass, direction: .up),
|
makeFilter(dry, mode: .highpass, direction: .up, freqLo: restingFreq, freqHi: peakFreq),
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -153,7 +209,9 @@ public final class MutantPedal: Pedal {
|
|||||||
private func makeFilter(
|
private func makeFilter(
|
||||||
_ dry: any ValidGeneratorInput,
|
_ dry: any ValidGeneratorInput,
|
||||||
mode: MuTronIIIMode,
|
mode: MuTronIIIMode,
|
||||||
direction: MuTronIIISweep
|
direction: MuTronIIISweep,
|
||||||
|
freqLo: any ValidGeneratorInput,
|
||||||
|
freqHi: any ValidGeneratorInput
|
||||||
) -> MuTronIII.Audio {
|
) -> MuTronIII.Audio {
|
||||||
MuTronIII.Audio(
|
MuTronIII.Audio(
|
||||||
input: dry,
|
input: dry,
|
||||||
@@ -163,8 +221,8 @@ public final class MutantPedal: Pedal {
|
|||||||
peak: $resonance,
|
peak: $resonance,
|
||||||
freqLo: freqLo,
|
freqLo: freqLo,
|
||||||
freqHi: freqHi,
|
freqHi: freqHi,
|
||||||
attackTime: attackTime,
|
attackTime: $attack,
|
||||||
releaseTime: releaseTime
|
releaseTime: $release
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -11,20 +11,19 @@ import LyrebirdUI
|
|||||||
///
|
///
|
||||||
/// Signal chain (inside `effect(_:)`):
|
/// Signal chain (inside `effect(_:)`):
|
||||||
/// ```
|
/// ```
|
||||||
/// dry ─┬─────────────────────────────────────────────────────────┐
|
/// detector(dry) → Schmidt(lo: thr, hi: thr×ratio) → LinLin(0…1 → floor…1) → LagUpDown(open/close)
|
||||||
/// └→ AmplitudeFollower → Schmidt(lo: thr, hi: thr×ratio) │
|
/// Peak: AmplitudeFollower(|x|)
|
||||||
/// → LinLin(0…1 → floor…1) │
|
/// RMS: √Lag(x²) out = dry × smoothed-gain
|
||||||
/// → LagUpDown(fast open/slow close) × ─┴→ mono out
|
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// An `AmplitudeFollower` tracks the dry signal level. A Schmitt trigger turns that
|
/// The **detector** tracks the dry signal level — either peak (`|x|`) or RMS (√mean-square). A
|
||||||
/// envelope into an open/closed gate with hysteresis (opens above `threshold × openRatio`,
|
/// Schmitt trigger turns that envelope into an open/closed gate with hysteresis (opens above
|
||||||
/// closes below `threshold`) so the gate does not chatter around the threshold. The 0/1
|
/// `threshold × openRatio`, closes below `threshold`) so the gate does not chatter around the
|
||||||
/// gate is mapped to a gain in `[floor, 1]` and smoothed **asymmetrically** — opening fast so a
|
/// threshold. The 0/1 gate is mapped to a gain in `[floor, 1]` and smoothed **asymmetrically** —
|
||||||
/// note's attack isn't softened, closing slowly so the gate fades shut instead of snapping (a fast
|
/// opening fast so a note's attack isn't softened, closing slowly so the gate fades shut instead of
|
||||||
/// close popped audibly when heavy downstream gain amplified the step). When the gate is closed the
|
/// snapping (a fast close popped audibly when heavy downstream gain amplified the step). When the
|
||||||
/// signal is attenuated to `floor` rather than hard-muted, so `floor` sets how much of the quiet
|
/// gate is closed the signal is attenuated to `floor` rather than hard-muted, so `floor` sets how
|
||||||
/// signal/noise tail bleeds through.
|
/// much of the quiet signal/noise tail bleeds through.
|
||||||
///
|
///
|
||||||
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class.
|
||||||
///
|
///
|
||||||
@@ -39,6 +38,8 @@ import LyrebirdUI
|
|||||||
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
|
/// mute, `1` = no gating. Range `[0, 1]`. Defaults to `0.0`.
|
||||||
/// - attack: Gate open time in seconds (advanced pop-over). Range `[0.001, 0.05]`. Defaults to `0.005`.
|
/// - attack: Gate open time in seconds (advanced pop-over). Range `[0.001, 0.05]`. Defaults to `0.005`.
|
||||||
/// - release: Gate close time in seconds (advanced pop-over). Range `[0.01, 0.5]`. Defaults to `0.08`.
|
/// - release: Gate close time in seconds (advanced pop-over). Range `[0.01, 0.5]`. Defaults to `0.08`.
|
||||||
|
/// - detector: Level-detection mode (switch). `0` = Peak (`|x|`), `1` = RMS (√mean-square).
|
||||||
|
/// Defaults to RMS (`1`).
|
||||||
public final class NoiseGatePedal: Pedal {
|
public final class NoiseGatePedal: Pedal {
|
||||||
|
|
||||||
/// One-line description shown in the picker and info panel.
|
/// One-line description shown in the picker and info panel.
|
||||||
@@ -63,17 +64,33 @@ public final class NoiseGatePedal: Pedal {
|
|||||||
/// out chatter at the threshold). Range `[0.01, 0.5]`. Surfaced in the advanced pop-over.
|
/// out chatter at the threshold). Range `[0.01, 0.5]`. Surfaced in the advanced pop-over.
|
||||||
@UIParam public var release: Double = 0.08
|
@UIParam public var release: Double = 0.08
|
||||||
|
|
||||||
|
/// Detector mode: `0` = **Peak** (tracks `|x|`), `1` = **RMS** (tracks √mean-square). RMS follows
|
||||||
|
/// perceived loudness, so the threshold decision — and the level at which the gate closes — lines
|
||||||
|
/// up with how loud the note actually is, instead of riding the waveform's peaks. Defaults to RMS.
|
||||||
|
@UIParam public var detector: Double = 1.0
|
||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
|
|
||||||
/// Default wet/dry blend — fully wet; the gate sits in-line.
|
/// Default wet/dry blend — fully wet; the gate sits in-line.
|
||||||
private static let defaultMix: Double = 1.0
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
|
/// `detector` value selecting the peak follower.
|
||||||
|
private let detectorPeakValue: Double = 0.0
|
||||||
|
|
||||||
|
/// `detector` value selecting the RMS follower.
|
||||||
|
private let detectorRMSValue: Double = 1.0
|
||||||
|
|
||||||
/// Envelope-follower attack time, in seconds — fast so the gate opens promptly on a note.
|
/// Envelope-follower attack time, in seconds — fast so the gate opens promptly on a note.
|
||||||
private let detectAttack: Double = 0.002
|
private let detectAttack: Double = 0.002
|
||||||
|
|
||||||
/// Envelope-follower release time, in seconds — slower so the gate holds through decay.
|
/// Envelope-follower release time, in seconds — slower so the gate holds through decay.
|
||||||
private let detectRelease: Double = 0.05
|
private let detectRelease: Double = 0.05
|
||||||
|
|
||||||
|
/// RMS integration window (one-pole averaging time, in seconds) for the RMS detector. Long enough
|
||||||
|
/// to average out the waveform's per-cycle ripple so the envelope reflects mean-square level, not
|
||||||
|
/// instantaneous peaks.
|
||||||
|
private let rmsWindow: Double = 0.02
|
||||||
|
|
||||||
/// Open-threshold multiplier. The gate opens above `threshold × openRatio` and closes
|
/// Open-threshold multiplier. The gate opens above `threshold × openRatio` and closes
|
||||||
/// below `threshold`, giving hysteresis that prevents chatter near the threshold.
|
/// below `threshold`, giving hysteresis that prevents chatter near the threshold.
|
||||||
private let openRatio: Double = 2.0
|
private let openRatio: Double = 2.0
|
||||||
@@ -122,6 +139,23 @@ public final class NoiseGatePedal: Pedal {
|
|||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Detector-mode switch (Peak / RMS). Appended as the gate's only switch, so a gate saved before
|
||||||
|
/// it existed (empty `switchValues`) loads with the RMS default — no migration.
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Detector",
|
||||||
|
node: $detector,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Peak", value: detectorPeakValue),
|
||||||
|
PedalSwitch.Option(title: "RMS", value: detectorRMSValue),
|
||||||
|
],
|
||||||
|
// Switching detector changes which follower is instantiated, so rebuild the board.
|
||||||
|
rebuildsOnChange: true
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
|
|
||||||
/// Creates a noise-gate pedal.
|
/// Creates a noise-gate pedal.
|
||||||
@@ -150,12 +184,26 @@ public final class NoiseGatePedal: Pedal {
|
|||||||
/// - Parameter dry: Dry mono input signal.
|
/// - Parameter dry: Dry mono input signal.
|
||||||
/// - Returns: Gated mono output.
|
/// - Returns: Gated mono output.
|
||||||
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
// Track the dry signal's amplitude envelope.
|
// Build the chosen detector only. `detector` is a `rebuildsOnChange` switch, so it is read
|
||||||
let envelope: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
// here as a plain value at build time (the board rebuilds when it is toggled) — no live
|
||||||
|
// node-select in the graph.
|
||||||
|
let envelope: any ValidGeneratorInput
|
||||||
|
if detector >= detectorRMSValue {
|
||||||
|
// RMS detector: √(symmetric one-pole average of x²). The averaging window must be
|
||||||
|
// symmetric — a fast attack would track the *squared peaks* and collapse back to peak
|
||||||
|
// detection — so a plain `Lag` over `rmsWindow` recovers the mean square, giving a
|
||||||
|
// loudness-tracking envelope roughly 3 dB below the peak for a steady tone.
|
||||||
|
let squared: any ValidGeneratorInput = dry * dry
|
||||||
|
let meanSquare: Lag.Audio = Lag.Audio(input: squared, time: rmsWindow)
|
||||||
|
envelope = Sqrt.Audio(meanSquare)
|
||||||
|
} else {
|
||||||
|
// Peak detector: a one-pole follower of |x| (fast attack, slower release).
|
||||||
|
envelope = AmplitudeFollower.Audio(
|
||||||
in: dry,
|
in: dry,
|
||||||
attackTime: detectAttack,
|
attackTime: detectAttack,
|
||||||
releaseTime: detectRelease
|
releaseTime: detectRelease
|
||||||
)
|
)
|
||||||
|
}
|
||||||
|
|
||||||
// Hysteretic open/closed gate: opens above threshold×openRatio, closes below threshold.
|
// Hysteretic open/closed gate: opens above threshold×openRatio, closes below threshold.
|
||||||
let gate: Schmidt.Audio = Schmidt.Audio(
|
let gate: Schmidt.Audio = Schmidt.Audio(
|
||||||
|
|||||||
@@ -0,0 +1,242 @@
|
|||||||
|
// PolyOctavePedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Polyphonic octave generator in the EHX POG mould.
|
||||||
|
///
|
||||||
|
/// Stacks four fixed pitch-shifted voices — two octaves down, one octave down, one octave up, two
|
||||||
|
/// octaves up — under the dry note, each with its own level, so a single note becomes an
|
||||||
|
/// organ-like chord of octaves. Unlike the ``WhammyPedal`` (one voice swept by an expression
|
||||||
|
/// pedal), every voice sounds at once at a **fixed** interval, and because the ratios are exact
|
||||||
|
/// powers of two the shifter needs no pitch tracking — chords shift as cleanly as single notes.
|
||||||
|
///
|
||||||
|
/// Each voice is a `PitchShift` — Lyrebird's four-head SOLA shifter, whose `pitchRatio` clamps to
|
||||||
|
/// `[0.25, 4.0]`, i.e. exactly ±2 octaves, so every voice here is a single stage (no cascade).
|
||||||
|
///
|
||||||
|
/// The five voice levels sum without an internal limiter (as with the OC-2-style
|
||||||
|
/// ``BassOctaverPedal``), so driving several to full can push the sum above unity; the pedal's
|
||||||
|
/// `level` knob and the board output master set the final gain, like a real mixer's channel sum.
|
||||||
|
///
|
||||||
|
/// A low-pass **Tone** control tames the shifted voices (the dry stays untouched), and an
|
||||||
|
/// **Attack** control adds the POG's signature volume **swell**: turned up, the octave voices fade
|
||||||
|
/// in after each note instead of sounding instantly, for a bowed / synth-pad bloom. The swell is a
|
||||||
|
/// "slow-gear" gain — the ratio of a slow envelope follower to a fast one — so at `Attack = 0` the
|
||||||
|
/// two followers are identical and the gain is unity (voices respond instantly), and the swell
|
||||||
|
/// never depends on how loud you play.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `subTwo`: −2 octave voice level in `[0, 1]`.
|
||||||
|
/// - `subOne`: −1 octave voice level in `[0, 1]`.
|
||||||
|
/// - `upOne`: +1 octave voice level in `[0, 1]`.
|
||||||
|
/// - `upTwo`: +2 octave voice level in `[0, 1]`.
|
||||||
|
/// - `dry`: Dry (direct) signal level in `[0, 1]`.
|
||||||
|
/// - `attack`: Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom.
|
||||||
|
/// - `tone`: Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
|
||||||
|
public final class PolyOctavePedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Stacks fixed octave voices under your note — organ-like, with a volume swell."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// −2 octave voice level in `[0, 1]`.
|
||||||
|
@UIParam public var subTwo: Double = 0.0
|
||||||
|
|
||||||
|
/// −1 octave voice level in `[0, 1]`.
|
||||||
|
@UIParam public var subOne: Double = 0.0
|
||||||
|
|
||||||
|
/// +1 octave voice level in `[0, 1]`.
|
||||||
|
@UIParam public var upOne: Double = 0.5
|
||||||
|
|
||||||
|
/// +2 octave voice level in `[0, 1]`.
|
||||||
|
@UIParam public var upTwo: Double = 0.0
|
||||||
|
|
||||||
|
/// Dry (direct) signal level in `[0, 1]`.
|
||||||
|
@UIParam public var dry: Double = 1.0
|
||||||
|
|
||||||
|
/// Octave-voice swell in `[0, 1]`. `0` = instant; higher = slower volume bloom after each note.
|
||||||
|
@UIParam public var attack: Double = 0.0
|
||||||
|
|
||||||
|
/// Octave-voice low-pass cutoff in Hz. Range `[500, 12000]`.
|
||||||
|
@UIParam public var tone: Double = 8000.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Pedal blends everything internally via the level knobs, so the base wet/dry stays fully wet.
|
||||||
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
|
/// Fixed `PitchShift` playback ratios for the four voices (exact powers of two).
|
||||||
|
private let subTwoRatio: Double = 0.25 // −2 octaves
|
||||||
|
private let subOneRatio: Double = 0.5 // −1 octave
|
||||||
|
private let upOneRatio: Double = 2.0 // +1 octave
|
||||||
|
private let upTwoRatio: Double = 4.0 // +2 octaves
|
||||||
|
|
||||||
|
/// Grain window for each `PitchShift`, in seconds. A touch over the shifter's `0.1` default to
|
||||||
|
/// soften the periodic four-head comb without adding audible lag.
|
||||||
|
private let voiceWindowSize: Double = 0.11
|
||||||
|
|
||||||
|
/// Per-head timing jitter for each `PitchShift`, in seconds. Breaks the fixed-grid comb; kept
|
||||||
|
/// small so the voices stay tight.
|
||||||
|
private let voiceTimeDispersion: Double = 0.02
|
||||||
|
|
||||||
|
/// Fixed PRNG seeds, one per voice, so a given setting renders identically every time
|
||||||
|
/// (reproducible audio and exact-pitch tests). Distinct per voice so their grain dispersion
|
||||||
|
/// sequences decorrelate instead of jittering in lockstep.
|
||||||
|
private let subTwoSeed: UInt64 = 0x9E37_79B9_7F4A_7C15
|
||||||
|
private let subOneSeed: UInt64 = 0xC2B2_AE3D_27D4_EB4F
|
||||||
|
private let upOneSeed: UInt64 = 0x1656_67B1_9E37_79F9
|
||||||
|
private let upTwoSeed: UInt64 = 0x2545_F491_4F6C_DD1D
|
||||||
|
|
||||||
|
/// Fast envelope-follower attack for the swell's denominator, in seconds — near-instant, so it
|
||||||
|
/// tracks note onsets tightly. Also the floor of the mapped slow attack, so `attack = 0` makes
|
||||||
|
/// the two followers identical and the swell gain unity (neutral).
|
||||||
|
private let swellFastAttack: Double = 0.005
|
||||||
|
|
||||||
|
/// Slowest envelope-follower attack the `attack` knob maps to, in seconds (at `attack = 1`).
|
||||||
|
private let swellMaxAttack: Double = 1.5
|
||||||
|
|
||||||
|
/// Shared release time for both swell followers, in seconds. Equal on both so only the attack
|
||||||
|
/// differs between them.
|
||||||
|
private let swellRelease: Double = 0.15
|
||||||
|
|
||||||
|
/// Floor added to the swell denominator before the reciprocal, so a silent input (both
|
||||||
|
/// followers near zero) cannot divide by zero. Kept well below any real signal level
|
||||||
|
/// (`1e-6` ≈ −120 dB) so the neutral gain stays ~1 across the whole playing range — a larger
|
||||||
|
/// floor would pull the `attack = 0` gain toward `0.5` for quiet input.
|
||||||
|
private let swellDenomFloor: Double = 1.0e-6
|
||||||
|
|
||||||
|
/// Clamp bounds for the swell gain. With equal release times the two followers track in
|
||||||
|
/// lockstep once settled, so the ratio stays `≤ 1` in normal use (it dips below `1` only during
|
||||||
|
/// the attack ramp, when the slow follower lags); the ceiling is a defensive guard against a
|
||||||
|
/// transient overshoot from the reciprocal, and the floor keeps the gain non-negative.
|
||||||
|
private let swellGainFloor: Double = 0.0
|
||||||
|
private let swellGainCeil: Double = 1.0
|
||||||
|
|
||||||
|
/// Butterworth Q (no resonant peak) for the tone low-pass.
|
||||||
|
private let toneQ: Double = 0.707
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let levelRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
private let attackRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
private let toneRange: ClosedRange<Double> = 500.0 ... 12000.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "-2 Oct", node: $subTwo, range: levelRange),
|
||||||
|
PedalKnob(label: "-1 Oct", node: $subOne, range: levelRange),
|
||||||
|
PedalKnob(label: "+1 Oct", node: $upOne, range: levelRange),
|
||||||
|
PedalKnob(label: "+2 Oct", node: $upTwo, range: levelRange),
|
||||||
|
PedalKnob(label: "Dry", node: $dry, range: levelRange),
|
||||||
|
PedalKnob(label: "Attack", node: $attack, range: attackRange),
|
||||||
|
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a polyphonic octave pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Poly Octave",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: PolyOctavePedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Four fixed-ratio voices. Each ratio is within PitchShift's ±2-octave clamp, so a single
|
||||||
|
// stage suffices (no cascade, unlike the Whammy's 3-octave Dive Bomb).
|
||||||
|
let subTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subTwoRatio, seed: subTwoSeed)
|
||||||
|
let subOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: subOneRatio, seed: subOneSeed)
|
||||||
|
let upOneVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upOneRatio, seed: upOneSeed)
|
||||||
|
let upTwoVoice: PitchShift.Audio = makeVoice(dry: dry, ratio: upTwoRatio, seed: upTwoSeed)
|
||||||
|
|
||||||
|
// Octave bus: each voice scaled by its level knob.
|
||||||
|
let octaveBus: any ValidGeneratorInput =
|
||||||
|
(subTwoVoice * $subTwo)
|
||||||
|
+ (subOneVoice * $subOne)
|
||||||
|
+ (upOneVoice * $upOne)
|
||||||
|
+ (upTwoVoice * $upTwo)
|
||||||
|
|
||||||
|
// Swell: a "slow-gear" gain applied to the octave bus only (the dry stays immediate).
|
||||||
|
let swelled: any ValidGeneratorInput = octaveBus * swellGain(dry: dry)
|
||||||
|
|
||||||
|
// Tone shapes the shifted voices, not the dry.
|
||||||
|
let octaveToned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||||
|
input: swelled,
|
||||||
|
freq: $tone,
|
||||||
|
q: toneQ
|
||||||
|
)
|
||||||
|
|
||||||
|
return (dry * $dry) + octaveToned
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds one fixed-ratio octave voice.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - dry: Dry input to shift.
|
||||||
|
/// - ratio: Fixed playback ratio (power of two) within PitchShift's `[0.25, 4.0]` clamp.
|
||||||
|
/// - seed: Per-voice PRNG seed for reproducible grain dispersion.
|
||||||
|
/// - Returns: The pitch-shifted voice (pre-level).
|
||||||
|
private func makeVoice(
|
||||||
|
dry: any ValidGeneratorInput,
|
||||||
|
ratio: Double,
|
||||||
|
seed: UInt64
|
||||||
|
) -> PitchShift.Audio {
|
||||||
|
PitchShift.Audio(
|
||||||
|
input: dry,
|
||||||
|
pitchRatio: ratio,
|
||||||
|
windowSize: voiceWindowSize,
|
||||||
|
timeDispersion: voiceTimeDispersion,
|
||||||
|
seed: seed
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds the octave-voice swell gain: the ratio of a slow envelope follower to a fast one,
|
||||||
|
/// clamped to `[0, 1]`. Unity when `attack = 0` (both followers identical), dipping and then
|
||||||
|
/// recovering as `attack` rises, so the voices bloom in after each onset independent of level.
|
||||||
|
///
|
||||||
|
/// - Parameter dry: Dry input the swell tracks.
|
||||||
|
/// - Returns: A `[0, 1]` gain to multiply the octave bus by.
|
||||||
|
private func swellGain(dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// attack [0, 1] → slow-follower attack [swellFastAttack, swellMaxAttack] seconds.
|
||||||
|
let attackSpan: Double = swellMaxAttack - swellFastAttack
|
||||||
|
let slowAttackTime: any ValidGeneratorInput = ($attack * attackSpan) + swellFastAttack
|
||||||
|
|
||||||
|
let fastEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||||
|
in: dry,
|
||||||
|
attackTime: swellFastAttack,
|
||||||
|
releaseTime: swellRelease
|
||||||
|
)
|
||||||
|
let slowEnv: AmplitudeFollower.Audio = AmplitudeFollower.Audio(
|
||||||
|
in: dry,
|
||||||
|
attackTime: slowAttackTime,
|
||||||
|
releaseTime: swellRelease
|
||||||
|
)
|
||||||
|
|
||||||
|
// gain = slowEnv / (fastEnv + floor), clamped to [0, 1].
|
||||||
|
let denom: any ValidGeneratorInput = fastEnv + swellDenomFloor
|
||||||
|
let ratio: any ValidGeneratorInput = slowEnv * Reciprocal.Audio(denom)
|
||||||
|
return Clip.Audio(ratio, lo: swellGainFloor, hi: swellGainCeil)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
// ReverseReverbPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Reverse reverb — a backwards-swelling ambience, the "sucked-in" pre-verb of ambient and
|
||||||
|
/// shoegaze records.
|
||||||
|
///
|
||||||
|
/// The dry signal is first run through a segmented ``ReverseDelay``: it is captured in fixed-length
|
||||||
|
/// segments and each is played back reversed, so a note's natural decay becomes a swell that rises
|
||||||
|
/// *into* the note. That reversed signal then feeds a `GVerb` room tank, so the backwards swell
|
||||||
|
/// arrives wrapped in a diffuse reverberant wash rather than as a dry backwards note. The result is
|
||||||
|
/// distinct from the plain ``ReverseDelayPedal`` (no reverb) and from a forward ``RoomReverbPedal``
|
||||||
|
/// (energy that follows the note instead of swelling up to it).
|
||||||
|
///
|
||||||
|
/// `Time` sets the reverse segment length (and so the pre-delay before each swell); `Decay`, `Size`,
|
||||||
|
/// and `Damp` shape the GVerb tail. The tank runs natively in stereo and is folded to mono. The
|
||||||
|
/// base `Pedal` `mix` sets the wet/dry blend, so your live note stays up front while the reversed
|
||||||
|
/// wash sits under it. Latency is one segment — a note's reversed swell appears up to `Time` seconds
|
||||||
|
/// after you play it.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `time`: Reverse segment length in seconds. Range `[0.1, 2.0]`. Also the swell pre-delay.
|
||||||
|
/// - `decay`: GVerb reverb time (T60) in seconds. Range `[0.2, 12.0]`.
|
||||||
|
/// - `size`: GVerb room size in metres. Range `[1, 100]`.
|
||||||
|
/// - `damp`: High-frequency damping `[0, 1]` (0 = bright, 1 = dark).
|
||||||
|
public final class ReverseReverbPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Backwards-swelling reverb — notes bloom in reverse, wrapped in a diffuse wash."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Reverse segment length in seconds (also the swell pre-delay). Range [0.1, 2.0].
|
||||||
|
@UIParam public var time: Double = 0.5
|
||||||
|
|
||||||
|
/// GVerb reverb time (T60) in seconds. Range [0.2, 12.0].
|
||||||
|
@UIParam public var decay: Double = 3.0
|
||||||
|
|
||||||
|
/// GVerb room size in metres. Range [1, 100].
|
||||||
|
@UIParam public var size: Double = 30.0
|
||||||
|
|
||||||
|
/// High-frequency damping in [0, 1]. Higher = darker tail.
|
||||||
|
@UIParam public var damp: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — the reversed wash sits under the dry note.
|
||||||
|
private static let defaultMix: Double = 0.4
|
||||||
|
|
||||||
|
/// Maximum reverse segment length the `ReverseDelay` buffers are allocated for, in seconds.
|
||||||
|
/// Matches the top of the `time` range so a full-length segment never clamps.
|
||||||
|
private let maxReverseTime: Double = 2.0
|
||||||
|
|
||||||
|
/// Reverse-trail feedback. Kept at `0` so each swell is a single clean pass (the GVerb tail,
|
||||||
|
/// not recirculated reverse segments, provides the sustain).
|
||||||
|
private let reverseFeedback: Double = 0.0
|
||||||
|
|
||||||
|
/// GVerb dry level — how much of the GVerb *source* passes through the tank's dry path. The
|
||||||
|
/// source here is the already-reversed signal (not the raw input), so this keeps the backwards
|
||||||
|
/// swell itself audible under its reverb rather than being fully smeared. The pedal's own `mix`
|
||||||
|
/// then blends this whole wet result against the true dry note. Kept at `0.5` (with the tail and
|
||||||
|
/// early levels below) so the summed wet path keeps headroom below clipping on a loud input.
|
||||||
|
private let reverseSwellLevel: Double = 0.5
|
||||||
|
|
||||||
|
/// GVerb late-reverb (tail) level.
|
||||||
|
private let reverbTailLevel: Double = 0.5
|
||||||
|
|
||||||
|
/// GVerb early-reflection level. Lowered from the generator's `0.4` default: early reflections
|
||||||
|
/// fire forward (not reversed), so a high level would fight the backwards-swell character; a
|
||||||
|
/// smaller amount keeps some room sense while favouring the reversed tail, and trims the sum.
|
||||||
|
private let reverbEarlyLevel: Double = 0.3
|
||||||
|
|
||||||
|
/// Gain folding GVerb's two decorrelated reverb channels to mono. A conservative trim (not a
|
||||||
|
/// strict doubling correction — the channels are not identical), leaving output headroom.
|
||||||
|
private let stereoSumGain: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let timeRange: ClosedRange<Double> = 0.1 ... 2.0
|
||||||
|
private let decayRange: ClosedRange<Double> = 0.2 ... 12.0
|
||||||
|
private let sizeRange: ClosedRange<Double> = 1.0 ... 100.0
|
||||||
|
private let normalizedRange: ClosedRange<Double> = 0.0 ... 1.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),
|
||||||
|
PedalKnob(label: "Decay", node: $decay, range: decayRange),
|
||||||
|
PedalKnob(label: "Size", node: $size, range: sizeRange),
|
||||||
|
PedalKnob(label: "Damp", node: $damp, range: normalizedRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a reverse-reverb pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Reverse Reverb",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: ReverseReverbPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Reverse the dry in fixed segments: a note's decay becomes a swell rising into it.
|
||||||
|
let reversed: ReverseDelay = ReverseDelay(
|
||||||
|
input: dry,
|
||||||
|
maxDelay: maxReverseTime,
|
||||||
|
delay: $time,
|
||||||
|
feedback: reverseFeedback,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
// Wrap the reversed swell in a GVerb room tank (native stereo). `dryLevel` keeps the swell
|
||||||
|
// itself present under the reverb.
|
||||||
|
let stereoVerb: GVerb.Audio = GVerb.Audio(
|
||||||
|
source: reversed,
|
||||||
|
roomSize: $size,
|
||||||
|
reverbTime: $decay,
|
||||||
|
damping: $damp,
|
||||||
|
earlyLevel: reverbEarlyLevel,
|
||||||
|
tailLevel: reverbTailLevel,
|
||||||
|
dryLevel: reverseSwellLevel,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
// Sum stereo → mono with ×0.5 to avoid level doubling.
|
||||||
|
return SumChannels.Audio(
|
||||||
|
input: stereoVerb,
|
||||||
|
mul: stereoSumGain
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
// ScriptPhaserPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Script phaser — the classic one-knob, four-stage orange phaser (the script-logo voicing).
|
||||||
|
///
|
||||||
|
/// A single **Speed** knob sweeps a fixed four-stage all-pass cascade; there is no depth or
|
||||||
|
/// feedback knob, just the signature liquid whoosh. A **Voicing** switch picks the character: the
|
||||||
|
/// smoother *Script* voicing (lower feedback, gentler notch) or the more resonant *Block* voicing
|
||||||
|
/// (more feedback, sharper notch) — the two eras of the hardware.
|
||||||
|
///
|
||||||
|
/// Distinct from the general-purpose ``PhaserPedal`` (six stages, with rate **and** feedback knobs):
|
||||||
|
/// this is deliberately the fixed, four-stage, one-knob classic. Wraps the shared `Phaser.Audio`
|
||||||
|
/// generator run fully wet; the base `Pedal` `mix` sets the wet/dry blend.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `speed`: LFO sweep rate in Hz. Range `[0.05, 5.0]`.
|
||||||
|
///
|
||||||
|
/// ## Switches
|
||||||
|
/// - `voicing` (two-state): `0` = Script (smoother), `1` = Block (more resonant).
|
||||||
|
public final class ScriptPhaserPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"The one-knob four-stage orange phaser — liquid whoosh, script or block voicing."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// LFO sweep rate in Hz. Range [0.05, 5.0].
|
||||||
|
@UIParam public var speed: Double = 0.5
|
||||||
|
|
||||||
|
/// Voicing selector. `0` = Script (smoother, lower feedback), `1` = Block (more resonant).
|
||||||
|
@UIParam public var voicing: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — an even mix for the classic comb-filter sweep.
|
||||||
|
private static let defaultMix: Double = 0.5
|
||||||
|
|
||||||
|
/// Internal `Phaser.Audio` mix — `1.0` so the base `Pedal` handles dry/wet.
|
||||||
|
private let phaserInternalMix: Double = 1.0
|
||||||
|
|
||||||
|
/// LFO depth fraction — sweeps the all-pass coefficient across its range.
|
||||||
|
private let phaserDepth: Double = 0.9
|
||||||
|
|
||||||
|
/// Center frequency in Hz for the all-pass coefficient sweep.
|
||||||
|
private let phaserCenterFreq: Double = 800.0
|
||||||
|
|
||||||
|
/// Four cascaded all-pass stages — the defining topology of this phaser (`Phaser.Audio`
|
||||||
|
/// requires 4, 6, or 8).
|
||||||
|
private let phaserStages: Int = 4
|
||||||
|
|
||||||
|
/// Feedback for the Script voicing — low, for a smooth gentle notch.
|
||||||
|
private let scriptFeedbackValue: Double = 0.2
|
||||||
|
|
||||||
|
/// Feedback for the Block voicing — higher, for a sharper, more resonant notch.
|
||||||
|
private let blockFeedbackValue: Double = 0.45
|
||||||
|
|
||||||
|
// MARK: - Switch values
|
||||||
|
|
||||||
|
private let voicingScriptValue: Double = 0.0
|
||||||
|
private let voicingBlockValue: Double = 1.0
|
||||||
|
|
||||||
|
/// Smoothing time in seconds for the voicing→feedback change, so flipping Script↔Block glides
|
||||||
|
/// the feedback coefficient instead of stepping it (which could tick on a live toggle).
|
||||||
|
private let voicingSmoothTime: Double = 0.03
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let speedRange: ClosedRange<Double> = 0.05 ... 5.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||||
|
[
|
||||||
|
TempoSyncableParam(key: "speed", label: "Speed", node: $speed, kind: .rate, range: speedRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Speed", node: $speed, range: speedRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Switches
|
||||||
|
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Voicing",
|
||||||
|
node: $voicing,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Script", value: voicingScriptValue),
|
||||||
|
PedalSwitch.Option(title: "Block", value: voicingBlockValue),
|
||||||
|
]
|
||||||
|
)
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a script-phaser pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Script Phaser",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: ScriptPhaserPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Voicing (0 = Script, 1 = Block) selects the feedback amount live — a linear map between the
|
||||||
|
// two fixed values, no rebuild needed since feedback is a live Phaser parameter. A short Lag
|
||||||
|
// glides the coefficient on a Script↔Block toggle so it doesn't step audibly.
|
||||||
|
let feedbackSpan: Double = blockFeedbackValue - scriptFeedbackValue
|
||||||
|
let voicedFeedback: any ValidGeneratorInput = ($voicing * feedbackSpan) + scriptFeedbackValue
|
||||||
|
let smoothedFeedback: Lag.Audio = Lag.Audio(input: voicedFeedback, time: voicingSmoothTime)
|
||||||
|
|
||||||
|
return Phaser.Audio(
|
||||||
|
input: dry,
|
||||||
|
rate: $speed,
|
||||||
|
depth: phaserDepth,
|
||||||
|
centerFreq: phaserCenterFreq,
|
||||||
|
feedback: smoothedFeedback,
|
||||||
|
stages: phaserStages,
|
||||||
|
mix: phaserInternalMix,
|
||||||
|
sampleRate: sampleRate
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -31,13 +31,16 @@ public final class ShimmerReverbPedal: Pedal {
|
|||||||
@UIParam public var size: Double = 0.06
|
@UIParam public var size: Double = 0.06
|
||||||
|
|
||||||
/// Tail length (feedback). Range [0, 0.92].
|
/// Tail length (feedback). Range [0, 0.92].
|
||||||
@UIParam public var decay: Double = 0.8
|
///
|
||||||
|
/// The regenerating loop gain is roughly `decay + shimmer`; keep their sum well under `1` to avoid
|
||||||
|
/// self-oscillation (a sustaining screech with little or no input). Defaults sum to `0.75`.
|
||||||
|
@UIParam public var decay: Double = 0.5
|
||||||
|
|
||||||
/// Octave-up regeneration amount. Range [0, 0.85].
|
/// Octave-up regeneration amount. Range [0, 0.85]. See ``decay`` on keeping `decay + shimmer < 1`.
|
||||||
@UIParam public var shimmer: Double = 0.5
|
@UIParam public var shimmer: Double = 0.25
|
||||||
|
|
||||||
/// High-frequency damping. Range [0, 1].
|
/// High-frequency damping. Range [0, 1].
|
||||||
@UIParam public var damp: Double = 0.4
|
@UIParam public var damp: Double = 0.5
|
||||||
|
|
||||||
// MARK: - Constants
|
// MARK: - Constants
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
// SustainFuzzPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Sustaining, mid-scooped fuzz: two cascaded soft-clipping stages into a scoop-and-tone filter.
|
||||||
|
///
|
||||||
|
/// Signal chain (inside `effect(_:)`):
|
||||||
|
/// ```
|
||||||
|
/// dry → Saturator(soft, sustain) → Saturator(soft, sustain) → RBJPeakingEQ(−scoop @ 750 Hz) → RBJLowPass(tone) → out
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// This is the "wall of sustain" fuzz voice — distinct from the single-stage ``FuzzPedal``. Two
|
||||||
|
/// cascaded *soft*-clipping stages compress and stack harmonics for long, smooth, violin-like
|
||||||
|
/// sustain rather than the aggressive bite of a single hard `tanh` stage. A fixed mid **scoop**
|
||||||
|
/// (a bell cut around 750 Hz) hollows the midrange — the defining character of this fuzz family —
|
||||||
|
/// and the **tone** low-pass sets how dark or bright the top end sits.
|
||||||
|
///
|
||||||
|
/// The wet/dry mix and bypass switching are handled by the `Pedal` base class; base `mix` is fully
|
||||||
|
/// wet so the fuzz replaces the dry signal.
|
||||||
|
///
|
||||||
|
/// ## Parameters
|
||||||
|
///
|
||||||
|
/// Inherits `mix`, `bypass`, and `level` from `Pedal`, plus:
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - sustain: Drive into both soft-clip stages. Higher = more sustain and compression.
|
||||||
|
/// Range `[1, 30]`. Defaults to `6.0`.
|
||||||
|
/// - tone: Low-pass tone cutoff in Hz. Range `[800, 6000]`. Defaults to `2500.0`.
|
||||||
|
/// - scoop: Midrange cut depth in dB at 750 Hz (applied as a cut). Range `[0, 18]`. Defaults to `8.0`.
|
||||||
|
public final class SustainFuzzPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Sustaining, mid-scooped fuzz for smooth, violin-like leads and thick walls of sound."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Drive into both cascaded soft-clip stages. Range [1, 30]; higher = more sustain.
|
||||||
|
@UIParam public var sustain: Double = 6.0
|
||||||
|
|
||||||
|
/// Tone low-pass cutoff in Hz. Range [800, 6000].
|
||||||
|
@UIParam public var tone: Double = 2500.0
|
||||||
|
|
||||||
|
/// Midrange cut depth in dB at 750 Hz. Range [0, 18].
|
||||||
|
@UIParam public var scoop: Double = 8.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — fully wet so the fuzz completely replaces the dry signal.
|
||||||
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
|
/// Oversampling factor for the soft-clip stages — 2× keeps generated harmonics from folding back.
|
||||||
|
private let oversampleFactor: Int = 2
|
||||||
|
|
||||||
|
/// Centre frequency of the midrange scoop in Hz.
|
||||||
|
private let scoopFreq: Double = 750.0
|
||||||
|
|
||||||
|
/// Q of the midrange scoop bell. Moderately wide for a broad, hollow midrange.
|
||||||
|
private let scoopQ: Double = 0.9
|
||||||
|
|
||||||
|
/// Q of the tone low-pass. Butterworth (no resonant peak).
|
||||||
|
private let toneQ: Double = 0.707
|
||||||
|
|
||||||
|
/// Output trim after two soft-clip stages (each ≈ ±1) plus the mid cut, to sit at a sane level.
|
||||||
|
private let outputTrim: Double = 0.6
|
||||||
|
|
||||||
|
// MARK: - UI knobs
|
||||||
|
|
||||||
|
/// Sustain knob range (drive into the soft-clip stages).
|
||||||
|
private let sustainRange: ClosedRange<Double> = 1.0 ... 30.0
|
||||||
|
|
||||||
|
/// Tone knob range in Hz (low-pass cutoff).
|
||||||
|
private let toneRange: ClosedRange<Double> = 800.0 ... 6000.0
|
||||||
|
|
||||||
|
/// Scoop knob range in dB (midrange cut depth).
|
||||||
|
private let scoopRange: ClosedRange<Double> = 0.0 ... 18.0
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Sustain", node: $sustain, range: sustainRange),
|
||||||
|
PedalKnob(label: "Tone", node: $tone, range: toneRange),
|
||||||
|
PedalKnob(label: "Scoop", node: $scoop, range: scoopRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a sustain-fuzz pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Sustain Fuzz",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: SustainFuzzPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
/// Cascades two soft-clip stages, scoops the mids, then rolls off the top with the tone control.
|
||||||
|
///
|
||||||
|
/// - Parameter dry: Dry mono input signal.
|
||||||
|
/// - Returns: Sustained, mid-scooped, tone-shaped mono output.
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// Two cascaded soft-clip stages. `softClipNormalized` keeps the level bounded as sustain
|
||||||
|
// rises, so stacking two stages compresses and sustains rather than runs away.
|
||||||
|
let stage1: OversampledSaturator = OversampledSaturator(
|
||||||
|
dry,
|
||||||
|
drive: $sustain,
|
||||||
|
curve: .softClipNormalized,
|
||||||
|
oversample: oversampleFactor
|
||||||
|
)
|
||||||
|
let stage2: OversampledSaturator = OversampledSaturator(
|
||||||
|
stage1,
|
||||||
|
drive: $sustain,
|
||||||
|
curve: .softClipNormalized,
|
||||||
|
oversample: oversampleFactor
|
||||||
|
)
|
||||||
|
|
||||||
|
// Fixed midrange scoop (cut) — the hollow midrange that defines this fuzz family.
|
||||||
|
let scoopCutDB: any ValidGeneratorInput = 0.0 - $scoop
|
||||||
|
let scooped: RBJPeakingEQ.Audio = RBJPeakingEQ.Audio(
|
||||||
|
input: stage2,
|
||||||
|
freq: scoopFreq,
|
||||||
|
gain: scoopCutDB,
|
||||||
|
q: scoopQ
|
||||||
|
)
|
||||||
|
|
||||||
|
// Tone low-pass rolls off the top end.
|
||||||
|
let toned: RBJLowPass.Audio = RBJLowPass.Audio(
|
||||||
|
input: scooped,
|
||||||
|
freq: $tone,
|
||||||
|
q: toneQ
|
||||||
|
)
|
||||||
|
return toned * outputTrim
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,396 @@
|
|||||||
|
// TapeLooperPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// A simple one-loop tape-style looper with the two classic tape tricks: **half-speed** (an octave
|
||||||
|
/// down, the loop twice as long) and **reverse**. Where the full ``LooperPedal`` is a synchronized
|
||||||
|
/// four-track overdub station, this is the single-knob stompbox: record a phrase, play it back, and
|
||||||
|
/// layer overdubs onto the one loop — then drop it to half speed or flip it backwards for the dubby,
|
||||||
|
/// Frippertronics-style wash.
|
||||||
|
///
|
||||||
|
/// Both speed tricks are **live** playback controls — flipping Reverse or Half-Speed re-reads the
|
||||||
|
/// same recorded loop at a new rate, with no rebuild. Recording and overdubbing always run at normal
|
||||||
|
/// forward speed (the write head can't stay aligned with a backward or slowed play-head), so
|
||||||
|
/// engaging overdub is ignored while Reverse or Half-Speed is on.
|
||||||
|
///
|
||||||
|
/// ## Transport (the Record footswitch, by state)
|
||||||
|
/// - **Empty**: press → record the loop.
|
||||||
|
/// - **Recording**: press → close the loop at its current length and start playing.
|
||||||
|
/// - **Playing**: press → toggle overdub onto the loop (forward normal speed only).
|
||||||
|
/// - **Stopped**: press → resume playback. Clear returns to empty.
|
||||||
|
///
|
||||||
|
/// The dry signal always passes through; the loop is added on top (so the wet/dry Mix knob is hidden
|
||||||
|
/// and the base `mix` stays fully wet).
|
||||||
|
public final class TapeLooperPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"A one-loop tape looper — record, overdub, then play it back half-speed or reversed."
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Double-width card so the transport row and loop controls fit without scrolling.
|
||||||
|
public override var widthUnits: Int { 2 }
|
||||||
|
|
||||||
|
/// The looper passes the clean signal through and adds the loop on top, so the wet/dry Mix knob
|
||||||
|
/// is meaningless — hide it and keep `mix` fully wet.
|
||||||
|
public override var showsMixControl: Bool { false }
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
/// Loop playback gain, in dB.
|
||||||
|
@UIParam public var playbackLevel: Double = 0.0
|
||||||
|
|
||||||
|
/// Retained level of existing loop content on each overdub pass, `[0, 1]`. `1.0` keeps prior
|
||||||
|
/// layers indefinitely; lower values fade them for a decaying tape-echo loop.
|
||||||
|
@UIParam public var feedback: Double = 1.0
|
||||||
|
|
||||||
|
// MARK: - Switches
|
||||||
|
|
||||||
|
/// Playback direction. `0` = forward, `1` = reverse.
|
||||||
|
@UIParam public var reverse: Double = 0.0
|
||||||
|
|
||||||
|
/// Playback speed. `0` = normal, `1` = half speed (an octave down, loop twice as long).
|
||||||
|
@UIParam public var halfSpeed: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Internal live state (read by the audio graph)
|
||||||
|
|
||||||
|
/// `1` while the loop is playing, else `0`. Gates the player sum and the overdub recorder's run.
|
||||||
|
@UIParam public var isPlaying: Double = 0.0
|
||||||
|
|
||||||
|
/// Play-head reset trigger. Pulsed `0 → 1` at play-start so the loop starts from frame 0.
|
||||||
|
@UIParam public var playTrigger: Double = 0.0
|
||||||
|
|
||||||
|
/// LED state for the Record footswitch: `1` while recording or overdubbing.
|
||||||
|
@UIParam public var recordIndicator: Double = 0.0
|
||||||
|
|
||||||
|
/// LED state for the Stop footswitch: `1` while stopped.
|
||||||
|
@UIParam public var stoppedIndicator: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Maximum recordable loop length, in seconds. The buffer allocates this long (roughly
|
||||||
|
/// `maxDurationSeconds × sampleRate × 8 bytes` per instance).
|
||||||
|
private static let maxDurationSeconds: Double = 30.0
|
||||||
|
|
||||||
|
/// Fade time constant, in seconds, for the play/stop mute — smooths the loop in and out so a
|
||||||
|
/// stop or resume doesn't click.
|
||||||
|
private let playFadeTime: Double = 0.02
|
||||||
|
|
||||||
|
/// Forward playback rate.
|
||||||
|
private let forwardRate: Double = 1.0
|
||||||
|
|
||||||
|
/// Amount subtracted from the rate per unit of `reverse` — `2.0` flips `+1` to `−1`.
|
||||||
|
private let reverseRateSpan: Double = 2.0
|
||||||
|
|
||||||
|
/// Fraction the rate is reduced by at full `halfSpeed` — `0.5` turns `×1` into `×0.5`.
|
||||||
|
private let halfSpeedDrop: Double = 0.5
|
||||||
|
|
||||||
|
/// Smallest loop length in frames, so a zero-length take can't produce a degenerate buffer.
|
||||||
|
private static let minimumLoopFrames: Int = 1
|
||||||
|
|
||||||
|
private let levelRangeDb: ClosedRange<Double> = -24.0 ... 12.0
|
||||||
|
private let feedbackRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Buffers + generators
|
||||||
|
|
||||||
|
private var buffer: LyrebirdBuffer?
|
||||||
|
private var player: PlayBuffer.Audio?
|
||||||
|
private var masterRecorder: RecordBuffer.Audio?
|
||||||
|
private var overdubRecorder: RecordBuffer.Audio?
|
||||||
|
|
||||||
|
/// Overdub record gate (`1` = layering new input, `0` = passing existing content through).
|
||||||
|
private var overdubGate: ParameterNode = ParameterNode(0.0)
|
||||||
|
|
||||||
|
// MARK: - Transport state
|
||||||
|
|
||||||
|
private enum Phase {
|
||||||
|
case empty
|
||||||
|
case recording
|
||||||
|
case playing
|
||||||
|
case stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
private var phase: Phase = .empty
|
||||||
|
private var overdubbing: Bool = false
|
||||||
|
|
||||||
|
/// Recorded loop length in frames (`0` until a loop is closed).
|
||||||
|
private var masterLength: Int = 0
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a tape-looper pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(inputBus: Int = 0, outputBus: Int = 0) {
|
||||||
|
super.init(name: "Tape Looper", inputBus: inputBus, outputBus: outputBus, initialMix: 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Knobs / switches / buttons
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Playback", node: $playbackLevel, range: levelRangeDb),
|
||||||
|
PedalKnob(label: "Feedback", node: $feedback, range: feedbackRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Direction",
|
||||||
|
node: $reverse,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Fwd", value: 0.0),
|
||||||
|
PedalSwitch.Option(title: "Rev", value: 1.0),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Speed",
|
||||||
|
node: $halfSpeed,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Normal", value: 0.0),
|
||||||
|
PedalSwitch.Option(title: "Half", value: 1.0),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var effectTransportButtons: [PedalButton] {
|
||||||
|
[
|
||||||
|
PedalButton(label: "Record", indicator: $recordIndicator,
|
||||||
|
dynamicLabel: { [weak self] in self?.recordButtonCaption ?? "Record" }) { [weak self] in self?.pressRecord() },
|
||||||
|
PedalButton(label: "Stop", indicator: $stoppedIndicator) { [weak self] in self?.stopPlayback() },
|
||||||
|
PedalButton(label: "Clear") { [weak self] in self?.clearLoop() },
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - UI read-outs
|
||||||
|
|
||||||
|
/// Caption for the Record footswitch describing what the *next* press does.
|
||||||
|
public var recordButtonCaption: String {
|
||||||
|
switch phase {
|
||||||
|
case .empty: return "Record"
|
||||||
|
case .recording: return "Play"
|
||||||
|
case .stopped: return "Play"
|
||||||
|
case .playing: return overdubbing ? "Overdub Off" : "Overdub"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `true` once a loop has been recorded.
|
||||||
|
public var hasLoop: Bool { masterLength > 0 }
|
||||||
|
|
||||||
|
/// Recorded loop length in frames (`0` until a loop is closed).
|
||||||
|
public var loopFrameCount: Int { masterLength }
|
||||||
|
|
||||||
|
/// Recorded loop length in seconds.
|
||||||
|
public var loopLengthSeconds: Double { Double(masterLength) / sampleRate }
|
||||||
|
|
||||||
|
/// `true` while the loop is being overdubbed.
|
||||||
|
public var isOverdubbing: Bool { overdubbing }
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// `effect()` runs from `build()`, which the engine re-invokes on every add (including the
|
||||||
|
// re-adds a board edit performs on this same instance). Start clean so nothing references a
|
||||||
|
// discarded buffer and the transport returns to empty.
|
||||||
|
resetForRebuild()
|
||||||
|
|
||||||
|
let maxFrames: Int = Int(TapeLooperPedal.maxDurationSeconds * sampleRate)
|
||||||
|
let loopBuffer: LyrebirdBuffer = LyrebirdBuffer(count: maxFrames, channelCount: 1)
|
||||||
|
buffer = loopBuffer
|
||||||
|
|
||||||
|
// Playback rate: direction × speed, both live. reverse 0→+1 / 1→−1; halfSpeed 0→×1 / 1→×0.5.
|
||||||
|
let directionRate: any ValidGeneratorInput = forwardRate - reverseRateSpan * $reverse
|
||||||
|
let speedScale: any ValidGeneratorInput = forwardRate - halfSpeedDrop * $halfSpeed
|
||||||
|
let playbackRate: any ValidGeneratorInput = directionRate * speedScale
|
||||||
|
|
||||||
|
// Non-looping master recorder for the length-defining first take.
|
||||||
|
let master: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||||
|
input: dry,
|
||||||
|
buffer: loopBuffer,
|
||||||
|
loop: false,
|
||||||
|
doneAction: .nothing
|
||||||
|
)
|
||||||
|
master.run = 0.0
|
||||||
|
masterRecorder = master
|
||||||
|
|
||||||
|
// Always-running overdub recorder (gated by play): layers new input only while the overdub
|
||||||
|
// gate is open, otherwise it passes existing content through (`preLevel = 1`). While
|
||||||
|
// overdubbing, prior content is retained at `feedback`.
|
||||||
|
let unity: Double = 1.0
|
||||||
|
let overdub: RecordBuffer.Audio = RecordBuffer.Audio(
|
||||||
|
input: dry,
|
||||||
|
buffer: loopBuffer,
|
||||||
|
loop: true,
|
||||||
|
doneAction: .nothing
|
||||||
|
)
|
||||||
|
// The effective record-enable also closes if Reverse or Half-Speed is engaged *after* an
|
||||||
|
// overdub is toggled on — the write head runs forward 1× and can't stay aligned with a
|
||||||
|
// backward or slowed play-head. `(1 − reverse)·(1 − halfSpeed)` is `1` only at forward normal
|
||||||
|
// speed; when it drops to `0`, `recLevel` is `0` and `preLevel` is `1` (existing content
|
||||||
|
// preserved), so the layers never misalign.
|
||||||
|
overdub.$run.source = $isPlaying
|
||||||
|
let forwardNormal: BinaryOpGenerator = (unity - $reverse) * (unity - $halfSpeed)
|
||||||
|
let effectiveGate: BinaryOpGenerator = overdubGate * forwardNormal
|
||||||
|
overdub.$recLevel.source = effectiveGate
|
||||||
|
overdub.$preLevel.source = (unity - effectiveGate) + effectiveGate * $feedback
|
||||||
|
overdubRecorder = overdub
|
||||||
|
|
||||||
|
let loopPlayer: PlayBuffer.Audio = PlayBuffer.Audio(
|
||||||
|
buffer: loopBuffer,
|
||||||
|
loop: true,
|
||||||
|
interpolation: .cubic,
|
||||||
|
rate: playbackRate,
|
||||||
|
trigger: $playTrigger,
|
||||||
|
mul: DbAmp.Control($playbackLevel)
|
||||||
|
)
|
||||||
|
player = loopPlayer
|
||||||
|
|
||||||
|
// Loop audible only while playing; smoothed to avoid clicks on stop/resume.
|
||||||
|
let smoothedGate: Lag.Control = Lag.Control(input: $isPlaying, time: playFadeTime)
|
||||||
|
|
||||||
|
// Dry always passes through; the loop is added on top, gated by play.
|
||||||
|
return dry + (loopPlayer * smoothedGate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Transport
|
||||||
|
|
||||||
|
/// The smart Record press. Behaviour depends on the current phase.
|
||||||
|
public func pressRecord() {
|
||||||
|
switch phase {
|
||||||
|
case .empty: beginRecording()
|
||||||
|
case .recording: closeAndPlay()
|
||||||
|
case .playing: toggleOverdub()
|
||||||
|
case .stopped: resumePlayback()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private func beginRecording() {
|
||||||
|
guard let master: RecordBuffer.Audio = masterRecorder else { return }
|
||||||
|
master.requestReset()
|
||||||
|
master.run = 1.0
|
||||||
|
recordIndicator = 1.0
|
||||||
|
stoppedIndicator = 0.0
|
||||||
|
phase = .recording
|
||||||
|
}
|
||||||
|
|
||||||
|
private func closeAndPlay() {
|
||||||
|
guard phase == .recording, let master: RecordBuffer.Audio = masterRecorder,
|
||||||
|
let loopBuffer: LyrebirdBuffer = buffer else { return }
|
||||||
|
master.run = 0.0
|
||||||
|
// Nothing actually recorded (e.g. a double-press with no time between) — don't close a
|
||||||
|
// degenerate one-frame loop that would play as a DC buzz; drop back to empty.
|
||||||
|
let recorded: Int = master.recordedFrameCount
|
||||||
|
guard recorded > 0 else {
|
||||||
|
clearLoop()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
masterLength = max(TapeLooperPedal.minimumLoopFrames, recorded)
|
||||||
|
loopBuffer.setLoopLength(masterLength)
|
||||||
|
recordIndicator = 0.0
|
||||||
|
startPlayback()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Toggles overdub onto the loop. Overdub records forward at normal speed, so it is blocked while
|
||||||
|
/// Reverse or Half-Speed is engaged (the write head can't follow a backward or slowed play-head).
|
||||||
|
private func toggleOverdub() {
|
||||||
|
guard phase == .playing else { return }
|
||||||
|
if overdubbing {
|
||||||
|
overdubbing = false
|
||||||
|
} else {
|
||||||
|
guard reverse < 0.5, halfSpeed < 0.5 else { return }
|
||||||
|
overdubbing = true
|
||||||
|
}
|
||||||
|
updateOverdubGate()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func startPlayback() {
|
||||||
|
overdubRecorder?.requestReset() // realign the write head to the top
|
||||||
|
isPlaying = 1.0
|
||||||
|
stoppedIndicator = 0.0
|
||||||
|
overdubbing = false
|
||||||
|
phase = .playing // set before updateOverdubGate so the LED reads "playing"
|
||||||
|
updateOverdubGate()
|
||||||
|
playTrigger = 1.0 // rising edge resets the play-head to frame 0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resumes playback from the stopped state.
|
||||||
|
private func resumePlayback() {
|
||||||
|
guard phase == .stopped, masterLength > 0 else { return }
|
||||||
|
startPlayback()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Halts playback; recorded content is retained (resume via Record).
|
||||||
|
public func stopPlayback() {
|
||||||
|
guard phase == .playing else { return }
|
||||||
|
overdubbing = false
|
||||||
|
updateOverdubGate()
|
||||||
|
isPlaying = 0.0
|
||||||
|
playTrigger = 0.0 // rearm the play-head reset edge
|
||||||
|
recordIndicator = 0.0
|
||||||
|
stoppedIndicator = 1.0
|
||||||
|
phase = .stopped
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the recorded loop and returns to the empty state.
|
||||||
|
public func clearLoop() {
|
||||||
|
masterRecorder?.run = 0.0
|
||||||
|
masterRecorder?.requestReset()
|
||||||
|
overdubRecorder?.requestReset()
|
||||||
|
isPlaying = 0.0
|
||||||
|
if let loopBuffer: LyrebirdBuffer = buffer {
|
||||||
|
loopBuffer.clear()
|
||||||
|
loopBuffer.setLoopLength(loopBuffer.count)
|
||||||
|
}
|
||||||
|
masterLength = 0
|
||||||
|
overdubbing = false
|
||||||
|
playTrigger = 0.0
|
||||||
|
recordIndicator = 0.0
|
||||||
|
stoppedIndicator = 0.0
|
||||||
|
updateOverdubGate()
|
||||||
|
phase = .empty
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets to the empty state when the engine stops — a stopped engine can't keep a loop running.
|
||||||
|
public override func engineDidStop() {
|
||||||
|
clearLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resets before this instance is discarded on a rig teardown.
|
||||||
|
public override func rigWillTeardown() {
|
||||||
|
clearLoop()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Helpers
|
||||||
|
|
||||||
|
private func updateOverdubGate() {
|
||||||
|
overdubGate.value = overdubbing ? 1.0 : 0.0
|
||||||
|
recordIndicator = (phase == .recording || overdubbing) ? 1.0 : 0.0
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Clears the generator references and returns the transport to empty, so a graph rebuild
|
||||||
|
/// (`build()` re-run) starts fresh. Called at the top of ``effect(_:)``.
|
||||||
|
private func resetForRebuild() {
|
||||||
|
buffer = nil
|
||||||
|
player = nil
|
||||||
|
masterRecorder = nil
|
||||||
|
overdubRecorder = nil
|
||||||
|
overdubGate = ParameterNode(0.0)
|
||||||
|
phase = .empty
|
||||||
|
overdubbing = false
|
||||||
|
masterLength = 0
|
||||||
|
isPlaying = 0.0
|
||||||
|
playTrigger = 0.0
|
||||||
|
recordIndicator = 0.0
|
||||||
|
stoppedIndicator = 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,154 @@
|
|||||||
|
// VibePedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Photocell "vibe" pedal: four staggered all-pass stages swept by one shared LFO.
|
||||||
|
///
|
||||||
|
/// Signal chain (inside `effect(_:)`):
|
||||||
|
/// ```
|
||||||
|
/// dry → RBJAllPass(freq₀(t)) → RBJAllPass(freq₁(t)) → RBJAllPass(freq₂(t)) → RBJAllPass(freq₃(t)) → wet
|
||||||
|
/// out = wet·wetAmount + dry·dryAmount (mode: chorus blends dry+wet, vibrato is wet only)
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// Unlike a phaser (evenly-spaced stages producing symmetric notches), the vibe cascades all-pass
|
||||||
|
/// stages at **staggered** centre frequencies, so the phase relationships between stages produce the
|
||||||
|
/// characteristic uneven, vocal throb. A single low-frequency sine modulates every stage's centre
|
||||||
|
/// frequency together; the `intensity` knob scales the sweep depth and the `speed` knob sets the LFO
|
||||||
|
/// rate. In *chorus* mode the swept signal is blended 50/50 with the dry signal (comb-filter throb);
|
||||||
|
/// in *vibrato* mode only the swept (phase-modulated) signal passes, for a pitch-vibrato-like warble.
|
||||||
|
///
|
||||||
|
/// The bypass switching is handled by the `Pedal` base class. The base `mix` is fixed fully wet — the
|
||||||
|
/// chorus/vibrato dry blend is handled internally so the two modes behave correctly.
|
||||||
|
///
|
||||||
|
/// ## Parameters
|
||||||
|
///
|
||||||
|
/// Inherits `bypass` and `level` from `Pedal`, plus:
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - speed: LFO sweep rate in Hz. Range `[0.1, 12.0]`. Defaults to `3.0`.
|
||||||
|
/// - intensity: Sweep depth as a fraction of each stage's centre frequency. Range `[0, 0.7]`.
|
||||||
|
/// Defaults to `0.5`.
|
||||||
|
/// - mode: `0` = chorus (dry + swept), `1` = vibrato (swept only). Defaults to chorus.
|
||||||
|
public final class VibePedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Throbbing photocell vibe — swirling chorus and warbling pitch-vibrato motion."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// LFO sweep rate in Hz. Range [0.1, 12.0].
|
||||||
|
@UIParam public var speed: Double = 3.0
|
||||||
|
|
||||||
|
/// Sweep depth as a fraction of each stage's centre frequency. Range [0, 0.7].
|
||||||
|
@UIParam public var intensity: Double = 0.5
|
||||||
|
|
||||||
|
/// Mode select: `0` = chorus (dry + swept), `1` = vibrato (swept only).
|
||||||
|
@UIParam public var mode: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Default wet/dry blend — fully wet; the chorus/vibrato dry mix is handled inside `effect`.
|
||||||
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
|
/// Q for each all-pass stage. Gentle phase transition for a smooth, vocal vibe (not sharp notches).
|
||||||
|
private let vibeQ: Double = 0.6
|
||||||
|
|
||||||
|
/// Staggered all-pass stage centre frequencies in Hz. Unequal spacing is what distinguishes the
|
||||||
|
/// vibe's uneven throb from an evenly-spaced phaser.
|
||||||
|
private let stageCenterFreqs: [Double] = [300.0, 620.0, 1300.0, 2200.0]
|
||||||
|
|
||||||
|
/// `mode` value selecting chorus (dry + swept).
|
||||||
|
private let modeChorusValue: Double = 0.0
|
||||||
|
|
||||||
|
/// `mode` value selecting vibrato (swept only).
|
||||||
|
private let modeVibratoValue: Double = 1.0
|
||||||
|
|
||||||
|
/// Wet gain at chorus mode (`mode == 0`); the swept signal sits 50/50 with dry.
|
||||||
|
private let chorusWetGain: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - UI knobs
|
||||||
|
|
||||||
|
/// Speed knob range in Hz (LFO sweep rate).
|
||||||
|
private let speedRange: ClosedRange<Double> = 0.1 ... 12.0
|
||||||
|
|
||||||
|
/// Intensity knob range (sweep depth fraction). Capped below `1.0` so a stage's swept frequency
|
||||||
|
/// never collapses toward `0 Hz` at the bottom of the sweep.
|
||||||
|
private let intensityRange: ClosedRange<Double> = 0.0 ... 0.7
|
||||||
|
|
||||||
|
public override var tempoSyncableParams: [TempoSyncableParam] {
|
||||||
|
[
|
||||||
|
TempoSyncableParam(key: "speed", label: "Speed", node: $speed, kind: .rate, range: speedRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Speed", node: $speed, range: speedRange),
|
||||||
|
PedalKnob(label: "Intensity", node: $intensity, range: intensityRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
public override var effectSwitches: [PedalSwitch] {
|
||||||
|
[
|
||||||
|
PedalSwitch(
|
||||||
|
label: "Mode",
|
||||||
|
node: $mode,
|
||||||
|
options: [
|
||||||
|
PedalSwitch.Option(title: "Chorus", value: modeChorusValue),
|
||||||
|
PedalSwitch.Option(title: "Vibrato", value: modeVibratoValue),
|
||||||
|
]
|
||||||
|
),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a vibe pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the processed output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Vibe",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: VibePedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
/// Cascades four staggered all-pass stages swept by a shared sine LFO, then blends per mode.
|
||||||
|
///
|
||||||
|
/// - Parameter dry: Dry mono input signal.
|
||||||
|
/// - Returns: Wet mono vibe output.
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// One shared low-frequency sine drives every stage: ±1 scaled by intensity gives the sweep.
|
||||||
|
let lfo: any ValidGeneratorInput = OscSin.Audio(freq: $speed)
|
||||||
|
let sweep: any ValidGeneratorInput = lfo * $intensity // ±intensity
|
||||||
|
|
||||||
|
// Cascade the stages. Each stage's centre frequency is centre·(1 + sweep) = centre + centre·sweep.
|
||||||
|
var signal: any ValidGeneratorInput = dry
|
||||||
|
for center: Double in stageCenterFreqs {
|
||||||
|
let stageFreq: any ValidGeneratorInput = sweep * center + center
|
||||||
|
signal = RBJAllPass.Audio(input: signal, freq: stageFreq, q: vibeQ)
|
||||||
|
}
|
||||||
|
let wet: any ValidGeneratorInput = signal
|
||||||
|
|
||||||
|
// Blend by mode. Chorus (mode 0): 0.5·dry + 0.5·wet. Vibrato (mode 1): wet only.
|
||||||
|
let wetAmount: any ValidGeneratorInput = $mode * chorusWetGain + chorusWetGain // 0.5 → 1.0
|
||||||
|
let dryAmount: any ValidGeneratorInput = (modeVibratoValue - $mode) * chorusWetGain // 0.5 → 0.0
|
||||||
|
return wet * wetAmount + dry * dryAmount
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,237 @@
|
|||||||
|
// WhammyPedal.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
|
||||||
|
/// Expression-pedal pitch shifter in the DigiTech Whammy mould.
|
||||||
|
///
|
||||||
|
/// A rocking **expression pedal** (`position`, heel `0` → toe `1`) sweeps the pitch between two
|
||||||
|
/// endpoints set by the selected `mode`. Modes fall into the three families the hardware groups
|
||||||
|
/// them into:
|
||||||
|
///
|
||||||
|
/// - **Whammy** (pitch-bend, wet only): the pedal bends the note itself from unison at the heel to
|
||||||
|
/// the mode's interval at the toe — octave/two-octave up, octave/two-octave down, the three-octave
|
||||||
|
/// "dive bomb", or a fixed whole-step "drop tune". No dry signal; you hear only the bent pitch.
|
||||||
|
/// - **Harmony** (dry + bent voice): a pitch-shifted voice is layered under the dry note, and the
|
||||||
|
/// pedal morphs that voice's interval between the mode's two stops (e.g. a 5th down at the heel to
|
||||||
|
/// a 4th down at the toe) while the dry note stays put.
|
||||||
|
/// - **Detune** (dry + near-unison voice): a voice a few cents off unison beats against the dry
|
||||||
|
/// note; the pedal sweeps the detune depth from none (heel) to shallow or deep (toe).
|
||||||
|
///
|
||||||
|
/// Each voice is a `PitchShift` — Lyrebird's SC-faithful four-head SOLA shifter, the same
|
||||||
|
/// windowed time-domain overlap-add family the real Whammy used (IVL Technologies' patented
|
||||||
|
/// pitch-synchronous time-domain method, US 5,567,901). The characteristic warble/flutter of large
|
||||||
|
/// bends is inherent to that method and is the Whammy's signature, not a defect. Ratio is
|
||||||
|
/// `2^(semitones/12)`, with `semitones` interpolated live from `position`.
|
||||||
|
///
|
||||||
|
/// The shifter's four heads re-trigger on a fixed grid, which colours the output with a static
|
||||||
|
/// comb filter. A small per-head time dispersion (see `timeDispersion`) plus a window a touch
|
||||||
|
/// over the default (see `windowSize`) break that regularity to reduce the combing while leaving
|
||||||
|
/// the Whammy's grit intact.
|
||||||
|
///
|
||||||
|
/// A single SOLA stage clamps at the engine's `±2`-octave `pitchRatio` range. The three-octave
|
||||||
|
/// **Dive Bomb** reaches `-36` semitones by cascading two stages, each doing half the shift.
|
||||||
|
///
|
||||||
|
/// `position` is an ordinary live parameter, so it can be mapped to a MIDI expression pedal or
|
||||||
|
/// automated like any other knob.
|
||||||
|
///
|
||||||
|
/// ## Knobs
|
||||||
|
/// - `position`: Expression-pedal position in `[0, 1]`. Heel `0` = no bend, toe `1` = full bend.
|
||||||
|
///
|
||||||
|
/// ## Selectors (knob picker)
|
||||||
|
/// - `mode`: Pitch program (snaps to the fixed Whammy / Harmony / Detune list). Changing it
|
||||||
|
/// rebuilds the voice, so it is read as a plain value at build time.
|
||||||
|
public final class WhammyPedal: Pedal {
|
||||||
|
|
||||||
|
/// One-line description shown in the picker and info panel.
|
||||||
|
public override var summary: String {
|
||||||
|
"Expression-pedal pitch bend — octave dives and climbs, a morphing harmony, or a detune."
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Mode table
|
||||||
|
|
||||||
|
/// One Whammy program: the pedal interpolates `semitones` from `heel` (pedal up) to `toe`
|
||||||
|
/// (pedal down). `harmony` keeps the dry note under the shifted voice (Harmony/Detune families);
|
||||||
|
/// `twoStage` cascades two SOLA stages to reach shifts beyond a single stage's ±2-octave clamp.
|
||||||
|
private struct Program {
|
||||||
|
let title: String
|
||||||
|
let heel: Double
|
||||||
|
let toe: Double
|
||||||
|
let harmony: Bool
|
||||||
|
let twoStage: Bool
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The selectable programs, grouped Whammy → Harmony → Detune as on the hardware. Whammy
|
||||||
|
/// programs bend a wet-only voice; Harmony/Detune programs layer a voice under the dry note.
|
||||||
|
/// Intervals mirror the DigiTech Whammy preset chart.
|
||||||
|
private static let programs: [Program] = [
|
||||||
|
// Whammy — wet only, bend from unison to the interval.
|
||||||
|
Program(title: "2 Oct Up", heel: 0.0, toe: 24.0, harmony: false, twoStage: false),
|
||||||
|
Program(title: "Oct Up", heel: 0.0, toe: 12.0, harmony: false, twoStage: false),
|
||||||
|
Program(title: "Oct Down", heel: 0.0, toe: -12.0, harmony: false, twoStage: false),
|
||||||
|
Program(title: "2 Oct Down", heel: 0.0, toe: -24.0, harmony: false, twoStage: false),
|
||||||
|
// Dive Bomb drops three octaves; a single SOLA stage clamps at two, so cascade two.
|
||||||
|
Program(title: "Dive Bomb", heel: 0.0, toe: -36.0, harmony: false, twoStage: true),
|
||||||
|
// Drop Tune is a fixed whole-step down — the pedal does not move it.
|
||||||
|
Program(title: "Drop Tune", heel: -2.0, toe: -2.0, harmony: false, twoStage: false),
|
||||||
|
// Harmony — dry note kept, layered voice morphs heel → toe.
|
||||||
|
Program(title: "Oct Up/Dn", heel: 12.0, toe: -12.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "5Dn/4Dn", heel: -7.0, toe: -5.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "4Dn/3Dn", heel: -5.0, toe: -4.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "5Up/7Up", heel: 7.0, toe: 11.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "5Up/6Up", heel: 7.0, toe: 9.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "4Up/5Up", heel: 5.0, toe: 7.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "3Up/4Up", heel: 4.0, toe: 5.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "m3Up/3Up", heel: 3.0, toe: 4.0, harmony: true, twoStage: false),
|
||||||
|
Program(title: "2Up/3Up", heel: 2.0, toe: 4.0, harmony: true, twoStage: false),
|
||||||
|
// Detune — dry note kept, near-unison voice beats against it; pedal sweeps the depth.
|
||||||
|
Program(title: "Detune Shallow", heel: 0.0, toe: 0.07, harmony: true, twoStage: false),
|
||||||
|
Program(title: "Detune Deep", heel: 0.0, toe: 0.20, harmony: true, twoStage: false),
|
||||||
|
]
|
||||||
|
|
||||||
|
// MARK: - Parameters
|
||||||
|
|
||||||
|
/// Expression-pedal position in `[0, 1]`. Heel (`0`) = no bend, toe (`1`) = the mode's full
|
||||||
|
/// interval. Live, so it can be driven by a mapped expression pedal or automation.
|
||||||
|
@UIParam public var position: Double = 0.0
|
||||||
|
|
||||||
|
/// Selected program index into ``programs``. A knob-picker selector; rebuilds on change.
|
||||||
|
@UIParam public var mode: Double = 0.0
|
||||||
|
|
||||||
|
// MARK: - Constants
|
||||||
|
|
||||||
|
/// Pedal manages its own dry/wet internally (per mode), so the base stays fully wet.
|
||||||
|
private static let defaultMix: Double = 1.0
|
||||||
|
|
||||||
|
/// `semitones → ratio` exponent scale: `2^(s/12) = e^(s · ln2/12)`, fed to `Exp.Audio`.
|
||||||
|
private let semitoneToRatioScale: Double = 0.05776226504666215 // ln(2) / 12
|
||||||
|
|
||||||
|
/// Granular pitch-shift window in seconds. Larger = smoother but more latency and sweep lag;
|
||||||
|
/// smaller tracks faster with more grit. Tuned slightly above the SOLA shifter's `0.1` default
|
||||||
|
/// to soften the periodic comb without adding audible lag.
|
||||||
|
private let windowSize: Double = 0.11
|
||||||
|
|
||||||
|
/// Per-head random timing jitter in seconds fed to each `PitchShift` stage. The four SOLA heads
|
||||||
|
/// re-trigger on a fixed grid, and that periodicity colours the shift with a static comb filter;
|
||||||
|
/// dispersing each head's read position breaks the regularity and reduces the combing. Kept
|
||||||
|
/// small so the voice stays tight. Clamped internally to `[0, windowSize]`.
|
||||||
|
private let timeDispersion: Double = 0.02
|
||||||
|
|
||||||
|
/// Fixed PRNG seed for the grain dispersion. With `timeDispersion > 0` the shifter draws random
|
||||||
|
/// per-head jitter; passing an explicit seed (rather than letting `PitchShift` derive one from
|
||||||
|
/// the clock) makes a given pedal setting render identically every time — reproducible audio,
|
||||||
|
/// and tests that can assert exact pitch instead of just "something changed".
|
||||||
|
private let pitchShiftSeed: UInt64 = 0x7A11_90D5_0C7A_1BEE
|
||||||
|
|
||||||
|
/// Seed for the Dive Bomb cascade's second stage. Distinct from ``pitchShiftSeed`` so the two
|
||||||
|
/// stages' dispersion sequences decorrelate instead of jittering in lockstep.
|
||||||
|
private let pitchShiftSeedStage2: UInt64 = 0x51A6_2B0F_3D44_9C17
|
||||||
|
|
||||||
|
/// Per-voice gain in harmony/detune modes, where the dry note and the shifted voice are summed.
|
||||||
|
/// At the heel the shifted voice is near-unison and correlated with the dry note, so the two sum
|
||||||
|
/// coherently — `0.5` per leg caps that worst case at unity, rather than the `1.4×` peak two
|
||||||
|
/// near-full-scale correlated voices would otherwise reach.
|
||||||
|
private let harmonyVoiceGain: Double = 0.5
|
||||||
|
|
||||||
|
/// Factor splitting a cascaded two-stage shift evenly between its stages.
|
||||||
|
private let twoStageSplit: Double = 0.5
|
||||||
|
|
||||||
|
// MARK: - Ranges
|
||||||
|
|
||||||
|
private let positionRange: ClosedRange<Double> = 0.0 ... 1.0
|
||||||
|
|
||||||
|
// MARK: - Knobs
|
||||||
|
|
||||||
|
public override var effectKnobs: [PedalKnob] {
|
||||||
|
[
|
||||||
|
PedalKnob(label: "Pedal", node: $position, range: positionRange),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Selectors
|
||||||
|
|
||||||
|
public override var effectSelectors: [PedalSelectorKnob] {
|
||||||
|
let stops: [PedalSelectorKnob.Stop] = WhammyPedal.programs.enumerated().map { index, program in
|
||||||
|
PedalSelectorKnob.Stop(title: program.title, value: Double(index))
|
||||||
|
}
|
||||||
|
return [
|
||||||
|
// Each program is a different voice topology (interval span + dry blend + stage count),
|
||||||
|
// read at build time — so switching it must rebuild the board, not just write the node.
|
||||||
|
PedalSelectorKnob(label: "Mode", node: $mode, stops: stops, rebuildsOnChange: true),
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Init
|
||||||
|
|
||||||
|
/// Creates a Whammy pedal.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - inputBus: Audio bus index to read the dry input from. Defaults to `0`.
|
||||||
|
/// - outputBus: Audio bus index to write the output to. Defaults to `0`.
|
||||||
|
public init(
|
||||||
|
inputBus: Int = 0,
|
||||||
|
outputBus: Int = 0
|
||||||
|
) {
|
||||||
|
super.init(
|
||||||
|
name: "Whammy",
|
||||||
|
inputBus: inputBus,
|
||||||
|
outputBus: outputBus,
|
||||||
|
initialMix: WhammyPedal.defaultMix
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Effect
|
||||||
|
|
||||||
|
public override func effect(_ dry: any ValidGeneratorInput) -> any ValidGeneratorInput {
|
||||||
|
// `mode` is read as a plain value at build time; the board rebuilds when it changes (the
|
||||||
|
// voice topology — interval span, dry blend, stage count — is fixed per program).
|
||||||
|
// `position` stays live and sweeps the bend within the program.
|
||||||
|
let index: Int = min(max(0, Int(mode.rounded())), WhammyPedal.programs.count - 1)
|
||||||
|
let program: Program = WhammyPedal.programs[index]
|
||||||
|
|
||||||
|
// semitones = heel + position · (toe − heel), interpolated live from the pedal position.
|
||||||
|
let span: Double = program.toe - program.heel
|
||||||
|
let semitones: any ValidGeneratorInput = ($position * span) + program.heel
|
||||||
|
|
||||||
|
if program.twoStage {
|
||||||
|
// Beyond one SOLA stage's ±2-octave ratio clamp (the 3-octave Dive Bomb): cascade two
|
||||||
|
// stages, each shifting half, so the net shift reaches the full interval.
|
||||||
|
let half: any ValidGeneratorInput = semitones * twoStageSplit
|
||||||
|
let stage1: PitchShift.Audio = PitchShift.Audio(
|
||||||
|
input: dry,
|
||||||
|
pitchRatio: Exp.Audio(half * semitoneToRatioScale),
|
||||||
|
windowSize: windowSize,
|
||||||
|
timeDispersion: timeDispersion,
|
||||||
|
seed: pitchShiftSeed
|
||||||
|
)
|
||||||
|
let stage2: PitchShift.Audio = PitchShift.Audio(
|
||||||
|
input: stage1,
|
||||||
|
pitchRatio: Exp.Audio(half * semitoneToRatioScale),
|
||||||
|
windowSize: windowSize,
|
||||||
|
timeDispersion: timeDispersion,
|
||||||
|
seed: pitchShiftSeedStage2
|
||||||
|
)
|
||||||
|
return stage2
|
||||||
|
}
|
||||||
|
|
||||||
|
let shifted: PitchShift.Audio = PitchShift.Audio(
|
||||||
|
input: dry,
|
||||||
|
pitchRatio: Exp.Audio(semitones * semitoneToRatioScale),
|
||||||
|
windowSize: windowSize,
|
||||||
|
timeDispersion: timeDispersion,
|
||||||
|
seed: pitchShiftSeed
|
||||||
|
)
|
||||||
|
|
||||||
|
if program.harmony {
|
||||||
|
// Harmony/Detune: dry note stays, shifted voice layered under it. Both legs attenuated
|
||||||
|
// so the sum of two near-full-scale voices stays near unity rather than peaking toward 2.
|
||||||
|
return (dry * harmonyVoiceGain) + (shifted * harmonyVoiceGain)
|
||||||
|
}
|
||||||
|
// Whammy: the bent pitch replaces the dry note entirely.
|
||||||
|
return shifted
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
// ChainRouterState.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
/// Serialisable snapshot of one ``ChainRouter`` — its two linear board chains and its blend state.
|
||||||
|
///
|
||||||
|
/// A router splits one input to two independent boards and blends their outputs. Its branches are
|
||||||
|
/// built linearly (via ``ChainRouter/addToA(_:)`` / ``ChainRouter/addToB(_:)``), so each is captured
|
||||||
|
/// as a flat list of ``PedalState``. The splitter's two branch-enable levels capture the A / B / both
|
||||||
|
/// selection (and any continuous blend between them); the merger's two levels capture the output mix.
|
||||||
|
///
|
||||||
|
/// Persisted as part of ``ShoeGazeState/routers`` so a routed multi-board rig survives save / load.
|
||||||
|
///
|
||||||
|
/// > Note: The router's output-stage master gain (`masterGainNode`) is intentionally not captured,
|
||||||
|
/// > matching the existing behaviour for a plain board's `masterGainNode` in `BoardState` — output
|
||||||
|
/// > level is treated as a live mix control, not part of the saved rig.
|
||||||
|
public struct ChainRouterState: Codable, Equatable {
|
||||||
|
|
||||||
|
/// Pedals on board A (the first branch), in chain order.
|
||||||
|
public let boardA: [PedalState]
|
||||||
|
|
||||||
|
/// Pedals on board B (the second branch), in chain order.
|
||||||
|
public let boardB: [PedalState]
|
||||||
|
|
||||||
|
/// Splitter branch-A enable level in `[0, 1]`. `1` = A audible, `0` = A muted.
|
||||||
|
public let branchA: Double
|
||||||
|
|
||||||
|
/// Splitter branch-B enable level in `[0, 1]`. `1` = B audible, `0` = B muted.
|
||||||
|
public let branchB: Double
|
||||||
|
|
||||||
|
/// Merger board-A output level in `[0, 1]`.
|
||||||
|
public let mergerLevelA: Double
|
||||||
|
|
||||||
|
/// Merger board-B output level in `[0, 1]`.
|
||||||
|
public let mergerLevelB: Double
|
||||||
|
|
||||||
|
/// Creates a router snapshot.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - boardA: Board A's pedals in chain order.
|
||||||
|
/// - boardB: Board B's pedals in chain order.
|
||||||
|
/// - branchA: Splitter branch-A enable level `[0, 1]`.
|
||||||
|
/// - branchB: Splitter branch-B enable level `[0, 1]`.
|
||||||
|
/// - mergerLevelA: Merger board-A output level `[0, 1]`.
|
||||||
|
/// - mergerLevelB: Merger board-B output level `[0, 1]`.
|
||||||
|
public init(
|
||||||
|
boardA: [PedalState],
|
||||||
|
boardB: [PedalState],
|
||||||
|
branchA: Double,
|
||||||
|
branchB: Double,
|
||||||
|
mergerLevelA: Double,
|
||||||
|
mergerLevelB: Double
|
||||||
|
) {
|
||||||
|
self.boardA = boardA
|
||||||
|
self.boardB = boardB
|
||||||
|
self.branchA = branchA
|
||||||
|
self.branchB = branchB
|
||||||
|
self.mergerLevelA = mergerLevelA
|
||||||
|
self.mergerLevelB = mergerLevelB
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
// FactoryRig.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// A single built-in starter rig: a named, described pedal chain shipped with the app and seeded
|
||||||
|
/// into a fresh rig library on first launch.
|
||||||
|
///
|
||||||
|
/// A `FactoryRig` is a *builder*, not a stored snapshot. Its ``build`` closure constructs the chain
|
||||||
|
/// against a live ``ShoeGaze`` session using the concrete pedal editing API, so the recipe is
|
||||||
|
/// type-checked against the real pedal parameters at compile time — a renamed pedal control breaks
|
||||||
|
/// the build (a compile error) rather than silently corrupting a hand-written JSON preset. The
|
||||||
|
/// builder is run once at seed time (see ``FactoryRigLibrary/makeEntries(makeSession:)``), captured
|
||||||
|
/// to a ``RigEntry`` via ``ShoeGaze/captureEntry(name:id:)``, and thereafter behaves exactly like a
|
||||||
|
/// user-saved rig.
|
||||||
|
///
|
||||||
|
/// The rig names and blurbs are deliberately descriptive of the *sound*, not any trademarked pedal,
|
||||||
|
/// amplifier, or artist; a blurb may nod at the era or style a tone evokes, but a factory rig is
|
||||||
|
/// never presented as a named product or a specific performer's endorsed setup.
|
||||||
|
public struct FactoryRig: Identifiable, Sendable {
|
||||||
|
|
||||||
|
/// Stable identifier for this rig.
|
||||||
|
///
|
||||||
|
/// Fixed per rig (a literal, not freshly generated) so re-seeding an already-populated library
|
||||||
|
/// overwrites the same entry in place rather than creating a duplicate — `RigLibraryStore.save`
|
||||||
|
/// keys on the entry `id`.
|
||||||
|
public let id: UUID
|
||||||
|
|
||||||
|
/// Human-readable rig name shown in the picker and used as the saved ``RigEntry`` name.
|
||||||
|
public let name: String
|
||||||
|
|
||||||
|
/// One- or two-sentence, user-facing description of the sound and how to play it. Shown as the
|
||||||
|
/// picker subtitle / info blurb. Descriptive of the tone only — never a trademarked product or
|
||||||
|
/// an artist endorsement.
|
||||||
|
public let blurb: String
|
||||||
|
|
||||||
|
/// Sonic family this rig belongs to, for grouping in a picker. Presentational only.
|
||||||
|
public let category: FactoryRigCategory
|
||||||
|
|
||||||
|
/// How this rig builds its graph at seed time.
|
||||||
|
public let build: FactoryRigBuild
|
||||||
|
|
||||||
|
/// Creates a single-board factory rig.
|
||||||
|
///
|
||||||
|
/// The `build` closure receives a fresh, empty ``PedalBoard`` (already returned by
|
||||||
|
/// `session.addBoard()`) and appends pedals to it. Do **not** call `finalizeBoard` /
|
||||||
|
/// `captureEntry` here — the seeding driver owns that lifecycle.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
|
||||||
|
/// - name: Rig name (picker title + saved entry name).
|
||||||
|
/// - blurb: User-facing description of the sound.
|
||||||
|
/// - category: Sonic family for picker grouping.
|
||||||
|
/// - build: Chain-building closure run against a fresh, empty board at seed time.
|
||||||
|
public init(
|
||||||
|
id: UUID,
|
||||||
|
name: String,
|
||||||
|
blurb: String,
|
||||||
|
category: FactoryRigCategory,
|
||||||
|
build: @escaping @MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void
|
||||||
|
) {
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
self.blurb = blurb
|
||||||
|
self.category = category
|
||||||
|
self.build = .singleBoard(build)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a session-scoped factory rig that builds its own boards and/or routers.
|
||||||
|
///
|
||||||
|
/// Use this for rigs the single-board form can't express — e.g. a two-board signal split via
|
||||||
|
/// ``ShoeGaze/makeChainRouter()``. The `sessionBuild` closure gets the whole session and owns the
|
||||||
|
/// full lifecycle for what it creates: it must call `addBoard`/`finalizeBoard` (for plain boards)
|
||||||
|
/// and/or `makeChainRouter`/`addToA`/`addToB`/`finalize` (for routers) itself. Do **not** call
|
||||||
|
/// `captureEntry` here — the seeding driver owns that.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
|
||||||
|
/// - name: Rig name (picker title + saved entry name).
|
||||||
|
/// - blurb: User-facing description of the sound.
|
||||||
|
/// - category: Sonic family for picker grouping.
|
||||||
|
/// - sessionBuild: Graph-building closure run against the session at seed time.
|
||||||
|
public init(
|
||||||
|
id: UUID,
|
||||||
|
name: String,
|
||||||
|
blurb: String,
|
||||||
|
category: FactoryRigCategory,
|
||||||
|
sessionBuild: @escaping @MainActor (_ session: ShoeGaze) throws -> Void
|
||||||
|
) {
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
self.blurb = blurb
|
||||||
|
self.category = category
|
||||||
|
self.build = .session(sessionBuild)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a factory rig from a pre-captured ``ShoeGazeState``.
|
||||||
|
///
|
||||||
|
/// The rig's content is the supplied state verbatim — used for a complex, hand-authored rig
|
||||||
|
/// captured from the app. Seeding builds the entry directly from `state` (no live session).
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - id: Stable identifier (a fixed literal per rig — see ``id``).
|
||||||
|
/// - name: Rig name (picker title + saved entry name).
|
||||||
|
/// - blurb: User-facing description of the sound.
|
||||||
|
/// - category: Sonic family for picker grouping.
|
||||||
|
/// - state: The captured rig content to ship.
|
||||||
|
@MainActor
|
||||||
|
public init(
|
||||||
|
id: UUID,
|
||||||
|
name: String,
|
||||||
|
blurb: String,
|
||||||
|
category: FactoryRigCategory,
|
||||||
|
state: ShoeGazeState
|
||||||
|
) {
|
||||||
|
self.id = id
|
||||||
|
self.name = name
|
||||||
|
self.blurb = blurb
|
||||||
|
self.category = category
|
||||||
|
self.build = .state({ state })
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
// FactoryRigBuild.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
/// How a ``FactoryRig`` builds its graph at seed time.
|
||||||
|
public enum FactoryRigBuild: Sendable {
|
||||||
|
|
||||||
|
/// Appends pedals to a single pre-made, empty board; the seeding driver calls `addBoard` before
|
||||||
|
/// and `finalizeBoard` after.
|
||||||
|
case singleBoard(@MainActor (_ session: ShoeGaze, _ board: PedalBoard) throws -> Void)
|
||||||
|
|
||||||
|
/// Builds the whole graph against the session (boards and/or routers), owning its own
|
||||||
|
/// `addBoard`/`finalizeBoard` and `makeChainRouter`/`finalize` lifecycle.
|
||||||
|
case session(@MainActor (_ session: ShoeGaze) throws -> Void)
|
||||||
|
|
||||||
|
/// Ships a pre-captured ``ShoeGazeState`` directly — the entry is built from it with no live
|
||||||
|
/// session. Use for a complex, hand-authored rig captured from the app, where transcribing the
|
||||||
|
/// exact `PedalState` arrays (mix, sliders, selectors, advanced values) is more faithful than
|
||||||
|
/// re-deriving them through typed setters. The closure returns the state so the case stays
|
||||||
|
/// `Sendable` without requiring `ShoeGazeState` itself to be `Sendable`.
|
||||||
|
case state(@MainActor () -> ShoeGazeState)
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
// FactoryRigCategory.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// Broad sonic grouping for a built-in ``FactoryRig``.
|
||||||
|
///
|
||||||
|
/// Purely presentational: the category lets a rig picker cluster the shipped starter rigs into
|
||||||
|
/// recognisable families ("Shoegaze Walls", "Dreampop", …). It is **not** persisted in the saved
|
||||||
|
/// ``RigEntry`` — a recalled rig is just a board, indistinguishable from a user rig once loaded.
|
||||||
|
public enum FactoryRigCategory: String, CaseIterable, Sendable {
|
||||||
|
|
||||||
|
/// Dense fuzz-and-reverb "wall of sound" textures.
|
||||||
|
case shoegazeWalls = "Shoegaze Walls"
|
||||||
|
|
||||||
|
/// Lush, clean, chorused and delayed dream-pop voices.
|
||||||
|
case dreamPop = "Dreampop"
|
||||||
|
|
||||||
|
/// Classic overdrive / fuzz / wah lead and rhythm tones.
|
||||||
|
case classic = "Classic"
|
||||||
|
|
||||||
|
/// Slow, evolving, reverb-heavy ambient beds.
|
||||||
|
case ambient = "Ambient"
|
||||||
|
|
||||||
|
/// Lo-fi, bit-crushed, and otherwise experimental noise textures.
|
||||||
|
case experimental = "Experimental"
|
||||||
|
|
||||||
|
/// Human-readable name shown as a section header in a rig picker.
|
||||||
|
public var displayName: String { rawValue }
|
||||||
|
}
|
||||||
@@ -0,0 +1,842 @@
|
|||||||
|
// FactoryRigLibrary.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
|
// MARK: - Typed board-building helper
|
||||||
|
|
||||||
|
extension PedalBoard {
|
||||||
|
|
||||||
|
/// Constructs a concrete pedal, applies `configure` to its typed parameters, and appends it to
|
||||||
|
/// the end of the chain.
|
||||||
|
///
|
||||||
|
/// This is the building block for ``FactoryRig`` recipes: because `configure` receives the
|
||||||
|
/// concrete pedal type, every parameter it touches (`$0.fuzz`, `$0.time`, …) is checked by the
|
||||||
|
/// compiler against the real pedal API — a renamed control is a build error, not a silently
|
||||||
|
/// broken preset. Bus wiring is handled by ``add(_:after:)``.
|
||||||
|
///
|
||||||
|
/// - Parameters:
|
||||||
|
/// - pedal: A freshly-constructed pedal (its default buses are overwritten by the board).
|
||||||
|
/// - configure: Sets the pedal's parameters before it is inserted.
|
||||||
|
/// - Returns: The same pedal, now wired into the chain.
|
||||||
|
/// - Throws: `BusAllocatorError.noFreeBus`, `EngineAddError`, or `ShoeGazeError.stereoWidthExceeded`.
|
||||||
|
@discardableResult
|
||||||
|
func append<P: Pedal>(
|
||||||
|
_ pedal: P,
|
||||||
|
configure: (P) -> Void
|
||||||
|
) throws -> P {
|
||||||
|
configure(pedal)
|
||||||
|
try add(pedal)
|
||||||
|
return pedal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
extension ChainRouter {
|
||||||
|
|
||||||
|
/// Constructs a concrete pedal, applies `configure`, and appends it to board A of the router.
|
||||||
|
///
|
||||||
|
/// The concrete-type `configure` closure keeps every parameter compile-checked, exactly like
|
||||||
|
/// ``PedalBoard/append(_:configure:)``. Uses ``addToA(_:)`` so ``finalize()`` ordering stays correct.
|
||||||
|
@discardableResult
|
||||||
|
func appendToA<P: Pedal>(_ pedal: P, configure: (P) -> Void) throws -> P {
|
||||||
|
configure(pedal)
|
||||||
|
try addToA(pedal)
|
||||||
|
return pedal
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Constructs a concrete pedal, applies `configure`, and appends it to board B of the router.
|
||||||
|
@discardableResult
|
||||||
|
func appendToB<P: Pedal>(_ pedal: P, configure: (P) -> Void) throws -> P {
|
||||||
|
configure(pedal)
|
||||||
|
try addToB(pedal)
|
||||||
|
return pedal
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Factory rig catalog
|
||||||
|
|
||||||
|
/// The built-in starter rigs shipped with the app and seeded into an empty rig library on first
|
||||||
|
/// launch.
|
||||||
|
///
|
||||||
|
/// Each entry is a ``FactoryRig`` — a compile-checked builder, not a stored JSON blob. Call
|
||||||
|
/// ``makeEntries(makeSession:)`` at seed time to materialise them into ``RigEntry`` snapshots.
|
||||||
|
///
|
||||||
|
/// Rig names and blurbs describe the *sound*; a blurb may reference an era or style but never a
|
||||||
|
/// trademarked product or a specific artist's endorsed setup.
|
||||||
|
@MainActor
|
||||||
|
public enum FactoryRigLibrary {
|
||||||
|
|
||||||
|
/// Catalog seed version. Bump this whenever the shipped starter rigs change — new rigs added, or
|
||||||
|
/// an existing rig's definition corrected — so launch catch-up re-runs on already-populated
|
||||||
|
/// libraries and refreshes every starter to its current form. Within a single version the marker
|
||||||
|
/// only advances once, so a starter the user deletes stays deleted until the next bump.
|
||||||
|
public static let seedVersion: Int = 4
|
||||||
|
|
||||||
|
/// Stable ids of every built-in rig, for detecting whether a library entry is a factory rig.
|
||||||
|
///
|
||||||
|
/// Because factory rigs are seeded with their fixed ``FactoryRig/id``, an entry recalled from the
|
||||||
|
/// library can be identified as shipped-vs-user by id membership here. Callers use this to guard
|
||||||
|
/// destructive actions (e.g. warn before overwriting a starter rig).
|
||||||
|
public static let factoryIDs: Set<UUID> = Set(all.map { $0.id })
|
||||||
|
|
||||||
|
/// Whether `id` belongs to a shipped factory rig.
|
||||||
|
///
|
||||||
|
/// - Parameter id: A ``RigEntry/id`` from the rig library.
|
||||||
|
/// - Returns: `true` if the entry is one of the built-in starter rigs.
|
||||||
|
public static func isFactory(_ id: UUID) -> Bool {
|
||||||
|
factoryIDs.contains(id)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The ``FactoryRigCategory`` of the shipped rig with this id, or `nil` for a user rig.
|
||||||
|
///
|
||||||
|
/// - Parameter id: A ``RigEntry/id`` from the rig library.
|
||||||
|
/// - Returns: The rig's category, or `nil` if `id` is not a factory rig.
|
||||||
|
public static func category(for id: UUID) -> FactoryRigCategory? {
|
||||||
|
all.first(where: { $0.id == id })?.category
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shipped rigs of a given category, in catalog order.
|
||||||
|
///
|
||||||
|
/// - Parameter category: The category to filter by.
|
||||||
|
/// - Returns: The `FactoryRig`s in `category`, in the order they appear in ``all``.
|
||||||
|
public static func rigs(in category: FactoryRigCategory) -> [FactoryRig] {
|
||||||
|
all.filter { $0.category == category }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Every built-in rig, in the order a picker should present them.
|
||||||
|
public static let all: [FactoryRig] = [
|
||||||
|
glideWall,
|
||||||
|
chorusCathedral,
|
||||||
|
fuzzWahClassic,
|
||||||
|
dottedEighthAnthem,
|
||||||
|
ambientShimmerBed,
|
||||||
|
springReverbSurf,
|
||||||
|
octaveFuzzLead,
|
||||||
|
bitcrushNoiseTexture,
|
||||||
|
funkEnvelopeClav,
|
||||||
|
postRockCrescendo,
|
||||||
|
nashvilleCleanComp,
|
||||||
|
dubDelayThrow,
|
||||||
|
ringModTexture,
|
||||||
|
rockabillySlapback,
|
||||||
|
psychVibeLead,
|
||||||
|
comfortablyNumbLead,
|
||||||
|
doomRiffWall,
|
||||||
|
garciaOBELSplit,
|
||||||
|
]
|
||||||
|
|
||||||
|
// MARK: Shoegaze walls
|
||||||
|
|
||||||
|
/// Dense detuned fuzz + reverse swells + plate bloom.
|
||||||
|
static let glideWall: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Glide Wall"),
|
||||||
|
name: "90s Glide Wall",
|
||||||
|
blurb: "A dense, saturated fuzz wall with reverse swells blooming around it. Hold big open "
|
||||||
|
+ "chords and let the reverse delay and plate wash carry them — early-'90s British "
|
||||||
|
+ "shoegaze territory.",
|
||||||
|
category: .shoegazeWalls
|
||||||
|
) { _, board in
|
||||||
|
try board.append(FuzzPedal()) { p in
|
||||||
|
p.fuzz = 42.0
|
||||||
|
p.tone = 2600.0
|
||||||
|
}
|
||||||
|
try board.append(ChimeTopBoostAmpPedal()) { p in
|
||||||
|
p.gain = 6.5
|
||||||
|
p.bass = 0.6
|
||||||
|
p.mid = 0.4
|
||||||
|
p.treble = 0.7
|
||||||
|
p.cut = 0.3
|
||||||
|
p.brilliant = 1.0
|
||||||
|
}
|
||||||
|
try board.append(ReverseDelayPedal()) { p in
|
||||||
|
p.time = 0.45
|
||||||
|
p.feedback = 0.4
|
||||||
|
}
|
||||||
|
try board.append(PlateReverbPedal()) { p in
|
||||||
|
p.decay = 0.8
|
||||||
|
p.tone = 0.7
|
||||||
|
p.damp = 0.25
|
||||||
|
p.mod = 0.7
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Dreampop
|
||||||
|
|
||||||
|
/// Glassy clean chorus into cascading delay and octave-up shimmer.
|
||||||
|
static let chorusCathedral: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Chorus Cathedral"),
|
||||||
|
name: "Dreampop Chorus Cathedral",
|
||||||
|
blurb: "Glassy clean chorus into cascading delay and octave-up shimmer — lush and "
|
||||||
|
+ "weightless. Play slow arpeggios and let every note ring into the next.",
|
||||||
|
category: .dreamPop
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 3.0
|
||||||
|
p.threshold = -18.0
|
||||||
|
p.ratio = 3.0
|
||||||
|
}
|
||||||
|
try board.append(FullertonReverbAmpPedal()) { p in
|
||||||
|
p.gain = 3.5
|
||||||
|
p.bass = 0.5
|
||||||
|
p.mid = 0.5
|
||||||
|
p.treble = 0.6
|
||||||
|
// Lean on the shimmer reverb downstream rather than the amp's own tank.
|
||||||
|
p.reverbEnabled = 0.0
|
||||||
|
p.vibratoEnabled = 0.0
|
||||||
|
}
|
||||||
|
// Chorus is a mono→stereo widener; keep it the only width change in the chain.
|
||||||
|
try board.append(ChorusPedal()) { p in
|
||||||
|
p.rate = 0.5
|
||||||
|
p.depth = 0.005
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
p.time = 0.4
|
||||||
|
p.feedback = 1.5
|
||||||
|
}
|
||||||
|
try board.append(ShimmerReverbPedal()) { p in
|
||||||
|
// Keep decay + shimmer well below self-oscillation — the loop gain is ~decay + shimmer, so
|
||||||
|
// high values screech into runaway feedback with little or no input.
|
||||||
|
p.size = 0.09
|
||||||
|
p.decay = 0.5
|
||||||
|
p.shimmer = 0.25
|
||||||
|
p.damp = 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Classic
|
||||||
|
|
||||||
|
/// Envelope-wah into thick fuzz and a cranked British stack.
|
||||||
|
static let fuzzWahClassic: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Fuzz Wah Classic"),
|
||||||
|
name: "Fuzz + Wah Classic",
|
||||||
|
blurb: "Envelope-wah into thick fuzz and a cranked British stack — an expressive, vocal "
|
||||||
|
+ "lead voice with a touch of spring. Dig in and the wah opens up under your picking.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(AutoWahPedal()) { p in
|
||||||
|
p.sensitivity = 2.5
|
||||||
|
p.resonance = 4.0
|
||||||
|
p.range = 2600.0
|
||||||
|
}
|
||||||
|
try board.append(FuzzPedal()) { p in
|
||||||
|
p.fuzz = 38.0
|
||||||
|
p.tone = 3200.0
|
||||||
|
}
|
||||||
|
try board.append(BritishPlexiAmpPedal()) { p in
|
||||||
|
p.gain = 8.0
|
||||||
|
p.bass = 0.6
|
||||||
|
p.mid = 0.6
|
||||||
|
p.treble = 0.6
|
||||||
|
p.presence = 0.5
|
||||||
|
p.bright = 1.0
|
||||||
|
}
|
||||||
|
try board.append(SpringReverbPedal()) { p in
|
||||||
|
p.decay = 1.8
|
||||||
|
p.tension = 0.5
|
||||||
|
p.damp = 0.3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Chiming overdrive with a rhythmic dotted-eighth delay.
|
||||||
|
static let dottedEighthAnthem: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Dotted Eighth Anthem"),
|
||||||
|
name: "Dotted-Eighth Anthem",
|
||||||
|
blurb: "Chiming overdrive with a dotted-eighth delay that turns single notes into "
|
||||||
|
+ "cascading patterns — bright, anthemic, arena-sized. Tuned to a dotted eighth at 120 "
|
||||||
|
+ "BPM; play on the beat and let the echoes fill the gaps.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(OverdrivePedal()) { p in
|
||||||
|
p.drive = 5.0
|
||||||
|
p.tone = 4200.0
|
||||||
|
}
|
||||||
|
try board.append(ChimeTopBoostAmpPedal()) { p in
|
||||||
|
p.gain = 5.0
|
||||||
|
p.bass = 0.5
|
||||||
|
p.mid = 0.5
|
||||||
|
p.treble = 0.65
|
||||||
|
p.cut = 0.25
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
// Dotted eighth at 120 BPM = 0.375 s.
|
||||||
|
p.time = 0.375
|
||||||
|
p.feedback = 1.6
|
||||||
|
}
|
||||||
|
try board.append(PlateReverbPedal()) { p in
|
||||||
|
p.decay = 0.6
|
||||||
|
p.tone = 0.8
|
||||||
|
p.damp = 0.3
|
||||||
|
p.mod = 0.4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wet spring reverb and throbbing tremolo through a clean combo.
|
||||||
|
static let springReverbSurf: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Spring Reverb Surf"),
|
||||||
|
name: "Spring-Reverb Surf",
|
||||||
|
blurb: "Drippy spring reverb and throbbing tremolo through a clean Fullerton-style combo — "
|
||||||
|
+ "classic surf voicing. Stab chords and ride the tremolo.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(TremoloPedal()) { p in
|
||||||
|
p.rate = 5.5
|
||||||
|
p.depth = 0.6
|
||||||
|
}
|
||||||
|
try board.append(FullertonReverbAmpPedal()) { p in
|
||||||
|
p.gain = 3.5
|
||||||
|
p.bass = 0.55
|
||||||
|
p.mid = 0.5
|
||||||
|
p.treble = 0.6
|
||||||
|
p.reverb = 0.5
|
||||||
|
p.reverbEnabled = 1.0
|
||||||
|
p.vibratoEnabled = 0.0
|
||||||
|
}
|
||||||
|
try board.append(SpringReverbPedal()) { p in
|
||||||
|
p.decay = 2.2
|
||||||
|
p.tension = 0.6
|
||||||
|
p.damp = 0.25
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Ambient
|
||||||
|
|
||||||
|
/// Long feedback echoes into octave-up shimmer and a cavernous room.
|
||||||
|
static let ambientShimmerBed: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Ambient Shimmer Bed"),
|
||||||
|
name: "Ambient Shimmer Bed",
|
||||||
|
blurb: "Long feedback echoes wash into octave-up shimmer and a cavernous room — a slow, "
|
||||||
|
+ "evolving bed for swells and volume-knob fades. Play sparse and let it bloom.",
|
||||||
|
category: .ambient
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 4.0
|
||||||
|
p.threshold = -20.0
|
||||||
|
p.ratio = 4.0
|
||||||
|
}
|
||||||
|
try board.append(FeedbackDelayPedal()) { p in
|
||||||
|
p.time = 0.6
|
||||||
|
p.feedback = 5.0
|
||||||
|
p.tone = 3500.0
|
||||||
|
}
|
||||||
|
try board.append(ShimmerReverbPedal()) { p in
|
||||||
|
// Long ambient tail, but decay + shimmer kept under ~0.8 so it never self-oscillates; the
|
||||||
|
// room reverb downstream supplies the extra length.
|
||||||
|
p.size = 0.11
|
||||||
|
p.decay = 0.6
|
||||||
|
p.shimmer = 0.2
|
||||||
|
p.damp = 0.5
|
||||||
|
}
|
||||||
|
try board.append(RoomReverbPedal()) { p in
|
||||||
|
p.size = 60.0
|
||||||
|
p.decay = 8.0
|
||||||
|
p.damp = 0.5
|
||||||
|
p.tail = 0.7
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Experimental
|
||||||
|
|
||||||
|
/// A sub-octave layered under saturated fuzz for a thick, synth-like lead.
|
||||||
|
static let octaveFuzzLead: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Octave Fuzz Lead"),
|
||||||
|
name: "Octave-Fuzz Lead",
|
||||||
|
blurb: "A sub-octave layered under saturated fuzz for a thick, synth-like lead, pushed "
|
||||||
|
+ "through a British master-volume voice. Single-note lines turn huge.",
|
||||||
|
category: .experimental
|
||||||
|
) { _, board in
|
||||||
|
try board.append(BassOctaverPedal()) { p in
|
||||||
|
p.oct1 = 0.8
|
||||||
|
p.oct2 = 0.2
|
||||||
|
p.direct = 0.9
|
||||||
|
// Track mode: follow the played pitch rather than octave-flip.
|
||||||
|
p.mode = 1.0
|
||||||
|
}
|
||||||
|
try board.append(FuzzPedal()) { p in
|
||||||
|
p.fuzz = 45.0
|
||||||
|
p.tone = 2800.0
|
||||||
|
}
|
||||||
|
try board.append(BritishMasterAmpPedal()) { p in
|
||||||
|
p.gain = 7.0
|
||||||
|
p.master = 0.5
|
||||||
|
p.bass = 0.55
|
||||||
|
p.mid = 0.6
|
||||||
|
p.treble = 0.55
|
||||||
|
p.presence = 0.4
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
p.time = 0.28
|
||||||
|
p.feedback = 1.4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Gritty sample-rate crushing into runaway feedback delay and a wide room.
|
||||||
|
static let bitcrushNoiseTexture: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Bitcrush Noise Texture"),
|
||||||
|
name: "Bitcrush Noise Texture",
|
||||||
|
blurb: "Gritty sample-rate crushing into runaway feedback delay and a wide room — harsh, "
|
||||||
|
+ "lo-fi and unstable in the best way. Made for drones and glitch textures.",
|
||||||
|
category: .experimental
|
||||||
|
) { _, board in
|
||||||
|
try board.append(BitcrusherPedal()) { p in
|
||||||
|
p.crush = 6.0
|
||||||
|
p.bits = 5.0
|
||||||
|
p.tone = 3200.0
|
||||||
|
}
|
||||||
|
try board.append(FeedbackDelayPedal()) { p in
|
||||||
|
p.time = 0.33
|
||||||
|
p.feedback = 4.0
|
||||||
|
p.tone = 2800.0
|
||||||
|
}
|
||||||
|
try board.append(ReverbPedal()) { p in
|
||||||
|
p.roomSize = 0.8
|
||||||
|
p.damping = 0.4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: More classic voices
|
||||||
|
|
||||||
|
/// Envelope filter into light overdrive and a clean amp — funky, vocal, touch-sensitive.
|
||||||
|
static let funkEnvelopeClav: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Funk Envelope Clav"),
|
||||||
|
name: "Funk Envelope Clav",
|
||||||
|
blurb: "An envelope filter that opens with your picking, into light grit and a clean amp — "
|
||||||
|
+ "funky and vocal, the classic auto-wah clav voice. Play staccato and let your "
|
||||||
|
+ "dynamics work the filter.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(MutantPedal()) { p in
|
||||||
|
p.sensitivity = 3.0
|
||||||
|
p.resonance = 6.0
|
||||||
|
}
|
||||||
|
try board.append(OverdrivePedal()) { p in
|
||||||
|
p.drive = 3.0
|
||||||
|
p.tone = 4500.0
|
||||||
|
}
|
||||||
|
try board.append(JazzCleanAmpPedal()) { p in
|
||||||
|
p.gain = 4.0
|
||||||
|
p.bass = 0.5
|
||||||
|
p.mid = 0.6
|
||||||
|
p.treble = 0.6
|
||||||
|
p.reverb = 0.15
|
||||||
|
p.chorusEnabled = 0.0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compressed clean into slapback echo and spring — bright, springy country/rockabilly.
|
||||||
|
static let nashvilleCleanComp: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Nashville Clean Comp"),
|
||||||
|
name: "Nashville Clean Comp",
|
||||||
|
blurb: "Squashed clean tone into a short slapback and spring reverb — bright, snappy and "
|
||||||
|
+ "articulate, the Nashville country voice. Hybrid-pick and let the compressor even it "
|
||||||
|
+ "out.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 3.0
|
||||||
|
p.threshold = -16.0
|
||||||
|
p.ratio = 4.0
|
||||||
|
}
|
||||||
|
try board.append(FullertonReverbAmpPedal()) { p in
|
||||||
|
p.gain = 3.0
|
||||||
|
p.bass = 0.5
|
||||||
|
p.mid = 0.55
|
||||||
|
p.treble = 0.65
|
||||||
|
p.reverb = 0.3
|
||||||
|
p.reverbEnabled = 1.0
|
||||||
|
p.vibratoEnabled = 0.0
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
// Short slapback.
|
||||||
|
p.time = 0.11
|
||||||
|
p.feedback = 0.3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compressed chime into tight slapback and spring — classic rockabilly.
|
||||||
|
static let rockabillySlapback: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Rockabilly Slapback"),
|
||||||
|
name: "Rockabilly Slapback",
|
||||||
|
blurb: "Compressed chime with a tight tape-style slapback and spring — the rockabilly "
|
||||||
|
+ "bounce. Palm-mute and dig in for the classic '50s snap.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 2.0
|
||||||
|
p.threshold = -14.0
|
||||||
|
p.ratio = 3.0
|
||||||
|
}
|
||||||
|
try board.append(ChimeTopBoostAmpPedal()) { p in
|
||||||
|
p.gain = 4.0
|
||||||
|
p.bass = 0.5
|
||||||
|
p.mid = 0.5
|
||||||
|
p.treble = 0.65
|
||||||
|
p.cut = 0.2
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
// Very short slapback echo.
|
||||||
|
p.time = 0.09
|
||||||
|
p.feedback = 0.25
|
||||||
|
}
|
||||||
|
try board.append(SpringReverbPedal()) { p in
|
||||||
|
p.decay = 1.2
|
||||||
|
p.tension = 0.6
|
||||||
|
p.damp = 0.3
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: More ambient / experimental voices
|
||||||
|
|
||||||
|
/// Overdriven arpeggios into long delay and shimmer — a swelling post-rock build.
|
||||||
|
static let postRockCrescendo: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Post-Rock Crescendo"),
|
||||||
|
name: "Post-Rock Crescendo",
|
||||||
|
blurb: "Warm overdrive into a long delay and octave-up shimmer — a swelling, cinematic "
|
||||||
|
+ "post-rock build. Layer arpeggios and let the wash grow into a crescendo.",
|
||||||
|
category: .ambient
|
||||||
|
) { _, board in
|
||||||
|
try board.append(OverdrivePedal()) { p in
|
||||||
|
p.drive = 6.0
|
||||||
|
p.tone = 4000.0
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
p.time = 0.5
|
||||||
|
p.feedback = 2.5
|
||||||
|
}
|
||||||
|
try board.append(ShimmerReverbPedal()) { p in
|
||||||
|
p.size = 0.1
|
||||||
|
p.decay = 0.55
|
||||||
|
p.shimmer = 0.25
|
||||||
|
p.damp = 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A dub-style feedback echo washing into deep spring — sparse, spacious, delay-forward.
|
||||||
|
static let dubDelayThrow: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Dub Delay Throw"),
|
||||||
|
name: "Dub Delay Throw",
|
||||||
|
blurb: "A long, dark feedback echo washing into deep spring reverb — the dub delay-throw. "
|
||||||
|
+ "Play sparse skanks and ride the feedback for runaway repeats.",
|
||||||
|
category: .ambient
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 2.0
|
||||||
|
p.threshold = -16.0
|
||||||
|
p.ratio = 3.0
|
||||||
|
}
|
||||||
|
try board.append(FeedbackDelayPedal()) { p in
|
||||||
|
p.time = 0.45
|
||||||
|
p.feedback = 6.0
|
||||||
|
p.tone = 2500.0
|
||||||
|
}
|
||||||
|
try board.append(SpringReverbPedal()) { p in
|
||||||
|
p.decay = 2.5
|
||||||
|
p.tension = 0.5
|
||||||
|
p.damp = 0.35
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Ring modulation into delay and reverb — clangorous, inharmonic, otherworldly.
|
||||||
|
static let ringModTexture: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Ring-Mod Texture"),
|
||||||
|
name: "Ring-Mod Texture",
|
||||||
|
blurb: "Ring modulation into delay and a wide room — clangorous, inharmonic and "
|
||||||
|
+ "otherworldly. Try single notes and let the metallic overtones ring out.",
|
||||||
|
category: .experimental
|
||||||
|
) { _, board in
|
||||||
|
try board.append(RingModulatorPedal()) { p in
|
||||||
|
p.frequency = 180.0
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
p.time = 0.3
|
||||||
|
p.feedback = 1.8
|
||||||
|
}
|
||||||
|
try board.append(ReverbPedal()) { p in
|
||||||
|
p.roomSize = 0.75
|
||||||
|
p.damping = 0.4
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Fuzz swirled by a throbbing vibe into delay and plate — vintage psychedelic lead.
|
||||||
|
static let psychVibeLead: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Psych Vibe Lead"),
|
||||||
|
name: "Psychedelic Vibe Lead",
|
||||||
|
blurb: "Thick fuzz swirled by a throbbing photocell vibe, into delay and plate — the "
|
||||||
|
+ "late-'60s psychedelic lead voice. Hold notes and let the vibe pulse underneath.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(FuzzPedal()) { p in
|
||||||
|
p.fuzz = 30.0
|
||||||
|
p.tone = 3000.0
|
||||||
|
}
|
||||||
|
try board.append(VibePedal()) { p in
|
||||||
|
p.speed = 2.5
|
||||||
|
p.intensity = 0.6
|
||||||
|
// Chorus mode: dry + swept, the classic vibe throb.
|
||||||
|
p.mode = 0.0
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
p.time = 0.4
|
||||||
|
p.feedback = 2.0
|
||||||
|
}
|
||||||
|
try board.append(PlateReverbPedal()) { p in
|
||||||
|
p.decay = 0.6
|
||||||
|
p.tone = 0.75
|
||||||
|
p.damp = 0.3
|
||||||
|
p.mod = 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Compressed sustaining fuzz into a dotted delay and shimmer — a soaring, singing lead.
|
||||||
|
static let comfortablyNumbLead: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Comfortably Numb Lead"),
|
||||||
|
name: "Comfortably Numb Lead",
|
||||||
|
blurb: "Compressed, mid-scooped sustain fuzz into a dotted delay and octave-up shimmer — a "
|
||||||
|
+ "soaring, singing lead that holds forever. Bend into long notes and let them bloom.",
|
||||||
|
category: .classic
|
||||||
|
) { _, board in
|
||||||
|
try board.append(CompressorPedal()) { p in
|
||||||
|
p.inputGain = 4.0
|
||||||
|
p.threshold = -18.0
|
||||||
|
p.ratio = 4.0
|
||||||
|
}
|
||||||
|
try board.append(SustainFuzzPedal()) { p in
|
||||||
|
p.sustain = 14.0
|
||||||
|
p.tone = 3000.0
|
||||||
|
p.scoop = 10.0
|
||||||
|
}
|
||||||
|
try board.append(DelayPedal()) { p in
|
||||||
|
// Dotted eighth at ~100 BPM.
|
||||||
|
p.time = 0.45
|
||||||
|
p.feedback = 2.2
|
||||||
|
}
|
||||||
|
try board.append(ShimmerReverbPedal()) { p in
|
||||||
|
p.size = 0.09
|
||||||
|
p.decay = 0.55
|
||||||
|
p.shimmer = 0.25
|
||||||
|
p.damp = 0.5
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sub-octave under a huge scooped fuzz into a cavernous room — heavy, slow doom.
|
||||||
|
static let doomRiffWall: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Doom Riff Wall"),
|
||||||
|
name: "Doom Riff Wall",
|
||||||
|
blurb: "A sub-octave stacked under a huge mid-scooped fuzz, into a cavernous room — crushing, "
|
||||||
|
+ "slow doom. Down-tune, play half-time and let the low end swallow the room.",
|
||||||
|
category: .experimental
|
||||||
|
) { _, board in
|
||||||
|
try board.append(BassOctaverPedal()) { p in
|
||||||
|
p.oct1 = 0.8
|
||||||
|
p.oct2 = 0.3
|
||||||
|
p.direct = 0.9
|
||||||
|
// Track mode: follow the played pitch.
|
||||||
|
p.mode = 1.0
|
||||||
|
}
|
||||||
|
try board.append(SustainFuzzPedal()) { p in
|
||||||
|
p.sustain = 22.0
|
||||||
|
p.tone = 2200.0
|
||||||
|
p.scoop = 6.0
|
||||||
|
}
|
||||||
|
try board.append(RoomReverbPedal()) { p in
|
||||||
|
p.size = 70.0
|
||||||
|
p.decay = 6.0
|
||||||
|
p.damp = 0.55
|
||||||
|
p.tail = 0.7
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: Two-board split
|
||||||
|
|
||||||
|
/// Two boards — a full effects chain and a clean direct path — switched with the board selector.
|
||||||
|
static let garciaOBELSplit: FactoryRig = FactoryRig(
|
||||||
|
id: stableID("Garcia OBEL Split"),
|
||||||
|
name: "Garcia OBEL Clean/Effects Split",
|
||||||
|
blurb: "Two boards, one selector: Board 1 is an effects/lead chain (octave, envelope filter, "
|
||||||
|
+ "overdrive, graphic EQ, phaser, delay, reverb); Board 2 is a fuller direct voice "
|
||||||
|
+ "(overdrive, graphic EQ, compression, reverb). Use the board Solo / Blend control at the "
|
||||||
|
+ "top to switch between them, like an on-board effects loop. In the spirit of a certain "
|
||||||
|
+ "improvising guitarist's late-'80s rig.",
|
||||||
|
category: .classic,
|
||||||
|
// Hand-authored in the app and shipped as a captured state — transcribing the exact pedal
|
||||||
|
// values (mix, graphic-EQ sliders, cab selector, amp sag/bias) is more faithful than
|
||||||
|
// re-deriving them through typed setters. Input source / channel counts are intentionally
|
||||||
|
// omitted so the rig is input-agnostic.
|
||||||
|
state: garciaState
|
||||||
|
)
|
||||||
|
|
||||||
|
/// The shipped Garcia rig content. `static let` so its (default) pedal ids are stable per process,
|
||||||
|
/// keeping seeding deterministic.
|
||||||
|
private static let garciaState: ShoeGazeState = ShoeGazeState(
|
||||||
|
boards: [
|
||||||
|
BoardState(label: "Board 1", pedals: [
|
||||||
|
PedalState(type: "Bass Octaver",
|
||||||
|
knobValues: [0.5, 0, 1, 1, 1], switchValues: [1], bypass: 0),
|
||||||
|
PedalState(type: "Mutant",
|
||||||
|
knobValues: [2.5, 4.45515625, 1, 1], switchValues: [1, 0], bypass: 0),
|
||||||
|
PedalState(type: "Overdrive",
|
||||||
|
knobValues: [5, 4200, 1, 1], bypass: 0),
|
||||||
|
PedalState(type: "Graphic EQ",
|
||||||
|
knobValues: [1, 1],
|
||||||
|
sliderValues: [-4.7786931818181815, -2.214204545454546, 1.552840909090909,
|
||||||
|
1.8536931818181799, -3.3426136363636374, -0.45852272727272947],
|
||||||
|
bypass: 0),
|
||||||
|
PedalState(type: "Phaser",
|
||||||
|
knobValues: [0.4, 0.4, 0.5, 1], bypass: 0),
|
||||||
|
PedalState(type: "Delay",
|
||||||
|
knobValues: [0.35, 1.8, 0.35, 1], bypass: 0),
|
||||||
|
PedalState(type: "Fullerton Reverb",
|
||||||
|
knobValues: [2.5505078125, 0.5, 0.5, 0.6, 0.25, 4, 0, 1, 1],
|
||||||
|
switchValues: [0, 1, 0], selectorValues: [4],
|
||||||
|
advancedValues: [0, 0.5, 0], bypass: 0),
|
||||||
|
]),
|
||||||
|
BoardState(label: "Board 2", pedals: [
|
||||||
|
PedalState(type: "Overdrive",
|
||||||
|
knobValues: [6.54533203125, 4000, 1, 1], bypass: 0),
|
||||||
|
PedalState(type: "Graphic EQ",
|
||||||
|
knobValues: [1, 1],
|
||||||
|
sliderValues: [2.957386363636365, 0, 2.7741477272727266,
|
||||||
|
1.940624999999999, -0.6767045454545446, 0],
|
||||||
|
bypass: 0),
|
||||||
|
PedalState(type: "Compressor",
|
||||||
|
knobValues: [2, -16, 3, 1, 1], switchValues: [0], bypass: 0),
|
||||||
|
PedalState(type: "Fullerton Reverb",
|
||||||
|
knobValues: [5.08, 0.5, 0.5, 0.6, 0.13624999999999998, 4, 0, 1, 1],
|
||||||
|
switchValues: [0, 1, 0], selectorValues: [4],
|
||||||
|
advancedValues: [0, 0.5, 0], bypass: 0),
|
||||||
|
]),
|
||||||
|
],
|
||||||
|
bpm: 120,
|
||||||
|
tempoEnabled: true
|
||||||
|
)
|
||||||
|
|
||||||
|
// MARK: - Seeding
|
||||||
|
|
||||||
|
/// Builds every factory rig into a ``RigEntry`` snapshot suitable for the rig library.
|
||||||
|
///
|
||||||
|
/// Each rig is constructed in a fresh, **never-started** ``ShoeGaze`` session (capturing a rig
|
||||||
|
/// only reads `@UIParam` values — no audio is rendered), captured with the rig's stable `id`, and
|
||||||
|
/// the session is torn down before the next. Because ids are stable, re-running this against an
|
||||||
|
/// already-seeded library overwrites entries in place rather than duplicating them.
|
||||||
|
///
|
||||||
|
/// - Parameter makeSession: Returns a fresh, empty session (typically backed by an offline
|
||||||
|
/// engine). Called once per rig.
|
||||||
|
/// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order.
|
||||||
|
/// - Throws: Any error from session creation, board building, or finalisation.
|
||||||
|
public static func makeEntries(
|
||||||
|
makeSession: @MainActor () throws -> ShoeGaze
|
||||||
|
) throws -> [RigEntry] {
|
||||||
|
var entries: [RigEntry] = []
|
||||||
|
entries.reserveCapacity(all.count)
|
||||||
|
for rig: FactoryRig in all {
|
||||||
|
// A state-backed rig needs no live session — build its entry directly from the state.
|
||||||
|
if case .state(let makeState) = rig.build {
|
||||||
|
entries.append(RigEntry(id: rig.id, name: rig.name, state: makeState()))
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
let session: ShoeGaze = try makeSession()
|
||||||
|
// Tear down on every exit from this iteration, including a throw from a builder, so a
|
||||||
|
// failing rig never leaks its throwaway engine's buses/nodes.
|
||||||
|
defer { session.teardown() }
|
||||||
|
switch rig.build {
|
||||||
|
case .singleBoard(let build):
|
||||||
|
let board: PedalBoard = try session.addBoard()
|
||||||
|
try build(session, board)
|
||||||
|
try session.finalizeBoard(board)
|
||||||
|
case .session(let build):
|
||||||
|
// The builder owns its own board/router lifecycle (addBoard/finalizeBoard,
|
||||||
|
// makeChainRouter/finalize).
|
||||||
|
try build(session)
|
||||||
|
case .state:
|
||||||
|
continue // handled above
|
||||||
|
}
|
||||||
|
entries.append(session.captureEntry(name: rig.name, id: rig.id))
|
||||||
|
}
|
||||||
|
return entries
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds every factory rig using a self-contained offline engine per rig.
|
||||||
|
///
|
||||||
|
/// Convenience over ``makeEntries(makeSession:)`` for callers with no session of their own (the
|
||||||
|
/// first-launch seeding path). Each rig gets a fresh ``NRTDriver``-backed engine that is never
|
||||||
|
/// started — no audio is rendered and no output file is written (the driver only touches disk in
|
||||||
|
/// `start()`), so the temporary URL handed to the driver never comes into existence.
|
||||||
|
///
|
||||||
|
/// - Returns: One ``RigEntry`` per ``all`` rig, in catalog order.
|
||||||
|
/// - Throws: Any error from board building or finalisation.
|
||||||
|
public static func makeEntries() throws -> [RigEntry] {
|
||||||
|
try makeEntries(makeSession: makeOfflineSeedSession)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Block size for the throwaway seeding engine. Matches the framework default; never renders.
|
||||||
|
private static let seedBlockSize: Int = 512
|
||||||
|
|
||||||
|
/// Sample rate for the throwaway seeding engine. Only affects `@UIParam` capture indirectly; no
|
||||||
|
/// audio is produced.
|
||||||
|
private static let seedSampleRate: Double = 44_100.0
|
||||||
|
|
||||||
|
/// Audio bus count for the throwaway seeding engine — generous headroom for the longest chain.
|
||||||
|
private static let seedAudioBusCount: Int = 128
|
||||||
|
|
||||||
|
/// Control bus count for the throwaway seeding engine.
|
||||||
|
private static let seedControlBusCount: Int = 512
|
||||||
|
|
||||||
|
/// Nominal render duration handed to the offline driver. Unused — the engine is never started.
|
||||||
|
private static let seedRenderDuration: Double = 0.05
|
||||||
|
|
||||||
|
/// Creates a fresh, never-started offline ``ShoeGaze`` session for building one factory rig.
|
||||||
|
private static func makeOfflineSeedSession() -> ShoeGaze {
|
||||||
|
let outputURL: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||||
|
let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: seedRenderDuration)
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: seedBlockSize,
|
||||||
|
sampleRate: seedSampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: seedAudioBusCount,
|
||||||
|
numControlBuses: seedControlBusCount,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
return ShoeGaze(engine: engine, inputSource: .testLoop)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Stable identifiers
|
||||||
|
|
||||||
|
/// Deterministic UUID derived from a rig's identity string via two FNV-1a hashes.
|
||||||
|
///
|
||||||
|
/// Gives each rig a stable library id across launches without a hand-written UUID literal, and
|
||||||
|
/// keeps seeding idempotent (same id ⇒ overwrite in place). Not a cryptographic identifier —
|
||||||
|
/// only stability and per-rig uniqueness matter here.
|
||||||
|
static func stableID(_ seed: String) -> UUID {
|
||||||
|
let fnvOffset: UInt64 = 0xcbf2_9ce4_8422_2325
|
||||||
|
let fnvPrime: UInt64 = 0x0000_0100_0000_01b3
|
||||||
|
|
||||||
|
func hash(_ string: String) -> UInt64 {
|
||||||
|
var value: UInt64 = fnvOffset
|
||||||
|
for byte: UInt8 in string.utf8 {
|
||||||
|
value = (value ^ UInt64(byte)) &* fnvPrime
|
||||||
|
}
|
||||||
|
return value
|
||||||
|
}
|
||||||
|
|
||||||
|
let high: UInt64 = hash(seed)
|
||||||
|
let low: UInt64 = hash(seed + "\u{1}salt")
|
||||||
|
|
||||||
|
func byte(_ source: UInt64, _ shift: UInt64) -> UInt8 {
|
||||||
|
UInt8((source >> shift) & 0xFF)
|
||||||
|
}
|
||||||
|
|
||||||
|
let bytes: uuid_t = (
|
||||||
|
byte(high, 56), byte(high, 48), byte(high, 40), byte(high, 32),
|
||||||
|
byte(high, 24), byte(high, 16), byte(high, 8), byte(high, 0),
|
||||||
|
byte(low, 56), byte(low, 48), byte(low, 40), byte(low, 32),
|
||||||
|
byte(low, 24), byte(low, 16), byte(low, 8), byte(low, 0)
|
||||||
|
)
|
||||||
|
return UUID(uuid: bytes)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -92,6 +92,12 @@ extension Pedal {
|
|||||||
/// always applied regardless of any count mismatch. Presets saved before a given control existed
|
/// always applied regardless of any count mismatch. Presets saved before a given control existed
|
||||||
/// carry an empty array for it, leaving those controls at their defaults.
|
/// carry an empty array for it, leaving those controls at their defaults.
|
||||||
///
|
///
|
||||||
|
/// **Pass order is contractual: switches are restored before selectors.** A pedal whose selector
|
||||||
|
/// *set* depends on a switch value (e.g. ``KarplusResonatorPedal``, whose Root note selector
|
||||||
|
/// appears only in the Pitched tuning mode) relies on `tuning` being written in the switch pass
|
||||||
|
/// before `effectSelectors` is re-read in the selector pass, so the mode-dependent selector exists
|
||||||
|
/// to receive its value. Do not reorder these passes without revisiting such pedals.
|
||||||
|
///
|
||||||
/// - Parameter rawState: The state to restore. The `state.type` is not validated against
|
/// - Parameter rawState: The state to restore. The `state.type` is not validated against
|
||||||
/// `displayName` — the caller is responsible for matching types before calling this method.
|
/// `displayName` — the caller is responsible for matching types before calling this method.
|
||||||
public func applyState(_ rawState: PedalState) {
|
public func applyState(_ rawState: PedalState) {
|
||||||
|
|||||||
@@ -66,8 +66,10 @@ public enum PedalRegistry {
|
|||||||
"Reverb": { ReverbPedal() },
|
"Reverb": { ReverbPedal() },
|
||||||
"Modulation": { ModulationPedal() },
|
"Modulation": { ModulationPedal() },
|
||||||
"Fuzz": { FuzzPedal() },
|
"Fuzz": { FuzzPedal() },
|
||||||
|
"Sustain Fuzz": { SustainFuzzPedal() },
|
||||||
"Tremolo": { TremoloPedal() },
|
"Tremolo": { TremoloPedal() },
|
||||||
"Phaser": { PhaserPedal() },
|
"Phaser": { PhaserPedal() },
|
||||||
|
"Script Phaser": { ScriptPhaserPedal() },
|
||||||
"Compressor": { CompressorPedal() },
|
"Compressor": { CompressorPedal() },
|
||||||
"Mutant": { MutantPedal() },
|
"Mutant": { MutantPedal() },
|
||||||
"Auto-Wah": { AutoWahPedal() },
|
"Auto-Wah": { AutoWahPedal() },
|
||||||
@@ -78,12 +80,17 @@ public enum PedalRegistry {
|
|||||||
"Octave Splitter": { OctaveUpSplitterPedal() },
|
"Octave Splitter": { OctaveUpSplitterPedal() },
|
||||||
"Bass Octaver": { BassOctaverPedal() },
|
"Bass Octaver": { BassOctaverPedal() },
|
||||||
"Harmonizer": { HarmonizerPedal() },
|
"Harmonizer": { HarmonizerPedal() },
|
||||||
|
"Whammy": { WhammyPedal() },
|
||||||
|
"Poly Octave": { PolyOctavePedal() },
|
||||||
"Ping-Pong": { PingPongDelayPedal() },
|
"Ping-Pong": { PingPongDelayPedal() },
|
||||||
"Reverse Delay": { ReverseDelayPedal() },
|
"Reverse Delay": { ReverseDelayPedal() },
|
||||||
|
"DL4": { DL4Pedal() },
|
||||||
"Shimmer Reverb": { ShimmerReverbPedal() },
|
"Shimmer Reverb": { ShimmerReverbPedal() },
|
||||||
"Plate Reverb": { PlateReverbPedal() },
|
"Plate Reverb": { PlateReverbPedal() },
|
||||||
"Room Reverb": { RoomReverbPedal() },
|
"Room Reverb": { RoomReverbPedal() },
|
||||||
"Spring Reverb": { SpringReverbPedal() },
|
"Spring Reverb": { SpringReverbPedal() },
|
||||||
|
"Reverse Reverb": { ReverseReverbPedal() },
|
||||||
|
"Granular Reverb": { GranularReverbPedal() },
|
||||||
"Limiter": { LimiterPedal() },
|
"Limiter": { LimiterPedal() },
|
||||||
"Cabinet": { CabinetPedal() },
|
"Cabinet": { CabinetPedal() },
|
||||||
"Noise Gate": { NoiseGatePedal() },
|
"Noise Gate": { NoiseGatePedal() },
|
||||||
@@ -91,6 +98,7 @@ public enum PedalRegistry {
|
|||||||
"Chorus": { ChorusPedal() },
|
"Chorus": { ChorusPedal() },
|
||||||
"Flanger": { FlangerPedal() },
|
"Flanger": { FlangerPedal() },
|
||||||
"Vibrato": { VibratoPedal() },
|
"Vibrato": { VibratoPedal() },
|
||||||
|
"Vibe": { VibePedal() },
|
||||||
"Rotary": { RotaryPedal() },
|
"Rotary": { RotaryPedal() },
|
||||||
"Sustainer": { SustainerPedal() },
|
"Sustainer": { SustainerPedal() },
|
||||||
"Ring Modulator": { RingModulatorPedal() },
|
"Ring Modulator": { RingModulatorPedal() },
|
||||||
@@ -98,7 +106,9 @@ public enum PedalRegistry {
|
|||||||
"Bitcrusher": { BitcrusherPedal() },
|
"Bitcrusher": { BitcrusherPedal() },
|
||||||
"Granulator": { GranulatorPedal() },
|
"Granulator": { GranulatorPedal() },
|
||||||
"Auto Granulator": { AutoGranulatorPedal() },
|
"Auto Granulator": { AutoGranulatorPedal() },
|
||||||
|
"Karplus Resonator": { KarplusResonatorPedal() },
|
||||||
"Looper": { LooperPedal() },
|
"Looper": { LooperPedal() },
|
||||||
|
"Tape Looper": { TapeLooperPedal() },
|
||||||
]
|
]
|
||||||
|
|
||||||
/// Maps a pedal `displayName` that has since been renamed to its current registry key, so rigs
|
/// Maps a pedal `displayName` that has since been renamed to its current registry key, so rigs
|
||||||
|
|||||||
@@ -18,6 +18,16 @@ extension ShoeGaze {
|
|||||||
/// - Returns: A `ShoeGazeState` reflecting the current rig.
|
/// - Returns: A `ShoeGazeState` reflecting the current rig.
|
||||||
public func captureState() -> ShoeGazeState {
|
public func captureState() -> ShoeGazeState {
|
||||||
let boardStates: [BoardState] = boards.map { $0.captureState() }
|
let boardStates: [BoardState] = boards.map { $0.captureState() }
|
||||||
|
let routerStates: [ChainRouterState] = routers.map { router in
|
||||||
|
ChainRouterState(
|
||||||
|
boardA: router.boardA.pedals.map { $0.captureState() },
|
||||||
|
boardB: router.boardB.pedals.map { $0.captureState() },
|
||||||
|
branchA: router.splitter.branchAEnabled,
|
||||||
|
branchB: router.splitter.branchBEnabled,
|
||||||
|
mergerLevelA: router.merger?.levelA ?? 1.0,
|
||||||
|
mergerLevelB: router.merger?.levelB ?? 1.0
|
||||||
|
)
|
||||||
|
}
|
||||||
return ShoeGazeState(
|
return ShoeGazeState(
|
||||||
boards: boardStates,
|
boards: boardStates,
|
||||||
midiMap: midiMap,
|
midiMap: midiMap,
|
||||||
@@ -25,7 +35,10 @@ extension ShoeGaze {
|
|||||||
tempoEnabled: tempoEnabled,
|
tempoEnabled: tempoEnabled,
|
||||||
inputSource: inputSource,
|
inputSource: inputSource,
|
||||||
numInputChannels: engine.numInputChannels,
|
numInputChannels: engine.numInputChannels,
|
||||||
numOutputChannels: engine.numOutputChannels
|
numOutputChannels: engine.numOutputChannels,
|
||||||
|
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
|
||||||
|
// unchanged and byte-identical to one saved before router persistence existed.
|
||||||
|
routers: routerStates.isEmpty ? nil : routerStates
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,9 +107,18 @@ extension ShoeGaze {
|
|||||||
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
|
/// rebuilds every board with the all-or-nothing semantics of ``rebuildAllBoards(from:)``.
|
||||||
///
|
///
|
||||||
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
|
/// - Important: Call with the engine **stopped**, as with ``loadRig(from:)``.
|
||||||
/// - Parameter state: The rig snapshot to restore.
|
/// - Parameters:
|
||||||
|
/// - state: The rig snapshot to restore.
|
||||||
|
/// - keepingCurrentInput: When `true`, the session's current ``inputSource`` is preserved and
|
||||||
|
/// the rig's saved input is ignored — used when the player switches between rigs, so the live
|
||||||
|
/// input (e.g. a plugged-in guitar) doesn't snap back to the test loop a rig was authored
|
||||||
|
/// with. When `false` (the default, used by file open and launch restore), the rig's saved
|
||||||
|
/// input is applied so a saved/loaded rig recreates its authored input. Defaults to `false`.
|
||||||
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
|
/// - Throws: `PresetError.unsupportedVersion` for a too-new snapshot, or any board-build error.
|
||||||
public func loadRig(from state: ShoeGazeState) throws {
|
public func loadRig(
|
||||||
|
from state: ShoeGazeState,
|
||||||
|
keepingCurrentInput: Bool = false
|
||||||
|
) throws {
|
||||||
guard state.version <= presetFormatVersion else {
|
guard state.version <= presetFormatVersion else {
|
||||||
throw PresetError.unsupportedVersion(state.version)
|
throw PresetError.unsupportedVersion(state.version)
|
||||||
}
|
}
|
||||||
@@ -107,11 +129,12 @@ extension ShoeGaze {
|
|||||||
// enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a
|
// enable-live-input flow (rebuild engine to 1 input, then load a rig saved with 0). Apply a
|
||||||
// rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead.
|
// rig's saved layout deliberately via `applyChannelLayout(from:)` / the config UI instead.
|
||||||
|
|
||||||
// Restore the saved input source before rebuilding, since board construction reads it. A
|
// Restore the saved input source before rebuilding, since board construction reads it — unless
|
||||||
// saved live-input channel that no longer exists on this engine falls back to the test loop
|
// the caller is switching rigs (`keepingCurrentInput`), in which case the current input is
|
||||||
// (same guard as reconfigureEngine), so the rebuild's addBoard() can't throw on a stale
|
// kept so the player's live input survives the switch. A saved live-input channel that no
|
||||||
// channel. Absent (older rig) → leave the current input source untouched.
|
// longer exists on this engine falls back to the test loop (same guard as reconfigureEngine),
|
||||||
if let savedInput: InputSource = state.inputSource {
|
// so the rebuild's addBoard() can't throw on a stale channel. Absent (older rig) → untouched.
|
||||||
|
if !keepingCurrentInput, let savedInput: InputSource = state.inputSource {
|
||||||
if case .liveInput(let channel) = savedInput,
|
if case .liveInput(let channel) = savedInput,
|
||||||
channel < 0 || channel >= engine.numInputChannels {
|
channel < 0 || channel >= engine.numInputChannels {
|
||||||
inputSource = .testLoop
|
inputSource = .testLoop
|
||||||
@@ -162,6 +185,9 @@ extension ShoeGaze {
|
|||||||
try rebuildSegments(boardState.segments, into: board)
|
try rebuildSegments(boardState.segments, into: board)
|
||||||
try finalizeBoard(board)
|
try finalizeBoard(board)
|
||||||
}
|
}
|
||||||
|
for routerState: ChainRouterState in snapshot.routers ?? [] {
|
||||||
|
try rebuildRouter(routerState)
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Leave no partial rig behind: tear down whatever was built, then rethrow.
|
// Leave no partial rig behind: tear down whatever was built, then rethrow.
|
||||||
teardown()
|
teardown()
|
||||||
@@ -169,6 +195,32 @@ extension ShoeGaze {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Reconstructs one ``ChainRouter`` from a saved snapshot: creates the router, replays both linear
|
||||||
|
/// branches (skipping unknown pedal types), finalizes, then restores the splitter branch levels
|
||||||
|
/// and merger output levels so the saved A / B / blend selection is preserved.
|
||||||
|
///
|
||||||
|
/// - Parameter state: The router snapshot to reconstruct.
|
||||||
|
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from router construction.
|
||||||
|
private func rebuildRouter(_ state: ChainRouterState) throws {
|
||||||
|
let router: ChainRouter = try makeChainRouter()
|
||||||
|
for pedalState: PedalState in state.boardA {
|
||||||
|
if let pedal: Pedal = makeAndApply(pedalState) {
|
||||||
|
try router.addToA(pedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for pedalState: PedalState in state.boardB {
|
||||||
|
if let pedal: Pedal = makeAndApply(pedalState) {
|
||||||
|
try router.addToB(pedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try router.finalize()
|
||||||
|
// Restore the blend after finalize: the splitter exists from init, the merger only after.
|
||||||
|
router.splitter.branchAEnabled = state.branchA
|
||||||
|
router.splitter.branchBEnabled = state.branchB
|
||||||
|
router.merger?.levelA = state.mergerLevelA
|
||||||
|
router.merger?.levelB = state.mergerLevelB
|
||||||
|
}
|
||||||
|
|
||||||
/// Loads a rig from a JSON preset file and rebuilds the engine graph.
|
/// Loads a rig from a JSON preset file and rebuilds the engine graph.
|
||||||
///
|
///
|
||||||
/// This method:
|
/// This method:
|
||||||
@@ -368,6 +420,19 @@ extension ShoeGaze {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
// Routers recall positionally too: their branch pedals' params and the splitter/merger
|
||||||
|
// blend. Topology (pedal counts/types) is assumed identical for a lightweight recall — a
|
||||||
|
// mismatch is skipped, exactly as for boards. A `rebuildsOnChange` selector inside a router
|
||||||
|
// branch is not handled here (routers have no per-branch rebuild path); use `loadRig(from:)`
|
||||||
|
// for that.
|
||||||
|
for (router, routerState): (ChainRouter, ChainRouterState) in zip(routers, state.routers ?? []) {
|
||||||
|
applyLinearParams(routerState.boardA, to: router.boardA.pedals)
|
||||||
|
applyLinearParams(routerState.boardB, to: router.boardB.pedals)
|
||||||
|
router.splitter.branchAEnabled = routerState.branchA
|
||||||
|
router.splitter.branchBEnabled = routerState.branchB
|
||||||
|
router.merger?.levelA = routerState.mergerLevelA
|
||||||
|
router.merger?.levelB = routerState.mergerLevelB
|
||||||
|
}
|
||||||
// A recall restores each pedal's tempo-sync state but not its derived values (no clock is
|
// 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 —
|
// consulted in `Pedal.applyState`), so recompute them against the rig's current tempo —
|
||||||
// mirroring the full `loadRig(from:)` path.
|
// mirroring the full `loadRig(from:)` path.
|
||||||
@@ -376,6 +441,15 @@ extension ShoeGaze {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Positionally applies pedal parameter snapshots to a live linear pedal chain (e.g. a router
|
||||||
|
/// branch). A position whose live pedal type doesn't match the snapshot is skipped, matching the
|
||||||
|
/// silent-skip semantics of the board recall path.
|
||||||
|
private func applyLinearParams(_ states: [PedalState], to pedals: [Pedal]) {
|
||||||
|
for (pedal, state): (Pedal, PedalState) in zip(pedals, states) where pedal.displayName == state.type {
|
||||||
|
pedal.applyState(state)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Positionally applies segment parameter snapshots to live board segments, including
|
/// Positionally applies segment parameter snapshots to live board segments, including
|
||||||
/// branch pedals and split routing modes. Type or topology mismatches at any position are
|
/// branch pedals and split routing modes. Type or topology mismatches at any position are
|
||||||
/// skipped silently (lightweight recall is for topologically identical rigs).
|
/// skipped silently (lightweight recall is for topologically identical rigs).
|
||||||
|
|||||||
@@ -57,6 +57,11 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
/// persistence. Reapplied on load under the same conditions as ``numInputChannels``.
|
/// persistence. Reapplied on load under the same conditions as ``numInputChannels``.
|
||||||
public let numOutputChannels: Int?
|
public let numOutputChannels: Int?
|
||||||
|
|
||||||
|
/// The rig's chain routers (two-board split/blend units), or `nil` for a rig saved before router
|
||||||
|
/// persistence existed. Additive: decoded with `decodeIfPresent`, so older rigs — which never had
|
||||||
|
/// routers — decode cleanly to `nil` without a format-version bump.
|
||||||
|
public let routers: [ChainRouterState]?
|
||||||
|
|
||||||
/// Creates a rig state snapshot.
|
/// Creates a rig state snapshot.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
@@ -68,6 +73,7 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
/// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`.
|
/// - inputSource: The rig's input selection, or `nil` to not persist one. Defaults to `nil`.
|
||||||
/// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`.
|
/// - numInputChannels: The engine input-channel count, or `nil`. Defaults to `nil`.
|
||||||
/// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`.
|
/// - numOutputChannels: The engine output-channel count, or `nil`. Defaults to `nil`.
|
||||||
|
/// - routers: The rig's chain routers, or `nil` when there are none. Defaults to `nil`.
|
||||||
public init(
|
public init(
|
||||||
version: Int = presetFormatVersion,
|
version: Int = presetFormatVersion,
|
||||||
boards: [BoardState],
|
boards: [BoardState],
|
||||||
@@ -76,7 +82,8 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
tempoEnabled: Bool? = nil,
|
tempoEnabled: Bool? = nil,
|
||||||
inputSource: InputSource? = nil,
|
inputSource: InputSource? = nil,
|
||||||
numInputChannels: Int? = nil,
|
numInputChannels: Int? = nil,
|
||||||
numOutputChannels: Int? = nil
|
numOutputChannels: Int? = nil,
|
||||||
|
routers: [ChainRouterState]? = nil
|
||||||
) {
|
) {
|
||||||
self.version = version
|
self.version = version
|
||||||
self.boards = boards
|
self.boards = boards
|
||||||
@@ -86,6 +93,7 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
self.inputSource = inputSource
|
self.inputSource = inputSource
|
||||||
self.numInputChannels = numInputChannels
|
self.numInputChannels = numInputChannels
|
||||||
self.numOutputChannels = numOutputChannels
|
self.numOutputChannels = numOutputChannels
|
||||||
|
self.routers = routers
|
||||||
}
|
}
|
||||||
|
|
||||||
private enum CodingKeys: String, CodingKey {
|
private enum CodingKeys: String, CodingKey {
|
||||||
@@ -97,6 +105,7 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
case inputSource
|
case inputSource
|
||||||
case numInputChannels
|
case numInputChannels
|
||||||
case numOutputChannels
|
case numOutputChannels
|
||||||
|
case routers
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
|
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
|
||||||
@@ -129,5 +138,22 @@ public struct ShoeGazeState: Codable, Equatable {
|
|||||||
self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource)
|
self.inputSource = try container.decodeIfPresent(InputSource.self, forKey: .inputSource)
|
||||||
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
|
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
|
||||||
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
|
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
|
||||||
|
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
|
||||||
|
/// ignoring live session settings that are not part of the recalled rig: the input source and the
|
||||||
|
/// engine's channel counts.
|
||||||
|
///
|
||||||
|
/// Use this for unsaved-changes detection. Those session fields are deliberately not applied when
|
||||||
|
/// switching rigs (see ``ShoeGaze/loadRig(from:keepingCurrentInput:)``), so a plain `==` would
|
||||||
|
/// report a freshly-loaded rig as "changed" merely because the player's current input differs from
|
||||||
|
/// the input the rig was saved with — producing a spurious "save changes?" prompt.
|
||||||
|
public func hasSameRigContent(as other: ShoeGazeState) -> Bool {
|
||||||
|
boards == other.boards
|
||||||
|
&& routers == other.routers
|
||||||
|
&& midiMap == other.midiMap
|
||||||
|
&& bpm == other.bpm
|
||||||
|
&& tempoEnabled == other.tempoEnabled
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -199,7 +199,10 @@ public final class ShoeGaze {
|
|||||||
|
|
||||||
/// All chain routers created via ``makeChainRouter()``.
|
/// All chain routers created via ``makeChainRouter()``.
|
||||||
/// Routers are torn down (in reverse-creation order) by ``teardown()``.
|
/// Routers are torn down (in reverse-creation order) by ``teardown()``.
|
||||||
private var routers: [ChainRouter] = []
|
///
|
||||||
|
/// `internal` (not `private`) so the preset capture/rebuild path in `ShoeGaze+Preset.swift` can
|
||||||
|
/// snapshot and reconstruct routers.
|
||||||
|
var routers: [ChainRouter] = []
|
||||||
|
|
||||||
// MARK: - Init
|
// MARK: - Init
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@
|
|||||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
|
||||||
/// Descriptor for one pedal parameter that can be locked to the tempo.
|
/// Descriptor for one pedal parameter that can be locked to the tempo.
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
/// A horizontal board-mixer strip for switching between, or blending, multiple `PedalBoard`s.
|
/// A horizontal board-mixer strip for switching between, or blending, multiple `PedalBoard`s.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
/// A full board manager presented as a sheet — the richer companion to the inline
|
/// A full board manager presented as a sheet — the richer companion to the inline
|
||||||
/// ``BoardBarView``.
|
/// ``BoardBarView``.
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
/// Renders a ``ChainRouter`` as a vertical stack with transport controls, two labelled
|
/// Renders a ``ChainRouter`` as a vertical stack with transport controls, two labelled
|
||||||
/// board rows, and a merger + optional master-gain output stage.
|
/// board rows, and a merger + optional master-gain output stage.
|
||||||
|
|||||||
@@ -93,6 +93,25 @@ public struct HelpView: View {
|
|||||||
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
|
"Reorder rigs into a set list by dragging a row, or via each rig's Move Up / "
|
||||||
+ "Move Down menu. The order is saved and travels with an exported archive; "
|
+ "Move Down menu. The order is saved and travels with an exported archive; "
|
||||||
+ "the top ten map to ⌘⇧1–⌘⇧0.",
|
+ "the top ten map to ⌘⇧1–⌘⇧0.",
|
||||||
|
"Switching rigs keeps your current input — your live guitar stays selected "
|
||||||
|
+ "instead of snapping back to the test loop.",
|
||||||
|
]
|
||||||
|
)
|
||||||
|
topicSection(
|
||||||
|
icon: "guitars",
|
||||||
|
title: "Starter Rigs",
|
||||||
|
intro: "ShoeGaze ships a library of ready-to-play rigs so you always have somewhere "
|
||||||
|
+ "to start.",
|
||||||
|
steps: [
|
||||||
|
"The Rigs sidebar has a Mine / Starters toggle at the top: Mine is your own "
|
||||||
|
+ "saved rigs; Starters is the shipped set, grouped by style — Shoegaze "
|
||||||
|
+ "Walls, Dreampop, Classic, Ambient, and Experimental.",
|
||||||
|
"Tap a starter to load it. To keep your tweaks, use Save As or Duplicate to make "
|
||||||
|
+ "your own copy — saving directly over a starter asks first and offers Save "
|
||||||
|
+ "as New Rig.",
|
||||||
|
"Restore Starter Rigs (the rig-library ⋯ menu, or the Starters empty state) "
|
||||||
|
+ "reinstalls the shipped rigs — handy if you deleted some, or to refresh "
|
||||||
|
+ "them after an update.",
|
||||||
]
|
]
|
||||||
)
|
)
|
||||||
topicSection(
|
topicSection(
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
/// A horizontal scrolling strip of ``PedalView`` cards, one per pedal in a `PedalBoard`.
|
/// A horizontal scrolling strip of ``PedalView`` cards, one per pedal in a `PedalBoard`.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
// MARK: - PedalButtonView
|
// MARK: - PedalButtonView
|
||||||
|
|
||||||
|
|||||||
@@ -53,11 +53,15 @@ public enum PedalCategory: String, CaseIterable, Identifiable, Sendable {
|
|||||||
"Cabinet": .cabinet,
|
"Cabinet": .cabinet,
|
||||||
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
|
"Tremolo": .modulation, "Phaser": .modulation, "Modulation": .modulation, "Chorus": .modulation,
|
||||||
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
|
"Flanger": .modulation, "Vibrato": .modulation, "Rotary": .modulation, "Ring Modulator": .modulation,
|
||||||
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch,
|
"Script Phaser": .modulation,
|
||||||
|
"Bass Octaver": .pitch, "Octave Splitter": .pitch, "Harmonizer": .pitch, "Whammy": .pitch,
|
||||||
|
"Poly Octave": .pitch,
|
||||||
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
|
"Delay": .delay, "Feedback Delay": .delay, "Multi-Tap Delay": .delay, "Ping-Pong": .delay,
|
||||||
"Reverse Delay": .delay,
|
"Reverse Delay": .delay, "DL4": .delay,
|
||||||
"Reverb": .reverb, "Shimmer Reverb": .reverb,
|
"Reverb": .reverb, "Shimmer Reverb": .reverb,
|
||||||
"Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb,
|
"Plate Reverb": .reverb, "Room Reverb": .reverb, "Spring Reverb": .reverb,
|
||||||
|
"Reverse Reverb": .reverb, "Granular Reverb": .reverb,
|
||||||
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
|
"Diffuser": .texture, "Bitcrusher": .texture, "Granulator": .texture, "Auto Granulator": .texture,
|
||||||
|
"Karplus Resonator": .texture, "Tape Looper": .texture,
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -54,9 +54,9 @@ public struct PedalPaletteView: View {
|
|||||||
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
|
/// Preferred display order for the built-in pedals. Any registered pedal not listed here is
|
||||||
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
|
/// appended afterwards (sorted) so the palette never silently drops a newly added pedal.
|
||||||
private static let preferredOrder: [String] = [
|
private static let preferredOrder: [String] = [
|
||||||
"California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz",
|
"California", "British", "British Plexi", "British JTM", "British Bluesbreaker", "British Master", "British Dual", "Boutique Lead", "Boutique OD", "Cali Hi-Gain", "Command", "Citrus", "Sixties Combo", "Magna Vibrato", "Anaheim", "Modern High-Gain", "Chime", "Chime 15", "Chime Normal", "Chime Baby", "Fullerton Reverb", "Fullerton Deluxe", "Fullerton Ivy League", "Fullerton Drive", "Jazz Clean", "Chime Top Boost", "Cabinet", "Overdrive", "Distortion", "Compressor", "Sustainer", "Limiter", "Noise Gate", "Fuzz", "Sustain Fuzz",
|
||||||
"Volume",
|
"Volume",
|
||||||
"Graphic EQ", "Tremolo", "Phaser", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
"Graphic EQ", "Tremolo", "Phaser", "Vibe", "Modulation", "Chorus", "Flanger", "Vibrato", "Rotary",
|
||||||
"Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
|
"Auto-Wah", "Wah", "Mutant", "Ring Modulator", "Diffuser", "Bitcrusher", "Granulator",
|
||||||
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
|
"Auto Granulator", "Bass Octaver", "Octave Splitter", "Harmonizer",
|
||||||
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
"Delay", "Feedback Delay", "Multi-Tap Delay", "Ping-Pong", "Reverse Delay", "Reverb",
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
/// Environment action a leaf pedal control can call to ask the host to rebuild the board that
|
/// Environment action a leaf pedal control can call to ask the host to rebuild the board that
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
|||||||
@@ -8,6 +8,7 @@ import SwiftUI
|
|||||||
import UniformTypeIdentifiers
|
import UniformTypeIdentifiers
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
// MARK: - Accent-color mapping (UI-only, never in the core target)
|
// MARK: - Accent-color mapping (UI-only, never in the core target)
|
||||||
|
|
||||||
@@ -54,8 +55,10 @@ private func enclosureColor(for displayName: String) -> Color {
|
|||||||
case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan
|
case "Spring Reverb": return Color(red: 0.20, green: 0.46, blue: 0.64) // steel cyan
|
||||||
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
|
case "Modulation": return Color(red: 0.12, green: 0.58, blue: 0.22) // green
|
||||||
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
|
case "Fuzz": return Color(red: 0.55, green: 0.10, blue: 0.10) // deep crimson
|
||||||
|
case "Sustain Fuzz": return Color(red: 0.72, green: 0.24, blue: 0.10) // rust / burnt orange
|
||||||
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
|
case "Tremolo": return Color(red: 0.20, green: 0.38, blue: 0.72) // cobalt blue
|
||||||
case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet
|
case "Phaser": return Color(red: 0.60, green: 0.22, blue: 0.62) // violet
|
||||||
|
case "Vibe": return Color(red: 0.28, green: 0.20, blue: 0.62) // deep indigo
|
||||||
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
|
case "Compressor": return Color(red: 0.18, green: 0.42, blue: 0.32) // forest green
|
||||||
case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
|
case "Mutant": return Color(red: 0.70, green: 0.12, blue: 0.48) // magenta / plum
|
||||||
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
|
case "Auto-Wah": return Color(red: 0.80, green: 0.62, blue: 0.10) // gold
|
||||||
@@ -535,6 +538,8 @@ public struct PedalView: View {
|
|||||||
Group {
|
Group {
|
||||||
if let looper: LooperPedal = pedal as? LooperPedal {
|
if let looper: LooperPedal = pedal as? LooperPedal {
|
||||||
looperColumnarContent(looper)
|
looperColumnarContent(looper)
|
||||||
|
} else if pedal is KarplusResonatorPedal {
|
||||||
|
karplusContent
|
||||||
} else {
|
} else {
|
||||||
defaultContent(sliders: sliders)
|
defaultContent(sliders: sliders)
|
||||||
}
|
}
|
||||||
@@ -728,6 +733,82 @@ public struct PedalView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Karplus Resonator layout
|
||||||
|
|
||||||
|
/// Bespoke layout for the ``KarplusResonatorPedal``. The generic stack would show a redundant
|
||||||
|
/// Tune Hz knob beside the Root note selector in Pitched mode, and strand Sensitivity on a row of
|
||||||
|
/// its own. Instead:
|
||||||
|
/// - **Top row**: the root control, then Sustain and Tone. The root slot is the continuous Tune
|
||||||
|
/// Hz knob in Free mode and the stepped Root note selector in Pitched mode — one slot, reused.
|
||||||
|
/// - **Switch** directly beneath the top row: the Free / Pitched toggle.
|
||||||
|
/// - **Voicing + Sensitivity** share the next row.
|
||||||
|
/// - Standard Level · Bypass · Mix footer.
|
||||||
|
///
|
||||||
|
/// Only the *view* changes — the pedal still publishes Tune as a stable effect knob, so positional
|
||||||
|
/// presets round-trip exactly as for any other pedal.
|
||||||
|
private var karplusContent: some View {
|
||||||
|
VStack(spacing: PedalView.sectionSpacing) {
|
||||||
|
namePlate
|
||||||
|
karplusTopRow
|
||||||
|
switchRow
|
||||||
|
karplusVoicingSensitivityRow
|
||||||
|
bottomControls
|
||||||
|
PedalMappingStrip(pedal: pedal, map: controlMappingMap)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first effect knob whose label matches `label`, or `nil`.
|
||||||
|
private func effectKnob(_ label: String) -> PedalKnob? {
|
||||||
|
pedal.effectKnobs.first { $0.label == label }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The first selector whose label matches `label`, or `nil`.
|
||||||
|
private func effectSelector(_ label: String) -> PedalSelectorKnob? {
|
||||||
|
pedal.effectSelectors.first { $0.label == label }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders one selector with the standard rebuild-on-commit wiring.
|
||||||
|
private func selectorCell(_ selector: PedalSelectorKnob) -> some View {
|
||||||
|
PedalSelectorKnobView(
|
||||||
|
selector,
|
||||||
|
onCommit: selector.rebuildsOnChange
|
||||||
|
? { [pedal, pedalRebuildAction] in pedalRebuildAction(pedal) }
|
||||||
|
: nil
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The root-tuning control: the stepped Root note selector when Pitched (it is published only in
|
||||||
|
/// that mode), otherwise the continuous Tune Hz knob. One physical slot, reused across modes.
|
||||||
|
@ViewBuilder
|
||||||
|
private var karplusRootControl: some View {
|
||||||
|
if let root: PedalSelectorKnob = effectSelector("Root") {
|
||||||
|
selectorCell(root)
|
||||||
|
} else if let tune: PedalKnob = effectKnob("Tune") {
|
||||||
|
knobCell(tune)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Top row: the root control (Tune knob or Root selector), then Sustain and Tone.
|
||||||
|
private var karplusTopRow: some View {
|
||||||
|
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
karplusRootControl
|
||||||
|
if let sustain: PedalKnob = effectKnob("Sustain") { knobCell(sustain) }
|
||||||
|
if let tone: PedalKnob = effectKnob("Tone") { knobCell(tone) }
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Second row: the Voicing selector paired with the Sensitivity knob.
|
||||||
|
private var karplusVoicingSensitivityRow: some View {
|
||||||
|
HStack(alignment: .top, spacing: PedalView.knobRowItemSpacing) {
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
if let voicing: PedalSelectorKnob = effectSelector("Voicing") { selectorCell(voicing) }
|
||||||
|
if let sensitivity: PedalKnob = effectKnob("Sensitivity") { knobCell(sensitivity) }
|
||||||
|
Spacer(minLength: 0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Subviews
|
// MARK: - Subviews
|
||||||
|
|
||||||
/// Capsule name plate near the top of the enclosure.
|
/// Capsule name plate near the top of the enclosure.
|
||||||
|
|||||||
@@ -10,44 +10,87 @@ import LyrebirdShoeGaze
|
|||||||
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
|
||||||
///
|
///
|
||||||
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
|
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
|
||||||
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
|
/// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving
|
||||||
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
|
/// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time
|
||||||
/// library from the current working rig **only after** the real (possibly iCloud) contents are
|
/// catch-up seed of any missing shipped starter rigs.
|
||||||
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
|
|
||||||
@MainActor
|
@MainActor
|
||||||
public enum RigLibraryBootstrap {
|
public enum RigLibraryBootstrap {
|
||||||
|
|
||||||
|
/// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has
|
||||||
|
/// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device
|
||||||
|
/// that receives the rigs via iCloud sync simply finds them already present and seeds nothing.
|
||||||
|
private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion"
|
||||||
|
|
||||||
/// Creates an auto-resolving store. Construct this synchronously at launch; call
|
/// Creates an auto-resolving store. Construct this synchronously at launch; call
|
||||||
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
/// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
|
||||||
public static func makeStore() -> RigLibraryStore {
|
public static func makeStore() -> RigLibraryStore {
|
||||||
RigLibraryStore()
|
RigLibraryStore()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
|
/// Resolves + loads `store` off the main thread, then performs a one-time catch-up install of the
|
||||||
/// empty after loading (first run). Idempotent enough to call once at launch.
|
/// shipped starter rigs. Idempotent — safe to call once at every launch.
|
||||||
|
///
|
||||||
|
/// Installing (re)saves every factory rig by its stable id, so it **adds** missing starters and
|
||||||
|
/// **refreshes** existing ones to their current shipped definition (a corrected rig replaces the
|
||||||
|
/// stale copy in place, keeping its library position). User rigs are never touched — factory rigs
|
||||||
|
/// have their own fixed ids. It runs at most once per ``FactoryRigLibrary/seedVersion``: a first
|
||||||
|
/// launch installs every starter; a launch after a version bump refreshes/adds; and within a
|
||||||
|
/// version a starter the user deletes stays deleted (the marker has already advanced). This
|
||||||
|
/// deliberately replaces the old "only seed an empty library" rule so existing users get starters.
|
||||||
///
|
///
|
||||||
/// - Parameters:
|
/// - Parameters:
|
||||||
/// - store: The store from ``makeStore()``.
|
/// - store: The store from ``makeStore()``.
|
||||||
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
|
/// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability
|
||||||
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
|
/// and future working-rig seeding needs).
|
||||||
public static func start(
|
public static func start(
|
||||||
_ store: RigLibraryStore,
|
_ store: RigLibraryStore,
|
||||||
seedFrom shoeGaze: ShoeGaze,
|
seedFrom shoeGaze: ShoeGaze
|
||||||
seedName: String = "Default"
|
|
||||||
) async {
|
) async {
|
||||||
await store.start()
|
await store.start()
|
||||||
|
|
||||||
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
|
let defaults: UserDefaults = .standard
|
||||||
// genuine first run, not a not-yet-synced one.
|
let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded
|
||||||
guard store.entries.isEmpty, !shoeGaze.boards.isEmpty else { return }
|
guard seededVersion < FactoryRigLibrary.seedVersion else { return }
|
||||||
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
|
|
||||||
|
// Install the starters. Only advance the marker if it succeeded, so a transient failure
|
||||||
|
// (which should not happen for this deterministic data) is retried on the next launch.
|
||||||
|
if installFactoryRigs(into: store) != nil {
|
||||||
|
defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (Re)installs every shipped starter rig to its current definition. Safe to call anytime.
|
||||||
|
///
|
||||||
|
/// Drives the user-facing "Restore Starter Rigs" action: it re-adds starters the user deleted,
|
||||||
|
/// adds newly-shipped ones, and refreshes any stale copies — all without disturbing the user's own
|
||||||
|
/// rigs — and advances the seed marker so automatic catch-up won't fight the manual restore.
|
||||||
|
///
|
||||||
|
/// - Parameter store: The library to install into.
|
||||||
|
/// - Returns: The number of starter rigs written (0 on a build/encode failure).
|
||||||
|
@discardableResult
|
||||||
|
public static func restoreStarterRigs(into store: RigLibraryStore) -> Int {
|
||||||
|
// Advance the seed marker only on success, mirroring `start()` — a failed restore must not
|
||||||
|
// suppress the automatic catch-up seed on the next launch.
|
||||||
|
guard let written: Int = installFactoryRigs(into: store) else { return 0 }
|
||||||
|
UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
|
||||||
|
return written
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builds every starter rig and saves it, overwriting any existing entry with the same stable id
|
||||||
|
/// (`store.save` upserts by id, keeping an overwritten entry's library position).
|
||||||
|
///
|
||||||
|
/// - Parameter store: The library to install into.
|
||||||
|
/// - Returns: The number of rigs written, or `nil` if building/encoding failed.
|
||||||
|
private static func installFactoryRigs(into store: RigLibraryStore) -> Int? {
|
||||||
do {
|
do {
|
||||||
|
let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
|
||||||
|
for entry: RigEntry in entries {
|
||||||
try store.save(entry)
|
try store.save(entry)
|
||||||
// The seeded entry was captured from the working graph, so it is the session's source
|
}
|
||||||
// rig — record it so the sidebar highlights it and the autosave envelope carries it.
|
return entries.count
|
||||||
shoeGaze.currentRigID = entry.id
|
|
||||||
} catch {
|
} catch {
|
||||||
print("[RigLibraryBootstrap] seeding library failed: \(error)")
|
print("[RigLibraryBootstrap] installing factory rigs failed: \(error)")
|
||||||
|
return nil
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ struct RigLibrarySidebarView: View {
|
|||||||
private static let subtitleOpacity: Double = 0.5
|
private static let subtitleOpacity: Double = 0.5
|
||||||
private static let headerOpacity: Double = 0.65
|
private static let headerOpacity: Double = 0.65
|
||||||
private static let emptyOpacity: Double = 0.4
|
private static let emptyOpacity: Double = 0.4
|
||||||
|
private static let tabPickerWidth: CGFloat = 168
|
||||||
|
|
||||||
// MARK: - Inputs
|
// MARK: - Inputs
|
||||||
|
|
||||||
@@ -45,6 +46,9 @@ struct RigLibrarySidebarView: View {
|
|||||||
let onImportArchive: () -> Void
|
let onImportArchive: () -> Void
|
||||||
let onExportArchive: () -> Void
|
let onExportArchive: () -> Void
|
||||||
|
|
||||||
|
/// Invoked to (re-)install any shipped starter rigs missing from the library. Defaults to a no-op.
|
||||||
|
var onRestoreStarters: () -> Void = {}
|
||||||
|
|
||||||
/// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can
|
/// Invoked when the local-only (iCloud-unavailable) status icon is tapped, so the host can
|
||||||
/// explain how to re-enable iCloud sync. Defaults to a no-op.
|
/// explain how to re-enable iCloud sync. Defaults to a no-op.
|
||||||
var onShowCloudStatus: () -> Void = {}
|
var onShowCloudStatus: () -> Void = {}
|
||||||
@@ -52,6 +56,16 @@ struct RigLibrarySidebarView: View {
|
|||||||
private static let timestampFormat: Date.FormatStyle =
|
private static let timestampFormat: Date.FormatStyle =
|
||||||
Date.FormatStyle(date: .abbreviated, time: .shortened)
|
Date.FormatStyle(date: .abbreviated, time: .shortened)
|
||||||
|
|
||||||
|
/// Which group of rigs the list is currently showing.
|
||||||
|
private enum RigTab: String, CaseIterable, Identifiable {
|
||||||
|
case mine = "Mine"
|
||||||
|
case starters = "Starters"
|
||||||
|
var id: String { rawValue }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The selected list tab. Defaults to the user's own rigs.
|
||||||
|
@State private var tab: RigTab = .mine
|
||||||
|
|
||||||
// MARK: - Body
|
// MARK: - Body
|
||||||
|
|
||||||
var body: some View {
|
var body: some View {
|
||||||
@@ -63,6 +77,18 @@ struct RigLibrarySidebarView: View {
|
|||||||
actionBar
|
actionBar
|
||||||
}
|
}
|
||||||
.frame(width: RigLibrarySidebarView.width)
|
.frame(width: RigLibrarySidebarView.width)
|
||||||
|
// Open on the tab that contains the currently-loaded rig, so a session restored on a starter
|
||||||
|
// rig (e.g. Garcia) shows Starters, and one on a user rig shows Mine.
|
||||||
|
.onAppear { tab = tabForCurrentRig() }
|
||||||
|
.onChange(of: currentRigID) { tab = tabForCurrentRig() }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The tab whose group contains the currently-loaded rig: Starters for a factory rig, else Mine.
|
||||||
|
private func tabForCurrentRig() -> RigTab {
|
||||||
|
if let id: UUID = currentRigID, FactoryRigLibrary.isFactory(id) {
|
||||||
|
return .starters
|
||||||
|
}
|
||||||
|
return .mine
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Header
|
// MARK: - Header
|
||||||
@@ -99,9 +125,8 @@ struct RigLibrarySidebarView: View {
|
|||||||
|
|
||||||
// MARK: - List
|
// MARK: - List
|
||||||
|
|
||||||
|
@ViewBuilder
|
||||||
private var rigList: some View {
|
private var rigList: some View {
|
||||||
ScrollView(.vertical, showsIndicators: true) {
|
|
||||||
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
|
||||||
if !store.isLoaded {
|
if !store.isLoaded {
|
||||||
HStack(spacing: 6) {
|
HStack(spacing: 6) {
|
||||||
ProgressView().controlSize(.small)
|
ProgressView().controlSize(.small)
|
||||||
@@ -110,23 +135,95 @@ struct RigLibrarySidebarView: View {
|
|||||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||||
}
|
}
|
||||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||||
} else if store.entries.isEmpty {
|
.frame(maxHeight: .infinity, alignment: .top)
|
||||||
Text("No saved rigs yet.\nTap New or Save to add one.")
|
} else {
|
||||||
.font(.caption)
|
VStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
tabPicker
|
||||||
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
ScrollView(.vertical, showsIndicators: true) {
|
||||||
}
|
LazyVStack(alignment: .leading, spacing: RigLibrarySidebarView.rowSpacing) {
|
||||||
ForEach(store.entries) { entry in
|
switch tab {
|
||||||
rigRow(entry)
|
case .mine: mineList
|
||||||
|
case .starters: startersList
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
.frame(maxHeight: .infinity)
|
.frame(maxHeight: .infinity)
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private func rigRow(_ entry: RigEntry) -> some View {
|
/// Segmented Mine / Starters switch, centered at the top of the list.
|
||||||
|
private var tabPicker: some View {
|
||||||
|
Picker("", selection: $tab) {
|
||||||
|
ForEach(RigTab.allCases) { option in
|
||||||
|
Text(option.rawValue).tag(option)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
.pickerStyle(.segmented)
|
||||||
|
.labelsHidden()
|
||||||
|
// Constrain the control's own width, then center it in the full column width.
|
||||||
|
.frame(maxWidth: RigLibrarySidebarView.tabPickerWidth)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .center)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user's own rigs — a flat, reorderable list.
|
||||||
|
@ViewBuilder
|
||||||
|
private var mineList: some View {
|
||||||
|
let userRigs: [RigEntry] = userEntries
|
||||||
|
if userRigs.isEmpty {
|
||||||
|
Text("No saved rigs yet.\nTap New or Save to add one.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||||
|
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||||
|
} else {
|
||||||
|
ForEach(userRigs) { entry in
|
||||||
|
rigRow(entry, reorderable: true)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The shipped starter rigs, grouped by category (fixed catalog order, not reorderable).
|
||||||
|
@ViewBuilder
|
||||||
|
private var startersList: some View {
|
||||||
|
let sections: [(category: FactoryRigCategory, entries: [RigEntry])] = factorySections
|
||||||
|
if sections.isEmpty {
|
||||||
|
VStack(alignment: .leading, spacing: 6) {
|
||||||
|
Text("No starter rigs installed.")
|
||||||
|
.font(.caption)
|
||||||
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.emptyOpacity))
|
||||||
|
Button("Restore Starter Rigs") { onRestoreStarters() }
|
||||||
|
.buttonStyle(.bordered)
|
||||||
|
.tint(.orange)
|
||||||
|
.controlSize(.small)
|
||||||
|
}
|
||||||
|
.padding(.vertical, RigLibrarySidebarView.rowPadding)
|
||||||
|
} else {
|
||||||
|
ForEach(sections, id: \.category) { section in
|
||||||
|
sectionHeader(section.category.displayName)
|
||||||
|
ForEach(section.entries) { entry in
|
||||||
|
rigRow(entry, reorderable: false)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A small uppercase section header for a group of rigs.
|
||||||
|
private func sectionHeader(_ title: String) -> some View {
|
||||||
|
Text(title.uppercased())
|
||||||
|
.font(.caption2)
|
||||||
|
.fontWeight(.semibold)
|
||||||
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.headerOpacity))
|
||||||
|
.padding(.top, RigLibrarySidebarView.rowPadding)
|
||||||
|
.padding(.horizontal, 2)
|
||||||
|
.frame(maxWidth: .infinity, alignment: .leading)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// One rig row. `reorderable` rows (the user's own rigs) accept drag-to-reorder and expose
|
||||||
|
/// Move Up / Down; starter rigs are fixed and show a "Starter rig" subtitle instead of a date.
|
||||||
|
@ViewBuilder
|
||||||
|
private func rigRow(_ entry: RigEntry, reorderable: Bool) -> some View {
|
||||||
let isSelected: Bool = entry.id == currentRigID
|
let isSelected: Bool = entry.id == currentRigID
|
||||||
return Button {
|
let button = Button {
|
||||||
onSelect(entry)
|
onSelect(entry)
|
||||||
} label: {
|
} label: {
|
||||||
VStack(alignment: .leading, spacing: 2) {
|
VStack(alignment: .leading, spacing: 2) {
|
||||||
@@ -134,7 +231,9 @@ struct RigLibrarySidebarView: View {
|
|||||||
.font(.subheadline)
|
.font(.subheadline)
|
||||||
.foregroundStyle(Color.white)
|
.foregroundStyle(Color.white)
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
Text(entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat))
|
Text(reorderable
|
||||||
|
? entry.savedAt.formatted(RigLibrarySidebarView.timestampFormat)
|
||||||
|
: "Starter rig")
|
||||||
.font(.caption2)
|
.font(.caption2)
|
||||||
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
|
.foregroundStyle(Color.white.opacity(RigLibrarySidebarView.subtitleOpacity))
|
||||||
.lineLimit(1)
|
.lineLimit(1)
|
||||||
@@ -149,20 +248,35 @@ struct RigLibrarySidebarView: View {
|
|||||||
.contentShape(Rectangle())
|
.contentShape(Rectangle())
|
||||||
}
|
}
|
||||||
.buttonStyle(.plain)
|
.buttonStyle(.plain)
|
||||||
|
.contextMenu {
|
||||||
|
rowContextMenu(entry, reorderable: reorderable)
|
||||||
|
}
|
||||||
|
|
||||||
|
if reorderable {
|
||||||
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
|
// Drag the row onto another to reorder; dropping inserts it just before the target. Works
|
||||||
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
|
// on macOS (mouse drag) and iPad (long-press drag); taps still select.
|
||||||
|
button
|
||||||
.draggable(entry.id.uuidString)
|
.draggable(entry.id.uuidString)
|
||||||
.dropDestination(for: String.self) { droppedIDs, _ in
|
.dropDestination(for: String.self) { droppedIDs, _ in
|
||||||
guard let first: String = droppedIDs.first else { return false }
|
guard let first: String = droppedIDs.first else { return false }
|
||||||
moveDragged(first, onto: entry)
|
moveDragged(first, onto: entry)
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
.contextMenu {
|
} else {
|
||||||
|
button
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The context menu for a rig row. Move Up / Down appear only for reorderable (user) rigs.
|
||||||
|
@ViewBuilder
|
||||||
|
private func rowContextMenu(_ entry: RigEntry, reorderable: Bool) -> some View {
|
||||||
|
if reorderable {
|
||||||
Button("Move Up") { store.moveUp(entry) }
|
Button("Move Up") { store.moveUp(entry) }
|
||||||
.disabled(isFirst(entry))
|
.disabled(isFirstUser(entry))
|
||||||
Button("Move Down") { store.moveDown(entry) }
|
Button("Move Down") { store.moveDown(entry) }
|
||||||
.disabled(isLast(entry))
|
.disabled(isLastUser(entry))
|
||||||
Divider()
|
Divider()
|
||||||
|
}
|
||||||
Button("Rename…") { onRename(entry) }
|
Button("Rename…") { onRename(entry) }
|
||||||
Button("Duplicate…") { onDuplicate(entry) }
|
Button("Duplicate…") { onDuplicate(entry) }
|
||||||
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
|
// Encoding a fully-concrete RigEntry to JSON does not fail in practice; on the
|
||||||
@@ -178,16 +292,37 @@ struct RigLibrarySidebarView: View {
|
|||||||
Divider()
|
Divider()
|
||||||
Button("Delete", role: .destructive) { onDelete(entry) }
|
Button("Delete", role: .destructive) { onDelete(entry) }
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// MARK: - Grouping
|
||||||
|
|
||||||
|
/// The starter-rig sections: each non-empty ``FactoryRigCategory`` present in the library, in
|
||||||
|
/// catalog order, paired with its entries (also in catalog order).
|
||||||
|
private var factorySections: [(category: FactoryRigCategory, entries: [RigEntry])] {
|
||||||
|
let byID: [UUID: RigEntry] = Dictionary(
|
||||||
|
store.entries.map { ($0.id, $0) },
|
||||||
|
uniquingKeysWith: { first, _ in first }
|
||||||
|
)
|
||||||
|
return FactoryRigCategory.allCases.compactMap { category in
|
||||||
|
let entries: [RigEntry] = FactoryRigLibrary.rigs(in: category).compactMap { byID[$0.id] }
|
||||||
|
return entries.isEmpty ? nil : (category, entries)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The user's own (non-factory) rigs, in library order.
|
||||||
|
private var userEntries: [RigEntry] {
|
||||||
|
store.entries.filter { !FactoryRigLibrary.isFactory($0.id) }
|
||||||
}
|
}
|
||||||
|
|
||||||
// MARK: - Reorder helpers
|
// MARK: - Reorder helpers
|
||||||
|
|
||||||
private func isFirst(_ entry: RigEntry) -> Bool {
|
/// Whether `entry` is the first among the user's own rigs (so Move Up is disabled for it).
|
||||||
store.entries.first?.id == entry.id
|
private func isFirstUser(_ entry: RigEntry) -> Bool {
|
||||||
|
userEntries.first?.id == entry.id
|
||||||
}
|
}
|
||||||
|
|
||||||
private func isLast(_ entry: RigEntry) -> Bool {
|
/// Whether `entry` is the last among the user's own rigs (so Move Down is disabled for it).
|
||||||
store.entries.last?.id == entry.id
|
private func isLastUser(_ entry: RigEntry) -> Bool {
|
||||||
|
userEntries.last?.id == entry.id
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Moves the dragged entry (by id string) to sit just before `target` in the set list.
|
/// Moves the dragged entry (by id string) to sit just before `target` in the set list.
|
||||||
@@ -217,6 +352,8 @@ struct RigLibrarySidebarView: View {
|
|||||||
Button("Import Archive…") { onImportArchive() }
|
Button("Import Archive…") { onImportArchive() }
|
||||||
Button("Export Archive…") { onExportArchive() }
|
Button("Export Archive…") { onExportArchive() }
|
||||||
Divider()
|
Divider()
|
||||||
|
Button("Restore Starter Rigs") { onRestoreStarters() }
|
||||||
|
Divider()
|
||||||
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
|
Button("Erase All Rigs…", role: .destructive) { onEraseAll() }
|
||||||
} label: {
|
} label: {
|
||||||
Image(systemName: "ellipsis.circle")
|
Image(systemName: "ellipsis.circle")
|
||||||
|
|||||||
@@ -149,6 +149,18 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
let message: String
|
let message: String
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A pending confirmation to overwrite a built-in factory rig. Non-`nil` shows the dialog;
|
||||||
|
/// carries the target entry and the follow-up to run once the user resolves the choice (so the
|
||||||
|
/// "Save & Clear" flow still clears after a confirmed overwrite).
|
||||||
|
private struct FactoryOverwriteRequest: Identifiable {
|
||||||
|
let id: UUID = UUID()
|
||||||
|
let entry: RigEntry
|
||||||
|
let completion: () -> Void
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Drives the "overwrite a starter rig?" confirmation dialog. `nil` = not shown.
|
||||||
|
@State private var factoryOverwrite: FactoryOverwriteRequest?
|
||||||
|
|
||||||
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
|
/// Archive export state. Cross-platform: backs the sidebar's Export Archive and the
|
||||||
/// "Save & Clear" flow is separate (it saves to the library, not a file).
|
/// "Save & Clear" flow is separate (it saves to the library, not a file).
|
||||||
@State private var showExporter: Bool = false
|
@State private var showExporter: Bool = false
|
||||||
@@ -297,13 +309,43 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private var presentationChrome: some View {
|
// Split off the first half of the presentation chain into its own computed property: the full
|
||||||
|
// modifier chain is long enough to blow the Swift expression type-checker's budget, so this
|
||||||
|
// boundary keeps each half small enough to type-check quickly.
|
||||||
|
private var chromeWithPrompts: some View {
|
||||||
layoutChrome
|
layoutChrome
|
||||||
.background(boardsSheetAnchor)
|
.background(boardsSheetAnchor)
|
||||||
.background(rigExportAnchor)
|
.background(rigExportAnchor)
|
||||||
.background(rigImportAnchor)
|
.background(rigImportAnchor)
|
||||||
.background(actionErrorAnchor)
|
.background(actionErrorAnchor)
|
||||||
.rigNamePrompt($namePrompt)
|
.rigNamePrompt($namePrompt)
|
||||||
|
.confirmationDialog(
|
||||||
|
"Starter rig",
|
||||||
|
isPresented: Binding(
|
||||||
|
get: { factoryOverwrite != nil },
|
||||||
|
set: { presented in if !presented { factoryOverwrite = nil } }
|
||||||
|
),
|
||||||
|
titleVisibility: .visible,
|
||||||
|
presenting: factoryOverwrite
|
||||||
|
) { request in
|
||||||
|
// A starter rig is managed content: it is refreshed to the shipped version whenever the
|
||||||
|
// starter catalog updates, so it deliberately cannot be overwritten in place — that would
|
||||||
|
// silently revert on the next update. The player keeps their changes as a new rig instead.
|
||||||
|
Button("Save as New Rig…") {
|
||||||
|
// Defer one runloop hop: presenting the name-entry alert while the confirmation
|
||||||
|
// dialog is still dismissing can drop the new presentation on some SwiftUI versions.
|
||||||
|
let completion: () -> Void = request.completion
|
||||||
|
DispatchQueue.main.async { promptSaveAs(then: completion) }
|
||||||
|
}
|
||||||
|
Button("Cancel", role: .cancel) { }
|
||||||
|
} message: { request in
|
||||||
|
Text("“\(request.entry.name)” is a built-in starter rig and can't be changed in place. "
|
||||||
|
+ "Save your changes as a new rig to keep them.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private var presentationChrome: some View {
|
||||||
|
chromeWithPrompts
|
||||||
.confirmationDialog(
|
.confirmationDialog(
|
||||||
"Erase all rigs?",
|
"Erase all rigs?",
|
||||||
isPresented: $showEraseAllDialog,
|
isPresented: $showEraseAllDialog,
|
||||||
@@ -607,10 +649,18 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
onEraseAll: { showEraseAllDialog = true },
|
onEraseAll: { showEraseAllDialog = true },
|
||||||
onImportArchive: { showImporter = true },
|
onImportArchive: { showImporter = true },
|
||||||
onExportArchive: { exportArchiveAction() },
|
onExportArchive: { exportArchiveAction() },
|
||||||
|
onRestoreStarters: { restoreStarterRigs() },
|
||||||
onShowCloudStatus: { showICloudUnavailableAlert = true }
|
onShowCloudStatus: { showICloudUnavailableAlert = true }
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// (Re-)installs any shipped starter rigs missing from the library. Non-destructive: user rigs
|
||||||
|
/// are untouched, and already-present starters are skipped (matched by stable id).
|
||||||
|
private func restoreStarterRigs() {
|
||||||
|
let added: Int = RigLibraryBootstrap.restoreStarterRigs(into: library)
|
||||||
|
print("[ShoeGazeBuilderView] restored \(added) starter rig(s)")
|
||||||
|
}
|
||||||
|
|
||||||
// MARK: - Sleep / iCloud status
|
// MARK: - Sleep / iCloud status
|
||||||
|
|
||||||
/// Platform name for the settings app, used in the iCloud guidance alert.
|
/// Platform name for the settings app, used in the iCloud guidance alert.
|
||||||
@@ -1587,7 +1637,9 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
let wasRunning: Bool = shoeGaze.engine.isRunning
|
let wasRunning: Bool = shoeGaze.engine.isRunning
|
||||||
if wasRunning { shoeGaze.engine.stop() }
|
if wasRunning { shoeGaze.engine.stop() }
|
||||||
do {
|
do {
|
||||||
try shoeGaze.loadRig(from: entry.state)
|
// Keep the player's currently-chosen input across the switch (e.g. a live guitar), rather
|
||||||
|
// than snapping to the input the selected rig was authored with.
|
||||||
|
try shoeGaze.loadRig(from: entry.state, keepingCurrentInput: true)
|
||||||
currentRigID = entry.id
|
currentRigID = entry.id
|
||||||
selectedBoardIndex = 0
|
selectedBoardIndex = 0
|
||||||
autosave()
|
autosave()
|
||||||
@@ -1622,12 +1674,16 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
|
|
||||||
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
|
/// Whether the working rig differs from the library entry it was loaded from. A working rig with
|
||||||
/// no backing entry counts as dirty when it has any boards.
|
/// no backing entry counts as dirty when it has any boards.
|
||||||
|
///
|
||||||
|
/// Compares rig content only (boards, routers, MIDI, tempo) — not the live input source or engine
|
||||||
|
/// channel counts, which are intentionally kept across a rig switch and so must not register as
|
||||||
|
/// unsaved changes (otherwise switching between rigs always prompts to save).
|
||||||
private func isCurrentRigDirty() -> Bool {
|
private func isCurrentRigDirty() -> Bool {
|
||||||
guard let id: UUID = currentRigID,
|
guard let id: UUID = currentRigID,
|
||||||
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
|
let entry: RigEntry = library.entries.first(where: { $0.id == id }) else {
|
||||||
return !shoeGaze.boards.isEmpty
|
return !shoeGaze.boards.isEmpty
|
||||||
}
|
}
|
||||||
return shoeGaze.captureState() != entry.state
|
return !shoeGaze.captureState().hasSameRigContent(as: entry.state)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
|
/// Saves the current session over the loaded library entry, or prompts for a name when no entry
|
||||||
@@ -1649,6 +1705,12 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
}
|
}
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
// Overwriting a built-in starter rig replaces it in the library. Confirm first, offering a
|
||||||
|
// non-destructive "Save as New Rig" so the shipped original can be kept.
|
||||||
|
if FactoryRigLibrary.isFactory(existing.id) {
|
||||||
|
factoryOverwrite = FactoryOverwriteRequest(entry: existing, completion: completion)
|
||||||
|
return
|
||||||
|
}
|
||||||
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
|
persist(shoeGaze.captureEntry(name: existing.name, id: id), then: completion)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1664,13 +1726,16 @@ public struct ShoeGazeBuilderView: View {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Prompts for a name and saves the current session as a new library entry (new id).
|
/// Prompts for a name and saves the current session as a new library entry (new id).
|
||||||
private func promptSaveAs() {
|
///
|
||||||
|
/// - Parameter completion: Follow-up run once the new entry is persisted (e.g. the "Save & Clear"
|
||||||
|
/// clear step, or the pending action from a factory-rig overwrite prompt).
|
||||||
|
private func promptSaveAs(then completion: @escaping () -> Void = { }) {
|
||||||
namePrompt = RigNamePrompt(
|
namePrompt = RigNamePrompt(
|
||||||
title: "Save Rig As",
|
title: "Save Rig As",
|
||||||
initialText: currentRigName() ?? defaultNewRigName(),
|
initialText: currentRigName() ?? defaultNewRigName(),
|
||||||
confirmLabel: "Save"
|
confirmLabel: "Save"
|
||||||
) { name in
|
) { name in
|
||||||
persist(shoeGaze.captureEntry(name: name))
|
persist(shoeGaze.captureEntry(name: name), then: completion)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -5,6 +5,7 @@
|
|||||||
// SPDX-License-Identifier: MIT
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
|
import LyrebirdSynth
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
import LyrebirdShoeGaze
|
import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
|
|
||||||
import SwiftUI
|
import SwiftUI
|
||||||
import LyrebirdUI
|
import LyrebirdUI
|
||||||
|
import LyrebirdSynth
|
||||||
|
|
||||||
/// A vertical fader bound to a single ``UIParamNode``.
|
/// A vertical fader bound to a single ``UIParamNode``.
|
||||||
///
|
///
|
||||||
|
|||||||
@@ -0,0 +1,105 @@
|
|||||||
|
// ChainRouterPersistenceTests.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("ChainRouter persistence")
|
||||||
|
struct ChainRouterPersistenceTests {
|
||||||
|
|
||||||
|
@Test func routerRigRoundTripsThroughJSONAndRenders() throws {
|
||||||
|
// Build a routed session: two-pedal board A, one-pedal board B, selecting board B.
|
||||||
|
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
|
||||||
|
defer { try? FileManager.default.removeItem(at: urlA) }
|
||||||
|
let sessionA: ShoeGaze = ShoeGaze(engine: engineA)
|
||||||
|
let router: ChainRouter = try sessionA.makeChainRouter()
|
||||||
|
try router.addToA(FuzzPedal())
|
||||||
|
try router.addToA(OverdrivePedal())
|
||||||
|
try router.addToB(ReverbPedal())
|
||||||
|
router.mode = .b
|
||||||
|
try router.finalize()
|
||||||
|
|
||||||
|
let state: ShoeGazeState = sessionA.captureState()
|
||||||
|
#expect(state.routers?.count == 1, "router was not captured")
|
||||||
|
#expect(state.boards.isEmpty, "router rig should have no plain boards")
|
||||||
|
|
||||||
|
// JSON round-trip.
|
||||||
|
let data: Data = try JSONEncoder().encode(state)
|
||||||
|
let decoded: ShoeGazeState = try JSONDecoder().decode(ShoeGazeState.self, from: data)
|
||||||
|
#expect(decoded == state, "router state did not survive a JSON round-trip")
|
||||||
|
|
||||||
|
// Load into a fresh session and verify the router was rebuilt structurally.
|
||||||
|
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.2, numAudioBuses: 128)
|
||||||
|
defer { try? FileManager.default.removeItem(at: urlB) }
|
||||||
|
let sessionB: ShoeGaze = ShoeGaze(engine: engineB)
|
||||||
|
try sessionB.loadRig(from: decoded)
|
||||||
|
|
||||||
|
#expect(sessionB.routers.count == 1, "router was not rebuilt on load")
|
||||||
|
guard let rebuilt: ChainRouter = sessionB.routers.first else {
|
||||||
|
Issue.record("no rebuilt router")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
#expect(rebuilt.boardA.pedals.count == 2, "board A pedal count not restored")
|
||||||
|
#expect(rebuilt.boardB.pedals.count == 1, "board B pedal count not restored")
|
||||||
|
#expect(rebuilt.boardA.pedals.map { $0.displayName } == ["Fuzz", "Overdrive"])
|
||||||
|
#expect(rebuilt.boardB.pedals.map { $0.displayName } == ["Reverb"])
|
||||||
|
// mode == .b → branch A muted, branch B active.
|
||||||
|
#expect(rebuilt.splitter.branchAEnabled == 0.0, "branch A level not restored")
|
||||||
|
#expect(rebuilt.splitter.branchBEnabled == 1.0, "branch B level not restored")
|
||||||
|
|
||||||
|
// The rebuilt router should render audio (board B is the active path).
|
||||||
|
try engineB.start()
|
||||||
|
let samples: [Float] = readStereoCAF(url: urlB)
|
||||||
|
#expect(hasNonSilentOutput(samples), "rebuilt router produced silence")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func applyStateRecallsRouterParamsLive() throws {
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 128)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let session: ShoeGaze = ShoeGaze(engine: engine)
|
||||||
|
let router: ChainRouter = try session.makeChainRouter()
|
||||||
|
let fuzz: FuzzPedal = FuzzPedal()
|
||||||
|
fuzz.fuzz = 20.0
|
||||||
|
try router.addToA(fuzz)
|
||||||
|
try router.addToB(ReverbPedal())
|
||||||
|
router.mode = .a
|
||||||
|
try router.finalize()
|
||||||
|
|
||||||
|
let original: ShoeGazeState = session.captureState()
|
||||||
|
|
||||||
|
// Mutate live: change a router pedal param and flip the A/B selection.
|
||||||
|
fuzz.fuzz = 55.0
|
||||||
|
router.mode = .b
|
||||||
|
|
||||||
|
// Lightweight recall should restore the router pedal param and blend without a rebuild.
|
||||||
|
session.applyState(original)
|
||||||
|
|
||||||
|
#expect(fuzz.fuzz == 20.0, "router pedal param was not recalled")
|
||||||
|
#expect(router.splitter.branchAEnabled == 1.0, "branch A level not recalled")
|
||||||
|
#expect(router.splitter.branchBEnabled == 0.0, "branch B level not recalled")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func routerlessRigStoresNoRoutersKey() throws {
|
||||||
|
// A plain single-board session must not gain a `routers` payload (byte-compat with rigs
|
||||||
|
// saved before router persistence existed).
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let session: ShoeGaze = ShoeGaze(engine: engine)
|
||||||
|
let board: PedalBoard = try session.addBoard()
|
||||||
|
try board.add(FuzzPedal())
|
||||||
|
try session.finalizeBoard(board)
|
||||||
|
|
||||||
|
let state: ShoeGazeState = session.captureState()
|
||||||
|
#expect(state.routers == nil, "routerless rig should capture nil routers")
|
||||||
|
|
||||||
|
let json: String = String(data: try JSONEncoder().encode(state), encoding: .utf8) ?? ""
|
||||||
|
#expect(!json.contains("\"routers\""), "routerless JSON should omit the routers key")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,314 @@
|
|||||||
|
// DL4PedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A single decaying pluck so a test can hear the delay repeats in the silence after the note.
|
||||||
|
@MainActor
|
||||||
|
private final class TestPluckSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
private let burstDur: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
self.burstDur = burstDur
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
let env: Line.Control = Line.Control(start: amp, end: 0.0, dur: burstDur)
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq) * env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A steady sine for the bypass click test.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
init(targetBus: Int, freq: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("DL4Pedal")
|
||||||
|
struct DL4PedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let pluckHz: Double = 180.0
|
||||||
|
private let burstDur: Double = 0.08
|
||||||
|
private let renderDiffEpsilon: Double = 1.0e-3
|
||||||
|
|
||||||
|
private let modelCount: Int = 8
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
duration: Double = 1.2,
|
||||||
|
pluck: Bool = true,
|
||||||
|
amplitude: Double = 0.7,
|
||||||
|
configure: (DL4Pedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: SynthesizerBase = pluck
|
||||||
|
? TestPluckSource(targetBus: srcBus.index, freq: pluckHz, amplitude: amplitude, burstDur: burstDur)
|
||||||
|
: TestSineSource(targetBus: srcBus.index, freq: pluckHz)
|
||||||
|
let pedal: DL4Pedal = DL4Pedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analysis
|
||||||
|
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = Double(samples[2 * i])
|
||||||
|
sum += v * v
|
||||||
|
}
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func rmsDiff(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let n: Int = min(a.count, b.count) / 2
|
||||||
|
guard n > 0 else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in 0 ..< n {
|
||||||
|
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
|
||||||
|
sum += d * d
|
||||||
|
}
|
||||||
|
return (sum / Double(n)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Tail window (after the pluck has decayed), in interleaved frames.
|
||||||
|
private var tailSkip: Int { Int(0.5 * sampleRate) }
|
||||||
|
private var tailWindow: Int { 16_384 }
|
||||||
|
|
||||||
|
// MARK: - Behaviour
|
||||||
|
|
||||||
|
@Test func everyModelProducesEchoesAfterTheNote() throws {
|
||||||
|
// The pluck decays by burstDur (0.08 s). Every model must still produce audible repeats well
|
||||||
|
// into the tail at a long Time / Repeats.
|
||||||
|
for index: Int in 0 ..< modelCount {
|
||||||
|
let out: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = Double(index)
|
||||||
|
pedal.time = 0.25; pedal.repeats = 4.0; pedal.mod = 0.5
|
||||||
|
}
|
||||||
|
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
#expect(tail > 1.0e-3, "model index \(index) produced no echo tail, RMS \(tail)")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func modelsRenderDifferently() throws {
|
||||||
|
// Two different models at the same settings should produce substantially different output.
|
||||||
|
let tube: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.25; pedal.repeats = 3.0
|
||||||
|
}
|
||||||
|
let reverse: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 7.0; pedal.time = 0.25; pedal.repeats = 3.0
|
||||||
|
}
|
||||||
|
#expect(rmsDiff(tube, reverse) > renderDiffEpsilon,
|
||||||
|
"Tube and Reverse models should differ substantially, diff \(rmsDiff(tube, reverse))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func timeChangesTheEcho() throws {
|
||||||
|
let short: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.1; pedal.repeats = 3.0
|
||||||
|
}
|
||||||
|
let long: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.5; pedal.repeats = 3.0
|
||||||
|
}
|
||||||
|
#expect(rmsDiff(short, long) > renderDiffEpsilon,
|
||||||
|
"different delay times should render differently, diff \(rmsDiff(short, long))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func repeatsChangesTheTailLength() throws {
|
||||||
|
// More feedback (longer decay time) = a louder tail at the same point.
|
||||||
|
let few: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 0.3
|
||||||
|
}
|
||||||
|
let many: [Float] = try render { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 0.0; pedal.time = 0.2; pedal.repeats = 6.0
|
||||||
|
}
|
||||||
|
let tailFew: Double = rms(few, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
let tailMany: Double = rms(many, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
#expect(tailMany > tailFew,
|
||||||
|
"more repeats should ring louder in the tail: many \(tailMany) vs few \(tailFew)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func multiHeadStaysBelowClipping() throws {
|
||||||
|
// The Multi-Head tap sum (3 taps + a feedback repeat) is gain-staged to total 1.0, so a
|
||||||
|
// full-scale input, fully wet, must not clip even where the taps align.
|
||||||
|
let out: [Float] = try render(amplitude: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.model = 4.0; pedal.time = 0.15; pedal.repeats = 4.0
|
||||||
|
}
|
||||||
|
var peak: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (out.count / 2) {
|
||||||
|
let v: Double = abs(Double(out[2 * i]))
|
||||||
|
if v > peak { peak = v }
|
||||||
|
}
|
||||||
|
#expect(peak <= 1.05, "Multi-Head peaked at \(peak), above the 1.05 ceiling")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// Every model's node graph is deterministic (no RNG), so two identical renders are identical.
|
||||||
|
for index: Int in 0 ..< modelCount {
|
||||||
|
let a: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
|
||||||
|
let b: [Float] = try render(duration: 0.6) { pedal in pedal.model = Double(index); pedal.time = 0.2 }
|
||||||
|
#expect(a == b, "model index \(index) should render bit-identically")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass
|
||||||
|
|
||||||
|
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: pluckHz)
|
||||||
|
let pedal: DL4Pedal = DL4Pedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460
|
||||||
|
let flipFrame: Int = 15_435
|
||||||
|
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func exposesKnobsAndModelSelector() throws {
|
||||||
|
let pedal: DL4Pedal = DL4Pedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Repeats", "Tone", "Mod"])
|
||||||
|
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||||
|
#expect(selectors.map { $0.label } == ["Model"])
|
||||||
|
#expect(selectors.first?.stops.count == modelCount)
|
||||||
|
#expect(selectors.first?.stops.map { $0.title } ==
|
||||||
|
["Tube", "Tape", "Analog", "Analog Mod", "Multi-Head", "Sweep", "Lo-Res", "Reverse"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func timeIsTempoSyncable() throws {
|
||||||
|
let pedal: DL4Pedal = DL4Pedal()
|
||||||
|
#expect(pedal.tempoSyncableParams.map { $0.key } == ["time"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesControls() throws {
|
||||||
|
let pedal: DL4Pedal = DL4Pedal()
|
||||||
|
pedal.time = 0.33
|
||||||
|
pedal.repeats = 2.2
|
||||||
|
pedal.tone = 4000.0
|
||||||
|
pedal.mod = 0.7
|
||||||
|
pedal.model = 5.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: DL4Pedal = DL4Pedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.time == 0.33)
|
||||||
|
#expect(restored.repeats == 2.2)
|
||||||
|
#expect(restored.tone == 4000.0)
|
||||||
|
#expect(restored.mod == 0.7)
|
||||||
|
#expect(restored.model == 5.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "DL4")
|
||||||
|
#expect(pedal is DL4Pedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,136 @@
|
|||||||
|
// FactoryRigLibraryTests.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("FactoryRigLibrary")
|
||||||
|
struct FactoryRigLibraryTests {
|
||||||
|
|
||||||
|
// MARK: - Catalog integrity
|
||||||
|
|
||||||
|
@Test func catalogIsWellFormed() {
|
||||||
|
let rigs: [FactoryRig] = FactoryRigLibrary.all
|
||||||
|
#expect(rigs.count >= 6, "expected a full starter slate")
|
||||||
|
|
||||||
|
let ids: Set<UUID> = Set(rigs.map { $0.id })
|
||||||
|
#expect(ids.count == rigs.count, "rig ids must be unique")
|
||||||
|
|
||||||
|
let names: Set<String> = Set(rigs.map { $0.name })
|
||||||
|
#expect(names.count == rigs.count, "rig names must be unique")
|
||||||
|
|
||||||
|
let minBlurbLength: Int = 20
|
||||||
|
for rig: FactoryRig in rigs {
|
||||||
|
#expect(!rig.name.isEmpty, "\(rig.name) has empty name")
|
||||||
|
#expect(rig.blurb.count >= minBlurbLength, "\(rig.name) blurb too short")
|
||||||
|
}
|
||||||
|
|
||||||
|
// The slate should span more than one sonic family.
|
||||||
|
let categories: Set<FactoryRigCategory> = Set(rigs.map { $0.category })
|
||||||
|
#expect(categories.count >= 3, "starter slate should cover several categories")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func blurbsAvoidTrademarkedProductNames() {
|
||||||
|
// Guard against a blurb accidentally naming a real amp/pedal brand: factory rigs describe
|
||||||
|
// the sound, never a trademarked product.
|
||||||
|
let forbidden: [String] = [
|
||||||
|
"marshall", "fender", "vox", "mesa", "boss", "orange", "dumble", "roland", "ibanez",
|
||||||
|
]
|
||||||
|
for rig: FactoryRig in FactoryRigLibrary.all {
|
||||||
|
let haystack: String = (rig.name + " " + rig.blurb).lowercased()
|
||||||
|
for brand: String in forbidden {
|
||||||
|
#expect(!haystack.contains(brand), "\(rig.name) mentions '\(brand)'")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func factoryDetectionRecognisesEveryRigAndRejectsOthers() {
|
||||||
|
let rigs: [FactoryRig] = FactoryRigLibrary.all
|
||||||
|
#expect(FactoryRigLibrary.factoryIDs.count == rigs.count)
|
||||||
|
for rig: FactoryRig in rigs {
|
||||||
|
#expect(FactoryRigLibrary.isFactory(rig.id), "\(rig.name) not recognised as factory")
|
||||||
|
}
|
||||||
|
// A freshly generated id is not a factory rig.
|
||||||
|
#expect(!FactoryRigLibrary.isFactory(UUID()))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func categoryLookupAndGroupingCoverEveryRigOnce() {
|
||||||
|
for rig: FactoryRig in FactoryRigLibrary.all {
|
||||||
|
#expect(FactoryRigLibrary.category(for: rig.id) == rig.category,
|
||||||
|
"\(rig.name) category lookup mismatch")
|
||||||
|
}
|
||||||
|
#expect(FactoryRigLibrary.category(for: UUID()) == nil, "a random id has no category")
|
||||||
|
|
||||||
|
// Each category grouping contains only its own rigs, in catalog order.
|
||||||
|
for category: FactoryRigCategory in FactoryRigCategory.allCases {
|
||||||
|
let rigs: [FactoryRig] = FactoryRigLibrary.rigs(in: category)
|
||||||
|
#expect(rigs.allSatisfy { $0.category == category })
|
||||||
|
}
|
||||||
|
|
||||||
|
// Grouping by every category partitions the catalog exactly (no rig lost or duplicated).
|
||||||
|
let grouped: [FactoryRig] = FactoryRigCategory.allCases.flatMap { FactoryRigLibrary.rigs(in: $0) }
|
||||||
|
#expect(grouped.count == FactoryRigLibrary.all.count, "grouping dropped or duplicated a rig")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Seeding entries
|
||||||
|
|
||||||
|
@Test func makeEntriesMatchesCatalogAndIsStable() throws {
|
||||||
|
let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
|
||||||
|
let rigs: [FactoryRig] = FactoryRigLibrary.all
|
||||||
|
|
||||||
|
#expect(entries.count == rigs.count, "one entry per rig")
|
||||||
|
for (entry, rig): (RigEntry, FactoryRig) in zip(entries, rigs) {
|
||||||
|
#expect(entry.id == rig.id, "entry id must be the rig's stable id")
|
||||||
|
#expect(entry.name == rig.name)
|
||||||
|
// A rig builds either plain boards or a router (or both) — never nothing.
|
||||||
|
let routerStates: [ChainRouterState] = entry.state.routers ?? []
|
||||||
|
#expect(!entry.state.boards.isEmpty || !routerStates.isEmpty, "\(rig.name) built nothing")
|
||||||
|
let boardPedals: Int = entry.state.boards.reduce(0) { $0 + $1.pedals.count }
|
||||||
|
let routerPedals: Int = routerStates.reduce(0) { $0 + $1.boardA.count + $1.boardB.count }
|
||||||
|
#expect(boardPedals + routerPedals >= 3, "\(rig.name) should build a non-trivial chain")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stable ids: re-seeding yields identical ids (so a re-seed overwrites in place).
|
||||||
|
let again: [RigEntry] = try FactoryRigLibrary.makeEntries()
|
||||||
|
#expect(entries.map { $0.id } == again.map { $0.id })
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func entriesRoundTripThroughJSON() throws {
|
||||||
|
let encoder: JSONEncoder = JSONEncoder()
|
||||||
|
let decoder: JSONDecoder = JSONDecoder()
|
||||||
|
for entry: RigEntry in try FactoryRigLibrary.makeEntries() {
|
||||||
|
let data: Data = try encoder.encode(entry)
|
||||||
|
let decoded: RigEntry = try decoder.decode(RigEntry.self, from: data)
|
||||||
|
#expect(decoded == entry, "\(entry.name) did not survive a JSON round-trip")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Load + render (full ship path)
|
||||||
|
|
||||||
|
@Test func everyFactoryEntryLoadsAndRenders() throws {
|
||||||
|
let renderDuration: Double = 0.2
|
||||||
|
let numAudioBuses: Int = 128
|
||||||
|
|
||||||
|
for entry: RigEntry in try FactoryRigLibrary.makeEntries() {
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: renderDuration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let session: ShoeGaze = ShoeGaze(engine: engine)
|
||||||
|
try session.loadRig(from: entry.state)
|
||||||
|
|
||||||
|
try engine.start()
|
||||||
|
let samples: [Float] = readStereoCAF(url: url)
|
||||||
|
#expect(hasNonSilentOutput(samples), "\(entry.name) rendered silence")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,382 @@
|
|||||||
|
// GranularReverbPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A steady sine source.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A decaying sine burst (full at t=0, silent after `burstDur`) for tail checks.
|
||||||
|
@MainActor
|
||||||
|
private final class TestBurstSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
private let burstDur: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
self.burstDur = burstDur
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
let envelope: Line.Control = Line.Control(start: 1.0, end: 0.0, dur: burstDur)
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp) * envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("GranularReverbPedal")
|
||||||
|
struct GranularReverbPedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let sineHz: Double = 220.0
|
||||||
|
private let analysisSkipFrames: Int = 13_230 // ~0.3 s, clears warm-up
|
||||||
|
private let analysisWindowFrames: Int = 16_384
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
duration: Double,
|
||||||
|
makeSource: @escaping (Int) -> any Synthesizer,
|
||||||
|
configure: (GranularReverbPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: any Synthesizer = makeSource(srcBus.index)
|
||||||
|
let pedal: GranularReverbPedal = GranularReverbPedal(
|
||||||
|
inputBus: srcBus.index,
|
||||||
|
outputBus: dstBus.index
|
||||||
|
)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analysis
|
||||||
|
|
||||||
|
/// Normalised peak autocorrelation of the left channel over the analysis window — a "tonalness"
|
||||||
|
/// score in ~[0, 1]: near 1 for a clean periodic tone, low for a smeared/inharmonic cloud.
|
||||||
|
private func tonalness(_ samples: [Float]) -> Double {
|
||||||
|
let needed: Int = analysisSkipFrames + analysisWindowFrames
|
||||||
|
guard samples.count >= 2 * needed else { return 0.0 }
|
||||||
|
var x: [Double] = []
|
||||||
|
x.reserveCapacity(analysisWindowFrames)
|
||||||
|
for i: Int in analysisSkipFrames ..< needed {
|
||||||
|
x.append(Double(samples[2 * i]))
|
||||||
|
}
|
||||||
|
let mean: Double = x.reduce(0.0, +) / Double(x.count)
|
||||||
|
for i: Int in x.indices { x[i] -= mean }
|
||||||
|
|
||||||
|
var zeroLag: Double = 0.0
|
||||||
|
for v: Double in x { zeroLag += v * v }
|
||||||
|
guard zeroLag > 0.0 else { return 0.0 }
|
||||||
|
|
||||||
|
let minLag: Int = Int(sampleRate / 1_000.0) // up to 1 kHz
|
||||||
|
let maxLag: Int = min(Int(sampleRate / 50.0), x.count - 1)
|
||||||
|
var best: Double = 0.0
|
||||||
|
for lag: Int in minLag ... maxLag {
|
||||||
|
var c: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (x.count - lag) {
|
||||||
|
c += x[i] * x[i + lag]
|
||||||
|
}
|
||||||
|
if c > best { best = c }
|
||||||
|
}
|
||||||
|
return best / zeroLag
|
||||||
|
}
|
||||||
|
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b { let v: Double = Double(samples[2 * i]); sum += v * v }
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Peak absolute left-channel sample over an interleaved-frame range `[loFrame, hiFrame)`.
|
||||||
|
private func peak(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = abs(Double(samples[2 * i]))
|
||||||
|
if v > m { m = v }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Behaviour
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 0.8,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { _ in }
|
||||||
|
)
|
||||||
|
#expect(!out.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(out), "granular-reverb output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func higherScatterSmearsPitchIntoBroadbandHaze() throws {
|
||||||
|
// The defining character: at pitch 0 and scatter 0 the cloud tracks the input's pitch
|
||||||
|
// (fairly tonal); raising scatter sprays grains across random ratios, smearing the output
|
||||||
|
// into a broadband haze (low tonalness) — a grain cloud, not a coherent shimmer.
|
||||||
|
let coherent: [Float] = try render(
|
||||||
|
duration: 1.0,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.pitch = 0.0
|
||||||
|
pedal.scatter = 0.0
|
||||||
|
pedal.density = 60.0
|
||||||
|
pedal.decay = 0.8 // short tail so cloud tonalness dominates the window
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let smeared: [Float] = try render(
|
||||||
|
duration: 1.0,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.pitch = 0.0
|
||||||
|
pedal.scatter = 0.5
|
||||||
|
pedal.density = 60.0
|
||||||
|
pedal.decay = 0.8
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let coherentTonalness: Double = tonalness(coherent)
|
||||||
|
let smearedTonalness: Double = tonalness(smeared)
|
||||||
|
#expect(hasNonSilentOutput(smeared), "smeared render was silent")
|
||||||
|
#expect(coherentTonalness > smearedTonalness * 1.3,
|
||||||
|
"scatter should smear pitch (coherent \(coherentTonalness) vs smeared \(smearedTonalness))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func densityNormalizationBoundsThePeak() throws {
|
||||||
|
// Worst case for clipping: max density × max grain (heaviest overlap), scatter 0 (grains
|
||||||
|
// correlated), fully wet, driven by a near-full-scale sine. The sqrt power normalisation must
|
||||||
|
// keep the output peak bounded — nothing downstream limits it.
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 1.0,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz, amplitude: 0.9) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.density = 80.0
|
||||||
|
pedal.grain = 0.3
|
||||||
|
pedal.scatter = 0.0
|
||||||
|
pedal.decay = 12.0 // longest tail → most reverb buildup, worst case for peak
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let peakOut: Double = peak(out, loFrame: Int(0.3 * sampleRate), hiFrame: Int(0.95 * sampleRate))
|
||||||
|
#expect(hasNonSilentOutput(out), "max-overlap render was silent")
|
||||||
|
#expect(peakOut < 1.0, "density normalisation should keep the peak below clipping, got \(peakOut)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func densityChangesTheTexture() throws {
|
||||||
|
// Normalisation keeps the LEVEL roughly constant, but density still changes the grain
|
||||||
|
// texture — a sparse and a dense cloud must not render identically, and both must sound.
|
||||||
|
let sparse: [Float] = try render(
|
||||||
|
duration: 1.0,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.density = 8.0; pedal.scatter = 0.1; pedal.decay = 1.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let dense: [Float] = try render(
|
||||||
|
duration: 1.0,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.density = 70.0; pedal.scatter = 0.1; pedal.decay = 1.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
#expect(hasNonSilentOutput(sparse) && hasNonSilentOutput(dense), "a density render was silent")
|
||||||
|
#expect(sparse != dense, "sparse and dense clouds should render differently")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reverbTailPersistsAfterInput() throws {
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 1.4,
|
||||||
|
makeSource: { bus in
|
||||||
|
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.15)
|
||||||
|
},
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.decay = 6.0
|
||||||
|
pedal.density = 40.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate))
|
||||||
|
#expect(lateRMS > 1.0e-4, "granular-reverb tail should still ring late, got \(lateRMS)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// The grain cloud is seeded and GVerb is RNG-free, so two identical renders are bit-identical.
|
||||||
|
let make: () throws -> [Float] = {
|
||||||
|
try self.render(
|
||||||
|
duration: 0.8,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.scatter = 0.3
|
||||||
|
pedal.density = 30.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
let a: [Float] = try make()
|
||||||
|
let b: [Float] = try make()
|
||||||
|
#expect(a == b, "seeded granular-reverb renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass
|
||||||
|
|
||||||
|
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: GranularReverbPedal = GranularReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460
|
||||||
|
let flipFrame: Int = 15_435
|
||||||
|
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func exposesSixKnobs() throws {
|
||||||
|
let pedal: GranularReverbPedal = GranularReverbPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label }
|
||||||
|
== ["Decay", "Density", "Grain", "Pitch", "Scatter", "Damp"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesKnobs() throws {
|
||||||
|
let pedal: GranularReverbPedal = GranularReverbPedal()
|
||||||
|
pedal.decay = 5.0
|
||||||
|
pedal.density = 40.0
|
||||||
|
pedal.grain = 0.2
|
||||||
|
pedal.pitch = 12.0
|
||||||
|
pedal.scatter = 0.3
|
||||||
|
pedal.damp = 0.4
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: GranularReverbPedal = GranularReverbPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.decay == 5.0)
|
||||||
|
#expect(restored.density == 40.0)
|
||||||
|
#expect(restored.grain == 0.2)
|
||||||
|
#expect(restored.pitch == 12.0)
|
||||||
|
#expect(restored.scatter == 0.3)
|
||||||
|
#expect(restored.damp == 0.4)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Granular Reverb")
|
||||||
|
#expect(pedal is GranularReverbPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,495 @@
|
|||||||
|
// KarplusResonatorPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A single decaying pluck: a sine whose amplitude ramps from full to zero over `burstDur`, then
|
||||||
|
/// holds silent. Lets a test see the resonator bank ring on in the silence after the note has gone.
|
||||||
|
@MainActor
|
||||||
|
private final class TestPluckSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
private let burstDur: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
self.burstDur = burstDur
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
// Line 1→0 over burstDur, holding 0 after — a pluck that decays to silence, so the pedal's
|
||||||
|
// gate opens during the note and closes once it has faded, letting the strings ring.
|
||||||
|
let env: Line.Control = Line.Control(start: amp, end: 0.0, dur: burstDur)
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq) * env)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A steady sine source for the bypass click test — a stable tone with no silence, so the transition
|
||||||
|
/// step can be compared against a real steady-state slope.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("KarplusResonatorPedal")
|
||||||
|
struct KarplusResonatorPedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let pluckHz: Double = 110.0
|
||||||
|
private let burstDur: Double = 0.4
|
||||||
|
/// Minimum RMS to count a tail as an audible, sustained ring.
|
||||||
|
private let tailRmsFloor: Double = 1.0e-3
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
private func renderPluck(
|
||||||
|
duration: Double = 2.0,
|
||||||
|
amplitude: Double = 0.7,
|
||||||
|
configure: (KarplusResonatorPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
try render(duration: duration, pluck: true, amplitude: amplitude, configure: configure)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
duration: Double,
|
||||||
|
pluck: Bool,
|
||||||
|
amplitude: Double = 0.7,
|
||||||
|
configure: (KarplusResonatorPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: SynthesizerBase = pluck
|
||||||
|
? TestPluckSource(targetBus: srcBus.index, freq: pluckHz, amplitude: amplitude, burstDur: burstDur)
|
||||||
|
: TestSineSource(targetBus: srcBus.index, freq: pluckHz)
|
||||||
|
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analysis
|
||||||
|
|
||||||
|
/// RMS of the left channel over an interleaved-frame range `[loFrame, hiFrame)`.
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = Double(samples[2 * i])
|
||||||
|
sum += v * v
|
||||||
|
}
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Autocorrelation fundamental of the left channel over `[skip, skip + window)`, searching
|
||||||
|
/// `[minHz, maxHz]`.
|
||||||
|
private func fundamentalHz(
|
||||||
|
_ samples: [Float],
|
||||||
|
skip: Int,
|
||||||
|
window: Int,
|
||||||
|
minHz: Double,
|
||||||
|
maxHz: Double
|
||||||
|
) -> Double {
|
||||||
|
let needed: Int = skip + window
|
||||||
|
guard samples.count >= 2 * needed else { return 0.0 }
|
||||||
|
var x: [Double] = []
|
||||||
|
x.reserveCapacity(window)
|
||||||
|
for i: Int in skip ..< needed {
|
||||||
|
x.append(Double(samples[2 * i]))
|
||||||
|
}
|
||||||
|
let mean: Double = x.reduce(0.0, +) / Double(x.count)
|
||||||
|
for i: Int in x.indices { x[i] -= mean }
|
||||||
|
|
||||||
|
let minLag: Int = Int(sampleRate / maxHz)
|
||||||
|
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
|
||||||
|
guard maxLag > minLag else { return 0.0 }
|
||||||
|
|
||||||
|
var bestLag: Int = minLag
|
||||||
|
var bestCorr: Double = -Double.infinity
|
||||||
|
for lag: Int in minLag ... maxLag {
|
||||||
|
var c: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (x.count - lag) {
|
||||||
|
c += x[i] * x[i + lag]
|
||||||
|
}
|
||||||
|
if c > bestCorr {
|
||||||
|
bestCorr = c
|
||||||
|
bestLag = lag
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sampleRate / Double(bestLag)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RMS of the sample-by-sample difference between two renders' left channels over `[loFrame, hiFrame)`.
|
||||||
|
private func rmsDiff(_ a: [Float], _ b: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let lo: Int = max(0, loFrame)
|
||||||
|
let hi: Int = min(hiFrame, min(a.count, b.count) / 2)
|
||||||
|
guard hi > lo else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in lo ..< hi {
|
||||||
|
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
|
||||||
|
sum += d * d
|
||||||
|
}
|
||||||
|
return (sum / Double(hi - lo)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Start of the tail-analysis window, in frames — well past the pluck's decay to silence, so only
|
||||||
|
/// the ringing resonator bank remains.
|
||||||
|
private var tailSkipFrames: Int { Int(0.7 * sampleRate) }
|
||||||
|
/// Tail-analysis window length in frames (~0.37 s).
|
||||||
|
private var tailWindowFrames: Int { 16_384 }
|
||||||
|
|
||||||
|
// MARK: - Behaviour
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let out: [Float] = try renderPluck { _ in }
|
||||||
|
#expect(!out.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(out), "resonator output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func ringsAfterNoteDecays() throws {
|
||||||
|
// The pluck decays to silence by burstDur (0.4 s). A plain effect would then be silent; the
|
||||||
|
// sympathetic strings keep ringing, so the tail well past the note is non-trivial.
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
}
|
||||||
|
let tail: Double = rms(out, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
|
||||||
|
#expect(tail > tailRmsFloor, "expected a sustained sympathetic ring after the note, tail RMS \(tail)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func tailIsPitchedToTuneRoot() throws {
|
||||||
|
// Drone voicing tunes the strings to root/5th/oct/oct+5th, which all share the root's period,
|
||||||
|
// so the ringing tail's fundamental sits at the Tune root (not the 110 Hz pluck pitch).
|
||||||
|
let tune: Double = 82.41
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tune = tune; pedal.voicing = 0.0
|
||||||
|
}
|
||||||
|
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 40.0, maxHz: 400.0)
|
||||||
|
let tolerance: Double = 0.1
|
||||||
|
#expect(abs(f - tune) / tune < tolerance,
|
||||||
|
"tail fundamental \(f) Hz should sit near the Tune root \(tune) Hz")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func sustainLengthensTheTail() throws {
|
||||||
|
// More sustain = higher string feedback = a louder ring at the same point in the tail.
|
||||||
|
let low: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.1; pedal.sensitivity = 0.6
|
||||||
|
}
|
||||||
|
let high: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.95; pedal.sensitivity = 0.6
|
||||||
|
}
|
||||||
|
let tailLow: Double = rms(low, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
|
||||||
|
let tailHigh: Double = rms(high, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
|
||||||
|
#expect(tailHigh > tailLow,
|
||||||
|
"higher sustain should ring louder in the tail: high \(tailHigh) vs low \(tailLow)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func voicingRetunesTheRing() throws {
|
||||||
|
// Each voicing tunes the strings to a different chord, so the ringing tail differs
|
||||||
|
// substantially between two voicings at the same Tune root.
|
||||||
|
let tune: Double = 82.41
|
||||||
|
let drone: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tune = tune; pedal.voicing = 0.0
|
||||||
|
}
|
||||||
|
let octaves: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tune = tune; pedal.voicing = 1.0
|
||||||
|
}
|
||||||
|
let diff: Double = rmsDiff(drone, octaves, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
|
||||||
|
let droneTail: Double = rms(drone, loFrame: tailSkipFrames, hiFrame: tailSkipFrames + tailWindowFrames)
|
||||||
|
// The difference should be a real fraction of the ring, not analysis noise.
|
||||||
|
#expect(diff > droneTail * 0.25,
|
||||||
|
"two voicings should ring differently: tail diff \(diff) vs drone tail \(droneTail)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func freeModeReachesTrebleStaffTop() throws {
|
||||||
|
// Free-mode Tune now reaches E5 (≈ 659 Hz, top of the treble staff). Drone voicing shares the
|
||||||
|
// root period, so the ring's fundamental sits at the set root.
|
||||||
|
let e5: Double = 659.25
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tuning = 0.0; pedal.tune = e5; pedal.voicing = 0.0
|
||||||
|
}
|
||||||
|
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 300.0, maxHz: 900.0)
|
||||||
|
#expect(abs(f - e5) / e5 < 0.1, "Free Tune at E5 should ring near \(e5) Hz, got \(f)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// Every node in the bank is deterministic (no RNG), so two identical renders are bit-identical.
|
||||||
|
let a: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
|
||||||
|
let b: [Float] = try renderPluck { pedal in pedal.sustain = 0.8; pedal.voicing = 2.0 }
|
||||||
|
#expect(a == b, "deterministic resonator renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func fullScaleBankStaysBelowClipping() throws {
|
||||||
|
// A full-scale pluck at max sustain, fully wet. The bank is scaled by 1/stringCount, so even
|
||||||
|
// when a voicing's strings align (shared periods) the summed output must stay near unity —
|
||||||
|
// no clipping without a limiter. Checked across all three voicings.
|
||||||
|
let ceiling: Double = 1.05
|
||||||
|
for voicingIndex: Int in 0 ..< 3 {
|
||||||
|
let out: [Float] = try renderPluck(amplitude: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 1.0; pedal.sensitivity = 0.8
|
||||||
|
pedal.voicing = Double(voicingIndex)
|
||||||
|
}
|
||||||
|
var peak: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (out.count / 2) {
|
||||||
|
let v: Double = abs(Double(out[2 * i]))
|
||||||
|
if v > peak { peak = v }
|
||||||
|
}
|
||||||
|
#expect(peak <= ceiling, "voicing \(voicingIndex) peaked at \(peak), above the \(ceiling) ceiling")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass
|
||||||
|
|
||||||
|
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: pluckHz)
|
||||||
|
let pedal: KarplusResonatorPedal = KarplusResonatorPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
pedal.sustain = 0.7
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460
|
||||||
|
let flipFrame: Int = 15_435
|
||||||
|
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func exposesControls() throws {
|
||||||
|
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Tune", "Sustain", "Tone", "Sensitivity"])
|
||||||
|
// One Tuning switch, Free/Pitched.
|
||||||
|
#expect(pedal.effectSwitches.map { $0.label } == ["Tuning"])
|
||||||
|
let tuning: PedalSwitch? = pedal.effectSwitches.first { $0.label == "Tuning" }
|
||||||
|
#expect(tuning?.options.map { $0.title } == ["Free", "Pitched"])
|
||||||
|
#expect(tuning?.rebuildsOnChange == true)
|
||||||
|
// Default (Free) shows only the Voicing selector — the Root note knob is hidden.
|
||||||
|
#expect(pedal.effectSelectors.map { $0.label } == ["Voicing"])
|
||||||
|
#expect(pedal.effectSelectors.first?.stops.map { $0.title } == ["Drone", "Octaves", "Shimmer"])
|
||||||
|
|
||||||
|
// Pitched reveals the Root chromatic selector at index 1, spanning E1 … E5.
|
||||||
|
pedal.tuning = 1.0
|
||||||
|
#expect(pedal.effectSelectors.map { $0.label } == ["Voicing", "Root"])
|
||||||
|
let root: PedalSelectorKnob? = pedal.effectSelectors.first { $0.label == "Root" }
|
||||||
|
#expect(root?.stops.count == 49) // MIDI 28 … 76 inclusive
|
||||||
|
#expect(root?.stops.first?.title == "E1")
|
||||||
|
#expect(root?.stops.last?.title == "E5")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func frequencyMapsEqualTemperament() throws {
|
||||||
|
// A4 = 440 (MIDI 69), so A3 (MIDI 57) = 220; C4 (middle C, MIDI 60) ≈ 261.63.
|
||||||
|
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 57) - 220.0) < 0.01)
|
||||||
|
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 69) - 440.0) < 0.01)
|
||||||
|
#expect(abs(KarplusResonatorPedal.frequency(forMidiNote: 60) - 261.6256) < 0.01)
|
||||||
|
#expect(KarplusResonatorPedal.caption(forMidiNote: 28) == "E1")
|
||||||
|
#expect(KarplusResonatorPedal.caption(forMidiNote: 57) == "A3")
|
||||||
|
#expect(KarplusResonatorPedal.caption(forMidiNote: 76) == "E5")
|
||||||
|
#expect(KarplusResonatorPedal.caption(forMidiNote: 61) == "C♯4") // sharp pitch class
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func pitchedModeTunesTheRootToThePitch() throws {
|
||||||
|
// Tuning = Pitched, A3 (MIDI 57), Drone voicing → the ring's fundamental sits at 220 Hz
|
||||||
|
// regardless of the 110 Hz pluck or the Tune Hz knob.
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tune = 60.0 // deliberately off, to prove Pitched overrides it
|
||||||
|
pedal.tuning = 1.0; pedal.pitchedNote = 57.0
|
||||||
|
}
|
||||||
|
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 400.0)
|
||||||
|
#expect(abs(f - 220.0) / 220.0 < 0.1, "Pitched A3 should ring near 220 Hz, got \(f)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func pitchedModeOctaveRaisesThePitch() throws {
|
||||||
|
// A3 (MIDI 57) vs A4 (MIDI 69) — one octave up should roughly double the ring fundamental.
|
||||||
|
let a3: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tuning = 1.0; pedal.pitchedNote = 57.0
|
||||||
|
}
|
||||||
|
let a4: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tuning = 1.0; pedal.pitchedNote = 69.0
|
||||||
|
}
|
||||||
|
let f3: Double = fundamentalHz(a3, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0)
|
||||||
|
let f4: Double = fundamentalHz(a4, skip: tailSkipFrames, window: tailWindowFrames, minHz: 120.0, maxHz: 700.0)
|
||||||
|
#expect(f4 > f3 * 1.5, "A4 should ring well above A3: a4 \(f4) vs a3 \(f3)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func pitchedModeReachesTrebleStaffTop() throws {
|
||||||
|
// The Root selector's top stop is E5 (MIDI 76 ≈ 659 Hz). Drone voicing shares the root period.
|
||||||
|
let e5: Double = 659.25
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tuning = 1.0; pedal.pitchedNote = 76.0; pedal.voicing = 0.0
|
||||||
|
}
|
||||||
|
let f: Double = fundamentalHz(out, skip: tailSkipFrames, window: tailWindowFrames, minHz: 300.0, maxHz: 900.0)
|
||||||
|
#expect(abs(f - e5) / e5 < 0.1, "Pitched E5 should ring near \(e5) Hz, got \(f)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesControls() throws {
|
||||||
|
let pedal: KarplusResonatorPedal = KarplusResonatorPedal()
|
||||||
|
pedal.tune = 123.4
|
||||||
|
pedal.sustain = 0.85
|
||||||
|
pedal.tone = 0.6
|
||||||
|
pedal.sensitivity = 0.3
|
||||||
|
pedal.voicing = 2.0
|
||||||
|
pedal.tuning = 1.0 // Pitched, so the Root selector is captured
|
||||||
|
pedal.pitchedNote = 64.0 // E4
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: KarplusResonatorPedal = KarplusResonatorPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.tune == 123.4)
|
||||||
|
#expect(restored.sustain == 0.85)
|
||||||
|
#expect(restored.tone == 0.6)
|
||||||
|
#expect(restored.sensitivity == 0.3)
|
||||||
|
#expect(restored.voicing == 2.0)
|
||||||
|
#expect(restored.tuning == 1.0)
|
||||||
|
#expect(restored.pitchedNote == 64.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func freeStateRestoresOntoAPitchedPedal() throws {
|
||||||
|
// A Free preset applied to an instance already in Pitched mode: the switch pass writes
|
||||||
|
// tuning = 0 before effectSelectors is re-read, so the selector list collapses to [Voicing]
|
||||||
|
// and the stale Root value is dropped — no positional corruption.
|
||||||
|
let saved: KarplusResonatorPedal = KarplusResonatorPedal() // defaults to Free
|
||||||
|
saved.voicing = 1.0
|
||||||
|
saved.tune = 200.0
|
||||||
|
let state: PedalState = saved.captureState()
|
||||||
|
#expect(state.selectorValues.count == 1, "a Free preset should carry only the Voicing selector")
|
||||||
|
|
||||||
|
let target: KarplusResonatorPedal = KarplusResonatorPedal()
|
||||||
|
target.tuning = 1.0 // put it in Pitched first
|
||||||
|
target.pitchedNote = 76.0
|
||||||
|
target.applyState(state)
|
||||||
|
|
||||||
|
#expect(target.tuning == 0.0, "restoring a Free preset should return the switch to Free")
|
||||||
|
#expect(target.voicing == 1.0)
|
||||||
|
#expect(target.tune == 200.0)
|
||||||
|
#expect(target.effectSelectors.map { $0.label } == ["Voicing"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func pitchedNoteClampsOutOfRange() throws {
|
||||||
|
// A pitchedNote past the Root selector's E1…E5 window still rings (clamped at build time),
|
||||||
|
// never crashing or going silent.
|
||||||
|
let out: [Float] = try renderPluck { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.sustain = 0.9; pedal.sensitivity = 0.6
|
||||||
|
pedal.tuning = 1.0; pedal.pitchedNote = 200.0 // far above E5
|
||||||
|
}
|
||||||
|
#expect(hasNonSilentOutput(out), "out-of-range pitchedNote should clamp and still ring")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Karplus Resonator")
|
||||||
|
#expect(pedal is KarplusResonatorPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -100,28 +100,110 @@ struct MutantPedalTests {
|
|||||||
pedal.mode = 2.0 // highpass
|
pedal.mode = 2.0 // highpass
|
||||||
pedal.direction = 0.0 // down
|
pedal.direction = 0.0 // down
|
||||||
|
|
||||||
|
pedal.range = 1.0 // high band
|
||||||
|
pedal.sweep = 12.0
|
||||||
|
pedal.attack = 0.02
|
||||||
|
pedal.release = 0.3
|
||||||
|
|
||||||
let state: PedalState = pedal.captureState()
|
let state: PedalState = pedal.captureState()
|
||||||
#expect(state.switchValues == [0.0, 2.0]) // [direction, mode]
|
#expect(state.switchValues == [0.0, 2.0, 1.0]) // [direction, mode, range]
|
||||||
|
#expect(state.advancedValues == [12.0, 0.02, 0.3]) // [sweep, attack, release]
|
||||||
|
|
||||||
let restored: MutantPedal = MutantPedal()
|
let restored: MutantPedal = MutantPedal()
|
||||||
restored.applyState(state)
|
restored.applyState(state)
|
||||||
#expect(restored.mode == 2.0)
|
#expect(restored.mode == 2.0)
|
||||||
#expect(restored.direction == 0.0)
|
#expect(restored.direction == 0.0)
|
||||||
|
#expect(restored.range == 1.0)
|
||||||
|
#expect(restored.sweep == 12.0)
|
||||||
|
#expect(restored.attack == 0.02)
|
||||||
|
#expect(restored.release == 0.3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func oldTwoSwitchStateStillLoads() throws {
|
||||||
|
// A rig saved before Range / the advanced knobs existed carries only [direction, mode] and
|
||||||
|
// an empty advancedValues; it must load without mis-mapping, leaving the new controls at
|
||||||
|
// their defaults.
|
||||||
|
let legacy: PedalState = PedalState(
|
||||||
|
type: "Mutant",
|
||||||
|
knobValues: [2.5, 4.0, 1, 1], // sensitivity, resonance, mix, level
|
||||||
|
switchValues: [1.0, 0.0], // direction=up, mode=lowpass
|
||||||
|
bypass: 0
|
||||||
|
)
|
||||||
|
let pedal: MutantPedal = MutantPedal()
|
||||||
|
pedal.applyState(legacy)
|
||||||
|
#expect(pedal.direction == 1.0)
|
||||||
|
#expect(pedal.mode == 0.0)
|
||||||
|
#expect(pedal.sensitivity == 2.5)
|
||||||
|
#expect(pedal.resonance == 4.0)
|
||||||
|
// New controls keep their defaults.
|
||||||
|
#expect(pedal.range == 0.0)
|
||||||
|
#expect(pedal.sweep == 20.0)
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func exposesSensitivityAndResonanceKnobs() throws {
|
@Test func exposesSensitivityAndResonanceKnobs() throws {
|
||||||
let pedal: MutantPedal = MutantPedal()
|
let pedal: MutantPedal = MutantPedal()
|
||||||
let labels: [String] = pedal.effectKnobs.map { $0.label }
|
#expect(pedal.effectKnobs.map { $0.label } == ["Sensitivity", "Resonance"])
|
||||||
#expect(labels == ["Sensitivity", "Resonance"])
|
#expect(pedal.advancedKnobs.map { $0.label } == ["Sweep", "Attack", "Release"])
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func exposesTwoStateSweepAndThreeStateModeSwitches() throws {
|
@Test func exposesDirectionModeAndRangeSwitches() throws {
|
||||||
let pedal: MutantPedal = MutantPedal()
|
let pedal: MutantPedal = MutantPedal()
|
||||||
let switches: [PedalSwitch] = pedal.effectSwitches
|
let switches: [PedalSwitch] = pedal.effectSwitches
|
||||||
#expect(switches.map { $0.label } == ["Sweep", "Mode"])
|
#expect(switches.map { $0.label } == ["Direction", "Mode", "Range"])
|
||||||
// Two-state sweep (Down/Up), three-state mode (LP/BP/HP).
|
#expect(switches[0].options.map { $0.title } == ["Down", "Up"])
|
||||||
#expect(switches.first?.options.map { $0.title } == ["Down", "Up"])
|
#expect(switches[1].options.map { $0.title } == ["LP", "BP", "HP"])
|
||||||
#expect(switches.last?.options.map { $0.title } == ["LP", "BP", "HP"])
|
#expect(switches[2].options.map { $0.title } == ["Lo", "Hi"])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the test loop through a Mutant configured by `configure`, returning a mid-render window.
|
||||||
|
private func renderWindow(configure: (MutantPedal) -> Void) throws -> [Float] {
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.1, numAudioBuses: 64)
|
||||||
|
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: MutantPedal = MutantPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let skip: Int = 1024
|
||||||
|
let window: Int = 2048
|
||||||
|
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
|
||||||
|
return zip(a[skip..<(skip + window)], b[skip..<(skip + window)]).reduce(0.0) { acc, pair in
|
||||||
|
let d: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + d * d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func sweepAmountChangesOutput() throws {
|
||||||
|
let narrow: [Float] = try renderWindow { $0.sweep = 3.0 }
|
||||||
|
let wide: [Float] = try renderWindow { $0.sweep = 45.0 }
|
||||||
|
#expect(hasNonSilentOutput(narrow))
|
||||||
|
#expect(hasNonSilentOutput(wide))
|
||||||
|
#expect(windowSSD(narrow, wide) > 0, "sweep amount did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rangeSwitchChangesOutput() throws {
|
||||||
|
let low: [Float] = try renderWindow { $0.range = 0.0 }
|
||||||
|
let high: [Float] = try renderWindow { $0.range = 1.0 }
|
||||||
|
#expect(windowSSD(low, high) > 0, "range band did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func attackReleaseChangesOutput() throws {
|
||||||
|
let fast: [Float] = try renderWindow { $0.attack = 0.001; $0.release = 0.03 }
|
||||||
|
let slow: [Float] = try renderWindow { $0.attack = 0.06; $0.release = 0.5 }
|
||||||
|
#expect(windowSSD(fast, slow) > 0, "attack/release did not change output")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func sweepDirectionChangesOutput() throws {
|
@Test func sweepDirectionChangesOutput() throws {
|
||||||
|
|||||||
@@ -170,4 +170,69 @@ struct NoiseGatePedalTests {
|
|||||||
#expect(pedal.threshold == 0.03 && pedal.floor == 0.4, "legacy Threshold/Floor mis-mapped")
|
#expect(pedal.threshold == 0.03 && pedal.floor == 0.4, "legacy Threshold/Floor mis-mapped")
|
||||||
#expect(pedal.attack == 0.005 && pedal.release == 0.08, "legacy gate should default Attack/Release")
|
#expect(pedal.attack == 0.005 && pedal.release == 0.08, "legacy gate should default Attack/Release")
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test func exposesDetectorSwitch() throws {
|
||||||
|
let switches: [PedalSwitch] = NoiseGatePedal().effectSwitches
|
||||||
|
#expect(switches.map { $0.label } == ["Detector"])
|
||||||
|
#expect(switches.first?.options.map { $0.title } == ["Peak", "RMS"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func defaultsToRMSAndLegacyGateGetsRMS() throws {
|
||||||
|
#expect(NoiseGatePedal().detector == 1.0, "new gate should default to RMS")
|
||||||
|
// A gate saved before the detector switch (empty switchValues) loads with the RMS default.
|
||||||
|
let legacy: PedalState = PedalState(
|
||||||
|
id: UUID(), type: "Noise Gate",
|
||||||
|
knobValues: [0.03, 0.4, 1.0, 1.0], switchValues: [], advancedValues: [], bypass: 0.0)
|
||||||
|
let pedal: NoiseGatePedal = NoiseGatePedal()
|
||||||
|
pedal.applyState(legacy)
|
||||||
|
#expect(pedal.detector == 1.0, "legacy gate should default to the RMS detector")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func detectorRoundTripsThroughState() throws {
|
||||||
|
let pedal: NoiseGatePedal = NoiseGatePedal()
|
||||||
|
pedal.detector = 0.0 // Peak
|
||||||
|
let restored: NoiseGatePedal = NoiseGatePedal()
|
||||||
|
restored.applyState(pedal.captureState())
|
||||||
|
#expect(restored.detector == 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rmsDetectorClosesEarlierThanPeak() throws {
|
||||||
|
// On a note held just above threshold, the RMS envelope (≈ 3 dB below the peak envelope for a
|
||||||
|
// steady tone) drops under the close threshold sooner than the peak envelope does — so the
|
||||||
|
// RMS gate shuts earlier and passes less of the sustained tail than the Peak gate. The source
|
||||||
|
// steps to a constant 0.03 (peak env ≈ 0.03, RMS env ≈ 0.021); with threshold 0.025 the Peak
|
||||||
|
// gate stays open on the tail while the RMS gate closes.
|
||||||
|
func tailEnergy(detector: Double) throws -> Double {
|
||||||
|
let sr: Double = 48000.0
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: 0.6, sampleRate: sr)
|
||||||
|
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: DecaySineSource = DecaySineSource(bus: srcBus.index)
|
||||||
|
let gate: NoiseGatePedal = NoiseGatePedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
gate.sampleRate = sr
|
||||||
|
gate.threshold = 0.025
|
||||||
|
gate.floor = 0.0
|
||||||
|
gate.detector = detector
|
||||||
|
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: dstBus.index)
|
||||||
|
try engine.add(source)
|
||||||
|
try engine.add(gate, position: NodePosition.after(source))
|
||||||
|
try engine.add(master, position: NodePosition.after(gate))
|
||||||
|
try engine.start()
|
||||||
|
let inter: [Float] = readStereoCAF(url: url, sampleRate: sr)
|
||||||
|
let mono: [Double] = stride(from: 0, to: inter.count, by: 2).map { Double(inter[$0]) }
|
||||||
|
let start: Int = Int(0.15 * sr) // the sustained, below-peak-threshold tail
|
||||||
|
var energy: Double = 0.0
|
||||||
|
for i: Int in start..<mono.count { energy += mono[i] * mono[i] }
|
||||||
|
return energy
|
||||||
|
}
|
||||||
|
let peakTail: Double = try tailEnergy(detector: 0.0)
|
||||||
|
let rmsTail: Double = try tailEnergy(detector: 1.0)
|
||||||
|
#expect(peakTail > rmsTail * 2.0,
|
||||||
|
"RMS should close earlier than Peak on the sustained tail (peak=\(peakTail) rms=\(rmsTail))")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,412 @@
|
|||||||
|
// PolyOctavePedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A steady sine source for pitch tests — a known, stable fundamental the octave voices can shift
|
||||||
|
/// so a test can measure the output pitch.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("PolyOctavePedal")
|
||||||
|
struct PolyOctavePedalTests {
|
||||||
|
|
||||||
|
// MARK: - Analysis constants
|
||||||
|
|
||||||
|
/// Engine sample rate (matches `makeNRTEngine`'s default).
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
/// Render long enough that the analysis window lands well past the shifter's warm-up.
|
||||||
|
private let renderDuration: Double = 0.8
|
||||||
|
/// Test tone fundamental. Mid-range so ±2 octaves stays inside `[20, Nyquist]`.
|
||||||
|
private let sineHz: Double = 220.0
|
||||||
|
/// Interleaved-stereo frame offset to start analysis at — clears the shifter's warm-up.
|
||||||
|
private let analysisSkipFrames: Int = 13_230 // ~0.3 s
|
||||||
|
/// Analysis window length in frames. ~0.37 s → ≥10 cycles even at −2 octaves.
|
||||||
|
private let analysisWindowFrames: Int = 16_384
|
||||||
|
|
||||||
|
// MARK: - Render helpers
|
||||||
|
|
||||||
|
/// Renders the pedal driven by a steady sine at `sineHz`, over `renderDuration`.
|
||||||
|
private func renderSine(
|
||||||
|
configure: (PolyOctavePedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
try renderSine(duration: renderDuration, configure: configure)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the pedal driven by a steady sine at `sineHz`, over a caller-chosen duration (the
|
||||||
|
/// swell test needs a longer window to see the bloom develop).
|
||||||
|
private func renderSine(
|
||||||
|
duration: Double,
|
||||||
|
configure: (PolyOctavePedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: PolyOctavePedal = PolyOctavePedal(
|
||||||
|
inputBus: srcBus.index,
|
||||||
|
outputBus: dstBus.index
|
||||||
|
)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Signal analysis
|
||||||
|
|
||||||
|
/// Estimates the fundamental of the left channel by autocorrelation. Searches lags in
|
||||||
|
/// `[20 Hz, maxHz]`; a deep down-shift carries strong grain-rate HF that a wide search would lock
|
||||||
|
/// onto, so callers testing those pass a ceiling near the expected Hz.
|
||||||
|
private func fundamentalHz(_ samples: [Float], minHz: Double = 20.0, maxHz: Double = 1_500.0) -> Double {
|
||||||
|
let needed: Int = analysisSkipFrames + analysisWindowFrames
|
||||||
|
guard samples.count >= 2 * needed else { return 0.0 }
|
||||||
|
|
||||||
|
var x: [Double] = []
|
||||||
|
x.reserveCapacity(analysisWindowFrames)
|
||||||
|
for i: Int in analysisSkipFrames ..< needed {
|
||||||
|
x.append(Double(samples[2 * i])) // left channel of the interleaved pair
|
||||||
|
}
|
||||||
|
let mean: Double = x.reduce(0.0, +) / Double(x.count)
|
||||||
|
for i: Int in x.indices { x[i] -= mean }
|
||||||
|
|
||||||
|
let minLag: Int = Int(sampleRate / maxHz)
|
||||||
|
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
|
||||||
|
guard maxLag > minLag else { return 0.0 }
|
||||||
|
|
||||||
|
var bestLag: Int = minLag
|
||||||
|
var bestCorr: Double = -Double.infinity
|
||||||
|
for lag: Int in minLag ... maxLag {
|
||||||
|
var c: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (x.count - lag) {
|
||||||
|
c += x[i] * x[i + lag]
|
||||||
|
}
|
||||||
|
if c > bestCorr {
|
||||||
|
bestCorr = c
|
||||||
|
bestLag = lag
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sampleRate / Double(bestLag)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RMS of the left channel over an interleaved-frame range `[lo, hi)`.
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = Double(samples[2 * i])
|
||||||
|
sum += v * v
|
||||||
|
}
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Max absolute first difference (per-sample step) over `[lo, hi)`. An impulsive click shows up
|
||||||
|
/// as a step far larger than the signal's own slope.
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Pitch behaviour (one voice isolated at a time, dry muted)
|
||||||
|
|
||||||
|
@Test func upOneVoiceRaisesPitchAnOctave() throws {
|
||||||
|
// +1 oct voice alone (ratio 2.0): 220 Hz should land near 440 Hz.
|
||||||
|
let out: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.upOne = 1.0
|
||||||
|
}
|
||||||
|
let hz: Double = fundamentalHz(out)
|
||||||
|
#expect(hasNonSilentOutput(out), "+1 oct render was silent")
|
||||||
|
// ±12% is tight enough to reject a wrong interval (a fifth is +50%) but clears the
|
||||||
|
// autocorrelation lag quantisation (~1% here) and the shifter's warble.
|
||||||
|
#expect(abs(hz - sineHz * 2.0) < sineHz * 2.0 * 0.12, "+1 oct should be ~440 Hz, got \(hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func subOneVoiceLowersPitchAnOctave() throws {
|
||||||
|
// −1 oct voice alone (ratio 0.5): 220 Hz should land near 110 Hz.
|
||||||
|
let out: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.subOne = 1.0
|
||||||
|
}
|
||||||
|
let hz: Double = fundamentalHz(out)
|
||||||
|
#expect(hasNonSilentOutput(out), "−1 oct render was silent")
|
||||||
|
#expect(abs(hz - sineHz * 0.5) < sineHz * 0.5 * 0.12, "−1 oct should be ~110 Hz, got \(hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func upTwoVoiceRaisesPitchTwoOctaves() throws {
|
||||||
|
// +2 oct voice alone (ratio 4.0, single stage at the clamp edge): 220 Hz → ~880 Hz.
|
||||||
|
let out: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.upTwo = 1.0
|
||||||
|
}
|
||||||
|
// Search a band around +2 oct so the autocorrelation can't lock onto the 441 Hz subharmonic
|
||||||
|
// lag (an 880 Hz tone is also periodic at 440 Hz, a near-tie in the correlation).
|
||||||
|
let hz: Double = fundamentalHz(out, minHz: 500.0)
|
||||||
|
#expect(hasNonSilentOutput(out), "+2 oct render was silent")
|
||||||
|
#expect(abs(hz - sineHz * 4.0) < sineHz * 4.0 * 0.15, "+2 oct should be ~880 Hz, got \(hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func subTwoVoiceLowersPitchTwoOctaves() throws {
|
||||||
|
// −2 oct voice alone (ratio 0.25, single stage at the clamp edge): 220 Hz → ~55 Hz.
|
||||||
|
// Cap the search near the expected low fundamental so deep-shift grain HF can't win.
|
||||||
|
let out: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.subTwo = 1.0
|
||||||
|
}
|
||||||
|
let hz: Double = fundamentalHz(out, maxHz: 160.0)
|
||||||
|
#expect(hasNonSilentOutput(out), "−2 oct render was silent")
|
||||||
|
#expect(abs(hz - sineHz * 0.25) < sineHz * 0.25 * 0.15, "−2 oct should be ~55 Hz, got \(hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func dryVoicePassesAtUnison() throws {
|
||||||
|
// Dry voice alone (no octaves): output stays at the input pitch.
|
||||||
|
let out: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 1.0
|
||||||
|
pedal.upOne = 0.0
|
||||||
|
}
|
||||||
|
let hz: Double = fundamentalHz(out)
|
||||||
|
#expect(hasNonSilentOutput(out), "dry-only render was silent")
|
||||||
|
#expect(abs(hz - sineHz) < sineHz * 0.2, "dry should stay ~220 Hz, got \(hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Swell
|
||||||
|
|
||||||
|
@Test func swellIsNeutralAtZeroAttackAndBloomsAtHighAttack() throws {
|
||||||
|
// Isolate the +1 oct voice (dry muted). The sine starts from silence at engine start, so the
|
||||||
|
// swell's slow-gear gain shapes the voice's onset: at attack 0 the voice is present from the
|
||||||
|
// first cycles (early RMS ≈ late RMS); at attack 1 it blooms in over ~1.5 s (early RMS well
|
||||||
|
// below late RMS). Compare the early/late RMS ratio between the two settings.
|
||||||
|
let duration: Double = 2.0
|
||||||
|
let warmupFrames: Int = Int(0.15 * sampleRate) // past the shifter warm-up
|
||||||
|
let earlyLo: Int = warmupFrames
|
||||||
|
let earlyHi: Int = warmupFrames + Int(0.2 * sampleRate) // ~0.15–0.35 s
|
||||||
|
let lateLo: Int = Int(1.5 * sampleRate)
|
||||||
|
let lateHi: Int = Int(1.9 * sampleRate)
|
||||||
|
|
||||||
|
let instant: [Float] = try renderSine(duration: duration) { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.upOne = 1.0
|
||||||
|
pedal.attack = 0.0
|
||||||
|
}
|
||||||
|
let swelled: [Float] = try renderSine(duration: duration) { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.upOne = 1.0
|
||||||
|
pedal.attack = 1.0
|
||||||
|
}
|
||||||
|
|
||||||
|
let instantRatio: Double =
|
||||||
|
rms(instant, loFrame: earlyLo, hiFrame: earlyHi)
|
||||||
|
/ max(rms(instant, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
|
||||||
|
let swelledRatio: Double =
|
||||||
|
rms(swelled, loFrame: earlyLo, hiFrame: earlyHi)
|
||||||
|
/ max(rms(swelled, loFrame: lateLo, hiFrame: lateHi), 1.0e-9)
|
||||||
|
|
||||||
|
#expect(hasNonSilentOutput(swelled), "swelled render was silent")
|
||||||
|
// Instant: roughly flat onset (early ≈ late).
|
||||||
|
#expect(instantRatio > 0.6, "attack 0 should have a near-flat onset, early/late ratio \(instantRatio)")
|
||||||
|
// Swell: the early window is markedly quieter than steady state, and quieter than the
|
||||||
|
// instant setting's early window.
|
||||||
|
#expect(swelledRatio < instantRatio * 0.6,
|
||||||
|
"attack 1 should bloom in (swelled early/late \(swelledRatio) vs instant \(instantRatio))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// Every PitchShift voice is seeded and the sine source is RNG-free, so two identical renders
|
||||||
|
// must be bit-identical.
|
||||||
|
let a: [Float] = try renderSine { pedal in
|
||||||
|
pedal.subTwo = 0.3
|
||||||
|
pedal.upOne = 0.7
|
||||||
|
pedal.upTwo = 0.4
|
||||||
|
}
|
||||||
|
let b: [Float] = try renderSine { pedal in
|
||||||
|
pedal.subTwo = 0.3
|
||||||
|
pedal.upOne = 0.7
|
||||||
|
pedal.upTwo = 0.4
|
||||||
|
}
|
||||||
|
#expect(a == b, "seeded renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass transition
|
||||||
|
|
||||||
|
/// Renders the pedal manually block-by-block through a no-op `OfflineDriver`, flipping `bypass`
|
||||||
|
/// from engaged (`0`) to bypassed (`1`) at `flipFrame`, and returns the left hardware-output
|
||||||
|
/// channel. Hand-stepping `processBlock` is the only way to change a live `@UIParam` mid-render.
|
||||||
|
private func renderBypassFlip(
|
||||||
|
flipFrame: Int,
|
||||||
|
totalFrames: Int,
|
||||||
|
blockSize: Int,
|
||||||
|
configure: (PolyOctavePedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: PolyOctavePedal = PolyOctavePedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0 // engage → bypassed, mid-render
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
let bus: [Float] = engine.audioBuses[0] // hardware output, left
|
||||||
|
left.append(contentsOf: bus)
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
// Clocking a wet-only octave-up voice (dry muted, +1 oct at full) on/off crossfades the dry
|
||||||
|
// note against a fully decorrelated shifted voice. The audio-rate linear equal-power bypass
|
||||||
|
// crossfade must keep that click-free at the engine's real 512-sample block — a block-rate
|
||||||
|
// smoother would leak a coarse step here.
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460 // 0.6 s
|
||||||
|
let flipFrame: Int = 15_435 // ~0.35 s
|
||||||
|
let left: [Float] = try renderBypassFlip(
|
||||||
|
flipFrame: flipFrame,
|
||||||
|
totalFrames: totalFrames,
|
||||||
|
blockSize: blockSize
|
||||||
|
) { pedal in
|
||||||
|
pedal.dry = 0.0
|
||||||
|
pedal.upOne = 1.0
|
||||||
|
pedal.attack = 0.0 // no swell, so the voice is full-scale at the seam
|
||||||
|
}
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
let steadyLo: Int = 9_700 // ~0.22 s
|
||||||
|
let steadyHi: Int = 14_500 // ~0.33 s
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transLo: Int = flipFrame - blockSize
|
||||||
|
let transHi: Int = flipFrame + fadeFrames + 2_000
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
|
||||||
|
let transStep: Double = maxStep(left, lo: transLo, hi: transHi)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Build / wiring
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try renderSine { pedal in
|
||||||
|
pedal.dry = 1.0
|
||||||
|
pedal.upOne = 0.5
|
||||||
|
}
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "poly-octave output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesSevenVoiceKnobs() throws {
|
||||||
|
let pedal: PolyOctavePedal = PolyOctavePedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label }
|
||||||
|
== ["-2 Oct", "-1 Oct", "+1 Oct", "+2 Oct", "Dry", "Attack", "Tone"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesKnobs() throws {
|
||||||
|
let pedal: PolyOctavePedal = PolyOctavePedal()
|
||||||
|
pedal.subTwo = 0.2
|
||||||
|
pedal.subOne = 0.3
|
||||||
|
pedal.upOne = 0.4
|
||||||
|
pedal.upTwo = 0.5
|
||||||
|
pedal.dry = 0.6
|
||||||
|
pedal.attack = 0.7
|
||||||
|
pedal.tone = 6000.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: PolyOctavePedal = PolyOctavePedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.subTwo == 0.2)
|
||||||
|
#expect(restored.subOne == 0.3)
|
||||||
|
#expect(restored.upOne == 0.4)
|
||||||
|
#expect(restored.upTwo == 0.5)
|
||||||
|
#expect(restored.dry == 0.6)
|
||||||
|
#expect(restored.attack == 0.7)
|
||||||
|
#expect(restored.tone == 6000.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Poly Octave")
|
||||||
|
#expect(pedal is PolyOctavePedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -422,11 +422,36 @@ struct PresetTests {
|
|||||||
try sg.loadRig(from: presetURL)
|
try sg.loadRig(from: presetURL)
|
||||||
#expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)")
|
#expect(abs(sg.clock.bpm - savedBpm) < 1e-9, "bpm should restore to \(savedBpm)")
|
||||||
#expect(sg.tempoEnabled == false, "tempoEnabled should restore to false")
|
#expect(sg.tempoEnabled == false, "tempoEnabled should restore to false")
|
||||||
#expect(sg.inputSource == .testLoop, "input source should restore to test loop")
|
// Input is a live session setting, not part of the recalled rig: the session was on the test
|
||||||
|
// loop and stays there (load never changes the current input).
|
||||||
|
#expect(sg.inputSource == .testLoop, "load leaves the current input source unchanged")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func liveInputSourcePersistsAndFallsBackWhenChannelMissing() throws {
|
@Test func rigContentComparisonIgnoresInputAndChannels() throws {
|
||||||
// Engine WITH an input channel: a live-input rig round-trips its source.
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: 0.05, numInputChannels: 1, numAudioBuses: 64
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
let sg: ShoeGaze = ShoeGaze(engine: engine, inputSource: .testLoop)
|
||||||
|
let board: PedalBoard = try sg.addBoard()
|
||||||
|
try board.add(FuzzPedal())
|
||||||
|
try sg.finalizeBoard(board)
|
||||||
|
let saved: ShoeGazeState = sg.captureState()
|
||||||
|
|
||||||
|
// Changing only the live input source must NOT read as a rig change (the source of the
|
||||||
|
// spurious "save changes?" prompt when switching starter rigs).
|
||||||
|
sg.inputSource = .liveInput(channel: 0)
|
||||||
|
let afterInputChange: ShoeGazeState = sg.captureState()
|
||||||
|
#expect(afterInputChange.hasSameRigContent(as: saved), "input change must not be a rig change")
|
||||||
|
#expect(afterInputChange != saved, "but the raw snapshots still differ on the input field")
|
||||||
|
|
||||||
|
// A genuine graph difference IS a content change.
|
||||||
|
let emptyRig: ShoeGazeState = ShoeGazeState(boards: [])
|
||||||
|
#expect(!saved.hasSameRigContent(as: emptyRig), "different boards must count as a rig change")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func loadPreservesCurrentInputSourceNotTheSavedOne() throws {
|
||||||
|
// A rig captured with live input still RECORDS its source in the snapshot...
|
||||||
let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine(
|
let (engineIn, urlIn): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
duration: 0.1,
|
duration: 0.1,
|
||||||
numInputChannels: 1,
|
numInputChannels: 1,
|
||||||
@@ -434,29 +459,57 @@ struct PresetTests {
|
|||||||
)
|
)
|
||||||
defer { try? FileManager.default.removeItem(at: urlIn) }
|
defer { try? FileManager.default.removeItem(at: urlIn) }
|
||||||
let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0))
|
let sgIn: ShoeGaze = ShoeGaze(engine: engineIn, inputSource: .liveInput(channel: 0))
|
||||||
let board: PedalBoard = try sgIn.addBoard()
|
let liveBoard: PedalBoard = try sgIn.addBoard()
|
||||||
try board.add(OverdrivePedal())
|
try liveBoard.add(OverdrivePedal())
|
||||||
try sgIn.finalizeBoard(board)
|
try sgIn.finalizeBoard(liveBoard)
|
||||||
|
let liveState: ShoeGazeState = sgIn.captureState()
|
||||||
|
#expect(liveState.inputSource == .liveInput(channel: 0), "capture records the live input")
|
||||||
|
|
||||||
let state: ShoeGazeState = sgIn.captureState()
|
// ...but loading a rig NEVER switches the session's current input — switching rigs keeps
|
||||||
#expect(state.inputSource == .liveInput(channel: 0), "capture should record the live input")
|
// whatever input the player has chosen. Here a test-loop session loads a live-input rig on an
|
||||||
|
// engine that DOES have the channel: under the old "restore saved input" behaviour this would
|
||||||
// Reload into the same input-capable engine: source preserved.
|
// become live input; the new behaviour leaves it on the test loop.
|
||||||
try sgIn.loadRig(from: state)
|
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
#expect(sgIn.inputSource == .liveInput(channel: 0), "live input should round-trip")
|
|
||||||
|
|
||||||
// loadRig does NOT auto-apply the saved channel layout, so loading into an engine with no
|
|
||||||
// input channels falls back to the test loop rather than clobbering the engine's config.
|
|
||||||
let (engineNoIn, urlNoIn): (SynthesisEngine, URL) = makeNRTEngine(
|
|
||||||
duration: 0.1,
|
duration: 0.1,
|
||||||
numInputChannels: 0,
|
numInputChannels: 1,
|
||||||
numAudioBuses: 128
|
numAudioBuses: 128
|
||||||
)
|
)
|
||||||
defer { try? FileManager.default.removeItem(at: urlNoIn) }
|
defer { try? FileManager.default.removeItem(at: urlA) }
|
||||||
let sgNoIn: ShoeGaze = ShoeGaze(engine: engineNoIn)
|
let sgA: ShoeGaze = ShoeGaze(engine: engineA) // defaults to .testLoop
|
||||||
try sgNoIn.loadRig(from: state)
|
try sgA.loadRig(from: liveState, keepingCurrentInput: true)
|
||||||
#expect(engineNoIn.numInputChannels == 0, "loadRig must not reconfigure the engine's I/O")
|
#expect(sgA.inputSource == .testLoop, "switch must keep the current input, not adopt the rig's")
|
||||||
#expect(sgNoIn.inputSource == .testLoop, "missing channel should fall back to test loop")
|
|
||||||
|
// The reverse: a live-input session loading a test-loop rig stays on live input.
|
||||||
|
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: 0.1,
|
||||||
|
numInputChannels: 1,
|
||||||
|
numAudioBuses: 128
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: urlB) }
|
||||||
|
let sgTestLoop: ShoeGaze = ShoeGaze(engine: engineB) // .testLoop
|
||||||
|
let plainBoard: PedalBoard = try sgTestLoop.addBoard()
|
||||||
|
try plainBoard.add(OverdrivePedal())
|
||||||
|
try sgTestLoop.finalizeBoard(plainBoard)
|
||||||
|
let testLoopState: ShoeGazeState = sgTestLoop.captureState()
|
||||||
|
#expect(testLoopState.inputSource == .testLoop)
|
||||||
|
|
||||||
|
sgIn.currentRigID = nil
|
||||||
|
try sgIn.loadRig(from: testLoopState, keepingCurrentInput: true)
|
||||||
|
#expect(sgIn.inputSource == .liveInput(channel: 0),
|
||||||
|
"switch must keep the current live input, not adopt the rig's test loop")
|
||||||
|
|
||||||
|
// A default load (file open / launch restore) still applies the rig's saved input.
|
||||||
|
let (engineC, urlC): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: 0.1, numInputChannels: 1, numAudioBuses: 128
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: urlC) }
|
||||||
|
let sgDefault: ShoeGaze = ShoeGaze(engine: engineC) // .testLoop
|
||||||
|
try sgDefault.loadRig(from: liveState) // default: restore saved input
|
||||||
|
#expect(sgDefault.inputSource == .liveInput(channel: 0),
|
||||||
|
"a default load restores the rig's saved input")
|
||||||
|
|
||||||
|
// loadRig still never reconfigures the engine's channel layout.
|
||||||
|
#expect(engineA.numInputChannels == 1, "loadRig must not reconfigure the engine's I/O")
|
||||||
}
|
}
|
||||||
|
|
||||||
@Test func channelCountsPersistButLoadDoesNotReconfigure() throws {
|
@Test func channelCountsPersistButLoadDoesNotReconfigure() throws {
|
||||||
|
|||||||
@@ -0,0 +1,338 @@
|
|||||||
|
// ReverseReverbPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A steady sine source (for non-silent / bypass checks).
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A decaying sine burst: full at the start, linearly fading to silence over `burstDur`, then
|
||||||
|
/// silent. Its amplitude envelope peaks at `t = 0`, so after the reverse delay the swell appears
|
||||||
|
/// *later* — the signature a forward effect would not show.
|
||||||
|
@MainActor
|
||||||
|
private final class TestBurstSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
private let burstDur: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double, burstDur: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
self.burstDur = burstDur
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
let envelope: Line.Control = Line.Control(start: 1.0, end: 0.0, dur: burstDur)
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp) * envelope)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("ReverseReverbPedal")
|
||||||
|
struct ReverseReverbPedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let sineHz: Double = 220.0
|
||||||
|
|
||||||
|
// MARK: - Render helpers
|
||||||
|
|
||||||
|
/// Renders a source through the pedal to a stereo CAF, returning interleaved samples.
|
||||||
|
private func render(
|
||||||
|
duration: Double,
|
||||||
|
makeSource: @escaping (Int) -> any Synthesizer,
|
||||||
|
configure: (ReverseReverbPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: any Synthesizer = makeSource(srcBus.index)
|
||||||
|
let pedal: ReverseReverbPedal = ReverseReverbPedal(
|
||||||
|
inputBus: srcBus.index,
|
||||||
|
outputBus: dstBus.index
|
||||||
|
)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analysis
|
||||||
|
|
||||||
|
/// RMS of the left channel over an interleaved-frame range `[loFrame, hiFrame)`.
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = Double(samples[2 * i])
|
||||||
|
sum += v * v
|
||||||
|
}
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Max absolute first difference (per-sample step) over `[lo, hi)`.
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Behaviour
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 0.8,
|
||||||
|
makeSource: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: { _ in }
|
||||||
|
)
|
||||||
|
#expect(!out.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(out), "reverse-reverb output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reverseSwellDelaysEnergyPastOneSegment() throws {
|
||||||
|
// A burst peaking at t=0, rendered fully wet. The reverse delay plays nothing until its first
|
||||||
|
// segment completes (~`time` seconds), then releases the burst reversed — so the wet energy
|
||||||
|
// lands AFTER one segment, not at the input's early peak. A forward reverb would put its
|
||||||
|
// loudest energy during the burst instead. Assert the mid window dominates the early window.
|
||||||
|
let segmentTime: Double = 0.4
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 1.2,
|
||||||
|
makeSource: { bus in
|
||||||
|
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
|
||||||
|
},
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0 // isolate the wet path (no dry passthrough)
|
||||||
|
pedal.time = segmentTime
|
||||||
|
pedal.decay = 2.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
#expect(hasNonSilentOutput(out), "reverse-reverb burst render was silent")
|
||||||
|
|
||||||
|
// Early: during/just after the input burst, before the first reversed segment plays.
|
||||||
|
let earlyRMS: Double = rms(out, loFrame: 0, hiFrame: Int(0.3 * sampleRate))
|
||||||
|
// Mid: the reversed swell has been released and reverberates.
|
||||||
|
let midRMS: Double = rms(out, loFrame: Int(0.42 * sampleRate), hiFrame: Int(0.8 * sampleRate))
|
||||||
|
|
||||||
|
// The reversed signal is genuinely silent before one segment, so earlyRMS ≈ 0; assert the mid
|
||||||
|
// window is both non-trivially loud and far above the early window (a forward reverb would put
|
||||||
|
// its energy in the early window and fail this).
|
||||||
|
#expect(midRMS > 1.0e-3, "reversed swell should be clearly audible in the mid window, got \(midRMS)")
|
||||||
|
#expect(midRMS > earlyRMS * 3.0,
|
||||||
|
"reversed energy should arrive after one segment (mid RMS \(midRMS) vs early \(earlyRMS))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func energyRisesAcrossTheReversedSegment() throws {
|
||||||
|
// The reverse signature: a burst decaying from t=0 is recorded over segment [0, time) and
|
||||||
|
// played back end-to-start over [time, 2·time). The recorded END (late, silent) plays first
|
||||||
|
// and the recorded START (t=0, loudest) plays last, so within the reversed playback the
|
||||||
|
// energy RISES toward the segment's end. A plain delay→reverb would not — it would preserve
|
||||||
|
// the burst's decaying shape. Assert the late-segment window is louder than the mid-segment
|
||||||
|
// window. mix=1.0 isolates the wet path.
|
||||||
|
let segmentTime: Double = 0.4
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 1.2,
|
||||||
|
makeSource: { bus in
|
||||||
|
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
|
||||||
|
},
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.time = segmentTime
|
||||||
|
pedal.decay = 1.5 // modest tail so the rising dry swell dominates the window
|
||||||
|
}
|
||||||
|
)
|
||||||
|
// Reversed playback spans [0.4, 0.8) s. Early-in-playback (reads the silent recorded tail)
|
||||||
|
// vs late-in-playback (reads the loud recorded onset).
|
||||||
|
let midSegRMS: Double = rms(out, loFrame: Int(0.48 * sampleRate), hiFrame: Int(0.60 * sampleRate))
|
||||||
|
let lateSegRMS: Double = rms(out, loFrame: Int(0.68 * sampleRate), hiFrame: Int(0.80 * sampleRate))
|
||||||
|
#expect(lateSegRMS > midSegRMS * 1.5,
|
||||||
|
"energy should rise into the segment end (late \(lateSegRMS) vs mid \(midSegRMS))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reverbTailPersistsAfterInput() throws {
|
||||||
|
// After the burst and its reversed playback, the GVerb tail should still ring.
|
||||||
|
let out: [Float] = try render(
|
||||||
|
duration: 1.4,
|
||||||
|
makeSource: { bus in
|
||||||
|
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
|
||||||
|
},
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.mix = 1.0
|
||||||
|
pedal.time = 0.4
|
||||||
|
pedal.decay = 6.0 // long tail so late energy is unambiguous
|
||||||
|
}
|
||||||
|
)
|
||||||
|
let lateRMS: Double = rms(out, loFrame: Int(1.05 * sampleRate), hiFrame: Int(1.35 * sampleRate))
|
||||||
|
#expect(lateRMS > 1.0e-4, "reverb tail should still ring late in the render, got \(lateRMS)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// ReverseDelay and GVerb are RNG-free, so two identical renders must be bit-identical.
|
||||||
|
let make: () throws -> [Float] = {
|
||||||
|
try self.render(
|
||||||
|
duration: 0.8,
|
||||||
|
makeSource: { bus in
|
||||||
|
TestBurstSource(targetBus: bus, freq: self.sineHz, amplitude: 0.6, burstDur: 0.12)
|
||||||
|
},
|
||||||
|
configure: { pedal in
|
||||||
|
pedal.time = 0.3
|
||||||
|
pedal.decay = 2.0
|
||||||
|
}
|
||||||
|
)
|
||||||
|
}
|
||||||
|
let a: [Float] = try make()
|
||||||
|
let b: [Float] = try make()
|
||||||
|
#expect(a == b, "reverse-reverb renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass transition
|
||||||
|
|
||||||
|
private func renderBypassFlip(
|
||||||
|
flipFrame: Int,
|
||||||
|
totalFrames: Int,
|
||||||
|
blockSize: Int
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: ReverseReverbPedal = ReverseReverbPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
// The audio-rate equal-power bypass crossfade must stay click-free at the engine's real
|
||||||
|
// 512-sample block.
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460 // 0.6 s
|
||||||
|
let flipFrame: Int = 15_435 // ~0.35 s
|
||||||
|
let left: [Float] = try renderBypassFlip(
|
||||||
|
flipFrame: flipFrame,
|
||||||
|
totalFrames: totalFrames,
|
||||||
|
blockSize: blockSize
|
||||||
|
)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func exposesFourKnobs() throws {
|
||||||
|
let pedal: ReverseReverbPedal = ReverseReverbPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Time", "Decay", "Size", "Damp"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesKnobs() throws {
|
||||||
|
let pedal: ReverseReverbPedal = ReverseReverbPedal()
|
||||||
|
pedal.time = 0.8
|
||||||
|
pedal.decay = 5.0
|
||||||
|
pedal.size = 50.0
|
||||||
|
pedal.damp = 0.3
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: ReverseReverbPedal = ReverseReverbPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.time == 0.8)
|
||||||
|
#expect(restored.decay == 5.0)
|
||||||
|
#expect(restored.size == 50.0)
|
||||||
|
#expect(restored.damp == 0.3)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Reverse Reverb")
|
||||||
|
#expect(pedal is ReverseReverbPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,232 @@
|
|||||||
|
// ScriptPhaserPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A steady sine source — a stable tone the phaser's sweeping notches act on.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("ScriptPhaserPedal")
|
||||||
|
struct ScriptPhaserPedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let sineHz: Double = 220.0
|
||||||
|
/// Minimum RMS difference between two renders to count as a substantial, audible change.
|
||||||
|
private let renderDiffEpsilon: Double = 1.0e-3
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
duration: Double,
|
||||||
|
configure: (ScriptPhaserPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: duration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: ScriptPhaserPedal = ScriptPhaserPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// RMS of the sample-by-sample difference between two renders' left channels — a magnitude of how
|
||||||
|
/// much two settings actually diverge, not just whether any bit differs.
|
||||||
|
private func rmsDiff(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let n: Int = min(a.count, b.count) / 2
|
||||||
|
guard n > 0 else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in 0 ..< n {
|
||||||
|
let d: Double = Double(a[2 * i]) - Double(b[2 * i])
|
||||||
|
sum += d * d
|
||||||
|
}
|
||||||
|
return (sum / Double(n)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Behaviour
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let out: [Float] = try render(duration: 0.8) { _ in }
|
||||||
|
#expect(!out.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(out), "script-phaser output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func voicingChangesCharacter() throws {
|
||||||
|
// Script (feedback 0.2) and Block (0.45) are different notch depths, so the rendered output
|
||||||
|
// must differ between them.
|
||||||
|
let script: [Float] = try render(duration: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.speed = 0.8; pedal.voicing = 0.0
|
||||||
|
}
|
||||||
|
let block: [Float] = try render(duration: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.speed = 0.8; pedal.voicing = 1.0
|
||||||
|
}
|
||||||
|
#expect(hasNonSilentOutput(script) && hasNonSilentOutput(block), "a voicing render was silent")
|
||||||
|
#expect(rmsDiff(script, block) > renderDiffEpsilon,
|
||||||
|
"Script and Block voicings should differ substantially, diff \(rmsDiff(script, block))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func speedChangesModulation() throws {
|
||||||
|
// A faster LFO sweeps the notches more often, so a slow and a fast render must differ.
|
||||||
|
let slow: [Float] = try render(duration: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.speed = 0.2
|
||||||
|
}
|
||||||
|
let fast: [Float] = try render(duration: 1.0) { pedal in
|
||||||
|
pedal.mix = 1.0; pedal.speed = 3.0
|
||||||
|
}
|
||||||
|
#expect(hasNonSilentOutput(slow) && hasNonSilentOutput(fast), "a speed render was silent")
|
||||||
|
#expect(rmsDiff(slow, fast) > renderDiffEpsilon,
|
||||||
|
"slow and fast sweeps should differ substantially, diff \(rmsDiff(slow, fast))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// The phaser LFO is a deterministic sine (no RNG), so two identical renders are bit-identical.
|
||||||
|
let a: [Float] = try render(duration: 0.8) { pedal in pedal.speed = 1.0; pedal.voicing = 1.0 }
|
||||||
|
let b: [Float] = try render(duration: 0.8) { pedal in pedal.speed = 1.0; pedal.voicing = 1.0 }
|
||||||
|
#expect(a == b, "deterministic script-phaser renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass
|
||||||
|
|
||||||
|
private func renderBypassFlip(flipFrame: Int, totalFrames: Int, blockSize: Int) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: ScriptPhaserPedal = ScriptPhaserPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460
|
||||||
|
let flipFrame: Int = 15_435
|
||||||
|
let left: [Float] = try renderBypassFlip(flipFrame: flipFrame, totalFrames: totalFrames, blockSize: blockSize)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func exposesSpeedKnobAndVoicingSwitch() throws {
|
||||||
|
let pedal: ScriptPhaserPedal = ScriptPhaserPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Speed"])
|
||||||
|
let switches: [PedalSwitch] = pedal.effectSwitches
|
||||||
|
#expect(switches.map { $0.label } == ["Voicing"])
|
||||||
|
#expect(switches.first?.options.map { $0.title } == ["Script", "Block"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesKnobs() throws {
|
||||||
|
let pedal: ScriptPhaserPedal = ScriptPhaserPedal()
|
||||||
|
pedal.speed = 1.7
|
||||||
|
pedal.voicing = 1.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: ScriptPhaserPedal = ScriptPhaserPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.speed == 1.7)
|
||||||
|
#expect(restored.voicing == 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Script Phaser")
|
||||||
|
#expect(pedal is ScriptPhaserPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,100 @@
|
|||||||
|
// SustainFuzzPedalTests.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("SustainFuzzPedal")
|
||||||
|
struct SustainFuzzPedalTests {
|
||||||
|
|
||||||
|
/// Renders the test loop through a sustain-fuzz configured by `configure`, returning stereo samples.
|
||||||
|
private func render(configure: (SustainFuzzPedal) -> Void) throws -> [Float] {
|
||||||
|
let renderDuration: Double = 0.2
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
|
||||||
|
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: SustainFuzzPedal = SustainFuzzPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sum of squared differences over a mid-render window, guarding on length.
|
||||||
|
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let skip: Int = 1024
|
||||||
|
let window: Int = 2048
|
||||||
|
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
|
||||||
|
let aw: ArraySlice<Float> = a[skip..<(skip + window)]
|
||||||
|
let bw: ArraySlice<Float> = b[skip..<(skip + window)]
|
||||||
|
return zip(aw, bw).reduce(0.0) { acc, pair in
|
||||||
|
let d: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + d * d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try render { _ in }
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "SustainFuzzPedal produced silence")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func sustainChangesOutput() throws {
|
||||||
|
let low: [Float] = try render { $0.sustain = 2.0 }
|
||||||
|
let high: [Float] = try render { $0.sustain = 25.0 }
|
||||||
|
#expect(hasNonSilentOutput(low))
|
||||||
|
#expect(hasNonSilentOutput(high))
|
||||||
|
#expect(windowSSD(low, high) > 0, "sustain did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func toneChangesOutput() throws {
|
||||||
|
let dark: [Float] = try render { $0.tone = 900.0 }
|
||||||
|
let bright: [Float] = try render { $0.tone = 5500.0 }
|
||||||
|
#expect(windowSSD(dark, bright) > 0, "tone did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func scoopChangesOutput() throws {
|
||||||
|
let flat: [Float] = try render { $0.scoop = 0.0 }
|
||||||
|
let scooped: [Float] = try render { $0.scoop = 16.0 }
|
||||||
|
#expect(windowSSD(flat, scooped) > 0, "scoop did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesSustainToneScoopKnobs() {
|
||||||
|
let pedal: SustainFuzzPedal = SustainFuzzPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Sustain", "Tone", "Scoop"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func stateRoundTripsThroughPreset() {
|
||||||
|
let pedal: SustainFuzzPedal = SustainFuzzPedal()
|
||||||
|
pedal.sustain = 18.0
|
||||||
|
pedal.tone = 3200.0
|
||||||
|
pedal.scoop = 12.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: SustainFuzzPedal = SustainFuzzPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.sustain == 18.0)
|
||||||
|
#expect(restored.tone == 3200.0)
|
||||||
|
#expect(restored.scoop == 12.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,435 @@
|
|||||||
|
// TapeLooperPedalTests.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("TapeLooperPedal")
|
||||||
|
struct TapeLooperPedalTests {
|
||||||
|
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
private let toneHz: Double = 220.0
|
||||||
|
|
||||||
|
// MARK: - Fixtures
|
||||||
|
|
||||||
|
/// A constant-frequency sine with a live-settable amplitude, so a test can silence the live input
|
||||||
|
/// at an exact time and attribute any remaining output to the loop.
|
||||||
|
private final class ToneSource: SynthesizerBase {
|
||||||
|
let ampNode: ParameterNode = ParameterNode(0.4)
|
||||||
|
var amplitude: Double {
|
||||||
|
get { ampNode.value }
|
||||||
|
set { ampNode.value = newValue }
|
||||||
|
}
|
||||||
|
private let targetBus: Int
|
||||||
|
private let toneFreq: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.toneFreq = freq
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: toneFreq) * ampNode)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Posts a `TriggerEvent` at an exact time within a single NRT render, so a test can flip a
|
||||||
|
/// transport action mid-render.
|
||||||
|
private final class TimedTrigger: SynthesizerBase {
|
||||||
|
private let fireTime: Double
|
||||||
|
private let triggerID: Int32
|
||||||
|
private static let minRampDuration: Double = 0.001
|
||||||
|
|
||||||
|
init(fireTime: Double, id: Int32) {
|
||||||
|
self.fireTime = fireTime
|
||||||
|
self.triggerID = id
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
let rampDuration: Double = max(fireTime, TimedTrigger.minRampDuration) * 2.0
|
||||||
|
let ramp: Line.Control = Line.Control(start: -1.0, end: 1.0, dur: rampDuration)
|
||||||
|
_ = SendTrigger.Control(trig: ramp, id: triggerID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Render
|
||||||
|
|
||||||
|
private func render(
|
||||||
|
totalDuration: Double,
|
||||||
|
toneFreq: Double = 220.0,
|
||||||
|
configure: (
|
||||||
|
_ engine: SynthesisEngine,
|
||||||
|
_ source: ToneSource,
|
||||||
|
_ pedal: TapeLooperPedal,
|
||||||
|
_ scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void
|
||||||
|
) throws -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let url: URL = FileManager.default.temporaryDirectory
|
||||||
|
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let driver: NRTDriver = NRTDriver(outputURL: url, duration: totalDuration)
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: 512,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 64,
|
||||||
|
numControlBuses: 512,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
let listener: TriggerListener = TriggerListener(engine: engine)
|
||||||
|
driver.triggerListener = listener
|
||||||
|
|
||||||
|
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: ToneSource = ToneSource(targetBus: srcBus.index, freq: toneFreq)
|
||||||
|
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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))
|
||||||
|
|
||||||
|
var nextTriggerID: Int32 = 0
|
||||||
|
let scheduleAction: (Double, @escaping @MainActor @Sendable () -> Void) throws -> Void = { time, action in
|
||||||
|
nextTriggerID += 1
|
||||||
|
let id: Int32 = nextTriggerID
|
||||||
|
let trigger: TimedTrigger = TimedTrigger(fireTime: time, id: id)
|
||||||
|
try engine.add(trigger)
|
||||||
|
listener.addHandler(id: id) { _, _ in
|
||||||
|
MainActor.assumeIsolated { action() }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
try configure(engine, source, pedal, scheduleAction)
|
||||||
|
|
||||||
|
try engine.start()
|
||||||
|
return readStereoCAF(url: url, sampleRate: sampleRate)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Analysis
|
||||||
|
|
||||||
|
private func rms(_ samples: [Float], loFrame: Int, hiFrame: Int) -> Double {
|
||||||
|
let a: Int = max(0, loFrame)
|
||||||
|
let b: Int = min(hiFrame, samples.count / 2)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var sum: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let v: Double = Double(samples[2 * i])
|
||||||
|
sum += v * v
|
||||||
|
}
|
||||||
|
return (sum / Double(b - a)).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
private func fundamentalHz(_ samples: [Float], skip: Int, window: Int, minHz: Double, maxHz: Double) -> Double {
|
||||||
|
let needed: Int = skip + window
|
||||||
|
guard samples.count >= 2 * needed else { return 0.0 }
|
||||||
|
var x: [Double] = []
|
||||||
|
x.reserveCapacity(window)
|
||||||
|
for i: Int in skip ..< needed {
|
||||||
|
x.append(Double(samples[2 * i]))
|
||||||
|
}
|
||||||
|
let mean: Double = x.reduce(0.0, +) / Double(x.count)
|
||||||
|
for i: Int in x.indices { x[i] -= mean }
|
||||||
|
|
||||||
|
let minLag: Int = Int(sampleRate / maxHz)
|
||||||
|
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
|
||||||
|
guard maxLag > minLag else { return 0.0 }
|
||||||
|
|
||||||
|
var bestLag: Int = minLag
|
||||||
|
var bestCorr: Double = -Double.infinity
|
||||||
|
for lag: Int in minLag ... maxLag {
|
||||||
|
var c: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (x.count - lag) {
|
||||||
|
c += x[i] * x[i + lag]
|
||||||
|
}
|
||||||
|
if c > bestCorr {
|
||||||
|
bestCorr = c
|
||||||
|
bestLag = lag
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sampleRate / Double(bestLag)
|
||||||
|
}
|
||||||
|
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
// Record a loop from 0 → recordDur, then close + play; the caller may tweak the pedal at play.
|
||||||
|
private let recordDur: Double = 0.15
|
||||||
|
private let totalDur: Double = 0.7
|
||||||
|
/// Tail window (loop-only, after the live input is silenced), in interleaved frames.
|
||||||
|
private var tailSkip: Int { Int(0.45 * sampleRate) }
|
||||||
|
private var tailWindow: Int { 8_192 }
|
||||||
|
|
||||||
|
/// Builds an offline engine driving a steady tone into the looper, records a real loop (so
|
||||||
|
/// `masterLength > 0`), closes it, and leaves the pedal in the playing state. Returns the engine
|
||||||
|
/// (kept alive by the caller) and the pedal for state-machine assertions.
|
||||||
|
private func makePlayingLooper(recordBlocks: Int = 8) throws -> (SynthesisEngine, TapeLooperPedal) {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: 64,
|
||||||
|
numControlBuses: 512,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
let dstBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz)
|
||||||
|
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
pedal.pressRecord() // begin recording
|
||||||
|
for _: Int in 0 ..< recordBlocks { engine.processBlock(inputSamples: noInput) }
|
||||||
|
pedal.pressRecord() // close + play (frames recorded)
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
return (engine, pedal)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Controls
|
||||||
|
|
||||||
|
@Test func exposesTapeLooperControls() throws {
|
||||||
|
let pedal: TapeLooperPedal = TapeLooperPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Playback", "Feedback"])
|
||||||
|
#expect(pedal.effectSwitches.map { $0.label } == ["Direction", "Speed"])
|
||||||
|
#expect(pedal.effectTransportButtons.map { $0.label } == ["Record", "Stop", "Clear"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func isDoubleWidthAndHidesMix() throws {
|
||||||
|
#expect(TapeLooperPedal().widthUnits == 2)
|
||||||
|
#expect(TapeLooperPedal().showsMixControl == false)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func rebuildWipesTheRecordedLoop() throws {
|
||||||
|
// effect() runs from build(), re-invoked on every add (a board edit re-adds this instance).
|
||||||
|
// A rebuild must start clean — a previously recorded loop must not survive it.
|
||||||
|
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||||
|
#expect(pedal.hasLoop, "fixture should have recorded a loop")
|
||||||
|
_ = pedal.effect(OscSin.Audio(freq: 100.0)) // simulate a second build()
|
||||||
|
#expect(pedal.hasLoop == false, "a rebuild must wipe the recorded loop")
|
||||||
|
#expect(pedal.loopFrameCount == 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Audio behaviour
|
||||||
|
|
||||||
|
@Test func clearStatePassesDryThrough() throws {
|
||||||
|
let out: [Float] = try render(totalDuration: 0.2) { _, _, _, _ in }
|
||||||
|
#expect(hasNonSilentOutput(out), "an empty looper should pass the dry signal through")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func recordedLoopPlaysBackAfterInputSilenced() throws {
|
||||||
|
// Record a tone, close + play, then silence the live input. The loop must keep sounding.
|
||||||
|
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||||
|
pedal.pressRecord() // begin recording at t = 0
|
||||||
|
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
|
||||||
|
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||||
|
}
|
||||||
|
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
#expect(tail > 1.0e-3, "recorded loop should keep playing after the input is silenced, tail RMS \(tail)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func clearSilencesTheLoop() throws {
|
||||||
|
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||||
|
pedal.pressRecord()
|
||||||
|
try scheduleAction(recordDur) { pedal.pressRecord() } // close + play
|
||||||
|
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||||
|
try scheduleAction(0.35) { pedal.clearLoop() } // wipe the loop
|
||||||
|
}
|
||||||
|
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
#expect(tail < 1.0e-3, "after Clear with the input silenced the output should be silent, tail RMS \(tail)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func halfSpeedLowersLoopPitch() throws {
|
||||||
|
// Record a 220 Hz loop, then play it at half speed: the loop-only tail should drop an octave.
|
||||||
|
let normal: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
|
||||||
|
pedal.pressRecord()
|
||||||
|
try scheduleAction(recordDur) { pedal.pressRecord() }
|
||||||
|
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||||
|
}
|
||||||
|
let half: [Float] = try render(totalDuration: totalDur, toneFreq: toneHz) { _, source, pedal, scheduleAction in
|
||||||
|
pedal.pressRecord()
|
||||||
|
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.halfSpeed = 1.0 }
|
||||||
|
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||||
|
}
|
||||||
|
let fNormal: Double = fundamentalHz(normal, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
|
||||||
|
let fHalf: Double = fundamentalHz(half, skip: tailSkip, window: tailWindow, minHz: 60.0, maxHz: 400.0)
|
||||||
|
#expect(abs(fNormal - toneHz) / toneHz < 0.1, "normal loop should sound at the recorded pitch, got \(fNormal) Hz")
|
||||||
|
#expect(abs(fHalf - toneHz * 0.5) / (toneHz * 0.5) < 0.12,
|
||||||
|
"half-speed loop should sound an octave down (~\(toneHz * 0.5) Hz), got \(fHalf) Hz")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func reversePlaybackStillRunsTheLoop() throws {
|
||||||
|
// A reversed loop still plays (non-silent after the input is silenced).
|
||||||
|
let out: [Float] = try render(totalDuration: totalDur) { _, source, pedal, scheduleAction in
|
||||||
|
pedal.pressRecord()
|
||||||
|
try scheduleAction(recordDur) { pedal.pressRecord(); pedal.reverse = 1.0 }
|
||||||
|
try scheduleAction(recordDur + 0.02) { source.amplitude = 0.0 }
|
||||||
|
}
|
||||||
|
let tail: Double = rms(out, loFrame: tailSkip, hiFrame: tailSkip + tailWindow)
|
||||||
|
#expect(tail > 1.0e-3, "reversed loop should keep playing, tail RMS \(tail)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func overdubBlockedWhileReversedOrHalfSpeed() throws {
|
||||||
|
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||||
|
#expect(pedal.hasLoop)
|
||||||
|
#expect(pedal.isOverdubbing == false)
|
||||||
|
|
||||||
|
// Forward normal speed: overdub engages.
|
||||||
|
pedal.pressRecord()
|
||||||
|
#expect(pedal.isOverdubbing == true)
|
||||||
|
pedal.pressRecord() // toggle it back off
|
||||||
|
#expect(pedal.isOverdubbing == false)
|
||||||
|
|
||||||
|
// Reversed: overdub is blocked at engage time.
|
||||||
|
pedal.reverse = 1.0
|
||||||
|
pedal.pressRecord()
|
||||||
|
#expect(pedal.isOverdubbing == false, "overdub must be blocked while reversed")
|
||||||
|
|
||||||
|
// Half speed: overdub is blocked at engage time.
|
||||||
|
pedal.reverse = 0.0
|
||||||
|
pedal.halfSpeed = 1.0
|
||||||
|
pedal.pressRecord()
|
||||||
|
#expect(pedal.isOverdubbing == false, "overdub must be blocked at half speed")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func recordLedTracksTransportState() throws {
|
||||||
|
// Regression: closing a loop must not leave the Record LED stuck lit for the whole playback.
|
||||||
|
let (_, pedal): (SynthesisEngine, TapeLooperPedal) = try makePlayingLooper()
|
||||||
|
#expect(pedal.recordIndicator == 0.0, "Record LED should be off while just playing")
|
||||||
|
#expect(pedal.stoppedIndicator == 0.0)
|
||||||
|
|
||||||
|
pedal.pressRecord() // engage overdub
|
||||||
|
#expect(pedal.recordIndicator == 1.0, "Record LED should light while overdubbing")
|
||||||
|
pedal.pressRecord() // disengage
|
||||||
|
#expect(pedal.recordIndicator == 0.0, "Record LED should clear when overdub ends")
|
||||||
|
|
||||||
|
pedal.stopPlayback()
|
||||||
|
#expect(pedal.stoppedIndicator == 1.0, "Stop LED should light when stopped")
|
||||||
|
#expect(pedal.recordIndicator == 0.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass
|
||||||
|
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
init(targetBus: Int, freq: Double) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: 0.5))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460
|
||||||
|
let flipFrame: Int = 15_435
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: toneHz)
|
||||||
|
let pedal: TapeLooperPedal = TapeLooperPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
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()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
left.append(contentsOf: engine.audioBuses[0])
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
let steadyStep: Double = maxStep(left, lo: 9_700, hi: 14_500)
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transStep: Double = maxStep(left, lo: flipFrame - blockSize, hi: flipFrame + fadeFrames + 2_000)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Wiring
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesControls() throws {
|
||||||
|
let pedal: TapeLooperPedal = TapeLooperPedal()
|
||||||
|
pedal.playbackLevel = -6.0
|
||||||
|
pedal.feedback = 0.75
|
||||||
|
pedal.reverse = 1.0
|
||||||
|
pedal.halfSpeed = 1.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: TapeLooperPedal = TapeLooperPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.playbackLevel == -6.0)
|
||||||
|
#expect(restored.feedback == 0.75)
|
||||||
|
#expect(restored.reverse == 1.0)
|
||||||
|
#expect(restored.halfSpeed == 1.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Tape Looper")
|
||||||
|
#expect(pedal is TapeLooperPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
// VibePedalTests.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("VibePedal")
|
||||||
|
struct VibePedalTests {
|
||||||
|
|
||||||
|
/// Renders the test loop through a vibe pedal configured by `configure`, returning stereo samples.
|
||||||
|
private func render(configure: (VibePedal) -> Void) throws -> [Float] {
|
||||||
|
let renderDuration: Double = 0.2
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(duration: renderDuration)
|
||||||
|
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: VibePedal = VibePedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sum of squared differences over a mid-render window, guarding on length.
|
||||||
|
private func windowSSD(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let skip: Int = 1024
|
||||||
|
let window: Int = 2048
|
||||||
|
guard a.count >= skip + window, b.count >= skip + window else { return 0 }
|
||||||
|
let aw: ArraySlice<Float> = a[skip..<(skip + window)]
|
||||||
|
let bw: ArraySlice<Float> = b[skip..<(skip + window)]
|
||||||
|
return zip(aw, bw).reduce(0.0) { acc, pair in
|
||||||
|
let d: Double = Double(pair.0 - pair.1)
|
||||||
|
return acc + d * d
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try render { _ in }
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "VibePedal produced silence")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func speedChangesOutput() throws {
|
||||||
|
let slow: [Float] = try render { $0.speed = 1.0 }
|
||||||
|
let fast: [Float] = try render { $0.speed = 8.0 }
|
||||||
|
#expect(hasNonSilentOutput(slow))
|
||||||
|
#expect(hasNonSilentOutput(fast))
|
||||||
|
#expect(windowSSD(slow, fast) > 0, "vibe speed did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func intensityChangesOutput() throws {
|
||||||
|
let shallow: [Float] = try render { $0.intensity = 0.1 }
|
||||||
|
let deep: [Float] = try render { $0.intensity = 0.7 }
|
||||||
|
#expect(windowSSD(shallow, deep) > 0, "vibe intensity did not change output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func modeChangesOutput() throws {
|
||||||
|
let chorus: [Float] = try render { $0.mode = 0.0 }
|
||||||
|
let vibrato: [Float] = try render { $0.mode = 1.0 }
|
||||||
|
#expect(hasNonSilentOutput(chorus))
|
||||||
|
#expect(hasNonSilentOutput(vibrato))
|
||||||
|
#expect(windowSSD(chorus, vibrato) > 0, "chorus and vibrato modes produced identical output")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesSpeedIntensityKnobsAndModeSwitch() {
|
||||||
|
let pedal: VibePedal = VibePedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Speed", "Intensity"])
|
||||||
|
#expect(pedal.effectSwitches.map { $0.label } == ["Mode"])
|
||||||
|
#expect(pedal.effectSwitches.first?.options.map { $0.title } == ["Chorus", "Vibrato"])
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func stateRoundTripsThroughPreset() {
|
||||||
|
let pedal: VibePedal = VibePedal()
|
||||||
|
pedal.speed = 6.5
|
||||||
|
pedal.intensity = 0.42
|
||||||
|
pedal.mode = 1.0
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
let restored: VibePedal = VibePedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
|
||||||
|
#expect(restored.speed == 6.5)
|
||||||
|
#expect(restored.intensity == 0.42)
|
||||||
|
#expect(restored.mode == 1.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,464 @@
|
|||||||
|
// WhammyPedalTests.swift
|
||||||
|
// Lyrebird
|
||||||
|
//
|
||||||
|
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||||
|
// SPDX-License-Identifier: MIT
|
||||||
|
|
||||||
|
import Testing
|
||||||
|
import Foundation
|
||||||
|
import LyrebirdSynth
|
||||||
|
import LyrebirdUI
|
||||||
|
@testable import LyrebirdShoeGaze
|
||||||
|
|
||||||
|
/// A steady sine source for pitch tests — a known, stable fundamental the shifter can act on so a
|
||||||
|
/// test can measure the output pitch, which the arpeggiated `TestLoopSource` (pitch changing three
|
||||||
|
/// times a second) cannot support.
|
||||||
|
@MainActor
|
||||||
|
private final class TestSineSource: SynthesizerBase {
|
||||||
|
private let targetBus: Int
|
||||||
|
private let freq: Double
|
||||||
|
private let amp: Double
|
||||||
|
|
||||||
|
init(targetBus: Int, freq: Double, amplitude: Double = 0.5) {
|
||||||
|
self.targetBus = targetBus
|
||||||
|
self.freq = freq
|
||||||
|
self.amp = amplitude
|
||||||
|
super.init()
|
||||||
|
}
|
||||||
|
|
||||||
|
override func build() {
|
||||||
|
output(bus: targetBus, source: OscSin.Audio(freq: freq, mul: amp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@MainActor
|
||||||
|
@Suite("WhammyPedal")
|
||||||
|
struct WhammyPedalTests {
|
||||||
|
|
||||||
|
// MARK: - Analysis constants
|
||||||
|
|
||||||
|
/// Engine sample rate (matches `makeNRTEngine`'s default).
|
||||||
|
private let sampleRate: Double = 44_100.0
|
||||||
|
/// Render long enough that the analysis window lands well past the shifter's warm-up.
|
||||||
|
private let renderDuration: Double = 0.8
|
||||||
|
/// Test tone fundamental. Mid-range so ±2 octaves stays inside `[20, Nyquist]`.
|
||||||
|
private let sineHz: Double = 220.0
|
||||||
|
/// Interleaved-stereo frame offset to start analysis at — clears the shifter's warm-up.
|
||||||
|
private let analysisSkipFrames: Int = 13_230 // ~0.3 s
|
||||||
|
/// Analysis window length in frames. ~0.37 s → ≥10 cycles even at the −3-octave Dive Bomb.
|
||||||
|
private let analysisWindowFrames: Int = 16_384
|
||||||
|
|
||||||
|
// MARK: - Render helpers
|
||||||
|
|
||||||
|
/// Renders the pedal driven by the arpeggiated `TestLoopSource` (for non-pitch checks).
|
||||||
|
private func render(
|
||||||
|
configure: (WhammyPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
try renderThroughPedal(source: { bus in TestLoopSource(targetBus: bus) }, configure: configure)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the pedal driven by a steady sine at `sineHz` (for pitch checks).
|
||||||
|
private func renderSine(
|
||||||
|
configure: (WhammyPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
try renderThroughPedal(
|
||||||
|
source: { bus in TestSineSource(targetBus: bus, freq: self.sineHz) },
|
||||||
|
configure: configure
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Renders the steady sine straight to the master with no pedal in the path — a dry reference
|
||||||
|
/// for correlation tests.
|
||||||
|
private func renderSineDry() throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: renderDuration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
defer { try? FileManager.default.removeItem(at: url) }
|
||||||
|
|
||||||
|
let srcBus: AudioBus = try engine.busAllocator.allocateAudioBus(channelCount: 1)
|
||||||
|
defer { engine.busAllocator.releaseAudioBus(srcBus) }
|
||||||
|
|
||||||
|
let source: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let master: TestRouteMaster = TestRouteMaster(inputBusIndex: srcBus.index)
|
||||||
|
|
||||||
|
try engine.add(source)
|
||||||
|
try engine.add(master, position: NodePosition.after(source))
|
||||||
|
try engine.start()
|
||||||
|
|
||||||
|
return readStereoCAF(url: url)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shared body: `source` writes the pedal's input bus, the pedal processes it, the master routes
|
||||||
|
/// the pedal output to the hardware file.
|
||||||
|
private func renderThroughPedal(
|
||||||
|
source makeSource: (Int) -> any Synthesizer,
|
||||||
|
configure: (WhammyPedal) -> Void
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
|
||||||
|
duration: renderDuration,
|
||||||
|
numAudioBuses: numAudioBuses
|
||||||
|
)
|
||||||
|
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: any Synthesizer = makeSource(srcBus.index)
|
||||||
|
let pedal: WhammyPedal = WhammyPedal(
|
||||||
|
inputBus: srcBus.index,
|
||||||
|
outputBus: dstBus.index
|
||||||
|
)
|
||||||
|
configure(pedal)
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Signal analysis
|
||||||
|
|
||||||
|
/// Estimates the fundamental of the left channel by autocorrelation — robust to the grain-splice
|
||||||
|
/// glitches a zero-crossing count would miscount. Searches lags in `[20 Hz, maxHz]`; a deep
|
||||||
|
/// down-shift carries strong grain-rate HF that a wide search would lock onto instead of the
|
||||||
|
/// intended low fundamental, so callers testing those modes pass a ceiling near the expected Hz.
|
||||||
|
private func fundamentalHz(_ samples: [Float], maxHz: Double = 1_500.0) -> Double {
|
||||||
|
let minHz: Double = 20.0
|
||||||
|
let needed: Int = analysisSkipFrames + analysisWindowFrames
|
||||||
|
guard samples.count >= 2 * needed else { return 0.0 }
|
||||||
|
|
||||||
|
var x: [Double] = []
|
||||||
|
x.reserveCapacity(analysisWindowFrames)
|
||||||
|
for i: Int in analysisSkipFrames ..< needed {
|
||||||
|
x.append(Double(samples[2 * i])) // left channel of the interleaved pair
|
||||||
|
}
|
||||||
|
// Remove DC so the autocorrelation peak reflects periodicity, not offset.
|
||||||
|
let mean: Double = x.reduce(0.0, +) / Double(x.count)
|
||||||
|
for i: Int in x.indices { x[i] -= mean }
|
||||||
|
|
||||||
|
let minLag: Int = Int(sampleRate / maxHz)
|
||||||
|
let maxLag: Int = min(Int(sampleRate / minHz), x.count - 1)
|
||||||
|
guard maxLag > minLag else { return 0.0 }
|
||||||
|
|
||||||
|
var bestLag: Int = minLag
|
||||||
|
var bestCorr: Double = -Double.infinity
|
||||||
|
for lag: Int in minLag ... maxLag {
|
||||||
|
var c: Double = 0.0
|
||||||
|
for i: Int in 0 ..< (x.count - lag) {
|
||||||
|
c += x[i] * x[i + lag]
|
||||||
|
}
|
||||||
|
if c > bestCorr {
|
||||||
|
bestCorr = c
|
||||||
|
bestLag = lag
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sampleRate / Double(bestLag)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Pearson correlation of two renders' left channels over the analysis window. Scale-invariant,
|
||||||
|
/// so gain differences between the two signals don't matter — only shared waveform shape does.
|
||||||
|
private func correlation(_ a: [Float], _ b: [Float]) -> Double {
|
||||||
|
let needed: Int = analysisSkipFrames + analysisWindowFrames
|
||||||
|
guard a.count >= 2 * needed, b.count >= 2 * needed else { return 0.0 }
|
||||||
|
|
||||||
|
var xa: [Double] = []
|
||||||
|
var xb: [Double] = []
|
||||||
|
xa.reserveCapacity(analysisWindowFrames)
|
||||||
|
xb.reserveCapacity(analysisWindowFrames)
|
||||||
|
for i: Int in analysisSkipFrames ..< needed {
|
||||||
|
xa.append(Double(a[2 * i]))
|
||||||
|
xb.append(Double(b[2 * i]))
|
||||||
|
}
|
||||||
|
let n: Double = Double(xa.count)
|
||||||
|
let ma: Double = xa.reduce(0.0, +) / n
|
||||||
|
let mb: Double = xb.reduce(0.0, +) / n
|
||||||
|
var num: Double = 0.0
|
||||||
|
var da: Double = 0.0
|
||||||
|
var db: Double = 0.0
|
||||||
|
for i: Int in 0 ..< xa.count {
|
||||||
|
let u: Double = xa[i] - ma
|
||||||
|
let v: Double = xb[i] - mb
|
||||||
|
num += u * v
|
||||||
|
da += u * u
|
||||||
|
db += v * v
|
||||||
|
}
|
||||||
|
guard da > 0.0, db > 0.0 else { return 0.0 }
|
||||||
|
return num / (da * db).squareRoot()
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Pitch behaviour
|
||||||
|
|
||||||
|
@Test func pitchShiftsUpTwoOctavesAtToe() throws {
|
||||||
|
// 2 Oct Up (mode 0): toe = +24 st = ratio 4. A 220 Hz tone should land near 880 Hz, and well
|
||||||
|
// above the unison it produces at the heel.
|
||||||
|
let heel: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 0.0
|
||||||
|
pedal.position = 0.0
|
||||||
|
}
|
||||||
|
let toe: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 0.0
|
||||||
|
pedal.position = 1.0
|
||||||
|
}
|
||||||
|
let heelHz: Double = fundamentalHz(heel)
|
||||||
|
let toeHz: Double = fundamentalHz(toe)
|
||||||
|
#expect(hasNonSilentOutput(toe), "2 Oct Up toe render was silent")
|
||||||
|
#expect(abs(heelHz - sineHz) < sineHz * 0.3, "heel should be unison (~220 Hz), got \(heelHz)")
|
||||||
|
#expect(abs(toeHz - sineHz * 4.0) < sineHz * 4.0 * 0.3,
|
||||||
|
"2 Oct Up toe should be ~880 Hz, got \(toeHz)")
|
||||||
|
#expect(toeHz > heelHz * 2.0, "toe pitch should be far above the heel")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func pitchShiftsDownAnOctaveAtToe() throws {
|
||||||
|
// Oct Down (mode 2): toe = −12 st = ratio 0.5. 220 Hz should land near 110 Hz, below unison.
|
||||||
|
let heel: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 2.0
|
||||||
|
pedal.position = 0.0
|
||||||
|
}
|
||||||
|
let toe: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 2.0
|
||||||
|
pedal.position = 1.0
|
||||||
|
}
|
||||||
|
let heelHz: Double = fundamentalHz(heel)
|
||||||
|
let toeHz: Double = fundamentalHz(toe)
|
||||||
|
#expect(hasNonSilentOutput(toe), "Oct Down toe render was silent")
|
||||||
|
#expect(abs(toeHz - sineHz * 0.5) < sineHz * 0.5 * 0.3,
|
||||||
|
"Oct Down toe should be ~110 Hz, got \(toeHz)")
|
||||||
|
#expect(toeHz < heelHz * 0.7, "toe pitch should be well below the heel")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func diveBombCascadeReachesThreeOctaves() throws {
|
||||||
|
// Dive Bomb (mode 4, cascade) toe = −36 st = ratio 0.125 → ~27.5 Hz. It must drop below the
|
||||||
|
// single-stage 2 Oct Down (mode 3, −24 st = ~55 Hz), proving the second cascade stage engaged.
|
||||||
|
// Cap the search near the expected low fundamentals so the deep-shift grain HF can't win.
|
||||||
|
let deepCeilingHz: Double = 120.0
|
||||||
|
let twoOctDownHz: Double = fundamentalHz(try renderSine { pedal in
|
||||||
|
pedal.mode = 3.0
|
||||||
|
pedal.position = 1.0
|
||||||
|
}, maxHz: deepCeilingHz)
|
||||||
|
let diveBomb: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 4.0
|
||||||
|
pedal.position = 1.0
|
||||||
|
}
|
||||||
|
let diveHz: Double = fundamentalHz(diveBomb, maxHz: deepCeilingHz)
|
||||||
|
#expect(hasNonSilentOutput(diveBomb), "Dive Bomb render was silent")
|
||||||
|
#expect(abs(diveHz - sineHz * 0.125) < sineHz * 0.125 * 0.35,
|
||||||
|
"Dive Bomb toe should be ~27.5 Hz, got \(diveHz)")
|
||||||
|
#expect(diveHz < twoOctDownHz * 0.75,
|
||||||
|
"Dive Bomb (\(diveHz) Hz) should dive below 2 Oct Down (\(twoOctDownHz) Hz)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func harmonyKeepsDryVoiceUnderShifted() throws {
|
||||||
|
// Oct Up/Dn (mode 6) at the toe shifts a voice to −12 st AND keeps the dry note. Its output
|
||||||
|
// must correlate with the dry signal far more than the wet-only Oct Down (mode 2, also −12 st,
|
||||||
|
// no dry) does — the only difference between the two is the summed-in dry voice.
|
||||||
|
let dry: [Float] = try renderSineDry()
|
||||||
|
let harmony: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 6.0 // Oct Up/Dn — toe = −12 st, dry + shifted
|
||||||
|
pedal.position = 1.0
|
||||||
|
}
|
||||||
|
let wetOnly: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 2.0 // Oct Down — toe = −12 st, shifted only
|
||||||
|
pedal.position = 1.0
|
||||||
|
}
|
||||||
|
let harmonyCorr: Double = correlation(harmony, dry)
|
||||||
|
let wetCorr: Double = correlation(wetOnly, dry)
|
||||||
|
#expect(hasNonSilentOutput(harmony), "harmony render was silent")
|
||||||
|
#expect(harmonyCorr > wetCorr + 0.2,
|
||||||
|
"harmony should correlate with the dry signal far more than the wet-only shift (harmony \(harmonyCorr) vs wet-only \(wetCorr))")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func renderIsDeterministic() throws {
|
||||||
|
// Every PitchShift stage is seeded, and the sine source is RNG-free, so two identical renders
|
||||||
|
// must be bit-identical. (Guards the seeding that makes the pitch assertions meaningful.)
|
||||||
|
let a: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 4.0 // Dive Bomb — exercises both cascade stages' seeds
|
||||||
|
pedal.position = 0.6
|
||||||
|
}
|
||||||
|
let b: [Float] = try renderSine { pedal in
|
||||||
|
pedal.mode = 4.0
|
||||||
|
pedal.position = 0.6
|
||||||
|
}
|
||||||
|
#expect(a == b, "seeded renders of the same setting should be bit-identical")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Bypass transition
|
||||||
|
|
||||||
|
/// Renders the Whammy manually block-by-block through a no-op `OfflineDriver`, flipping `bypass`
|
||||||
|
/// from engaged (`0`) to bypassed (`1`) at `flipFrame`, and returns the left hardware-output
|
||||||
|
/// channel. Hand-stepping `processBlock` is the only way to change a live `@UIParam` mid-render —
|
||||||
|
/// `NRTDriver.start()` renders the whole file in one blocking call with no seam to intervene at.
|
||||||
|
private func renderBypassFlip(
|
||||||
|
mode: Double,
|
||||||
|
position: Double,
|
||||||
|
flipFrame: Int,
|
||||||
|
totalFrames: Int,
|
||||||
|
blockSize: Int = 64
|
||||||
|
) throws -> [Float] {
|
||||||
|
let numAudioBuses: Int = 64
|
||||||
|
let numControlBuses: Int = 512
|
||||||
|
let driver: OfflineDriver = OfflineDriver()
|
||||||
|
let engine: SynthesisEngine = SynthesisEngine(
|
||||||
|
blockSize: blockSize,
|
||||||
|
sampleRate: sampleRate,
|
||||||
|
numOutputChannels: 2,
|
||||||
|
numInputChannels: 0,
|
||||||
|
numAudioBuses: numAudioBuses,
|
||||||
|
numControlBuses: numControlBuses,
|
||||||
|
driver: driver
|
||||||
|
)
|
||||||
|
|
||||||
|
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: TestSineSource = TestSineSource(targetBus: srcBus.index, freq: sineHz)
|
||||||
|
let pedal: WhammyPedal = WhammyPedal(inputBus: srcBus.index, outputBus: dstBus.index)
|
||||||
|
pedal.mode = mode
|
||||||
|
pedal.position = position
|
||||||
|
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))
|
||||||
|
// OfflineDriver.start() is a no-op, so this allocates buses + builds the node tree without
|
||||||
|
// rendering; the block loop below drives the render by hand.
|
||||||
|
try engine.start()
|
||||||
|
|
||||||
|
let noInput: [[Float]] = []
|
||||||
|
var left: [Float] = []
|
||||||
|
left.reserveCapacity(totalFrames)
|
||||||
|
var frame: Int = 0
|
||||||
|
var flipped: Bool = false
|
||||||
|
while frame < totalFrames {
|
||||||
|
if !flipped, frame >= flipFrame {
|
||||||
|
pedal.bypass = 1.0 // engage → bypassed, mid-render
|
||||||
|
flipped = true
|
||||||
|
}
|
||||||
|
engine.processBlock(inputSamples: noInput)
|
||||||
|
let bus: [Float] = engine.audioBuses[0] // hardware output, left
|
||||||
|
left.append(contentsOf: bus)
|
||||||
|
frame += blockSize
|
||||||
|
}
|
||||||
|
engine.stop()
|
||||||
|
return left
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Max absolute first difference (per-sample step) over `[lo, hi)`. An impulsive click shows up
|
||||||
|
/// here as a step far larger than the signal's own slope.
|
||||||
|
private func maxStep(_ x: [Float], lo: Int, hi: Int) -> Double {
|
||||||
|
let a: Int = max(1, lo)
|
||||||
|
let b: Int = min(hi, x.count)
|
||||||
|
guard b > a else { return 0.0 }
|
||||||
|
var m: Double = 0.0
|
||||||
|
for i: Int in a ..< b {
|
||||||
|
let d: Double = abs(Double(x[i]) - Double(x[i - 1]))
|
||||||
|
if d > m { m = d }
|
||||||
|
}
|
||||||
|
return m
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func bypassSwitchIsClickFree() throws {
|
||||||
|
// Clocking a wet-only pitch voice (Oct Up, +12 at the toe) on/off crossfades the dry note
|
||||||
|
// against a fully decorrelated shifted voice. The linear-slew equal-power bypass crossfade
|
||||||
|
// must keep that transition click-free: no impulsive step and no energy dropout at the seam.
|
||||||
|
// (A naive hard gate, or the old front-loaded one-pole lag, spikes the first difference here.)
|
||||||
|
// Use the engine's real 512-sample block: a block-rate bypass smoother takes only a few
|
||||||
|
// coarse steps per short fade at this size, so testing at a small block would hide the click.
|
||||||
|
let blockSize: Int = 512
|
||||||
|
let totalFrames: Int = 26_460 // 0.6 s at 44.1 kHz
|
||||||
|
let flipFrame: Int = 15_435 // ~0.35 s
|
||||||
|
let left: [Float] = try renderBypassFlip(
|
||||||
|
mode: 1.0, // Oct Up — wet only, +12 st at the toe
|
||||||
|
position: 1.0,
|
||||||
|
flipFrame: flipFrame,
|
||||||
|
totalFrames: totalFrames,
|
||||||
|
blockSize: blockSize
|
||||||
|
)
|
||||||
|
#expect(hasNonSilentOutput(left), "bypass-flip render was silent")
|
||||||
|
|
||||||
|
// Steady engaged region, past the shifter warm-up and before the flip.
|
||||||
|
let steadyLo: Int = 9_700 // ~0.22 s
|
||||||
|
let steadyHi: Int = 14_500 // ~0.33 s
|
||||||
|
// Transition region: the flip plus the fade time and a little settle.
|
||||||
|
let fadeFrames: Int = Int(0.03 * sampleRate)
|
||||||
|
let transLo: Int = flipFrame - blockSize
|
||||||
|
let transHi: Int = flipFrame + fadeFrames + 2_000
|
||||||
|
|
||||||
|
let steadyStep: Double = maxStep(left, lo: steadyLo, hi: steadyHi)
|
||||||
|
let transStep: Double = maxStep(left, lo: transLo, hi: transHi)
|
||||||
|
// No impulsive click: the biggest per-sample step across the seam stays within a small
|
||||||
|
// multiple of the signal's own steady-state slope (grain splices included). This is the real
|
||||||
|
// guard — at the engine's 512-sample block a block-rate smoother (the old one-pole lag, or a
|
||||||
|
// control-rate slew) leaks a coarse step here; the audio-rate slew ramps per sample.
|
||||||
|
// (Energy continuity is not asserted: the Oct Up wet voice's inherent SOLA amplitude warble
|
||||||
|
// swamps any seam-level change, so a short-window RMS is not a usable dropout metric here.)
|
||||||
|
#expect(transStep <= steadyStep * 4.0,
|
||||||
|
"bypass transition stepped \(transStep) vs steady \(steadyStep) — a click leaked through")
|
||||||
|
}
|
||||||
|
|
||||||
|
// MARK: - Build / wiring
|
||||||
|
|
||||||
|
@Test func buildsAndProducesNonSilentOutput() throws {
|
||||||
|
let samples: [Float] = try render { pedal in
|
||||||
|
pedal.mode = 0.0 // 2 Oct Up
|
||||||
|
pedal.position = 0.5
|
||||||
|
}
|
||||||
|
#expect(!samples.isEmpty)
|
||||||
|
#expect(hasNonSilentOutput(samples), "whammy output was silent")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func exposesPedalKnobAndModeSelector() throws {
|
||||||
|
let pedal: WhammyPedal = WhammyPedal()
|
||||||
|
#expect(pedal.effectKnobs.map { $0.label } == ["Pedal"])
|
||||||
|
let selectors: [PedalSelectorKnob] = pedal.effectSelectors
|
||||||
|
#expect(selectors.map { $0.label } == ["Mode"])
|
||||||
|
let titles: [String] = selectors.first?.stops.map { $0.title } ?? []
|
||||||
|
#expect(titles.contains("2 Oct Up"))
|
||||||
|
#expect(titles.contains("Dive Bomb"))
|
||||||
|
#expect(titles.contains("Drop Tune"))
|
||||||
|
#expect(titles.contains("Oct Up/Dn"))
|
||||||
|
#expect(titles.contains("Detune Deep"))
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func presetRoundTripPreservesModeAndPosition() throws {
|
||||||
|
let pedal: WhammyPedal = WhammyPedal()
|
||||||
|
pedal.position = 0.75
|
||||||
|
pedal.mode = 2.0 // Oct Down
|
||||||
|
|
||||||
|
let state: PedalState = pedal.captureState()
|
||||||
|
#expect(state.selectorValues == [2.0], "mode should round-trip as the sole selector value")
|
||||||
|
#expect(state.knobValues.first == 0.75, "position should be the first knob value")
|
||||||
|
|
||||||
|
let restored: WhammyPedal = WhammyPedal()
|
||||||
|
restored.applyState(state)
|
||||||
|
#expect(restored.position == 0.75)
|
||||||
|
#expect(restored.mode == 2.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func modeSwitchRebuildsBoard() throws {
|
||||||
|
// Each program is a distinct voice topology read at build time, so the Mode selector must
|
||||||
|
// drive a board rebuild — a plain node write would leave the audible program stuck.
|
||||||
|
let pedal: WhammyPedal = WhammyPedal()
|
||||||
|
pedal.mode = 3.0
|
||||||
|
#expect(pedal.rebuildTopologyValues == [3.0],
|
||||||
|
"Mode must be a rebuildsOnChange selector so switching programs re-enters effect(_:)")
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test func registeredInBuiltInRegistry() throws {
|
||||||
|
let pedal: Pedal? = PedalRegistry.makePedal(type: "Whammy")
|
||||||
|
#expect(pedal is WhammyPedal)
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user