Compare commits
10 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 77580ee98e | |||
| ea0aa84ca7 | |||
| 3e33f09e07 | |||
| d6875da2cb | |||
| 5e6534a615 | |||
| 9ec92277de | |||
| 90dc00f323 | |||
| 8eb64f883f | |||
| 62b2f5dbec | |||
| 8519cabe42 |
@@ -11,30 +11,11 @@
|
||||
C8D0000000000000000000D /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000008 /* AppDelegate.swift */; };
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; };
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000034 /* LyrebirdLiveCompileUIDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000036 /* LyrebirdDynamic in Embed Frameworks */ = {isa = PBXBuildFile; productRef = C8D0000000000000000001D /* LyrebirdDynamic */; settings = {ATTRIBUTES = (CodeSignOnCopy, ); }; };
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = C8D00000000000000000040 /* Assets.xcassets */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratchDemo.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratchDemo.entitlements; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
C8D00000000000000000035 /* Embed Frameworks */ = {
|
||||
isa = PBXCopyFilesBuildPhase;
|
||||
@@ -50,11 +31,32 @@
|
||||
};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = LyrebirdScratch.app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
C8D00000000000000000006 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
C8D00000000000000000007 /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000008 /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = LyrebirdScratch.entitlements; sourceTree = "<group>"; };
|
||||
C8D00000000000000000040 /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
C8D00000000000000000012 /* Frameworks */ = {
|
||||
isa = PBXFrameworksBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D0000000000000000000F /* LyrebirdDynamic in Frameworks */,
|
||||
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
C8D00000000000000000002 = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000005 /* LyrebirdScratch */,
|
||||
C8D00000000000000000003 /* Products */,
|
||||
);
|
||||
sourceTree = "<group>";
|
||||
@@ -62,45 +64,47 @@
|
||||
C8D00000000000000000003 /* Products */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000004 /* LyrebirdScratchDemo.app */,
|
||||
C8D00000000000000000004 /* LyrebirdScratch.app */,
|
||||
);
|
||||
name = Products;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
C8D00000000000000000005 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000005 /* LyrebirdScratch */ = {
|
||||
isa = PBXGroup;
|
||||
children = (
|
||||
C8D00000000000000000007 /* main.swift */,
|
||||
C8D00000000000000000008 /* AppDelegate.swift */,
|
||||
C8D00000000000000000006 /* Info.plist */,
|
||||
C8D00000000000000000009 /* LyrebirdScratchDemo.entitlements */,
|
||||
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
|
||||
C8D00000000000000000040 /* Assets.xcassets */,
|
||||
);
|
||||
path = LyrebirdScratchDemo;
|
||||
path = LyrebirdScratch;
|
||||
sourceTree = "<group>";
|
||||
};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */ = {
|
||||
C8D00000000000000000014 /* LyrebirdScratch */ = {
|
||||
isa = PBXNativeTarget;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */;
|
||||
buildPhases = (
|
||||
C8D00000000000000000011 /* Sources */,
|
||||
C8D00000000000000000012 /* Frameworks */,
|
||||
C8D00000000000000000013 /* Resources */,
|
||||
C8D00000000000000000035 /* Embed Frameworks */,
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
|
||||
);
|
||||
buildRules = (
|
||||
);
|
||||
dependencies = (
|
||||
);
|
||||
name = LyrebirdScratchDemo;
|
||||
name = LyrebirdScratch;
|
||||
packageProductDependencies = (
|
||||
C8D0000000000000000001D /* LyrebirdDynamic */,
|
||||
C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */,
|
||||
);
|
||||
productName = LyrebirdScratchDemo;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratchDemo.app */;
|
||||
productName = LyrebirdScratch;
|
||||
productReference = C8D00000000000000000004 /* LyrebirdScratch.app */;
|
||||
productType = "com.apple.product-type.application";
|
||||
};
|
||||
/* End PBXNativeTarget section */
|
||||
@@ -111,14 +115,14 @@
|
||||
attributes = {
|
||||
BuildIndependentTargetsInParallel = 1;
|
||||
LastSwiftUpdateCheck = 1600;
|
||||
LastUpgradeCheck = 2620;
|
||||
LastUpgradeCheck = 2660;
|
||||
TargetAttributes = {
|
||||
C8D00000000000000000014 = {
|
||||
CreatedOnToolsVersion = 16.0;
|
||||
};
|
||||
};
|
||||
};
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */;
|
||||
buildConfigurationList = C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */;
|
||||
compatibilityVersion = "Xcode 14.0";
|
||||
developmentRegion = en;
|
||||
hasScannedForEncodings = 0;
|
||||
@@ -135,7 +139,7 @@
|
||||
projectDirPath = "";
|
||||
projectRoot = "";
|
||||
targets = (
|
||||
C8D00000000000000000014 /* LyrebirdScratchDemo */,
|
||||
C8D00000000000000000014 /* LyrebirdScratch */,
|
||||
);
|
||||
};
|
||||
/* End PBXProject section */
|
||||
@@ -145,11 +149,30 @@
|
||||
isa = PBXResourcesBuildPhase;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
C8D00000000000000000041 /* Assets.xcassets in Resources */,
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXShellScriptBuildPhase section */
|
||||
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */ = {
|
||||
isa = PBXShellScriptBuildPhase;
|
||||
alwaysOutOfDate = 1;
|
||||
buildActionMask = 2147483647;
|
||||
files = (
|
||||
);
|
||||
inputPaths = (
|
||||
);
|
||||
name = "Bundle Lyrebird swiftmodules";
|
||||
outputPaths = (
|
||||
);
|
||||
runOnlyForDeploymentPostprocessing = 0;
|
||||
shellPath = /bin/sh;
|
||||
shellScript = "# Bundle the Lyrebird module artifacts into the app so the live-compile scratchpad\n# can `import LyrebirdSynth` / `import LyrebirdLiveCompile` on any machine — they\n# otherwise resolve only from BUILT_PRODUCTS_DIR / the dev source tree, both absent\n# once the .app is exported. LiveSession stages Contents/Resources/LyrebirdArtifacts\n# at launch; artifactSourceDir() / discoverSPMModuleMaps() then find them.\nset -e\nART=\"${TARGET_BUILD_DIR}/${CONTENTS_FOLDER_PATH}/Resources/LyrebirdArtifacts\"\nDEST=\"${ART}/Modules\"\n/bin/rm -rf \"${ART}\"\n/bin/mkdir -p \"${DEST}\"\n# 1. Swift module interfaces the snippet imports (+ their transitive deps).\nfor m in LyrebirdSynth LyrebirdLiveCompile LyrebirdLiveCompileUI LyrebirdGraphDSLEmbedded; do\n SRC=\"${BUILT_PRODUCTS_DIR}/${m}.swiftmodule\"\n if [ -e \"${SRC}\" ]; then /bin/cp -R \"${SRC}\" \"${DEST}/\"; fi\ndone\n# 2. LyrebirdC C-shim Clang module (LyrebirdSynth depends on it; a snippet importing\n# LyrebirdSynth needs its module map + header). The SPM source map uses a header path\n# relative to the map dir, so map + include/ copied together stay self-contained and\n# relocatable — placed at LyrebirdArtifacts/LyrebirdC.build so discoverSPMModuleMaps()\n# finds it once staged.\nCSRC=\"${SRCROOT}/../../Sources/LyrebirdC\"\nif [ -f \"${CSRC}/module.modulemap\" ]; then\n CDEST=\"${ART}/LyrebirdC.build\"\n /bin/mkdir -p \"${CDEST}\"\n /bin/cp \"${CSRC}/module.modulemap\" \"${CDEST}/\"\n [ -d \"${CSRC}/include\" ] && /bin/cp -R \"${CSRC}/include\" \"${CDEST}/\"\nfi\necho \"Bundled Lyrebird modules + LyrebirdC shim into ${ART}\"\n";
|
||||
};
|
||||
/* End PBXShellScriptBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
C8D00000000000000000011 /* Sources */ = {
|
||||
isa = PBXSourcesBuildPhase;
|
||||
@@ -166,19 +189,40 @@
|
||||
C8D00000000000000000016 /* Debug */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -187,18 +231,39 @@
|
||||
C8D00000000000000000017 /* Release */ = {
|
||||
isa = XCBuildConfiguration;
|
||||
buildSettings = {
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratchDemo/LyrebirdScratchDemo.entitlements;
|
||||
ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
|
||||
ASSETCATALOG_COMPILER_INCLUDE_ALL_APPICON_ASSETS = YES;
|
||||
AUTOMATION_APPLE_EVENTS = NO;
|
||||
CODE_SIGN_ENTITLEMENTS = LyrebirdScratch/LyrebirdScratch.entitlements;
|
||||
CODE_SIGN_IDENTITY = "Apple Development";
|
||||
CODE_SIGN_STYLE = Automatic;
|
||||
COMBINE_HIDPI_IMAGES = YES;
|
||||
CURRENT_PROJECT_VERSION = 2;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
ENABLE_HARDENED_RUNTIME = YES;
|
||||
INFOPLIST_FILE = LyrebirdScratchDemo/Info.plist;
|
||||
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
|
||||
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CAMERA = NO;
|
||||
ENABLE_RESOURCE_ACCESS_CONTACTS = NO;
|
||||
ENABLE_RESOURCE_ACCESS_LOCATION = NO;
|
||||
ENABLE_RESOURCE_ACCESS_PHOTO_LIBRARY = NO;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = NO;
|
||||
INFOPLIST_FILE = LyrebirdScratch/Info.plist;
|
||||
LD_RUNPATH_SEARCH_PATHS = (
|
||||
"$(inherited)",
|
||||
"@executable_path/../Frameworks",
|
||||
);
|
||||
MACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratchDemo;
|
||||
MARKETING_VERSION = 1.6.2;
|
||||
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
|
||||
PRODUCT_NAME = "$(TARGET_NAME)";
|
||||
PROVISIONING_PROFILE_SPECIFIER = "";
|
||||
RUNTIME_EXCEPTION_ALLOW_DYLD_ENVIRONMENT_VARIABLES = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_JIT = NO;
|
||||
RUNTIME_EXCEPTION_ALLOW_UNSIGNED_EXECUTABLE_MEMORY = NO;
|
||||
RUNTIME_EXCEPTION_DEBUGGING_TOOL = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_EXECUTABLE_PAGE_PROTECTION = NO;
|
||||
RUNTIME_EXCEPTION_DISABLE_LIBRARY_VALIDATION = NO;
|
||||
SWIFT_EMIT_LOC_STRINGS = YES;
|
||||
SWIFT_VERSION = 5.0;
|
||||
};
|
||||
@@ -239,6 +304,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = dwarf;
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_TESTABILITY = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -263,9 +329,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
// Xcode 26 explicit-module-build regression: SPM dynamic-library
|
||||
// framework binaries (LyrebirdDynamic / LyrebirdLiveCompileUIDynamic)
|
||||
// are not emitted under the integrated driver. Classic driver fixes it.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Debug;
|
||||
@@ -305,6 +368,7 @@
|
||||
COPY_PHASE_STRIP = NO;
|
||||
DEAD_CODE_STRIPPING = YES;
|
||||
DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
DEVELOPMENT_TEAM = HE5VJFE9E4;
|
||||
ENABLE_NS_ASSERTIONS = NO;
|
||||
ENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
ENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
@@ -322,7 +386,6 @@
|
||||
STRING_CATALOG_GENERATE_SYMBOLS = YES;
|
||||
SWIFT_COMPILATION_MODE = wholemodule;
|
||||
SWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
// Xcode 26 explicit-module-build regression — see Debug config.
|
||||
SWIFT_USE_INTEGRATED_DRIVER = NO;
|
||||
};
|
||||
name = Release;
|
||||
@@ -330,7 +393,7 @@
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000015 /* Build configuration list for PBXNativeTarget "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000016 /* Debug */,
|
||||
@@ -339,7 +402,7 @@
|
||||
defaultConfigurationIsVisible = 0;
|
||||
defaultConfigurationName = Release;
|
||||
};
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratchDemo" */ = {
|
||||
C8D00000000000000000018 /* Build configuration list for PBXProject "LyrebirdScratch" */ = {
|
||||
isa = XCConfigurationList;
|
||||
buildConfigurations = (
|
||||
C8D00000000000000000019 /* Debug */,
|
||||
@@ -16,9 +16,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
@@ -31,7 +31,7 @@
|
||||
shouldAutocreateTestPlan = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
buildConfiguration = "Release"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0"
|
||||
@@ -45,9 +45,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
@@ -62,9 +62,9 @@
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "C8D00000000000000000014"
|
||||
BuildableName = "LyrebirdScratchDemo.app"
|
||||
BlueprintName = "LyrebirdScratchDemo"
|
||||
ReferencedContainer = "container:LyrebirdScratchDemo.xcodeproj">
|
||||
BuildableName = "LyrebirdScratch.app"
|
||||
BlueprintName = "LyrebirdScratch"
|
||||
ReferencedContainer = "container:LyrebirdScratch.xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
@@ -20,6 +20,21 @@ import LyrebirdLiveCompileUI
|
||||
// this demo used was `LyrebirdWindow`, an `NSWindow`/`NSHostingController`
|
||||
// wrapper with no `LyrebirdSynth` dependency — inlined below instead.
|
||||
|
||||
// Entitlements / signing posture (rationale kept here because Xcode strips
|
||||
// comments from `LyrebirdScratch.entitlements` on every project resave):
|
||||
//
|
||||
// • App Sandbox is intentionally OFF. Live-compile shells out to `swiftc`
|
||||
// (`posix_spawn`, disallowed under the sandbox) and `dlopen`s the resulting
|
||||
// UNSIGNED snippet dylib (rejected by the sandbox). This is a direct-
|
||||
// distribution developer tool, not a Mac App Store app; sandbox-off is the
|
||||
// only viable configuration. (An XPC-worker split could revisit this.)
|
||||
// • Hardened Runtime is ON, so the entitlement
|
||||
// `com.apple.security.cs.disable-library-validation = true` is REQUIRED —
|
||||
// without it dyld rejects `dlopen` of the unsigned, non-team-signed snippet
|
||||
// dylib ("code signing blocked mmap()").
|
||||
//
|
||||
// Do not remove that entitlement or the app can't load compiled snippets.
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
@@ -31,6 +46,12 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
@MainActor
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
// Stage the Lyrebird compile artifacts into ~/Library/Application Support
|
||||
// (ungated) before the session reads its default -I/-L/rpath. Without
|
||||
// this the snippet compiler points swiftc at the SPM build dir under
|
||||
// ~/Documents, tripping the macOS Documents-folder permission gate.
|
||||
// Best-effort: if staging fails the session falls back to the build dir.
|
||||
LiveSession.stageArtifacts()
|
||||
self.session = LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@@ -39,7 +60,7 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("[LyrebirdScratchDemo] Engine failed to start: \(error)")
|
||||
print("[LyrebirdScratch] Engine failed to start: \(error)")
|
||||
}
|
||||
|
||||
let model: LyrebirdScratchModel = LyrebirdScratchModel(session: session)
|
||||
@@ -48,13 +69,10 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
menuController.installMainMenu()
|
||||
self.menuController = menuController
|
||||
|
||||
let windowWidth: CGFloat = 720
|
||||
let windowHeight: CGFloat = 560
|
||||
let hosting: NSHostingController<LyrebirdScratchView> =
|
||||
NSHostingController(rootView: LyrebirdScratchView(model: model))
|
||||
let initialSize: CGSize = CGSize(width: windowWidth, height: windowHeight)
|
||||
let win: NSWindow = NSWindow(
|
||||
contentRect: NSRect(origin: .zero, size: initialSize),
|
||||
contentRect: NSRect(origin: .zero, size: CGSize(width: 720, height: 560)),
|
||||
styleMask: [.titled, .closable, .resizable, .miniaturizable],
|
||||
backing: .buffered,
|
||||
defer: false
|
||||
@@ -63,7 +81,16 @@ final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
win.isReleasedWhenClosed = false
|
||||
win.title = "Lyrebird — Live Scratch"
|
||||
win.contentViewController = hosting
|
||||
win.center()
|
||||
// Base geometry: three-quarters of the screen wide, three-quarters tall,
|
||||
// anchored to the left edge and vertically centered in the visible area
|
||||
// (below the menu bar, above the Dock).
|
||||
let visible: NSRect = (win.screen ?? NSScreen.main)?.visibleFrame
|
||||
?? NSRect(x: 0, y: 0, width: 1440, height: 900)
|
||||
let width: CGFloat = visible.width * 0.75
|
||||
let height: CGFloat = visible.height * 0.75
|
||||
let originX: CGFloat = visible.minX
|
||||
let originY: CGFloat = visible.minY + (visible.height - height) / 2
|
||||
win.setFrame(NSRect(x: originX, y: originY, width: width, height: height), display: true)
|
||||
win.makeKeyAndOrderFront(nil)
|
||||
self.window = win
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"images" : [
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "16x16", "filename" : "icon_16.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "16x16", "filename" : "icon_32.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "32x32", "filename" : "icon_32.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "32x32", "filename" : "icon_64.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "128x128", "filename" : "icon_128.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "128x128", "filename" : "icon_256.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "256x256", "filename" : "icon_256.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "256x256", "filename" : "icon_512.png" },
|
||||
{ "idiom" : "mac", "scale" : "1x", "size" : "512x512", "filename" : "icon_512.png" },
|
||||
{ "idiom" : "mac", "scale" : "2x", "size" : "512x512", "filename" : "icon_1024.png" }
|
||||
],
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
|
After Width: | Height: | Size: 338 KiB |
|
After Width: | Height: | Size: 13 KiB |
|
After Width: | Height: | Size: 720 B |
|
After Width: | Height: | Size: 39 KiB |
|
After Width: | Height: | Size: 1.4 KiB |
|
After Width: | Height: | Size: 115 KiB |
|
After Width: | Height: | Size: 4.0 KiB |
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"info" : { "author" : "xcode", "version" : 1 }
|
||||
}
|
||||
@@ -13,14 +13,14 @@
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<string>1.6.3</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<string>3</string>
|
||||
<key>LSMinimumSystemVersion</key>
|
||||
<string>$(MACOSX_DEPLOYMENT_TARGET)</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © 2026 Realized Sound. All rights reserved.</string>
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -1,45 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<!--
|
||||
App Sandbox is intentionally OFF.
|
||||
|
||||
LyrebirdScratchDemo shells out to `swiftc` at runtime to compile user-
|
||||
typed Swift snippets, then calls `dlopen` on the resulting unsigned dylib.
|
||||
Both operations are blocked by the macOS App Sandbox:
|
||||
|
||||
- `posix_spawn` / `fork` for the swiftc subprocess is disallowed in a
|
||||
sandboxed process (com.apple.security.temporary-exception.mach-lookup
|
||||
grants exist for specific Apple tools only, not arbitrary executables).
|
||||
- `dlopen` of a dylib that was not shipped with the app bundle and is
|
||||
not code-signed with a matching team ID is rejected by the sandbox.
|
||||
|
||||
This app is a direct-distribution developer tool, not a Mac App Store
|
||||
submission. Sandbox OFF is the only viable configuration for v1.
|
||||
This could be revisited if an XPC-worker approach is adopted.
|
||||
|
||||
com.apple.security.app-sandbox key is absent (defaults false).
|
||||
-->
|
||||
|
||||
<!--
|
||||
Hardened Runtime — Disable Library Validation.
|
||||
|
||||
With Hardened Runtime enabled (ENABLE_HARDENED_RUNTIME = YES in the
|
||||
Xcode project), `dlopen` of a dylib that was not signed with the same
|
||||
Team ID as the host app is rejected by the dynamic linker.
|
||||
|
||||
LyrebirdScratchDemo writes snippet dylibs to a per-session temp dir
|
||||
via `swiftc -emit-library`; those dylibs are unsigned (swiftc does not
|
||||
sign them). The `CS_ALLOW_UNSIGNED_EXECUTABLE_MEMORY` (library-
|
||||
validation disable) entitlement tells the kernel to skip the
|
||||
code-signing check for loaded libraries, allowing `dlopen` to succeed.
|
||||
|
||||
Without this entitlement the app would crash with DYLD_PRINT_LIBRARIES
|
||||
reporting: "Library not loaded: ... Reason: tried: ... no suitable image
|
||||
found. Did find: ... code signing blocked mmap() of '...'"
|
||||
-->
|
||||
<key>com.apple.security.cs.disable-library-validation</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
@@ -368,6 +368,6 @@ The repo ships eight runnable demos in [`Demos/`](Demos/), opened via `Lyrebird.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | `nrt` |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | `score` |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | `auv3` |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | live-coding scratchpad |
|
||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | live-coding scratchpad |
|
||||
|
||||
See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for per-demo notes and gotchas.
|
||||
|
||||
@@ -141,7 +141,7 @@ A container app + `.appex` extension target shipping **Realized Sound: LyrebirdF
|
||||
|
||||
---
|
||||
|
||||
### LyrebirdScratchDemo — Live-Coding Scratchpad
|
||||
### LyrebirdScratch — Live-Coding Scratchpad
|
||||
|
||||
A macOS app that compiles a typed Swift snippet against the live engine at ⌘↩. Backed by `LyrebirdScratchView` and `LiveSession` from the `LyrebirdLiveCompile` SPM target.
|
||||
|
||||
@@ -157,7 +157,7 @@ A macOS app that compiles a typed Swift snippet against the live engine at ⌘
|
||||
- **Clear Synths** toolbar button — full reset: removes all tracked synths *and* every named slot immediately.
|
||||
|
||||
**Why this app cannot be sandboxed:**
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratchDemo.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
`swiftc` is a subprocess (`posix_spawn`); the output dylib is unsigned. Both are blocked by the macOS App Sandbox. This app is a direct-distribution developer tool only. The entitlements file (`LyrebirdScratch.entitlements`) sets `com.apple.security.cs.disable-library-validation = true` to let Hardened Runtime `dlopen` the unsigned snippet dylib.
|
||||
|
||||
**Dylib lifetime:** loaded dylibs are never unloaded. `Synthesizer` instances reference types from the dylib; unloading while they are active would crash. Every ⌘↩ evaluation writes a new uniquely-named dylib to a per-session temp dir. This is intentional v1 behaviour; a future release may revisit with an XPC worker approach.
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
// ArtifactStagingError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Errors raised while staging compile artifacts into Application Support.
|
||||
enum ArtifactStagingError: Error {
|
||||
/// The staging destination already exists, is non-empty, and does not look
|
||||
/// like a prior staging root — refused rather than clobbered.
|
||||
case destinationNotAStagingRoot(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -40,6 +40,14 @@ public final class LiveSession: @unchecked Sendable {
|
||||
|
||||
public let engine: SynthesisEngine
|
||||
|
||||
/// Output-tapping oscilloscope capture for the editor's scope view. When a
|
||||
/// fresh tap is installed at init (the engine is not yet running and has no
|
||||
/// tap), this is that capture; if the engine already had a `scopeTap`, this
|
||||
/// reuses it; it is `nil` only when no tap is present (attachment declined,
|
||||
/// or the engine was already running with no tap). Must be installed before
|
||||
/// `start()`.
|
||||
public let scope: ScopeCapture?
|
||||
|
||||
/// `-I` paths threaded to `swiftc` for module discovery.
|
||||
public let importPaths: [URL]
|
||||
|
||||
@@ -64,9 +72,27 @@ public final class LiveSession: @unchecked Sendable {
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var reportedSampleRate: Double?
|
||||
|
||||
/// Side-channel for snippet `context.reportMessage(_:)` calls. Tests read
|
||||
/// via `@testable import`; not part of the public API.
|
||||
internal var lastSnippetMessage: String?
|
||||
/// Most recent snippet `context.reportMessage(_:)` value (tests read this via
|
||||
/// `@testable import`). Backed by the internal message log (`_messageLog`).
|
||||
internal var lastSnippetMessage: String? { _messageLog.last }
|
||||
|
||||
/// Accumulated `context.reportMessage(_:)` output (and host-side notices like
|
||||
/// a dropped slot swap) since the last drain. Main-thread only — appended
|
||||
/// during the synchronous snippet entry, drained by the host after each run.
|
||||
private var _messageLog: [String] = []
|
||||
|
||||
/// Append a snippet/host message to the log. Main-thread only.
|
||||
internal func appendMessage(_ message: String) {
|
||||
_messageLog.append(message)
|
||||
}
|
||||
|
||||
/// Return and clear the accumulated messages. Called by the host after a run
|
||||
/// to move them into its console.
|
||||
public func drainMessages() -> [String] {
|
||||
let out: [String] = _messageLog
|
||||
_messageLog.removeAll()
|
||||
return out
|
||||
}
|
||||
|
||||
// Tracked state — all access guarded by `trackingLock`.
|
||||
private let trackingLock: NSLock = NSLock()
|
||||
@@ -100,14 +126,31 @@ public final class LiveSession: @unchecked Sendable {
|
||||
private var _swapQuantize: SwapQuantize = .immediate
|
||||
private var _pendingSwapBeat: Double?
|
||||
|
||||
/// Samples per channel the scope captures per display frame.
|
||||
private static let scopeBufferSize: Int = 1024
|
||||
|
||||
/// - Parameter attachScope: When `true` (default) and the engine is not yet
|
||||
/// running and has no existing tap, install a ``ScopeCapture`` on the first
|
||||
/// one or two output buses for the editor's scope view.
|
||||
public init(
|
||||
engine: SynthesisEngine,
|
||||
attachScope: Bool = true,
|
||||
importPaths: [URL] = LiveSession.defaultImportPaths(),
|
||||
librarySearchPaths: [URL] = LiveSession.defaultLibrarySearchPaths(),
|
||||
libraries: [String] = ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [URL] = LiveSession.defaultRpaths()
|
||||
) {
|
||||
self.engine = engine
|
||||
// Install the scope tap before the host calls `start()` (the RT thread
|
||||
// caches `scopeTap` at start; setting it afterwards is a no-op).
|
||||
if attachScope, !engine.isRunning, engine.scopeTap == nil, engine.numOutputChannels >= 1 {
|
||||
let buses: [Int] = Array(0..<min(2, engine.numOutputChannels))
|
||||
let capture: ScopeCapture = ScopeCapture(buses: buses, bufferSize: LiveSession.scopeBufferSize)
|
||||
engine.scopeTap = capture
|
||||
self.scope = capture
|
||||
} else {
|
||||
self.scope = engine.scopeTap
|
||||
}
|
||||
self.importPaths = importPaths
|
||||
self.librarySearchPaths = librarySearchPaths
|
||||
self.libraries = libraries
|
||||
@@ -313,6 +356,59 @@ public final class LiveSession: @unchecked Sendable {
|
||||
return false
|
||||
}
|
||||
|
||||
/// **Gracefully release** the synth in the named `slot` (trigger its
|
||||
/// envelope release phase) and drop the slot handle, so the voice tails out
|
||||
/// and then frees itself via its own done-action — rather than being hard-cut
|
||||
/// like ``clearSlot(_:)``. This is the live-coding "let go of this voice"
|
||||
/// gesture: pair it with ``SnippetContext/play(slot:_:)-…`` to start a
|
||||
/// persistent voice under a name and release it later from a separate
|
||||
/// evaluation.
|
||||
///
|
||||
/// The handle is dropped **only if the release succeeds**, so a voice with no
|
||||
/// gate to release (its `release(engine:)` throws) stays in the slot and can
|
||||
/// still be stopped with ``clearSlot(_:)`` — it is never orphaned.
|
||||
///
|
||||
/// On success the voice is moved from the slot map into the anonymous
|
||||
/// tracked list, so it remains reachable by ``clearTracked()`` / ``resetAll()``
|
||||
/// (the toolbar "Clear Synths"). A well-behaved voice self-frees via its
|
||||
/// done-action before then; a mis-configured one that never self-frees is
|
||||
/// still reclaimable rather than leaked until a process restart. (A later
|
||||
/// hard `engine.remove` on an already-self-freed synth is a harmless no-op.)
|
||||
///
|
||||
/// - Parameter name: Slot to release.
|
||||
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||
/// empty or its occupant had no gate (reported via `lastSnippetMessage`).
|
||||
///
|
||||
/// The identity guard below (`… === entry.synth`) is load-bearing, not
|
||||
/// defensive dead code: `clearSlot` / `clearSlots` / `resetAll` are
|
||||
/// nonisolated and may run on another thread while this `release(engine:)`
|
||||
/// call is in flight on the main actor.
|
||||
@MainActor
|
||||
@discardableResult
|
||||
public func releaseSlot(_ name: String) -> Bool {
|
||||
let entry: SlotEntry?
|
||||
do {
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
entry = slottedSynths[name]
|
||||
}
|
||||
guard let entry: SlotEntry = entry else { return false }
|
||||
do {
|
||||
try entry.synth.release(engine: engine)
|
||||
// Released — free the name for reuse and keep the voice reachable by
|
||||
// the tracked-synth sweep (its safety net until it self-frees).
|
||||
trackingLock.lock(); defer { trackingLock.unlock() }
|
||||
if slottedSynths[name]?.synth === entry.synth {
|
||||
slottedSynths[name] = nil
|
||||
trackedSynths.append(entry.synth)
|
||||
}
|
||||
return true
|
||||
} catch {
|
||||
appendMessage(
|
||||
"slot '\(name)': release failed (\(error)) — use clearSlot() to stop it")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Remove a slot occupant, scheduling the removal no earlier than the
|
||||
/// occupant's own add time (`max(desired, addTime)`) so a still-pending
|
||||
/// scheduled add is never orphaned. `desired` is the caller's intended
|
||||
@@ -474,8 +570,8 @@ public final class LiveSession: @unchecked Sendable {
|
||||
if let previous: SlotEntry = previous {
|
||||
let removed: Bool = removeSlotOccupant(previous, desired: time)
|
||||
if !removed {
|
||||
lastSnippetMessage =
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap"
|
||||
appendMessage(
|
||||
"slot '\(name)': previous voice removal dropped (pending queue full) — voices may overlap")
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -713,19 +809,36 @@ public final class LiveSession: @unchecked Sendable {
|
||||
)
|
||||
}
|
||||
|
||||
/// Prefer a populated staged artifacts dir (App Support, ungated) over the
|
||||
/// SPM build dir (which lives under `~/Documents` in a dev checkout). Hosts
|
||||
/// that want staging call ``stageArtifacts(from:to:)`` before constructing
|
||||
/// the session; these defaults then resolve to the staged copy.
|
||||
private static func resolvedArtifactsDir() -> URL? {
|
||||
// Prefer the staged dir only when it is populated AND current relative to
|
||||
// the live build dir — so a stale copy left by a different build (or a
|
||||
// partial stage) never masquerades as the resolved artifacts for a host
|
||||
// that did not itself stage.
|
||||
if let staged: URL = stagedArtifactsDir(),
|
||||
isArtifactsDirPopulated(staged),
|
||||
stagedDirIsCurrent(staged) {
|
||||
return staged
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
public static func defaultImportPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir, buildDir.appendingPathComponent("Modules")]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir, dir.appendingPathComponent("Modules")]
|
||||
}
|
||||
|
||||
public static func defaultLibrarySearchPaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
|
||||
public static func defaultRpaths() -> [URL] {
|
||||
guard let buildDir: URL = currentBuildDir() else { return [] }
|
||||
return [buildDir]
|
||||
guard let dir: URL = resolvedArtifactsDir() else { return [] }
|
||||
return [dir]
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,355 @@
|
||||
// LiveSessionArtifactStaging.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Snippet compilation needs the Lyrebird module artifacts (swiftmodules, the
|
||||
// Lyrebird dylibs, and the C-shim Clang module map + its umbrella header). In a
|
||||
// dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
// non-sandboxed host reading them — and the `swiftc` it spawns reading them —
|
||||
// trips the macOS "wants to access your Documents folder" TCC gate.
|
||||
//
|
||||
// Staging copies the minimal artifact set into
|
||||
// `~/Library/Application Support/LyrebirdScratch/LiveCompile/`, an ungated
|
||||
// location, and rewrites the C module map's absolute umbrella-header path to the
|
||||
// staged copy. The default `-I` / `-L` / rpath resolution then prefers the
|
||||
// staged dir, so a shipped app compiles snippets without ever touching a
|
||||
// permission-gated folder.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
extension LiveSession {
|
||||
|
||||
/// Name of the artifacts subdirectory a host may ship inside its app bundle
|
||||
/// (`<App>.app/Contents/Resources/<name>`). Staging prefers this over the
|
||||
/// dev build dir when present, so a shipped app never reads outside its
|
||||
/// bundle or App Support.
|
||||
public static let bundledArtifactsDirName: String = "LyrebirdArtifacts"
|
||||
|
||||
/// `~/Library/Application Support/LyrebirdScratch/LiveCompile` — the ungated
|
||||
/// destination for staged compile artifacts. `nil` only if the Application
|
||||
/// Support directory can't be resolved.
|
||||
public static func stagedArtifactsDir() -> URL? {
|
||||
guard let base: URL = FileManager.default.urls(
|
||||
for: .applicationSupportDirectory,
|
||||
in: .userDomainMask
|
||||
).first else { return nil }
|
||||
return base
|
||||
.appendingPathComponent("LyrebirdScratch", isDirectory: true)
|
||||
.appendingPathComponent("LiveCompile", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Whether `dir` is a usable compile root: it has a `Modules/` directory
|
||||
/// holding at least one `.swiftmodule`.
|
||||
public static func isArtifactsDirPopulated(_ dir: URL) -> Bool {
|
||||
let modules: URL = dir.appendingPathComponent("Modules", isDirectory: true)
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: modules,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return false }
|
||||
return entries.contains { $0.pathExtension == "swiftmodule" }
|
||||
}
|
||||
|
||||
/// Where to stage FROM. Prefers a `LyrebirdArtifacts` directory shipped in
|
||||
/// the app bundle's `Resources` (self-contained, never under a gated
|
||||
/// folder); falls back to the dev SPM build dir.
|
||||
public static func artifactSourceDir() -> URL? {
|
||||
if let resources: URL = Bundle.main.resourceURL {
|
||||
let bundled: URL = resources.appendingPathComponent(
|
||||
bundledArtifactsDirName,
|
||||
isDirectory: true
|
||||
)
|
||||
if isArtifactsDirPopulated(bundled) { return bundled }
|
||||
}
|
||||
return currentBuildDir()
|
||||
}
|
||||
|
||||
/// Copy the minimal artifact set from `source` (default: ``artifactSourceDir()``)
|
||||
/// into `destination` (default: ``stagedArtifactsDir()``), rewriting the C
|
||||
/// module map to point at a staged copy of its umbrella header. Idempotent:
|
||||
/// skips the copy when the destination is already newer than the source.
|
||||
/// Best-effort — returns the staged dir on success, `nil` on any failure or
|
||||
/// when no source/destination could be resolved.
|
||||
///
|
||||
/// - Note: In a dev checkout the source is the build dir under `~/Documents`,
|
||||
/// so the one-time copy still reads that gated folder; every subsequent
|
||||
/// launch reuses the staged copy and reads only App Support. A shipped app
|
||||
/// whose `Resources/LyrebirdArtifacts` is populated never reads a gated
|
||||
/// folder at all.
|
||||
@discardableResult
|
||||
public static func stageArtifacts(
|
||||
from source: URL? = nil,
|
||||
to destination: URL? = nil
|
||||
) -> URL? {
|
||||
guard let dest: URL = destination ?? stagedArtifactsDir() else { return nil }
|
||||
guard let src: URL = source ?? artifactSourceDir() else { return nil }
|
||||
do {
|
||||
try stageArtifactsThrowing(from: src, to: dest)
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
return isArtifactsDirPopulated(dest) ? dest : nil
|
||||
}
|
||||
|
||||
// MARK: - Implementation
|
||||
|
||||
static let stageReceiptName: String = ".stage-receipt"
|
||||
|
||||
/// Slack in the receipt-vs-source stamp comparison. A `Date` stores seconds
|
||||
/// since 2001; the receipt records `timeIntervalSince1970`, so reconstructing
|
||||
/// it adds then subtracts the ~978-million-second epoch offset — floating-
|
||||
/// point arithmetic at that magnitude perturbs the sub-second fraction, so a
|
||||
/// bit-exact `>=` can spuriously read "stale" (the string encoding itself is
|
||||
/// exact; the loss is in the epoch conversion, not the receipt). mtime
|
||||
/// staleness needs no sub-second resolution — a rebuild moves mtimes by far
|
||||
/// more than a second.
|
||||
private static let stageStampToleranceSeconds: TimeInterval = 1.0
|
||||
|
||||
/// Whether a staged dir at `dest` is current relative to the artifact source
|
||||
/// it would stage from. When no source is discoverable (a shipped app with no
|
||||
/// build dir and no bundled artifacts), any populated staged dir is trusted.
|
||||
/// Otherwise the receipt must be at or after the source's newest artifact —
|
||||
/// so a staged copy left by a *different* build (or a partial stage that never
|
||||
/// wrote a receipt) is ignored and the resolver falls back to the build dir.
|
||||
/// Compared against ``artifactSourceDir()`` (not the build dir directly) so
|
||||
/// the base matches what ``stageArtifacts(from:to:)`` actually copies from.
|
||||
static func stagedDirIsCurrent(_ dest: URL) -> Bool {
|
||||
guard let source: URL = artifactSourceDir() else { return true }
|
||||
guard let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false))
|
||||
else { return false }
|
||||
return prior.timeIntervalSince1970 >= sourceArtifactStamp(source).timeIntervalSince1970 - stageStampToleranceSeconds
|
||||
}
|
||||
|
||||
private static func stageArtifactsThrowing(from src: URL, to dest: URL) throws {
|
||||
let fm: FileManager = FileManager.default
|
||||
let srcStamp: Date = sourceArtifactStamp(src)
|
||||
|
||||
// Up to date? A populated dest whose receipt is at or after the source's
|
||||
// newest artifact mtime needs no re-copy.
|
||||
if isArtifactsDirPopulated(dest),
|
||||
let prior: Date = stageReceiptDate(dest.appendingPathComponent(stageReceiptName, isDirectory: false)),
|
||||
prior.timeIntervalSince1970 >= srcStamp.timeIntervalSince1970 - stageStampToleranceSeconds {
|
||||
return
|
||||
}
|
||||
|
||||
// Refuse to clobber a directory we did not create: an existing, non-empty
|
||||
// `dest` must look like a prior staging root (a receipt or a `Modules/`
|
||||
// dir) before we replace it. Guards a typo'd `to:` from wiping real data.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Build everything in a private sibling temp dir, then atomically swap it
|
||||
// over `dest`. `dest` is therefore only ever fully-complete or absent — a
|
||||
// failed/partial stage never leaves a dir that *looks* valid, and two
|
||||
// stagers racing the same `dest` can't observe a half-written tree.
|
||||
let staging: URL = dest.deletingLastPathComponent()
|
||||
.appendingPathComponent(".\(dest.lastPathComponent).staging-\(UUID().uuidString)", isDirectory: true)
|
||||
try fm.createDirectory(at: staging, withIntermediateDirectories: true)
|
||||
defer { try? fm.removeItem(at: staging) }
|
||||
|
||||
// 1. Swift modules.
|
||||
let srcModules: URL = src.appendingPathComponent("Modules", isDirectory: true)
|
||||
if fm.fileExists(atPath: srcModules.path) {
|
||||
try fm.copyItem(at: srcModules, to: staging.appendingPathComponent("Modules", isDirectory: true))
|
||||
}
|
||||
|
||||
// 2. Lyrebird dylibs (the snippet links these and bakes an rpath here;
|
||||
// at dlopen dyld matches the already-loaded install name, so the copy is
|
||||
// a link-time search target, not a second loaded image).
|
||||
for dylib: URL in lyrebirdDylibs(in: src) {
|
||||
try? fm.copyItem(at: dylib, to: staging.appendingPathComponent(dylib.lastPathComponent))
|
||||
}
|
||||
|
||||
// 2.5. Self-contained C-shim module dirs (`<Module>.build/` holding a
|
||||
// `module.modulemap` whose header path is relative to the map — as shipped
|
||||
// in the app bundle's LyrebirdArtifacts). Copy the whole dir verbatim so the
|
||||
// relative header resolves at the staged location; no path rewrite needed.
|
||||
// (The absolute-`umbrella header` dev-build maps are handled separately in
|
||||
// step 3 — a relative-header map is skipped there, so no double-write.)
|
||||
copySelfContainedModuleMapDirs(from: src, writeInto: staging)
|
||||
|
||||
// 3. C module maps + their umbrella headers. Files are written under the
|
||||
// temp `staging` dir, but the umbrella path baked into each map must
|
||||
// reference the FINAL `dest` (where they land after the atomic swap) —
|
||||
// the temp dir is deleted.
|
||||
stageClangModuleMaps(from: src, writeInto: staging, finalRoot: dest)
|
||||
|
||||
// Receipt: store the source stamp so the next call can skip an unchanged
|
||||
// source.
|
||||
let stampText: String = String(srcStamp.timeIntervalSince1970)
|
||||
try stampText.write(
|
||||
to: staging.appendingPathComponent(stageReceiptName, isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
|
||||
// Re-check the clobber guard immediately before the swap: the copy phase
|
||||
// above is a window in which something could have materialized a
|
||||
// non-staging directory at `dest`. Holding the guard across the whole
|
||||
// operation, not just at entry, keeps `replaceItemAt` from silently
|
||||
// wiping a dir we would have refused.
|
||||
if fm.fileExists(atPath: dest.path), !isReplaceableStagingDest(dest) {
|
||||
throw ArtifactStagingError.destinationNotAStagingRoot(dest.path)
|
||||
}
|
||||
|
||||
// Atomic swap into place.
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
_ = try fm.replaceItemAt(dest, withItemAt: staging)
|
||||
} else {
|
||||
try fm.createDirectory(at: dest.deletingLastPathComponent(), withIntermediateDirectories: true)
|
||||
do {
|
||||
try fm.moveItem(at: staging, to: dest)
|
||||
} catch {
|
||||
// A concurrent stager may have created `dest` between the check
|
||||
// and the move; if it is now a valid root, treat as success.
|
||||
guard isArtifactsDirPopulated(dest) else { throw error }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Lyrebird dylibs present at the top level of `src`.
|
||||
private static func lyrebirdDylibs(in src: URL) -> [URL] {
|
||||
guard let entries: [URL] = try? FileManager.default.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return [] }
|
||||
return entries.filter {
|
||||
$0.pathExtension == "dylib" && $0.lastPathComponent.hasPrefix("libLyrebird")
|
||||
}
|
||||
}
|
||||
|
||||
/// A `dest` is safe to replace when it doesn't exist, is empty, or looks like
|
||||
/// a prior staging root (has a receipt or a `Modules/` dir).
|
||||
private static func isReplaceableStagingDest(_ dest: URL) -> Bool {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent(stageReceiptName).path) { return true }
|
||||
if fm.fileExists(atPath: dest.appendingPathComponent("Modules").path) { return true }
|
||||
let contents: [URL] = (try? fm.contentsOfDirectory(at: dest, includingPropertiesForKeys: nil)) ?? []
|
||||
return contents.isEmpty
|
||||
}
|
||||
|
||||
/// For each `<Module>.build/module.modulemap` under `src` whose umbrella
|
||||
/// header exists, copy the header's `include` directory into
|
||||
/// `writeInto/<Module>.headers` and write a staged map whose umbrella path
|
||||
/// points at `finalRoot/<Module>.headers/<header>` — the location those files
|
||||
/// occupy after the caller's atomic swap of `writeInto` onto `finalRoot`.
|
||||
/// Best-effort per map: a map with no resolvable umbrella header, or one that
|
||||
/// fails to copy, is skipped without aborting the rest.
|
||||
/// Copy each `<Module>.build/` directory under `src` that holds a
|
||||
/// `module.modulemap` **without** an `umbrella header` directive — i.e. a
|
||||
/// self-contained map whose `header "…"` path is relative to the map's own
|
||||
/// directory (as bundled in the app's `LyrebirdArtifacts`). The whole dir is
|
||||
/// copied verbatim (map + adjacent headers), so the relative path resolves at
|
||||
/// the staged location and `discoverSPMModuleMaps` finds the copied map. Maps
|
||||
/// with an absolute `umbrella header` are left for ``stageClangModuleMaps``.
|
||||
private static func copySelfContainedModuleMapDirs(from src: URL, writeInto staging: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
|
||||
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
guard fm.fileExists(atPath: map.path),
|
||||
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||
umbrellaHeaderPath(in: text) == nil // self-contained (relative header) only
|
||||
else { continue }
|
||||
let stagedDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||
try? fm.removeItem(at: stagedDir)
|
||||
try? fm.copyItem(at: buildDir, to: stagedDir)
|
||||
}
|
||||
}
|
||||
|
||||
private static func stageClangModuleMaps(from src: URL, writeInto staging: URL, finalRoot dest: URL) {
|
||||
let fm: FileManager = FileManager.default
|
||||
guard let entries: [URL] = try? fm.contentsOfDirectory(
|
||||
at: src,
|
||||
includingPropertiesForKeys: nil
|
||||
) else { return }
|
||||
|
||||
for buildDir: URL in entries where buildDir.pathExtension == "build" {
|
||||
let map: URL = buildDir.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
guard fm.fileExists(atPath: map.path),
|
||||
let text: String = try? String(contentsOf: map, encoding: .utf8),
|
||||
let umbrella: String = umbrellaHeaderPath(in: text)
|
||||
else { continue }
|
||||
|
||||
let headerURL: URL = URL(fileURLWithPath: umbrella)
|
||||
guard fm.fileExists(atPath: headerURL.path) else { continue }
|
||||
|
||||
let includeDir: URL = headerURL.deletingLastPathComponent()
|
||||
let moduleName: String = buildDir.deletingPathExtension().lastPathComponent
|
||||
let headerName: String = headerURL.lastPathComponent
|
||||
// Files go under the temp staging dir…
|
||||
let stagedHeaders: URL = staging.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
let stagedMapDir: URL = staging.appendingPathComponent(buildDir.lastPathComponent, isDirectory: true)
|
||||
// …but the baked umbrella path names their final resting place.
|
||||
let finalHeader: URL = dest
|
||||
.appendingPathComponent("\(moduleName).headers", isDirectory: true)
|
||||
.appendingPathComponent(headerName, isDirectory: false)
|
||||
let rewritten: String = text.replacingOccurrences(of: umbrella, with: finalHeader.path)
|
||||
do {
|
||||
try? fm.removeItem(at: stagedHeaders)
|
||||
try fm.copyItem(at: includeDir, to: stagedHeaders)
|
||||
try fm.createDirectory(at: stagedMapDir, withIntermediateDirectories: true)
|
||||
try rewritten.write(
|
||||
to: stagedMapDir.appendingPathComponent("module.modulemap", isDirectory: false),
|
||||
atomically: true,
|
||||
encoding: .utf8
|
||||
)
|
||||
} catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract the path inside `umbrella header "..."` from a Clang module map.
|
||||
static func umbrellaHeaderPath(in modulemap: String) -> String? {
|
||||
guard let marker: Range<String.Index> = modulemap.range(of: "umbrella header") else { return nil }
|
||||
let after: Substring = modulemap[marker.upperBound...]
|
||||
guard let open: String.Index = after.firstIndex(of: "\"") else { return nil }
|
||||
let afterOpen: Substring = after[after.index(after: open)...]
|
||||
guard let close: String.Index = afterOpen.firstIndex(of: "\"") else { return nil }
|
||||
return String(afterOpen[..<close])
|
||||
}
|
||||
|
||||
/// Newest modification date among the artifacts we actually copy — a cheap
|
||||
/// staleness proxy that avoids walking the whole build tree. Derives the
|
||||
/// dylib set from the same wildcard scan the copy step uses, so a new/renamed
|
||||
/// Lyrebird dylib can't slip past the freshness check.
|
||||
///
|
||||
/// It does not probe the C module map or its umbrella header directly: a
|
||||
/// header edit forces `swift build` to rebuild the downstream swiftmodules
|
||||
/// too, which moves `Modules/`'s mtime — so a header change is caught
|
||||
/// transitively. (A hand-edited header with no rebuild would not re-stage,
|
||||
/// but that state never occurs from a normal build.)
|
||||
private static func sourceArtifactStamp(_ src: URL) -> Date {
|
||||
let fm: FileManager = FileManager.default
|
||||
var newest: Date = Date.distantPast
|
||||
var probes: [URL] = [src.appendingPathComponent("Modules", isDirectory: true)]
|
||||
probes += lyrebirdDylibs(in: src)
|
||||
for probe: URL in probes {
|
||||
if let attrs: [FileAttributeKey: Any] = try? fm.attributesOfItem(atPath: probe.path),
|
||||
let date: Date = attrs[.modificationDate] as? Date,
|
||||
date > newest {
|
||||
newest = date
|
||||
}
|
||||
}
|
||||
return newest
|
||||
}
|
||||
|
||||
private static func stageReceiptDate(_ receipt: URL) -> Date? {
|
||||
guard let text: String = try? String(contentsOf: receipt, encoding: .utf8),
|
||||
let interval: TimeInterval = TimeInterval(text.trimmingCharacters(in: .whitespacesAndNewlines))
|
||||
else { return nil }
|
||||
return Date(timeIntervalSince1970: interval)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -43,7 +43,7 @@ public final class SnippetContext {
|
||||
session.track(synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "engine.add failed: \(error)"
|
||||
session.appendMessage("engine.add failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -79,7 +79,7 @@ public final class SnippetContext {
|
||||
try session.swapSlot(name, synth: synth)
|
||||
return true
|
||||
} catch {
|
||||
session.lastSnippetMessage = "play(slot: \"\(name)\") failed: \(error)"
|
||||
session.appendMessage("play(slot: \"\(name)\") failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -136,6 +136,41 @@ public final class SnippetContext {
|
||||
play(ClosureSynthesizer(bus: bus, make))
|
||||
}
|
||||
|
||||
/// **Gracefully release** the voice in a named slot — trigger its envelope
|
||||
/// release phase and let it tail out and free itself — then drop the slot.
|
||||
///
|
||||
/// The live-coding "start a voice, let go of it later" gesture: name a slot
|
||||
/// with ``play(slot:_:)``, then release it from a *separate* evaluation (e.g.
|
||||
/// select the line and hit ⌘E):
|
||||
///
|
||||
/// ```swift
|
||||
/// context.play(slot: "pad") { EnvGen(gate: 1, ...) * OscSaw.Audio(freq: 110) }
|
||||
/// // …later, in another evaluation:
|
||||
/// context.release(slot: "pad")
|
||||
/// ```
|
||||
///
|
||||
/// The released voice must free itself (an `EnvGen`/gate with a free-on-done
|
||||
/// action) to leave the engine. For an immediate hard stop instead, use
|
||||
/// ``free(slot:)``.
|
||||
///
|
||||
/// - Parameter name: Slot to release.
|
||||
/// - Returns: `true` if a gated voice was released; `false` if the slot was
|
||||
/// empty or its occupant has no gate.
|
||||
@discardableResult
|
||||
@MainActor public func release(slot name: String) -> Bool {
|
||||
session.releaseSlot(name)
|
||||
}
|
||||
|
||||
/// **Immediately** stop and remove the voice in a named slot — a hard cut,
|
||||
/// no release tail. The counterpart to ``release(slot:)``.
|
||||
///
|
||||
/// - Parameter name: Slot to free.
|
||||
/// - Returns: `true` if a voice was removed; `false` if the slot was empty.
|
||||
@discardableResult
|
||||
@MainActor public func free(slot name: String) -> Bool {
|
||||
session.clearSlot(name)
|
||||
}
|
||||
|
||||
/// Snippet-side hook for test verification: report the engine's sample rate
|
||||
/// back through the session so tests can confirm the `context.engine`
|
||||
/// linkage compiled and called correctly.
|
||||
@@ -146,7 +181,7 @@ public final class SnippetContext {
|
||||
/// Snippet-side hook for test verification: record an arbitrary message
|
||||
/// back on the session. Lets tests confirm the snippet body executed.
|
||||
public func reportMessage(_ message: String) {
|
||||
session.lastSnippetMessage = message
|
||||
session.appendMessage(message)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -27,6 +27,7 @@ public enum SnippetHarness {
|
||||
/// `compileAndRun` is `@MainActor`).
|
||||
public static func wrap(userBody: String) -> WrappedSnippet {
|
||||
let preamble: String = """
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// SwiftFormatter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdLiveCompile — snippet source formatting.
|
||||
//
|
||||
// Shells out to the toolchain's `swift-format` (the same way `LiveCompiler`
|
||||
// shells to `swiftc`) to pretty-print a snippet. macOS only — iOS cannot exec
|
||||
// subprocesses. Writes the source to a temp file and runs `swift-format format
|
||||
// <file>`, capturing stdout — avoids the write-stdin/read-stdout pipe deadlock
|
||||
// a streaming approach risks on large output.
|
||||
|
||||
import Foundation
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Stateless `swift-format` wrapper.
|
||||
public enum SwiftFormatter {
|
||||
|
||||
/// Format `source` and return the pretty-printed result. Runs synchronously
|
||||
/// (spawns `swift-format`); call off the main thread.
|
||||
///
|
||||
/// - Parameter source: Swift source to format. Top-level snippet code is
|
||||
/// accepted — `swift-format` formats whatever parses.
|
||||
/// - Returns: The formatted source.
|
||||
/// - Throws: ``SwiftFormatterError`` for a missing tool, a non-zero exit
|
||||
/// (typically a parse error), or an I/O failure.
|
||||
public static func format(source: String) throws -> String {
|
||||
let tool: String = try findSwiftFormat()
|
||||
|
||||
let id: String = UUID().uuidString.replacingOccurrences(of: "-", with: "")
|
||||
let workDir: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LyrebirdSwiftFormat-\(id)", isDirectory: true)
|
||||
let sourcePath: String = workDir.appendingPathComponent("Snippet.swift").path
|
||||
do {
|
||||
try FileManager.default.createDirectory(at: workDir, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
// Register cleanup as soon as the dir exists, so a later write failure
|
||||
// doesn't leak it.
|
||||
defer { try? FileManager.default.removeItem(at: workDir) }
|
||||
do {
|
||||
try source.write(toFile: sourcePath, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("\(error)")
|
||||
}
|
||||
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: tool)
|
||||
process.arguments = ["format", sourcePath]
|
||||
let stdoutPipe: Pipe = Pipe()
|
||||
let stderrPipe: Pipe = Pipe()
|
||||
process.standardOutput = stdoutPipe
|
||||
process.standardError = stderrPipe
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
throw SwiftFormatterError.ioFailed("swift-format launch failed: \(error)")
|
||||
}
|
||||
// Drain stdout AND stderr concurrently before waiting. `swift-format` can
|
||||
// emit both a large formatted buffer and (on a broken snippet) a large
|
||||
// diagnostic stream; reading them sequentially would deadlock if the
|
||||
// stream we aren't reading yet fills its OS pipe buffer while the child
|
||||
// blocks writing to it.
|
||||
let outHandle: FileHandle = stdoutPipe.fileHandleForReading
|
||||
let errHandle: FileHandle = stderrPipe.fileHandleForReading
|
||||
let group: DispatchGroup = DispatchGroup()
|
||||
let drainQueue: DispatchQueue = DispatchQueue(
|
||||
label: "net.realizedsound.lyrebird.swift-format-drain",
|
||||
attributes: .concurrent
|
||||
)
|
||||
var outData: Data = Data()
|
||||
var errData: Data = Data()
|
||||
group.enter()
|
||||
drainQueue.async { outData = outHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.enter()
|
||||
drainQueue.async { errData = errHandle.readDataToEndOfFile(); group.leave() }
|
||||
group.wait()
|
||||
process.waitUntilExit()
|
||||
|
||||
guard process.terminationStatus == 0 else {
|
||||
let stderr: String = String(data: errData, encoding: .utf8) ?? ""
|
||||
throw SwiftFormatterError.formatFailed(exitCode: process.terminationStatus, stderr: stderr)
|
||||
}
|
||||
guard let formatted: String = String(data: outData, encoding: .utf8) else {
|
||||
throw SwiftFormatterError.ioFailed("swift-format produced non-UTF8 output")
|
||||
}
|
||||
return formatted
|
||||
}
|
||||
|
||||
/// Whether a `swift-format` executable is available on this machine.
|
||||
public static var isAvailable: Bool {
|
||||
(try? findSwiftFormat()) != nil
|
||||
}
|
||||
|
||||
// MARK: - Tool resolution
|
||||
|
||||
/// First-success search: `xcrun -f swift-format`, then hard-coded paths.
|
||||
static func findSwiftFormat() throws -> String {
|
||||
if let viaXcrun: String = swiftFormatViaXcrun() {
|
||||
return viaXcrun
|
||||
}
|
||||
let candidates: [String] = [
|
||||
"/usr/bin/swift-format",
|
||||
"/usr/local/bin/swift-format",
|
||||
"/opt/homebrew/bin/swift-format",
|
||||
]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw SwiftFormatterError.toolNotFound
|
||||
}
|
||||
|
||||
private static func swiftFormatViaXcrun() -> String? {
|
||||
let xcrunPath: String = "/usr/bin/xcrun"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcrunPath) else { return nil }
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcrunPath)
|
||||
process.arguments = ["-f", "swift-format"]
|
||||
let stdout: Pipe = Pipe()
|
||||
process.standardOutput = stdout
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
guard process.terminationStatus == 0 else { return nil }
|
||||
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,20 @@
|
||||
// SwiftFormatterError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Errors raised while formatting snippet source with `swift-format`.
|
||||
public enum SwiftFormatterError: Error {
|
||||
/// No `swift-format` executable could be located (no Xcode / toolchain, or
|
||||
/// an older toolchain that predates the bundled formatter).
|
||||
case toolNotFound
|
||||
/// `swift-format` exited non-zero — usually a parse error in the source.
|
||||
case formatFailed(exitCode: Int32, stderr: String)
|
||||
/// A filesystem or process I/O failure.
|
||||
case ioFailed(String)
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,26 @@
|
||||
// SwiftToolchainStatus.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// Result of probing for a usable Swift toolchain (the Swift scratchpad compiles
|
||||
/// snippets by shelling out to `swiftc`, which requires Xcode or the Command Line
|
||||
/// Tools). The Graph DSL mode does not need a toolchain, so a `.missing*` status is
|
||||
/// a soft condition — it gates only the Swift-compile path. Produced by ``ToolchainProbe``.
|
||||
public enum SwiftToolchainStatus: Equatable, Sendable {
|
||||
/// `swiftc` and the macOS SDK both resolve — the Swift scratchpad can compile.
|
||||
case available
|
||||
/// No developer tools at all (`xcode-select -p` fails and `swiftc` is unresolved).
|
||||
/// Fix: install the Command Line Tools (`xcode-select --install`) or Xcode.
|
||||
case missingDeveloperTools
|
||||
/// A developer directory is selected but `swiftc` could not be resolved.
|
||||
/// Fix: install/repair Xcode or the Command Line Tools.
|
||||
case missingSwiftc
|
||||
/// `swiftc` resolves but the macOS SDK does not — usually an incomplete Xcode.
|
||||
/// Fix: install a full Xcode.
|
||||
case missingSDK
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
// ToolchainProbe.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Foundation
|
||||
|
||||
/// Detects whether a usable Swift toolchain is present, so the app can warn the user
|
||||
/// (with install guidance) instead of only failing into the console on the first Run.
|
||||
///
|
||||
/// The resolvers are injectable so the `.missing*` branches can be unit-tested without
|
||||
/// actually uninstalling the toolchain; the defaults wrap the real `LiveCompiler`
|
||||
/// resolution (`xcrun -f swiftc`, `xcrun --show-sdk-path`) plus `xcode-select -p`.
|
||||
///
|
||||
/// **Not RT-related.** Runs `xcrun` / `xcode-select` subprocesses — call off the main
|
||||
/// thread (a couple of fast execs).
|
||||
public struct ToolchainProbe: Sendable {
|
||||
|
||||
private let swiftcResolver: @Sendable () -> String?
|
||||
private let sdkResolver: @Sendable () -> String?
|
||||
private let developerDirResolver: @Sendable () -> String?
|
||||
|
||||
/// - Parameters:
|
||||
/// - swiftcResolver: Returns the `swiftc` path, or `nil` when unresolved.
|
||||
/// - sdkResolver: Returns the macOS SDK path, or `nil` when unresolved.
|
||||
/// - developerDirResolver: Returns the active developer dir (`xcode-select -p`),
|
||||
/// or `nil` when no developer directory is configured.
|
||||
public init(
|
||||
swiftcResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSwiftcResolver,
|
||||
sdkResolver: @escaping @Sendable () -> String? = ToolchainProbe.defaultSDKResolver,
|
||||
developerDirResolver: @escaping @Sendable () -> String? = ToolchainProbe.developerDirViaXcodeSelect
|
||||
) {
|
||||
self.swiftcResolver = swiftcResolver
|
||||
self.sdkResolver = sdkResolver
|
||||
self.developerDirResolver = developerDirResolver
|
||||
}
|
||||
|
||||
/// Default `swiftc` resolver — wraps the internal `LiveCompiler.findSwiftc()` so the
|
||||
/// public `init` default argument does not reference internal API.
|
||||
public static func defaultSwiftcResolver() -> String? { try? LiveCompiler.findSwiftc() }
|
||||
|
||||
/// Default macOS SDK resolver — wraps the internal `LiveCompiler.sdkPathViaXcrun()`.
|
||||
public static func defaultSDKResolver() -> String? { LiveCompiler.sdkPathViaXcrun() }
|
||||
|
||||
/// Classify the current toolchain state.
|
||||
public func status() -> SwiftToolchainStatus {
|
||||
let swiftc: String? = swiftcResolver()
|
||||
let sdk: String? = sdkResolver()
|
||||
if swiftc != nil && sdk != nil { return .available }
|
||||
if swiftc == nil {
|
||||
// No swiftc: distinguish "no developer tools at all" from "tools present
|
||||
// but swiftc unresolved" by whether a developer dir is configured.
|
||||
return developerDirResolver() == nil ? .missingDeveloperTools : .missingSwiftc
|
||||
}
|
||||
// swiftc resolves but the SDK does not.
|
||||
return .missingSDK
|
||||
}
|
||||
|
||||
/// Active developer directory via `xcode-select -p`, or `nil` when unset / xcode-select
|
||||
/// is missing / returns non-zero.
|
||||
public static func developerDirViaXcodeSelect() -> String? {
|
||||
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else { return nil }
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||
process.arguments = ["-p"]
|
||||
let stdout: Pipe = Pipe()
|
||||
process.standardOutput = stdout
|
||||
process.standardError = FileHandle.nullDevice
|
||||
do {
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
} catch {
|
||||
return nil
|
||||
}
|
||||
guard process.terminationStatus == 0 else { return nil }
|
||||
let data: Data = stdout.fileHandleForReading.readDataToEndOfFile()
|
||||
guard let raw: String = String(data: data, encoding: .utf8) else { return nil }
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespacesAndNewlines)
|
||||
return trimmed.isEmpty ? nil : trimmed
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -19,6 +19,13 @@ The view is macOS-only — `LyrebirdLiveCompile` shells out to `swiftc`, which i
|
||||
unavailable on iOS. The nested `LiveCompile/` sub-package declares
|
||||
`platforms: [.macOS(.v15)]` and cannot be added to an iOS target.
|
||||
|
||||
> Note: **Swift mode needs a Swift toolchain** (Xcode or the Command Line Tools) —
|
||||
> it compiles snippets with `swiftc`. At launch the app probes for one
|
||||
> (`ToolchainProbe`) and, if none is found, shows an alert (once per launch) with
|
||||
> install guidance (Install Command Line Tools / Get Xcode). **Graph DSL mode needs no
|
||||
> toolchain** — it interprets generator-graph expressions in-process — so it's the
|
||||
> zero-install fallback.
|
||||
|
||||
## Hosting
|
||||
|
||||
```swift
|
||||
@@ -41,19 +48,43 @@ window.open {
|
||||
|
||||
| Shortcut | Action |
|
||||
|----------|--------|
|
||||
| ⌘↩ | Compile + run. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run additively. Keeps previously played synths in the engine. |
|
||||
| ⌘↩ | Compile + run the **whole buffer**. Removes the previous run's *anonymous* synths first (named slots persist). |
|
||||
| ⌘⇧↩ | Compile + run the whole buffer additively. Keeps previously played synths in the engine. |
|
||||
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
|
||||
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
|
||||
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
|
||||
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
|
||||
|
||||
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
|
||||
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
|
||||
anonymous tracked synths and every named slot.
|
||||
|
||||
**Run Selection (⌘E)** evaluates only the highlighted text and *adds* it to the
|
||||
running graph, without touching the rest of the buffer or the whole-buffer
|
||||
re-evaluation baseline (the buffer's clean/dirty status still reflects the last
|
||||
whole run). This is the live-coding "evaluate this line/region" gesture: audition
|
||||
a single voice or tweak, layer it in, keep going. It reads the editor selection
|
||||
via ``LyrebirdScratchModel/updateSelection(_:)`` and runs it through
|
||||
``LyrebirdScratchModel/runSelection()``; disabled when nothing is selected.
|
||||
|
||||
The engine status pill at the top-left is also a **Start/Stop** button
|
||||
(``LyrebirdScratchModel/toggleEngine()``): green "engine running" when live,
|
||||
red "▶ start engine" when stopped. A snippet is only audible while the engine
|
||||
is running; the host normally starts it at launch, but this lets the user
|
||||
recover from a failed start (e.g. no output device) without relaunching.
|
||||
|
||||
## Engine panel (scope + status)
|
||||
|
||||
The panel at the bottom of the window is a small always-on view of the running
|
||||
engine:
|
||||
|
||||
- A live dual-channel **oscilloscope** of the output (``ScratchScopeView``),
|
||||
fed by a ``ScopeCapture`` that ``LiveSession`` attaches to the first one or two
|
||||
output buses at init (it must be installed before `start()`). Pass
|
||||
`attachScope: false` to `LiveSession.init` to opt out.
|
||||
- **CPU average / peak** meter bars and the **synth / group / snippet** counts,
|
||||
so overrun and node growth are visible at a glance.
|
||||
|
||||
## Snippet API surface
|
||||
|
||||
A snippet has one local in scope:
|
||||
@@ -71,8 +102,152 @@ context: SnippetContext
|
||||
subclass needed (wraps it in a `ClosureSynthesizer`).
|
||||
- `context.play(slot:_:)` / `context.play(slot:) { <graph> }` — play into a
|
||||
**named slot** (see below).
|
||||
- `context.reportMessage(_:)` — write back to the host (used by tests; handy for
|
||||
`print`-style probes during development).
|
||||
- `context.reportMessage(_:)` — print a line to the **Console** panel (see
|
||||
below); the live-coding equivalent of `print`.
|
||||
|
||||
## Console
|
||||
|
||||
An always-open panel down the right side of the window is the log:
|
||||
|
||||
- **Report messages** — every `context.reportMessage(_:)` line (and host notices
|
||||
like a failed `engine.add` or a dropped slot swap).
|
||||
- **Errors** — compile and Graph DSL diagnostics, with their `line:col`, shown
|
||||
here rather than in a transient bottom strip so they stay visible while you
|
||||
fix them.
|
||||
- **Run notices** — a one-line result for each run.
|
||||
|
||||
Oldest first, auto-scrolled to the newest, capped at
|
||||
``LyrebirdScratchModel/maxConsoleEntries`` lines. **Clear** empties it; a
|
||||
**Reset Session** clears it too. The model exposes the log as
|
||||
``LyrebirdScratchModel/consoleEntries``.
|
||||
|
||||
## Functional snippets & scheduling
|
||||
|
||||
A Swift-mode snippet is **real Swift**, not just a graph expression — loops,
|
||||
`let` bindings, functions, arrays all work. The harness preamble imports
|
||||
**Foundation**, `LyrebirdSynth`, and `LyrebirdLiveCompile`, so `pow`, `sin`,
|
||||
`sqrt`, `Date`, and the whole generator library are in scope without any
|
||||
`import` — which is good, because a snippet **can't** declare one (its body is
|
||||
wrapped inside the entry function, and `import` is only legal at file scope). The
|
||||
one rule for anything time-based: **schedule** events, don't `Thread.sleep`. The snippet body runs
|
||||
once, synchronously, on the main thread; sleeping in a loop would freeze the UI
|
||||
(the audio thread is separate, but the editor isn't). Use
|
||||
`engine.schedule(_:after:)` for sample-accurate timing instead.
|
||||
|
||||
For example, a `for` loop that plays ten short sine tones a third of a second
|
||||
apart — a C-major run — each a decaying `Line` envelope times a sine that frees
|
||||
itself when done (`doneAction: .freeNode`), so the voices never pile up:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule \(i) failed: \(error)") }
|
||||
}
|
||||
context.reportMessage("scheduled 10 tones")
|
||||
```
|
||||
|
||||
The loop returns immediately after scheduling all ten adds; the engine fires
|
||||
each at its time (`0, 0.35, 0.70 … s`). A 0.2 s tone with 0.35 s spacing leaves a
|
||||
short gap between each. This is *fire-and-forget* scheduling for a fixed sequence.
|
||||
|
||||
### The one rule: retention
|
||||
|
||||
The snippet body runs **once, synchronously, then returns**. Anything that fires
|
||||
*later* must be held by something that outlives the snippet — the snippet itself
|
||||
is transient. Three things self-sustain, and everything below builds on them:
|
||||
|
||||
- **`engine.schedule(…)`** — the engine holds the pending event.
|
||||
- **`LyrebirdRoutine` / `LyrebirdTask`** — the routine runs on a dedicated
|
||||
background thread that retains it until the body finishes or `stop()` is called.
|
||||
- **`context.play(…)` synths** — the session tracks them (and named slots).
|
||||
|
||||
A `Thread.sleep` or busy `while` loop in the snippet *body* is the anti-pattern:
|
||||
it runs on the **main thread**, so it freezes the editor UI (the RT audio thread
|
||||
keeps going, but you can't type). Anything that *waits* belongs on a routine's
|
||||
background thread, not in the body.
|
||||
|
||||
### Mechanisms
|
||||
|
||||
| Mechanism | Use for | Timing API |
|
||||
|---|---|---|
|
||||
| `context.engine.schedule(_:after:)` / `schedule(_:at:)` | One-shot "play this at time T" | Seconds, or a `SampleTime` |
|
||||
| `LyrebirdRoutine` | A sequence with pauses; open-ended loops | `ctx.wait(seconds:)` / `wait(beats:)` / `waitUntil(sampleTime:)` |
|
||||
| `LyrebirdTask` | Same as a routine but **pausable** (`pause()` / `resume()`) | same as routine |
|
||||
| `LyrebirdClock` | Beat → sample-time reference | `clock.sampleTime(beat:)`, `nextBeat(after:)` → feed `schedule(_:at:)` or `ctx.waitUntil(sampleTime:)` |
|
||||
| Trigger generators (`Impulse` → `Demand` / `TriggeredRandom` / gate) | Timing *inside* the audio graph — arps, gated LFOs, step patterns | Sample-accurate, in the running synth |
|
||||
| `LyrebirdProcess` / `LyrebirdEventList`, `Score` / `ScorePlayer` | Structured / pre-composed timelines | Event lists |
|
||||
|
||||
All of these are reachable from a snippet through `context.engine` and the public
|
||||
`LyrebirdSynth` types — nothing extra is injected.
|
||||
|
||||
### Waiting: `LyrebirdRoutine`
|
||||
|
||||
For "play N things with a pause between each" — the reactive counterpart to the
|
||||
fire-and-forget loop above — use a routine. Its body runs on a background thread
|
||||
(so `wait` never freezes the UI), and `routine.start(engine:)` keeps it alive
|
||||
after the snippet returns:
|
||||
|
||||
```swift
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0]
|
||||
let routine = LyrebirdRoutine { ctx in
|
||||
for freq in scale {
|
||||
ctx.add(ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
})
|
||||
try ctx.wait(seconds: 0.3) // background-thread wait — UI stays live
|
||||
}
|
||||
}
|
||||
routine.start(engine: context.engine) // self-sustaining; survives the snippet
|
||||
```
|
||||
|
||||
`ctx.add(_:)` hops to the main-actor `engine.add` for you. `ctx.wait(beats:)`
|
||||
waits at `ctx.tempo` (default 120 BPM; set `ctx.tempo = …` in the body to change
|
||||
it); `ctx.waitUntil(sampleTime:)` waits to an absolute engine time, which is where
|
||||
`LyrebirdClock.sampleTime(beat:)` comes in for on-grid spacing. Call
|
||||
`routine.stop()` (e.g. from a later ⌘E) to cancel — the body exits at its next
|
||||
`wait`.
|
||||
|
||||
### Caveats
|
||||
|
||||
- **Never block the main thread** — no `Thread.sleep` / busy loops in the snippet
|
||||
body. Wait on a routine instead.
|
||||
- `Task { }` / `DispatchQueue.main.asyncAfter` *technically* work (they fire later
|
||||
on main and the session keeps `context` alive), but prefer `engine.schedule`
|
||||
(sample-accurate) or a routine (proper timed waits) over ad-hoc dispatch.
|
||||
- A `LyrebirdClock` used only to compute schedule times is fine to let go; if
|
||||
you need it *driving* something over time, a routine's thread keeps it alive.
|
||||
|
||||
### NRT: sample-clock timing only
|
||||
|
||||
**Render to File (⌥⌘R) is offline.** The `NRTDriver` renders faster than real
|
||||
time in a tight **synchronous burst** — 10 s of audio in a fraction of a second —
|
||||
and it does **not** wait for anything on the wall clock. So only timing expressed
|
||||
in **engine / sample time** survives a render; wall-clock timing silently drops out.
|
||||
|
||||
| Mechanism | Live | Render to File |
|
||||
|---|---|---|
|
||||
| `engine.schedule(_:after:/at:)` | ✅ | ✅ — fires at its sample time as blocks render |
|
||||
| In-graph triggers (`Impulse` → `Demand` / gates) | ✅ | ✅ — per-sample, driven by the render itself (best for NRT) |
|
||||
| `LyrebirdClock.sampleTime(beat:)` → `schedule(_:at:)` | ✅ | ✅ — pure beat→sample math |
|
||||
| `LyrebirdRoutine` / `LyrebirdTask` (`wait(seconds:/beats:)`) | ✅ | ❌ — **wall-clock sleeps on a background thread; the render finishes before they fire, so their `ctx.add`s never make the file** |
|
||||
| Real-time playback (`playTimeline`, live `ScorePlayer`) | ✅ | ❌ — the sample-accurate scheduling underneath is fine; the wall-clock playback driver isn't |
|
||||
|
||||
Rule of thumb: if the timing is a routine's `wait`, it's for **live** play; to make
|
||||
the same idea render, re-express it as `engine.schedule(_:after:)` (fixed
|
||||
sequence) or an `Impulse`-driven graph (periodic / patterned). This is a real
|
||||
footgun — routine timing works when you play it and silently produces an empty or
|
||||
truncated bounce when you render it.
|
||||
|
||||
> Note: **Graph DSL mode** evaluates only generator-graph expressions — no loops
|
||||
> or scheduling. Functional code like the above needs **Swift mode**.
|
||||
|
||||
## Named slots (hot-swap)
|
||||
|
||||
@@ -95,11 +270,35 @@ voice at a time while the rest of the patch keeps going (the `Pdef` idiom).
|
||||
| `context.play(_:)` / `context.play { }` | Removed on the next non-additive run. |
|
||||
| `context.play(slot:) { }` | Persists; a same-name re-run replaces it in place. |
|
||||
|
||||
Clear a slot with `context.session.clearSlot("bass")`, all slots with
|
||||
`context.session.clearSlots()`. The toolbar **Clear Synths** button is a full
|
||||
reset — anonymous synths *and* every slot. A slot definition you delete from the
|
||||
buffer and stop re-running is *not* auto-removed (a `Pdef`-style gotcha) — clear
|
||||
it explicitly or hit Clear Synths.
|
||||
### Start a voice, release it later
|
||||
|
||||
The slot **name is the handle** — the persistent reference you keep across
|
||||
evaluations. (Swift `let`/`var` bindings do not carry from one snippet to the
|
||||
next: each ⌘↩ / ⌘E is a separately-compiled unit, so a variable declared in one
|
||||
run is invisible to the next.) So the "start something, let go of it later"
|
||||
gesture is: name a slot in one evaluation, then release it by name from another —
|
||||
a natural pairing with **Run Selection** (⌘E):
|
||||
|
||||
```swift
|
||||
// Select this line, ⌘E — starts a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* … release-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, select this line, ⌘E — graceful release: the envelope tails out,
|
||||
// then the voice frees itself:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
drops the handle; the voice must free itself (an `EnvGen`/gate with a
|
||||
free-on-done action) to leave the engine.
|
||||
- `context.free(slot:)` is the **immediate** hard stop (no tail) — the
|
||||
counterpart to `release`.
|
||||
|
||||
Clear a slot with `context.free(slot: "bass")` (or `context.session.clearSlot`),
|
||||
all slots with `context.session.clearSlots()`. The toolbar **Clear Synths**
|
||||
button is a full reset — anonymous synths *and* every slot. A slot definition you
|
||||
delete from the buffer and stop re-running is *not* auto-removed (a `Pdef`-style
|
||||
gotcha) — release/free it explicitly or hit Clear Synths.
|
||||
|
||||
## Threading
|
||||
|
||||
@@ -190,15 +389,48 @@ through its own diagnostics.
|
||||
> which turns a benign ObjC class-duplication warning into a hard cast crash when
|
||||
> a snippet is `dlopen`'d.
|
||||
|
||||
## Compile artifacts & Application Support
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts: the
|
||||
swiftmodules, the Lyrebird dylibs, and the C-shim (`LyrebirdC`) Clang module map.
|
||||
In a dev checkout those live in the SPM build dir under `~/Documents`, so a
|
||||
non-sandboxed host — and the `swiftc` subprocess it spawns — trips the macOS
|
||||
"wants to access your Documents folder" permission gate. (The scratch/compile
|
||||
temp dirs use `/var/folders/…` and are never the cause.)
|
||||
|
||||
``LiveSession/stageArtifacts(from:to:)`` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` — an ungated
|
||||
location — and **rewrites the C module map's absolute umbrella-header path** to a
|
||||
staged copy of the header, so the staged directory is a fully self-contained
|
||||
compile root. ``LiveSession/defaultImportPaths()`` / `defaultLibrarySearchPaths()`
|
||||
/ `defaultRpaths()` then prefer the staged dir when it is populated. Staging is
|
||||
idempotent (a receipt file skips an unchanged source) and best-effort (falls back
|
||||
to the build dir on any failure). A host calls it once before constructing the
|
||||
session:
|
||||
|
||||
```swift
|
||||
LiveSession.stageArtifacts() // stage into App Support
|
||||
let session = LiveSession(engine: engine) // defaults resolve to the staged dir
|
||||
```
|
||||
|
||||
For a **standalone** app, ship the artifacts inside the bundle at
|
||||
`Contents/Resources/LyrebirdArtifacts` (name = ``LiveSession/bundledArtifactsDirName``);
|
||||
``LiveSession/artifactSourceDir()`` prefers that over the build dir, so a shipped
|
||||
`LyrebirdScratch.app` in `/Applications` stages without ever reading a
|
||||
permission-gated folder. In a dev checkout the one-time stage copy still reads
|
||||
the build dir under `~/Documents`; every later launch reuses the staged copy.
|
||||
|
||||
## Code completion
|
||||
|
||||
Swift code completion is provided by the toolchain's `sourcekit-lsp`, driven over
|
||||
stdio by ``SourceKitLSPClient`` and bridged to the editor by
|
||||
``SnippetCompletionService``. Typing `.` after an expression pops the standard
|
||||
completion window; the candidates are the real symbols the snippet would see at
|
||||
compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`, …),
|
||||
the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||
standard library.
|
||||
``SnippetCompletionService``. Press **Esc** (or **F5** — the standard macOS
|
||||
completion keys) to complete at the caret; the candidates are the real symbols the snippet would
|
||||
see at compile time — `LyrebirdSynth` generators (`OscSin.` → `Audio`, `Control`,
|
||||
…), the injected `context` (`context.` → `play`, `engine`, …), and the Swift
|
||||
standard library. Completion is **manual, never auto-triggered on `.`** — an
|
||||
unrequested popup ambushes typing and the built-in completion window is awkward
|
||||
to dismiss mid-edit.
|
||||
|
||||
How it resolves those symbols for an otherwise free-standing file: the service
|
||||
maintains a small temp workspace holding the snippet **wrapped** in the same
|
||||
@@ -216,8 +448,8 @@ candidates rather than an error.
|
||||
- Syntax highlighting is a lightweight built-in lexer (`ScratchSwiftTokenizer`) —
|
||||
approximate by design, not a full parser. Completion (above) uses the real
|
||||
compiler via sourcekit-lsp; the two are independent.
|
||||
- Completion currently triggers on `.`; a manual-invoke shortcut is a possible
|
||||
follow-up.
|
||||
- Completion is invoked manually with **Esc** (or **F5**); there is no
|
||||
auto-trigger on `.`.
|
||||
- The host `.app` must not be sandboxed and must allow library validation to be
|
||||
disabled, since `swiftc` is invoked via `Process` and the resulting unsigned
|
||||
dylib is `dlopen`'d.
|
||||
@@ -251,6 +483,17 @@ orange and a warning banner appears — nudging the user to restart to reclaim t
|
||||
memory, or to switch to Graph DSL mode (which maps no dylibs). It is a nudge, not
|
||||
a hard stop: the choice stays with the user.
|
||||
|
||||
Two Run-menu commands act on this:
|
||||
|
||||
- **Reset Session** (``LyrebirdScratchModel/resetSession()``) — an *in-process*
|
||||
reset: stops all snippet audio, shuts down the code-completion server (freeing
|
||||
its subprocess and temp workspace), and clears diagnostics and the run
|
||||
baseline. **Non-destructive** — your buffer is left untouched, so it needs no
|
||||
confirmation. It does **not** unload the mapped snippet dylibs.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (after a confirmation,
|
||||
since unsaved buffer edits are lost), the only way to actually free the mapped
|
||||
dylibs. The fresh process starts at zero.
|
||||
|
||||
## Graph DSL mode (instant, no compile)
|
||||
|
||||
The status-bar toggle switches the editor between two evaluators:
|
||||
|
||||
@@ -28,7 +28,7 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
|
||||
/// Construct the full menu bar (App / File / Edit / Run / View / Window /
|
||||
/// Help) and assign it to `NSApplication.shared.mainMenu`.
|
||||
public func installMainMenu(appName: String = "LyrebirdScratchDemo") {
|
||||
public func installMainMenu(appName: String = "LyrebirdScratch") {
|
||||
let mainMenu: NSMenu = NSMenu()
|
||||
|
||||
mainMenu.addItem(appMenuItem(appName: appName))
|
||||
@@ -39,6 +39,11 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
mainMenu.addItem(windowMenuItem())
|
||||
|
||||
NSApplication.shared.mainMenu = mainMenu
|
||||
|
||||
// Launch check: if the Swift toolchain is missing, warn with install guidance
|
||||
// (the Swift scratchpad needs swiftc). Fires once per launch — the probe runs
|
||||
// off-main and the alert (if any) is dispatched back to the main thread.
|
||||
warnIfSwiftToolchainMissing()
|
||||
}
|
||||
|
||||
// MARK: App menu
|
||||
@@ -135,6 +140,12 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "f")
|
||||
find.tag = Int(NSFindPanelAction.showFindPanel.rawValue)
|
||||
menu.addItem(find)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let format: NSMenuItem = target(NSMenuItem(title: "Format Code",
|
||||
action: #selector(formatCode(_:)),
|
||||
keyEquivalent: "f"))
|
||||
format.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(format)
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -152,10 +163,26 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
keyEquivalent: "\r")
|
||||
runAdd.keyEquivalentModifierMask = [.command, .shift]
|
||||
menu.addItem(target(runAdd))
|
||||
menu.addItem(target(NSMenuItem(title: "Run Selection",
|
||||
action: #selector(runSelection(_:)),
|
||||
keyEquivalent: "e")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
let render: NSMenuItem = target(NSMenuItem(title: "Render to File…",
|
||||
action: #selector(renderToFile(_:)),
|
||||
keyEquivalent: "r"))
|
||||
render.keyEquivalentModifierMask = [.command, .option]
|
||||
menu.addItem(render)
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Clear Tracked Synths",
|
||||
action: #selector(clearSynths(_:)),
|
||||
keyEquivalent: "k")))
|
||||
menu.addItem(NSMenuItem.separator())
|
||||
menu.addItem(target(NSMenuItem(title: "Reset Session",
|
||||
action: #selector(resetSession(_:)),
|
||||
keyEquivalent: "")))
|
||||
menu.addItem(target(NSMenuItem(title: "Restart to Reclaim Memory…",
|
||||
action: #selector(restartApp(_:)),
|
||||
keyEquivalent: "")))
|
||||
item.submenu = menu
|
||||
return item
|
||||
}
|
||||
@@ -215,6 +242,18 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
switch menuItem.action {
|
||||
case #selector(runSnippet(_:)), #selector(runSnippetAdditive(_:)):
|
||||
return model.reevalState.canEvaluate
|
||||
case #selector(runSelection(_:)):
|
||||
// Needs a selection to run and an evaluator that isn't mid-compile.
|
||||
return model.hasSelection && model.reevalState.canEvaluate
|
||||
case #selector(resetSession(_:)):
|
||||
// Don't tear the session down mid-compile.
|
||||
return !model.isCompiling
|
||||
case #selector(formatCode(_:)):
|
||||
// Not mid-compile; the model's formatter no-ops on a blank buffer.
|
||||
return !model.isCompiling
|
||||
case #selector(renderToFile(_:)):
|
||||
// Needs an evaluatable buffer and no compile/render in flight.
|
||||
return model.reevalState.canEvaluate
|
||||
default:
|
||||
return true
|
||||
}
|
||||
@@ -280,6 +319,90 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
|
||||
Task { @MainActor in _ = await model.run(additive: true) }
|
||||
}
|
||||
|
||||
@objc private func runSelection(_ sender: Any?) {
|
||||
Task { @MainActor in _ = await model.runSelection() }
|
||||
}
|
||||
|
||||
@objc private func formatCode(_ sender: Any?) {
|
||||
Task { @MainActor in await model.formatBuffer() }
|
||||
}
|
||||
|
||||
@objc private func renderToFile(_ sender: Any?) {
|
||||
// Single save dialog: an accessory view carries the format popup + duration,
|
||||
// and keeps the filename extension in sync with the chosen container.
|
||||
let defaultRenderDuration: Double = 5.0
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
panel.message = "Render the snippet (or selection) to an audio file"
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: defaultRenderDuration, savePanel: panel
|
||||
)
|
||||
panel.accessoryView = accessory
|
||||
|
||||
guard panel.runModal() == .OK, let chosenURL: URL = panel.url else { return }
|
||||
|
||||
guard let duration: Double = accessory.durationSeconds else {
|
||||
let invalid: NSAlert = NSAlert()
|
||||
invalid.messageText = "Invalid duration"
|
||||
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
|
||||
invalid.runModal()
|
||||
return
|
||||
}
|
||||
|
||||
let format: AudioFileFormat = accessory.selectedFormat
|
||||
// This is the source of truth for the final extension: force it to match the
|
||||
// chosen format so a hand-typed name with the wrong (or no) extension still
|
||||
// produces a correctly-named file. (The accessory's own panel-name sync is a
|
||||
// live-preview convenience; enforcement happens here.)
|
||||
let url: URL = chosenURL.deletingPathExtension().appendingPathExtension(format.fileExtension)
|
||||
|
||||
Task { @MainActor in
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: duration)
|
||||
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func resetSession(_ sender: Any?) {
|
||||
model.resetSession()
|
||||
}
|
||||
|
||||
@objc private func restartApp(_ sender: Any?) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart to reclaim memory?"
|
||||
alert.informativeText =
|
||||
"Relaunches the app to free the \(model.loadedSnippetCount) mapped snippet "
|
||||
+ "dylibs (compiled snippets can't be unloaded any other way). Unsaved changes "
|
||||
+ "in the buffer will be lost."
|
||||
alert.addButton(withTitle: "Restart")
|
||||
alert.addButton(withTitle: "Cancel")
|
||||
guard alert.runModal() == .alertFirstButtonReturn else { return }
|
||||
LyrebirdScratchMenuController.relaunchApp()
|
||||
}
|
||||
|
||||
/// Relaunch the host `.app`: open a fresh instance, then terminate this one
|
||||
/// once it is confirmed on its way. The new process starts with zero mapped
|
||||
/// snippet dylibs — the only way to reclaim that memory. On a launch failure
|
||||
/// the current process is **kept** (and the user informed) rather than
|
||||
/// terminated into oblivion.
|
||||
private static func relaunchApp() {
|
||||
let url: URL = Bundle.main.bundleURL
|
||||
let config: NSWorkspace.OpenConfiguration = NSWorkspace.OpenConfiguration()
|
||||
config.createsNewApplicationInstance = true
|
||||
NSWorkspace.shared.openApplication(at: url, configuration: config) { app, error in
|
||||
DispatchQueue.main.async {
|
||||
if let error: Error = error {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = "Restart failed"
|
||||
alert.informativeText =
|
||||
"Could not relaunch the app (\(error.localizedDescription)). "
|
||||
+ "The current session is unchanged."
|
||||
alert.runModal()
|
||||
} else if app != nil {
|
||||
NSApp.terminate(nil)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@objc private func clearSynths(_ sender: Any?) {
|
||||
model.clearTracked()
|
||||
}
|
||||
|
||||
@@ -17,7 +17,7 @@ import Foundation
|
||||
import CoreGraphics
|
||||
import LyrebirdSynth
|
||||
// Re-exported so consumers that link only the `LyrebirdLiveCompileUI` product
|
||||
// (e.g. the LyrebirdScratchDemo app) get the `LyrebirdLiveCompile` API
|
||||
// (e.g. the LyrebirdScratch app) get the `LyrebirdLiveCompile` API
|
||||
// (`LiveSession`, …) without separately linking the `LyrebirdLiveCompile`
|
||||
// dynamic product — which clashes in Xcode with the static target embed.
|
||||
@_exported import LyrebirdLiveCompile
|
||||
@@ -99,6 +99,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// Updated by `run(additive:)` and `clearTracked()`.
|
||||
@Published public private(set) var statusMessage: String = ""
|
||||
|
||||
/// Accumulated console log shown in the always-open right panel: snippet
|
||||
/// `context.reportMessage(_:)` output, compile/DSL errors, and run notices,
|
||||
/// oldest first. Capped at ``maxConsoleEntries``.
|
||||
@Published public private(set) var consoleEntries: [ScratchConsoleEntry] = []
|
||||
|
||||
/// Upper bound on retained console lines; the oldest are dropped past it.
|
||||
public nonisolated static let maxConsoleEntries: Int = 500
|
||||
|
||||
private var _consoleSeq: Int = 0
|
||||
|
||||
/// Append one console line, trimming the log to ``maxConsoleEntries``.
|
||||
private func appendConsole(_ kind: ScratchConsoleEntry.Kind, _ text: String, location: String? = nil) {
|
||||
_consoleSeq += 1
|
||||
consoleEntries.append(ScratchConsoleEntry(id: _consoleSeq, kind: kind, text: text, location: location))
|
||||
let overflow: Int = consoleEntries.count - LyrebirdScratchModel.maxConsoleEntries
|
||||
if overflow > 0 { consoleEntries.removeFirst(overflow) }
|
||||
}
|
||||
|
||||
/// Empty the console.
|
||||
public func clearConsole() {
|
||||
consoleEntries.removeAll()
|
||||
}
|
||||
|
||||
/// After a run resolves, move the snippet's report messages into the console
|
||||
/// (they arrive in order during the run), then the run outcome: on failure,
|
||||
/// each diagnostic as an error line; on success, a one-line notice.
|
||||
private func recordRunConsole(succeeded: Bool) {
|
||||
for message: String in session.drainMessages() {
|
||||
appendConsole(.message, message)
|
||||
}
|
||||
if succeeded {
|
||||
appendConsole(.info, statusMessage)
|
||||
} else if diagnostics.isEmpty {
|
||||
appendConsole(.error, statusMessage)
|
||||
} else {
|
||||
for diagnostic: Diagnostic in diagnostics {
|
||||
let location: String? = diagnostic.line.map { "\($0):\(diagnostic.column)" }
|
||||
appendConsole(.error, diagnostic.message, location: location)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Mirror of `session.trackedSynthCount`, refreshed after every `run` /
|
||||
/// `clearTracked` call so the toolbar can show the count without polling.
|
||||
@Published public private(set) var trackedSynthCount: Int
|
||||
@@ -151,6 +193,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// horizontally.
|
||||
@Published public var wrapsLines: Bool = true
|
||||
|
||||
/// The current editor selection text (empty when nothing is selected).
|
||||
/// Pushed by the editor on selection change; drives ``hasSelection`` and
|
||||
/// ``runSelection()``.
|
||||
@Published public private(set) var selectionText: String = ""
|
||||
|
||||
/// `true` when the editor has a non-whitespace selection available to run.
|
||||
public var hasSelection: Bool {
|
||||
!selectionText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
|
||||
}
|
||||
|
||||
/// Record the editor's current selection. Called by the editor's
|
||||
/// selection-change delegate; empty string clears it.
|
||||
public func updateSelection(_ text: String) {
|
||||
guard text != selectionText else { return } // avoid redundant republish
|
||||
selectionText = text
|
||||
}
|
||||
|
||||
/// Which evaluator ``run(additive:)`` sends the buffer through. `.swift`
|
||||
/// compiles a snippet dylib; `.graphDSL` interprets a generator graph
|
||||
/// instantly. Toggle via ``switchMode(to:)`` so the seed placeholder swaps
|
||||
@@ -229,7 +288,11 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
/// resolves (edits made mid-compile are re-evaluated once it finishes).
|
||||
private func recomputeReevalStateAfterEdit() {
|
||||
guard !isCompiling else { return }
|
||||
reevalState = derivedIdleState()
|
||||
// Assign only on a real change: after the first edit dirties the buffer,
|
||||
// every later keystroke re-derives `.dirty` — republishing an unchanged
|
||||
// value would re-render the whole view for nothing.
|
||||
let next: ReevalState = derivedIdleState()
|
||||
if next != reevalState { reevalState = next }
|
||||
}
|
||||
|
||||
/// Settle a `.queued` state once its scheduled swap has become audible.
|
||||
@@ -268,29 +331,48 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
@discardableResult
|
||||
public func run(additive: Bool) async -> Bool {
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(additive: additive)
|
||||
case .graphDSL: return runGraphDSLBuffer(additive: additive)
|
||||
case .swift: return await runSwiftSnippet(body: text, additive: additive, recordBaseline: true)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: text, additive: additive, recordBaseline: true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile the buffer to a dylib off-main and run it.
|
||||
private func runSwiftSnippet(additive: Bool) async -> Bool {
|
||||
/// Evaluate just the current editor selection as an **additive** run: the
|
||||
/// selected text is compiled/interpreted and added to whatever is already
|
||||
/// playing (never a non-additive replace), and it does not disturb the
|
||||
/// whole-buffer re-evaluation baseline — the buffer's `.clean`/`.dirty`
|
||||
/// status still reflects the last *whole* run. No-op when nothing is
|
||||
/// selected. Works in both Swift and Graph DSL modes.
|
||||
@discardableResult
|
||||
public func runSelection() async -> Bool {
|
||||
guard hasSelection else { return false }
|
||||
let body: String = selectionText
|
||||
switch evalMode {
|
||||
case .swift: return await runSwiftSnippet(body: body, additive: true, recordBaseline: false)
|
||||
case .graphDSL: return runGraphDSLBuffer(body: body, additive: true, recordBaseline: false)
|
||||
}
|
||||
}
|
||||
|
||||
/// Swift path: compile `body` to a dylib off-main and run it.
|
||||
/// `recordBaseline` distinguishes a whole-buffer run (updates the `.clean`
|
||||
/// baseline) from a selection run (leaves it untouched).
|
||||
private func runSwiftSnippet(body: String, additive: Bool, recordBaseline: Bool) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
statusMessage = "Compiling…"
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
isCompiling = false
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try await session.compileAndRunAsync(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
switch sessionError {
|
||||
@@ -303,7 +385,7 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
message: "\(underlying)",
|
||||
rawLine: 0
|
||||
)]
|
||||
statusMessage = "Compile failed — see diagnostics below."
|
||||
statusMessage = "Compile failed — see console."
|
||||
} else {
|
||||
diagnostics = diags
|
||||
let plural: String = diags.count == 1 ? "" : "s"
|
||||
@@ -316,31 +398,32 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
diagnostics = diags
|
||||
statusMessage = "DSL error — \(diags.count) diagnostic(s)."
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Graph-DSL path: interpret the buffer in-process — instant, no swiftc, so
|
||||
/// no `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// Graph-DSL path: interpret `body` in-process — instant, no swiftc, so no
|
||||
/// `isCompiling` spinner and no `await`. A parse/build failure leaves the
|
||||
/// currently-playing graph untouched (the session builds before it mutates).
|
||||
private func runGraphDSLBuffer(additive: Bool) -> Bool {
|
||||
private func runGraphDSLBuffer(body: String, additive: Bool, recordBaseline: Bool) -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
let body: String = text
|
||||
diagnostics = []
|
||||
var runSucceeded: Bool = false
|
||||
defer {
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
recordRunConsole(succeeded: runSucceeded)
|
||||
}
|
||||
do {
|
||||
try session.runGraphDSL(body, additive: additive)
|
||||
let mode: String = additive ? "additive" : "replaced"
|
||||
statusMessage = "Ran DSL (\(mode)). Tracked synths: \(session.trackedSynthCount)."
|
||||
settleReevalAfterSuccess(body: body)
|
||||
statusMessage = "Ran DSL \(runDescription(additive: additive, recordBaseline: recordBaseline))."
|
||||
settleReeval(body: body, recordBaseline: recordBaseline)
|
||||
runSucceeded = true
|
||||
return true
|
||||
} catch let sessionError as LiveSessionError {
|
||||
if case .graphDSLFailed(let diags, _) = sessionError {
|
||||
@@ -350,21 +433,23 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
} else {
|
||||
statusMessage = "Error: \(sessionError)"
|
||||
}
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
} catch {
|
||||
statusMessage = "Error: \(error)"
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
settleReevalAfterFailure(recordBaseline: recordBaseline)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Record the just-run text as the baseline and settle the readiness state:
|
||||
/// `.queued` when the buffer is unchanged and a quantized slot swap is
|
||||
/// scheduled but not yet audible, otherwise the derived idle state (`.clean`,
|
||||
/// or `.dirty` if the buffer was edited while the run was in flight).
|
||||
private func settleReevalAfterSuccess(body: String) {
|
||||
lastEvaluatedText = body
|
||||
/// Settle the readiness state after a successful run. For a whole-buffer run
|
||||
/// (`recordBaseline`), record the run text as the `.clean` baseline; for a
|
||||
/// selection run, leave the baseline untouched (the buffer's status still
|
||||
/// reflects the last whole run). Either way resolve to `.queued` when the
|
||||
/// buffer is unchanged and a quantized swap is pending, else the derived
|
||||
/// idle state.
|
||||
private func settleReeval(body: String, recordBaseline: Bool) {
|
||||
if recordBaseline { lastEvaluatedText = body }
|
||||
let idle: ReevalState = derivedIdleState()
|
||||
if idle == .clean, let beat: Double = session.pendingSwapBeat {
|
||||
reevalState = .queued(untilBeat: beat)
|
||||
@@ -373,6 +458,33 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
}
|
||||
}
|
||||
|
||||
/// Settle the readiness state after a *failed* run. A whole-buffer failure
|
||||
/// sets `.failed` (the badge should reflect that the buffer doesn't run). A
|
||||
/// selection failure must NOT touch the whole-buffer badge — the buffer and
|
||||
/// its last whole-run baseline are unaffected — so it recomputes the derived
|
||||
/// idle state and marks the status line as a selection failure. Diagnostics
|
||||
/// (already set by the caller) still surface the error either way.
|
||||
private func settleReevalAfterFailure(recordBaseline: Bool) {
|
||||
if recordBaseline {
|
||||
reevalState = .failed(diagnosticCount: diagnostics.count)
|
||||
} else {
|
||||
statusMessage = "Selection — " + statusMessage
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
}
|
||||
|
||||
/// Status-line phrase for a run: distinguishes a whole-buffer replace/add
|
||||
/// from a selection add, and includes the live tracked-synth count.
|
||||
private func runDescription(additive: Bool, recordBaseline: Bool) -> String {
|
||||
let what: String
|
||||
if !recordBaseline {
|
||||
what = "selection (added)"
|
||||
} else {
|
||||
what = additive ? "additive" : "replaced"
|
||||
}
|
||||
return "(\(what)). Tracked synths: \(session.trackedSynthCount)"
|
||||
}
|
||||
|
||||
/// Switch evaluation mode. When the buffer still holds the *current* mode's
|
||||
/// untouched placeholder, swap in the target mode's placeholder so the seed
|
||||
/// example matches the mode; any edited buffer is left as-is.
|
||||
@@ -392,6 +504,141 @@ public final class LyrebirdScratchModel: ObservableObject {
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
/// In-process session reset: stop all snippet audio, shut down the code-
|
||||
/// completion server (freeing its subprocess + temp workspace), and clear
|
||||
/// diagnostics and the run baseline. **Non-destructive** — the editor buffer
|
||||
/// (the user's code) is left untouched, so this needs no confirmation.
|
||||
///
|
||||
/// It reclaims everything it *can* in-process — but **not** the compiled
|
||||
/// snippet dylibs (`loadedSnippetCount`), which cannot be unloaded safely
|
||||
/// (`dlclose` is unsafe for Swift dylibs). Only relaunching the process frees
|
||||
/// those; the status line says so, and the "Restart" command does it.
|
||||
///
|
||||
/// No-op while a compile is in flight (matching the run methods' guard) — a
|
||||
/// reset must not tear the session down under an active `compileAndRunAsync`.
|
||||
/// Pretty-print the buffer with `swift-format` (off the main thread),
|
||||
/// replacing the text on success. Logs the outcome to the console; on a
|
||||
/// parse error or missing toolchain the buffer is left untouched.
|
||||
public func formatBuffer() async {
|
||||
guard !isCompiling else { return }
|
||||
let source: String = text
|
||||
guard !LyrebirdScratchModel.isBlank(source) else { return }
|
||||
// Hold the busy flag across the subprocess round-trip so a second Format
|
||||
// (or a Run) can't overlap, and re-check the buffer before applying: the
|
||||
// user may keep typing while `swift-format` runs, and a result computed
|
||||
// from the now-stale `source` must not clobber those edits. `reevalState`
|
||||
// goes `.compiling` too so the Run/Render menu items (validated on
|
||||
// `reevalState.canEvaluate`) actually disable during the format.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
do {
|
||||
let formatted: String = try await Task.detached(priority: .userInitiated) {
|
||||
try SwiftFormatter.format(source: source)
|
||||
}.value
|
||||
guard text == source else {
|
||||
appendConsole(.error, "Buffer changed during formatting — result discarded.")
|
||||
return
|
||||
}
|
||||
if formatted != source {
|
||||
text = formatted
|
||||
}
|
||||
appendConsole(.info, "Formatted.")
|
||||
} catch {
|
||||
appendConsole(.error, "Format failed: \(error)")
|
||||
}
|
||||
}
|
||||
|
||||
/// Render the current selection (or the whole buffer when nothing is
|
||||
/// selected) to an audio file, offline. Builds the snippet graph on a
|
||||
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
|
||||
/// sample rate / channel count / bus layout — then renders `duration`
|
||||
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
|
||||
/// outcome to the console.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - url: Destination file. Its extension should match `format`.
|
||||
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
|
||||
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
|
||||
/// - duration: Render length in seconds. Must be finite and > 0.
|
||||
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
|
||||
@discardableResult
|
||||
public func renderToFile(
|
||||
url: URL,
|
||||
format: AudioFileFormat = .cafFloat32,
|
||||
duration: Double
|
||||
) async -> Bool {
|
||||
guard !isCompiling else { return false }
|
||||
guard duration > 0, duration.isFinite else {
|
||||
appendConsole(.error, "Render duration must be a positive number of seconds.")
|
||||
return false
|
||||
}
|
||||
let code: String = hasSelection ? selectionText : text
|
||||
guard !LyrebirdScratchModel.isBlank(code) else {
|
||||
appendConsole(.error, "Nothing to render.")
|
||||
return false
|
||||
}
|
||||
// Gate the Run/Render menu items (validated on `reevalState.canEvaluate`)
|
||||
// and any re-entrancy for the render's duration.
|
||||
isCompiling = true
|
||||
reevalState = .compiling
|
||||
defer {
|
||||
isCompiling = false
|
||||
reevalState = derivedIdleState()
|
||||
}
|
||||
|
||||
let live: SynthesisEngine = session.engine
|
||||
let offline: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: live.blockSize,
|
||||
controlBlockSize: live.controlBlockSize,
|
||||
sampleRate: live.sampleRate,
|
||||
numOutputChannels: live.numOutputChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: live.numAudioBuses,
|
||||
numControlBuses: live.numControlBuses,
|
||||
driver: NRTDriver(outputURL: url, duration: duration, format: format)
|
||||
)
|
||||
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
|
||||
do {
|
||||
// Build the graph on the offline engine (compile off-main, add on main).
|
||||
try await offlineSession.compileAndRunAsync(code, additive: true)
|
||||
// Render synchronously, off the main thread; NRTDriver writes the CAF.
|
||||
// `stop()` runs inside the detached task (where `offline` lives): the
|
||||
// driver returns with the engine still `isRunning`, and only `stop()`
|
||||
// drains the node tree — without it every rendered graph leaks
|
||||
// (matches EngineHost's NRT job teardown). Keeping it here also avoids
|
||||
// a cross-actor use of the non-Sendable engine after the detached run.
|
||||
try await Task.detached(priority: .userInitiated) {
|
||||
defer { offline.stop() }
|
||||
try offline.start()
|
||||
}.value
|
||||
appendConsole(.info, "Rendered \(String(format: "%.2f", duration)) s → \(url.lastPathComponent)")
|
||||
return true
|
||||
} catch {
|
||||
appendConsole(.error, "Render failed: \(error)")
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
public func resetSession() {
|
||||
guard !isCompiling else { return }
|
||||
session.resetAll()
|
||||
_completion?.shutdownSynchronously()
|
||||
_completion = nil // recreated lazily on next completion
|
||||
diagnostics = []
|
||||
consoleEntries.removeAll()
|
||||
lastEvaluatedText = nil
|
||||
trackedSynthCount = session.trackedSynthCount
|
||||
loadedSnippetCount = session.loadedSnippetCount
|
||||
reevalState = derivedIdleState()
|
||||
statusMessage = loadedSnippetCount > 0
|
||||
? "Session reset. \(loadedSnippetCount) snippet dylibs still mapped — Restart to reclaim that memory."
|
||||
: "Session reset."
|
||||
}
|
||||
|
||||
/// Start the audio engine if stopped, or stop it if running. Surfaces the
|
||||
/// outcome (including a start failure — e.g. no audio device) on the status
|
||||
/// line. The host normally starts the engine at launch; this lets the user
|
||||
|
||||
@@ -58,9 +58,35 @@ import LyrebirdLiveCompile
|
||||
public struct LyrebirdScratchView: View {
|
||||
|
||||
@StateObject private var model: LyrebirdScratchModel
|
||||
@State private var engineTick: Int = 0
|
||||
/// Snapshot of the engine's non-`@Published` live stats, refreshed on the
|
||||
/// heartbeat. Bound in place by the status rows — deliberately NOT via
|
||||
/// `.id(tick)`, which forces a subview teardown/rebuild every tick and churns
|
||||
/// the surrounding layout, nudging the editor's scroll position ("screen
|
||||
/// jumping" while scrolled down). Updating an `@State` value re-renders the
|
||||
/// labels in place with stable identity, so the layout stays put.
|
||||
@State private var stats: EngineStats = EngineStats()
|
||||
private let engineRefresh = Timer.publish(every: 0.5, on: .main, in: .common).autoconnect()
|
||||
|
||||
/// Non-`@Published` engine values polled on the heartbeat.
|
||||
private struct EngineStats: Equatable {
|
||||
var isRunning: Bool = false
|
||||
var averageCPU: Double = 0
|
||||
var peakCPU: Double = 0
|
||||
var synthesizerCount: Int = 0
|
||||
var groupCount: Int = 0
|
||||
}
|
||||
|
||||
private func snapshotStats() -> EngineStats {
|
||||
let e: SynthesisEngine = model.session.engine
|
||||
return EngineStats(
|
||||
isRunning: e.isRunning,
|
||||
averageCPU: e.averageCPU,
|
||||
peakCPU: e.peakCPU,
|
||||
synthesizerCount: e.synthesizerCount,
|
||||
groupCount: e.groupCount
|
||||
)
|
||||
}
|
||||
|
||||
/// Construct with a fresh `LyrebirdScratchModel` wrapping `session`.
|
||||
///
|
||||
/// - Parameters:
|
||||
@@ -85,6 +111,29 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
HStack(spacing: 0) {
|
||||
mainColumn
|
||||
Divider()
|
||||
consolePanel
|
||||
.frame(width: consoleWidth)
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth + consoleWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
let next: EngineStats = snapshotStats()
|
||||
if next != stats { stats = next }
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
/// The editor column: engine controls, editor, status, engine panel.
|
||||
private var mainColumn: some View {
|
||||
VStack(spacing: 0) {
|
||||
engineBar
|
||||
if let hint: String = model.snippetMemoryHint {
|
||||
@@ -101,27 +150,50 @@ public struct LyrebirdScratchView: View {
|
||||
wrapsLines: model.wrapsLines,
|
||||
requestCompletions: { line, character in
|
||||
await model.completionItems(line: line, character: character)
|
||||
}
|
||||
},
|
||||
onSelectionChanged: { selected in model.updateSelection(selected) }
|
||||
)
|
||||
.frame(minHeight: editorMinHeight)
|
||||
Divider()
|
||||
statusBar
|
||||
if !model.diagnostics.isEmpty {
|
||||
Divider()
|
||||
diagnosticsList
|
||||
Divider()
|
||||
enginePanel
|
||||
}
|
||||
}
|
||||
|
||||
/// Always-open right-side console: report messages, errors, and run notices,
|
||||
/// oldest first, auto-scrolled to the newest.
|
||||
private var consolePanel: some View {
|
||||
VStack(spacing: 0) {
|
||||
HStack {
|
||||
Text("Console")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Button("Clear") { model.clearConsole() }
|
||||
.buttonStyle(.plain)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.disabled(model.consoleEntries.isEmpty)
|
||||
}
|
||||
.padding(.horizontal, statusHPad)
|
||||
.padding(.vertical, statusVPad)
|
||||
Divider()
|
||||
ScrollViewReader { proxy in
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: 2) {
|
||||
ForEach(model.consoleEntries) { entry in
|
||||
ConsoleRow(entry: entry)
|
||||
}
|
||||
Color.clear.frame(height: 1).id(consoleBottomID)
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
.frame(maxWidth: .infinity, alignment: .leading)
|
||||
}
|
||||
.onChange(of: model.consoleEntries.count) { _, _ in
|
||||
proxy.scrollTo(consoleBottomID, anchor: .bottom)
|
||||
}
|
||||
}
|
||||
}
|
||||
.frame(minWidth: scratchMinWidth, minHeight: scratchMinHeight)
|
||||
.onAppear {
|
||||
// Warm the module cache in the background so the first ⌘↩ is ~0.1 s
|
||||
// instead of paying the ~2–3 s cold `LyrebirdSynth` .pcm build.
|
||||
// Idempotent — safe if `onAppear` fires again.
|
||||
model.session.prewarm()
|
||||
}
|
||||
.onReceive(engineRefresh) { _ in
|
||||
engineTick &+= 1
|
||||
// Settle a `.queued` readiness badge once its swap has fired.
|
||||
model.refreshQueuedState()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -130,21 +202,21 @@ public struct LyrebirdScratchView: View {
|
||||
return HStack(spacing: toolbarSpacing) {
|
||||
Button {
|
||||
model.toggleEngine()
|
||||
engineTick &+= 1
|
||||
stats = snapshotStats()
|
||||
} label: {
|
||||
HStack(spacing: reevalBadgeSpacing) {
|
||||
Circle()
|
||||
.fill(engine.isRunning ? Color.green : Color.red)
|
||||
.fill(stats.isRunning ? Color.green : Color.red)
|
||||
.frame(width: engineDotSize, height: engineDotSize)
|
||||
Text(engine.isRunning ? "engine running" : "▶ start engine")
|
||||
Text(stats.isRunning ? "engine running" : "▶ start engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(engine.isRunning ? Color.secondary : Color.primary)
|
||||
.foregroundStyle(stats.isRunning ? Color.secondary : Color.primary)
|
||||
}
|
||||
}
|
||||
.buttonStyle(.plain)
|
||||
.help(engine.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
.help(stats.isRunning ? "Stop the audio engine" : "Start the audio engine")
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(engine.averageCPU))")
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch · CPU \(formatCPU(stats.averageCPU))")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer().frame(width: 8)
|
||||
@@ -160,7 +232,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
.id(engineTick)
|
||||
}
|
||||
|
||||
/// Warning strip shown once mapped snippet dylibs cross the restart
|
||||
@@ -180,6 +251,70 @@ public struct LyrebirdScratchView: View {
|
||||
.background(Color.orange.opacity(0.12))
|
||||
}
|
||||
|
||||
/// Bottom engine panel: a live output oscilloscope plus a compact status
|
||||
/// readout (sample rate, CPU average/peak meters, node counts). The status
|
||||
/// text refreshes in place off the ``stats`` snapshot — no `.id(tick)`
|
||||
/// teardown, so the surrounding layout (and the editor's scroll) stays put.
|
||||
private var enginePanel: some View {
|
||||
VStack(alignment: .leading, spacing: 6) {
|
||||
if let scope: ScopeCapture = model.session.scope {
|
||||
ScratchScopeView(capture: scope)
|
||||
.frame(height: scopeHeight)
|
||||
}
|
||||
engineStatusRow
|
||||
}
|
||||
.padding(.horizontal, toolbarPadding)
|
||||
.padding(.vertical, 6)
|
||||
}
|
||||
|
||||
/// Heartbeat-refreshed engine readout: rate/channels, CPU meters, node counts.
|
||||
private var engineStatusRow: some View {
|
||||
let engine: SynthesisEngine = model.session.engine
|
||||
return VStack(alignment: .leading, spacing: 6) {
|
||||
HStack {
|
||||
Text("Engine")
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
Spacer()
|
||||
Text("\(Int(engine.sampleRate)) Hz · \(engine.numOutputChannels) ch")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
cpuMeter(label: "CPU avg", value: stats.averageCPU)
|
||||
cpuMeter(label: "CPU peak", value: stats.peakCPU)
|
||||
Text("synths \(stats.synthesizerCount) · groups \(stats.groupCount) · snippets \(model.loadedSnippetCount)")
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
}
|
||||
|
||||
/// One labelled CPU meter bar. `value` is a fraction of one block period
|
||||
/// (`[0, 1]`); the fill greens/oranges/reds as it approaches overrun.
|
||||
private func cpuMeter(label: String, value: Double) -> some View {
|
||||
let clamped: CGFloat = CGFloat(min(max(value, 0), 1))
|
||||
let fill: Color = value > cpuMeterCriticalThreshold
|
||||
? .red
|
||||
: (value > cpuMeterWarningThreshold ? .orange : .green)
|
||||
return HStack(spacing: 6) {
|
||||
Text(label)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuLabelWidth, alignment: .leading)
|
||||
GeometryReader { geo in
|
||||
ZStack(alignment: .leading) {
|
||||
RoundedRectangle(cornerRadius: 2).fill(Color.secondary.opacity(0.15))
|
||||
RoundedRectangle(cornerRadius: 2).fill(fill)
|
||||
.frame(width: geo.size.width * clamped)
|
||||
}
|
||||
}
|
||||
.frame(height: meterHeight)
|
||||
Text(formatCPU(value))
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(width: cpuValueWidth, alignment: .trailing)
|
||||
}
|
||||
}
|
||||
|
||||
private func formatCPU(_ value: Double) -> String {
|
||||
String(format: "%.0f%%", value * 100)
|
||||
}
|
||||
@@ -190,6 +325,14 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
/// Evaluate just the current selection, additively. No-op when nothing is
|
||||
/// selected.
|
||||
public func runSelection() {
|
||||
Task { @MainActor in
|
||||
_ = await model.runSelection()
|
||||
}
|
||||
}
|
||||
|
||||
public func presentOpenPanel() {
|
||||
let panel: NSOpenPanel = NSOpenPanel()
|
||||
panel.allowedContentTypes = [.swiftSource]
|
||||
@@ -322,18 +465,6 @@ public struct LyrebirdScratchView: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var diagnosticsList: some View {
|
||||
ScrollView {
|
||||
LazyVStack(alignment: .leading, spacing: diagnosticRowSpacing) {
|
||||
ForEach(Array(model.diagnostics.enumerated()), id: \.offset) { _, diag in
|
||||
DiagnosticRow(diagnostic: diag)
|
||||
}
|
||||
}
|
||||
.padding(diagnosticListPadding)
|
||||
}
|
||||
.frame(minHeight: diagnosticsMinHeight, maxHeight: diagnosticsMaxHeight)
|
||||
}
|
||||
|
||||
// Layout constants — all in points. Kept private; tuned to match
|
||||
// LyrebirdEngineStatusView's visual density.
|
||||
private let scratchMinWidth: CGFloat = 520
|
||||
@@ -350,26 +481,38 @@ public struct LyrebirdScratchView: View {
|
||||
private let diagnosticsMaxHeight: CGFloat = 200
|
||||
private let engineDotSize: CGFloat = 8
|
||||
private let reevalBadgeSpacing: CGFloat = 4
|
||||
private let scopeHeight: CGFloat = 88
|
||||
private let meterHeight: CGFloat = 6
|
||||
private let consoleWidth: CGFloat = 300
|
||||
private let consoleBottomID: String = "scratch.console.bottom"
|
||||
private let cpuLabelWidth: CGFloat = 58
|
||||
private let cpuValueWidth: CGFloat = 40
|
||||
/// CPU-meter fill turns orange above this fraction of one block period, red
|
||||
/// above ``cpuMeterCriticalThreshold``.
|
||||
private let cpuMeterWarningThreshold: Double = 0.5
|
||||
private let cpuMeterCriticalThreshold: Double = 0.8
|
||||
}
|
||||
|
||||
/// One row in the diagnostics list. Renders `(line:col)`, severity, and
|
||||
/// message in a compact monospaced row.
|
||||
private struct DiagnosticRow: View {
|
||||
private struct ConsoleRow: View {
|
||||
|
||||
let diagnostic: Diagnostic
|
||||
let entry: ScratchConsoleEntry
|
||||
|
||||
var body: some View {
|
||||
HStack(alignment: .firstTextBaseline, spacing: rowGutter) {
|
||||
Text(locationString)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
.frame(minWidth: locationColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.severity.rawValue)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(color(for: diagnostic.severity))
|
||||
.frame(minWidth: severityColumnWidth, alignment: .leading)
|
||||
Text(diagnostic.message)
|
||||
HStack(alignment: .firstTextBaseline, spacing: 6) {
|
||||
Text(glyph)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(color)
|
||||
.frame(width: 14, alignment: .leading)
|
||||
if let location: String = entry.location {
|
||||
Text(location)
|
||||
.font(.system(.caption2, design: .monospaced))
|
||||
.foregroundStyle(.secondary)
|
||||
}
|
||||
Text(entry.text)
|
||||
.font(.system(.caption, design: .monospaced))
|
||||
.foregroundStyle(entry.kind == .error ? Color.primary : color)
|
||||
.textSelection(.enabled)
|
||||
.multilineTextAlignment(.leading)
|
||||
.fixedSize(horizontal: false, vertical: true)
|
||||
@@ -377,59 +520,94 @@ private struct DiagnosticRow: View {
|
||||
}
|
||||
}
|
||||
|
||||
private var locationString: String {
|
||||
if let line: Int = diagnostic.line {
|
||||
return "\(line):\(diagnostic.column)"
|
||||
/// Leading glyph per kind: an X for errors, an arrow for messages, a dot for
|
||||
/// info notices.
|
||||
private var glyph: String {
|
||||
switch entry.kind {
|
||||
case .error: return "✗"
|
||||
case .message: return "›"
|
||||
case .info: return "·"
|
||||
}
|
||||
// No user-body line. A swiftc preamble hit carries a real (1-based)
|
||||
// rawLine; a graph-DSL file-scope error carries rawLine 0 (there is no
|
||||
// harness/preamble at all), so label the two cases distinctly.
|
||||
return diagnostic.rawLine >= 1
|
||||
? "preamble:\(diagnostic.rawLine):\(diagnostic.column)"
|
||||
: "(file)"
|
||||
}
|
||||
|
||||
private func color(for severity: DiagnosticSeverity) -> Color {
|
||||
switch severity {
|
||||
private var color: Color {
|
||||
switch entry.kind {
|
||||
case .error: return .red
|
||||
case .warning: return .orange
|
||||
case .note: return .secondary
|
||||
case .message: return .cyan
|
||||
case .info: return .secondary
|
||||
}
|
||||
}
|
||||
|
||||
private let rowGutter: CGFloat = 8
|
||||
private let locationColumnWidth: CGFloat = 80
|
||||
private let severityColumnWidth: CGFloat = 56
|
||||
}
|
||||
|
||||
/// `NSTextView` subclass that fixes member-completion behavior.
|
||||
///
|
||||
/// The default `rangeForUserCompletion` scans back over the whole dotted
|
||||
/// expression, so completing a member right after a `.` (e.g. `context.` →
|
||||
/// `engine`) would *replace* the receiver (`context`) with the chosen member
|
||||
/// instead of inserting after the dot. When the character before the insertion
|
||||
/// point is a `.`, this override returns an empty range at the caret, so the
|
||||
/// completion is a pure insertion and `context.engine` is produced.
|
||||
/// UTF-16 code unit for `.` (the member-access operator that triggers and
|
||||
/// shapes completion).
|
||||
private let dotCharacterCode: unichar = 46
|
||||
/// expression, so a candidate would *replace* the receiver rather than the
|
||||
/// partial word being typed. Completing a member after `context.` → `engine`
|
||||
/// would replace `context`; accepting an argument label after `OscSin.Audio(`
|
||||
/// → `freq:` would replace `OscSin.Audio`. The correct replace range is just
|
||||
/// the run of identifier characters immediately before the caret (empty after
|
||||
/// any boundary — `.`, `(`, `,`, whitespace), so the candidate inserts there.
|
||||
|
||||
/// Whether `selection` is a bare insertion point sitting immediately after a
|
||||
/// `.` in `text` — the member-completion trigger condition.
|
||||
private func caretFollowsDot(in text: NSString, selection: NSRange) -> Bool {
|
||||
guard selection.length == 0, selection.location > 0, selection.location <= text.length
|
||||
else { return false }
|
||||
return text.character(at: selection.location - 1) == dotCharacterCode
|
||||
/// Whether `c` (a UTF-16 code unit) is a Swift identifier character —
|
||||
/// ASCII letter, digit, or underscore. Sufficient for completion-range
|
||||
/// scanning; identifiers with non-ASCII scalars are not a concern here.
|
||||
private func isIdentifierCodeUnit(_ c: unichar) -> Bool {
|
||||
let underscore: unichar = 95
|
||||
let zero: unichar = 48, nine: unichar = 57
|
||||
let upperA: unichar = 65, upperZ: unichar = 90
|
||||
let lowerA: unichar = 97, lowerZ: unichar = 122
|
||||
return c == underscore
|
||||
|| (c >= zero && c <= nine)
|
||||
|| (c >= upperA && c <= upperZ)
|
||||
|| (c >= lowerA && c <= lowerZ)
|
||||
}
|
||||
|
||||
final class ScratchTextView: NSTextView {
|
||||
/// Invoked when the user asks for completion (the standard completion key —
|
||||
/// Esc / F5). Set by `makeNSView`, right after `configure`; runs the async fetch and then
|
||||
/// shows the completion window. Completion is manual only.
|
||||
var onManualComplete: (() -> Void)?
|
||||
|
||||
override var rangeForUserCompletion: NSRange {
|
||||
let sel: NSRange = selectedRange()
|
||||
if caretFollowsDot(in: string as NSString, selection: sel) {
|
||||
return NSRange(location: sel.location, length: 0)
|
||||
// Never replace across an actual selection — defer to the default.
|
||||
guard sel.length == 0, sel.location <= (string as NSString).length else {
|
||||
return super.rangeForUserCompletion
|
||||
}
|
||||
return super.rangeForUserCompletion
|
||||
let ns: NSString = string as NSString
|
||||
var start: Int = sel.location
|
||||
while start > 0 && isIdentifierCodeUnit(ns.character(at: start - 1)) {
|
||||
start -= 1
|
||||
}
|
||||
return NSRange(location: start, length: sel.location - start)
|
||||
}
|
||||
|
||||
/// Intercept the built-in `complete:` command (bound to Esc / F5) so the
|
||||
/// candidates are fetched asynchronously first, then shown. Without this,
|
||||
/// pressing Esc would call the delegate with an empty (never-fetched) list.
|
||||
/// Everything else falls through to the normal editor commands.
|
||||
override func doCommand(by selector: Selector) {
|
||||
if selector == #selector(NSStandardKeyBindingResponding.complete(_:)) {
|
||||
onManualComplete?()
|
||||
return
|
||||
}
|
||||
super.doCommand(by: selector)
|
||||
}
|
||||
|
||||
/// Esc is delivered as `cancelOperation:` (not `complete:`) by the default
|
||||
/// key bindings, so it never reaches `doCommand(by:)`'s `complete:` arm —
|
||||
/// only F5 does. Route it here too so Esc invokes completion as documented.
|
||||
/// The completion window, once open, consumes Esc itself to dismiss, so this
|
||||
/// only fires when the window is closed.
|
||||
override func cancelOperation(_ sender: Any?) {
|
||||
onManualComplete?()
|
||||
}
|
||||
|
||||
/// Width of the line-number gutter drawn by ``ScratchLineNumberGutter``.
|
||||
/// `ScratchEditor.configure` reserves this as the text view's left inset so
|
||||
/// the gutter overlay doesn't cover the text.
|
||||
static let lineNumberGutterWidth: CGFloat = 40
|
||||
}
|
||||
|
||||
/// `NSViewRepresentable` wrapping a ``ScratchTextView`` inside an
|
||||
@@ -444,6 +622,9 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// Async source of code-completion candidates for a zero-based user-space
|
||||
/// (line, UTF-16 character). Supplied by the view from the model.
|
||||
let requestCompletions: @MainActor (_ line: Int, _ character: Int) async -> [LSPCompletionItem]
|
||||
/// Called with the current selected substring whenever the selection
|
||||
/// changes (empty when nothing is selected). Drives "Run Selection".
|
||||
let onSelectionChanged: @MainActor (String) -> Void
|
||||
|
||||
@MainActor
|
||||
final class Coordinator: NSObject, NSTextViewDelegate {
|
||||
@@ -455,17 +636,67 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
/// applies its results if it is still the newest (so a slow older request
|
||||
/// can't clobber a fresher one that landed first).
|
||||
private var _completionGeneration: Int = 0
|
||||
/// Pending debounced re-highlight; cancelled and rescheduled on each edit
|
||||
/// so a burst of keystrokes re-tokenizes the buffer once, not per key.
|
||||
private var _highlightWork: DispatchWorkItem?
|
||||
/// Last selection substring pushed to the model, so an unchanged selection
|
||||
/// (the common case while typing — caret moves, selection stays empty)
|
||||
/// doesn't republish `@Published` state and re-render the whole view.
|
||||
private var _lastSelectionPushed: String = ""
|
||||
/// Last `wrapsLines` value applied, so `updateNSView` can skip re-applying
|
||||
/// wrap/paragraph settings on a pure text republish (every keystroke).
|
||||
var lastWraps: Bool?
|
||||
|
||||
/// Idle delay before re-highlighting after an edit. Short enough to feel
|
||||
/// instant once typing pauses; long enough to coalesce a fast burst.
|
||||
private static let highlightDebounce: TimeInterval = 0.045
|
||||
|
||||
init(_ parent: ScratchEditor) { self.parent = parent }
|
||||
|
||||
func textDidChange(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
parent.text = tv.string
|
||||
parent.applyHighlight(to: tv)
|
||||
// Auto-trigger member completion right after a `.` is typed.
|
||||
if caretFollowsDot(in: tv.string as NSString, selection: tv.selectedRange()) {
|
||||
triggerCompletion(tv)
|
||||
scheduleHighlight(tv)
|
||||
// Completion is manual (Esc), never auto-triggered on `.`: an
|
||||
// unrequested popup ambushes typing and the built-in completion
|
||||
// window is awkward to dismiss mid-edit.
|
||||
}
|
||||
|
||||
/// Coalesce full-buffer re-highlighting: cancel any pending pass and run
|
||||
/// one shortly after the edits stop. Newly typed characters render in the
|
||||
/// base color immediately (via `typingAttributes`); syntax colors catch
|
||||
/// up a beat later, avoiding an O(n) tokenize on every keystroke.
|
||||
private func scheduleHighlight(_ tv: NSTextView) {
|
||||
_highlightWork?.cancel()
|
||||
let work: DispatchWorkItem = DispatchWorkItem { [weak self, weak tv] in
|
||||
guard let self: Coordinator = self, let tv: NSTextView = tv else { return }
|
||||
self.parent.applyHighlight(to: tv)
|
||||
}
|
||||
_highlightWork = work
|
||||
DispatchQueue.main.asyncAfter(deadline: .now() + Coordinator.highlightDebounce, execute: work)
|
||||
}
|
||||
|
||||
/// Push the current selected substring up to the model so "Run Selection"
|
||||
/// knows what (if anything) is selected — but only when it actually
|
||||
/// changed, to avoid a per-caret-move `@Published` republish.
|
||||
func textViewDidChangeSelection(_ notification: Notification) {
|
||||
guard let tv: NSTextView = notification.object as? NSTextView else { return }
|
||||
let sel: NSRange = tv.selectedRange()
|
||||
let selected: String
|
||||
if sel.length > 0, sel.location + sel.length <= (tv.string as NSString).length {
|
||||
selected = (tv.string as NSString).substring(with: sel)
|
||||
} else {
|
||||
selected = ""
|
||||
}
|
||||
guard selected != _lastSelectionPushed else { return }
|
||||
_lastSelectionPushed = selected
|
||||
// Defer the @Published mutation: a programmatic text change (via
|
||||
// `updateNSView` → `replaceText`) can clamp the selection and re-post
|
||||
// this notification from inside a SwiftUI update pass. Scheduling on
|
||||
// the next main-actor tick keeps that off the render pass ("Publishing
|
||||
// changes from within view updates is not allowed").
|
||||
let notify: @MainActor (String) -> Void = parent.onSelectionChanged
|
||||
Task { @MainActor in notify(selected) }
|
||||
}
|
||||
|
||||
/// The text view calls this synchronously from `complete(_:)`; return the
|
||||
@@ -515,6 +746,10 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.autoresizingMask = [.width, .height]
|
||||
|
||||
let tv: ScratchTextView = ScratchTextView(frame: .zero)
|
||||
// Opt into TextKit 1: accessing `layoutManager` permanently switches the
|
||||
// text view off TextKit 2, where `self.layoutManager` is nil — the gutter
|
||||
// drawing needs it to place numbers against laid-out line rects.
|
||||
_ = tv.layoutManager
|
||||
tv.autoresizingMask = [.width]
|
||||
tv.isVerticallyResizable = true
|
||||
tv.isHorizontallyResizable = false
|
||||
@@ -525,6 +760,16 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
scroll.documentView = tv
|
||||
|
||||
configure(tv, in: scroll, with: context.coordinator)
|
||||
// Manual completion (Esc): fetch candidates, then show the window.
|
||||
let coordinator: Coordinator = context.coordinator
|
||||
tv.onManualComplete = { [weak coordinator, weak tv] in
|
||||
guard let coordinator: Coordinator = coordinator, let tv: ScratchTextView = tv else { return }
|
||||
coordinator.triggerCompletion(tv)
|
||||
}
|
||||
// Line-number gutter: a floating overlay pinned to the left of the visible
|
||||
// area (see `ScratchLineNumberGutter` for why not an `NSRulerView`).
|
||||
let gutter: ScratchLineNumberGutter = ScratchLineNumberGutter(scrollView: scroll, textView: tv)
|
||||
scroll.addFloatingSubview(gutter, for: .vertical)
|
||||
return scroll
|
||||
}
|
||||
|
||||
@@ -533,14 +778,23 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
guard let tv: NSTextView = scroll.documentView as? NSTextView else { return }
|
||||
let font: NSFont = NSFont.monospacedSystemFont(ofSize: fontSize, weight: .regular)
|
||||
let fontChanged: Bool = (tv.font?.pointSize ?? -1) != fontSize
|
||||
if fontChanged {
|
||||
tv.font = font
|
||||
}
|
||||
let wrapChanged: Bool = context.coordinator.lastWraps != wrapsLines
|
||||
context.coordinator.lastWraps = wrapsLines
|
||||
let textChanged: Bool = tv.string != text
|
||||
|
||||
// Fast path: a pure text republish (the per-keystroke case) needs no work
|
||||
// here — the `NSTextView` already holds the text (it's the editor of
|
||||
// record), highlighting is debounced in the Coordinator, and font/wrap
|
||||
// are unchanged. Skip the paragraph-style measure + attribute churn.
|
||||
guard textChanged || fontChanged || wrapChanged else { return }
|
||||
|
||||
let paragraphStyle: NSParagraphStyle = makeParagraphStyle(for: font)
|
||||
if fontChanged { tv.font = font }
|
||||
tv.defaultParagraphStyle = paragraphStyle
|
||||
tv.typingAttributes = makeAttrs(font: font, paragraph: paragraphStyle)
|
||||
applyWrap(to: tv, in: scroll)
|
||||
if tv.string != text {
|
||||
if textChanged {
|
||||
// External change (load, reset, mode switch) — replace + re-highlight.
|
||||
replaceText(in: tv, with: text, font: font, paragraph: paragraphStyle)
|
||||
} else if fontChanged {
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraphStyle)
|
||||
@@ -573,6 +827,15 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.textStorage?.setAttributedString(attributed)
|
||||
tv.typingAttributes = attrs
|
||||
applyHighlight(to: tv, font: font, paragraph: paragraph)
|
||||
// A direct `setAttributedString` bypasses `NSTextView`'s edit path, so the
|
||||
// gutter (which redraws on `NSText.didChangeNotification`) isn't told to
|
||||
// refresh. Nudge it explicitly after a programmatic replace (format /
|
||||
// load / reset) so the line count doesn't go stale.
|
||||
if let scroll: NSScrollView = tv.enclosingScrollView {
|
||||
for sub: NSView in scroll.subviews {
|
||||
(sub as? ScratchLineNumberGutter)?.refresh()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Syntax highlighting
|
||||
@@ -638,7 +901,11 @@ private struct ScratchEditor: NSViewRepresentable {
|
||||
tv.smartInsertDeleteEnabled = false
|
||||
tv.allowsUndo = true
|
||||
tv.usesFindBar = true
|
||||
tv.textContainerInset = NSSize(width: editorInset, height: editorInset)
|
||||
// Left inset reserves the column the `ScratchLineNumberGutter` overlay
|
||||
// draws line numbers into (see `ScratchLineNumberGutter.draw(_:)`).
|
||||
// `textContainerInset` is symmetric, so the right margin matches —
|
||||
// harmless whitespace.
|
||||
tv.textContainerInset = NSSize(width: ScratchTextView.lineNumberGutterWidth, height: editorInset)
|
||||
tv.drawsBackground = true
|
||||
tv.backgroundColor = .textBackgroundColor
|
||||
tv.textColor = .labelColor
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// RenderOptionsAccessory.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Accessory view embedded in the "Render to File" `NSSavePanel`: a container/encoding
|
||||
/// popup and a duration field. Selecting a format rewrites the panel's filename
|
||||
/// extension and remembers the choice (`UserDefaults`) so the next render defaults to it.
|
||||
///
|
||||
/// The sample rate and channel count are intentionally **not** exposed here — the
|
||||
/// offline render mirrors the live engine (WYSIWYG with what was just heard).
|
||||
@MainActor
|
||||
final class RenderOptionsAccessory: NSView {
|
||||
|
||||
// MARK: - Format catalogue
|
||||
|
||||
/// One selectable output format. `token` is the persistence key (stable across
|
||||
/// reordering / re-titling of the list, unlike a raw index or the display title).
|
||||
private struct Option {
|
||||
let title: String
|
||||
let format: AudioFileFormat
|
||||
let token: String
|
||||
}
|
||||
|
||||
private static let options: [Option] = [
|
||||
Option(title: "WAV — 32-bit float", format: .wavFloat32, token: "wavF32"),
|
||||
Option(title: "WAV — 16-bit integer", format: .wavInt16, token: "wavI16"),
|
||||
Option(title: "WAV — 24-bit integer", format: .wavInt24, token: "wavI24"),
|
||||
Option(title: "AIFF — 32-bit float", format: .aiffFloat32, token: "aiffF32"),
|
||||
Option(title: "CAF — 32-bit float (uncapped)", format: .cafFloat32, token: "cafF32"),
|
||||
Option(title: "RF64 WAV — 32-bit float (>4 GB)", format: .rf64Float32, token: "rf64F32"),
|
||||
Option(title: "RF64 WAV — 24-bit integer (>4 GB)", format: .rf64Int24, token: "rf64I24"),
|
||||
Option(title: "AAC — 256 kbps (M4A)", format: .aacHigh, token: "aacHigh"),
|
||||
Option(title: "AAC — 128 kbps (M4A)", format: .aacMedium, token: "aacMedium"),
|
||||
Option(title: "Apple Lossless (M4A)", format: .alac, token: "alac"),
|
||||
]
|
||||
|
||||
/// Persisted last-used format token. Defaults to CAF (the pre-accessory behaviour).
|
||||
private static let defaultsKey: String = "com.lyrebird.scratch.renderFormatToken"
|
||||
private static let fallbackToken: String = "cafF32"
|
||||
|
||||
// MARK: - Layout metrics
|
||||
|
||||
private static let accessoryWidth: CGFloat = 380
|
||||
private static let accessoryHeight: CGFloat = 96
|
||||
private static let contentMargin: CGFloat = 16
|
||||
private static let gridSpacing: CGFloat = 8
|
||||
private static let minDurationFieldWidth: CGFloat = 80
|
||||
|
||||
// MARK: - Subviews
|
||||
|
||||
private let formatPopup: NSPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
|
||||
private let durationField: NSTextField = NSTextField(frame: .zero)
|
||||
|
||||
private let baseName: String
|
||||
private weak var savePanel: NSSavePanel?
|
||||
|
||||
// MARK: - Public read-out
|
||||
|
||||
/// The format for the currently selected popup item.
|
||||
var selectedFormat: AudioFileFormat {
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
guard index >= 0 && index < RenderOptionsAccessory.options.count else {
|
||||
return .cafFloat32
|
||||
}
|
||||
return RenderOptionsAccessory.options[index].format
|
||||
}
|
||||
|
||||
/// Parsed duration in seconds, or `nil` when the field is not a positive number.
|
||||
var durationSeconds: Double? { RenderOptionsAccessory.parseDuration(durationField.stringValue) }
|
||||
|
||||
/// Parse a duration string to a positive, finite seconds value (or `nil`). Pure —
|
||||
/// extracted so it can be unit-tested without the modal panel.
|
||||
static func parseDuration(_ raw: String) -> Double? {
|
||||
let trimmed: String = raw.trimmingCharacters(in: .whitespaces)
|
||||
guard let value: Double = Double(trimmed), value > 0, value.isFinite else { return nil }
|
||||
return value
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - baseName: Filename stem (no extension); the format's extension is appended.
|
||||
/// - initialDuration: Seconds pre-filled in the duration field.
|
||||
/// - savePanel: The panel to keep the filename extension in sync with.
|
||||
init(baseName: String, initialDuration: Double, savePanel: NSSavePanel) {
|
||||
self.baseName = baseName
|
||||
self.savePanel = savePanel
|
||||
super.init(frame: NSRect(x: 0, y: 0,
|
||||
width: RenderOptionsAccessory.accessoryWidth,
|
||||
height: RenderOptionsAccessory.accessoryHeight))
|
||||
|
||||
let startIndex: Int = RenderOptionsAccessory.persistedIndex()
|
||||
|
||||
formatPopup.addItems(withTitles: RenderOptionsAccessory.options.map(\.title))
|
||||
formatPopup.selectItem(at: startIndex)
|
||||
formatPopup.target = self
|
||||
formatPopup.action = #selector(formatChanged)
|
||||
formatPopup.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
durationField.stringValue = String(format: "%.2f", initialDuration)
|
||||
durationField.translatesAutoresizingMaskIntoConstraints = false
|
||||
|
||||
let formatLabel: NSTextField = RenderOptionsAccessory.makeLabel("Format:")
|
||||
let durationLabel: NSTextField = RenderOptionsAccessory.makeLabel("Duration (s):")
|
||||
|
||||
let grid: NSGridView = NSGridView(views: [
|
||||
[formatLabel, formatPopup],
|
||||
[durationLabel, durationField],
|
||||
])
|
||||
grid.translatesAutoresizingMaskIntoConstraints = false
|
||||
grid.rowSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.columnSpacing = RenderOptionsAccessory.gridSpacing
|
||||
grid.column(at: 0).xPlacement = .trailing
|
||||
addSubview(grid)
|
||||
|
||||
let margin: CGFloat = RenderOptionsAccessory.contentMargin
|
||||
NSLayoutConstraint.activate([
|
||||
grid.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
|
||||
grid.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
|
||||
grid.topAnchor.constraint(equalTo: topAnchor, constant: margin),
|
||||
grid.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin),
|
||||
durationField.widthAnchor.constraint(
|
||||
greaterThanOrEqualToConstant: RenderOptionsAccessory.minDurationFieldWidth),
|
||||
])
|
||||
|
||||
// Seed the panel filename once from baseName + the initial format's extension.
|
||||
savePanel.nameFieldStringValue = baseName + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
@available(*, unavailable)
|
||||
required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
|
||||
|
||||
// MARK: - Actions
|
||||
|
||||
@objc private func formatChanged() {
|
||||
syncPanelExtension()
|
||||
let index: Int = formatPopup.indexOfSelectedItem
|
||||
if index >= 0 && index < RenderOptionsAccessory.options.count {
|
||||
UserDefaults.standard.set(RenderOptionsAccessory.options[index].token,
|
||||
forKey: RenderOptionsAccessory.defaultsKey)
|
||||
}
|
||||
}
|
||||
|
||||
/// Re-extension the panel's current filename to match the selected format,
|
||||
/// **preserving any stem the user typed** — only the extension is replaced.
|
||||
private func syncPanelExtension() {
|
||||
guard let panel: NSSavePanel = savePanel else { return }
|
||||
let currentStem: String = (panel.nameFieldStringValue as NSString).deletingPathExtension
|
||||
let stem: String = currentStem.isEmpty ? baseName : currentStem
|
||||
panel.nameFieldStringValue = stem + "." + selectedFormat.fileExtension
|
||||
}
|
||||
|
||||
/// Test seam: select a format by index as if the user picked it from the popup
|
||||
/// (fires the same `formatChanged` side effects — panel re-extension + persistence).
|
||||
func selectFormatForTesting(at index: Int) {
|
||||
formatPopup.selectItem(at: index)
|
||||
formatChanged()
|
||||
}
|
||||
|
||||
/// Test seam: clear the persisted last-format so a test can start from the
|
||||
/// default and not leak state into other tests or the real app.
|
||||
static func clearPersistedFormatForTesting() {
|
||||
UserDefaults.standard.removeObject(forKey: defaultsKey)
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
private static func persistedIndex() -> Int {
|
||||
let token: String = UserDefaults.standard.string(forKey: defaultsKey) ?? fallbackToken
|
||||
if let index: Int = options.firstIndex(where: { $0.token == token }) { return index }
|
||||
return options.firstIndex(where: { $0.token == fallbackToken }) ?? 0
|
||||
}
|
||||
|
||||
private static func makeLabel(_ text: String) -> NSTextField {
|
||||
let label: NSTextField = NSTextField(labelWithString: text)
|
||||
label.translatesAutoresizingMaskIntoConstraints = false
|
||||
return label
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,42 @@
|
||||
// ScratchConsoleEntry.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// One line in the scratch editor's console panel — a report message, an error,
|
||||
// or a run notice.
|
||||
|
||||
#if os(macOS)
|
||||
|
||||
/// A single entry in the always-open console.
|
||||
public struct ScratchConsoleEntry: Identifiable, Equatable {
|
||||
|
||||
/// What kind of line this is, for coloring.
|
||||
public enum Kind: Equatable {
|
||||
/// `context.reportMessage(_:)` output (and host notices).
|
||||
case message
|
||||
/// A compile / DSL error.
|
||||
case error
|
||||
/// A run outcome / informational notice.
|
||||
case info
|
||||
}
|
||||
|
||||
/// Monotonic id (also the display order).
|
||||
public let id: Int
|
||||
public let kind: Kind
|
||||
public let text: String
|
||||
/// `"line:col"` for an error with a known source position, else `nil`.
|
||||
public let location: String?
|
||||
|
||||
public init(id: Int, kind: Kind, text: String, location: String? = nil) {
|
||||
self.id = id
|
||||
self.kind = kind
|
||||
self.text = text
|
||||
self.location = location
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,164 @@
|
||||
// ScratchLineNumberGutter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Line-number gutter for `ScratchEditor`'s text view, implemented as a plain
|
||||
// floating overlay `NSView` rather than an `NSRulerView`. Enabling
|
||||
// `NSScrollView.rulersVisible` in this SwiftUI `NSViewRepresentable` mis-tiles
|
||||
// the document view (text goes invisible and stops taking input), and drawing
|
||||
// inside a layer-backed `NSTextView` never reaches `draw(_:)`. A floating
|
||||
// subview draws normally and leaves the text view untouched. It reads the text
|
||||
// view's layout manager and the clip view's scroll offset to place one
|
||||
// right-aligned number per source line in the visible region.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
final class ScratchLineNumberGutter: NSView {
|
||||
|
||||
private weak var textView: NSTextView?
|
||||
private weak var scrollView: NSScrollView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.scrollView = scrollView
|
||||
self.textView = textView
|
||||
let height: CGFloat = scrollView.contentView.bounds.height
|
||||
super.init(frame: NSRect(x: 0, y: 0, width: ScratchTextView.lineNumberGutterWidth, height: height))
|
||||
self.autoresizingMask = [.height]
|
||||
|
||||
let clip: NSClipView = scrollView.contentView
|
||||
clip.postsBoundsChangedNotifications = true
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.boundsDidChangeNotification, object: clip)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSText.didChangeNotification, object: textView)
|
||||
center.addObserver(self, selector: #selector(refresh),
|
||||
name: NSView.frameDidChangeNotification, object: textView)
|
||||
}
|
||||
|
||||
required init?(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberGutter does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
override var isFlipped: Bool { true }
|
||||
|
||||
/// Redraw the whole gutter after an edit / scroll / relayout. A programmatic
|
||||
/// text replace (format / load / reset) can happen without an
|
||||
/// `NSText.didChangeNotification`, so the host also nudges this directly.
|
||||
@objc func refresh() { needsDisplay = true }
|
||||
|
||||
override func draw(_ dirtyRect: NSRect) {
|
||||
gutterFillColor.setFill()
|
||||
bounds.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let divider: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
divider.move(to: NSPoint(x: dividerX, y: bounds.minY))
|
||||
divider.line(to: NSPoint(x: dividerX, y: bounds.maxY))
|
||||
divider.lineWidth = 1
|
||||
divider.stroke()
|
||||
|
||||
guard let textView: NSTextView = textView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let container: NSTextContainer = textView.textContainer,
|
||||
let clip: NSClipView = scrollView?.contentView else { return }
|
||||
|
||||
let visibleRect: NSRect = clip.documentVisibleRect
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let ns: NSString = textView.string as NSString
|
||||
let total: Int = ns.length
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: gutterFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
// Glyphs visible in the clip, then the source-line walk over that range.
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: container)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
|
||||
// Snap to the START of the first visible source line before counting: when
|
||||
// word-wrap puts a wrapped continuation fragment at the top of the visible
|
||||
// area, `charRange.location` lands mid-line, and `lineNumber(at:)` would
|
||||
// over-count by one (throwing off every number below it).
|
||||
let firstLineStart: Int = ns.lineRange(for: NSRange(location: min(charRange.location, total), length: 0)).location
|
||||
var lineIndex: Int = lineNumber(at: firstLineStart, in: ns)
|
||||
var cursor: Int = firstLineStart
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor < total {
|
||||
let lineRange: NSRange = ns.lineRange(for: NSRange(location: cursor, length: 0))
|
||||
// Position from the line *fragment* rect (the row's box), not the glyph
|
||||
// bounding rect. `boundingRect` is inconsistent across a trailing
|
||||
// newline and blank lines — it's what left the last number cramped
|
||||
// against the trailing empty line. The fragment rect is one clean,
|
||||
// uniform-height box per row.
|
||||
let firstGlyph: Int = layoutManager.glyphIndexForCharacter(at: lineRange.location)
|
||||
let fragment: NSRect = layoutManager.lineFragmentRect(
|
||||
forGlyphAt: firstGlyph,
|
||||
effectiveRange: nil,
|
||||
withoutAdditionalLayout: true
|
||||
)
|
||||
drawNumber(lineIndex, docY: fragment.minY + inset, lineHeight: fragment.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break }
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
|
||||
// Trailing empty line (empty doc, or one ending in a newline): drawn from
|
||||
// the layout manager's extra fragment, which `boundingRect` on a
|
||||
// zero-length range does not cover.
|
||||
let endsWithNewline: Bool = total > 0 && CharacterSet.newlines.contains(
|
||||
Unicode.Scalar(ns.character(at: total - 1)) ?? Unicode.Scalar(0)
|
||||
)
|
||||
if total == 0 || endsWithNewline {
|
||||
let extra: NSRect = layoutManager.extraLineFragmentRect
|
||||
if extra.height > 0 {
|
||||
drawNumber(lineIndex, docY: extra.minY + inset, lineHeight: extra.height,
|
||||
visibleMinY: visibleRect.minY, attrs: attrs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private func drawNumber(_ n: Int, docY: CGFloat, lineHeight: CGFloat, visibleMinY: CGFloat,
|
||||
attrs: [NSAttributedString.Key: Any]) {
|
||||
// Document Y → gutter-local Y (the gutter floats over the visible area).
|
||||
let y: CGFloat = docY - visibleMinY
|
||||
let label: NSString = "\(n)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let point: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: y + (lineHeight - size.height) * verticalCenterFraction
|
||||
)
|
||||
label.draw(at: point, withAttributes: attrs)
|
||||
}
|
||||
|
||||
/// 1-based source line number of the character at `loc`. Counts CR/LF/CRLF.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
text.enumerateSubstrings(in: NSRange(location: 0, length: loc),
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5
|
||||
private let gutterFontSize: CGFloat = 11
|
||||
private let verticalCenterFraction: CGFloat = 0.5
|
||||
private let gutterFillColor: NSColor = .controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = .separatorColor
|
||||
private let gutterTextColor: NSColor = .tertiaryLabelColor
|
||||
private var gutterFont: NSFont { NSFont.monospacedSystemFont(ofSize: gutterFontSize, weight: .regular) }
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -1,145 +0,0 @@
|
||||
// ScratchLineNumberRuler.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// Vertical line-number gutter for `ScratchEditor`'s `NSTextView`. Installed as
|
||||
// the scroll view's `verticalRulerView` so it tracks scroll position for free.
|
||||
// Reads laid-out glyph rects from the text view's layout manager and writes one
|
||||
// 1-based line label per visible line into the ruler's bounds.
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
|
||||
/// `NSRulerView` subclass rendering one right-aligned line number per laid-out
|
||||
/// line of the host `NSTextView`. Tracks the text view's scroll origin via the
|
||||
/// `boundsDidChangeNotification` posted by the enclosing `NSClipView` and
|
||||
/// invalidates itself on every text edit and frame change.
|
||||
final class ScratchLineNumberRuler: NSRulerView {
|
||||
|
||||
/// Re-resolved on every `draw` so the ruler picks up font / layout-manager
|
||||
/// swaps the text view performs after attachment.
|
||||
private weak var textView: NSTextView?
|
||||
|
||||
init(scrollView: NSScrollView, textView: NSTextView) {
|
||||
self.textView = textView
|
||||
super.init(scrollView: scrollView, orientation: .verticalRuler)
|
||||
self.clientView = textView
|
||||
self.ruleThickness = gutterWidth
|
||||
let center: NotificationCenter = NotificationCenter.default
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSText.didChangeNotification,
|
||||
object: textView)
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.frameDidChangeNotification,
|
||||
object: textView)
|
||||
let clipView: NSClipView = scrollView.contentView
|
||||
clipView.postsBoundsChangedNotifications = true
|
||||
center.addObserver(self,
|
||||
selector: #selector(invalidateForChange(_:)),
|
||||
name: NSView.boundsDidChangeNotification,
|
||||
object: clipView)
|
||||
}
|
||||
|
||||
required init(coder: NSCoder) {
|
||||
fatalError("ScratchLineNumberRuler does not support NSCoder init")
|
||||
}
|
||||
|
||||
deinit {
|
||||
NotificationCenter.default.removeObserver(self)
|
||||
}
|
||||
|
||||
@objc private func invalidateForChange(_ note: Notification) {
|
||||
needsDisplay = true
|
||||
}
|
||||
|
||||
override func drawHashMarksAndLabels(in rect: NSRect) {
|
||||
guard let textView: NSTextView,
|
||||
let layoutManager: NSLayoutManager = textView.layoutManager,
|
||||
let textContainer: NSTextContainer = textView.textContainer else {
|
||||
return
|
||||
}
|
||||
|
||||
gutterFillColor.setFill()
|
||||
rect.fill()
|
||||
gutterDividerColor.setStroke()
|
||||
let dividerPath: NSBezierPath = NSBezierPath()
|
||||
let dividerX: CGFloat = bounds.maxX - dividerHalfPixel
|
||||
dividerPath.move(to: NSPoint(x: dividerX, y: rect.minY))
|
||||
dividerPath.line(to: NSPoint(x: dividerX, y: rect.maxY))
|
||||
dividerPath.lineWidth = 1
|
||||
dividerPath.stroke()
|
||||
|
||||
let nsText: NSString = textView.string as NSString
|
||||
let totalLength: Int = nsText.length
|
||||
let visibleRect: NSRect = scrollView?.contentView.bounds ?? .zero
|
||||
let glyphRange: NSRange = layoutManager.glyphRange(forBoundingRect: visibleRect, in: textContainer)
|
||||
let charRange: NSRange = layoutManager.characterRange(forGlyphRange: glyphRange, actualGlyphRange: nil)
|
||||
let inset: CGFloat = textView.textContainerInset.height
|
||||
let attrs: [NSAttributedString.Key: Any] = [
|
||||
.font: rulerFont,
|
||||
.foregroundColor: gutterTextColor,
|
||||
]
|
||||
|
||||
var lineIndex: Int = lineNumber(at: charRange.location, in: nsText)
|
||||
var cursor: Int = charRange.location
|
||||
let visibleEnd: Int = NSMaxRange(charRange)
|
||||
while cursor < visibleEnd && cursor <= totalLength {
|
||||
// `lineRange(for:)` advances cursor by the full line including its
|
||||
// terminator, so `\r`, `\n`, and `\r\n` line endings are all
|
||||
// handled by Foundation.
|
||||
let probeLength: Int = (cursor == totalLength) ? 0 : 0
|
||||
let lineRange: NSRange = nsText.lineRange(for: NSRange(location: cursor, length: probeLength))
|
||||
let lineGlyphRange: NSRange = layoutManager.glyphRange(forCharacterRange: lineRange,
|
||||
actualCharacterRange: nil)
|
||||
let usedRect: NSRect = layoutManager.boundingRect(forGlyphRange: lineGlyphRange,
|
||||
in: textContainer)
|
||||
let yInView: CGFloat = usedRect.minY + inset - visibleRect.minY
|
||||
let label: NSString = "\(lineIndex)" as NSString
|
||||
let size: CGSize = label.size(withAttributes: attrs)
|
||||
let drawPoint: NSPoint = NSPoint(
|
||||
x: bounds.maxX - size.width - rightInset,
|
||||
y: yInView + ((usedRect.height - size.height) * 0.5)
|
||||
)
|
||||
label.draw(at: drawPoint, withAttributes: attrs)
|
||||
|
||||
let advance: Int = NSMaxRange(lineRange)
|
||||
if advance <= cursor { break } // defensive — empty trailing line
|
||||
cursor = advance
|
||||
lineIndex += 1
|
||||
}
|
||||
}
|
||||
|
||||
// 1-based line number of the character at `loc`. Delegates to
|
||||
// `NSString.enumerateSubstrings(.byLines)` so CR, LF, and CRLF endings are
|
||||
// all counted correctly. Linear in `loc`, runs once per draw on the prefix
|
||||
// that precedes the first visible line.
|
||||
private func lineNumber(at loc: Int, in text: NSString) -> Int {
|
||||
if loc <= 0 { return 1 }
|
||||
var line: Int = 1
|
||||
let prefixRange: NSRange = NSRange(location: 0, length: loc)
|
||||
text.enumerateSubstrings(in: prefixRange,
|
||||
options: [.byLines, .substringNotRequired]) { _, _, _, _ in
|
||||
line += 1
|
||||
}
|
||||
return line
|
||||
}
|
||||
|
||||
private let gutterWidth: CGFloat = 40
|
||||
private let rightInset: CGFloat = 6
|
||||
private let dividerHalfPixel: CGFloat = 0.5 // crisp 1px divider on Retina
|
||||
private let rulerFontSize: CGFloat = 11
|
||||
private let gutterFillColor: NSColor = NSColor.controlBackgroundColor
|
||||
private let gutterDividerColor: NSColor = NSColor.separatorColor
|
||||
private let gutterTextColor: NSColor = NSColor.tertiaryLabelColor
|
||||
private var rulerFont: NSFont {
|
||||
NSFont.monospacedSystemFont(ofSize: rulerFontSize, weight: .regular)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,85 @@
|
||||
// ScratchScopeView.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// LyrebirdUI/LiveCompile
|
||||
//
|
||||
// A compact real-time oscilloscope for the scratch editor's engine panel.
|
||||
// Reimplemented here (rather than reusing `LyrebirdUI.LyrebirdScopeView`) because
|
||||
// the LiveCompile stack must not link `LyrebirdUI` — that would static-fold a
|
||||
// second copy of `LyrebirdSynth`'s ObjC classes. It reads the same core
|
||||
// `ScopeCapture` the engine writes to.
|
||||
|
||||
#if os(macOS)
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Polls a ``ScopeCapture`` at ~30 Hz and draws each captured channel's waveform
|
||||
/// with `Canvas`. Channels stack vertically; channel 0 cyan, channel 1 orange.
|
||||
struct ScratchScopeView: View {
|
||||
|
||||
let capture: ScopeCapture
|
||||
|
||||
@State private var channels: [[Float]] = []
|
||||
|
||||
private static let pollIntervalNs: UInt64 = 33_333_333 // ~30 Hz
|
||||
private static let channelColors: [Color] = [.cyan, .orange, .green, .yellow]
|
||||
private static let backgroundColor: Color = Color(white: 0.08)
|
||||
private static let zeroLineOpacity: Double = 0.25
|
||||
private static let separatorOpacity: Double = 0.3
|
||||
private static let waveformHeightFraction: CGFloat = 0.44
|
||||
|
||||
var body: some View {
|
||||
Canvas { ctx, size in
|
||||
ctx.fill(Path(CGRect(origin: .zero, size: size)),
|
||||
with: .color(ScratchScopeView.backgroundColor))
|
||||
guard !channels.isEmpty else { return }
|
||||
let count: Int = channels.count
|
||||
let rowH: CGFloat = size.height / CGFloat(count)
|
||||
|
||||
for (ch, samples): (Int, [Float]) in channels.enumerated() {
|
||||
let midY: CGFloat = rowH * (CGFloat(ch) + 0.5)
|
||||
let halfH: CGFloat = rowH * ScratchScopeView.waveformHeightFraction
|
||||
|
||||
var guide: Path = Path()
|
||||
guide.move(to: CGPoint(x: 0, y: midY))
|
||||
guide.addLine(to: CGPoint(x: size.width, y: midY))
|
||||
ctx.stroke(guide, with: .color(.white.opacity(ScratchScopeView.zeroLineOpacity)),
|
||||
lineWidth: 0.5)
|
||||
|
||||
if ch < count - 1 {
|
||||
let sepY: CGFloat = rowH * CGFloat(ch + 1)
|
||||
var sep: Path = Path()
|
||||
sep.move(to: CGPoint(x: 0, y: sepY))
|
||||
sep.addLine(to: CGPoint(x: size.width, y: sepY))
|
||||
ctx.stroke(sep, with: .color(.white.opacity(ScratchScopeView.separatorOpacity)),
|
||||
lineWidth: 0.5)
|
||||
}
|
||||
|
||||
guard samples.count > 1 else { continue }
|
||||
let color: Color = ScratchScopeView.channelColors[ch % ScratchScopeView.channelColors.count]
|
||||
let xStep: CGFloat = size.width / CGFloat(samples.count - 1)
|
||||
var path: Path = Path()
|
||||
for (i, sample): (Int, Float) in samples.enumerated() {
|
||||
let x: CGFloat = CGFloat(i) * xStep
|
||||
let y: CGFloat = midY - CGFloat(sample) * halfH
|
||||
if i == 0 { path.move(to: CGPoint(x: x, y: y)) }
|
||||
else { path.addLine(to: CGPoint(x: x, y: y)) }
|
||||
}
|
||||
ctx.stroke(path, with: .color(color), lineWidth: 1.0)
|
||||
}
|
||||
}
|
||||
.background(ScratchScopeView.backgroundColor)
|
||||
.clipShape(RoundedRectangle(cornerRadius: 4))
|
||||
.task {
|
||||
while !Task.isCancelled {
|
||||
channels = capture.snapshot()
|
||||
try? await Task.sleep(nanoseconds: ScratchScopeView.pollIntervalNs)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,141 @@
|
||||
// ToolchainAlert.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import AppKit
|
||||
import LyrebirdLiveCompile
|
||||
|
||||
/// User-facing text for a missing-toolchain warning. Pure/value type so the
|
||||
/// status → message mapping is unit-testable without presenting a modal.
|
||||
public struct ToolchainAlertContent: Equatable {
|
||||
/// Alert title (the `NSAlert.messageText`).
|
||||
public let title: String
|
||||
/// Alert body explaining the problem and the fix (the `NSAlert.informativeText`).
|
||||
public let message: String
|
||||
/// Whether "Install Command Line Tools" is an appropriate remedy (it is for a
|
||||
/// missing toolchain, but not for a present-but-incomplete SDK).
|
||||
public let offersCommandLineToolsInstall: Bool
|
||||
}
|
||||
|
||||
/// Map a toolchain status to alert content, or `nil` when nothing needs saying
|
||||
/// (`.available`). Pure — no side effects.
|
||||
public func toolchainAlertContent(for status: SwiftToolchainStatus) -> ToolchainAlertContent? {
|
||||
let dslNote: String = " The Graph DSL mode works without a toolchain if you'd rather not install one."
|
||||
switch status {
|
||||
case .available:
|
||||
return nil
|
||||
case .missingDeveloperTools:
|
||||
return ToolchainAlertContent(
|
||||
title: "Swift toolchain not found",
|
||||
message: "The Swift scratchpad compiles snippets with swiftc, which needs "
|
||||
+ "Xcode or the Command Line Tools." + dslNote,
|
||||
offersCommandLineToolsInstall: true
|
||||
)
|
||||
case .missingSwiftc:
|
||||
return ToolchainAlertContent(
|
||||
title: "Swift compiler not found",
|
||||
message: "A developer directory is selected, but swiftc could not be resolved. "
|
||||
+ "Install or repair Xcode or the Command Line Tools." + dslNote,
|
||||
offersCommandLineToolsInstall: true
|
||||
)
|
||||
case .missingSDK:
|
||||
return ToolchainAlertContent(
|
||||
title: "macOS SDK not found",
|
||||
message: "swiftc was found but the macOS SDK is missing — your Xcode may be "
|
||||
+ "incomplete. Install a full Xcode." + dslNote,
|
||||
offersCommandLineToolsInstall: false
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// App Store product page for Xcode.
|
||||
private let xcodeAppStoreURL: String = "macappstore://apps.apple.com/app/xcode/id497799835"
|
||||
|
||||
@MainActor
|
||||
extension LyrebirdScratchMenuController {
|
||||
|
||||
/// Probe for a Swift toolchain off the main thread and, if missing, present a
|
||||
/// one-time warning alert with install guidance. Safe no-op when the toolchain is
|
||||
/// available. Called once at launch from `installMainMenu`.
|
||||
public func warnIfSwiftToolchainMissing(probe: ToolchainProbe = ToolchainProbe()) {
|
||||
DispatchQueue.global(qos: .utility).async {
|
||||
let status: SwiftToolchainStatus = probe.status()
|
||||
guard let content: ToolchainAlertContent = toolchainAlertContent(for: status) else { return }
|
||||
DispatchQueue.main.async {
|
||||
LyrebirdScratchMenuController.presentToolchainAlert(content)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Present the toolchain warning as a modal `NSAlert` with install actions.
|
||||
static func presentToolchainAlert(_ content: ToolchainAlertContent) {
|
||||
let alert: NSAlert = NSAlert()
|
||||
alert.messageText = content.title
|
||||
alert.informativeText = content.message
|
||||
alert.alertStyle = .warning
|
||||
|
||||
// Buttons are added in first→last order; NSAlert returns .alertFirstButtonReturn
|
||||
// for the first, +1 for the next, etc.
|
||||
let installButton: NSButton? = content.offersCommandLineToolsInstall
|
||||
? alert.addButton(withTitle: "Install Command Line Tools")
|
||||
: nil
|
||||
let xcodeButton: NSButton = alert.addButton(withTitle: "Get Xcode")
|
||||
let okButton: NSButton = alert.addButton(withTitle: "OK")
|
||||
|
||||
// Make OK the default (Return) so an accidental Return dismisses rather than
|
||||
// launching the installer / App Store. Clearing the other buttons' key
|
||||
// equivalents removes their default-button status.
|
||||
installButton?.keyEquivalent = ""
|
||||
xcodeButton.keyEquivalent = ""
|
||||
okButton.keyEquivalent = "\r"
|
||||
|
||||
let response: NSApplication.ModalResponse = alert.runModal()
|
||||
let firstButton: NSApplication.ModalResponse = .alertFirstButtonReturn
|
||||
let secondButton: NSApplication.ModalResponse =
|
||||
NSApplication.ModalResponse(rawValue: firstButton.rawValue + 1)
|
||||
|
||||
if content.offersCommandLineToolsInstall {
|
||||
if response == firstButton {
|
||||
launchCommandLineToolsInstaller()
|
||||
} else if response == secondButton {
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
// third button = OK: dismiss.
|
||||
} else {
|
||||
if response == firstButton {
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
// second button = OK: dismiss.
|
||||
}
|
||||
}
|
||||
|
||||
/// Launch Apple's Command Line Tools installer (`xcode-select --install`). This
|
||||
/// opens Apple's own GUI installer dialog — the app never installs silently.
|
||||
private static func launchCommandLineToolsInstaller() {
|
||||
let xcodeSelectPath: String = "/usr/bin/xcode-select"
|
||||
// Mirror the executable-file pre-check used by the other subprocess helpers.
|
||||
guard FileManager.default.isExecutableFile(atPath: xcodeSelectPath) else {
|
||||
openXcodeInAppStore()
|
||||
return
|
||||
}
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: xcodeSelectPath)
|
||||
process.arguments = ["--install"]
|
||||
do {
|
||||
try process.run()
|
||||
} catch {
|
||||
// If we can't launch it, fall back to the App Store (Xcode includes the tools).
|
||||
openXcodeInAppStore()
|
||||
}
|
||||
}
|
||||
|
||||
/// Open Xcode's App Store product page.
|
||||
private static func openXcodeInAppStore() {
|
||||
guard let url: URL = URL(string: xcodeAppStoreURL) else { return }
|
||||
NSWorkspace.shared.open(url)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,134 @@
|
||||
// ArtifactStagingTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Verifies that a staged artifacts directory is a self-contained, working
|
||||
/// compile root: a snippet compiled against the staged `-I` / `-L` / rpath
|
||||
/// succeeds without reaching back into the original build tree.
|
||||
@Suite("LiveSession artifact staging")
|
||||
struct ArtifactStagingTests {
|
||||
|
||||
/// The dev SPM build dir the tests run from — the staging source.
|
||||
private func buildDir() -> URL? {
|
||||
LiveSession.currentBuildDir()
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathParses() {
|
||||
let map: String = """
|
||||
module LyrebirdC {
|
||||
umbrella header "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h"
|
||||
export *
|
||||
}
|
||||
"""
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: map) == "/abs/path/Sources/LyrebirdC/include/LyrebirdC.h")
|
||||
}
|
||||
|
||||
@Test func umbrellaHeaderPathNilWhenAbsent() {
|
||||
#expect(LiveSession.umbrellaHeaderPath(in: "module Foo { export * }") == nil)
|
||||
}
|
||||
|
||||
@Test func stageProducesPopulatedRootWithStagedModuleMap() throws {
|
||||
guard let src: URL = buildDir() else {
|
||||
// No build dir discoverable (unusual for a test run) — nothing to stage.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
|
||||
// The staged C module map must point at the staged header copy, not the
|
||||
// original absolute path under the source tree.
|
||||
let stagedMap: URL = dest
|
||||
.appendingPathComponent("LyrebirdC.build", isDirectory: true)
|
||||
.appendingPathComponent("module.modulemap", isDirectory: false)
|
||||
if FileManager.default.fileExists(atPath: stagedMap.path) {
|
||||
let text: String = try String(contentsOf: stagedMap, encoding: .utf8)
|
||||
#expect(text.contains("\(dest.path)/LyrebirdC.headers"))
|
||||
#expect(!text.contains("/Sources/LyrebirdC/include"))
|
||||
}
|
||||
}
|
||||
|
||||
@Test func refusesToClobberNonStagingDir() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
try FileManager.default.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
// A pre-existing file that does NOT look like a staging root.
|
||||
let precious: URL = dest.appendingPathComponent("precious.txt", isDirectory: false)
|
||||
try "keep me".write(to: precious, atomically: true, encoding: .utf8)
|
||||
|
||||
let staged: URL? = LiveSession.stageArtifacts(from: src, to: dest)
|
||||
#expect(staged == nil) // refused
|
||||
#expect(FileManager.default.fileExists(atPath: precious.path)) // untouched
|
||||
}
|
||||
|
||||
@Test func idempotentSecondStageKeepsRoot() throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
// Second call with an unchanged source: still a valid, current root.
|
||||
#expect(LiveSession.stageArtifacts(from: src, to: dest) == dest)
|
||||
#expect(LiveSession.isArtifactsDirPopulated(dest))
|
||||
#expect(LiveSession.stagedDirIsCurrent(dest))
|
||||
}
|
||||
|
||||
@Test func snippetCompilesFromStagedRoot() async throws {
|
||||
guard let src: URL = buildDir() else { return }
|
||||
guard LiveSession.hasLyrebirdDylib(in: src) else {
|
||||
// Xcode-SPM layout (no dylib) — the staged-link path under test needs
|
||||
// the bare-SPM dylib present; skip when absent.
|
||||
return
|
||||
}
|
||||
let dest: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBStageTest-\(UUID().uuidString)", isDirectory: true)
|
||||
defer { try? FileManager.default.removeItem(at: dest) }
|
||||
|
||||
guard let staged: URL = LiveSession.stageArtifacts(from: src, to: dest) else {
|
||||
Issue.record("staging produced no root")
|
||||
return
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
// Point the session ONLY at the staged root — no original build dir.
|
||||
let session: LiveSession = await LiveSession(
|
||||
engine: engine,
|
||||
attachScope: false,
|
||||
importPaths: [staged, staged.appendingPathComponent("Modules")],
|
||||
librarySearchPaths: [staged],
|
||||
libraries: ["LyrebirdDynamic", "LyrebirdLiveCompileDynamic"],
|
||||
rpaths: [staged]
|
||||
)
|
||||
// A trivial snippet that touches the LyrebirdSynth API proves the module
|
||||
// resolves from the staged root.
|
||||
try await session.compileAndRunAsync("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
await session.clearTracked()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -15,8 +15,11 @@ struct DiagnosticParserTests {
|
||||
|
||||
@Test
|
||||
func parsesSingleErrorAtUserBodyLine() throws {
|
||||
// Wrapped snippet preamble is 8 lines; user body starts at line 9.
|
||||
// swiftc reports an error on wrapped line 10 → maps to user line 2.
|
||||
// Representative offset: for a preamble whose user body starts at line 9,
|
||||
// a swiftc error on wrapped line 10 maps to user line 2. (This tests the
|
||||
// parser's arithmetic directly; the actual harness offset — which shifts
|
||||
// when the preamble changes — is exercised by
|
||||
// `endToEndOffsetMatchesSnippetHarness` below.)
|
||||
let stderr: String = "/tmp/Snippet.swift:10:14: error: cannot find 'foo' in scope"
|
||||
let diagnostics: [Diagnostic] = DiagnosticParser.parse(stderr: stderr, userBodyLineOffset: 9)
|
||||
try #require(diagnostics.count == 1)
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// MessageLogTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession message log")
|
||||
struct MessageLogTests {
|
||||
|
||||
private func makeSession() -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LiveSession(engine: engine)
|
||||
}
|
||||
|
||||
@Test func accumulatesAndDrains() {
|
||||
let session: LiveSession = makeSession()
|
||||
session.appendMessage("a")
|
||||
session.appendMessage("b")
|
||||
#expect(session.lastSnippetMessage == "b") // last value, for tests
|
||||
#expect(session.drainMessages() == ["a", "b"])
|
||||
// Drained → empty.
|
||||
#expect(session.lastSnippetMessage == nil)
|
||||
#expect(session.drainMessages().isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,63 @@
|
||||
// ScopeAttachTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession scope attach")
|
||||
struct ScopeAttachTests {
|
||||
|
||||
private func makeEngine(outChannels: Int = 2) -> SynthesisEngine {
|
||||
SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: outChannels,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
}
|
||||
|
||||
@Test func attachesStereoScopeByDefault() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 2)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
let scope: ScopeCapture? = session.scope
|
||||
#expect(scope != nil)
|
||||
#expect(scope?.buses == [0, 1])
|
||||
// Installed on the engine so the RT thread writes to it.
|
||||
#expect(engine.scopeTap === scope)
|
||||
}
|
||||
|
||||
@Test func attachScopeFalseInstallsNothing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
#expect(session.scope == nil)
|
||||
#expect(engine.scopeTap == nil)
|
||||
}
|
||||
|
||||
@Test func monoEngineTapsOneBus() {
|
||||
let engine: SynthesisEngine = makeEngine(outChannels: 1)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
#expect(session.scope?.buses == [0])
|
||||
}
|
||||
|
||||
@Test func reusesExistingTapRatherThanReplacing() {
|
||||
let engine: SynthesisEngine = makeEngine()
|
||||
let existing: ScopeCapture = ScopeCapture(buses: [0], bufferSize: 256)
|
||||
engine.scopeTap = existing
|
||||
let session: LiveSession = LiveSession(engine: engine) // attach on, but a tap exists
|
||||
#expect(session.scope === existing)
|
||||
#expect(engine.scopeTap === existing)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,94 @@
|
||||
// SlotReleaseTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@MainActor
|
||||
@Suite("LiveSession slot release")
|
||||
struct SlotReleaseTests {
|
||||
|
||||
/// A synth whose graceful `release` succeeds (records the call) — stands in
|
||||
/// for a gated `EnvGen` voice.
|
||||
private final class GatedSynth: SynthesizerBase, @unchecked Sendable {
|
||||
var released: Bool = false
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
override func release(engine: SynthesisEngine) throws { released = true }
|
||||
}
|
||||
|
||||
/// A synth with no gate — inherits the default `release` that throws `.noGate`.
|
||||
private final class GatelessSynth: SynthesizerBase, @unchecked Sendable {
|
||||
override func build() { addOutputGenerator(Out.Audio(bus: 0, source: 0.1)) }
|
||||
}
|
||||
|
||||
private func makeStartedSession() throws -> LiveSession {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
try engine.start()
|
||||
return session
|
||||
}
|
||||
|
||||
@Test func releaseGatedSlotTriggersReleaseAndDropsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
let voice: GatedSynth = GatedSynth()
|
||||
try session.swapSlot("pad", synth: voice)
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
|
||||
let released: Bool = session.releaseSlot("pad")
|
||||
#expect(released)
|
||||
#expect(voice.released) // graceful release fired
|
||||
#expect(session.slotNames.contains("pad") == false) // handle dropped, name free
|
||||
// Safety net: the released voice moves to the tracked list so it stays
|
||||
// reclaimable by resetAll() / Clear Synths even if it never self-frees.
|
||||
#expect(session.trackedSynthCount == 1)
|
||||
session.resetAll()
|
||||
#expect(session.trackedSynthCount == 0)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func nameIsReusableAfterRelease() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.releaseSlot("pad"))
|
||||
// The name is free again — a fresh voice claims the slot cleanly.
|
||||
try session.swapSlot("pad", synth: GatedSynth())
|
||||
#expect(session.slotNames.contains("pad"))
|
||||
#expect(session.slotCount == 1)
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseGatelessSlotFailsAndKeepsHandle() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
try session.swapSlot("bass", synth: GatelessSynth())
|
||||
|
||||
let released: Bool = session.releaseSlot("bass")
|
||||
#expect(released == false)
|
||||
// Not orphaned — still in the slot, still stoppable with a hard clear.
|
||||
#expect(session.slotNames.contains("bass"))
|
||||
#expect(session.clearSlot("bass"))
|
||||
session.engine.stop()
|
||||
}
|
||||
|
||||
@Test func releaseEmptySlotReturnsFalse() throws {
|
||||
let session: LiveSession = try makeStartedSession()
|
||||
#expect(session.releaseSlot("nothing-here") == false)
|
||||
session.engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -16,6 +16,9 @@ struct SnippetHarnessTests {
|
||||
@Test
|
||||
func wrappedSourceContainsPreambleAndUserBody() {
|
||||
let wrapped: WrappedSnippet = SnippetHarness.wrap(userBody: "context.reportMessage(\"hello\")")
|
||||
// Foundation so snippets can use `pow`, `sin`, `Date`, … without an import
|
||||
// (a snippet can't declare one — its body is inside the entry function).
|
||||
#expect(wrapped.source.contains("import Foundation"))
|
||||
#expect(wrapped.source.contains("import LyrebirdSynth"))
|
||||
#expect(wrapped.source.contains("import LyrebirdLiveCompile"))
|
||||
#expect(wrapped.source.contains("@_cdecl(\"lyrebird_snippet_entry\")"))
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// SnippetScheduledLoopTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
/// Proves the scratch editor runs *functional* Swift — a real `for` loop that
|
||||
/// schedules a timed sequence — not just single-graph expressions.
|
||||
@MainActor
|
||||
@Suite("Snippet scheduled loop")
|
||||
struct SnippetScheduledLoopTests {
|
||||
|
||||
@Test func snippetCanUseFoundationMath() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 44_100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine, attachScope: false)
|
||||
try engine.start()
|
||||
// `pow` / `sin` come from Foundation, which the harness preamble imports —
|
||||
// a snippet can't add the import itself. This would fail to compile
|
||||
// ("cannot find 'pow' in scope") without it.
|
||||
let snippet: String = """
|
||||
let semitone: Double = pow(2.0, 1.0 / 12.0)
|
||||
let freq: Double = 440.0 * semitone
|
||||
context.play { OscSin.Audio(freq: freq) * (0.1 * sin(0.0) + 0.1) }
|
||||
context.reportMessage("math ok \\(freq)")
|
||||
"""
|
||||
try session.compileAndRun(snippet)
|
||||
#expect(session.lastSnippetMessage?.hasPrefix("math ok") == true)
|
||||
session.clearTracked()
|
||||
}
|
||||
|
||||
@Test func loopSchedulesTenSelfFreeingTones() throws {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 512,
|
||||
controlBlockSize: 64,
|
||||
sampleRate: 44_100,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
let session: LiveSession = LiveSession(engine: engine)
|
||||
try engine.start()
|
||||
|
||||
// A `for` loop that schedules ten short sine tones, 0.35 s apart. Each is
|
||||
// a decaying amplitude envelope (`Line` with `doneAction: .freeNode`)
|
||||
// times a sine, so it plays ~0.2 s and then frees itself — no manual
|
||||
// cleanup, no blocking the main thread.
|
||||
let snippet: String = """
|
||||
let scale: [Double] = [261.63, 293.66, 329.63, 349.23, 392.0,
|
||||
440.0, 493.88, 523.25, 587.33, 659.25]
|
||||
for i in 0..<10 {
|
||||
let freq: Double = scale[i]
|
||||
let tone = ClosureSynthesizer {
|
||||
Line.Control(start: 0.25, end: 0.0, dur: 0.2, doneAction: .freeNode)
|
||||
* OscSin.Audio(freq: freq)
|
||||
}
|
||||
do { try context.engine.schedule(tone, after: Double(i) * 0.35) }
|
||||
catch { context.reportMessage("schedule failed: \\(error)") }
|
||||
}
|
||||
context.reportMessage("scheduled 10 tones")
|
||||
"""
|
||||
|
||||
try session.compileAndRun(snippet)
|
||||
// The `for` loop and the scheduling calls compiled and ran.
|
||||
#expect(session.lastSnippetMessage == "scheduled 10 tones")
|
||||
|
||||
// Advance ~4.5 s of audio; the scheduled adds fire over time. (Each
|
||||
// tone's `.freeNode` self-frees via the engine's async auto-free watcher
|
||||
// in the running app — that background timer doesn't get a turn inside
|
||||
// this synchronous processBlock loop, so here the tones accumulate; the
|
||||
// auto-free path itself is covered by `AutoFreeOnDoneTests`.)
|
||||
let blocks: Int = Int(4.5 * 44_100 / 512)
|
||||
var peakActive: Int = 0
|
||||
var producedAudio: Bool = false
|
||||
for _ in 0..<blocks {
|
||||
engine.processBlock(inputSamples: [])
|
||||
peakActive = max(peakActive, engine.synthesizerCount)
|
||||
if engine.audioBuses[0].contains(where: { $0 != 0 }) { producedAudio = true }
|
||||
}
|
||||
|
||||
#expect(peakActive == 10, "all ten scheduled tones should have entered the tree over time")
|
||||
#expect(producedAudio, "the scheduled tones should have written audio to the bus")
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,52 @@
|
||||
// SwiftFormatterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("SwiftFormatter")
|
||||
struct SwiftFormatterTests {
|
||||
|
||||
@Test func formatsMessySource() throws {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let messy: String = "let x=1\nstruct Foo{let a:Int}\n"
|
||||
let formatted: String = try SwiftFormatter.format(source: messy)
|
||||
// Canonical spacing appears; the mangled originals are gone.
|
||||
#expect(formatted.contains("let x = 1"))
|
||||
#expect(!formatted.contains("let x=1"))
|
||||
#expect(!formatted.contains("struct Foo"))
|
||||
}
|
||||
|
||||
@Test func alreadyFormattedIsStable() throws {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
let clean: String = "let x = 1\n"
|
||||
let once: String = try SwiftFormatter.format(source: clean)
|
||||
let twice: String = try SwiftFormatter.format(source: once)
|
||||
#expect(once == twice) // idempotent
|
||||
}
|
||||
|
||||
@Test func parseErrorThrowsFormatFailed() {
|
||||
guard SwiftFormatter.isAvailable else { return }
|
||||
// Unbalanced brace — swift-format should exit non-zero.
|
||||
let broken: String = "func f( {\n"
|
||||
var caught: SwiftFormatterError?
|
||||
do {
|
||||
_ = try SwiftFormatter.format(source: broken)
|
||||
} catch let error as SwiftFormatterError {
|
||||
caught = error
|
||||
} catch {
|
||||
Issue.record("unexpected error type: \(error)")
|
||||
}
|
||||
guard case .formatFailed = caught else {
|
||||
Issue.record("expected .formatFailed, got \(String(describing: caught))")
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,54 @@
|
||||
// ToolchainProbeTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
@testable import LyrebirdLiveCompile
|
||||
|
||||
@Suite("ToolchainProbe")
|
||||
struct ToolchainProbeTests {
|
||||
|
||||
private func probe(swiftc: String?, sdk: String?, devDir: String?) -> ToolchainProbe {
|
||||
ToolchainProbe(
|
||||
swiftcResolver: { swiftc },
|
||||
sdkResolver: { sdk },
|
||||
developerDirResolver: { devDir }
|
||||
)
|
||||
}
|
||||
|
||||
@Test("swiftc + SDK both present → available")
|
||||
func availableWhenBothResolve() {
|
||||
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: "/SDK", devDir: "/Dev").status() == .available)
|
||||
}
|
||||
|
||||
@Test("no swiftc and no developer dir → missingDeveloperTools")
|
||||
func missingDeveloperTools() {
|
||||
#expect(probe(swiftc: nil, sdk: nil, devDir: nil).status() == .missingDeveloperTools)
|
||||
}
|
||||
|
||||
@Test("no swiftc but developer dir present → missingSwiftc")
|
||||
func missingSwiftc() {
|
||||
#expect(probe(swiftc: nil, sdk: nil, devDir: "/Dev").status() == .missingSwiftc)
|
||||
// SDK value is irrelevant when swiftc is unresolved.
|
||||
#expect(probe(swiftc: nil, sdk: "/SDK", devDir: "/Dev").status() == .missingSwiftc)
|
||||
}
|
||||
|
||||
@Test("swiftc present but SDK missing → missingSDK")
|
||||
func missingSDK() {
|
||||
#expect(probe(swiftc: "/usr/bin/swiftc", sdk: nil, devDir: "/Dev").status() == .missingSDK)
|
||||
}
|
||||
|
||||
@Test("default probe on a build machine finds developer tools")
|
||||
func defaultProbeFindsDeveloperTools() {
|
||||
// Any machine that can build/test this package has a developer directory, so
|
||||
// the real (non-injected) resolvers must never report missingDeveloperTools —
|
||||
// this smoke-tests that the default xcode-select / xcrun probes actually run.
|
||||
// (Not asserting strict `.available`: a full-SDK requirement would couple the
|
||||
// suite to the host's exact toolchain completeness.)
|
||||
#expect(ToolchainProbe().status() != .missingDeveloperTools)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -64,7 +64,9 @@ struct LyrebirdScratchModelTests {
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
#expect(model.statusMessage.contains("replaced"))
|
||||
#expect(model.statusMessage.contains("Tracked synths: 0"))
|
||||
#expect(session.lastSnippetMessage == "hello")
|
||||
// The report message is drained from the session into the console.
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello" })
|
||||
#expect(session.lastSnippetMessage == nil) // drained
|
||||
#expect(model.isCompiling == false)
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
// RenderOptionsAccessoryTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
// Serialized: these tests mutate a shared `UserDefaults` key (the persisted
|
||||
// last-format), so they must not interleave.
|
||||
@Suite("RenderOptionsAccessory", .serialized)
|
||||
@MainActor
|
||||
struct RenderOptionsAccessoryTests {
|
||||
|
||||
// Popup order (see RenderOptionsAccessory.options).
|
||||
private let wavFloat32Index: Int = 0
|
||||
private let wavInt24Index: Int = 2
|
||||
private let rf64Float32Index: Int = 5
|
||||
|
||||
private func makeAccessory() -> (RenderOptionsAccessory, NSSavePanel) {
|
||||
let panel: NSSavePanel = NSSavePanel()
|
||||
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
|
||||
baseName: "render", initialDuration: 5.0, savePanel: panel
|
||||
)
|
||||
return (accessory, panel)
|
||||
}
|
||||
|
||||
// MARK: - Duration parsing
|
||||
|
||||
@Test("parseDuration accepts positive finite numbers and rejects the rest")
|
||||
func durationParsing() {
|
||||
#expect(RenderOptionsAccessory.parseDuration("5.0") == 5.0)
|
||||
#expect(RenderOptionsAccessory.parseDuration(" 2.5 ") == 2.5)
|
||||
#expect(RenderOptionsAccessory.parseDuration("0") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("-1") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("abc") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("nan") == nil)
|
||||
#expect(RenderOptionsAccessory.parseDuration("inf") == nil)
|
||||
}
|
||||
|
||||
// MARK: - Format read-out
|
||||
|
||||
@Test("Selecting a format updates selectedFormat")
|
||||
func selectedFormatReflectsPopup() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(accessory.selectedFormat == .wavFloat32)
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(accessory.selectedFormat == .wavInt24)
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(accessory.selectedFormat == .rf64Float32)
|
||||
}
|
||||
|
||||
// MARK: - Panel filename sync
|
||||
|
||||
@Test("Changing format preserves a user-typed filename stem")
|
||||
func formatChangePreservesUserStem() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
|
||||
// User renames the target, then switches format.
|
||||
panel.nameFieldStringValue = "mySound.caf"
|
||||
accessory.selectFormatForTesting(at: wavFloat32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav")
|
||||
|
||||
// Switching again keeps the stem, swaps only the extension.
|
||||
accessory.selectFormatForTesting(at: rf64Float32Index)
|
||||
#expect(panel.nameFieldStringValue == "mySound.wav") // RF64 keeps .wav
|
||||
}
|
||||
|
||||
@Test("Empty filename falls back to the base name")
|
||||
func emptyStemFallsBackToBaseName() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
panel.nameFieldStringValue = ""
|
||||
accessory.selectFormatForTesting(at: wavInt24Index)
|
||||
#expect(panel.nameFieldStringValue == "render.wav")
|
||||
}
|
||||
|
||||
// MARK: - Persistence
|
||||
|
||||
@Test("Last-selected format persists to a fresh accessory")
|
||||
func formatSelectionPersists() {
|
||||
RenderOptionsAccessory.clearPersistedFormatForTesting()
|
||||
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
|
||||
|
||||
let (first, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
first.selectFormatForTesting(at: rf64Float32Index) // persists "rf64F32"
|
||||
|
||||
// A brand-new accessory should open on the remembered format.
|
||||
let (second, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
|
||||
#expect(second.selectedFormat == .rf64Float32)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -0,0 +1,76 @@
|
||||
// ScratchModelConsoleTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel console")
|
||||
@MainActor
|
||||
struct ScratchModelConsoleTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func successfulRunLogsInfo() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func failedRunLogsErrorEntries() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "NotAGenerator(freq: 1)")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
#expect(model.consoleEntries.contains { $0.text.contains("NotAGenerator") })
|
||||
}
|
||||
|
||||
@Test func reportMessagesAppearAsMessages() async {
|
||||
// A DSL run pushes no messages; drive the log directly to prove the
|
||||
// message → console wiring (drainMessages → .message entries).
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
model.session.appendMessage("hello from snippet")
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.consoleEntries.contains { $0.kind == .message && $0.text == "hello from snippet" })
|
||||
}
|
||||
|
||||
@Test func clearConsoleEmpties() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.clearConsole()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
|
||||
@Test func resetSessionClearsConsole() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false)
|
||||
#expect(!model.consoleEntries.isEmpty)
|
||||
model.resetSession()
|
||||
#expect(model.consoleEntries.isEmpty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,48 @@
|
||||
// ScratchModelFormatTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel formatting")
|
||||
@MainActor
|
||||
struct ScratchModelFormatTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func formatRewritesMessyBufferAndLogs() async {
|
||||
guard SwiftFormatter.isAvailable else { return } // no toolchain formatter — skip
|
||||
let model: LyrebirdScratchModel = makeModel(text: "let x=1\n")
|
||||
await model.formatBuffer()
|
||||
#expect(model.text.contains("let x = 1"))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
}
|
||||
|
||||
@Test func formatBlankBufferIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let before: String = model.text
|
||||
await model.formatBuffer()
|
||||
#expect(model.text == before)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,125 @@
|
||||
// ScratchModelRenderTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel render-to-file")
|
||||
@MainActor
|
||||
struct ScratchModelRenderTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine, attachScope: false), initialText: text)
|
||||
}
|
||||
|
||||
@Test func rendersWholeBufferToCAF() async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let duration: Double = 0.25
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: duration)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .info })
|
||||
|
||||
// The CAF should hold roughly `duration` seconds at the engine's rate.
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
guard let fileRef: ExtAudioFileRef = fileRef else {
|
||||
Issue.record("could not open rendered CAF")
|
||||
return
|
||||
}
|
||||
defer { ExtAudioFileDispose(fileRef) }
|
||||
var frames: Int64 = 0
|
||||
var size: UInt32 = UInt32(MemoryLayout<Int64>.size)
|
||||
#expect(ExtAudioFileGetProperty(fileRef, kExtAudioFileProperty_FileLengthFrames, &size, &frames) == noErr)
|
||||
// Allow a block of slack either way.
|
||||
let expected: Double = duration * 48_000
|
||||
#expect(Double(frames) > expected - 128 && Double(frames) < expected + 512)
|
||||
}
|
||||
|
||||
@Test func rendersSelectionWhenPresent() async {
|
||||
// Whole buffer has two statements; select only the first and render it.
|
||||
let model: LyrebirdScratchModel = makeModel(
|
||||
text: "context.play { OscSin.Audio(freq: 440) * 0.1 }\ncontext.play { OscSin.Audio(freq: 880) * 0.1 }")
|
||||
model.updateSelection("context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
#expect(model.hasSelection)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
@Test func nonPositiveDurationFails() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
#expect(model.consoleEntries.contains { $0.kind == .error })
|
||||
}
|
||||
|
||||
@Test func blankBufferRendersNothing() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: " \n")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString).caf")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
let ok: Bool = await model.renderToFile(url: url, duration: 0.1)
|
||||
#expect(!ok)
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
|
||||
/// The `format:` argument reaches the NRT driver: rendering to a WAV Int24 target
|
||||
/// and an RF64 target produces files with the requested on-disk encoding.
|
||||
@Test(arguments: [
|
||||
(AudioFileFormat.wavInt24, "wav", UInt32(24), false),
|
||||
(AudioFileFormat.rf64Float32, "wav", UInt32(32), true),
|
||||
])
|
||||
func rendersHonourFormat(format: AudioFileFormat, ext: String, bits: UInt32, isFloat: Bool) async throws {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent("LBRenderTest-\(UUID().uuidString)").appendingPathExtension(ext)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let ok: Bool = await model.renderToFile(url: url, format: format, duration: 0.1)
|
||||
#expect(ok)
|
||||
#expect(FileManager.default.fileExists(atPath: url.path))
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mBitsPerChannel == bits)
|
||||
#expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,58 @@
|
||||
// ScratchModelResetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel resetSession")
|
||||
@MainActor
|
||||
struct ScratchModelResetTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func resetStopsAudioAndClearsDiagnosticsButKeepsBuffer() async {
|
||||
let source: String = "OscSin(freq: 440) * 0.1"
|
||||
let model: LyrebirdScratchModel = makeModel(text: source)
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
model.resetSession()
|
||||
|
||||
#expect(model.trackedSynthCount == 0) // audio stopped
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
// Non-destructive: the user's buffer is preserved.
|
||||
#expect(model.text == source)
|
||||
#expect(model.statusMessage.contains("reset"))
|
||||
}
|
||||
|
||||
@Test func resetLeavesAFreshDirtyBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
model.resetSession()
|
||||
// The placeholder buffer was never run in this fresh session → .dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
// ScratchModelRunSelectionTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
@testable import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("LyrebirdScratchModel run selection")
|
||||
@MainActor
|
||||
struct ScratchModelRunSelectionTests {
|
||||
|
||||
private func makeModel(text: String) -> LyrebirdScratchModel {
|
||||
let engine: SynthesisEngine = SynthesisEngine(
|
||||
blockSize: 64,
|
||||
controlBlockSize: 16,
|
||||
sampleRate: 48_000,
|
||||
numOutputChannels: 2,
|
||||
numInputChannels: 0,
|
||||
numAudioBuses: 16,
|
||||
numControlBuses: 16,
|
||||
eventQueueCapacity: lyrebirdDefaultEventQueueCapacity,
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
return LyrebirdScratchModel(session: LiveSession(engine: engine), initialText: text)
|
||||
}
|
||||
|
||||
@Test func hasSelectionReflectsNonWhitespaceSelection() {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
#expect(model.hasSelection)
|
||||
model.updateSelection(" \n ") // whitespace only
|
||||
#expect(model.hasSelection == false)
|
||||
model.updateSelection("")
|
||||
#expect(model.hasSelection == false)
|
||||
}
|
||||
|
||||
@Test func runSelectionWithNoSelectionIsNoOp() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(model.trackedSynthCount == 0)
|
||||
}
|
||||
|
||||
@Test func runSelectionAddsToRunningWithoutDisturbingBaseline() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
|
||||
// Whole-buffer run establishes the baseline → clean, one synth.
|
||||
_ = await model.run(additive: false)
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.trackedSynthCount == 1)
|
||||
|
||||
// Run a selected fragment: additive (adds a second synth) and leaves the
|
||||
// whole-buffer baseline intact (buffer still matches the last whole run).
|
||||
model.updateSelection("OscSin(freq: 220) * 0.1")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok)
|
||||
#expect(model.trackedSynthCount == 2)
|
||||
#expect(model.reevalState == .clean) // baseline untouched
|
||||
#expect(model.diagnostics.isEmpty)
|
||||
}
|
||||
|
||||
@Test func selectionRunAddsEvenFromADirtyBuffer() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // tracked 1, .clean
|
||||
// Dirty the buffer (edited since the last whole run).
|
||||
model.text = "OscSin(freq: 440) * 0.1\n# edited"
|
||||
#expect(model.reevalState == .dirty)
|
||||
|
||||
model.updateSelection("OscSin(freq: 330) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 2
|
||||
model.updateSelection("OscSin(freq: 110) * 0.1")
|
||||
_ = await model.runSelection() // additive → tracked 3
|
||||
#expect(model.trackedSynthCount == 3)
|
||||
// The selection runs never replaced, and the buffer stays dirty.
|
||||
#expect(model.reevalState == .dirty)
|
||||
}
|
||||
|
||||
@Test func failedSelectionRunLeavesWholeBufferBadgeUntouched() async {
|
||||
let model: LyrebirdScratchModel = makeModel(text: "OscSin(freq: 440) * 0.1")
|
||||
model.switchMode(to: .graphDSL)
|
||||
_ = await model.run(additive: false) // .clean
|
||||
#expect(model.reevalState == .clean)
|
||||
|
||||
// A selection with an unknown generator fails to build.
|
||||
model.updateSelection("NotAGenerator(freq: 1)")
|
||||
let ok: Bool = await model.runSelection()
|
||||
#expect(ok == false)
|
||||
#expect(!model.diagnostics.isEmpty)
|
||||
// The whole-buffer badge must stay clean — the buffer itself is fine.
|
||||
#expect(model.reevalState == .clean)
|
||||
#expect(model.statusMessage.hasPrefix("Selection"))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -38,14 +38,49 @@ struct ScratchTextViewTests {
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// Mid-identifier (no preceding dot) falls through to the default behavior,
|
||||
/// which covers the whole partial word so it gets replaced on completion.
|
||||
@Test func partialIdentifierUsesDefaultWordRange() {
|
||||
/// Mid-identifier (no preceding dot): the range covers the run of identifier
|
||||
/// characters before the caret, so the partial word gets replaced.
|
||||
@Test func partialIdentifierCoversWordRange() {
|
||||
let tv: ScratchTextView = makeTextView("OscSi", caret: 5)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// Default range spans the partial word `OscSi` (length 5 from offset 0).
|
||||
#expect(range == NSRange(location: 0, length: 5))
|
||||
}
|
||||
|
||||
/// Right after an open paren, the range is EMPTY at the caret — an argument
|
||||
/// label (`freq:`) inserts there instead of replacing the receiver
|
||||
/// (`OscSin.Audio(` → erases `OscSin.Audio` bug).
|
||||
@Test func afterOpenParenRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio("
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// After a comma + space (next argument position), the range is empty too.
|
||||
@Test func afterCommaSpaceRangeIsEmptyAtCaret() {
|
||||
let text: String = "OscSin.Audio(freq: 440, "
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: text.utf16.count, length: 0))
|
||||
}
|
||||
|
||||
/// A partial argument label inside parens replaces just that partial word,
|
||||
/// not the receiver expression.
|
||||
@Test func partialArgLabelCoversOnlyThePartial() {
|
||||
let text: String = "OscSin.Audio(fr"
|
||||
let tv: ScratchTextView = makeTextView(text, caret: text.utf16.count)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
// `fr` starts at offset 13 (after `OscSin.Audio(`), length 2.
|
||||
#expect(range == NSRange(location: 13, length: 2))
|
||||
}
|
||||
|
||||
/// Underscore is an identifier character, so a leading-underscore partial is
|
||||
/// covered whole.
|
||||
@Test func underscoreIsIdentifierChar() {
|
||||
let tv: ScratchTextView = makeTextView("_foo", caret: 4)
|
||||
let range: NSRange = tv.rangeForUserCompletion
|
||||
#expect(range == NSRange(location: 0, length: 4))
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
// ToolchainAlertTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#if os(macOS)
|
||||
import Testing
|
||||
import LyrebirdLiveCompile
|
||||
@testable import LyrebirdLiveCompileUI
|
||||
|
||||
@Suite("ToolchainAlert content")
|
||||
struct ToolchainAlertTests {
|
||||
|
||||
@Test("available status produces no alert content")
|
||||
func availableIsNil() {
|
||||
#expect(toolchainAlertContent(for: .available) == nil)
|
||||
}
|
||||
|
||||
@Test("missing-toolchain statuses offer the Command Line Tools install")
|
||||
func missingOffersCLTInstall() {
|
||||
for status: SwiftToolchainStatus in [.missingDeveloperTools, .missingSwiftc] {
|
||||
let content: ToolchainAlertContent? = toolchainAlertContent(for: status)
|
||||
#expect(content != nil)
|
||||
#expect(content?.offersCommandLineToolsInstall == true)
|
||||
#expect(content?.title.isEmpty == false)
|
||||
// Steers the user to the dependency-free fallback.
|
||||
#expect(content?.message.contains("Graph DSL") == true)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("missing-SDK does not offer CLT install (needs a full Xcode)")
|
||||
func missingSDKNoCLT() {
|
||||
let content: ToolchainAlertContent? = toolchainAlertContent(for: .missingSDK)
|
||||
#expect(content != nil)
|
||||
#expect(content?.offersCommandLineToolsInstall == false)
|
||||
#expect(content?.message.contains("Xcode") == true)
|
||||
}
|
||||
}
|
||||
#endif
|
||||
@@ -20,7 +20,7 @@
|
||||
location = "group:Demos/LyrebirdAUv3Demo/LyrebirdAUv3Demo.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScratchDemo/LyrebirdScratchDemo.xcodeproj">
|
||||
location = "group:Demos/LyrebirdScratch/LyrebirdScratch.xcodeproj">
|
||||
</FileRef>
|
||||
<FileRef
|
||||
location = "group:Demos/LyrebirdScoreDemo/LyrebirdScoreDemo.xcodeproj">
|
||||
|
||||
@@ -100,7 +100,7 @@ tone.amp = 0.1
|
||||
engine.remove(tone) // fades out at the next block boundary
|
||||
```
|
||||
|
||||
Prefer a GUI? The `LyrebirdScratchDemo` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
Prefer a GUI? The `LyrebirdScratch` app embeds `LyrebirdScratchView`: type a snippet, press **⌘↩** to compile-and-hot-swap it against the live engine (or **⌘⇧↩** to layer additively). Each snippet receives a `SnippetContext` — `context.engine` and `context.play(_:)`:
|
||||
|
||||
```swift
|
||||
// Snippet body — `context: SnippetContext` is in scope.
|
||||
@@ -176,7 +176,7 @@ Workspace scheme selector exposes ten entries:
|
||||
| `LyrebirdNRTDemo` | CLI — offline render to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdScoreDemo` | CLI — builds notated `Score`s (result-builder DSL), exports MusicXML, renders to CAF via `NRTDriver` | macOS |
|
||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension. | macOS |
|
||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
| `LyrebirdScratch` | Live-coding scratchpad — type Swift snippets, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
Use `Lyrebird-Package` for day-to-day development of the engine and tests.
|
||||
|
||||
@@ -218,7 +218,7 @@ All eight live in [`Demos/`](Demos/). Open via `Lyrebird.xcworkspace`.
|
||||
| [`LyrebirdNRTDemo`](Demos/LyrebirdNRTDemo/) | CLI — offline render to CAF file via `NRTDriver` | macOS |
|
||||
| [`LyrebirdScoreDemo`](Demos/LyrebirdScoreDemo/) | CLI — notated `Score` → MusicXML export + offline render to CAF via `NRTDriver` | macOS |
|
||||
| [`LyrebirdAUv3Demo`](Demos/LyrebirdAUv3Demo/) | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as `LyrebirdAudioUnit`, loadable in Logic, GarageBand, AUM, Loopy Pro | macOS |
|
||||
| [`LyrebirdScratchDemo`](Demos/LyrebirdScratchDemo/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
| [`LyrebirdScratch`](Demos/LyrebirdScratch/) | Live-coding scratchpad — type Swift, ⌘↩ compiles and runs against the engine, ⌘⇧↩ additive | macOS |
|
||||
|
||||
Each demo has a `Synthesizers/` folder — drop new `SynthesizerBase` subclasses there. See [`LYREBIRD_START_HERE.md`](LYREBIRD_START_HERE.md) for step-by-step instructions and per-demo notes.
|
||||
|
||||
@@ -284,7 +284,7 @@ LyrebirdII/
|
||||
│ ├── LyrebirdNRTDemo/ # offline renderer
|
||||
│ ├── LyrebirdScoreDemo/ # notated Score → MusicXML + offline render
|
||||
│ ├── LyrebirdAUv3Demo/ # AUv3 `aumu` plugin reference (LyrebirdFM)
|
||||
│ └── LyrebirdScratchDemo/ # live-coding scratchpad (macOS, no sandbox)
|
||||
│ └── LyrebirdScratch/ # live-coding scratchpad (macOS, no sandbox)
|
||||
├── Tests/
|
||||
│ ├── LyrebirdTests/ # 5253 engine + generator tests
|
||||
│ ├── LyrebirdUITests/ # SwiftUI component tests
|
||||
|
||||
@@ -7,6 +7,372 @@ functionality in a backward-compatible way.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.1 — Neural-amp model importer
|
||||
|
||||
A patch release. One backward-compatible addition:
|
||||
|
||||
- **`ProteusModelImporter`** — loads a GuitarML **Proteus / NeuralPi** model JSON (single-layer
|
||||
LSTM capture) into a `NeuralAmpModel` for `LSTMAmp`. The state-dict tensors map straight onto
|
||||
`NeuralAmpModel`'s layout (PyTorch gate order; `skip` → residual); unsupported topologies and
|
||||
inconsistent tensor shapes throw. Model files are user-supplied — none are bundled (GuitarML
|
||||
models are GPL-3.0). A binary NAM `.nam` importer remains future work.
|
||||
|
||||
---
|
||||
|
||||
## 1.7.0 — Amp-modeling core: tone stack, triode stage, neural amp
|
||||
|
||||
A minor release. Three new, backward-compatible generators — the DSP core for guitar-amp
|
||||
modeling (consumed by the ShoeGaze 2.0 amp pedals):
|
||||
|
||||
- **`ToneStack`** — passive Fender/Marshall/Vox tone stack (bass/mid/treble). Models the
|
||||
interactive RC network as a whole (Yeh & Smith closed form → bilinear → 3rd-order IIR), so the
|
||||
controls load each other exactly as on the real amp. Model-selectable via `ToneStackModel`.
|
||||
- **`TriodeStage`** — tube-style preamp gain stage: a biased asymmetric `tanh` soft-clip (grid
|
||||
bias → even-harmonic warmth) evaluated at 2×/4× oversampling, with an output coupling
|
||||
(DC-block) high-pass. A musically-voiced static waveshaper; a full wave-digital triode remains
|
||||
future work.
|
||||
- **`LSTMAmp`** + `NeuralAmpModel` — real-time neural amp-capture inference (single-layer LSTM,
|
||||
GuitarML Proteus / NeuralPi topology), pure Swift, RT-safe (pre-allocated weights, no
|
||||
render-thread allocation). `NeuralAmpModel` is a `Codable` weight container with a validating
|
||||
decoder. An importer for external NAM `.nam` / Proteus JSON files is planned for a later release.
|
||||
|
||||
All three are additive; existing code is unaffected.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.4 — `LookAheadLimiter` release time decoupled from look-ahead
|
||||
|
||||
A patch release. One backward-compatible library addition.
|
||||
|
||||
`LookAheadLimiter` gains a `releaseTime` parameter, independent of
|
||||
`lookAheadTime`:
|
||||
|
||||
```swift
|
||||
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
|
||||
```
|
||||
|
||||
Previously the gain-release one-pole coefficient was derived from
|
||||
`lookAheadTime` (default 5 ms), so the release was fast enough to modulate the
|
||||
gain within a single cycle of a low-frequency signal — audible as distortion on
|
||||
sustained bass when the limiter was driven hard. `releaseTime` (default
|
||||
`0.050`) is now a separate control, read per block from a `ValidGeneratorInput`
|
||||
so it can be driven by a live parameter / knob. The look-ahead window size and
|
||||
the no-overshoot ceiling guarantee are unchanged.
|
||||
|
||||
The new parameter has a default, so existing call sites are source-compatible.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.3 — Notarization-ready `macos-ui-xcode` template
|
||||
|
||||
A patch release. Project-scaffolding fixes; no library API changes.
|
||||
|
||||
The `macos-ui-xcode` template (`lyrebird new MyApp --template macos-ui-xcode`)
|
||||
now scaffolds a distributable, notarization-ready macOS performance app out of
|
||||
the box:
|
||||
|
||||
- **Entitlements shipped and wired** — `<name>.entitlements` grants
|
||||
`com.apple.security.device.audio-input` (wired via `CODE_SIGN_ENTITLEMENTS`
|
||||
in both build configs), plus `NSMicrophoneUsageDescription` in `Info.plist`.
|
||||
Under the Hardened Runtime (already enabled) the OS hard-kills the process the
|
||||
moment the AUHAL input bus opens without these. They are harmless for
|
||||
output-only synths — no permission prompt fires until input is actually used.
|
||||
The app is deliberately **unsandboxed**: a live-performance app needs
|
||||
unrestricted audio-device / file / MIDI / OSC access the App Sandbox gates.
|
||||
|
||||
- **Compiles under Swift 6** — fixed a latent actor-isolation error that kept
|
||||
the generated project from building: `NoteController` (calls the engine's
|
||||
`@MainActor add(_:)`) and `AppDelegate` (constructs the main-actor controller
|
||||
and synth) are now `@MainActor`. Xcode app templates are excluded from the
|
||||
`swift build` CI matrix, so this had never been compile-checked; it is now
|
||||
verified end-to-end with `xcodebuild`.
|
||||
|
||||
A normal Lyrebird app needs no module-bundling: Lyrebird is statically linked
|
||||
from SPM source. (The swiftmodule / `LyrebirdC` bundling in `LyrebirdScratch`,
|
||||
added in 1.6.2, is unique to its runtime `swiftc` scratchpad.)
|
||||
|
||||
---
|
||||
|
||||
## 1.6.2 — Live Scratch: distributable / notarized app
|
||||
|
||||
A patch release. Live Scratch packaging only; no library API changes.
|
||||
|
||||
A notarized, moved-off-the-build-machine `LyrebirdScratch.app` could not compile
|
||||
snippets — the Swift scratchpad shells out to `swiftc`, and the modules it needs
|
||||
(`LyrebirdSynth`, `LyrebirdLiveCompile`, and the `LyrebirdC` C-shim they depend on)
|
||||
lived only in the dev build tree. Two failures surfaced in order — `no such module
|
||||
'LyrebirdSynth'`, then `missing required module 'LyrebirdC'`. Both are now fixed:
|
||||
|
||||
- **Swiftmodules bundled** — a build phase copies the Lyrebird `.swiftmodule`s into
|
||||
`Resources/LyrebirdArtifacts/Modules` inside the app, and the live compiler adds
|
||||
that directory to its import search path.
|
||||
- **LyrebirdC module relocatable** — the SPM *source* `module.modulemap` (relative
|
||||
header path, so map + `include/` are self-contained) is bundled into
|
||||
`LyrebirdArtifacts/LyrebirdC.build/`, and staging copies relative-header module
|
||||
maps verbatim so the Clang module resolves from the bundle rather than the
|
||||
absolute dev path Xcode's generated map baked in.
|
||||
|
||||
Verified end-to-end: a snippet compile resolving modules **only** from the app
|
||||
bundle typechecks clean, and the notarized app runs the Swift scratchpad on a
|
||||
machine without the dev tree.
|
||||
|
||||
---
|
||||
|
||||
## 1.6.1 — Live Scratch: Swift-toolchain detection
|
||||
|
||||
A patch release. Live Scratch quality-of-life; no library API changes.
|
||||
|
||||
The Swift scratchpad compiles snippets by shelling out to `swiftc` (Xcode or the
|
||||
Command Line Tools). Previously a missing toolchain only surfaced as a compile
|
||||
error in the console on the first Run. Now the app **detects it at launch** and
|
||||
shows an alert with actionable install guidance:
|
||||
|
||||
- **Install Command Line Tools** — launches Apple's own installer (`xcode-select
|
||||
--install`); the app never installs anything silently.
|
||||
- **Get Xcode** — opens the App Store product page.
|
||||
|
||||
The check is alert-only and never blocks the app: the **Graph DSL mode needs no
|
||||
toolchain**, so it's the zero-install fallback. (`ToolchainProbe` classifies the
|
||||
toolchain into available / missing-developer-tools / missing-swiftc / missing-SDK,
|
||||
with injectable resolvers so the missing states are unit-tested without uninstalling
|
||||
anything.)
|
||||
|
||||
---
|
||||
|
||||
## 1.6.0 — Soundfile format expansion
|
||||
|
||||
A minor release. Backward-compatible — the existing default write formats are
|
||||
unchanged; everything here is additive. One shared `AudioFileFormat` enum now
|
||||
drives every writer (`LyrebirdBuffer.write`, offline `NRTDriver` renders, and the
|
||||
real-time `DiskOut.Audio` recorder).
|
||||
|
||||
### New — audio output formats
|
||||
|
||||
```swift
|
||||
// Buffer / NRT / DiskOut (PCM):
|
||||
try buf.write(to: url, format: .wavInt24, sampleRate: 48000) // 16 / 24-bit WAV
|
||||
try buf.write(to: url, format: .aiffFloat32, sampleRate: 48000) // AIFF-C float
|
||||
try buf.write(to: url, format: .cafFloat32, sampleRate: 48000) // CAF (uncapped)
|
||||
|
||||
// Files past 4 GB — RF64/BW64, keeps the .wav extension:
|
||||
try buf.write(to: url, format: .rf64Float32, sampleRate: 96000)
|
||||
try buf.write(to: url, format: .rf64Int24, sampleRate: 96000)
|
||||
|
||||
// Compressed .m4a — offline writers only (LyrebirdBuffer.write / NRTDriver):
|
||||
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps
|
||||
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps
|
||||
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
|
||||
```
|
||||
|
||||
- **WAV bit depths** — 16-bit and 24-bit signed-integer PCM alongside 32-bit float.
|
||||
- **AIFF-C** and **CAF** float output across all writers.
|
||||
- **RF64 / BW64** (EBU Tech 3306) — the 64-bit-sized WAV variant for files past the
|
||||
4 GB limit, written by Lyrebird's own `RF64Writer` (CoreAudio has no RF64 *writer*;
|
||||
it reads them back fine). Opt-in `.rf64Float32` / `.rf64Int24`.
|
||||
- **Compressed AAC + Apple Lossless** (`.m4a`) — encoded natively through
|
||||
`ExtAudioFile`/`AudioConverter`, no third-party dependency. **Offline writers only**
|
||||
(`LyrebirdBuffer.write`, `NRTDriver`); `DiskOut.Audio` streams PCM/RF64 only. (MP3 is
|
||||
not offered — CoreAudio has no MP3 encoder.)
|
||||
- **Selectable NRT output** — `NRTDriver` / `NRTJob` take a `format:` (default CAF/float,
|
||||
unchanged), so offline renders and the multi-engine batch pool can bounce to any format.
|
||||
|
||||
### New — large-file safety
|
||||
|
||||
Plain WAV and AIFF-C carry 32-bit size fields (a 4 GB cap). A write projected past
|
||||
that now **throws `fileTooLargeForContainer`** (buffer / NRT) or stops cleanly and sets
|
||||
a pollable `fileTooLarge` flag (streaming `DiskOut`) instead of silently producing a
|
||||
truncated file. CAF and RF64 are 64-bit-sized and uncapped. `NRTDriver` also validates
|
||||
its `duration` (finite, non-negative) — `NRTDriverError.invalidDuration`.
|
||||
|
||||
### New — Live Scratch: Render-to-File format picker
|
||||
|
||||
The Scratch **Render to File** (⌥⌘R) save dialog now carries a **Format** popup (WAV
|
||||
32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV, and compressed AAC / Apple
|
||||
Lossless) plus the duration field, folded into one dialog. It remembers the last
|
||||
format. Sample rate and channel count still mirror the live engine.
|
||||
|
||||
### Changed
|
||||
|
||||
- **`DiskOutFormat` is deprecated** — it is now a type alias for `AudioFileFormat`.
|
||||
Existing `DiskOutFormat.wavFloat32` / `.aiff` / etc. spellings keep compiling (with a
|
||||
deprecation warning); migrate to `AudioFileFormat` directly.
|
||||
- `LyrebirdEventList.record(directory:format:)` now takes an `AudioFileFormat`. Stem
|
||||
recording is PCM/RF64 only — a compressed format is rejected with a logged message
|
||||
(stems stream through `DiskOut`, which does not do compressed).
|
||||
|
||||
---
|
||||
|
||||
## 1.5.0 — `LyrebirdRandom` + the Live Scratch editor grows up
|
||||
|
||||
A minor release. Backward-compatible — new public API plus a wave of Live Scratch
|
||||
tooling. No changes to existing behavior.
|
||||
|
||||
### New — scalar draws from any distribution (`LyrebirdRandom`)
|
||||
|
||||
Lyrebird had distribution-tied **signals** (noise generators), **sequences**
|
||||
(`Pattern`, `TemporalStream`), and the `DistributionKind` sampling math — but no
|
||||
ergonomic way to get *one value* from a named distribution. `LyrebirdRandom`
|
||||
fills that gap:
|
||||
|
||||
```swift
|
||||
var r = LyrebirdRandom(seed: 42)
|
||||
let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||
let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||
let jitter: Double = r.gauss(mean: 0, dev: 0.02)
|
||||
let skew: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5)
|
||||
let spike: Double = r.laplace(scale: 1.0)
|
||||
```
|
||||
|
||||
- **`LyrebirdRandom`** — a seedable value type owning a xorshift64 state, so a
|
||||
seed gives a fully reproducible stream of draws (what scored/rendered music
|
||||
wants). Named methods for every family in `DistributionKind` (uniform, low/
|
||||
high/mean-biased, exponential-range, exponential, gamma, laplace, asymmetric
|
||||
laplace, half-cosine, logistic, poisson, arcsin, beta, cauchy, gauss), plus a
|
||||
generic `value(_:parX:parY:parA:parB:)` reaching any kind.
|
||||
- **`LyrebirdRandom.shared`** (`SharedRandom`) — a process-wide, thread-safe
|
||||
source for throwaway draws (system-seeded, non-reproducible). The global
|
||||
**`Random`** is a shorthand for it, for the common non-seeded case:
|
||||
`Random.uniform(low: 0, high: 1)`. (Takes a lock — not RT-safe; use an owned
|
||||
`LyrebirdRandom` inside a Generator.)
|
||||
- **`DistributionKind.sample(parX:parY:parA:parB:using:)`** — the public
|
||||
single-draw dispatcher, now the single source of truth for the case→sampler
|
||||
mapping: `TemporalTendency` and `DemandTemporalTendency` were refactored onto it
|
||||
(behavior pinned by the golden-value tests), so a scalar draw and a stream of
|
||||
the same distribution agree given the same seed.
|
||||
|
||||
For a plain uniform scalar the Swift stdlib (`Double.random(in:)`) is still the
|
||||
lightest choice; reach for `LyrebirdRandom` when you want a *shaped* distribution
|
||||
or a reproducible seeded stream.
|
||||
|
||||
### Live Scratch — renamed and a lot more capable
|
||||
|
||||
The macOS live-coding scratchpad graduated from a demo to a shipping app:
|
||||
**`LyrebirdScratchDemo` → `LyrebirdScratch`** (bundle id
|
||||
`net.realizedsound.LyrebirdScratch`; project, scheme, entitlements renamed). New
|
||||
in the editor:
|
||||
|
||||
- **Render to File (⌥⌘R)** — bounce the selection (or whole buffer) to a **CAF**
|
||||
file offline instead of playing it live. Prompts for a path and duration, builds
|
||||
the graph on a throwaway `NRTDriver` engine mirroring the live engine's settings
|
||||
(so the bounce matches what you heard), renders faster-than-real-time off the
|
||||
main thread, and reveals the file in Finder. Only **sample-clock** timing renders
|
||||
(`engine.schedule`, in-graph triggers) — wall-clock routine/task waits don't.
|
||||
- **Format Code (⌥⌘F)** — pretty-print the buffer with the toolchain's
|
||||
`swift-format`. No-op on a blank buffer; parse errors go to the console.
|
||||
- **Line-number gutter** — a floating `ScratchLineNumberGutter` overlay,
|
||||
positioned from each row's line-fragment rect so numbers align on blank and
|
||||
wrapped lines. (An `NSRulerView` attempt was abandoned — `rulersVisible`
|
||||
mis-tiles the document view inside a SwiftUI `NSViewRepresentable`, blanking the
|
||||
editor.)
|
||||
- **`Foundation` in scope** — snippets can use `pow`, `sin`, `sqrt`, `Date`, … with
|
||||
no `import` (a snippet can't declare one — its body is wrapped in the entry
|
||||
function).
|
||||
- **Manual code completion (Esc / F5)** — no more auto-trigger on `.` that
|
||||
ambushed typing; completion replaces the partial word, not the receiver.
|
||||
- **Fixed — editor scroll-jump**: the engine status readout refreshed via
|
||||
`.id(engineTick)`, tearing down subviews every heartbeat and nudging the scroll
|
||||
offset. Stats now update in place from an `@State` snapshot.
|
||||
|
||||
### New — compile artifacts stage into Application Support (no Documents prompt)
|
||||
|
||||
Swift-mode compilation points `swiftc` at the Lyrebird module artifacts, which in
|
||||
a dev checkout live under `~/Documents` — tripping the macOS "wants to access your
|
||||
Documents folder" gate. `LiveSession.stageArtifacts()` copies the minimal set into
|
||||
`~/Library/Application Support/LyrebirdScratch/LiveCompile/` (ungated), rewriting
|
||||
the C module map's absolute umbrella-header path to a staged copy so the compile
|
||||
is self-contained. Idempotent (a receipt skips an unchanged source), best-effort
|
||||
(falls back to the build dir). A **shipped** app carrying its artifacts in
|
||||
`Contents/Resources/LyrebirdArtifacts` never reads a gated folder — groundwork for
|
||||
a standalone `LyrebirdScratch.app` download.
|
||||
|
||||
### Docs
|
||||
|
||||
New guidance on snippet **timing / scheduling** — `engine.schedule`,
|
||||
`LyrebirdRoutine` / `LyrebirdTask` (background-thread waits), `LyrebirdClock`,
|
||||
in-graph triggers — the retention rule (the snippet is transient), and which
|
||||
mechanisms survive an offline NRT render vs. which are wall-clock-only.
|
||||
|
||||
---
|
||||
|
||||
## 1.4.2 — Live-coding: Run Selection + graceful slot release
|
||||
|
||||
A minor release. Backward-compatible — additive conveniences to the (macOS-only)
|
||||
live-coding editor that make per-fragment evaluation and voice lifecycle feel
|
||||
like a proper live-coding environment. No changes to existing public API.
|
||||
|
||||
### New — Run Selection (⌘E)
|
||||
|
||||
Evaluate just the **highlighted text** and *add* it to whatever is already
|
||||
playing — always additively, never a replace. It leaves the rest of the buffer
|
||||
and the whole-buffer re-evaluation baseline (the clean/dirty badge still reflects
|
||||
your last full run) untouched. This is the live-coding "evaluate this line/region,
|
||||
keep going" gesture: audition a single voice, layer it in, iterate. Works in both
|
||||
Swift and Graph DSL modes; no-op with no selection. ⌘↩ / ⌘⇧↩ (whole buffer) are
|
||||
unchanged.
|
||||
|
||||
### New — Start a voice, release it later (`context.release(slot:)`)
|
||||
|
||||
Named slots are the persistent **handle** across evaluations — the slot *name* is
|
||||
your reference (Swift `let`/`var` bindings can't carry from one snippet to the
|
||||
next, since each ⌘↩/⌘E is a separately-compiled unit). Pair that with Run
|
||||
Selection to start a voice in one evaluation and let it go in another:
|
||||
|
||||
```swift
|
||||
// ⌘E this line — start a persistent, gated voice named "pad":
|
||||
context.play(slot: "pad") { EnvGen(gate: 1, /* free-on-done */) * OscSaw.Audio(freq: 110) }
|
||||
|
||||
// …later, ⌘E this line — graceful release: the envelope tails out, then frees:
|
||||
context.release(slot: "pad")
|
||||
```
|
||||
|
||||
- `context.release(slot:)` triggers the voice's envelope **release** phase and
|
||||
frees the name; the voice self-frees via its done-action (and, as a safety net,
|
||||
stays reclaimable by **Clear Synths** if it never does).
|
||||
- `context.free(slot:)` is the **immediate** hard stop — the counterpart, no tail.
|
||||
|
||||
### New — Engine panel (scope + status)
|
||||
|
||||
A panel at the bottom of the scratch window gives an always-on view of the
|
||||
running engine: a live dual-channel **oscilloscope** of the output (fed by a
|
||||
`ScopeCapture` the session attaches to the output buses), plus **CPU
|
||||
average/peak** meter bars and **synth / group / snippet** counts.
|
||||
|
||||
### New — Reset Session + Restart to Reclaim Memory
|
||||
|
||||
Two Run-menu commands for the by-design snippet-dylib cost:
|
||||
|
||||
- **Reset Session** — an in-process, *non-destructive* reset: stops all snippet
|
||||
audio, shuts down the code-completion server (freeing its subprocess and temp
|
||||
files), and clears diagnostics. Your buffer is untouched.
|
||||
- **Restart to Reclaim Memory…** — relaunches the app (with a confirmation), the
|
||||
only way to actually free the mapped snippet dylibs, which cannot be unloaded
|
||||
in-process.
|
||||
|
||||
### New — Console panel
|
||||
|
||||
An always-open panel down the right side logs everything: snippet
|
||||
`context.reportMessage(_:)` output (the live-coding `print`), compile / Graph DSL
|
||||
**errors** with their `line:col`, and a one-line notice per run — oldest first,
|
||||
auto-scrolled, with a **Clear** button. Errors moved here from the old transient
|
||||
bottom strip so they stay visible while you fix them.
|
||||
|
||||
### Faster typing
|
||||
|
||||
Cut the per-keystroke cost in the editor: syntax highlighting is debounced
|
||||
(coalesced after a brief pause instead of a full-buffer re-tokenize on every
|
||||
key), `updateNSView` fast-paths a pure text change, and redundant `@Published`
|
||||
republishes (selection, re-eval state) are elided.
|
||||
|
||||
### Changed — code completion is now manual (Esc / F5)
|
||||
|
||||
Completion no longer auto-opens on `.`. The auto-trigger ambushed typing — after
|
||||
`Pan2.` the popup opened and couldn't be dismissed by deleting, trapping the
|
||||
caret until a candidate was picked. Invoke completion deliberately with **Esc**
|
||||
(or **F5**); a member request after a dot still resolves. Wider default scratch
|
||||
window too (75% of the visible screen width).
|
||||
|
||||
---
|
||||
|
||||
## 1.4.1 — "Learning Swift for Lyrebird" intro guide
|
||||
|
||||
A documentation-only release, continuing the doc improvements begun in 1.3. No
|
||||
|
||||
@@ -7,11 +7,13 @@
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
/// Non-Real-Time audio driver. Renders synchronously to a CAF file.
|
||||
/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the
|
||||
/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`).
|
||||
/// `start()` blocks until rendering is complete — suitable for score/script workflows.
|
||||
public final class NRTDriver: AudioDriver {
|
||||
|
||||
private let outputURL: URL
|
||||
private let outputFormat: AudioFileFormat
|
||||
private let duration: Double
|
||||
|
||||
// Optional soundfile fed into the engine as simulated hardware input.
|
||||
@@ -38,8 +40,13 @@ public final class NRTDriver: AudioDriver {
|
||||
public var triggerListener: TriggerListener?
|
||||
|
||||
/// - Parameters:
|
||||
/// - outputURL: Destination CAF file path.
|
||||
/// - outputURL: Destination file path. The extension should match `format`
|
||||
/// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``.
|
||||
/// - duration: Render duration in seconds.
|
||||
/// - format: Container and PCM encoding for the output file. Defaults to
|
||||
/// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel
|
||||
/// count, so it suits long or multichannel offline renders; `.wavFloat32` /
|
||||
/// `.aiffFloat32` / the integer WAV cases are available for interchange.
|
||||
/// - inputURL: Optional soundfile whose samples are written to the engine's input buses
|
||||
/// each block, as if they came from a microphone. Channels are mapped in order starting
|
||||
/// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count
|
||||
@@ -50,11 +57,13 @@ public final class NRTDriver: AudioDriver {
|
||||
public init(
|
||||
outputURL: URL,
|
||||
duration: Double,
|
||||
format: AudioFileFormat = .cafFloat32,
|
||||
inputURL: URL? = nil,
|
||||
inputStartOffset: Double = 0.0
|
||||
) {
|
||||
|
||||
self.outputURL = outputURL
|
||||
self.outputFormat = format
|
||||
self.duration = duration
|
||||
self.inputURL = inputURL
|
||||
self.inputStartOffset = max(0.0, inputStartOffset)
|
||||
@@ -128,54 +137,112 @@ public final class NRTDriver: AudioDriver {
|
||||
count: inputChannelCount)
|
||||
}
|
||||
|
||||
/// Render synchronously to the output file.
|
||||
///
|
||||
/// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN,
|
||||
/// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render
|
||||
/// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders);
|
||||
/// or the file/IO error cases on create/write failure. For the `.rf64*`
|
||||
/// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`.
|
||||
public func start() throws {
|
||||
guard let engine: SynthesisEngine else { return }
|
||||
|
||||
// Create and configure an ExtAudioFile for CAF / 32-bit float interleaved output
|
||||
var fileRef: ExtAudioFileRef?
|
||||
var format: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: engine.sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels),
|
||||
mChannelsPerFrame: UInt32(engine.numOutputChannels),
|
||||
mBitsPerChannel: 32,
|
||||
mReserved: 0
|
||||
)
|
||||
|
||||
var status: OSStatus = ExtAudioFileCreateWithURL(
|
||||
outputURL as CFURL,
|
||||
kAudioFileCAFType,
|
||||
&format,
|
||||
nil,
|
||||
AudioFileFlags.eraseFile.rawValue,
|
||||
&fileRef
|
||||
)
|
||||
guard status == noErr, let fileRef: ExtAudioFileRef else {
|
||||
throw NRTDriverError.cannotCreateFile(status)
|
||||
// Validate duration before any Double→Int conversion: Int(_:) traps on a
|
||||
// non-finite or out-of-range value, and a negative duration would make the
|
||||
// render loop's `0..<totalBlocks` range crash. Throw instead.
|
||||
// The `< Double(Int.max)` bound also rejects a finite-but-astronomical
|
||||
// duration whose block count would overflow the `Int(_:)` conversion.
|
||||
let blocksDouble: Double = (duration * engine.sampleRate / Double(engine.blockSize)).rounded(.up)
|
||||
guard duration.isFinite, duration >= 0, blocksDouble < Double(Int.max) else {
|
||||
throw NRTDriverError.invalidDuration(duration)
|
||||
}
|
||||
// Guarantee disposal even if an error is thrown mid-render.
|
||||
|
||||
// Total render blocks — computed once and shared by the large-file guard and
|
||||
// the render loop below, so the two can never drift out of sync.
|
||||
let totalBlocks: Int = Int(blocksDouble)
|
||||
|
||||
// Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF
|
||||
// cap before opening the file, so we never emit a truncated/corrupt output.
|
||||
// CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on
|
||||
// overflow, so a frame count near Int.max still yields the correct decision.
|
||||
let (projectedFrames, framesOverflow): (Int, Bool) =
|
||||
totalBlocks.multipliedReportingOverflow(by: engine.blockSize)
|
||||
let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames
|
||||
if let overflow: (projected: Int, cap: Int) = outputFormat.riffOverflow(
|
||||
frameCount: effectiveFrames, channels: engine.numOutputChannels
|
||||
) {
|
||||
throw NRTDriverError.fileTooLargeForContainer(
|
||||
projectedBytes: overflow.projected, cap: overflow.cap
|
||||
)
|
||||
}
|
||||
|
||||
// Dispose the input file regardless of which output backend construction (or
|
||||
// the render) throws below — registered before backend selection so an early
|
||||
// throw can't leak it.
|
||||
defer {
|
||||
ExtAudioFileDispose(fileRef)
|
||||
if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) }
|
||||
inputFileRef = nil
|
||||
}
|
||||
|
||||
// Set client format (same as file format — already float32 interleaved)
|
||||
status = ExtAudioFileSetProperty(
|
||||
fileRef,
|
||||
kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&format
|
||||
)
|
||||
guard status == noErr else {
|
||||
throw NRTDriverError.cannotSetFormat(status)
|
||||
// Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64
|
||||
// cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so
|
||||
// both back-ends receive native Float32 interleaved samples.
|
||||
let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer
|
||||
? try RF64Writer(url: outputURL, format: outputFormat,
|
||||
sampleRate: engine.sampleRate, channels: engine.numOutputChannels)
|
||||
: nil
|
||||
|
||||
var extFileRef: ExtAudioFileRef? = nil
|
||||
if rf64Writer == nil {
|
||||
var fileFormat: AudioStreamBasicDescription = outputFormat.makeFileASBD(
|
||||
sampleRate: engine.sampleRate,
|
||||
channels: engine.numOutputChannels
|
||||
)
|
||||
var createdRef: ExtAudioFileRef?
|
||||
var status: OSStatus = ExtAudioFileCreateWithURL(
|
||||
outputURL as CFURL,
|
||||
outputFormat.audioFileTypeID,
|
||||
&fileFormat,
|
||||
nil,
|
||||
AudioFileFlags.eraseFile.rawValue,
|
||||
&createdRef
|
||||
)
|
||||
guard status == noErr, let createdRef: ExtAudioFileRef else {
|
||||
throw NRTDriverError.cannotCreateFile(status)
|
||||
}
|
||||
// Client format: always native Float32 interleaved. ExtAudioFile converts
|
||||
// Float32 → int16/int24 on write for the integer WAV formats.
|
||||
var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD(
|
||||
sampleRate: engine.sampleRate,
|
||||
channels: engine.numOutputChannels
|
||||
)
|
||||
status = ExtAudioFileSetProperty(
|
||||
createdRef,
|
||||
kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFormat
|
||||
)
|
||||
guard status == noErr else {
|
||||
ExtAudioFileDispose(createdRef)
|
||||
throw NRTDriverError.cannotSetFormat(status)
|
||||
}
|
||||
// Compressed (AAC) formats: push the target bitrate into the encoder.
|
||||
let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef)
|
||||
guard encoderStatus == noErr else {
|
||||
ExtAudioFileDispose(createdRef)
|
||||
throw NRTDriverError.cannotSetFormat(encoderStatus)
|
||||
}
|
||||
extFileRef = createdRef
|
||||
}
|
||||
|
||||
// Render loop — synchronous, no RT constraints
|
||||
let totalBlocks: Int = Int(ceil(duration * engine.sampleRate / Double(engine.blockSize)))
|
||||
// Guarantee disposal even if an error is thrown mid-render.
|
||||
defer {
|
||||
if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) }
|
||||
try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes
|
||||
}
|
||||
|
||||
// Render loop — synchronous, no RT constraints. `totalBlocks` was computed
|
||||
// once above (shared with the large-file guard).
|
||||
let bs: Int = engine.blockSize
|
||||
let nch: Int = engine.numOutputChannels
|
||||
|
||||
@@ -222,25 +289,35 @@ public final class NRTDriver: AudioDriver {
|
||||
}
|
||||
}
|
||||
|
||||
// Write interleaved block to file — check status; a failure means a corrupt
|
||||
// or truncated file, so we throw rather than silently swallow the error.
|
||||
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
|
||||
let frameCount: UInt32 = UInt32(bs)
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(nch),
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
// Write interleaved block to file — a failure means a corrupt or truncated
|
||||
// file, so we throw rather than silently swallow the error.
|
||||
if let rf64Writer: RF64Writer {
|
||||
try writeBuffer.withUnsafeBufferPointer { ptr in
|
||||
try rf64Writer.writeFloat32Interleaved(ptr, frames: bs)
|
||||
}
|
||||
} else if let extFileRef: ExtAudioFileRef {
|
||||
let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in
|
||||
let frameCount: UInt32 = UInt32(bs)
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(nch),
|
||||
mDataByteSize: UInt32(ptr.count * MemoryLayout<Float>.size),
|
||||
mData: ptr.baseAddress
|
||||
)
|
||||
)
|
||||
)
|
||||
return ExtAudioFileWrite(fileRef, frameCount, &bufList)
|
||||
}
|
||||
guard writeStatus == noErr else {
|
||||
throw NRTDriverError.writeFailed(writeStatus)
|
||||
return ExtAudioFileWrite(extFileRef, frameCount, &bufList)
|
||||
}
|
||||
guard writeStatus == noErr else {
|
||||
throw NRTDriverError.writeFailed(writeStatus)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is
|
||||
// finalised before this method returns.
|
||||
try rf64Writer?.close()
|
||||
|
||||
// Synchronous render is done and the freeWorker timer only starts after this
|
||||
// returns — emit any per-block event-drop warning here so it reaches the console
|
||||
// even if the process exits before that timer (or `stop()`) runs.
|
||||
@@ -267,4 +344,11 @@ public enum NRTDriverError: Error {
|
||||
case cannotSetInputClientFormat(OSStatus)
|
||||
case cannotSeekInputFile(OSStatus)
|
||||
case inputReadFailed(OSStatus)
|
||||
/// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value.
|
||||
case invalidDuration(Double)
|
||||
/// The render is projected to exceed the output container's 4 GB (32-bit size
|
||||
/// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is
|
||||
/// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with
|
||||
/// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration.
|
||||
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,361 @@
|
||||
// AudioFileFormat.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import AudioToolbox
|
||||
|
||||
/// Container-and-encoding format shared by every Lyrebird soundfile writer:
|
||||
/// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump),
|
||||
/// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver
|
||||
/// (offline score render).
|
||||
///
|
||||
/// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample
|
||||
/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand
|
||||
/// `ExtAudioFile` native-Float32 samples as the *client* format (see
|
||||
/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file*
|
||||
/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost
|
||||
/// the caller nothing beyond selecting the case.
|
||||
///
|
||||
/// ## Container notes
|
||||
/// - **WAV** — little-endian, cross-platform standard. Supports Float32 and
|
||||
/// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size
|
||||
/// fields); large renders should fall back to `.cafFloat32`.
|
||||
/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType`
|
||||
/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry
|
||||
/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels
|
||||
/// for compatibility with legacy readers; also 4 GB-capped.
|
||||
/// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any
|
||||
/// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB
|
||||
/// cap). Default for buffer and NRT writes.
|
||||
public enum AudioFileFormat: Sendable {
|
||||
|
||||
// MARK: - WAV variants
|
||||
|
||||
/// WAV container, 32-bit IEEE-754 float, little-endian.
|
||||
case wavFloat32
|
||||
/// WAV container, 16-bit signed integer, little-endian.
|
||||
case wavInt16
|
||||
/// WAV container, 24-bit signed integer (packed), little-endian.
|
||||
case wavInt24
|
||||
|
||||
// MARK: - AIFF-C variants
|
||||
|
||||
/// AIFF-C container, 32-bit IEEE-754 float, big-endian.
|
||||
case aiffFloat32
|
||||
|
||||
// MARK: - CAF variants
|
||||
|
||||
/// CAF container, 32-bit IEEE-754 float, little-endian.
|
||||
case cafFloat32
|
||||
|
||||
// MARK: - RF64 / BW64 variants (64-bit-sized WAV, no 4 GB cap)
|
||||
|
||||
/// RF64 (BW64) container, 32-bit IEEE-754 float, little-endian. WAV extension.
|
||||
/// Emitted by ``RF64Writer`` (not `ExtAudioFile`); readable by CoreAudio.
|
||||
case rf64Float32
|
||||
/// RF64 (BW64) container, 24-bit signed integer (packed), little-endian.
|
||||
case rf64Int24
|
||||
|
||||
// MARK: - Compressed variants (M4A container — offline writers only)
|
||||
|
||||
/// AAC in an M4A container, ~256 kbps. Lossy; **not sample-accurate** (encoder
|
||||
/// priming/padding). Encoded by `ExtAudioFile`/`AudioConverter`. Offline writers
|
||||
/// only (`LyrebirdBuffer.write`, `NRTDriver`); ``DiskOut/Audio`` rejects it.
|
||||
case aacHigh
|
||||
/// AAC in an M4A container, ~128 kbps. See ``aacHigh``.
|
||||
case aacMedium
|
||||
/// Apple Lossless (ALAC) in an M4A container, 24-bit source. Lossless of the
|
||||
/// 24-bit-quantised signal. Offline writers only; ``DiskOut/Audio`` rejects it.
|
||||
case alac
|
||||
|
||||
// MARK: - Back-compat shorthands
|
||||
|
||||
/// WAV / Float32. Alias for ``wavFloat32``.
|
||||
public static let wav: AudioFileFormat = .wavFloat32
|
||||
/// AIFF-C / Float32. Alias for ``aiffFloat32``.
|
||||
public static let aiff: AudioFileFormat = .aiffFloat32
|
||||
/// CAF / Float32. Alias for ``cafFloat32``.
|
||||
public static let caf: AudioFileFormat = .cafFloat32
|
||||
|
||||
// MARK: - Derived properties
|
||||
|
||||
/// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`.
|
||||
///
|
||||
/// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not
|
||||
/// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default.
|
||||
public var audioFileTypeID: AudioFileTypeID {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24:
|
||||
return kAudioFileWAVEType
|
||||
case .aiffFloat32:
|
||||
return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not
|
||||
case .cafFloat32:
|
||||
return kAudioFileCAFType
|
||||
case .aacHigh, .aacMedium, .alac:
|
||||
return kAudioFileM4AType
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem extension for the output file (no leading dot).
|
||||
public var fileExtension: String {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: return "wav"
|
||||
case .aiffFloat32: return "aiff"
|
||||
case .cafFloat32: return "caf"
|
||||
case .aacHigh, .aacMedium, .alac: return "m4a"
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits per sample in the *PCM* encoded file. Not meaningful for the compressed
|
||||
/// cases (they carry no fixed per-sample bit width); returns `0` there.
|
||||
public var fileBitsPerChannel: UInt32 {
|
||||
switch self {
|
||||
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return 32
|
||||
case .wavInt16: return 16
|
||||
case .wavInt24, .rf64Int24: return 24
|
||||
case .aacHigh, .aacMedium, .alac: return 0
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when the file encoding is IEEE-754 float; `false` for signed-integer PCM
|
||||
/// or a compressed codec.
|
||||
public var isFloatEncoding: Bool {
|
||||
switch self {
|
||||
case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return true
|
||||
case .wavInt16, .wavInt24, .rf64Int24, .aacHigh, .aacMedium, .alac: return false
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when the container stores big-endian sample data (AIFF-C spec).
|
||||
public var isBigEndian: Bool {
|
||||
switch self {
|
||||
case .aiffFloat32:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .cafFloat32, .rf64Float32, .rf64Int24,
|
||||
.aacHigh, .aacMedium, .alac:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` for the compressed codecs (AAC, ALAC) — encoded by
|
||||
/// `ExtAudioFile`/`AudioConverter` into an M4A container.
|
||||
public var isCompressed: Bool {
|
||||
switch self {
|
||||
case .aacHigh, .aacMedium, .alac:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||
.rf64Float32, .rf64Int24:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats.
|
||||
public var aacBitrate: Int? {
|
||||
switch self {
|
||||
case .aacHigh: return aacHighBitrate
|
||||
case .aacMedium: return aacMediumBitrate
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||
.rf64Float32, .rf64Int24, .alac:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when the container can address files larger than 4 GB.
|
||||
///
|
||||
/// WAV (classic RIFF) and AIFF-C carry unsigned **32-bit** size fields, so
|
||||
/// their total file size is capped at 4 GB (see `lyrebirdMaxRIFFBytes`). CAF
|
||||
/// (64-bit sizes) and RF64/BW64 (64-bit sizes via the `ds64` chunk) have no such
|
||||
/// cap. `ExtAudioFile` cannot emit RF64, so those cases are written by
|
||||
/// ``RF64Writer`` — see ``usesRF64Writer``.
|
||||
public var supportsLargeFiles: Bool {
|
||||
switch self {
|
||||
// CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all,
|
||||
// so the 4 GB RIFF/AIFF guard never applies to them either.
|
||||
case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when this format is emitted by ``RF64Writer`` (hand-rolled 64-bit WAV)
|
||||
/// rather than `ExtAudioFile`. The three soundfile writers branch on this.
|
||||
public var usesRF64Writer: Bool {
|
||||
switch self {
|
||||
case .rf64Float32, .rf64Int24:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32,
|
||||
.aacHigh, .aacMedium, .alac:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Large-file guard
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// Projected on-disk audio-data size in bytes for `frameCount` interleaved
|
||||
/// frames across `channels`, at this format's bit depth. Excludes container
|
||||
/// header/metadata (accounted for by the slack baked into `lyrebirdMaxRIFFBytes`).
|
||||
///
|
||||
/// Pure integer arithmetic — safe to evaluate for hypothetical sizes without
|
||||
/// allocating anything. **Saturates to `Int.max` on overflow** rather than
|
||||
/// trapping: any frame count large enough to overflow the byte product is, by
|
||||
/// definition, far past any container cap, so a saturated value gives the guard
|
||||
/// the correct "over cap" answer without a crash.
|
||||
func projectedByteCount(frameCount: Int, channels: Int) -> Int {
|
||||
let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte)
|
||||
let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels)
|
||||
if sampleOverflow { return Int.max }
|
||||
let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample)
|
||||
return byteOverflow ? Int.max : bytes
|
||||
}
|
||||
|
||||
/// Returns `(projected, cap)` when writing `frameCount × channels` frames in
|
||||
/// this format would overflow the container's addressable size, or `nil` when
|
||||
/// the write fits (or the container is 64-bit — see ``supportsLargeFiles``).
|
||||
///
|
||||
/// The single decision point behind both the `LyrebirdBuffer.write` and
|
||||
/// `NRTDriver` large-file guards, so the guard reads off the format rather
|
||||
/// than a hardcoded case list.
|
||||
func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? {
|
||||
guard !supportsLargeFiles else { return nil }
|
||||
let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels)
|
||||
return projected > lyrebirdMaxRIFFBytes ? (projected, lyrebirdMaxRIFFBytes) : nil
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ASBD factories (module-internal)
|
||||
|
||||
/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations.
|
||||
private let bitsPerByte: UInt32 = 8
|
||||
|
||||
/// Encoder packet geometry (samples per packet) for the compressed codecs.
|
||||
private let aacFramesPerPacket: UInt32 = 1024
|
||||
private let alacFramesPerPacket: UInt32 = 4096
|
||||
|
||||
/// AAC target bitrates (bits/second) for the two quality tiers.
|
||||
private let aacHighBitrate: Int = 256_000
|
||||
private let aacMediumBitrate: Int = 128_000
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
|
||||
/// with the case's bit depth, encoding flags, and endianness, interleaved
|
||||
/// across `channels`.
|
||||
///
|
||||
/// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with
|
||||
/// `makeClientASBD(sampleRate:channels:)` as the client format so
|
||||
/// `ExtAudioFile` performs any Float32 → integer / endian conversion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate embedded in the file header, in Hz.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
// Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry.
|
||||
// We supply the format ID, channel count, sample rate, and frames-per-packet;
|
||||
// `AudioConverter` (behind `ExtAudioFile`) computes the rest.
|
||||
if isCompressed {
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
asbd.mSampleRate = sampleRate
|
||||
asbd.mChannelsPerFrame = UInt32(channels)
|
||||
// AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the
|
||||
// codec from `aacBitrate` avoids a `switch self` with an unreachable
|
||||
// default that could silently leave `mFormatID == 0` for a future case.
|
||||
if aacBitrate != nil {
|
||||
asbd.mFormatID = kAudioFormatMPEG4AAC
|
||||
asbd.mFramesPerPacket = aacFramesPerPacket
|
||||
} else {
|
||||
asbd.mFormatID = kAudioFormatAppleLossless
|
||||
asbd.mFramesPerPacket = alacFramesPerPacket
|
||||
asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData
|
||||
}
|
||||
return asbd
|
||||
}
|
||||
|
||||
let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte
|
||||
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels)
|
||||
|
||||
var flags: AudioFormatFlags = kAudioFormatFlagIsPacked
|
||||
flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger
|
||||
if isBigEndian { flags |= kAudioFormatFlagIsBigEndian }
|
||||
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: flags,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: fileBitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
|
||||
/// Build the *client* `AudioStreamBasicDescription`: always native-endian
|
||||
/// Float32 interleaved across `channels`, independent of the file encoding.
|
||||
///
|
||||
/// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format
|
||||
/// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - sampleRate: Sample rate, in Hz. Should match the file ASBD.
|
||||
/// - channels: Interleaved channel count. Must be ≥ 1.
|
||||
func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription {
|
||||
let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels)
|
||||
return AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channels),
|
||||
mBitsPerChannel: lyrebirdBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Compressed encoder configuration
|
||||
|
||||
extension AudioFileFormat {
|
||||
|
||||
/// After an `ExtAudioFile` for a compressed format has been created and its client
|
||||
/// (Float32) format set, push the target AAC bitrate into the underlying
|
||||
/// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none).
|
||||
///
|
||||
/// Returns `noErr` on success (or when nothing needed doing), else the failing
|
||||
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
|
||||
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
|
||||
guard let bitrate: Int = aacBitrate else { return noErr }
|
||||
|
||||
var converter: AudioConverterRef?
|
||||
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
|
||||
let getStatus: OSStatus = ExtAudioFileGetProperty(
|
||||
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
|
||||
)
|
||||
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
|
||||
|
||||
var rate: UInt32 = UInt32(bitrate)
|
||||
let setStatus: OSStatus = AudioConverterSetProperty(
|
||||
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
|
||||
)
|
||||
guard setStatus == noErr else { return setStatus }
|
||||
|
||||
// Notify ExtAudioFile that the converter config changed so it re-reads it.
|
||||
// The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil
|
||||
// variable (NOT a null data pointer — CoreAudio dereferences the pointer).
|
||||
var config: CFPropertyList? = nil
|
||||
return withUnsafePointer(to: &config) { ptr in
|
||||
ExtAudioFileSetProperty(
|
||||
fileRef, kExtAudioFileProperty_ConverterConfig,
|
||||
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -7,44 +7,6 @@
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
|
||||
// MARK: - AudioFileFormat
|
||||
|
||||
/// Container format for `LyrebirdBuffer.write(to:format:sampleRate:)`.
|
||||
public enum AudioFileFormat {
|
||||
/// AIFF-C container (`.aiff`) — lossless Float32, big-endian. Common on macOS.
|
||||
///
|
||||
/// Uses `kAudioFileAIFCType` (AIFF-C), not classic `kAudioFileAIFFType`. Classic AIFF
|
||||
/// supports only integer PCM; AIFF-C adds float and other sample types while retaining
|
||||
/// the same `.aiff` file extension and broad macOS/iOS compatibility.
|
||||
///
|
||||
/// Note: AIFF-C has practical interoperability limits beyond 2 channels. For
|
||||
/// multichannel (3–8 ch) output, prefer `.caf` or `.wav`.
|
||||
case aiff
|
||||
/// WAV container (`.wav`) — lossless Float32, little-endian. Cross-platform standard.
|
||||
/// Supports up to `lyrebirdMaxFileChannelCount` channels via WAVE_FORMAT_EXTENSIBLE.
|
||||
case wav
|
||||
/// Core Audio Format (`.caf`) — Apple's flexible container; supports any sample rate
|
||||
/// and any channel count up to `lyrebirdMaxFileChannelCount`. Default for writes.
|
||||
case caf
|
||||
|
||||
fileprivate var audioFileTypeID: AudioFileTypeID {
|
||||
switch self {
|
||||
case .aiff: return kAudioFileAIFCType // AIFF-C: supports Float32 (classic AIFF does not)
|
||||
case .wav: return kAudioFileWAVEType
|
||||
case .caf: return kAudioFileCAFType
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the container requires big-endian sample data in the file format descriptor.
|
||||
/// AIFF-C is big-endian by spec; WAV and CAF use native/little-endian.
|
||||
fileprivate var requiresBigEndian: Bool {
|
||||
switch self {
|
||||
case .aiff: return true
|
||||
case .wav, .caf: return false
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - LyrebirdBufferIOError
|
||||
|
||||
/// Errors thrown by `LyrebirdBuffer` file I/O methods.
|
||||
@@ -70,6 +32,11 @@ public enum LyrebirdBufferIOError: Error, Equatable {
|
||||
case cannotSetOutputFormat(OSStatus)
|
||||
/// `ExtAudioFileWrite` returned a non-zero status.
|
||||
case writeFailed(OSStatus)
|
||||
/// The requested WAV/AIFF write is projected to exceed the container's 4 GB
|
||||
/// (32-bit size field) limit. `projectedBytes` is the estimated audio-data
|
||||
/// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32`
|
||||
/// (64-bit sizes, uncapped), shorten the buffer, or split it.
|
||||
case fileTooLargeForContainer(projectedBytes: Int, cap: Int)
|
||||
}
|
||||
|
||||
// MARK: - Constants
|
||||
@@ -251,18 +218,27 @@ public extension LyrebirdBuffer {
|
||||
|
||||
/// Write the buffer's contents to an audio file.
|
||||
///
|
||||
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]`. The file will
|
||||
/// contain interleaved Float32 samples at the specified sample rate. For multichannel
|
||||
/// buffers, `.caf` or `.wav` are recommended; `.aiff` (AIFF-C) is best limited to
|
||||
/// stereo for maximum compatibility with external readers.
|
||||
///
|
||||
/// Converts `Double` (Double) samples to Float32 on the way out.
|
||||
/// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]` and any
|
||||
/// ``AudioFileFormat`` case. The buffer's `Double` samples are handed to the
|
||||
/// writer as native Float32; the container's on-disk encoding (Float32, or
|
||||
/// signed-integer 16/24-bit for the WAV cases) is produced by its conversion.
|
||||
/// Most formats go through `ExtAudioFile`; the RF64 cases (`.rf64Float32` /
|
||||
/// `.rf64Int24`) are written by ``RF64Writer`` instead, since `ExtAudioFile`
|
||||
/// cannot emit RF64. For multichannel buffers, `.cafFloat32` or `.wavFloat32` are
|
||||
/// recommended; `.aiffFloat32` (AIFF-C) is best limited to stereo for maximum
|
||||
/// compatibility with external readers. `.wavFloat32` / `.wavInt16` / `.wavInt24`
|
||||
/// / `.aiffFloat32` throw ``LyrebirdBufferIOError/fileTooLargeForContainer(projectedBytes:cap:)``
|
||||
/// past 4 GB — use `.rf64*` or `.cafFloat32` for larger files.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - url: Destination file. Any existing file at this path is overwritten.
|
||||
/// - format: Container format. Defaults to `.caf`.
|
||||
/// - format: Container and PCM encoding. Defaults to `.cafFloat32`.
|
||||
/// - sampleRate: Sample rate embedded in the file header. Defaults to 44100.
|
||||
///
|
||||
/// - Throws: ``LyrebirdBufferIOError`` (`.fileTooLargeForContainer` when a
|
||||
/// WAV/AIFF write is projected past 4 GB, or the create/write cases on I/O
|
||||
/// failure). For the `.rf64*` formats, a ``RF64WriterError`` may surface instead.
|
||||
///
|
||||
/// **Not RT-safe.** Must be called from a non-RT thread (main thread or background queue).
|
||||
///
|
||||
/// For session-end dumps from a ``LyrebirdEventList`` teardown, see the
|
||||
@@ -282,39 +258,50 @@ public extension LyrebirdBuffer {
|
||||
+ "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))"
|
||||
)
|
||||
|
||||
let bytesPerSample: UInt32 = lyrebirdFileIOBitsPerSample / 8 // 4 bytes for Float32
|
||||
let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channelCount)
|
||||
// Large-file guard: WAV/AIFF are 4 GB-capped (32-bit size fields). Reject a
|
||||
// write that would overflow rather than emit a truncated/corrupt file. CAF
|
||||
// is 64-bit and exempt (riffOverflow returns nil).
|
||||
if let overflow: (projected: Int, cap: Int) =
|
||||
format.riffOverflow(frameCount: count, channels: channelCount) {
|
||||
throw LyrebirdBufferIOError.fileTooLargeForContainer(
|
||||
projectedBytes: overflow.projected, cap: overflow.cap
|
||||
)
|
||||
}
|
||||
|
||||
// File format: big-endian flags for AIFF-C; native-endian for WAV/CAF.
|
||||
let fileFlags: AudioFormatFlags = format.requiresBigEndian
|
||||
? kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsPacked
|
||||
: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked
|
||||
// RF64 / BW64 is not an ExtAudioFile-writable container — hand it to RF64Writer.
|
||||
// Client samples are native Float32 interleaved, same as the ExtAudioFile path.
|
||||
if format.usesRF64Writer {
|
||||
let writer: RF64Writer = try RF64Writer(
|
||||
url: url, format: format, sampleRate: sampleRate, channels: channelCount
|
||||
)
|
||||
let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount
|
||||
var chunkBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk)
|
||||
try withStorage { storage, frameCount, nch in
|
||||
var frameOffset: Int = 0
|
||||
while frameOffset < frameCount {
|
||||
let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, frameCount - frameOffset)
|
||||
let samplesThisChunk: Int = framesThisChunk * nch
|
||||
for i: Int in 0..<samplesThisChunk {
|
||||
chunkBuf[i] = Float(storage[frameOffset * nch + i])
|
||||
}
|
||||
try chunkBuf.withUnsafeBufferPointer { ptr in
|
||||
try writer.writeFloat32Interleaved(ptr, frames: framesThisChunk)
|
||||
}
|
||||
frameOffset += framesThisChunk
|
||||
}
|
||||
}
|
||||
try writer.close()
|
||||
return
|
||||
}
|
||||
|
||||
var fileFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: fileFlags,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channelCount),
|
||||
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
// File format: container/encoding/endianness per `format`.
|
||||
var fileFormat: AudioStreamBasicDescription =
|
||||
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
|
||||
|
||||
// Client format: always native-endian Float32 interleaved.
|
||||
// ExtAudioFile converts byte order to match the file format automatically.
|
||||
var clientFormat: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: bytesPerFrame,
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: bytesPerFrame,
|
||||
mChannelsPerFrame: UInt32(channelCount),
|
||||
mBitsPerChannel: lyrebirdFileIOBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
// ExtAudioFile converts byte order / encoding to match the file format automatically.
|
||||
var clientFormat: AudioStreamBasicDescription =
|
||||
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
||||
@@ -340,6 +327,12 @@ public extension LyrebirdBuffer {
|
||||
throw LyrebirdBufferIOError.cannotSetOutputFormat(setStatus)
|
||||
}
|
||||
|
||||
// Compressed (AAC) formats: push the target bitrate into the encoder.
|
||||
let encoderStatus: OSStatus = format.applyEncoderConfig(to: fileRef)
|
||||
guard encoderStatus == noErr else {
|
||||
throw LyrebirdBufferIOError.cannotSetOutputFormat(encoderStatus)
|
||||
}
|
||||
|
||||
// Write in chunks, converting Double (Double) → Float32 as we go.
|
||||
// The storage is interleaved so sequential reads produce correctly-ordered output
|
||||
// for any channel count.
|
||||
|
||||
@@ -0,0 +1,259 @@
|
||||
// RF64Writer.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Streaming writer for **RF64 / BW64** WAV files — the 64-bit-sized variant of RIFF
|
||||
/// WAVE (EBU Tech 3306) that lifts the classic 4 GB container limit.
|
||||
///
|
||||
/// `ExtAudioFile` can *read* RF64 but has no RF64 *writer*, so this type emits the
|
||||
/// container by hand via `FileHandle`: a fixed 104-byte header (`RF64` + `ds64` +
|
||||
/// `WAVE_FORMAT_EXTENSIBLE` `fmt ` + `data`) followed by little-endian PCM. The
|
||||
/// `RIFF` and `data` chunk sizes are written as the `0xFFFF_FFFF` sentinel; the true
|
||||
/// 64-bit sizes live in the `ds64` chunk and are patched in on ``close()``.
|
||||
///
|
||||
/// The caller always feeds native **Float32** interleaved samples (matching the other
|
||||
/// Lyrebird writers' client format); this type converts to the file encoding
|
||||
/// (Float32 passthrough, or signed 24-bit packed for `.rf64Int24`).
|
||||
///
|
||||
/// **Not RT-safe.** Construct, write, and close from a non-RT thread (offline render,
|
||||
/// buffer dump, or a `DiskOut` background drain).
|
||||
public final class RF64Writer {
|
||||
|
||||
// MARK: - Format constants
|
||||
|
||||
/// Value written into the 32-bit `RIFF` and `data` size fields; the real 64-bit
|
||||
/// sizes live in the `ds64` chunk. `0xFFFF_FFFF` is the RF64 "see ds64" sentinel.
|
||||
private static let sizeFieldSentinel: UInt32 = 0xFFFF_FFFF
|
||||
|
||||
private static let ds64ChunkBodySize: UInt32 = 28 // riffSize(8) + dataSize(8) + sampleCount(8) + tableLen(4)
|
||||
private static let fmtChunkBodySize: UInt32 = 40 // WAVE_FORMAT_EXTENSIBLE
|
||||
private static let waveFormatExtensible: UInt16 = 0xFFFE
|
||||
private static let fmtExtensionSize: UInt16 = 22 // cbSize for EXTENSIBLE
|
||||
private static let bitsPerByte: Int = 8
|
||||
|
||||
/// Absolute byte offset of the first `ds64` size field (`riffSize`). The three
|
||||
/// 64-bit sizes are contiguous from here (`riffSize`, `dataSize`, `sampleCount`),
|
||||
/// patched in on ``close()``. Fixed by the header layout built in `buildHeader`.
|
||||
private static let ds64RiffSizeOffset: UInt64 = 20
|
||||
|
||||
/// Total header size in bytes; PCM data begins here.
|
||||
static let headerByteCount: Int = 104
|
||||
|
||||
// KSDATAFORMAT_SUBTYPE GUIDs (16 bytes, as laid out in the file).
|
||||
private static let subFormatIEEEFloat: [UInt8] =
|
||||
[0x03, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
|
||||
private static let subFormatPCM: [UInt8] =
|
||||
[0x01, 0, 0, 0, 0, 0, 0x10, 0, 0x80, 0, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71]
|
||||
|
||||
/// Full-scale amplitude for signed 24-bit PCM (`2^23 − 1`).
|
||||
private static let int24FullScale: Float = 8_388_607.0
|
||||
|
||||
// MARK: - State (all non-RT, single-writer)
|
||||
|
||||
private let format: AudioFileFormat
|
||||
private let channels: Int
|
||||
private let bytesPerSample: Int
|
||||
private let blockAlign: Int
|
||||
private let fileHandle: FileHandle
|
||||
|
||||
private var dataBytesWritten: Int = 0
|
||||
private(set) public var framesWritten: Int = 0
|
||||
private var closed: Bool = false
|
||||
|
||||
/// Reusable little-endian conversion scratch (int24 path). Grows only.
|
||||
private var scratch: [UInt8] = []
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Create the file and write the RF64 header with placeholder (`ds64`) sizes.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - url: Destination file. Any existing file is truncated.
|
||||
/// - format: Must be `.rf64Float32` or `.rf64Int24`.
|
||||
/// - sampleRate: Sample rate in Hz written into the `fmt ` chunk.
|
||||
/// - channels: Interleaved channel count (≥ 1).
|
||||
public init(
|
||||
url: URL,
|
||||
format: AudioFileFormat,
|
||||
sampleRate: Double,
|
||||
channels: Int
|
||||
) throws {
|
||||
guard format == .rf64Float32 || format == .rf64Int24 else {
|
||||
throw RF64WriterError.unsupportedFormat(format)
|
||||
}
|
||||
precondition(channels >= 1, "RF64Writer requires channels >= 1, got \(channels)")
|
||||
self.format = format
|
||||
self.channels = channels
|
||||
let bytes: Int = Int(format.fileBitsPerChannel) / RF64Writer.bitsPerByte
|
||||
self.bytesPerSample = bytes
|
||||
self.blockAlign = channels * bytes
|
||||
|
||||
// Create (truncate) the file, then open a handle for writing.
|
||||
guard FileManager.default.createFile(atPath: url.path, contents: nil) else {
|
||||
throw RF64WriterError.cannotCreateFile(url)
|
||||
}
|
||||
do {
|
||||
self.fileHandle = try FileHandle(forWritingTo: url)
|
||||
} catch {
|
||||
throw RF64WriterError.cannotCreateFile(url)
|
||||
}
|
||||
|
||||
let header: [UInt8] = RF64Writer.buildHeader(
|
||||
format: format, sampleRate: sampleRate, channels: channels,
|
||||
blockAlign: blockAlign, bitsPerChannel: Int(format.fileBitsPerChannel)
|
||||
)
|
||||
do {
|
||||
try fileHandle.write(contentsOf: Data(header))
|
||||
} catch {
|
||||
try? fileHandle.close()
|
||||
throw RF64WriterError.writeFailed(error)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Header construction
|
||||
|
||||
/// Build the fixed 104-byte header by appending chunks in order, so no absolute
|
||||
/// byte offsets appear here. `close()` later patches the three `ds64` sizes at
|
||||
/// `ds64RiffSizeOffset` — which is fixed precisely because this layout is fixed.
|
||||
private static func buildHeader(
|
||||
format: AudioFileFormat,
|
||||
sampleRate: Double,
|
||||
channels: Int,
|
||||
blockAlign: Int,
|
||||
bitsPerChannel: Int
|
||||
) -> [UInt8] {
|
||||
var h: [UInt8] = []
|
||||
h.reserveCapacity(headerByteCount)
|
||||
|
||||
func fourCC(_ s: String) { h.append(contentsOf: Array(s.utf8)) }
|
||||
func u16(_ v: UInt16) {
|
||||
h.append(UInt8(truncatingIfNeeded: v))
|
||||
h.append(UInt8(truncatingIfNeeded: v >> 8))
|
||||
}
|
||||
func u32(_ v: UInt32) {
|
||||
for i: Int in 0..<4 { h.append(UInt8(truncatingIfNeeded: v >> (8 * i))) }
|
||||
}
|
||||
|
||||
// RF64 / RIFF-size sentinel / WAVE
|
||||
fourCC("RF64"); u32(sizeFieldSentinel); fourCC("WAVE")
|
||||
|
||||
// ds64 chunk — 64-bit sizes zero for now; patched on close().
|
||||
fourCC("ds64"); u32(ds64ChunkBodySize)
|
||||
u32(0); u32(0) // riffSize (8)
|
||||
u32(0); u32(0) // dataSize (8)
|
||||
u32(0); u32(0) // sampleCount (8)
|
||||
u32(0) // tableLength
|
||||
|
||||
// fmt chunk — WAVE_FORMAT_EXTENSIBLE
|
||||
fourCC("fmt "); u32(fmtChunkBodySize)
|
||||
let avgBytesPerSec: UInt32 = UInt32(sampleRate.rounded()) * UInt32(blockAlign)
|
||||
u16(waveFormatExtensible) // wFormatTag
|
||||
u16(UInt16(channels)) // nChannels
|
||||
u32(UInt32(sampleRate.rounded())) // nSamplesPerSec
|
||||
u32(avgBytesPerSec) // nAvgBytesPerSec
|
||||
u16(UInt16(blockAlign)) // nBlockAlign
|
||||
u16(UInt16(bitsPerChannel)) // wBitsPerSample
|
||||
u16(fmtExtensionSize) // cbSize
|
||||
u16(UInt16(bitsPerChannel)) // wValidBitsPerSample
|
||||
u32(0) // dwChannelMask
|
||||
let guid: [UInt8] = format.isFloatEncoding ? subFormatIEEEFloat : subFormatPCM
|
||||
h.append(contentsOf: guid) // SubFormat GUID (16)
|
||||
|
||||
// data chunk — size sentinel; real size in ds64.
|
||||
fourCC("data"); u32(sizeFieldSentinel)
|
||||
|
||||
return h
|
||||
}
|
||||
|
||||
// MARK: - Write
|
||||
|
||||
/// Append `frames` interleaved frames of native Float32 samples, converting to the
|
||||
/// file encoding. `samples` must contain at least `frames * channels` values.
|
||||
public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer<Float>, frames: Int) throws {
|
||||
guard frames > 0 else { return }
|
||||
let sampleCount: Int = frames * channels
|
||||
|
||||
let payload: Data
|
||||
if format.isFloatEncoding {
|
||||
// Float32 little-endian passthrough (Apple platforms are little-endian).
|
||||
guard let base: UnsafePointer<Float> = samples.baseAddress else { return }
|
||||
payload = Data(buffer: UnsafeBufferPointer(start: base, count: sampleCount))
|
||||
} else {
|
||||
// Signed 24-bit packed little-endian. Round to nearest (matches ExtAudioFile).
|
||||
let byteCount: Int = sampleCount * bytesPerSample
|
||||
if scratch.count < byteCount { scratch = [UInt8](repeating: 0, count: byteCount) }
|
||||
for i: Int in 0..<sampleCount {
|
||||
let clamped: Float = max(-1.0, min(1.0, samples[i]))
|
||||
let s: Int32 = Int32((clamped * RF64Writer.int24FullScale).rounded())
|
||||
scratch[i * 3] = UInt8(truncatingIfNeeded: s)
|
||||
scratch[i * 3 + 1] = UInt8(truncatingIfNeeded: s >> 8)
|
||||
scratch[i * 3 + 2] = UInt8(truncatingIfNeeded: s >> 16)
|
||||
}
|
||||
payload = Data(scratch[0..<byteCount])
|
||||
}
|
||||
|
||||
do {
|
||||
try fileHandle.write(contentsOf: payload)
|
||||
} catch {
|
||||
throw RF64WriterError.writeFailed(error)
|
||||
}
|
||||
dataBytesWritten += sampleCount * bytesPerSample
|
||||
framesWritten += frames
|
||||
}
|
||||
|
||||
// MARK: - Close
|
||||
|
||||
/// Finalise the file: write a RIFF word-alignment pad byte if the `data` payload is
|
||||
/// odd-length, patch the true 64-bit `ds64` sizes, and close the handle. Idempotent.
|
||||
///
|
||||
/// The `FileHandle` is closed unconditionally (even if patching throws) so a failed
|
||||
/// finalise never leaks the descriptor.
|
||||
public func close() throws {
|
||||
guard !closed else { return }
|
||||
closed = true
|
||||
defer { try? fileHandle.close() }
|
||||
|
||||
// RIFF requires a trailing pad byte after an odd-length chunk. The pad is part
|
||||
// of the file (counted in riffSize) but not in the chunk's own dataSize. If the
|
||||
// pad write fails, still patch the ds64 sizes below so the file reports its real
|
||||
// data (not the initialized zero); surface the pad error afterwards.
|
||||
var padWritten: Int = 0
|
||||
var padError: Error? = nil
|
||||
if dataBytesWritten % 2 == 1 {
|
||||
do { try fileHandle.write(contentsOf: Data([0])); padWritten = 1 }
|
||||
catch { padError = error }
|
||||
}
|
||||
|
||||
let dataSize: UInt64 = UInt64(dataBytesWritten)
|
||||
let riffSize: UInt64 = UInt64(RF64Writer.headerByteCount - 8) + dataSize + UInt64(padWritten)
|
||||
let sampleCount: UInt64 = blockAlign > 0 ? dataSize / UInt64(blockAlign) : 0
|
||||
|
||||
func u64LE(_ v: UInt64) -> Data {
|
||||
var bytes: [UInt8] = [UInt8](repeating: 0, count: 8)
|
||||
for i: Int in 0..<8 { bytes[i] = UInt8(truncatingIfNeeded: v >> (8 * i)) }
|
||||
return Data(bytes)
|
||||
}
|
||||
|
||||
do {
|
||||
try fileHandle.seek(toOffset: RF64Writer.ds64RiffSizeOffset)
|
||||
try fileHandle.write(contentsOf: u64LE(riffSize)) // ds64.riffSize
|
||||
try fileHandle.write(contentsOf: u64LE(dataSize)) // ds64.dataSize
|
||||
try fileHandle.write(contentsOf: u64LE(sampleCount)) // ds64.sampleCount
|
||||
} catch {
|
||||
throw RF64WriterError.seekFailed(error)
|
||||
}
|
||||
if let padError: Error = padError {
|
||||
throw RF64WriterError.writeFailed(padError)
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
// Best-effort: if the owner forgot to close(), still patch sizes so the file
|
||||
// is readable. Errors are unrecoverable here and deliberately swallowed.
|
||||
if !closed { try? close() }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// RF64WriterError.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by ``RF64Writer``.
|
||||
public enum RF64WriterError: Error {
|
||||
/// The output file could not be created at the given URL.
|
||||
case cannotCreateFile(URL)
|
||||
/// A `FileHandle` write failed; carries the underlying error.
|
||||
case writeFailed(Error)
|
||||
/// Seeking back to patch the `ds64` sizes on ``RF64Writer/close()`` failed.
|
||||
case seekFailed(Error)
|
||||
/// The format passed to ``RF64Writer/init(url:format:sampleRate:channels:)`` is not
|
||||
/// an RF64 case. Only `.rf64Float32` / `.rf64Int24` are supported.
|
||||
case unsupportedFormat(AudioFileFormat)
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
// DistributionKindSampling.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
extension DistributionKind {
|
||||
|
||||
/// Draw one sample from this distribution, advancing `rng` (a xorshift64
|
||||
/// state). This is the canonical mapping from a ``DistributionKind`` case to
|
||||
/// its sampler — the same mapping ``TemporalTendency`` and
|
||||
/// ``DemandTemporalTendency`` use — exposed for one-shot scalar draws.
|
||||
///
|
||||
/// The `parX` / `parY` / `parA` / `parB` roles are per-distribution; see the
|
||||
/// parameter table on ``DistributionKind``. `parA` / `parB` are optional and
|
||||
/// fall back to each distribution's own default (beta shapes default to `2`;
|
||||
/// Cauchy's positive-only flag defaults off).
|
||||
///
|
||||
/// RT-safe: pure arithmetic, no allocation. For an ergonomic seedable wrapper
|
||||
/// with named per-distribution methods, use ``LyrebirdRandom``.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - parX: First parameter (e.g. `lo`, density, dispersion, dev — per the table).
|
||||
/// - parY: Second parameter (e.g. `hi`, mean — per the table). Ignored by
|
||||
/// single-parameter distributions. Defaults to `1` (matching
|
||||
/// ``TemporalTendency`` / ``DemandTemporalTendency``), so an omitted
|
||||
/// `parY` on a range distribution gives `[lo, 1]` rather than a
|
||||
/// degenerate `[lo, 0]` — but supply it explicitly for a real range.
|
||||
/// - parA: Third parameter (beta `alpha`, Cauchy positive-only flag).
|
||||
/// `nil` uses the distribution's default.
|
||||
/// - parB: Fourth parameter (beta `beta`). `nil` uses the default.
|
||||
/// - rng: xorshift64 state, advanced in place.
|
||||
/// - Returns: One sample.
|
||||
public func sample(
|
||||
parX: Double,
|
||||
parY: Double = 1,
|
||||
parA: Double? = nil,
|
||||
parB: Double? = nil,
|
||||
using rng: inout UInt64
|
||||
) -> Double {
|
||||
let betaDefaultAlpha: Double = 2.0
|
||||
let betaDefaultBeta: Double = 2.0
|
||||
switch self {
|
||||
case .uniform:
|
||||
return _sampleUniform(lo: parX, hi: parY, rng: &rng)
|
||||
case .lpRand:
|
||||
return _sampleLpRand(lo: parX, hi: parY, rng: &rng)
|
||||
case .hpRand:
|
||||
return _sampleHpRand(lo: parX, hi: parY, rng: &rng)
|
||||
case .meanRand:
|
||||
return _sampleMeanRand(lo: parX, hi: parY, rng: &rng)
|
||||
case .expRand:
|
||||
return _sampleExpRand(lo: parX, hi: parY, rng: &rng)
|
||||
case .exponential:
|
||||
return _sampleExponential(density: parX, rng: &rng)
|
||||
case .gamma:
|
||||
return _sampleGamma(shape: parX, rng: &rng)
|
||||
case .laplace:
|
||||
return _sampleLaplace(dispersion: parX, rng: &rng)
|
||||
case .alaplace:
|
||||
return _sampleALaplace(dispersion: parX, rng: &rng)
|
||||
case .hcos:
|
||||
return _sampleHcos(dispersion: parX, rng: &rng)
|
||||
case .logistic:
|
||||
return _sampleLogistic(dispersion: parX, rng: &rng)
|
||||
case .poisson:
|
||||
return _samplePoisson(mean: parX, rng: &rng)
|
||||
case .arcsin:
|
||||
return _sampleArcsin(dispersion: parX, rng: &rng)
|
||||
case .betaRand:
|
||||
return _sampleBetaRand(
|
||||
lo: parX,
|
||||
hi: parY,
|
||||
alpha: parA ?? betaDefaultAlpha,
|
||||
beta: parB ?? betaDefaultBeta,
|
||||
rng: &rng
|
||||
)
|
||||
case .cauchy:
|
||||
return _sampleCauchy(mean: parX, spread: parY, posOnly: (parA ?? 0) > 0, rng: &rng)
|
||||
case .gauss:
|
||||
return _sampleGauss(dev: parX, mean: parY, rng: &rng)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,168 @@
|
||||
// LyrebirdRandom.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A seedable scalar random source over Lyrebird's distribution family.
|
||||
///
|
||||
/// Where ``TemporalStream`` / ``Pattern`` produce *sequences* and the noise
|
||||
/// generators produce *signals*, `LyrebirdRandom` answers the "give me one
|
||||
/// value" case: a single draw from a uniform range, a Gaussian, a Laplace, and
|
||||
/// so on. It owns a xorshift64 state, so a given `seed` produces a fully
|
||||
/// reproducible stream of draws — which is what musical use wants.
|
||||
///
|
||||
/// ```swift
|
||||
/// var r = LyrebirdRandom(seed: 42)
|
||||
/// let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||
/// let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||
/// let jitter: Double = r.gauss(mean: 0, dev: 0.02) // ± around 0
|
||||
/// ```
|
||||
///
|
||||
/// Each draw method maps to a ``DistributionKind`` case; the generic
|
||||
/// ``value(_:parX:parY:parA:parB:)`` reaches any distribution by kind. For
|
||||
/// throwaway draws with no seed bookkeeping, use ``shared``.
|
||||
///
|
||||
/// Value semantics: copying a `LyrebirdRandom` forks its stream. Not
|
||||
/// thread-safe — give each thread its own instance (or use ``shared``, which is
|
||||
/// synchronized).
|
||||
public struct LyrebirdRandom: Sendable {
|
||||
|
||||
/// The live xorshift64 state. Exposed so callers can snapshot/restore a
|
||||
/// draw position; mutated by every draw.
|
||||
public var state: UInt64
|
||||
|
||||
/// Create a reproducible source from an explicit seed.
|
||||
/// - Parameter seed: Any `UInt64`; normalised to a non-zero xorshift state.
|
||||
public init(seed: UInt64) {
|
||||
self.state = lyrebirdSeedXorshift64(from: seed)
|
||||
}
|
||||
|
||||
/// Create a source seeded from system entropy (uptime nanoseconds) — draws
|
||||
/// are not reproducible across runs. Prefer ``init(seed:)`` when you need
|
||||
/// repeatability.
|
||||
public init() {
|
||||
self.state = lyrebirdSeedXorshift64(from: nil)
|
||||
}
|
||||
|
||||
// MARK: - Generic
|
||||
|
||||
/// Draw one sample from `kind`, advancing this source's state.
|
||||
/// - Parameters:
|
||||
/// - kind: The distribution to sample.
|
||||
/// - parX: First parameter (per ``DistributionKind``'s table).
|
||||
/// - parY: Second parameter. Ignored by single-parameter distributions.
|
||||
/// - parA: Third parameter (beta `alpha` / Cauchy positive-only). `nil` = default.
|
||||
/// - parB: Fourth parameter (beta `beta`). `nil` = default.
|
||||
/// - Returns: One sample.
|
||||
public mutating func value(
|
||||
_ kind: DistributionKind,
|
||||
parX: Double,
|
||||
parY: Double = 1,
|
||||
parA: Double? = nil,
|
||||
parB: Double? = nil
|
||||
) -> Double {
|
||||
kind.sample(parX: parX, parY: parY, parA: parA, parB: parB, using: &state)
|
||||
}
|
||||
|
||||
// MARK: - Uniform family
|
||||
|
||||
/// A uniform sample in `[0, 1]`.
|
||||
public mutating func unit() -> Double {
|
||||
DistributionKind.uniform.sample(parX: 0, parY: 1, using: &state)
|
||||
}
|
||||
|
||||
/// Uniform (flat) sample in `[low, high]`.
|
||||
public mutating func uniform(low: Double, high: Double) -> Double {
|
||||
DistributionKind.uniform.sample(parX: low, parY: high, using: &state)
|
||||
}
|
||||
|
||||
/// Sample in `[low, high]` biased toward `low` (squared uniform).
|
||||
public mutating func lowBiased(low: Double, high: Double) -> Double {
|
||||
DistributionKind.lpRand.sample(parX: low, parY: high, using: &state)
|
||||
}
|
||||
|
||||
/// Sample in `[low, high]` biased toward `high` (mirrored squared uniform).
|
||||
public mutating func highBiased(low: Double, high: Double) -> Double {
|
||||
DistributionKind.hpRand.sample(parX: low, parY: high, using: &state)
|
||||
}
|
||||
|
||||
/// Sample in `[low, high]` biased toward the midpoint (mean of two uniforms).
|
||||
public mutating func meanBiased(low: Double, high: Double) -> Double {
|
||||
DistributionKind.meanRand.sample(parX: low, parY: high, using: &state)
|
||||
}
|
||||
|
||||
/// Log-uniform sample in `[low, high]`; both bounds must be `> 0`.
|
||||
public mutating func exponentialRange(low: Double, high: Double) -> Double {
|
||||
DistributionKind.expRand.sample(parX: low, parY: high, using: &state)
|
||||
}
|
||||
|
||||
// MARK: - Single-parameter families
|
||||
|
||||
/// Standard exponential; `density` is the rate λ (`> 0`). Output `≥ 0`.
|
||||
public mutating func exponential(density: Double) -> Double {
|
||||
DistributionKind.exponential.sample(parX: density, using: &state)
|
||||
}
|
||||
|
||||
/// Gamma distribution; `shape` is `k` (`> 0`). `k = 1` is exponential.
|
||||
public mutating func gamma(shape: Double) -> Double {
|
||||
DistributionKind.gamma.sample(parX: shape, using: &state)
|
||||
}
|
||||
|
||||
/// Laplace (double-exponential), symmetric about 0; `scale` is dispersion `b`.
|
||||
public mutating func laplace(scale: Double = 1) -> Double {
|
||||
DistributionKind.laplace.sample(parX: scale, using: &state)
|
||||
}
|
||||
|
||||
/// Asymmetric Laplace (right tail heavier, p = 0.7); `scale` is dispersion `b`.
|
||||
public mutating func asymmetricLaplace(scale: Double = 1) -> Double {
|
||||
DistributionKind.alaplace.sample(parX: scale, using: &state)
|
||||
}
|
||||
|
||||
/// Half-cosine bell centred at 0; output ≈ `[−d/π, d/π]`.
|
||||
public mutating func halfCosine(dispersion: Double = 1) -> Double {
|
||||
DistributionKind.hcos.sample(parX: dispersion, using: &state)
|
||||
}
|
||||
|
||||
/// Logistic distribution centred at 0 (heavier tails than Gaussian); `scale` is `s`.
|
||||
public mutating func logistic(scale: Double = 1) -> Double {
|
||||
DistributionKind.logistic.sample(parX: scale, using: &state)
|
||||
}
|
||||
|
||||
/// Poisson counts; `mean` is λ (clamped to `[0.001, 30]`). Integer-valued.
|
||||
public mutating func poisson(mean: Double) -> Double {
|
||||
DistributionKind.poisson.sample(parX: mean, using: &state)
|
||||
}
|
||||
|
||||
/// U-shaped arcsin distribution; output in `[−dispersion, dispersion]`.
|
||||
public mutating func arcsin(dispersion: Double = 1) -> Double {
|
||||
DistributionKind.arcsin.sample(parX: dispersion, using: &state)
|
||||
}
|
||||
|
||||
// MARK: - Multi-parameter families
|
||||
|
||||
/// Beta distribution mapped to `[low, high]`. `alpha`/`beta` shape it
|
||||
/// (`alpha == beta` symmetric; both `< 1` bimodal; `1, 1` uniform).
|
||||
public mutating func beta(
|
||||
low: Double,
|
||||
high: Double,
|
||||
alpha: Double = 2,
|
||||
beta: Double = 2
|
||||
) -> Double {
|
||||
DistributionKind.betaRand.sample(parX: low, parY: high, parA: alpha, parB: beta, using: &state)
|
||||
}
|
||||
|
||||
/// Cauchy distribution; heavy-tailed. `positiveOnly` folds onto the positive axis.
|
||||
public mutating func cauchy(
|
||||
mean: Double = 0,
|
||||
spread: Double = 1,
|
||||
positiveOnly: Bool = false
|
||||
) -> Double {
|
||||
DistributionKind.cauchy.sample(parX: mean, parY: spread, parA: positiveOnly ? 1 : 0, using: &state)
|
||||
}
|
||||
|
||||
/// Gaussian (normal) distribution; `dev` is the standard deviation σ.
|
||||
public mutating func gauss(mean: Double = 0, dev: Double = 1) -> Double {
|
||||
DistributionKind.gauss.sample(parX: dev, parY: mean, using: &state)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
// SharedRandom.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Process-wide, thread-safe scalar random source for throwaway draws where you
|
||||
/// don't want to thread a ``LyrebirdRandom`` through your code. Reached via
|
||||
/// ``LyrebirdRandom/shared``.
|
||||
///
|
||||
/// ```swift
|
||||
/// let x: Double = LyrebirdRandom.shared.uniform(low: 0, high: 1)
|
||||
/// let g: Double = LyrebirdRandom.shared.gauss(mean: 0, dev: 1)
|
||||
/// ```
|
||||
///
|
||||
/// System-seeded, so its stream is **not reproducible** across runs, and its
|
||||
/// interleaving across threads is non-deterministic — every draw locks a shared
|
||||
/// state. When you need repeatable draws (e.g. a rendered score), use an owned
|
||||
/// `LyrebirdRandom(seed:)` instead. Call ``reseed(_:)`` to pin the shared stream
|
||||
/// for a test.
|
||||
public final class SharedRandom: @unchecked Sendable {
|
||||
|
||||
private var gen: LyrebirdRandom
|
||||
private let lock: NSLock = NSLock()
|
||||
|
||||
init() {
|
||||
self.gen = LyrebirdRandom()
|
||||
}
|
||||
|
||||
/// Replace the shared state with one seeded from `seed`. Mainly for tests
|
||||
/// that need the shared source to be reproducible.
|
||||
public func reseed(_ seed: UInt64) {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
gen = LyrebirdRandom(seed: seed)
|
||||
}
|
||||
|
||||
private func locked(_ body: (inout LyrebirdRandom) -> Double) -> Double {
|
||||
lock.lock(); defer { lock.unlock() }
|
||||
return body(&gen)
|
||||
}
|
||||
|
||||
/// See ``LyrebirdRandom/value(_:parX:parY:parA:parB:)``.
|
||||
public func value(
|
||||
_ kind: DistributionKind,
|
||||
parX: Double,
|
||||
parY: Double = 1,
|
||||
parA: Double? = nil,
|
||||
parB: Double? = nil
|
||||
) -> Double {
|
||||
locked { $0.value(kind, parX: parX, parY: parY, parA: parA, parB: parB) }
|
||||
}
|
||||
|
||||
/// See ``LyrebirdRandom/unit()``.
|
||||
public func unit() -> Double { locked { $0.unit() } }
|
||||
|
||||
/// See ``LyrebirdRandom/uniform(low:high:)``.
|
||||
public func uniform(low: Double, high: Double) -> Double { locked { $0.uniform(low: low, high: high) } }
|
||||
|
||||
/// See ``LyrebirdRandom/lowBiased(low:high:)``.
|
||||
public func lowBiased(low: Double, high: Double) -> Double { locked { $0.lowBiased(low: low, high: high) } }
|
||||
|
||||
/// See ``LyrebirdRandom/highBiased(low:high:)``.
|
||||
public func highBiased(low: Double, high: Double) -> Double { locked { $0.highBiased(low: low, high: high) } }
|
||||
|
||||
/// See ``LyrebirdRandom/meanBiased(low:high:)``.
|
||||
public func meanBiased(low: Double, high: Double) -> Double { locked { $0.meanBiased(low: low, high: high) } }
|
||||
|
||||
/// See ``LyrebirdRandom/exponentialRange(low:high:)``.
|
||||
public func exponentialRange(low: Double, high: Double) -> Double { locked { $0.exponentialRange(low: low, high: high) } }
|
||||
|
||||
/// See ``LyrebirdRandom/exponential(density:)``.
|
||||
public func exponential(density: Double) -> Double { locked { $0.exponential(density: density) } }
|
||||
|
||||
/// See ``LyrebirdRandom/gamma(shape:)``.
|
||||
public func gamma(shape: Double) -> Double { locked { $0.gamma(shape: shape) } }
|
||||
|
||||
/// See ``LyrebirdRandom/laplace(scale:)``.
|
||||
public func laplace(scale: Double = 1) -> Double { locked { $0.laplace(scale: scale) } }
|
||||
|
||||
/// See ``LyrebirdRandom/asymmetricLaplace(scale:)``.
|
||||
public func asymmetricLaplace(scale: Double = 1) -> Double { locked { $0.asymmetricLaplace(scale: scale) } }
|
||||
|
||||
/// See ``LyrebirdRandom/halfCosine(dispersion:)``.
|
||||
public func halfCosine(dispersion: Double = 1) -> Double { locked { $0.halfCosine(dispersion: dispersion) } }
|
||||
|
||||
/// See ``LyrebirdRandom/logistic(scale:)``.
|
||||
public func logistic(scale: Double = 1) -> Double { locked { $0.logistic(scale: scale) } }
|
||||
|
||||
/// See ``LyrebirdRandom/poisson(mean:)``.
|
||||
public func poisson(mean: Double) -> Double { locked { $0.poisson(mean: mean) } }
|
||||
|
||||
/// See ``LyrebirdRandom/arcsin(dispersion:)``.
|
||||
public func arcsin(dispersion: Double = 1) -> Double { locked { $0.arcsin(dispersion: dispersion) } }
|
||||
|
||||
/// See ``LyrebirdRandom/beta(low:high:alpha:beta:)``.
|
||||
public func beta(
|
||||
low: Double,
|
||||
high: Double,
|
||||
alpha: Double = 2,
|
||||
beta: Double = 2
|
||||
) -> Double {
|
||||
locked { $0.beta(low: low, high: high, alpha: alpha, beta: beta) }
|
||||
}
|
||||
|
||||
/// See ``LyrebirdRandom/cauchy(mean:spread:positiveOnly:)``.
|
||||
public func cauchy(
|
||||
mean: Double = 0,
|
||||
spread: Double = 1,
|
||||
positiveOnly: Bool = false
|
||||
) -> Double {
|
||||
locked { $0.cauchy(mean: mean, spread: spread, positiveOnly: positiveOnly) }
|
||||
}
|
||||
|
||||
/// See ``LyrebirdRandom/gauss(mean:dev:)``.
|
||||
public func gauss(mean: Double = 0, dev: Double = 1) -> Double {
|
||||
locked { $0.gauss(mean: mean, dev: dev) }
|
||||
}
|
||||
}
|
||||
|
||||
extension LyrebirdRandom {
|
||||
/// Process-wide thread-safe source for quick, non-reproducible draws.
|
||||
/// See ``SharedRandom``.
|
||||
public static let shared: SharedRandom = SharedRandom()
|
||||
}
|
||||
|
||||
/// Global shorthand for the process-wide shared random source
|
||||
/// (``LyrebirdRandom/shared``) — the common non-seeded case.
|
||||
///
|
||||
/// ```swift
|
||||
/// let pan: Double = Random.uniform(low: -1, high: 1)
|
||||
/// let freq: Double = Random.exponentialRange(low: 200, high: 2000)
|
||||
/// ```
|
||||
///
|
||||
/// Draws are **not reproducible** across runs; for a repeatable seeded stream use
|
||||
/// `LyrebirdRandom(seed:)`. Capitalized to avoid shadowing C's `rand()`.
|
||||
public let Random: SharedRandom = LyrebirdRandom.shared
|
||||
@@ -495,6 +495,7 @@ public final class EngineHost: @unchecked Sendable {
|
||||
let driver: NRTDriver = NRTDriver(
|
||||
outputURL: job.outputURL,
|
||||
duration: job.duration,
|
||||
format: job.format,
|
||||
inputURL: job.inputURL,
|
||||
inputStartOffset: job.inputStartOffset
|
||||
)
|
||||
|
||||
@@ -26,11 +26,16 @@ import Foundation
|
||||
/// fires automatically.
|
||||
public struct NRTJob: Sendable {
|
||||
|
||||
/// Destination file URL the rendered audio writes to. CAF format
|
||||
/// per `NRTDriver`'s contract; the file is created by the driver
|
||||
/// at `engine.start()` time.
|
||||
/// Destination file URL the rendered audio writes to. The file is
|
||||
/// created by the driver at `engine.start()` time, using ``format``.
|
||||
public let outputURL: URL
|
||||
|
||||
/// Container and PCM encoding for ``outputURL``. Maps to
|
||||
/// `NRTDriver.init(format:)`. Defaults to `.cafFloat32` — CAF is
|
||||
/// 64-bit-sized (no 4 GB cap) and carries any channel count, which
|
||||
/// suits long offline renders and multichannel stems.
|
||||
public let format: AudioFileFormat
|
||||
|
||||
/// Render duration in seconds. Maps to `NRTDriver.init(duration:)`.
|
||||
public let duration: Double
|
||||
|
||||
@@ -86,6 +91,7 @@ public struct NRTJob: Sendable {
|
||||
public init(
|
||||
outputURL: URL,
|
||||
duration: Double,
|
||||
format: AudioFileFormat = .cafFloat32,
|
||||
blockSize: Int = lyrebirdDefaultResultBufferSize,
|
||||
sampleRate: Double = lyrebirdDefaultSampleRate,
|
||||
numOutputChannels: Int = 2,
|
||||
@@ -95,6 +101,7 @@ public struct NRTJob: Sendable {
|
||||
build: @escaping @Sendable (SynthesisEngine) throws -> Void
|
||||
) {
|
||||
self.outputURL = outputURL
|
||||
self.format = format
|
||||
self.duration = duration
|
||||
self.blockSize = blockSize
|
||||
self.sampleRate = sampleRate
|
||||
|
||||
@@ -40,7 +40,8 @@ public enum DiskOut {
|
||||
/// The overflow guard (`used + count <= _ringSize`) ensures indices never alias.
|
||||
/// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`.
|
||||
/// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`.
|
||||
/// - `_fileRef` and `_interleavedWriteBuf` are BG-only after `init`.
|
||||
/// - `_fileRef`, `_rf64Writer`, `_cumulativeFramesWritten`, and
|
||||
/// `_interleavedWriteBuf` are BG-only after `init`.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
@@ -58,6 +59,16 @@ public enum DiskOut {
|
||||
/// try engine.start() // render / play
|
||||
/// diskOut.close() // flush remaining frames and close the file
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - source: Audio source to record and pass through.
|
||||
/// - channelCount: Number of channels to record and pass through. Must be ≥ 1.
|
||||
/// - url: Output file path. Created (or overwritten) immediately in `init`.
|
||||
/// - sampleRate: Sample rate written into the file header. Defaults to 48000 Hz.
|
||||
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to `.aiffFloat32`.
|
||||
/// - bufferFrames: Ring buffer capacity in frames. Must be a power of two. Defaults to 8192.
|
||||
/// - mul: Output scale factor. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: GeneratorBase, @unchecked Sendable, AudioGenerator, RootRegistering {
|
||||
|
||||
// MARK: - Generator protocol
|
||||
@@ -100,6 +111,10 @@ public enum DiskOut {
|
||||
|
||||
private var _interleavedWriteBuf: [Float]
|
||||
|
||||
/// Cumulative frames written to the file across the whole session. BG-only
|
||||
/// (touched only in `_drainAndWrite`). Drives the large-file guard.
|
||||
private var _cumulativeFramesWritten: Int = 0
|
||||
|
||||
// MARK: - Pass-through output
|
||||
private var _mulAdd: MulAddSpec
|
||||
|
||||
@@ -109,14 +124,30 @@ public enum DiskOut {
|
||||
|
||||
private var _fileRef: ExtAudioFileRef?
|
||||
|
||||
/// RF64 backend for the `.rf64Float32` / `.rf64Int24` formats (`ExtAudioFile`
|
||||
/// can't write RF64). Exactly one of `_fileRef` / `_rf64Writer` is non-nil.
|
||||
private var _rf64Writer: RF64Writer?
|
||||
|
||||
/// Output container/encoding — fixed at init. Read by the BG drain's
|
||||
/// large-file guard (`riffOverflow`); CAF/RF64 are exempt.
|
||||
private let _outputFormat: AudioFileFormat
|
||||
|
||||
private let _backgroundQueue: DispatchQueue
|
||||
private let _stopped: Atomic<Bool> = Atomic(false)
|
||||
private let _writeError: Atomic<Bool> = Atomic(false)
|
||||
private let _fileTooLarge: Atomic<Bool> = Atomic(false)
|
||||
|
||||
/// `true` if any `ExtAudioFileWrite` call failed during recording.
|
||||
/// Poll from a non-RT context after `close()` to detect disk write errors.
|
||||
public var writeError: Bool { _writeError.load(ordering: .acquiring) }
|
||||
|
||||
/// `true` if recording stopped early because the file reached the WAV/AIFF
|
||||
/// 4 GB container cap (see `lyrebirdMaxRIFFBytes`). Frames past the cap are
|
||||
/// dropped rather than corrupting the file; audio already written stays
|
||||
/// valid. Always `false` for `.cafFloat32` (CAF is 64-bit, uncapped). Poll
|
||||
/// from a non-RT context.
|
||||
public var fileTooLarge: Bool { _fileTooLarge.load(ordering: .acquiring) }
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// Create a streaming disk recorder.
|
||||
@@ -131,17 +162,21 @@ public enum DiskOut {
|
||||
/// - url: Output file path. Created or overwritten immediately.
|
||||
/// - sampleRate: Engine sample rate written into the file header. Defaults
|
||||
/// to 48 000 Hz.
|
||||
/// - format: Container format. Defaults to `.aiff`.
|
||||
/// - format: Container and PCM encoding. Defaults to `.aiffFloat32`.
|
||||
/// - bufferFrames: Ring buffer capacity in frames. Must be a power of two.
|
||||
/// Default 8 192 (≈ 170 ms at 48 kHz).
|
||||
/// - mul: Output scale factor. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
///
|
||||
/// - Throws: ``DiskOutError`` on file-create/format failure for the
|
||||
/// `ExtAudioFile`-backed formats. For the `.rf64*` formats, a
|
||||
/// ``RF64WriterError`` may surface instead.
|
||||
public init(
|
||||
source: any ValidGeneratorInput,
|
||||
channelCount: Int,
|
||||
url: URL,
|
||||
sampleRate: Double = 48000,
|
||||
format: DiskOutFormat = .aiff,
|
||||
format: AudioFileFormat = .aiffFloat32,
|
||||
bufferFrames: Int = 8192,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
@@ -152,10 +187,16 @@ public enum DiskOut {
|
||||
bufferFrames > 0 && bufferFrames & (bufferFrames - 1) == 0,
|
||||
"DiskOut.Audio: bufferFrames \(bufferFrames) must be a power of two"
|
||||
)
|
||||
// Streaming a compressed encoder (priming/latency/flush) is out of scope —
|
||||
// reject before any allocation. AAC / ALAC render offline instead.
|
||||
guard !format.isCompressed else {
|
||||
throw DiskOutError.compressedFormatNotSupported(format)
|
||||
}
|
||||
|
||||
let resolvedSource: any ValidGeneratorInput = source._resolvedInput()
|
||||
self.channelCount = channelCount
|
||||
self._source = resolvedSource
|
||||
self._outputFormat = format
|
||||
self._ringSize = bufferFrames
|
||||
self._ringMask = bufferFrames - 1
|
||||
|
||||
@@ -170,78 +211,60 @@ public enum DiskOut {
|
||||
_backgroundQueue = DispatchQueue(label: "com.lyrebird.diskout",
|
||||
qos: .userInitiated)
|
||||
|
||||
// Create the output file.
|
||||
//
|
||||
// File format is derived from `format` (may be integer-encoded).
|
||||
// Client format is always Float32 interleaved — ExtAudioFile handles
|
||||
// the Float32 → int16/int24 conversion transparently.
|
||||
let fileBytesPerSample: UInt32 = UInt32(format.fileBitsPerChannel / 8)
|
||||
var fileFormatFlags: AudioFormatFlags = kAudioFormatFlagIsPacked
|
||||
if format.isFloatEncoding {
|
||||
fileFormatFlags |= kAudioFormatFlagIsFloat
|
||||
// Create the output file. RF64 (64-bit WAV) goes through RF64Writer;
|
||||
// everything else through ExtAudioFile. Client samples are always native
|
||||
// Float32 interleaved — ExtAudioFile handles Float32 → int16/int24, and
|
||||
// RF64Writer handles Float32 → RF64 float/int24, transparently.
|
||||
if format.usesRF64Writer {
|
||||
do {
|
||||
_rf64Writer = try RF64Writer(
|
||||
url: url, format: format, sampleRate: sampleRate, channels: channelCount
|
||||
)
|
||||
} catch {
|
||||
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
|
||||
// Rethrow the RF64WriterError directly (init throws are untyped).
|
||||
_ringStorage.deallocate()
|
||||
throw error
|
||||
}
|
||||
} else {
|
||||
fileFormatFlags |= kAudioFormatFlagIsSignedInteger
|
||||
}
|
||||
if format.isBigEndian {
|
||||
fileFormatFlags |= kAudioFormatFlagIsBigEndian
|
||||
}
|
||||
var fileFmt: AudioStreamBasicDescription =
|
||||
format.makeFileASBD(sampleRate: sampleRate, channels: channelCount)
|
||||
var rawRef: ExtAudioFileRef?
|
||||
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
||||
url as CFURL,
|
||||
format.audioFileTypeID,
|
||||
&fileFmt,
|
||||
nil,
|
||||
AudioFileFlags.eraseFile.rawValue,
|
||||
&rawRef
|
||||
)
|
||||
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
|
||||
// These guards throw before `super.init()`, so `deinit` will not
|
||||
// run — free the raw ring storage explicitly or it leaks. (The
|
||||
// former `[[Float]]` ring was ARC-managed and torn down here for
|
||||
// free; raw memory is not.)
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotCreateFile(createStatus)
|
||||
}
|
||||
_fileRef = rawRef
|
||||
|
||||
var fileFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: fileFormatFlags,
|
||||
mBytesPerPacket: fileBytesPerSample * UInt32(channelCount),
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: fileBytesPerSample * UInt32(channelCount),
|
||||
mChannelsPerFrame: UInt32(channelCount),
|
||||
mBitsPerChannel: format.fileBitsPerChannel,
|
||||
mReserved: 0
|
||||
)
|
||||
var rawRef: ExtAudioFileRef?
|
||||
let createStatus: OSStatus = ExtAudioFileCreateWithURL(
|
||||
url as CFURL,
|
||||
format.audioFileType,
|
||||
&fileFmt,
|
||||
nil,
|
||||
AudioFileFlags.eraseFile.rawValue,
|
||||
&rawRef
|
||||
)
|
||||
guard createStatus == noErr, let rawRef: ExtAudioFileRef else {
|
||||
// These guards throw before `super.init()`, so `deinit` will not
|
||||
// run — free the raw ring storage explicitly or it leaks. (The
|
||||
// former `[[Float]]` ring was ARC-managed and torn down here for
|
||||
// free; raw memory is not.)
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotCreateFile(createStatus)
|
||||
}
|
||||
_fileRef = rawRef
|
||||
|
||||
// Client format is always Float32 interleaved, regardless of the file
|
||||
// encoding. ExtAudioFile converts float→int when writing to the file.
|
||||
let float32ByteSize: UInt32 = UInt32(MemoryLayout<Float>.size)
|
||||
var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription(
|
||||
mSampleRate: sampleRate,
|
||||
mFormatID: kAudioFormatLinearPCM,
|
||||
mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked,
|
||||
mBytesPerPacket: float32ByteSize * UInt32(channelCount),
|
||||
mFramesPerPacket: 1,
|
||||
mBytesPerFrame: float32ByteSize * UInt32(channelCount),
|
||||
mChannelsPerFrame: UInt32(channelCount),
|
||||
mBitsPerChannel: lyrebirdBitsPerSample,
|
||||
mReserved: 0
|
||||
)
|
||||
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
|
||||
rawRef,
|
||||
kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt
|
||||
)
|
||||
guard setFmtStatus == noErr else {
|
||||
ExtAudioFileDispose(rawRef)
|
||||
_fileRef = nil
|
||||
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotSetFormat(setFmtStatus)
|
||||
// Client format is always Float32 interleaved, regardless of the file
|
||||
// encoding. ExtAudioFile converts float→int when writing to the file.
|
||||
var clientFmt: AudioStreamBasicDescription =
|
||||
format.makeClientASBD(sampleRate: sampleRate, channels: channelCount)
|
||||
let setFmtStatus: OSStatus = ExtAudioFileSetProperty(
|
||||
rawRef,
|
||||
kExtAudioFileProperty_ClientDataFormat,
|
||||
UInt32(MemoryLayout<AudioStreamBasicDescription>.size),
|
||||
&clientFmt
|
||||
)
|
||||
guard setFmtStatus == noErr else {
|
||||
ExtAudioFileDispose(rawRef)
|
||||
_fileRef = nil
|
||||
// Pre-`super.init()` throw — `deinit` won't run; free the ring.
|
||||
_ringStorage.deallocate()
|
||||
throw DiskOutError.cannotSetFormat(setFmtStatus)
|
||||
}
|
||||
}
|
||||
|
||||
super.init(channels: channelCount)
|
||||
@@ -264,6 +287,12 @@ public enum DiskOut {
|
||||
ExtAudioFileDispose(ref)
|
||||
_fileRef = nil
|
||||
}
|
||||
if let writer: RF64Writer = _rf64Writer {
|
||||
// Patch the ds64 sizes and close. A failure here means the size fields
|
||||
// stay unpatched; surface it via the same flag as write errors.
|
||||
do { try writer.close() } catch { _writeError.store(true, ordering: .releasing) }
|
||||
_rf64Writer = nil
|
||||
}
|
||||
}
|
||||
|
||||
deinit {
|
||||
@@ -275,6 +304,10 @@ public enum DiskOut {
|
||||
// finished its current iteration before deinit can start, so _fileRef
|
||||
// is not being accessed concurrently; direct disposal is safe.
|
||||
if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) }
|
||||
// RF64Writer.close() patches the ds64 sizes; its own deinit is a
|
||||
// best-effort fallback, but call it here so a forgotten close() still
|
||||
// finalises the file. Safe for the same no-concurrent-BG reason above.
|
||||
try? _rf64Writer?.close()
|
||||
}
|
||||
// Free the raw ring storage. Safe here for the same reason the file
|
||||
// disposal is: the BG loop upgrades its `[weak self]` to a strong
|
||||
@@ -309,7 +342,14 @@ public enum DiskOut {
|
||||
let rHead: Int = _framesRead.load(ordering: .relaxed)
|
||||
let wHead: Int = _framesWritten.load(ordering: .acquiring)
|
||||
let available: Int = wHead - rHead
|
||||
guard available > 0, let fileRef: ExtAudioFileRef = _fileRef else { return }
|
||||
guard available > 0, (_fileRef != nil || _rf64Writer != nil) else { return }
|
||||
|
||||
// Once the file has hit the container cap, discard remaining frames
|
||||
// without writing (keeps the ring draining so the RT side never stalls).
|
||||
if _fileTooLarge.load(ordering: .acquiring) {
|
||||
_framesRead.store(rHead + available, ordering: .releasing)
|
||||
return
|
||||
}
|
||||
|
||||
// Drain in chunks no larger than the interleaved write buffer capacity.
|
||||
let chunkFrames: Int = _interleavedWriteBuf.count / channelCount // == _ringSize
|
||||
@@ -317,32 +357,53 @@ public enum DiskOut {
|
||||
|
||||
while totalDrained < available {
|
||||
let toWrite: Int = min(chunkFrames, available - totalDrained)
|
||||
|
||||
// Large-file guard: for WAV/AIFF (32-bit-sized), stop before a write
|
||||
// that would push the file past the 4 GB cap. CAF → riffOverflow nil,
|
||||
// so this is a no-op for the default streaming format.
|
||||
if _outputFormat.riffOverflow(
|
||||
frameCount: _cumulativeFramesWritten + toWrite, channels: channelCount
|
||||
) != nil {
|
||||
_fileTooLarge.store(true, ordering: .releasing)
|
||||
break
|
||||
}
|
||||
|
||||
for f: Int in 0..<toWrite {
|
||||
let pos: Int = (rHead + totalDrained + f) & _ringMask
|
||||
for ch: Int in 0..<channelCount {
|
||||
_interleavedWriteBuf[f * channelCount + ch] = _ringStorage[ch * _ringSize + pos]
|
||||
}
|
||||
}
|
||||
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
let frames: UInt32 = UInt32(toWrite)
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(channelCount),
|
||||
mDataByteSize: UInt32(
|
||||
toWrite * channelCount * MemoryLayout<Float>.size),
|
||||
mData: base
|
||||
if let rf64Writer: RF64Writer = _rf64Writer {
|
||||
_interleavedWriteBuf.withUnsafeBufferPointer { ptr in
|
||||
do { try rf64Writer.writeFloat32Interleaved(ptr, frames: toWrite) }
|
||||
catch { _writeError.store(true, ordering: .releasing) }
|
||||
}
|
||||
} else if let fileRef: ExtAudioFileRef = _fileRef {
|
||||
_interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in
|
||||
guard let base: UnsafeMutablePointer<Float> = ptr.baseAddress else { return }
|
||||
let frames: UInt32 = UInt32(toWrite)
|
||||
var bufList: AudioBufferList = AudioBufferList(
|
||||
mNumberBuffers: 1,
|
||||
mBuffers: AudioBuffer(
|
||||
mNumberChannels: UInt32(channelCount),
|
||||
mDataByteSize: UInt32(
|
||||
toWrite * channelCount * MemoryLayout<Float>.size),
|
||||
mData: base
|
||||
)
|
||||
)
|
||||
)
|
||||
let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList)
|
||||
if writeStatus != noErr {
|
||||
_writeError.store(true, ordering: .releasing)
|
||||
let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList)
|
||||
if writeStatus != noErr {
|
||||
_writeError.store(true, ordering: .releasing)
|
||||
}
|
||||
}
|
||||
}
|
||||
_cumulativeFramesWritten += toWrite
|
||||
totalDrained += toWrite
|
||||
}
|
||||
|
||||
// Advance the read head by everything that was available — including any
|
||||
// frames skipped after an overflow break — so the ring keeps draining.
|
||||
_framesRead.store(rHead + available, ordering: .releasing)
|
||||
}
|
||||
|
||||
|
||||
@@ -11,4 +11,9 @@ import AudioToolbox
|
||||
public enum DiskOutError: Error {
|
||||
case cannotCreateFile(OSStatus)
|
||||
case cannotSetFormat(OSStatus)
|
||||
/// A compressed format (AAC / ALAC) was passed to ``DiskOut/Audio``. Real-time
|
||||
/// streaming to a compressed codec is not supported — use a PCM or RF64 format
|
||||
/// for `DiskOut`, and render offline (`LyrebirdBuffer.write` / `NRTDriver`) for
|
||||
/// AAC / ALAC output.
|
||||
case compressedFormatNotSupported(AudioFileFormat)
|
||||
}
|
||||
|
||||
@@ -4,87 +4,12 @@
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import AudioToolbox
|
||||
|
||||
/// Container-and-encoding format for ``DiskOut/Audio``.
|
||||
/// Deprecated alias for the framework-wide ``AudioFileFormat``.
|
||||
///
|
||||
/// Each case encodes both the container (WAV or AIFF) and the PCM bit depth.
|
||||
/// ``DiskOut/Audio`` always accepts Float32 from the signal graph (the client
|
||||
/// data format) and delegates any necessary conversion to `ExtAudioFile`.
|
||||
public enum DiskOutFormat: Sendable {
|
||||
|
||||
// MARK: - WAV variants
|
||||
|
||||
/// WAV container with 32-bit IEEE-754 float encoding.
|
||||
case wavFloat32
|
||||
/// WAV container with 16-bit signed integer encoding.
|
||||
case wavInt16
|
||||
/// WAV container with 24-bit signed integer encoding.
|
||||
case wavInt24
|
||||
|
||||
// MARK: - AIFF-C variants
|
||||
|
||||
/// AIFF-C container with 32-bit IEEE-754 float encoding.
|
||||
case aiffFloat32
|
||||
|
||||
// MARK: - Deprecated shorthands (kept for DiskOut.Audio default parameter)
|
||||
|
||||
/// AIFF-C container with 32-bit float encoding. Alias for ``aiffFloat32``.
|
||||
public static let aiff: DiskOutFormat = .aiffFloat32
|
||||
/// WAV container with 32-bit float encoding. Alias for ``wavFloat32``.
|
||||
public static let wav: DiskOutFormat = .wavFloat32
|
||||
|
||||
// MARK: - Derived properties
|
||||
|
||||
/// AudioToolbox container type ID used when creating the `ExtAudioFile`.
|
||||
var audioFileType: AudioFileTypeID {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24:
|
||||
return kAudioFileWAVEType
|
||||
case .aiffFloat32:
|
||||
return kAudioFileAIFCType
|
||||
}
|
||||
}
|
||||
|
||||
/// Filesystem extension for the output file (without the leading dot).
|
||||
public var fileExtension: String {
|
||||
switch self {
|
||||
case .wavFloat32, .wavInt16, .wavInt24:
|
||||
return "wav"
|
||||
case .aiffFloat32:
|
||||
return "aiff"
|
||||
}
|
||||
}
|
||||
|
||||
/// Bits per sample in the encoded file.
|
||||
var fileBitsPerChannel: UInt32 {
|
||||
switch self {
|
||||
case .wavFloat32, .aiffFloat32:
|
||||
return 32
|
||||
case .wavInt16:
|
||||
return 16
|
||||
case .wavInt24:
|
||||
return 24
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when the file encoding is IEEE-754 float.
|
||||
var isFloatEncoding: Bool {
|
||||
switch self {
|
||||
case .wavFloat32, .aiffFloat32:
|
||||
return true
|
||||
case .wavInt16, .wavInt24:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/// `true` when the container stores big-endian samples (AIFF-C spec).
|
||||
var isBigEndian: Bool {
|
||||
switch self {
|
||||
case .aiffFloat32:
|
||||
return true
|
||||
case .wavFloat32, .wavInt16, .wavInt24:
|
||||
return false
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The container/encoding enum is shared across ``DiskOut/Audio``,
|
||||
/// ``LyrebirdBuffer/write(to:format:sampleRate:)``, and the NRT driver, so it now
|
||||
/// lives under one name. This alias keeps existing `DiskOutFormat.wavFloat32` /
|
||||
/// `.aiffFloat32` / `.wav` / `.aiff` spellings compiling; migrate to
|
||||
/// ``AudioFileFormat`` directly.
|
||||
@available(*, deprecated, message: "Use AudioFileFormat instead.")
|
||||
public typealias DiskOutFormat = AudioFileFormat
|
||||
|
||||
@@ -11,7 +11,11 @@ import Darwin
|
||||
/// the output never exceeds ±`maxAmplitude` regardless of transients.
|
||||
///
|
||||
/// The gain attack is instantaneous within the look-ahead window. Gain release uses
|
||||
/// a one-pole smoother with a time constant equal to `lookAheadTime`.
|
||||
/// a one-pole smoother whose time constant is `releaseTime`, decoupled from
|
||||
/// `lookAheadTime`. A too-fast release modulates the gain within a single cycle of a
|
||||
/// low-frequency signal, which distorts sustained bass; keeping release slow (tens of
|
||||
/// ms) while the look-ahead window stays short (a few ms) catches transients without
|
||||
/// that distortion.
|
||||
///
|
||||
/// ## Latency
|
||||
/// Output is delayed by exactly `lookAheadSamples = Int(lookAheadTime × sampleRate)`.
|
||||
@@ -42,18 +46,22 @@ import Darwin
|
||||
/// - maxAmplitude: Peak ceiling (absolute value). Output `|y|` never exceeds
|
||||
/// this value once the look-ahead window has filled. Default `1.0`.
|
||||
/// - lookAheadTime: Look-ahead and output delay in seconds. Fixed at init —
|
||||
/// determines ring buffer size and release time constant.
|
||||
/// Range `[0, ∞)`; values above ~50 ms waste memory.
|
||||
/// Default `0.005` (5 ms).
|
||||
/// determines ring buffer size. Range `[0, ∞)`; values above
|
||||
/// ~50 ms waste memory. Default `0.005` (5 ms).
|
||||
/// - releaseTime: Gain-release time constant in seconds. Clamped to ≥ 0. Read per block,
|
||||
/// so it may be driven by a live parameter. Independent of `lookAheadTime`.
|
||||
/// Keep it well above the period of the lowest frequency you expect
|
||||
/// (tens of ms) to avoid low-frequency distortion. Default `0.050`.
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer sizes and release coefficient
|
||||
/// are computed at init from this value and cannot be updated at runtime.
|
||||
/// Required — no default. Ring buffer sizes are computed at init from
|
||||
/// this value and cannot be updated at runtime.
|
||||
public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _maxAmpInput: any ValidGeneratorInput
|
||||
private let _releaseTimeInput: any ValidGeneratorInput
|
||||
private let _lookAheadSamples: Int
|
||||
|
||||
// MARK: - Pre-allocated delay ring
|
||||
@@ -80,8 +88,6 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
|
||||
private var _writePos: Int = 0
|
||||
private var _gain: Double = 1.0
|
||||
private let _releaseCoeff: Double
|
||||
private let _attackComp: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
@@ -90,30 +96,30 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
/// - maxAmplitude: Peak ceiling (absolute value). Output `|y|` never exceeds
|
||||
/// this value once the look-ahead window has filled. Default `1.0`.
|
||||
/// - lookAheadTime: Look-ahead and output delay in seconds. Fixed at init —
|
||||
/// determines ring buffer size and release time constant.
|
||||
/// Range `[0, ∞)`. Default `0.005` (5 ms).
|
||||
/// determines ring buffer size. Range `[0, ∞)`. Default `0.005` (5 ms).
|
||||
/// - releaseTime: Gain-release time constant in seconds. Clamped to ≥ 0. Read per block, so it may be
|
||||
/// driven by a live parameter. Independent of `lookAheadTime`. Default `0.050`.
|
||||
/// - sampleRate: Engine sample rate in Hz. **Must match `SynthesisEngine.sampleRate`.**
|
||||
/// Required — no default. Ring buffer sizes and the release coefficient
|
||||
/// are computed at init from this value and cannot be updated at runtime.
|
||||
/// Required — no default. Ring buffer sizes are computed at init from this
|
||||
/// value and cannot be updated at runtime.
|
||||
public init(
|
||||
in input: any ValidGeneratorInput,
|
||||
maxAmplitude: any ValidGeneratorInput = 1.0,
|
||||
lookAheadTime: Double = 0.005,
|
||||
releaseTime: any ValidGeneratorInput = 0.050,
|
||||
sampleRate: Double
|
||||
) {
|
||||
precondition(lookAheadTime >= 0, "LookAheadLimiter: lookAheadTime must be ≥ 0")
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedMaxAmp: any ValidGeneratorInput = maxAmplitude._resolvedInput()
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedMaxAmp: any ValidGeneratorInput = maxAmplitude._resolvedInput()
|
||||
let resolvedRelease: any ValidGeneratorInput = releaseTime._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_maxAmpInput = resolvedMaxAmp
|
||||
_releaseTimeInput = resolvedRelease
|
||||
_lookAheadSamples = Int(lookAheadTime * sampleRate)
|
||||
let bufferSize: Int = _lookAheadSamples + lyrebirdDefaultResultBufferSize + 1
|
||||
_ringSize = bufferSize
|
||||
_delayRing = [Double](repeating: 0.0, count: bufferSize)
|
||||
_releaseCoeff = lookAheadTime > 0
|
||||
? exp(-1.0 / (sampleRate * lookAheadTime))
|
||||
: 0.0
|
||||
_attackComp = 1.0 - _releaseCoeff
|
||||
// Deque capacity = max-live (_lookAheadSamples + 1) + 1 slot of slack
|
||||
// so push-before-front-pop on a wraparound step does not collide.
|
||||
_dequeCapacity = max(2, _lookAheadSamples + 2)
|
||||
@@ -136,9 +142,14 @@ public final class LookAheadLimiter: GeneratorBase, AudioGenerator {
|
||||
let maxAmp: Double = max(0.0, Double(_maxAmpInput.floatValue(graph: graph)))
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
|
||||
// Release coefficient recomputed per block from the (possibly live) releaseTime.
|
||||
// Decoupled from lookAheadTime — a slow release avoids modulating the waveform.
|
||||
let sr: Double = graph.engine.sampleRate
|
||||
let releaseT: Double = max(0.0, Double(_releaseTimeInput.floatValue(graph: graph)))
|
||||
let releaseCoeff: Double = releaseT > 0 ? exp(-1.0 / (sr * releaseT)) : 0.0
|
||||
let attackComp: Double = 1.0 - releaseCoeff
|
||||
|
||||
let ringSize: Int = _ringSize
|
||||
let releaseCoeff: Double = _releaseCoeff
|
||||
let attackComp: Double = _attackComp
|
||||
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
// Pathological branch: upstream returned a 0-row matrix. Advance ring +
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// ToneStack.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Passive guitar-amplifier tone stack (bass / mid / treble) — the interactive Fender /
|
||||
/// Marshall / Vox EQ network, not three independent bands.
|
||||
///
|
||||
/// The continuous-time transfer function of the selected ``ToneStackModel``'s RC network is
|
||||
/// evaluated symbolically from the component values and the three control positions, then
|
||||
/// discretized with the bilinear transform into a 3rd-order IIR run in Direct Form I. Because
|
||||
/// the network is modeled as a whole, the controls interact exactly as they do on the real amp
|
||||
/// (e.g. the Fender mid-scoop, and treble/bass loading each other).
|
||||
///
|
||||
/// Coefficient set follows the Yeh & Smith derivation ("Discretization of the '59 Fender
|
||||
/// Bassman Tone Stack", DAFx-06); the same closed-form used by the Faust `tonestacks` library.
|
||||
///
|
||||
/// The bass control uses an exponential taper (matching the audio-taper pot of the hardware);
|
||||
/// mid and treble are linear. All three are clamped to `[0, 1]`.
|
||||
///
|
||||
/// Coefficients are recomputed (off the inner loop) only when a control value changes, so a
|
||||
/// static setting costs one recompute; an automated control recomputes at block rate.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - bass: Bass control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - mid: Mid control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - treble: Treble control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - model: Tone-stack topology (component values). Fixed at init. Defaults to `.fender`.
|
||||
///
|
||||
/// The sample rate is read from the graph at render time, so it is not an init parameter.
|
||||
///
|
||||
/// Output is mono: only channel 0 of the input is filtered.
|
||||
public final class ToneStack: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _bassInput: any ValidGeneratorInput
|
||||
private let _midInput: any ValidGeneratorInput
|
||||
private let _trebleInput: any ValidGeneratorInput
|
||||
private let _bassIsGenerator: Bool
|
||||
private let _midIsGenerator: Bool
|
||||
private let _trebleIsGenerator: Bool
|
||||
|
||||
// MARK: - Component values (from the model, fixed at init)
|
||||
|
||||
private let r1: Double
|
||||
private let r2: Double
|
||||
private let r3: Double
|
||||
private let r4: Double
|
||||
private let c1: Double
|
||||
private let c2: Double
|
||||
private let c3: Double
|
||||
|
||||
// MARK: - Discretized coefficients (Direct Form I, normalized so A0 == 1)
|
||||
|
||||
private var _b0: Double = 1.0
|
||||
private var _b1: Double = 0.0
|
||||
private var _b2: Double = 0.0
|
||||
private var _b3: Double = 0.0
|
||||
private var _a1: Double = 0.0
|
||||
private var _a2: Double = 0.0
|
||||
private var _a3: Double = 0.0
|
||||
|
||||
// MARK: - Filter state
|
||||
|
||||
private var _x1: Double = 0.0
|
||||
private var _x2: Double = 0.0
|
||||
private var _x3: Double = 0.0
|
||||
private var _y1: Double = 0.0
|
||||
private var _y2: Double = 0.0
|
||||
private var _y3: Double = 0.0
|
||||
|
||||
// MARK: - Coefficient cache
|
||||
|
||||
private var _coeffsValid: Bool = false
|
||||
private var _lastL: Double = -1.0
|
||||
private var _lastM: Double = -1.0
|
||||
private var _lastT: Double = -1.0
|
||||
private var _lastSampleRate: Double = 0.0
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Exponential-taper exponent applied to the bass control (audio-taper pot emulation):
|
||||
/// `l = exp((bass − 1) · bassTaperExponent)`.
|
||||
private let bassTaperExponent: Double = 3.4
|
||||
/// Binomial coefficient from expanding `(1 ± z⁻¹)³` in the bilinear substitution.
|
||||
private let bilinearBinomialThree: Double = 3.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - bass: Bass control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - mid: Mid control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - treble: Treble control in `[0, 1]`. Defaults to `0.5`.
|
||||
/// - model: Tone-stack topology. Fixed at init. Defaults to `.fender`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
bass: any ValidGeneratorInput = 0.5,
|
||||
mid: any ValidGeneratorInput = 0.5,
|
||||
treble: any ValidGeneratorInput = 0.5,
|
||||
model: ToneStackModel = .fender
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedBass: any ValidGeneratorInput = bass._resolvedInput()
|
||||
let resolvedMid: any ValidGeneratorInput = mid._resolvedInput()
|
||||
let resolvedTreble: any ValidGeneratorInput = treble._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_bassInput = resolvedBass
|
||||
_midInput = resolvedMid
|
||||
_trebleInput = resolvedTreble
|
||||
_bassIsGenerator = resolvedBass is any Generator
|
||||
_midIsGenerator = resolvedMid is any Generator
|
||||
_trebleIsGenerator = resolvedTreble is any Generator
|
||||
let resistors: (r1: Double, r2: Double, r3: Double, r4: Double) = model.resistors
|
||||
let capacitors: (c1: Double, c2: Double, c3: Double) = model.capacitors
|
||||
r1 = resistors.r1
|
||||
r2 = resistors.r2
|
||||
r3 = resistors.r3
|
||||
r4 = resistors.r4
|
||||
c1 = capacitors.c1
|
||||
c2 = capacitors.c2
|
||||
c3 = capacitors.c3
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
|
||||
let bassRaw: Double = lastGeneratorSampleOrFloat(
|
||||
_bassInput, isGenerator: _bassIsGenerator, graph: graph, count: count)
|
||||
let midRaw: Double = lastGeneratorSampleOrFloat(
|
||||
_midInput, isGenerator: _midIsGenerator, graph: graph, count: count)
|
||||
let trebleRaw: Double = lastGeneratorSampleOrFloat(
|
||||
_trebleInput, isGenerator: _trebleIsGenerator, graph: graph, count: count)
|
||||
|
||||
let l: Double = exp((clamp01(bassRaw) - 1.0) * bassTaperExponent)
|
||||
let m: Double = clamp01(midRaw)
|
||||
let t: Double = clamp01(trebleRaw)
|
||||
|
||||
if !_coeffsValid || l != _lastL || m != _lastM || t != _lastT || sampleRate != _lastSampleRate {
|
||||
recomputeCoefficients(l: l, m: m, t: t, sampleRate: sampleRate)
|
||||
_lastL = l
|
||||
_lastM = m
|
||||
_lastT = t
|
||||
_lastSampleRate = sampleRate
|
||||
_coeffsValid = true
|
||||
}
|
||||
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
let b0: Double = _b0
|
||||
let b1: Double = _b1
|
||||
let b2: Double = _b2
|
||||
let b3: Double = _b3
|
||||
let a1: Double = _a1
|
||||
let a2: Double = _a2
|
||||
let a3: Double = _a3
|
||||
var x1: Double = _x1
|
||||
var x2: Double = _x2
|
||||
var x3: Double = _x3
|
||||
var y1: Double = _y1
|
||||
var y2: Double = _y2
|
||||
var y3: Double = _y3
|
||||
let inCount: Int = ins.count
|
||||
|
||||
ins.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||||
guard let srcP: UnsafePointer<Double> = src.baseAddress else { return }
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? srcP[i] : 0
|
||||
// Flush the feedback output every sample (as CombFilter / MoogLadder do —
|
||||
// stricter than the once-per-block flush used by the scalar-coefficient
|
||||
// biquads, since this 3rd-order recursion has more room to decay into
|
||||
// subnormal range). NRT and AUv3 render paths never arm hardware
|
||||
// flush-to-zero, so without this a fade-out would compute subnormal all block.
|
||||
let y: Double = denormalsToZero(
|
||||
b0 * x + b1 * x1 + b2 * x2 + b3 * x3 - a1 * y1 - a2 * y2 - a3 * y3)
|
||||
x3 = x2
|
||||
x2 = x1
|
||||
x1 = x
|
||||
y3 = y2
|
||||
y2 = y1
|
||||
y1 = y
|
||||
dstP[i] = y
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_x1 = x1
|
||||
_x2 = x2
|
||||
_x3 = x3
|
||||
_y1 = y1
|
||||
_y2 = y2
|
||||
_y3 = y3
|
||||
return _result
|
||||
}
|
||||
|
||||
// MARK: - Coefficients
|
||||
|
||||
/// Evaluates the analog tone-stack transfer function for the given control positions and
|
||||
/// discretizes it with the bilinear transform into normalized Direct-Form-I coefficients.
|
||||
private func recomputeCoefficients(
|
||||
l: Double,
|
||||
m: Double,
|
||||
t: Double,
|
||||
sampleRate: Double
|
||||
) {
|
||||
// Continuous-time numerator (b0 == 0) and denominator (a0 == 1) coefficients — the
|
||||
// Yeh/Smith closed form for the shared tone-stack network.
|
||||
let b1c: Double = t * c1 * r1 + m * c3 * r3 + l * (c1 * r2 + c2 * r2) + (c1 * r3 + c2 * r3)
|
||||
let b2c: Double = t * (c1 * c2 * r1 * r4 + c1 * c3 * r1 * r4)
|
||||
- m * m * (c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ m * (c1 * c3 * r1 * r3 + c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * (c1 * c2 * r1 * r2 + c1 * c2 * r2 * r4 + c1 * c3 * r2 * r4)
|
||||
+ l * m * (c1 * c3 * r2 * r3 + c2 * c3 * r2 * r3)
|
||||
+ (c1 * c2 * r1 * r3 + c1 * c2 * r3 * r4 + c1 * c3 * r3 * r4)
|
||||
let b3c: Double = l * m * (c1 * c2 * c3 * r1 * r2 * r3 + c1 * c2 * c3 * r2 * r3 * r4)
|
||||
- m * m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ t * c1 * c2 * c3 * r1 * r3 * r4 - t * m * c1 * c2 * c3 * r1 * r3 * r4
|
||||
+ t * l * c1 * c2 * c3 * r1 * r2 * r4
|
||||
|
||||
let a0c: Double = 1.0
|
||||
let a1c: Double = (c1 * r1 + c1 * r3 + c2 * r3 + c2 * r4 + c3 * r4)
|
||||
+ m * c3 * r3 + l * (c1 * r2 + c2 * r2)
|
||||
let a2c: Double = m * (c1 * c3 * r1 * r3 - c2 * c3 * r3 * r4 + c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * m * (c1 * c3 * r2 * r3 + c2 * c3 * r2 * r3)
|
||||
- m * m * (c1 * c3 * r3 * r3 + c2 * c3 * r3 * r3)
|
||||
+ l * (c1 * c2 * r2 * r4 + c1 * c2 * r1 * r2 + c1 * c3 * r2 * r4 + c2 * c3 * r2 * r4)
|
||||
+ (c1 * c2 * r1 * r4 + c1 * c3 * r1 * r4 + c1 * c2 * r3 * r4 + c1 * c2 * r1 * r3 + c1 * c3 * r3 * r4 + c2 * c3 * r3 * r4)
|
||||
let a3c: Double = l * m * (c1 * c2 * c3 * r1 * r2 * r3 + c1 * c2 * c3 * r2 * r3 * r4)
|
||||
- m * m * (c1 * c2 * c3 * r1 * r3 * r3 + c1 * c2 * c3 * r3 * r3 * r4)
|
||||
+ m * (c1 * c2 * c3 * r3 * r3 * r4 + c1 * c2 * c3 * r1 * r3 * r3 - c1 * c2 * c3 * r1 * r3 * r4)
|
||||
+ l * c1 * c2 * c3 * r1 * r2 * r4
|
||||
+ c1 * c2 * c3 * r1 * r3 * r4
|
||||
|
||||
// Bilinear transform s = c·(1 − z⁻¹)/(1 + z⁻¹), c = 2·Fs. Multiplying numerator and
|
||||
// denominator by (1 + z⁻¹)³ and collecting powers of z⁻¹ uses the fixed binomial
|
||||
// expansions of (1 ± z⁻¹)ⁿ: 1·[1,3,3,1], s·[1,1,−1,−1], s²·[1,−1,−1,1], s³·[1,−3,3,−1].
|
||||
let cc: Double = 2.0 * sampleRate
|
||||
let cc2: Double = cc * cc
|
||||
let cc3: Double = cc2 * cc
|
||||
let three: Double = bilinearBinomialThree
|
||||
|
||||
// Numerator (b0c == 0).
|
||||
let bd0: Double = b1c * cc + b2c * cc2 + b3c * cc3
|
||||
let bd1: Double = b1c * cc - b2c * cc2 - three * b3c * cc3
|
||||
let bd2: Double = -b1c * cc - b2c * cc2 + three * b3c * cc3
|
||||
let bd3: Double = -b1c * cc + b2c * cc2 - b3c * cc3
|
||||
// Denominator.
|
||||
let ad0: Double = a0c + a1c * cc + a2c * cc2 + a3c * cc3
|
||||
let ad1: Double = three * a0c + a1c * cc - a2c * cc2 - three * a3c * cc3
|
||||
let ad2: Double = three * a0c - a1c * cc - a2c * cc2 + three * a3c * cc3
|
||||
let ad3: Double = a0c - a1c * cc + a2c * cc2 - a3c * cc3
|
||||
|
||||
let invA0: Double = ad0 != 0.0 ? 1.0 / ad0 : 0.0
|
||||
_b0 = bd0 * invA0
|
||||
_b1 = bd1 * invA0
|
||||
_b2 = bd2 * invA0
|
||||
_b3 = bd3 * invA0
|
||||
_a1 = ad1 * invA0
|
||||
_a2 = ad2 * invA0
|
||||
_a3 = ad3 * invA0
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func clamp01(_ value: Double) -> Double {
|
||||
Swift.min(1.0, Swift.max(0.0, value))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
// LSTMAmp.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// Real-time neural guitar-amp inference: a single-layer LSTM followed by a dense output,
|
||||
/// run one audio sample at a time. This is the GuitarML "Proteus" / NeuralPi topology —
|
||||
/// `LSTM(inputSize: 1, hiddenSize: H)` → `Linear(H, 1)`, optionally with an input skip.
|
||||
///
|
||||
/// All weights come from a ``NeuralAmpModel`` and are copied into contiguous storage at `init`;
|
||||
/// the hidden/cell state and gate scratch are pre-allocated. `_computeSamples` performs only
|
||||
/// scalar arithmetic over that pre-allocated storage — no allocation, locks, or ARC-heavy work
|
||||
/// on the render thread — the same discipline the physical models use.
|
||||
///
|
||||
/// Cost is `O(4·H²)` multiply-adds per sample (the recurrent term dominates), so keep `H`
|
||||
/// modest (Proteus captures are typically `H = 20…40`).
|
||||
///
|
||||
/// Output is mono. The `Double` output is whatever the trained model produces; a well-trained
|
||||
/// capture stays roughly in `[-1, 1]`, but this generator does not clamp.
|
||||
///
|
||||
/// > Note: Load a GuitarML Proteus / NeuralPi JSON model with ``ProteusModelImporter``, or
|
||||
/// > construct a ``NeuralAmpModel`` directly. A binary NAM `.nam` importer is a planned follow-up.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to process (dry guitar DI).
|
||||
/// - model: The trained ``NeuralAmpModel`` weights. Copied at init.
|
||||
public final class LSTMAmp: GeneratorBase, AudioGenerator {
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
|
||||
// MARK: - Weights (copied at init)
|
||||
|
||||
private let _hiddenSize: Int
|
||||
private let _residual: Bool
|
||||
private let _weightIH: [Double] // 4H
|
||||
private let _weightHH: [Double] // 4H · H, element (q·H+u)·H + j
|
||||
private let _bias: [Double] // 4H — biasIH + biasHH summed at init
|
||||
private let _denseWeight: [Double] // H
|
||||
private let _denseBias: Double
|
||||
|
||||
// MARK: - Pre-allocated state / scratch
|
||||
|
||||
private var _h: [Double] // hidden state, H
|
||||
private var _c: [Double] // cell state, H
|
||||
private var _pre: [Double] // gate pre-activations, 4H
|
||||
|
||||
/// Creates a neural amp from trained weights.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to process (dry guitar DI).
|
||||
/// - model: The trained ``NeuralAmpModel``. Its arrays are copied into contiguous storage.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
model: NeuralAmpModel
|
||||
) {
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
_input = resolvedInput
|
||||
let hidden: Int = model.hiddenSize
|
||||
_hiddenSize = hidden
|
||||
_residual = model.residual
|
||||
_weightIH = model.weightIH
|
||||
_weightHH = model.weightHH
|
||||
_denseWeight = model.denseWeight
|
||||
_denseBias = model.denseBias
|
||||
// Fold PyTorch's two bias vectors into one.
|
||||
var combined: [Double] = [Double](repeating: 0.0, count: model.biasIH.count)
|
||||
for r: Int in 0..<combined.count { combined[r] = model.biasIH[r] + model.biasHH[r] }
|
||||
_bias = combined
|
||||
_h = [Double](repeating: 0.0, count: hidden)
|
||||
_c = [Double](repeating: 0.0, count: hidden)
|
||||
_pre = [Double](repeating: 0.0, count: NeuralAmpModel.gateCount * hidden)
|
||||
super.init()
|
||||
}
|
||||
|
||||
@inline(__always)
|
||||
private func sigmoid(_ z: Double) -> Double {
|
||||
1.0 / (1.0 + exp(-z))
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
let hidden: Int = _hiddenSize
|
||||
let gateForget: Int = hidden // gate offsets in `_pre` (order i, f, g, o)
|
||||
let gateCell: Int = 2 * hidden
|
||||
let gateOutput: Int = 3 * hidden
|
||||
let residual: Bool = _residual
|
||||
let denseBias: Double = _denseBias
|
||||
let inCount: Int = ins.count
|
||||
let rows: Int = NeuralAmpModel.gateCount * hidden
|
||||
|
||||
// Bind every array (weights + state + I/O) to a raw base pointer so the O(4·H²) inner
|
||||
// loop is bounds-check-free and ARC-free. The weight buffers are read-only (never
|
||||
// mutated → no COW); `_pre`/`_h`/`_c` mutate in place.
|
||||
_weightIH.withUnsafeBufferPointer { (wihB: UnsafeBufferPointer<Double>) in
|
||||
_weightHH.withUnsafeBufferPointer { (whhB: UnsafeBufferPointer<Double>) in
|
||||
_bias.withUnsafeBufferPointer { (biasB: UnsafeBufferPointer<Double>) in
|
||||
_denseWeight.withUnsafeBufferPointer { (woutB: UnsafeBufferPointer<Double>) in
|
||||
ins.withUnsafeBufferPointer { (src: UnsafeBufferPointer<Double>) in
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_pre.withUnsafeMutableBufferPointer { (preB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_h.withUnsafeMutableBufferPointer { (hB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
_c.withUnsafeMutableBufferPointer { (cB: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let weightIH: UnsafePointer<Double> = wihB.baseAddress,
|
||||
let weightHH: UnsafePointer<Double> = whhB.baseAddress,
|
||||
let bias: UnsafePointer<Double> = biasB.baseAddress,
|
||||
let denseWeight: UnsafePointer<Double> = woutB.baseAddress,
|
||||
let srcP: UnsafePointer<Double> = src.baseAddress,
|
||||
let dstP: UnsafeMutablePointer<Double> = dst.baseAddress,
|
||||
let pre: UnsafeMutablePointer<Double> = preB.baseAddress,
|
||||
let h: UnsafeMutablePointer<Double> = hB.baseAddress,
|
||||
let c: UnsafeMutablePointer<Double> = cB.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? srcP[i] : 0
|
||||
// Gate pre-activations from the *previous* hidden state.
|
||||
for r: Int in 0..<rows {
|
||||
var acc: Double = bias[r] + weightIH[r] * x
|
||||
let rowBase: Int = r * hidden
|
||||
for j: Int in 0..<hidden {
|
||||
acc += weightHH[rowBase + j] * h[j]
|
||||
}
|
||||
pre[r] = acc
|
||||
}
|
||||
// Cell + hidden update and dense readout.
|
||||
var outAcc: Double = denseBias
|
||||
for u: Int in 0..<hidden {
|
||||
let inputGate: Double = sigmoid(pre[u])
|
||||
let forgetGate: Double = sigmoid(pre[gateForget + u])
|
||||
let cellGate: Double = tanh(pre[gateCell + u])
|
||||
let outputGate: Double = sigmoid(pre[gateOutput + u])
|
||||
let cu: Double = denormalsToZero(forgetGate * c[u] + inputGate * cellGate)
|
||||
c[u] = cu
|
||||
let hu: Double = outputGate * tanh(cu)
|
||||
h[u] = hu
|
||||
outAcc += denseWeight[u] * hu
|
||||
}
|
||||
if residual { outAcc += x }
|
||||
dstP[i] = outAcc
|
||||
}
|
||||
} } } } } } } } }
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
// NeuralAmpModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Weights for a single-layer LSTM guitar-amp capture, consumed by ``LSTMAmp``.
|
||||
///
|
||||
/// This matches the GuitarML "Proteus" / NeuralPi topology: a single `LSTM(inputSize: 1,
|
||||
/// hiddenSize: H)` followed by a `Linear(H, 1)`, optionally with an input skip
|
||||
/// (`y = x + dense(h)`), run one audio sample at a time.
|
||||
///
|
||||
/// ## Weight layout
|
||||
///
|
||||
/// All arrays are flat `Double`s. Gates use the PyTorch order **input, forget, cell, output**
|
||||
/// (`i, f, g, o`), stacked so gate `q ∈ 0…3`, hidden unit `u ∈ 0…H-1` lives at row `q·H + u`:
|
||||
///
|
||||
/// - `weightIH` — input→gate weights, `4·H` entries (input size is 1), row `q·H + u`.
|
||||
/// - `weightHH` — recurrent gate weights, `4·H · H` entries, element `(q·H + u)·H + j`.
|
||||
/// - `biasIH`, `biasHH` — `4·H` each (PyTorch keeps two bias vectors; they are summed).
|
||||
/// - `denseWeight` — `H` entries, `denseBias` — scalar.
|
||||
///
|
||||
/// This is Lyrebird's native, `Codable` container. Load a GuitarML Proteus / NeuralPi JSON
|
||||
/// model onto this layout with ``ProteusModelImporter``; a binary NAM `.nam` importer is a
|
||||
/// planned follow-up.
|
||||
public struct NeuralAmpModel: Codable, Sendable {
|
||||
|
||||
/// Number of LSTM hidden units.
|
||||
public let hiddenSize: Int
|
||||
|
||||
/// When `true`, the dry input is added to the dense output (`y = x + dense(h)`).
|
||||
public let residual: Bool
|
||||
|
||||
/// Input→gate weights, `4·hiddenSize` entries (input size 1), gate-major (`q·H + u`).
|
||||
public let weightIH: [Double]
|
||||
|
||||
/// Recurrent gate weights, `4·hiddenSize·hiddenSize` entries, element `(q·H + u)·H + j`.
|
||||
public let weightHH: [Double]
|
||||
|
||||
/// Input-side gate biases, `4·hiddenSize` entries.
|
||||
public let biasIH: [Double]
|
||||
|
||||
/// Hidden-side gate biases, `4·hiddenSize` entries (summed with `biasIH`).
|
||||
public let biasHH: [Double]
|
||||
|
||||
/// Dense output weights, `hiddenSize` entries.
|
||||
public let denseWeight: [Double]
|
||||
|
||||
/// Dense output bias.
|
||||
public let denseBias: Double
|
||||
|
||||
/// Number of gates in an LSTM cell (input, forget, cell, output).
|
||||
public static let gateCount: Int = 4
|
||||
|
||||
/// Creates a model, validating all array shapes against `hiddenSize`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - hiddenSize: LSTM hidden-unit count. Must be `> 0`.
|
||||
/// - residual: Add the dry input to the dense output. Defaults to `true` (Proteus-style).
|
||||
/// - weightIH: `4·hiddenSize` input→gate weights.
|
||||
/// - weightHH: `4·hiddenSize·hiddenSize` recurrent weights.
|
||||
/// - biasIH: `4·hiddenSize` input-side biases.
|
||||
/// - biasHH: `4·hiddenSize` hidden-side biases.
|
||||
/// - denseWeight: `hiddenSize` dense weights.
|
||||
/// - denseBias: Dense bias.
|
||||
public init(
|
||||
hiddenSize: Int,
|
||||
residual: Bool = true,
|
||||
weightIH: [Double],
|
||||
weightHH: [Double],
|
||||
biasIH: [Double],
|
||||
biasHH: [Double],
|
||||
denseWeight: [Double],
|
||||
denseBias: Double
|
||||
) {
|
||||
precondition(hiddenSize > 0, "NeuralAmpModel: hiddenSize must be > 0")
|
||||
let gated: Int = NeuralAmpModel.gateCount * hiddenSize
|
||||
precondition(weightIH.count == gated, "NeuralAmpModel: weightIH must be 4·hiddenSize")
|
||||
precondition(weightHH.count == gated * hiddenSize, "NeuralAmpModel: weightHH must be 4·hiddenSize·hiddenSize")
|
||||
precondition(biasIH.count == gated, "NeuralAmpModel: biasIH must be 4·hiddenSize")
|
||||
precondition(biasHH.count == gated, "NeuralAmpModel: biasHH must be 4·hiddenSize")
|
||||
precondition(denseWeight.count == hiddenSize, "NeuralAmpModel: denseWeight must be hiddenSize")
|
||||
self.hiddenSize = hiddenSize
|
||||
self.residual = residual
|
||||
self.weightIH = weightIH
|
||||
self.weightHH = weightHH
|
||||
self.biasIH = biasIH
|
||||
self.biasHH = biasHH
|
||||
self.denseWeight = denseWeight
|
||||
self.denseBias = denseBias
|
||||
}
|
||||
|
||||
private enum CodingKeys: String, CodingKey {
|
||||
case hiddenSize, residual, weightIH, weightHH, biasIH, biasHH, denseWeight, denseBias
|
||||
}
|
||||
|
||||
/// Decodes and **validates** array shapes against `hiddenSize`, throwing on a mismatch.
|
||||
///
|
||||
/// External model files are the primary source for this type, so a malformed/hand-edited
|
||||
/// JSON must fail loudly at load — not decode silently and crash later in `LSTMAmp.init` or,
|
||||
/// worse, in the RT render loop on an out-of-bounds weight read. (The synthesized decoder
|
||||
/// would bypass the memberwise init's shape `precondition`s, hence this explicit override.)
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container: KeyedDecodingContainer<CodingKeys> = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let hiddenSize: Int = try container.decode(Int.self, forKey: .hiddenSize)
|
||||
let residual: Bool = try container.decode(Bool.self, forKey: .residual)
|
||||
let weightIH: [Double] = try container.decode([Double].self, forKey: .weightIH)
|
||||
let weightHH: [Double] = try container.decode([Double].self, forKey: .weightHH)
|
||||
let biasIH: [Double] = try container.decode([Double].self, forKey: .biasIH)
|
||||
let biasHH: [Double] = try container.decode([Double].self, forKey: .biasHH)
|
||||
let denseWeight: [Double] = try container.decode([Double].self, forKey: .denseWeight)
|
||||
let denseBias: Double = try container.decode(Double.self, forKey: .denseBias)
|
||||
|
||||
func fail(_ key: CodingKeys, _ message: String) -> DecodingError {
|
||||
DecodingError.dataCorruptedError(forKey: key, in: container, debugDescription: message)
|
||||
}
|
||||
guard hiddenSize > 0 else { throw fail(.hiddenSize, "hiddenSize must be > 0") }
|
||||
let gated: Int = NeuralAmpModel.gateCount * hiddenSize
|
||||
guard weightIH.count == gated else { throw fail(.weightIH, "weightIH must be 4·hiddenSize (\(gated)); got \(weightIH.count)") }
|
||||
guard weightHH.count == gated * hiddenSize else { throw fail(.weightHH, "weightHH must be 4·hiddenSize·hiddenSize (\(gated * hiddenSize)); got \(weightHH.count)") }
|
||||
guard biasIH.count == gated else { throw fail(.biasIH, "biasIH must be 4·hiddenSize (\(gated)); got \(biasIH.count)") }
|
||||
guard biasHH.count == gated else { throw fail(.biasHH, "biasHH must be 4·hiddenSize (\(gated)); got \(biasHH.count)") }
|
||||
guard denseWeight.count == hiddenSize else { throw fail(.denseWeight, "denseWeight must be hiddenSize (\(hiddenSize)); got \(denseWeight.count)") }
|
||||
|
||||
self.hiddenSize = hiddenSize
|
||||
self.residual = residual
|
||||
self.weightIH = weightIH
|
||||
self.weightHH = weightHH
|
||||
self.biasIH = biasIH
|
||||
self.biasHH = biasHH
|
||||
self.denseWeight = denseWeight
|
||||
self.denseBias = denseBias
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,173 @@
|
||||
// ProteusModelImporter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Imports a GuitarML **Proteus / NeuralPi** model JSON into a ``NeuralAmpModel``.
|
||||
///
|
||||
/// Those tools export a single-layer PyTorch LSTM as JSON with two objects:
|
||||
///
|
||||
/// ```json
|
||||
/// { "model_data": { "unit_type": "LSTM", "input_size": 1, "hidden_size": 20,
|
||||
/// "num_layers": 1, "skip": 1, "output_size": 1 },
|
||||
/// "state_dict": { "rec.weight_ih_l0": [[…]], // 4H × input_size
|
||||
/// "rec.weight_hh_l0": [[…]], // 4H × H
|
||||
/// "rec.bias_ih_l0": [ … ], // 4H
|
||||
/// "rec.bias_hh_l0": [ … ], // 4H
|
||||
/// "lin.weight": [[…]], // output_size × H
|
||||
/// "lin.bias": [ … ] } } // output_size
|
||||
/// ```
|
||||
///
|
||||
/// PyTorch stacks the LSTM gates in the order **input, forget, cell, output** (i, f, g, o) —
|
||||
/// the same order ``NeuralAmpModel`` documents — so the tensors flatten straight onto its
|
||||
/// layout. `skip == 1` maps to ``NeuralAmpModel/residual``.
|
||||
///
|
||||
/// Only the single-layer, `input_size == 1`, `output_size == 1`, `unit_type == "LSTM"` shape
|
||||
/// (the Proteus/NeuralPi capture topology `LSTMAmp` runs) is supported; anything else throws.
|
||||
///
|
||||
/// > The model files themselves are **not** redistributed with Lyrebird — this only parses a
|
||||
/// > file the user supplies. GuitarML models are GPL-licensed; keep them out of MIT bundles.
|
||||
public enum ProteusModelImporter {
|
||||
|
||||
/// Errors thrown while importing a Proteus/NeuralPi model.
|
||||
public enum ImportError: Error, Equatable {
|
||||
/// `model_data.unit_type` was not `"LSTM"` (the only recurrent unit `LSTMAmp` runs).
|
||||
case unsupportedUnitType(String)
|
||||
/// A tensor shape (or `input_size`/`output_size`/`num_layers`) was inconsistent with the
|
||||
/// single-layer, mono LSTM topology or with `hidden_size`. The message names the field.
|
||||
case unsupportedShape(String)
|
||||
}
|
||||
|
||||
private static let supportedInputSize: Int = 1
|
||||
private static let supportedOutputSize: Int = 1
|
||||
private static let supportedLayerCount: Int = 1
|
||||
|
||||
/// Parses Proteus/NeuralPi model JSON into a validated ``NeuralAmpModel``.
|
||||
///
|
||||
/// - Parameter data: The raw JSON file contents.
|
||||
/// - Returns: The imported model.
|
||||
/// - Throws: `DecodingError` if the JSON is malformed, or ``ImportError`` if the topology is
|
||||
/// unsupported or a tensor shape is inconsistent with `hidden_size`.
|
||||
public static func model(fromProteusJSON data: Data) throws -> NeuralAmpModel {
|
||||
let file: ProteusFile = try JSONDecoder().decode(ProteusFile.self, from: data)
|
||||
let meta: ProteusFile.ModelData = file.modelData
|
||||
let dict: ProteusFile.StateDict = file.stateDict
|
||||
|
||||
guard meta.unitType.uppercased() == "LSTM" else {
|
||||
throw ImportError.unsupportedUnitType(meta.unitType)
|
||||
}
|
||||
let hidden: Int = meta.hiddenSize
|
||||
guard hidden > 0 else { throw ImportError.unsupportedShape("hidden_size must be > 0; got \(hidden)") }
|
||||
guard meta.numLayers == supportedLayerCount else {
|
||||
throw ImportError.unsupportedShape("only num_layers == 1 is supported; got \(meta.numLayers)")
|
||||
}
|
||||
guard meta.inputSize == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("only input_size == 1 is supported; got \(meta.inputSize)")
|
||||
}
|
||||
guard meta.outputSize == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("only output_size == 1 is supported; got \(meta.outputSize)")
|
||||
}
|
||||
|
||||
let gated: Int = NeuralAmpModel.gateCount * hidden
|
||||
|
||||
// rec.weight_ih_l0: 4H × input_size(1) → 4H (take the single column).
|
||||
guard dict.weightIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 rows must be 4·hidden (\(gated)); got \(dict.weightIH.count)")
|
||||
}
|
||||
var weightIH: [Double] = [Double](repeating: 0.0, count: gated)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightIH[r].count == supportedInputSize else {
|
||||
throw ImportError.unsupportedShape("rec.weight_ih_l0 row \(r) must have input_size (1) columns; got \(dict.weightIH[r].count)")
|
||||
}
|
||||
weightIH[r] = dict.weightIH[r][0]
|
||||
}
|
||||
|
||||
// rec.weight_hh_l0: 4H × H → flatten row-major to (r·H + j).
|
||||
guard dict.weightHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 rows must be 4·hidden (\(gated)); got \(dict.weightHH.count)")
|
||||
}
|
||||
var weightHH: [Double] = [Double](repeating: 0.0, count: gated * hidden)
|
||||
for r: Int in 0..<gated {
|
||||
guard dict.weightHH[r].count == hidden else {
|
||||
throw ImportError.unsupportedShape("rec.weight_hh_l0 row \(r) must have hidden (\(hidden)) columns; got \(dict.weightHH[r].count)")
|
||||
}
|
||||
let base: Int = r * hidden
|
||||
for j: Int in 0..<hidden { weightHH[base + j] = dict.weightHH[r][j] }
|
||||
}
|
||||
|
||||
guard dict.biasIH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_ih_l0 must be 4·hidden (\(gated)); got \(dict.biasIH.count)")
|
||||
}
|
||||
guard dict.biasHH.count == gated else {
|
||||
throw ImportError.unsupportedShape("rec.bias_hh_l0 must be 4·hidden (\(gated)); got \(dict.biasHH.count)")
|
||||
}
|
||||
|
||||
// lin.weight: output_size(1) × H → H.
|
||||
guard dict.linWeight.count == supportedOutputSize, dict.linWeight[0].count == hidden else {
|
||||
throw ImportError.unsupportedShape("lin.weight must be 1 × hidden (\(hidden))")
|
||||
}
|
||||
guard dict.linBias.count == supportedOutputSize else {
|
||||
throw ImportError.unsupportedShape("lin.bias must have output_size (1) entries; got \(dict.linBias.count)")
|
||||
}
|
||||
|
||||
return NeuralAmpModel(
|
||||
hiddenSize: hidden,
|
||||
residual: meta.skip != 0,
|
||||
weightIH: weightIH,
|
||||
weightHH: weightHH,
|
||||
biasIH: dict.biasIH,
|
||||
biasHH: dict.biasHH,
|
||||
denseWeight: dict.linWeight[0],
|
||||
denseBias: dict.linBias[0])
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodable mirror of the Proteus/NeuralPi model-file schema.
|
||||
private struct ProteusFile: Decodable {
|
||||
let modelData: ModelData
|
||||
let stateDict: StateDict
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case modelData = "model_data"
|
||||
case stateDict = "state_dict"
|
||||
}
|
||||
|
||||
struct ModelData: Decodable {
|
||||
let unitType: String
|
||||
let inputSize: Int
|
||||
let hiddenSize: Int
|
||||
let numLayers: Int
|
||||
let outputSize: Int
|
||||
let skip: Int
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case unitType = "unit_type"
|
||||
case inputSize = "input_size"
|
||||
case hiddenSize = "hidden_size"
|
||||
case numLayers = "num_layers"
|
||||
case outputSize = "output_size"
|
||||
case skip
|
||||
}
|
||||
}
|
||||
|
||||
struct StateDict: Decodable {
|
||||
let weightIH: [[Double]]
|
||||
let weightHH: [[Double]]
|
||||
let biasIH: [Double]
|
||||
let biasHH: [Double]
|
||||
let linWeight: [[Double]]
|
||||
let linBias: [Double]
|
||||
|
||||
enum CodingKeys: String, CodingKey {
|
||||
case weightIH = "rec.weight_ih_l0"
|
||||
case weightHH = "rec.weight_hh_l0"
|
||||
case biasIH = "rec.bias_ih_l0"
|
||||
case biasHH = "rec.bias_hh_l0"
|
||||
case linWeight = "lin.weight"
|
||||
case linBias = "lin.bias"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,17 @@
|
||||
|
||||
/// Maps an Int32 counter to [-1, 1].
|
||||
private let grayNoiseScalingFactor: Double = 1.0 / Double(Int32.max)
|
||||
|
||||
/// Scales a Gray-code counter to `[-1, 1]`, clamping the one out-of-range edge.
|
||||
///
|
||||
/// `Int32.max` scales to exactly `1.0`, but `Int32.min` (magnitude one greater) scales to
|
||||
/// ≈ `-1.0000000005`, just below the contract — so the result is clamped. Only that single
|
||||
/// counter value is affected; every other passes through unchanged, preserving the
|
||||
/// bitwise-quantized property (the clamped `-1.0 × Int32.max = -Int32.max` is still integral).
|
||||
/// Factored out so the boundary is unit-testable directly.
|
||||
func grayNoiseClampedScale(_ counter: Int32) -> Double {
|
||||
Swift.max(-1.0, Swift.min(1.0, Double(counter) * grayNoiseScalingFactor))
|
||||
}
|
||||
/// Bit mask to pick a random bit position in 0…31 from the raw PRNG word.
|
||||
private let grayNoiseBitMask: UInt64 = 31
|
||||
|
||||
@@ -44,7 +55,7 @@ public enum GrayNoise {
|
||||
let raw: UInt64 = xorshift64NextRaw(&rngState)
|
||||
let bitPos: Int = Int(raw & grayNoiseBitMask)
|
||||
counter ^= Int32(bitPattern: UInt32(1) << bitPos)
|
||||
return Double(counter) * grayNoiseScalingFactor
|
||||
return grayNoiseClampedScale(counter)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,8 +73,8 @@ public final class DemandTemporalTendency: TimedDemandGenerator {
|
||||
/// - distribution: Distribution family to sample from.
|
||||
/// - parX: First parameter (lo, density, mode, dev, dispersion — see `DistributionKind`).
|
||||
/// - parY: Second parameter (hi for two-parameter distributions; default `.value(1.0)`).
|
||||
/// - parA: Third parameter (alpha/lowProb for betaRand; posOnly flag for cauchy). `nil` = use distribution default.
|
||||
/// - parB: Fourth parameter (beta/highProb for betaRand). `nil` = use distribution default.
|
||||
/// - parA: Third parameter (alpha for betaRand; posOnly flag for cauchy). `nil` = use distribution default.
|
||||
/// - parB: Fourth parameter (beta for betaRand). `nil` = use distribution default.
|
||||
/// - repeats: Number of pulls before exhaustion. `-1` = infinite.
|
||||
/// - seed: PRNG seed. Defaults to a time-derived value.
|
||||
public init(
|
||||
@@ -126,42 +126,6 @@ public final class DemandTemporalTendency: TimedDemandGenerator {
|
||||
a: Double?,
|
||||
b: Double?
|
||||
) -> Double {
|
||||
switch _distribution {
|
||||
case .uniform:
|
||||
return _sampleUniform(lo: x, hi: y, rng: &_rng)
|
||||
case .lpRand:
|
||||
return _sampleLpRand(lo: x, hi: y, rng: &_rng)
|
||||
case .hpRand:
|
||||
return _sampleHpRand(lo: x, hi: y, rng: &_rng)
|
||||
case .meanRand:
|
||||
return _sampleMeanRand(lo: x, hi: y, rng: &_rng)
|
||||
case .expRand:
|
||||
return _sampleExpRand(lo: x, hi: y, rng: &_rng)
|
||||
case .exponential:
|
||||
return _sampleExponential(density: x, rng: &_rng)
|
||||
case .gamma:
|
||||
return _sampleGamma(shape: x, rng: &_rng)
|
||||
case .laplace:
|
||||
return _sampleLaplace(dispersion: x, rng: &_rng)
|
||||
case .alaplace:
|
||||
return _sampleALaplace(dispersion: x, rng: &_rng)
|
||||
case .hcos:
|
||||
return _sampleHcos(dispersion: x, rng: &_rng)
|
||||
case .logistic:
|
||||
return _sampleLogistic(dispersion: x, rng: &_rng)
|
||||
case .poisson:
|
||||
return _samplePoisson(mean: x, rng: &_rng)
|
||||
case .arcsin:
|
||||
return _sampleArcsin(dispersion: x, rng: &_rng)
|
||||
case .betaRand:
|
||||
let alpha: Double = a ?? 2.0
|
||||
let beta: Double = b ?? 2.0
|
||||
return _sampleBetaRand(lo: x, hi: y, alpha: alpha, beta: beta, rng: &_rng)
|
||||
case .cauchy:
|
||||
let posOnly: Bool = (a ?? 0) > 0
|
||||
return _sampleCauchy(mean: x, spread: y, posOnly: posOnly, rng: &_rng)
|
||||
case .gauss:
|
||||
return _sampleGauss(dev: x, mean: y, rng: &_rng)
|
||||
}
|
||||
_distribution.sample(parX: x, parY: y, parA: a, parB: b, using: &_rng)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,194 @@
|
||||
// TriodeStage.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Darwin
|
||||
|
||||
/// A tube-style preamp gain stage: an asymmetric saturating nonlinearity driven by `drive`
|
||||
/// and offset by a grid `bias`, evaluated at 2×/4× oversampling, followed by an output
|
||||
/// coupling (DC-blocking) high-pass.
|
||||
///
|
||||
/// A single triode stage is characterized less by hard clipping than by *asymmetry*: the
|
||||
/// operating-point bias makes the transfer curve steeper on one side than the other, which
|
||||
/// generates even-order harmonics (the "warmth" of a single-ended tube stage) and a
|
||||
/// program-dependent DC shift that the following coupling capacitor removes. This stage models
|
||||
/// that behavior with a biased `tanh` soft-clip — `tanh(drive·x + bias) − tanh(bias)` — so the
|
||||
/// static operating point is subtracted while the dynamic asymmetry (and its even harmonics)
|
||||
/// remains, then a one-pole DC blocker emulates the coupling cap.
|
||||
///
|
||||
/// The nonlinearity is evaluated at an oversampled rate so the harmonics it generates settle
|
||||
/// below the upsampled Nyquist instead of aliasing back into the audible band.
|
||||
///
|
||||
/// This is a musically-voiced static waveshaper, not a SPICE-accurate circuit solve; a true
|
||||
/// bidirectional wave-digital triode model is a separate, heavier path.
|
||||
///
|
||||
/// Output is mono (channel 0 of the input is used).
|
||||
///
|
||||
/// > Note: `drive` and `bias` are read once per block (control rate); audio-rate modulation of
|
||||
/// > them is quantized to block boundaries.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to drive through the stage.
|
||||
/// - drive: Input gain into the tube. Higher pushes harder into saturation. Defaults to `1.0`.
|
||||
/// - bias: Grid-bias offset controlling asymmetry / even-harmonic content. `0` is symmetric.
|
||||
/// Practical range roughly `[-1, 1]`. Defaults to `0.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `4`.
|
||||
public final class TriodeStage: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _driveInput: any ValidGeneratorInput
|
||||
private let _biasInput: any ValidGeneratorInput
|
||||
private let _driveIsGenerator: Bool
|
||||
private let _biasIsGenerator: Bool
|
||||
|
||||
private let _oversampleFactor: Int
|
||||
|
||||
// MARK: - Oversampling state
|
||||
|
||||
private var _upsampler2x: HalfbandUpsampler2x
|
||||
private var _downsampler2x: HalfbandDownsampler2x
|
||||
private var _upsampler4x: HalfbandUpsampler4x
|
||||
private var _downsampler4x: HalfbandDownsampler4x
|
||||
|
||||
// MARK: - DC-block (coupling) state
|
||||
|
||||
private var _dcX1: Double = 0.0
|
||||
private var _dcY1: Double = 0.0
|
||||
/// Cached coupling pole and the sample rate it was computed for, so the `exp` is evaluated only
|
||||
/// when the rate changes (never mid-render), not per block.
|
||||
private var _cachedCouplingPole: Double = 0.0
|
||||
private var _cachedCouplingSampleRate: Double = 0.0
|
||||
/// Coupling-cap corner in Hz, evaluated once at `init` (off the RT thread) into a plain stored
|
||||
/// field so `_computeSamples` never touches a lazily-initialised `static`/global (which would
|
||||
/// pay a `swift_once` lock on first access, on the RT thread).
|
||||
private let _couplingCornerHz: Double = TriodeStage.couplingCornerHz()
|
||||
|
||||
// MARK: - Constants
|
||||
|
||||
/// Reference sample rate at which the coupling corner is pinned to the legacy fixed pole.
|
||||
private static let couplingReferenceSampleRate: Double = 44_100.0
|
||||
|
||||
/// Coupling-cap DC-blocker corner in Hz, chosen so the one-pole coefficient equals
|
||||
/// `leakDCDefaultAudioCoef` at ``couplingReferenceSampleRate`` — i.e. identical to the old fixed
|
||||
/// pole at 44.1 kHz (≈ 35 Hz). Unlike the old fixed coefficient, whose corner drifted *up* with
|
||||
/// the sample rate (thinning the low end at 88.2 / 96 kHz+), this corner is held constant in Hz
|
||||
/// across sample rates by recomputing the pole from the live rate (see `_computeSamples`). A pure
|
||||
/// function so no lazy `static` storage is read on the RT thread.
|
||||
static func couplingCornerHz() -> Double {
|
||||
-log(leakDCDefaultAudioCoef) * couplingReferenceSampleRate / (2.0 * Double.pi)
|
||||
}
|
||||
|
||||
/// The DC-blocker pole for a given sample rate, holding the corner at ``couplingCornerHz()``.
|
||||
/// `exp(-2π·fc/Fs)` — equals `leakDCDefaultAudioCoef` at the reference rate. For tests /
|
||||
/// introspection; the render path uses the cached `_couplingCornerHz` instead.
|
||||
static func couplingPole(sampleRate: Double) -> Double {
|
||||
exp(-2.0 * Double.pi * couplingCornerHz() / sampleRate)
|
||||
}
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to drive through the stage.
|
||||
/// - drive: Input gain into the tube. Defaults to `1.0`.
|
||||
/// - bias: Grid-bias offset controlling asymmetry. `0` = symmetric. Defaults to `0.0`.
|
||||
/// - oversample: Oversampling factor — `2` or `4`. Defaults to `4`.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
drive: any ValidGeneratorInput = 1.0,
|
||||
bias: any ValidGeneratorInput = 0.0,
|
||||
oversample: Int = 4
|
||||
) {
|
||||
precondition(
|
||||
oversample == 2 || oversample == 4,
|
||||
"TriodeStage: oversample must be 2 or 4"
|
||||
)
|
||||
let resolvedInput: any ValidGeneratorInput = input._resolvedInput()
|
||||
let resolvedDrive: any ValidGeneratorInput = drive._resolvedInput()
|
||||
let resolvedBias: any ValidGeneratorInput = bias._resolvedInput()
|
||||
_input = resolvedInput
|
||||
_driveInput = resolvedDrive
|
||||
_biasInput = resolvedBias
|
||||
_driveIsGenerator = resolvedDrive is any Generator
|
||||
_biasIsGenerator = resolvedBias is any Generator
|
||||
_oversampleFactor = oversample
|
||||
_upsampler2x = HalfbandUpsampler2x()
|
||||
_downsampler2x = HalfbandDownsampler2x()
|
||||
_upsampler4x = HalfbandUpsampler4x()
|
||||
_downsampler4x = HalfbandDownsampler4x()
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
guard count > 0 else { return _result }
|
||||
|
||||
let drive: Double = lastGeneratorSampleOrFloat(
|
||||
_driveInput, isGenerator: _driveIsGenerator, graph: graph, count: count)
|
||||
let bias: Double = lastGeneratorSampleOrFloat(
|
||||
_biasInput, isGenerator: _biasIsGenerator, graph: graph, count: count)
|
||||
// Subtract the static operating point so only the dynamic (asymmetric) response passes.
|
||||
let biasOffset: Double = tanh(bias)
|
||||
// Recompute the coupling pole only when the sample rate changes, so the DC-blocker corner
|
||||
// stays fixed in Hz across rates (no low-end thinning at high sample rates).
|
||||
let sampleRate: Double = graph.engine.sampleRate
|
||||
if sampleRate != _cachedCouplingSampleRate {
|
||||
// Uses the instance `_couplingCornerHz` (evaluated at init) — no lazy static/global read.
|
||||
_cachedCouplingPole = exp(-2.0 * Double.pi * _couplingCornerHz / sampleRate)
|
||||
_cachedCouplingSampleRate = sampleRate
|
||||
}
|
||||
let pole: Double = _cachedCouplingPole
|
||||
let useFourX: Bool = _oversampleFactor == 4
|
||||
|
||||
let inputSamples: [[Double]] = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins: [Double] = inputSamples.first else {
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count { dstP[i] = 0 }
|
||||
}
|
||||
return _result
|
||||
}
|
||||
|
||||
var dcX1: Double = _dcX1
|
||||
var dcY1: Double = _dcY1
|
||||
let inCount: Int = ins.count
|
||||
|
||||
_result[0].withUnsafeMutableBufferPointer { (dst: inout UnsafeMutableBufferPointer<Double>) in
|
||||
guard let dstP: UnsafeMutablePointer<Double> = dst.baseAddress else { return }
|
||||
for i: Int in 0..<count {
|
||||
let x: Double = i < inCount ? ins[i] : 0
|
||||
let shaped: Double
|
||||
if useFourX {
|
||||
let (a, b, c, d) = _upsampler4x.process(x)
|
||||
shaped = _downsampler4x.process(
|
||||
tanh(drive * a + bias) - biasOffset,
|
||||
tanh(drive * b + bias) - biasOffset,
|
||||
tanh(drive * c + bias) - biasOffset,
|
||||
tanh(drive * d + bias) - biasOffset)
|
||||
} else {
|
||||
let (a, b) = _upsampler2x.process(x)
|
||||
shaped = _downsampler2x.process(
|
||||
tanh(drive * a + bias) - biasOffset,
|
||||
tanh(drive * b + bias) - biasOffset)
|
||||
}
|
||||
// One-pole DC blocker (coupling cap): y = x − x1 + pole·y1.
|
||||
let y: Double = denormalsToZero(shaped - dcX1 + pole * dcY1)
|
||||
dcX1 = shaped
|
||||
dcY1 = y
|
||||
dstP[i] = y
|
||||
}
|
||||
}
|
||||
|
||||
_dcX1 = dcX1
|
||||
_dcY1 = dcY1
|
||||
return _result
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
// ToneStackModel.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// A passive guitar-amplifier tone-stack topology, selecting the resistor/capacitor values
|
||||
/// used by ``ToneStack``.
|
||||
///
|
||||
/// All stacks share the same circuit; only the component values differ. The values here match the
|
||||
/// widely-used Yeh/Smith reference set (the same set used by the Faust `tonestacks` library).
|
||||
///
|
||||
/// - `fender`: Fender Bassman / Twin — scooped mids, bright.
|
||||
/// - `marshall`: Marshall JCM800 — more mid, tighter low end.
|
||||
/// - `vox`: Vox AC30 — a different taper, chimey top.
|
||||
/// - `mesa`: Mesa/Boogie Mark — Fender-derived but a deeper mid scoop and fatter low end.
|
||||
/// - `soldano`: Soldano SLO — Marshall-derived with a tighter slope for high-gain lead.
|
||||
public enum ToneStackModel: String, CaseIterable, Sendable {
|
||||
case fender
|
||||
case marshall
|
||||
case vox
|
||||
case mesa
|
||||
case soldano
|
||||
|
||||
/// Human-readable name for pickers.
|
||||
public var displayName: String {
|
||||
switch self {
|
||||
case .fender: return "Fender"
|
||||
case .marshall: return "Marshall"
|
||||
case .vox: return "Vox"
|
||||
case .mesa: return "Mesa"
|
||||
case .soldano: return "Soldano"
|
||||
}
|
||||
}
|
||||
|
||||
/// Resistor values in ohms: `(R1, R2, R3, R4)`.
|
||||
var resistors: (r1: Double, r2: Double, r3: Double, r4: Double) {
|
||||
switch self {
|
||||
case .fender: return (250_000.0, 1_000_000.0, 25_000.0, 56_000.0)
|
||||
case .marshall: return (220_000.0, 1_000_000.0, 22_000.0, 33_000.0)
|
||||
case .vox: return (1_000_000.0, 1_000_000.0, 10_000.0, 100_000.0)
|
||||
case .mesa: return (250_000.0, 250_000.0, 25_000.0, 100_000.0)
|
||||
case .soldano: return (250_000.0, 1_000_000.0, 25_000.0, 47_000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Capacitor values in farads: `(C1, C2, C3)`.
|
||||
var capacitors: (c1: Double, c2: Double, c3: Double) {
|
||||
switch self {
|
||||
case .fender: return (250.0e-12, 20.0e-9, 20.0e-9)
|
||||
case .marshall: return (470.0e-12, 22.0e-9, 22.0e-9)
|
||||
case .vox: return (50.0e-12, 22.0e-9, 22.0e-9)
|
||||
case .mesa: return (250.0e-12, 100.0e-9, 47.0e-9)
|
||||
case .soldano: return (470.0e-12, 20.0e-9, 20.0e-9)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -82,6 +82,52 @@ The same helpers work inside RT `_computeSamples` bodies (no allocation, no lock
|
||||
`rngState: UInt64` on the Generator and pass `&rngState` per call. Generators in the noise
|
||||
family inherit this state via ``NoiseBase``.
|
||||
|
||||
### Distribution-shaped scalars — ``LyrebirdRandom``
|
||||
|
||||
The stdlib and xorshift helpers above give you a *uniform* scalar. When you want a single draw
|
||||
from a *specific distribution* — Gaussian jitter, an exponential (log-uniform) frequency, a
|
||||
Laplace-shaped deviation, a Beta-weighted position — use ``LyrebirdRandom``. It owns a
|
||||
xorshift64 state, so a given `seed` produces a fully reproducible stream of draws, and it
|
||||
covers every family in ``DistributionKind``:
|
||||
|
||||
```swift
|
||||
var r = LyrebirdRandom(seed: 42)
|
||||
let freq: Double = r.exponentialRange(low: 200, high: 2000) // Hz, log-uniform
|
||||
let dur: Double = r.uniform(low: 0.1, high: 0.5) // seconds
|
||||
let jitter: Double = r.gauss(mean: 0, dev: 0.02) // ± around 0
|
||||
let skew: Double = r.beta(low: 0, high: 1, alpha: 2, beta: 5)
|
||||
let spike: Double = r.laplace(scale: 1.0)
|
||||
```
|
||||
|
||||
Named methods exist for the common families (``LyrebirdRandom/uniform(low:high:)``,
|
||||
``LyrebirdRandom/gauss(mean:dev:)``, ``LyrebirdRandom/laplace(scale:)``,
|
||||
``LyrebirdRandom/exponentialRange(low:high:)``, ``LyrebirdRandom/cauchy(mean:spread:positiveOnly:)``,
|
||||
``LyrebirdRandom/beta(low:high:alpha:beta:)`` …); reach any distribution by kind with
|
||||
``LyrebirdRandom/value(_:parX:parY:parA:parB:)``.
|
||||
|
||||
For throwaway draws where you don't want to thread a source through your code, use the
|
||||
process-wide, thread-safe ``LyrebirdRandom/shared`` (system-seeded, **not** reproducible).
|
||||
The global ``Random`` is a shorthand for exactly that shared instance — the common
|
||||
non-seeded case:
|
||||
|
||||
```swift
|
||||
let x: Double = Random.uniform(low: 0, high: 1) // == LyrebirdRandom.shared
|
||||
let g: Double = Random.gauss(mean: 0, dev: 1)
|
||||
let f: Double = Random.exponentialRange(low: 200, high: 2000)
|
||||
```
|
||||
|
||||
The single-draw dispatch (``DistributionKind/sample(parX:parY:parA:parB:using:)``) is the same
|
||||
mapping ``TemporalTendency`` and ``DemandTemporalTendency`` use — so a scalar draw and a stream
|
||||
of the same distribution agree given the same seed. `LyrebirdRandom` is not thread-safe (give
|
||||
each thread its own instance); `shared` is synchronized.
|
||||
|
||||
> Warning: ``SharedRandom`` / ``Random`` take a **lock** on every draw, so they are **not
|
||||
> RT-safe** — never call `Random.…` (or `LyrebirdRandom.shared.…`) from a Generator's
|
||||
> `_computeSamples` or any audio-thread path. Inside a Generator, store an owned
|
||||
> ``LyrebirdRandom`` (seeded at `init`) and draw from it: it holds no lock, is pure arithmetic,
|
||||
> and is RT-safe. `Random` is for non-RT setup / language-side code (Synthesizer `init`,
|
||||
> demos, live-coding snippets, tests).
|
||||
|
||||
### Want a *signal*, not a scalar?
|
||||
|
||||
For random *signals* — control-rate values that re-fire on a trigger, smoothed random walks,
|
||||
@@ -197,6 +243,10 @@ default or to temporarily freeze jitter without removing the generator.
|
||||
|
||||
## See Also
|
||||
|
||||
- ``LyrebirdRandom``
|
||||
- ``SharedRandom``
|
||||
- ``Random``
|
||||
- ``DistributionKind``
|
||||
- <doc:Noise>
|
||||
- <doc:TemporalDemand>
|
||||
- ``Impulse``
|
||||
@@ -36,7 +36,7 @@ Pick a scheme from the toolbar and hit **Run**:
|
||||
| `LyrebirdiOSDemo` | SwiftUI app — same UI via `iOSAudioDriver` (RemoteIO) | iOS |
|
||||
| `LyrebirdNRTDemo` | CLI — renders to `~/Desktop/nrt_output.caf` and exits | macOS |
|
||||
| `LyrebirdAUv3Demo` | AUv3 host app + `aumu` plugin extension (`Realized Sound: LyrebirdFM`) — a two-operator FM synth wrapped as ``LyrebirdAudioUnit``, loadable in Logic, GarageBand, AUM, Loopy Pro, etc. Run the host app once to register the extension, then load the plugin in any AUv3-capable host. | macOS |
|
||||
| `LyrebirdScratchDemo` | Live-coding scratchpad — compile a Swift snippet at ⌘↩, `dlopen` the dylib, run it against the live engine. ⌘⇧↩ is additive (prior synths stay). | macOS |
|
||||
| `LyrebirdScratch` | Live-coding scratchpad — compile a Swift snippet at ⌘↩, `dlopen` the dylib, run it against the live engine. ⌘⇧↩ is additive (prior synths stay). | macOS |
|
||||
|
||||
Use `Lyrebird-Package` for day-to-day development of the engine and tests. The other entries are convenience runs for the specific module or demo you're iterating on.
|
||||
|
||||
|
||||
@@ -39,7 +39,7 @@ try engine.add(MySynth()) // MySynth — your SynthesizerBase subclass
|
||||
|
||||
- <doc:Oscillators>
|
||||
- <doc:Noise>
|
||||
- <doc:Random>
|
||||
- <doc:RandomAndJitter>
|
||||
|
||||
### Buffer Utilities
|
||||
|
||||
|
||||
@@ -250,12 +250,44 @@ afconvert -f WAVE -d LEF32 output.caf output.wav
|
||||
### LyrebirdBuffer.write() — AIFF, WAV, or CAF
|
||||
|
||||
```swift
|
||||
try buf.write(to: url, format: .caf, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .aiff, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .wav, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .cafFloat32, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .aiffFloat32, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .wavFloat32, sampleRate: 44100)
|
||||
|
||||
// Integer WAV encodings, for smaller files / DAW interchange:
|
||||
try buf.write(to: url, format: .wavInt16, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .wavInt24, sampleRate: 44100)
|
||||
|
||||
// RF64 / BW64 — WAV extension, 64-bit sizes, no 4 GB cap:
|
||||
try buf.write(to: url, format: .rf64Float32, sampleRate: 44100)
|
||||
try buf.write(to: url, format: .rf64Int24, sampleRate: 44100)
|
||||
|
||||
// Compressed M4A (offline writers only — LyrebirdBuffer.write / NRTDriver):
|
||||
try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps (lossy)
|
||||
try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps (lossy)
|
||||
try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless
|
||||
```
|
||||
|
||||
All formats write 32-bit float (Float32). `Double` (Double) values are downcast on the way out.
|
||||
The buffer's `Double` samples are handed to `ExtAudioFile` as native Float32; the
|
||||
container's on-disk encoding drives the conversion. The `.cafFloat32` /
|
||||
`.aiffFloat32` / `.wavFloat32` cases are lossless 32-bit float; `.wavInt16` /
|
||||
`.wavInt24` quantise to signed 16/24-bit PCM. (`.caf` / `.aiff` / `.wav` remain
|
||||
as Float32 shorthands.)
|
||||
|
||||
**Files past 4 GB**: plain `.wav`/`.aiff` are limited to 4 GB (32-bit size fields) and
|
||||
throw `fileTooLargeForContainer` past that. For a big file that must keep the `.wav`
|
||||
extension, use `.rf64Float32` / `.rf64Int24` — RF64/BW64 (EBU Tech 3306) carries 64-bit
|
||||
sizes in a `ds64` chunk (written by Lyrebird's own ``RF64Writer``; CoreAudio reads it
|
||||
back). `.cafFloat32` is the other uncapped option.
|
||||
|
||||
**Compressed output** (`.aacHigh` / `.aacMedium` / `.alac`): AAC and Apple Lossless in an
|
||||
`.m4a` container, encoded by `ExtAudioFile`/`AudioConverter`. **Offline writers only** —
|
||||
`LyrebirdBuffer.write` and `NRTDriver`; ``DiskOut/Audio`` throws `compressedFormatNotSupported`
|
||||
(real-time streaming of a compressed encoder is out of scope). AAC is lossy and **not
|
||||
sample-accurate** (encoder priming/padding shifts the signal a few ms), so frame-count
|
||||
round-trips aren't exact; ALAC is lossless of a 24-bit-quantised source. Introspect a
|
||||
format with ``AudioFileFormat/isCompressed`` (true for these three) and, for AAC, its
|
||||
target rate via ``AudioFileFormat/aacBitrate``.
|
||||
|
||||
## Complete Example — NRT Bounce to AIFF
|
||||
|
||||
@@ -316,6 +348,9 @@ do {
|
||||
| `NRTDriverError.cannotOpenInputFile` | `inputURL` not found or unreadable | Verify the file path exists |
|
||||
| `NRTDriverError.cannotSeekInputFile` | `inputStartOffset` beyond file end | Reduce `inputStartOffset` |
|
||||
| `NRTDriverError.inputReadFailed` | Disk I/O error reading input file | Check disk health |
|
||||
| `NRTDriverError.invalidDuration` | `duration` is negative, NaN, or infinite | Pass a finite, non-negative duration |
|
||||
| `NRTDriverError.fileTooLargeForContainer` | WAV/AIFF render projected past the 4 GB RIFF cap | Use `format: .cafFloat32`, or shorten `duration` |
|
||||
| `LyrebirdBufferIOError.fileTooLargeForContainer` | `LyrebirdBuffer.write` to WAV/AIFF projected past 4 GB | Use `.cafFloat32`, or split/shorten the buffer |
|
||||
| Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` before `start()` |
|
||||
| File truncated short | `duration` too short | Increase `NRTDriver` duration |
|
||||
|
||||
|
||||
@@ -455,11 +455,13 @@ list.stopRecord()
|
||||
// Inspect state:
|
||||
list.isRecording // Bool
|
||||
list.recordDirectory // URL?
|
||||
list.recordFormat // DiskOutFormat
|
||||
list.recordFormat // AudioFileFormat
|
||||
```
|
||||
|
||||
**Late-start behavior**: calling `record(directory:format:)` after the first event has already fired is valid. Processes already running do not start recording retroactively — only new ``LyrebirdProcess/play(engine:)`` calls after this point produce stem files.
|
||||
|
||||
**4 GB cap on WAV/AIFF stems**: the default `format` is a WAV encoding, and WAV/AIFF-C containers are limited to 4 GB (32-bit size fields). A very long performance can hit that ceiling — the affected stem stops growing at the cap (frames past it are silently dropped; audio already written stays valid) rather than corrupting. For multi-hour sessions record to a 64-bit container: `.cafFloat32`, or `.rf64Float32` / `.rf64Int24` (RF64/BW64 — keeps the `.wav` extension, uncapped). Each stem's ``DiskOut/Audio`` exposes `fileTooLarge` if you need to detect the condition after teardown.
|
||||
|
||||
### Stem Filename Scheme
|
||||
|
||||
Each stem file is named:
|
||||
@@ -484,12 +486,16 @@ The offset field is zero-padded to a fixed width (7 integer digits, 4 decimal pl
|
||||
|
||||
### Format Options
|
||||
|
||||
| ``DiskOutFormat`` case | Container | Encoding | Use when |
|
||||
| ``AudioFileFormat`` case | Container | Encoding | Use when |
|
||||
|------------------------|-----------|----------|----------|
|
||||
| `.wavFloat32` | WAV | 32-bit float | Default. Lossless, DAW-compatible. |
|
||||
| `.wavInt16` | WAV | 16-bit PCM | Smallest file; -96 dB noise floor. |
|
||||
| `.wavInt24` | WAV | 24-bit PCM | Balanced. |
|
||||
| `.aiffFloat32` | AIFF | 32-bit float | Legacy Mac/ProTools compatibility. |
|
||||
| `.cafFloat32` | CAF | 32-bit float | Long sessions — 64-bit sizes, no 4 GB cap. |
|
||||
| `.rf64Float32` / `.rf64Int24` | WAV (RF64) | 32-bit float / 24-bit PCM | Long sessions needing the `.wav` extension. |
|
||||
|
||||
> Note: The compressed codecs (`.aacHigh` / `.aacMedium` / `.alac`) are **not** available for stem recording — ``DiskOut/Audio`` (which backs stems) rejects them. Compressed output is offline-only (`LyrebirdBuffer.write` / `NRTDriver`).
|
||||
|
||||
> Note: A master file that captures the mixed master bus (after the `EventListMasterSynth`) is planned for a future phase. Currently only per-process dry stems are recorded.
|
||||
|
||||
|
||||
@@ -481,5 +481,5 @@ Pass `timespan: 0` to snapshot all values at `elapsedSeconds = 0`. Pass a non-ze
|
||||
- ``TemporalParameter``
|
||||
- ``DistributionKind``
|
||||
- <doc:Noise>
|
||||
- <doc:Random>
|
||||
- <doc:RandomAndJitter>
|
||||
- <doc:RoutineTask>
|
||||
|
||||
@@ -72,6 +72,21 @@ public let lyrebirdBufferMonoChannelCount: Int = 1
|
||||
/// multichannel configurations.
|
||||
public let lyrebirdMaxFileChannelCount: Int = 8
|
||||
|
||||
/// Largest audio-data payload (bytes) a classic RIFF (WAV) or AIFF-C container can
|
||||
/// address. Both use unsigned **32-bit** size fields, so the whole file must fit in
|
||||
/// 4 GB (`0xFFFF_FFFF`). We subtract a header slack so header + data together stay
|
||||
/// within range regardless of the exact chunk layout.
|
||||
///
|
||||
/// `ExtAudioFile` writes only classic RIFF / AIFF — CoreAudio has no RF64 / BW64 /
|
||||
/// W64 writer — so a WAV/AIFF write past this cap is unreachable and is rejected by
|
||||
/// the `LyrebirdBuffer.write` / `NRTDriver` large-file guards (throwing
|
||||
/// `fileTooLargeForContainer`). Use `.cafFloat32` (64-bit sizes, uncapped) instead.
|
||||
///
|
||||
/// Rule of thumb: 4 ch × Float32 × 48 kHz ≈ 4 GB in ~43 minutes.
|
||||
private let riffSizeFieldMax: Int = 0xFFFF_FFFF
|
||||
private let riffHeaderSlackBytes: Int = 1024
|
||||
public let lyrebirdMaxRIFFBytes: Int = riffSizeFieldMax - riffHeaderSlackBytes
|
||||
|
||||
// MARK: - Granular synthesis
|
||||
|
||||
/// Pre-allocated grain pool size for `BufferGrain`.
|
||||
|
||||
@@ -246,7 +246,7 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// Non-nil while recording is enabled. Set by ``record(directory:format:)``
|
||||
/// and cleared by ``stopRecord()``.
|
||||
private var _recordingDirectory: URL?
|
||||
private var _recordingFormat: DiskOutFormat = .wavFloat32
|
||||
private var _recordingFormat: AudioFileFormat = .wavFloat32
|
||||
private var _isRecording: Bool = false
|
||||
|
||||
// MARK: - Timeline state (main-thread only)
|
||||
@@ -515,8 +515,8 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
|
||||
/// Container-and-encoding format used for stem files.
|
||||
///
|
||||
/// Defaults to ``DiskOutFormat/wavFloat32``. Set via ``record(directory:format:)``.
|
||||
public var recordFormat: DiskOutFormat { _recordingFormat }
|
||||
/// Defaults to ``AudioFileFormat/wavFloat32``. Set via ``record(directory:format:)``.
|
||||
public var recordFormat: AudioFileFormat { _recordingFormat }
|
||||
|
||||
// MARK: - Playback
|
||||
|
||||
@@ -818,11 +818,26 @@ public final class LyrebirdEventList: @unchecked Sendable {
|
||||
/// eagerly (including intermediate directories) before this call returns.
|
||||
/// A failure to create the directory is logged but does not throw — recording
|
||||
/// will simply fail silently when the first process attempts to write.
|
||||
/// - format: Container and PCM encoding. Defaults to ``DiskOutFormat/wavFloat32``.
|
||||
/// - format: Container and PCM encoding. Defaults to ``AudioFileFormat/wavFloat32``.
|
||||
/// Must be a PCM or RF64 format — compressed formats (`.aacHigh` / `.aacMedium`
|
||||
/// / `.alac`) are **rejected** (stems stream through ``DiskOut/Audio``, which is
|
||||
/// PCM/RF64 only); passing one logs a warning and leaves recording disabled.
|
||||
public func record(
|
||||
directory: URL,
|
||||
format: DiskOutFormat = .wavFloat32
|
||||
format: AudioFileFormat = .wavFloat32
|
||||
) {
|
||||
// Stems are written by DiskOut, which streams PCM/RF64 only — a compressed
|
||||
// format would make every per-process DiskOut.init throw and recording fail
|
||||
// silently. Reject it up front with a clear message and do not enable
|
||||
// recording (render offline for compressed output).
|
||||
guard !format.isCompressed else {
|
||||
print("[LyrebirdEventList '\(id)'] Compressed formats (AAC/ALAC) are not "
|
||||
+ "supported for stem recording — DiskOut streams PCM/RF64 only. "
|
||||
+ "Recording NOT enabled. Use a PCM/RF64 format for stems, or render "
|
||||
+ "offline (LyrebirdBuffer.write / NRTDriver) for AAC/ALAC.")
|
||||
return
|
||||
}
|
||||
|
||||
// Eagerly create the directory so the contract "directory exists when the
|
||||
// first process plays" is guaranteed regardless of whether any event fires.
|
||||
do {
|
||||
|
||||
@@ -20,7 +20,7 @@ struct ProcessRecordingConfig {
|
||||
let directory: URL
|
||||
|
||||
/// Output file encoding/container format.
|
||||
let format: DiskOutFormat
|
||||
let format: AudioFileFormat
|
||||
|
||||
/// The EventList's `id`, pre-sanitised for filesystem use.
|
||||
let sanitisedEventListID: String
|
||||
|
||||
@@ -118,45 +118,6 @@ public final class TemporalTendency: TemporalAlgorithmBase {
|
||||
b: Double?,
|
||||
rng: inout UInt64
|
||||
) -> Double {
|
||||
let betaDefaultAlpha: Double = 2.0
|
||||
let betaDefaultBeta: Double = 2.0
|
||||
switch _distribution {
|
||||
case .uniform:
|
||||
return _sampleUniform(lo: x, hi: y, rng: &rng)
|
||||
case .lpRand:
|
||||
return _sampleLpRand(lo: x, hi: y, rng: &rng)
|
||||
case .hpRand:
|
||||
return _sampleHpRand(lo: x, hi: y, rng: &rng)
|
||||
case .meanRand:
|
||||
return _sampleMeanRand(lo: x, hi: y, rng: &rng)
|
||||
case .expRand:
|
||||
return _sampleExpRand(lo: x, hi: y, rng: &rng)
|
||||
case .exponential:
|
||||
return _sampleExponential(density: x, rng: &rng)
|
||||
case .gamma:
|
||||
return _sampleGamma(shape: x, rng: &rng)
|
||||
case .laplace:
|
||||
return _sampleLaplace(dispersion: x, rng: &rng)
|
||||
case .alaplace:
|
||||
return _sampleALaplace(dispersion: x, rng: &rng)
|
||||
case .hcos:
|
||||
return _sampleHcos(dispersion: x, rng: &rng)
|
||||
case .logistic:
|
||||
return _sampleLogistic(dispersion: x, rng: &rng)
|
||||
case .poisson:
|
||||
return _samplePoisson(mean: x, rng: &rng)
|
||||
case .arcsin:
|
||||
return _sampleArcsin(dispersion: x, rng: &rng)
|
||||
case .betaRand:
|
||||
return _sampleBetaRand(
|
||||
lo: x, hi: y,
|
||||
alpha: a ?? betaDefaultAlpha,
|
||||
beta: b ?? betaDefaultBeta,
|
||||
rng: &rng)
|
||||
case .cauchy:
|
||||
return _sampleCauchy(mean: x, spread: y, posOnly: (a ?? 0) > 0, rng: &rng)
|
||||
case .gauss:
|
||||
return _sampleGauss(dev: x, mean: y, rng: &rng)
|
||||
}
|
||||
_distribution.sample(parX: x, parY: y, parA: a, parB: b, using: &rng)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -41,6 +41,7 @@ extension ProjectScaffolder {
|
||||
/* Begin PBXFileReference section */
|
||||
\t\t\(pbxAppProductRef) /* \(name).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \(name).app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
\t\t\(pbxInfoPlistRef) /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
\t\t\(pbxAppEntitlementsRef) /* \(name).entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = \(name).entitlements; sourceTree = "<group>"; };
|
||||
\t\t\(pbxMainSwiftRef) /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxAppDelegateRef) /* AppDelegate.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppDelegate.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxSynthRef) /* \(name)Synth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)Synth.swift; sourceTree = "<group>"; };
|
||||
@@ -85,6 +86,7 @@ extension ProjectScaffolder {
|
||||
\t\t\t\t\(pbxNoteControllerRef) /* NoteController.swift */,
|
||||
\t\t\t\t\(pbxViewRef) /* \(name)View.swift */,
|
||||
\t\t\t\t\(pbxInfoPlistRef) /* Info.plist */,
|
||||
\t\t\t\t\(pbxAppEntitlementsRef) /* \(name).entitlements */,
|
||||
\t\t\t);
|
||||
\t\t\tpath = \(name);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
@@ -177,6 +179,7 @@ extension ProjectScaffolder {
|
||||
\t\t\(pbxAppDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)/\(name).entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
@@ -197,6 +200,7 @@ extension ProjectScaffolder {
|
||||
\t\t\(pbxAppReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)/\(name).entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
|
||||
@@ -122,6 +122,8 @@ extension ProjectScaffolder {
|
||||
let files: [(String, String)] = [
|
||||
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
macOSAppInfoPlist(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name).entitlements"),
|
||||
macOSAppEntitlements()),
|
||||
((appGroupDir as NSString).appendingPathComponent("main.swift"),
|
||||
macOSAppMainSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
@@ -146,6 +148,35 @@ extension ProjectScaffolder {
|
||||
appInfoPlist(name: name, platform: .macOS)
|
||||
}
|
||||
|
||||
/// Entitlements for the standalone macOS performance app.
|
||||
///
|
||||
/// Not sandboxed — a live-performance app needs unrestricted access to
|
||||
/// audio devices, files (buffer load/render), MIDI, and OSC networking,
|
||||
/// which the App Sandbox would gate. The one entitlement granted is
|
||||
/// microphone / line-in: under the Hardened Runtime (enabled in the
|
||||
/// pbxproj, and required for notarization) the OS hard-kills the process
|
||||
/// the moment the AUHAL input bus opens unless this is present. It only
|
||||
/// prompts the user when input is actually opened
|
||||
/// (`numInputChannels > 0`), so it is harmless for output-only synths.
|
||||
///
|
||||
/// If a project needs to load dynamic libraries signed by a different
|
||||
/// team (e.g. a bundled `.dylib`), add
|
||||
/// `com.apple.security.cs.disable-library-validation`. If it must ship on
|
||||
/// the Mac App Store, add `com.apple.security.app-sandbox` and the
|
||||
/// specific resource entitlements the piece uses instead.
|
||||
static func macOSAppEntitlements() -> String {
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>com.apple.security.device.audio-input</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppMainSwift(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
@@ -178,6 +209,9 @@ extension ProjectScaffolder {
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// `@MainActor`: constructs the main-actor `NoteController` and synth,
|
||||
/// and `NSApplicationDelegate` callbacks already run on the main actor.
|
||||
@MainActor
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let controller: NoteController
|
||||
@@ -246,6 +280,11 @@ extension ProjectScaffolder {
|
||||
|
||||
/// Owns engine + synth + scope; mediates start/stop from the UI so the
|
||||
/// engine isn't kicked until user is ready (avoids first-block dropouts).
|
||||
///
|
||||
/// `@MainActor`: this drives SwiftUI and calls the engine's
|
||||
/// main-actor-isolated `add(_:)`, so the whole controller lives on the
|
||||
/// main actor.
|
||||
@MainActor
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
@@ -385,9 +424,15 @@ extension ProjectScaffolder {
|
||||
case .macOS:
|
||||
minOSKey = "LSMinimumSystemVersion"
|
||||
minOSValue = "$(MACOSX_DEPLOYMENT_TARGET)"
|
||||
// The mic usage string is required whenever the app opens the
|
||||
// AUHAL input bus: macOS crashes a Hardened-Runtime process on
|
||||
// audio-input access if this key is absent. Harmless for
|
||||
// output-only synths (no prompt fires until input opens).
|
||||
extras = """
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
<key>NSMicrophoneUsageDescription</key>
|
||||
<string>\(name) uses audio input for live signal processing.</string>
|
||||
"""
|
||||
case .iOS:
|
||||
minOSKey = "MinimumOSVersion"
|
||||
|
||||
@@ -3332,6 +3332,7 @@ extension DSLBuiltinRegistry {
|
||||
DSLParameter(label: "in", hasDefault: false),
|
||||
DSLParameter(label: "maxAmplitude", hasDefault: true),
|
||||
DSLParameter(label: "lookAheadTime", hasDefault: true),
|
||||
DSLParameter(label: "releaseTime", hasDefault: true),
|
||||
DSLParameter(label: "sampleRate", hasDefault: false),
|
||||
],
|
||||
make: { args in
|
||||
@@ -3339,6 +3340,7 @@ extension DSLBuiltinRegistry {
|
||||
in: try DSLArgument.input(args["in"], "LookAheadLimiter", "in"),
|
||||
maxAmplitude: try DSLArgument.input(args["maxAmplitude"] ?? .signal(1.0), "LookAheadLimiter", "maxAmplitude"),
|
||||
lookAheadTime: try DSLArgument.double(args["lookAheadTime"] ?? .signal(0.005), "LookAheadLimiter", "lookAheadTime"),
|
||||
releaseTime: try DSLArgument.input(args["releaseTime"] ?? .signal(0.050), "LookAheadLimiter", "releaseTime"),
|
||||
sampleRate: try DSLArgument.double(args["sampleRate"], "LookAheadLimiter", "sampleRate")
|
||||
)
|
||||
}
|
||||
@@ -5626,6 +5628,24 @@ extension DSLBuiltinRegistry {
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "ToneStack",
|
||||
rate: .audio,
|
||||
parameters: [
|
||||
DSLParameter(label: "input", hasDefault: false),
|
||||
DSLParameter(label: "bass", hasDefault: true),
|
||||
DSLParameter(label: "mid", hasDefault: true),
|
||||
DSLParameter(label: "treble", hasDefault: true),
|
||||
],
|
||||
make: { args in
|
||||
ToneStack(
|
||||
input: try DSLArgument.input(args["input"], "ToneStack", "input"),
|
||||
bass: try DSLArgument.input(args["bass"] ?? .signal(0.5), "ToneStack", "bass"),
|
||||
mid: try DSLArgument.input(args["mid"] ?? .signal(0.5), "ToneStack", "mid"),
|
||||
treble: try DSLArgument.input(args["treble"] ?? .signal(0.5), "ToneStack", "treble")
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "Trig",
|
||||
rate: .audio,
|
||||
@@ -5754,6 +5774,24 @@ extension DSLBuiltinRegistry {
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "TriodeStage",
|
||||
rate: .audio,
|
||||
parameters: [
|
||||
DSLParameter(label: "input", hasDefault: false),
|
||||
DSLParameter(label: "drive", hasDefault: true),
|
||||
DSLParameter(label: "bias", hasDefault: true),
|
||||
DSLParameter(label: "oversample", hasDefault: true),
|
||||
],
|
||||
make: { args in
|
||||
TriodeStage(
|
||||
input: try DSLArgument.input(args["input"], "TriodeStage", "input"),
|
||||
drive: try DSLArgument.input(args["drive"] ?? .signal(1.0), "TriodeStage", "drive"),
|
||||
bias: try DSLArgument.input(args["bias"] ?? .signal(0.0), "TriodeStage", "bias"),
|
||||
oversample: try DSLArgument.int(args["oversample"] ?? .signal(4), "TriodeStage", "oversample")
|
||||
)
|
||||
}
|
||||
),
|
||||
DSLBuiltin(
|
||||
name: "TuneablePitchShift",
|
||||
rate: .audio,
|
||||
|
||||
@@ -280,6 +280,7 @@ struct ProjectScaffolderTests {
|
||||
"MyMac/NoteController.swift",
|
||||
"MyMac/MyMacView.swift",
|
||||
"MyMac/Info.plist",
|
||||
"MyMac/MyMac.entitlements",
|
||||
]
|
||||
for rel: String in expected {
|
||||
let path: String = (root as NSString).appendingPathComponent(rel)
|
||||
@@ -299,6 +300,15 @@ struct ProjectScaffolderTests {
|
||||
#expect(src.contains("engine.remove(synth)"))
|
||||
}
|
||||
|
||||
@Test func macOSAppControllerAndDelegateAreMainActor() {
|
||||
// Both call the engine's @MainActor `add(_:)` / a main-actor synth
|
||||
// init; without @MainActor the template fails to compile under Swift 6.
|
||||
let controller: String = ProjectScaffolder.macOSAppNoteControllerSwift(name: "Foo")
|
||||
#expect(controller.contains("@MainActor"))
|
||||
let delegate: String = ProjectScaffolder.macOSAppDelegateSwift(name: "Foo")
|
||||
#expect(delegate.contains("@MainActor"))
|
||||
}
|
||||
|
||||
@Test func macOSAppViewHasStartStopButtons() {
|
||||
let src: String = ProjectScaffolder.macOSAppViewSwift(name: "Foo")
|
||||
#expect(src.contains("Start Engine"))
|
||||
@@ -576,6 +586,29 @@ struct ProjectScaffolderTests {
|
||||
#expect(pbx.contains("/local/Lyrebird"))
|
||||
}
|
||||
|
||||
@Test func macOSAppPBXProjWiresEntitlementsAndHardenedRuntime() {
|
||||
let pbx: String = ProjectScaffolder.macOSAppPBXProj(name: "Perf")
|
||||
// Hardened Runtime + entitlements are both required for a notarized,
|
||||
// distributable performance app that opens the AUHAL input bus.
|
||||
#expect(pbx.contains("ENABLE_HARDENED_RUNTIME = YES"))
|
||||
#expect(pbx.contains("CODE_SIGN_ENTITLEMENTS = Perf/Perf.entitlements;"))
|
||||
#expect(pbx.contains("Perf.entitlements */ = {isa = PBXFileReference"))
|
||||
}
|
||||
|
||||
@Test func macOSAppEntitlementsGrantAudioInputAndAreNotSandboxed() {
|
||||
let ent: String = ProjectScaffolder.macOSAppEntitlements()
|
||||
#expect(ent.contains("com.apple.security.device.audio-input"))
|
||||
// A live-performance app must not be sandboxed — it needs free file /
|
||||
// device / MIDI / OSC access the sandbox would gate.
|
||||
#expect(!ent.contains("com.apple.security.app-sandbox"))
|
||||
}
|
||||
|
||||
@Test func macOSAppInfoPlistHasMicrophoneUsageDescription() {
|
||||
let plist: String = ProjectScaffolder.macOSAppInfoPlist(name: "Perf")
|
||||
// Absent, a Hardened-Runtime process crashes on audio-input access.
|
||||
#expect(plist.contains("NSMicrophoneUsageDescription"))
|
||||
}
|
||||
|
||||
@Test func iOSAppPBXProjReferencesIPhoneOS() {
|
||||
let pbx: String = ProjectScaffolder.iOSAppPBXProj(name: "Foo")
|
||||
#expect(pbx.contains("SDKROOT = iphoneos"))
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// AudioFileCompressedTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AudioFileFormat compressed (AAC / ALAC)")
|
||||
struct AudioFileCompressedTests {
|
||||
|
||||
// MARK: - Derived properties
|
||||
|
||||
@Test("Compressed derived properties")
|
||||
func compressedProps() {
|
||||
for format: AudioFileFormat in [.aacHigh, .aacMedium, .alac] {
|
||||
#expect(format.audioFileTypeID == kAudioFileM4AType)
|
||||
#expect(format.fileExtension == "m4a")
|
||||
#expect(format.isCompressed == true)
|
||||
#expect(format.isFloatEncoding == false)
|
||||
#expect(format.usesRF64Writer == false)
|
||||
#expect(format.supportsLargeFiles == true) // not RIFF → 4 GB guard N/A
|
||||
#expect(format.riffOverflow(frameCount: Int.max / 4, channels: 8) == nil)
|
||||
}
|
||||
#expect(AudioFileFormat.aacHigh.aacBitrate == 256_000)
|
||||
#expect(AudioFileFormat.aacMedium.aacBitrate == 128_000)
|
||||
#expect(AudioFileFormat.alac.aacBitrate == nil)
|
||||
}
|
||||
|
||||
// MARK: - Container type on disk
|
||||
|
||||
@Test("Written m4a carries the requested codec", arguments: [
|
||||
(AudioFileFormat.aacHigh, kAudioFormatMPEG4AAC),
|
||||
(AudioFileFormat.aacMedium, kAudioFormatMPEG4AAC),
|
||||
(AudioFileFormat.alac, kAudioFormatAppleLossless),
|
||||
])
|
||||
func writtenCodecMatches(format: AudioFileFormat, formatID: AudioFormatID) throws {
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 4096)
|
||||
buffer.fillSine()
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mFormatID == formatID)
|
||||
}
|
||||
|
||||
// MARK: - ALAC round-trip (lossless of the 24-bit source)
|
||||
|
||||
@Test("ALAC round-trips through CoreAudio within 24-bit tolerance")
|
||||
func alacRoundTrip() throws {
|
||||
let frameCount: Int = 4096
|
||||
let values: [Double] = (0..<frameCount).map { sin(2.0 * Double.pi * 5.0 * Double($0) / Double(frameCount)) * 0.5 }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .alac, sampleRate: 44100)
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
|
||||
// ALAC is lossless of its 24-bit-quantised source; decoders may report a few
|
||||
// priming frames, so compare the overlapping interior. Tolerance ≈ 24-bit LSB.
|
||||
let tolerance: Double = 4.0 / 8388608.0
|
||||
let compareCount: Int = min(loaded.count, frameCount)
|
||||
#expect(compareCount > frameCount / 2) // most of the signal survived
|
||||
var maxErr: Double = 0
|
||||
for i: Int in 0..<compareCount {
|
||||
maxErr = max(maxErr, abs(loaded[i] - values[i]))
|
||||
}
|
||||
#expect(maxErr < tolerance, "ALAC max error \(maxErr) exceeds \(tolerance)")
|
||||
}
|
||||
|
||||
// MARK: - AAC round-trip (lossy — energy check)
|
||||
|
||||
@Test("AAC round-trips through CoreAudio and preserves signal energy", arguments: [
|
||||
AudioFileFormat.aacHigh, .aacMedium
|
||||
])
|
||||
func aacRoundTrip(format: AudioFileFormat) throws {
|
||||
let frameCount: Int = 8192
|
||||
let amplitude: Double = 0.5
|
||||
// A steady mid-band sine — AAC reconstructs this faithfully in energy terms.
|
||||
let values: [Double] = (0..<frameCount).map {
|
||||
sin(2.0 * Double.pi * 440.0 * Double($0) / 44100.0) * amplitude
|
||||
}
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count > frameCount / 2)
|
||||
|
||||
// RMS of the decoded interior (skip the primed head) should be near the
|
||||
// input sine's RMS (amplitude / sqrt(2)); AAC is lossy so allow a wide band.
|
||||
let skip: Int = 2048
|
||||
guard loaded.count > skip else { Issue.record("decoded too short"); return }
|
||||
var sumSquares: Double = 0
|
||||
var n: Int = 0
|
||||
for i: Int in skip..<loaded.count {
|
||||
sumSquares += loaded[i] * loaded[i]
|
||||
n += 1
|
||||
}
|
||||
let rms: Double = (n > 0) ? (sumSquares / Double(n)).squareRoot() : 0
|
||||
let expectedRMS: Double = amplitude / 2.0.squareRoot()
|
||||
#expect(rms > expectedRMS * 0.6 && rms < expectedRMS * 1.4,
|
||||
"AAC decoded RMS \(rms) not near expected \(expectedRMS)")
|
||||
}
|
||||
|
||||
// MARK: - Bitrate config actually takes effect
|
||||
|
||||
/// The AAC bitrate tiers must differ on disk — proves `applyEncoderConfig` set the
|
||||
/// encoder bitrate rather than silently no-opping (both would otherwise default).
|
||||
@Test("aacHigh produces a larger file than aacMedium")
|
||||
func aacBitrateTiersDiffer() throws {
|
||||
let frameCount: Int = 44100 // ~1 s of broadband content at 44.1 kHz
|
||||
var rng: UInt64 = 0x1234_5678
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { _, _ in
|
||||
// Cheap white-ish noise (xorshift) — broadband so bitrate matters.
|
||||
rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17
|
||||
return (Double(rng % 20000) / 10000.0 - 1.0) * 0.3
|
||||
}
|
||||
|
||||
func fileSize(_ format: AudioFileFormat) throws -> Int {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
try buffer.write(to: url, format: format, sampleRate: 44100)
|
||||
let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: url.path)
|
||||
return (attrs[.size] as? Int) ?? 0
|
||||
}
|
||||
|
||||
let highSize: Int = try fileSize(.aacHigh)
|
||||
let mediumSize: Int = try fileSize(.aacMedium)
|
||||
#expect(highSize > mediumSize,
|
||||
"aacHigh (\(highSize) B) should exceed aacMedium (\(mediumSize) B)")
|
||||
}
|
||||
|
||||
// MARK: - DiskOut rejects compressed
|
||||
|
||||
@MainActor
|
||||
@Test("DiskOut.Audio rejects compressed formats", arguments: [
|
||||
AudioFileFormat.aacHigh, .aacMedium, .alac
|
||||
])
|
||||
func diskOutRejectsCompressed(format: AudioFileFormat) {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
#expect {
|
||||
_ = try DiskOut.Audio(source: 0.0 as Double, channelCount: 1, url: url,
|
||||
sampleRate: 44100, format: format)
|
||||
} throws: { error in
|
||||
guard case DiskOutError.compressedFormatNotSupported(let rejected) = error
|
||||
else { return false }
|
||||
return rejected == format
|
||||
}
|
||||
// The guard fires before file creation — no file should exist.
|
||||
#expect(!FileManager.default.fileExists(atPath: url.path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
// AudioFileFormatTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("AudioFileFormat")
|
||||
struct AudioFileFormatTests {
|
||||
|
||||
// MARK: - Derived properties (golden per case)
|
||||
|
||||
@Test("Container type IDs per case")
|
||||
func containerTypeIDs() {
|
||||
#expect(AudioFileFormat.wavFloat32.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.wavInt16.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.wavInt24.audioFileTypeID == kAudioFileWAVEType)
|
||||
#expect(AudioFileFormat.aiffFloat32.audioFileTypeID == kAudioFileAIFCType)
|
||||
#expect(AudioFileFormat.cafFloat32.audioFileTypeID == kAudioFileCAFType)
|
||||
}
|
||||
|
||||
@Test("File extensions per case")
|
||||
func fileExtensions() {
|
||||
#expect(AudioFileFormat.wavFloat32.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.wavInt16.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.wavInt24.fileExtension == "wav")
|
||||
#expect(AudioFileFormat.aiffFloat32.fileExtension == "aiff")
|
||||
#expect(AudioFileFormat.cafFloat32.fileExtension == "caf")
|
||||
}
|
||||
|
||||
@Test("Bit depth per case")
|
||||
func bitDepths() {
|
||||
#expect(AudioFileFormat.wavFloat32.fileBitsPerChannel == 32)
|
||||
#expect(AudioFileFormat.wavInt16.fileBitsPerChannel == 16)
|
||||
#expect(AudioFileFormat.wavInt24.fileBitsPerChannel == 24)
|
||||
#expect(AudioFileFormat.aiffFloat32.fileBitsPerChannel == 32)
|
||||
#expect(AudioFileFormat.cafFloat32.fileBitsPerChannel == 32)
|
||||
}
|
||||
|
||||
@Test("Float vs integer encoding per case")
|
||||
func floatEncoding() {
|
||||
#expect(AudioFileFormat.wavFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.aiffFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.cafFloat32.isFloatEncoding == true)
|
||||
#expect(AudioFileFormat.wavInt16.isFloatEncoding == false)
|
||||
#expect(AudioFileFormat.wavInt24.isFloatEncoding == false)
|
||||
}
|
||||
|
||||
@Test("Endianness per case (only AIFF-C is big-endian)")
|
||||
func endianness() {
|
||||
#expect(AudioFileFormat.aiffFloat32.isBigEndian == true)
|
||||
#expect(AudioFileFormat.wavFloat32.isBigEndian == false)
|
||||
#expect(AudioFileFormat.wavInt16.isBigEndian == false)
|
||||
#expect(AudioFileFormat.wavInt24.isBigEndian == false)
|
||||
#expect(AudioFileFormat.cafFloat32.isBigEndian == false)
|
||||
}
|
||||
|
||||
// MARK: - Back-compat shorthands
|
||||
|
||||
@Test("Back-compat shorthands map to Float32 cases")
|
||||
func backCompatShorthands() {
|
||||
#expect(AudioFileFormat.wav == .wavFloat32)
|
||||
#expect(AudioFileFormat.aiff == .aiffFloat32)
|
||||
#expect(AudioFileFormat.caf == .cafFloat32)
|
||||
}
|
||||
|
||||
/// The deprecated `DiskOutFormat` alias still resolves for external source
|
||||
/// compatibility. Annotated deprecated so the alias reference does not raise an
|
||||
/// in-tree deprecation warning (the whole point of the alias is out-of-tree use).
|
||||
@available(*, deprecated, message: "Exercises the deprecated DiskOutFormat alias.")
|
||||
@Test("DiskOutFormat alias still resolves to AudioFileFormat")
|
||||
func diskOutFormatAliasResolves() {
|
||||
#expect(DiskOutFormat.wavFloat32 == AudioFileFormat.wavFloat32)
|
||||
#expect(DiskOutFormat.aiff == AudioFileFormat.aiffFloat32)
|
||||
}
|
||||
|
||||
// MARK: - makeFileASBD golden fields
|
||||
|
||||
@Test("File ASBD — WAV Float32 stereo")
|
||||
func fileASBDWavFloat32() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavFloat32.makeFileASBD(sampleRate: 48000, channels: 2)
|
||||
#expect(asbd.mSampleRate == 48000)
|
||||
#expect(asbd.mFormatID == kAudioFormatLinearPCM)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mChannelsPerFrame == 2)
|
||||
#expect(asbd.mFramesPerPacket == 1)
|
||||
#expect(asbd.mBytesPerFrame == 8) // 4 bytes/sample × 2 ch
|
||||
#expect(asbd.mBytesPerPacket == 8)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — WAV Int16 mono")
|
||||
func fileASBDWavInt16() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavInt16.makeFileASBD(sampleRate: 44100, channels: 1)
|
||||
#expect(asbd.mBitsPerChannel == 16)
|
||||
#expect(asbd.mBytesPerFrame == 2) // 2 bytes/sample × 1 ch
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — WAV Int24 packed stereo")
|
||||
func fileASBDWavInt24() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.wavInt24.makeFileASBD(sampleRate: 96000, channels: 2)
|
||||
#expect(asbd.mBitsPerChannel == 24)
|
||||
#expect(asbd.mBytesPerFrame == 6) // 3 bytes/sample × 2 ch (packed)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0)
|
||||
}
|
||||
|
||||
@Test("File ASBD — AIFF-C Float32 is big-endian")
|
||||
func fileASBDAiffFloat32() {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
AudioFileFormat.aiffFloat32.makeFileASBD(sampleRate: 48000, channels: 1)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mBytesPerFrame == 4)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian != 0)
|
||||
}
|
||||
|
||||
// MARK: - makeClientASBD always native Float32
|
||||
|
||||
@Test("Client ASBD is native-endian Float32 regardless of file encoding")
|
||||
func clientASBDAlwaysFloat32() {
|
||||
for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32] {
|
||||
let asbd: AudioStreamBasicDescription =
|
||||
format.makeClientASBD(sampleRate: 48000, channels: 2)
|
||||
#expect(asbd.mFormatID == kAudioFormatLinearPCM)
|
||||
#expect(asbd.mBitsPerChannel == 32)
|
||||
#expect(asbd.mBytesPerFrame == 8) // Float32 × 2 ch
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Large-file guard
|
||||
|
||||
@Test("supportsLargeFiles is true only for CAF")
|
||||
func supportsLargeFiles() {
|
||||
#expect(AudioFileFormat.cafFloat32.supportsLargeFiles == true)
|
||||
for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32] {
|
||||
#expect(format.supportsLargeFiles == false)
|
||||
}
|
||||
}
|
||||
|
||||
@Test("projectedByteCount tracks the format's bit depth")
|
||||
func projectedByteCount() {
|
||||
let frames: Int = 100
|
||||
let channels: Int = 2
|
||||
let bytesFloat32: Int = 4
|
||||
let bytesInt16: Int = 2
|
||||
let bytesInt24: Int = 3
|
||||
#expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32)
|
||||
#expect(AudioFileFormat.wavInt16.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt16)
|
||||
#expect(AudioFileFormat.wavInt24.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt24)
|
||||
#expect(AudioFileFormat.aiffFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32)
|
||||
}
|
||||
|
||||
@Test("riffOverflow flags an oversize WAV at the boundary and exempts CAF")
|
||||
func riffOverflowBoundary() {
|
||||
let cap: Int = lyrebirdMaxRIFFBytes
|
||||
let bytesPerSampleFloat32: Int = 4
|
||||
// Largest mono Float32 frame count that still fits under the cap.
|
||||
let underFrames: Int = cap / bytesPerSampleFloat32
|
||||
#expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames, channels: 1) == nil)
|
||||
|
||||
// One frame past that overflows (the cap's remainder mod 4 < 4 guarantees crossing).
|
||||
let over: (projected: Int, cap: Int)? =
|
||||
AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1)
|
||||
#expect(over != nil)
|
||||
#expect(over?.cap == cap)
|
||||
#expect((over?.projected ?? 0) > cap)
|
||||
|
||||
// AIFF-C is likewise 32-bit-capped.
|
||||
#expect(AudioFileFormat.aiffFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1) != nil)
|
||||
|
||||
// CAF is 64-bit — never flagged, even for absurd sizes. (Returns nil before
|
||||
// projectedByteCount runs, so the multiply cannot overflow Int.)
|
||||
#expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: Int.max / 8, channels: 8) == nil)
|
||||
}
|
||||
|
||||
@Test("projectedByteCount / riffOverflow saturate instead of trapping on overflow")
|
||||
func projectedByteCountOverflowSafe() {
|
||||
// A frame count large enough to overflow the byte product must saturate to
|
||||
// Int.max (no trap) and be reported as over-cap for a 32-bit container.
|
||||
#expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: Int.max, channels: 8) == Int.max)
|
||||
let over: (projected: Int, cap: Int)? =
|
||||
AudioFileFormat.wavFloat32.riffOverflow(frameCount: Int.max, channels: 8)
|
||||
#expect(over != nil)
|
||||
#expect(over?.projected == Int.max)
|
||||
}
|
||||
|
||||
@Test("LyrebirdBuffer.write throws fileTooLargeForContainer for oversize WAV projection")
|
||||
func bufferWriteGuardDecision() {
|
||||
// The decision the buffer guard makes is exactly riffOverflow — asserted here
|
||||
// without allocating a multi-GB buffer. A 200M-frame × 8ch Float32 projection
|
||||
// is ~6.4 GB > cap.
|
||||
let frames: Int = 200_000_000
|
||||
let channels: Int = 8
|
||||
#expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: frames, channels: channels) != nil)
|
||||
#expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: frames, channels: channels) == nil)
|
||||
}
|
||||
|
||||
// MARK: - Round-trip: write via factory-backed LyrebirdBuffer.write, reload
|
||||
|
||||
/// Write a mono ramp buffer in each Float32 container and reload it, confirming
|
||||
/// sample rate, frame count, and channel count survive the round-trip.
|
||||
@Test("Round-trip write→load preserves rate/frames/channels", arguments: [
|
||||
AudioFileFormat.wavFloat32, .aiffFloat32, .cafFloat32
|
||||
])
|
||||
func roundTripFloat32(format: AudioFileFormat) throws {
|
||||
let frameCount: Int = 256
|
||||
let sampleRate: Double = 44100
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
for i: Int in 0..<frameCount {
|
||||
buffer.setValue(Double(i) / Double(frameCount), at: i)
|
||||
}
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension(format.fileExtension)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: sampleRate)
|
||||
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(reloaded.count == frameCount)
|
||||
#expect(reloaded.channelCount == 1)
|
||||
let reloadedRate: Double = try #require(reloaded.sampleRate)
|
||||
#expect(abs(reloadedRate - sampleRate) < 1.0)
|
||||
|
||||
// Float32 is lossless for these ramp values — expect near-exact reload.
|
||||
let mid: Int = frameCount / 2
|
||||
#expect(abs(reloaded[mid] - buffer[mid]) < 1e-5)
|
||||
}
|
||||
|
||||
/// The written file's on-disk encoding matches the requested format's bit depth
|
||||
/// and float/integer flag (queried via the reopened file's data-format ASBD).
|
||||
@Test("Written file encoding matches requested format", arguments: [
|
||||
AudioFileFormat.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32
|
||||
])
|
||||
func writtenEncodingMatches(format: AudioFileFormat) throws {
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 64)
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString)
|
||||
.appendingPathExtension(format.fileExtension)
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: format, sampleRate: 48000)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef)
|
||||
#expect(openStatus == noErr)
|
||||
let fileRef2: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(fileRef2) }
|
||||
|
||||
var fileASBD: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
let status: OSStatus = ExtAudioFileGetProperty(
|
||||
fileRef2, kExtAudioFileProperty_FileDataFormat, &size, &fileASBD
|
||||
)
|
||||
#expect(status == noErr)
|
||||
#expect(fileASBD.mBitsPerChannel == format.fileBitsPerChannel)
|
||||
let isFloat: Bool = fileASBD.mFormatFlags & kAudioFormatFlagIsFloat != 0
|
||||
#expect(isFloat == format.isFloatEncoding)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
// RF64WriterTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
@Suite("RF64Writer")
|
||||
struct RF64WriterTests {
|
||||
|
||||
// MARK: - Header golden bytes
|
||||
|
||||
@Test("RF64 header has RF64/WAVE/ds64/fmt/data structure")
|
||||
func headerStructure() throws {
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 8, channelCount: 2)
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: 48000)
|
||||
|
||||
let data: Data = try Data(contentsOf: url)
|
||||
#expect(data.count >= 104)
|
||||
func fourCC(_ off: Int) -> String { String(decoding: data[off..<off+4], as: UTF8.self) }
|
||||
#expect(fourCC(0) == "RF64")
|
||||
#expect(fourCC(8) == "WAVE")
|
||||
#expect(fourCC(12) == "ds64")
|
||||
#expect(fourCC(48) == "fmt ")
|
||||
#expect(fourCC(96) == "data")
|
||||
// RIFF-size and data-size sentinels.
|
||||
func u32(_ off: Int) -> UInt32 {
|
||||
data[off..<off+4].reversed().reduce(UInt32(0)) { ($0 << 8) | UInt32($1) }
|
||||
}
|
||||
#expect(u32(4) == 0xFFFF_FFFF) // RIFF size sentinel
|
||||
#expect(u32(100) == 0xFFFF_FFFF) // data size sentinel
|
||||
}
|
||||
|
||||
// MARK: - CoreAudio interop (RF64 read-back)
|
||||
|
||||
/// The definitive interop proof: write RF64 with RF64Writer, then reopen with
|
||||
/// CoreAudio's `ExtAudioFile` (via `LyrebirdBuffer.load`). CoreAudio reads RF64,
|
||||
/// so a successful load with matching samples proves the container is valid.
|
||||
@Test("RF64 Float32 round-trips through CoreAudio reader")
|
||||
func rf64Float32RoundTrip() throws {
|
||||
let frameCount: Int = 128
|
||||
let sampleRate: Double = 44100
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: sampleRate)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
#expect(loaded.channelCount == 1)
|
||||
let reloadedRate: Double = try #require(loaded.sampleRate)
|
||||
#expect(abs(reloadedRate - sampleRate) < 1.0)
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < 1e-5, "RF64 Float32 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 Int24 round-trips through CoreAudio reader within one LSB")
|
||||
func rf64Int24RoundTrip() throws {
|
||||
let frameCount: Int = 128
|
||||
let values: [Double] = (0..<frameCount).map { -1.0 + 2.0 * Double($0) / Double(frameCount - 1) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Int24, sampleRate: 44100)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
let tolerance: Double = 2.0 / 8388608.0
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance, "RF64 Int24 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 multichannel preserves channel order")
|
||||
func rf64MultichannelRoundTrip() throws {
|
||||
let frameCount: Int = 64
|
||||
let channelCount: Int = 3
|
||||
let ch: [[Double]] = [
|
||||
(0..<frameCount).map { 0.01 * Double($0) },
|
||||
(0..<frameCount).map { -0.02 * Double($0) },
|
||||
(0..<frameCount).map { 0.5 - 0.03 * Double($0) }
|
||||
]
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount, channelCount: channelCount)
|
||||
for c: Int in 0..<channelCount {
|
||||
for f: Int in 0..<frameCount { buffer.setValue(ch[c][f], frame: f, channel: c) }
|
||||
}
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Float32, sampleRate: 48000)
|
||||
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url)
|
||||
#expect(reloaded.channelCount == channelCount)
|
||||
#expect(reloaded.count == frameCount)
|
||||
for c: Int in 0..<channelCount {
|
||||
for f: Int in 0..<frameCount {
|
||||
#expect(abs(reloaded[f, c] - ch[c][f]) < 1e-5, "RF64 ch \(c) frame \(f) mismatch")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Odd `data`-payload length (mono Int24 × odd frames = odd byte count) must get a
|
||||
/// RIFF word-alignment pad byte and still read back correctly through CoreAudio.
|
||||
@Test("RF64 Int24 mono odd frame count round-trips (pad-byte path)")
|
||||
func rf64Int24OddFramesPadByte() throws {
|
||||
let frameCount: Int = 127 // 127 × 3 bytes = 381 (odd) → needs a pad byte
|
||||
let values: [Double] = (0..<frameCount).map { -0.5 + Double($0) / Double(frameCount) }
|
||||
let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount)
|
||||
buffer.fill { i, _ in values[i] }
|
||||
|
||||
let url: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav")
|
||||
defer { try? FileManager.default.removeItem(at: url) }
|
||||
|
||||
try buffer.write(to: url, format: .rf64Int24, sampleRate: 44100)
|
||||
|
||||
// File length must be even (header 104 + 381 data + 1 pad = 486).
|
||||
let fileBytes: Int = try Data(contentsOf: url).count
|
||||
#expect(fileBytes % 2 == 0)
|
||||
|
||||
let loaded: LyrebirdBuffer = try LyrebirdBuffer.load(url: url)
|
||||
#expect(loaded.count == frameCount)
|
||||
let tolerance: Double = 2.0 / 8388608.0
|
||||
for i: Int in 0..<frameCount {
|
||||
#expect(abs(loaded[i] - values[i]) < tolerance, "odd-frame Int24 mismatch at \(i)")
|
||||
}
|
||||
}
|
||||
|
||||
@Test("RF64 format is exempt from the 4 GB large-file guard")
|
||||
func rf64ExemptFromCap() {
|
||||
#expect(AudioFileFormat.rf64Float32.supportsLargeFiles == true)
|
||||
#expect(AudioFileFormat.rf64Int24.supportsLargeFiles == true)
|
||||
#expect(AudioFileFormat.rf64Float32.usesRF64Writer == true)
|
||||
// riffOverflow must never flag RF64, even at absurd sizes.
|
||||
#expect(AudioFileFormat.rf64Float32.riffOverflow(frameCount: Int.max / 8, channels: 8) == nil)
|
||||
}
|
||||
}
|
||||
@@ -496,6 +496,108 @@ struct DiskInOutTests {
|
||||
#expect(interior.allSatisfy { abs(Double($0) - Double(testValue)) < 0.01 })
|
||||
}
|
||||
|
||||
@Test func diskOutSmallWavDoesNotTripLargeFileGuard() throws {
|
||||
// A normal short WAV recording must not trip the 4 GB container guard, and
|
||||
// the guard wiring must leave the drain intact (file written, no errors).
|
||||
// The overflow *decision* is covered by AudioFileFormat.riffOverflow unit
|
||||
// tests — actually writing 4 GB in CI is infeasible.
|
||||
let sampleRate: Double = 44100
|
||||
let renderFrames: Int = 512
|
||||
let testValue: Float = 0.4
|
||||
|
||||
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: diskOutURL)
|
||||
try? FileManager.default.removeItem(at: nrtOutURL)
|
||||
}
|
||||
|
||||
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
||||
channelCount: 1,
|
||||
url: diskOutURL,
|
||||
sampleRate: sampleRate,
|
||||
format: .wavFloat32,
|
||||
bufferFrames: 512)
|
||||
|
||||
final class RecordSynth: SynthesizerBase {
|
||||
let d: DiskOut.Audio
|
||||
init(_ d: DiskOut.Audio) { self.d = d }
|
||||
override func build() { output(bus: 0, source: d) }
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(RecordSynth(diskOut))
|
||||
try engine.start()
|
||||
diskOut.close()
|
||||
|
||||
#expect(diskOut.fileTooLarge == false)
|
||||
#expect(diskOut.writeError == false)
|
||||
|
||||
let channels: [[Float]] = try readWAVSamples(url: diskOutURL, channelCount: 1,
|
||||
sampleRate: sampleRate)
|
||||
#expect(channels.count == 1)
|
||||
let interior: [Float] = Array(channels[0].dropFirst())
|
||||
#expect(interior.allSatisfy { abs(Double($0) - Double(testValue)) < 0.01 })
|
||||
}
|
||||
|
||||
@Test func diskOutRF64StreamingRoundTrip() throws {
|
||||
// Stream a constant through DiskOut to an RF64 target, close (patches ds64
|
||||
// sizes), then read back through CoreAudio to prove the streamed RF64 file is
|
||||
// valid and the size patch landed.
|
||||
let sampleRate: Double = 44100
|
||||
let renderFrames: Int = 1024
|
||||
let testValue: Float = 0.3
|
||||
|
||||
let diskOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".wav")
|
||||
let nrtOutURL: URL = FileManager.default.temporaryDirectory
|
||||
.appendingPathComponent(UUID().uuidString + ".caf")
|
||||
defer {
|
||||
try? FileManager.default.removeItem(at: diskOutURL)
|
||||
try? FileManager.default.removeItem(at: nrtOutURL)
|
||||
}
|
||||
|
||||
let diskOut: DiskOut.Audio = try DiskOut.Audio(source: Double(testValue),
|
||||
channelCount: 2,
|
||||
url: diskOutURL,
|
||||
sampleRate: sampleRate,
|
||||
format: .rf64Float32,
|
||||
bufferFrames: 512)
|
||||
|
||||
final class RecordSynth: SynthesizerBase {
|
||||
let d: DiskOut.Audio
|
||||
init(_ d: DiskOut.Audio) { self.d = d }
|
||||
override func build() {
|
||||
output(bus: 0, source: d)
|
||||
output(bus: 1, source: d)
|
||||
}
|
||||
}
|
||||
|
||||
let engine: SynthesisEngine = makeNRTEngine(outputURL: nrtOutURL,
|
||||
duration: Double(renderFrames) / sampleRate)
|
||||
try engine.add(RecordSynth(diskOut))
|
||||
try engine.start()
|
||||
diskOut.close()
|
||||
|
||||
#expect(diskOut.writeError == false)
|
||||
#expect(diskOut.fileTooLarge == false)
|
||||
|
||||
// First four bytes must be the RF64 FourCC.
|
||||
let head: Data = try Data(contentsOf: diskOutURL).prefix(4)
|
||||
#expect(String(decoding: head, as: UTF8.self) == "RF64")
|
||||
|
||||
// CoreAudio reads it back; the streamed constant survives.
|
||||
let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: diskOutURL)
|
||||
#expect(reloaded.channelCount == 2)
|
||||
#expect(reloaded.count > 0)
|
||||
for f: Int in 1..<reloaded.count {
|
||||
#expect(abs(reloaded[f, 0] - Double(testValue)) < 1e-4, "RF64 DiskOut ch0 frame \(f)")
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - DiskOut stereo round-trip
|
||||
|
||||
@Test func diskOutStereoRoundTrip() throws {
|
||||
|
||||
@@ -6,6 +6,7 @@
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
import AudioToolbox
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// NRT `build`-closure shim.
|
||||
@@ -286,6 +287,44 @@ struct EngineHostTests {
|
||||
}
|
||||
}
|
||||
|
||||
@Test func renderConcurrentHonoursJobFormat() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||
let host: EngineHost = EngineHost()
|
||||
// A non-default format (WAV / Int16) must reach the output file.
|
||||
let outURL: URL = dir.appendingPathComponent("stem.wav")
|
||||
let jobs: [NRTJob] = [
|
||||
NRTJob(
|
||||
outputURL: outURL,
|
||||
duration: 0.05,
|
||||
format: .wavInt16,
|
||||
blockSize: 64,
|
||||
sampleRate: 44100,
|
||||
numOutputChannels: 2
|
||||
) { engine in
|
||||
try nrtBuildAdd(engine) { ConstSynth(value: 0.25) }
|
||||
}
|
||||
]
|
||||
|
||||
var results: [NRTResult] = []
|
||||
for try await result: NRTResult in host.renderConcurrent(jobs: jobs) {
|
||||
results.append(result)
|
||||
}
|
||||
#expect(results.count == 1)
|
||||
|
||||
var fileRef: ExtAudioFileRef?
|
||||
#expect(ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr)
|
||||
let ref: ExtAudioFileRef = try #require(fileRef)
|
||||
defer { ExtAudioFileDispose(ref) }
|
||||
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
|
||||
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
|
||||
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
|
||||
#expect(asbd.mBitsPerChannel == 16)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0)
|
||||
#expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0)
|
||||
}
|
||||
|
||||
@Test func renderConcurrentPropagatesBuildFailure() async throws {
|
||||
let (dir, cleanup): (URL, () -> Void) = try makeScratchDir()
|
||||
defer { cleanup() }
|
||||
|
||||