4 Commits

Author SHA1 Message Date
josh d6875da2cb v1.6.4 release: LookAheadLimiter releaseTime decoupled from lookAheadTime
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-31 18:10:54 -07:00
josh 5e6534a615 v1.6.3 release: notarization-ready macos-ui-xcode template
Scaffolded macOS app now ships audio-input entitlement + mic usage string
under Hardened Runtime (unsandboxed for performance), and compiles under
Swift 6 (NoteController/AppDelegate marked @MainActor).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-23 08:38:41 -07:00
josh 9ec92277de v1.6.2 release: Live Scratch distributable/notarized app
Bundle Lyrebird swiftmodules + relocatable LyrebirdC module into the app so a
notarized, moved LyrebirdScratch.app can compile snippets off the build machine.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 20:13:47 -07:00
josh 90dc00f323 v1.6.1 release: Live Scratch Swift-toolchain detection + app icon
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-22 19:19:44 -07:00
28 changed files with 713 additions and 40 deletions
@@ -13,6 +13,7 @@
C8D00000000000000000022 /* LyrebirdLiveCompileUIDynamic in Frameworks */ = {isa = PBXBuildFile; productRef = C8D00000000000000000020 /* LyrebirdLiveCompileUIDynamic */; };
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 PBXCopyFilesBuildPhase section */
@@ -36,6 +37,7 @@
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 */
@@ -74,6 +76,7 @@
C8D00000000000000000008 /* AppDelegate.swift */,
C8D00000000000000000006 /* Info.plist */,
C8D00000000000000000009 /* LyrebirdScratch.entitlements */,
C8D00000000000000000040 /* Assets.xcassets */,
);
path = LyrebirdScratch;
sourceTree = "<group>";
@@ -89,6 +92,7 @@
C8D00000000000000000012 /* Frameworks */,
C8D00000000000000000013 /* Resources */,
C8D00000000000000000035 /* Embed Frameworks */,
C8D00000000000000000042 /* Bundle Lyrebird swiftmodules */,
);
buildRules = (
);
@@ -111,7 +115,7 @@
attributes = {
BuildIndependentTargetsInParallel = 1;
LastSwiftUpdateCheck = 1600;
LastUpgradeCheck = 2620;
LastUpgradeCheck = 2660;
TargetAttributes = {
C8D00000000000000000014 = {
CreatedOnToolsVersion = 16.0;
@@ -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,14 +189,16 @@
C8D00000000000000000016 /* Debug */ = {
isa = XCBuildConfiguration;
buildSettings = {
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;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
@@ -181,12 +206,14 @@
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;
MARKETING_VERSION = 1.6.2;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -204,13 +231,15 @@
C8D00000000000000000017 /* Release */ = {
isa = XCBuildConfiguration;
buildSettings = {
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;
DEVELOPMENT_TEAM = HE5VJFE9E4;
ENABLE_HARDENED_RUNTIME = YES;
ENABLE_RESOURCE_ACCESS_AUDIO_INPUT = YES;
ENABLE_RESOURCE_ACCESS_CALENDARS = NO;
@@ -218,12 +247,14 @@
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;
MARKETING_VERSION = 1.6.2;
PRODUCT_BUNDLE_IDENTIFIER = net.realizedsound.LyrebirdScratch;
PRODUCT_NAME = "$(TARGET_NAME)";
PROVISIONING_PROFILE_SPECIFIER = "";
@@ -273,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;
@@ -336,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;
@@ -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 }
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 338 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 13 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 720 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

Binary file not shown.

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>
@@ -164,6 +164,14 @@ extension LiveSession {
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) —
@@ -232,6 +240,32 @@ extension LiveSession {
/// 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(
@@ -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
@@ -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
@@ -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,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
@@ -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
+99
View File
@@ -7,6 +7,105 @@ functionality in a backward-compatible way.
---
## 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
@@ -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 +
@@ -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")
)
}
@@ -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"))
@@ -480,6 +480,34 @@ struct LookAheadLimiterTests {
let tailMax: Double = tail.map { abs($0) }.max() ?? 0
#expect(tailMax < maxAmp * 10.0) // generous bound; really we want "small"
}
/// `releaseTime` is decoupled from `lookAheadTime`: with the look-ahead window held
/// fixed, two different release times must produce different gain-recovery behaviour
/// (hence different output) on a low-frequency signal that crosses the ceiling on its
/// peaks and dips below between them — while both still respect the ceiling.
@Test func releaseTimeIndependentOfLookAhead() {
let maxAmp: Double = 0.3
func run(_ releaseTime: Double) -> [Double] {
let sine: OscSin.Audio = OscSin.Audio(freq: 60.0, mul: 1.0)
let lim: LookAheadLimiter = LookAheadLimiter(
in: sine, maxAmplitude: maxAmp,
lookAheadTime: 0.005, releaseTime: releaseTime, sampleRate: sr)
return collectBlocks(lim, engine: engine, blocks: 100)
}
let fast: [Double] = run(0.005)
let slow: [Double] = run(0.200)
// Ceiling holds for both release settings.
#expect(fast.allSatisfy { abs($0) <= maxAmp + 0.001 })
#expect(slow.allSatisfy { abs($0) <= maxAmp + 0.001 })
// Different release → different waveform.
let tailFast: [Double] = Array(fast.suffix(engine.blockSize * 50))
let tailSlow: [Double] = Array(slow.suffix(engine.blockSize * 50))
let ssd: Double = zip(tailFast, tailSlow).reduce(0.0) { acc, pair in
let diff: Double = pair.0 - pair.1
return acc + diff * diff
}
#expect(ssd > 0, "releaseTime had no effect on limiter output")
}
}
// MARK: - Compressor Tests
+5 -3
View File
@@ -105,7 +105,7 @@ File: `Sources/Lyrebird/Generators/Dynamics/LookAheadLimiter.swift`
Delays the output by `lookAheadTime` seconds and uses the look-ahead window to detect peaks before they arrive, guaranteeing the output never exceeds `±maxAmplitude`. No overshoot.
```swift
LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
LookAheadLimiter(in:maxAmplitude:lookAheadTime:releaseTime:sampleRate:)
```
| Parameter | Type | Default | Description |
@@ -113,6 +113,7 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
| `in` | `ValidGeneratorInput` | — | Signal to limit |
| `maxAmplitude` | `ValidGeneratorInput` | `1.0` | Peak ceiling (absolute value) |
| `lookAheadTime` | `Double` | `0.005` | Delay in seconds. Set at init. |
| `releaseTime` | `ValidGeneratorInput` | `0.050` | Gain-release time constant (seconds), read per block; decoupled from `lookAheadTime`. Clamped to ≥ 0. Keep it above the period of the lowest expected frequency to avoid low-frequency distortion. |
| `sampleRate` | `Double` | `44100.0` | Used to size ring buffers at init. |
**Output:** single channel, delayed by `lookAheadSamples = Int(lookAheadTime × sampleRate)`.
@@ -122,7 +123,7 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
2. Scan the look-ahead window (`lookAheadSamples`) for peak.
3. Required gain = `min(1, maxAmplitude / peak)`.
4. Attack is **instantaneous** (gain can always be reduced within the window).
5. Release smoothed: `releaseCoeff = exp(−1 / (sr × lookAheadTime))`.
5. Release smoothed: `releaseCoeff = exp(−1 / (sr × releaseTime))`, recomputed per block (so `releaseTime` may track a live parameter) rather than fixed at init.
6. Output = delayed sample × current gain.
**Pre-allocated buffers:**
@@ -134,7 +135,8 @@ LookAheadLimiter(in:maxAmplitude:lookAheadTime:sampleRate:)
**Usage:**
```swift
let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005)
let mastered = LookAheadLimiter(in: mix, maxAmplitude: 0.99, lookAheadTime: 0.005,
releaseTime: 0.050, sampleRate: engine.sampleRate)
```
---
+16 -10
View File
@@ -49,7 +49,7 @@ Xcode-project templates (ship a real `.xcodeproj` for deliverables SwiftPM can't
| Template | Command | Description |
|---|---|---|
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth, hardened runtime |
| `macos-ui-xcode` | `lyrebird new MyApp --template macos-ui-xcode` | macOS `.app` (AppKit + SwiftUI), `@UIParam` synth. Notarization-ready: hardened runtime + `.entitlements` (audio-input) + mic usage string, unsandboxed for performance |
| `ios-ui` | `lyrebird new MyApp --template ios-ui` | iOS `.app` (SwiftUI + `iOSAudioDriver`), `AVAudioSession` activation, iPhone + iPad device family |
| `auv3` | `lyrebird new MyPlugin --template auv3` | AUv3 host `.app` + `aumu` `.appex` subclassing `LyrebirdAudioUnit`. Entitlements for both. Subtype + manufacturer pre-filled (manufacturer = `LYRB` placeholder — rewrite for distribution) |
@@ -62,7 +62,7 @@ Each Xcode-project template lays out:
│ └── xcshareddata/xcschemes/<name>.xcscheme
├── <name>.xcworkspace/
│ └── contents.xcworkspacedata (references <name>.xcodeproj)
├── <name>/ (app target sources + Info.plist [+ entitlements for auv3])
├── <name>/ (app target sources + Info.plist [+ .entitlements for macos-ui-xcode / auv3])
│ └── ...
└── <name>Extension/ (auv3 only — extension target + Info.plist + .entitlements)
└── ...
@@ -70,20 +70,26 @@ Each Xcode-project template lays out:
Lyrebird is pulled in via a remote SPM dependency on `https://realizedsound.mooo.com/josh/Lyrebird` (configurable via `ProjectScaffolder.lyrebirdPackageURL`). The scaffolded project lives anywhere on disk and does not need a local checkout.
### Microphone input — not pre-wired in any template
### Distribution & microphone input
No template adds `NSMicrophoneUsageDescription` to the generated `Info.plist`, no template adds the hardened-runtime / sandbox audio-input capability, and the `ios-ui` template's `AVAudioSession` category is `.playback` (output only). Most pieces don't read live input, so the templates default to "no mic capability" rather than triggering a permission prompt on every first run.
The `macos-ui-xcode` template is **notarization-ready and distributable for performance out of the box**. It ships:
- **Hardened Runtime** enabled (required for Developer-ID notarization), and
- `<name>.entitlements` granting `com.apple.security.device.audio-input`, plus `NSMicrophoneUsageDescription` in `Info.plist`.
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph), the project owner must add these themselves:
The app is deliberately **not sandboxed** — a live-performance app needs unrestricted audio-device / file / MIDI / OSC access that the App Sandbox would gate. Nothing else is required to move the signed `.app` to another machine and run it: Lyrebird is statically linked (compiled from the SPM source), so there is no external module to bundle. (The bundled-swiftmodule dance in `LyrebirdScratch` is unique to its *runtime* `swiftc` scratchpad and does not apply to a normal Lyrebird app.)
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver.
The audio-input entitlement + usage string are **harmless for output-only synths**: no permission prompt fires until the AUHAL input bus actually opens (`numInputChannels > 0`). They exist so a piece that *does* take live input works without the OS hard-killing the Hardened-Runtime process on first input access.
**macOS** (`macos-ui-xcode`, `ui-demo` opened in Xcode, any AppKit/SwiftUI app):
- Add `NSMicrophoneUsageDescription` (string explaining the use) to the target's `Info.plist`. Required since macOS 10.14 — without it the OS silently denies input access and `CoreAudioDriver` reads zeros.
- If the app is sandboxed: add `com.apple.security.device.audio-input` to the `.entitlements` file. The `macos-ui-xcode` template ships unsandboxed; the `auv3` host app is sandboxed and will need the entitlement before the host can read mic in addition to hosting the plugin.
If a piece needs live input (e.g. tapping the engine input bus into `ScopeCapture` or routing `In.Audio(bus: numOutputChannels)` through the graph):
**Engine init** — set `numInputChannels > 0` and pass a non-nil `inputDeviceID` (macOS) when constructing `SynthesisEngine` / starting the driver. On `macos-ui-xcode` the mic entitlement + usage string are already present, so the first `start()` after that triggers the permission prompt directly.
**Other knobs:**
- **Mac App Store** target: add `com.apple.security.app-sandbox` to `<name>.entitlements` plus the specific resource entitlements the piece uses. (Sandboxing is off by default precisely because most performance work is Developer-ID / direct-distribution, not App Store.)
- **Loading a differently-signed dynamic library** (a bundled `.dylib`): add `com.apple.security.cs.disable-library-validation`.
**iOS** (`ios-ui`):
- Add `NSMicrophoneUsageDescription` to the app `Info.plist`.
- Add `NSMicrophoneUsageDescription` to the app `Info.plist` (not pre-wired — the iOS template is output-only by default).
- Change the `AVAudioSession` category in the generated `AppDelegate` / `App` activation block from `.playback` to `.playAndRecord` (typically `mode: .default` or `.measurement`, options `[.defaultToSpeaker, .allowBluetooth]` depending on routing needs). `.playback` is output-only and will return zero-filled input buffers regardless of the engine's `numInputChannels`.
The first `start()` call after these are in place triggers the system permission prompt. Until the user grants, input frames remain zero — a scope tap on input buses will draw a flat line.