1.0.0 release
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
// CLICommand.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// Top-level commands parsed from `CommandLine.arguments`.
|
||||
public enum CLICommand: Equatable {
|
||||
/// Build the current package, then launch `swift repl` with Lyrebird available.
|
||||
case repl
|
||||
/// Enter the LineNoise-powered `lyrebird>` interactive shell (no subcommand given).
|
||||
case interactive
|
||||
/// Print usage help.
|
||||
case help
|
||||
/// Print the lyrebird version string.
|
||||
case version
|
||||
/// Scaffold a new Lyrebird project in a directory named `name` using `template`.
|
||||
/// When `lyrebirdPath` is set, the generated `Package.swift` and (where
|
||||
/// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at
|
||||
/// that absolute path instead of pulling from the published Git URL.
|
||||
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
|
||||
/// Run the current project with `swift run`.
|
||||
case run(release: Bool)
|
||||
/// Export a named Synthesizer template to a Swift source file.
|
||||
/// When `overwrite` is `true`, an existing file at the destination is replaced.
|
||||
case export(name: String, to: String?, overwrite: Bool)
|
||||
/// Install Lyrebird Xcode file templates to the user template directory.
|
||||
/// When `force` is `true`, replaces any existing installation.
|
||||
case installTemplates(force: Bool)
|
||||
/// Remove Lyrebird Xcode file templates from the user template directory.
|
||||
case uninstallTemplates
|
||||
|
||||
/// Parse the command from a raw arguments array (typically `CommandLine.arguments`).
|
||||
///
|
||||
/// - Parameter arguments: The full argument vector. `arguments[0]` is the binary name;
|
||||
/// `arguments[1]` (if present) is the subcommand.
|
||||
/// - Returns: The matching command, or `.help` for unrecognised or malformed subcommands.
|
||||
public static func parse(_ arguments: [String]) -> CLICommand {
|
||||
guard arguments.count > 1 else { return .interactive }
|
||||
switch arguments[1].lowercased() {
|
||||
case "repl":
|
||||
return .repl
|
||||
|
||||
case "version", "--version":
|
||||
return .version
|
||||
|
||||
case "help", "--help", "-h":
|
||||
return .help
|
||||
|
||||
case "new":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !arguments[2].hasPrefix("-") else { return .help }
|
||||
let template: ProjectTemplate
|
||||
if let tIdx: Array<String>.Index = arguments.firstIndex(of: "--template"),
|
||||
tIdx + 1 < arguments.count,
|
||||
let t: ProjectTemplate = ProjectTemplate(string: arguments[tIdx + 1]) {
|
||||
template = t
|
||||
} else {
|
||||
template = .basic
|
||||
}
|
||||
// Optional `--lyrebird-path <abs-path>` for local-checkout use.
|
||||
// Value must not be a flag token.
|
||||
let lyrebirdPath: String?
|
||||
if let pIdx: Array<String>.Index = arguments.firstIndex(of: "--lyrebird-path"),
|
||||
pIdx + 1 < arguments.count,
|
||||
!arguments[pIdx + 1].hasPrefix("-") {
|
||||
lyrebirdPath = arguments[pIdx + 1]
|
||||
} else {
|
||||
lyrebirdPath = nil
|
||||
}
|
||||
return .new(name: arguments[2],
|
||||
template: template,
|
||||
lyrebirdPath: lyrebirdPath)
|
||||
|
||||
case "run":
|
||||
let release: Bool = arguments.contains("--release")
|
||||
return .run(release: release)
|
||||
|
||||
case "install-templates":
|
||||
let force: Bool = arguments.contains("--force")
|
||||
return .installTemplates(force: force)
|
||||
|
||||
case "uninstall-templates":
|
||||
return .uninstallTemplates
|
||||
|
||||
case "export":
|
||||
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
|
||||
let synthName: String = arguments[2]
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !synthName.hasPrefix("-") else { return .help }
|
||||
// Look for `--to <path>` anywhere after the subcommand.
|
||||
// Guard that the value following `--to` is not itself a flag token.
|
||||
let toPath: String?
|
||||
if let toIdx: Array<String>.Index = arguments.firstIndex(of: "--to"),
|
||||
toIdx + 1 < arguments.count,
|
||||
!arguments[toIdx + 1].hasPrefix("-") {
|
||||
toPath = arguments[toIdx + 1]
|
||||
} else {
|
||||
toPath = nil
|
||||
}
|
||||
let overwrite: Bool = arguments.contains("--overwrite")
|
||||
return .export(name: synthName, to: toPath, overwrite: overwrite)
|
||||
|
||||
default:
|
||||
return .help
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,299 @@
|
||||
// InteractiveShell.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
import LineNoise
|
||||
|
||||
/// Commands recognised by the `lyrebird>` interactive shell.
|
||||
public enum ShellCommand: Equatable {
|
||||
/// Build the current package, then launch `swift repl` with Lyrebird available.
|
||||
case repl
|
||||
/// Scaffold a new Lyrebird project with the given name and template.
|
||||
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
|
||||
/// Build and run the current project, optionally in release mode.
|
||||
case run(release: Bool)
|
||||
/// Export a Synthesizer template to a `.swift` file.
|
||||
/// When `overwrite` is `true`, an existing file at the destination is replaced.
|
||||
case export(name: String, to: String?, overwrite: Bool)
|
||||
/// Install Xcode file templates to the user template directory.
|
||||
case installTemplates(force: Bool)
|
||||
/// Remove Xcode file templates from the user template directory.
|
||||
case uninstallTemplates
|
||||
/// Print the help text.
|
||||
case help
|
||||
/// Print the lyrebird version.
|
||||
case version
|
||||
/// Exit the interactive shell.
|
||||
case quit
|
||||
/// Empty input — no-op.
|
||||
case none
|
||||
/// Unrecognised input.
|
||||
case unknown(String)
|
||||
}
|
||||
|
||||
/// The LineNoise-powered `lyrebird>` interactive command shell.
|
||||
///
|
||||
/// Launched when `lyrebird` is run with no subcommand. Provides:
|
||||
/// - Arrow-key line editing (via LineNoise / linenoise C library)
|
||||
/// - Persistent command history saved to `~/.lyrebird_history`
|
||||
/// - Tab completion for all recognised subcommands
|
||||
///
|
||||
/// Typing `repl` builds the current package and hands off to `swift repl` (with
|
||||
/// Lyrebird linked in via `-I`/`-L`/`-l` flags) for a full Swift REPL session.
|
||||
/// Ctrl+D or `quit` exits.
|
||||
public enum InteractiveShell {
|
||||
|
||||
/// The list of top-level subcommand names used for tab completion.
|
||||
private static let subcommands: [String] = [
|
||||
"new", "run", "export", "install-templates", "uninstall-templates",
|
||||
"repl", "help", "version", "quit"
|
||||
]
|
||||
|
||||
/// Maximum number of entries retained in the LineNoise history ring buffer.
|
||||
private static let historyMaxLength: UInt = 500
|
||||
|
||||
/// Path to the history file shared with `REPLLauncher`.
|
||||
public static var historyFilePath: String { REPLLauncher.historyFilePath }
|
||||
|
||||
/// Returns completions for the given line prefix (used by LineNoise tab completion).
|
||||
public static func completions(for prefix: String) -> [String] {
|
||||
subcommands.filter { $0.hasPrefix(prefix) }
|
||||
}
|
||||
|
||||
/// Parses a raw input string (from `LineNoise.getLine`) into a `ShellCommand`.
|
||||
public static func command(from input: String) -> ShellCommand {
|
||||
let trimmed: String = input.trimmingCharacters(in: .whitespaces)
|
||||
let tokens: [String] = trimmed.split(separator: " ", omittingEmptySubsequences: true)
|
||||
.map(String.init)
|
||||
|
||||
// Lowercase only the verb so commands are case-insensitive, but argument values
|
||||
// (e.g. class names like "MySynth") preserve the user's original casing.
|
||||
switch tokens.first?.lowercased() ?? "" {
|
||||
case "":
|
||||
return .none
|
||||
case "repl":
|
||||
return .repl
|
||||
case "help":
|
||||
return .help
|
||||
case "version":
|
||||
return .version
|
||||
case "quit", "exit", ":quit":
|
||||
return .quit
|
||||
|
||||
case "new":
|
||||
guard tokens.count >= 2 else {
|
||||
return .unknown("new: missing <name>")
|
||||
}
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !tokens[1].hasPrefix("-") else {
|
||||
return .unknown("new: missing <name>")
|
||||
}
|
||||
let template: ProjectTemplate
|
||||
if let tIdx: Array<String>.Index = tokens.firstIndex(of: "--template"),
|
||||
tIdx + 1 < tokens.count,
|
||||
let t: ProjectTemplate = ProjectTemplate(string: tokens[tIdx + 1]) {
|
||||
template = t
|
||||
} else {
|
||||
template = .basic
|
||||
}
|
||||
let lyrebirdPath: String?
|
||||
if let pIdx: Array<String>.Index = tokens.firstIndex(of: "--lyrebird-path"),
|
||||
pIdx + 1 < tokens.count,
|
||||
!tokens[pIdx + 1].hasPrefix("-") {
|
||||
lyrebirdPath = tokens[pIdx + 1]
|
||||
} else {
|
||||
lyrebirdPath = nil
|
||||
}
|
||||
return .new(name: tokens[1],
|
||||
template: template,
|
||||
lyrebirdPath: lyrebirdPath)
|
||||
|
||||
case "run":
|
||||
let release: Bool = tokens.contains("--release")
|
||||
return .run(release: release)
|
||||
|
||||
case "install-templates":
|
||||
let force: Bool = tokens.contains("--force")
|
||||
return .installTemplates(force: force)
|
||||
|
||||
case "uninstall-templates":
|
||||
return .uninstallTemplates
|
||||
|
||||
case "export":
|
||||
guard tokens.count >= 2 else {
|
||||
return .unknown("export: missing <name>")
|
||||
}
|
||||
let synthName: String = tokens[1]
|
||||
// If the positional argument looks like a flag, the user omitted the name.
|
||||
guard !synthName.hasPrefix("-") else {
|
||||
return .unknown("export: missing <name>")
|
||||
}
|
||||
// Guard that the value following `--to` is not itself a flag token.
|
||||
let toPath: String?
|
||||
if let toIdx: Array<String>.Index = tokens.firstIndex(of: "--to"),
|
||||
toIdx + 1 < tokens.count,
|
||||
!tokens[toIdx + 1].hasPrefix("-") {
|
||||
toPath = tokens[toIdx + 1]
|
||||
} else {
|
||||
toPath = nil
|
||||
}
|
||||
let overwrite: Bool = tokens.contains("--overwrite")
|
||||
return .export(name: synthName, to: toPath, overwrite: overwrite)
|
||||
|
||||
default:
|
||||
return .unknown(trimmed)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the interactive shell loop until the user quits or hits Ctrl+D.
|
||||
///
|
||||
/// Uses LineNoise for line editing, history, and tab completion.
|
||||
/// On `repl`, hands off to `REPLLauncher.launch()` and resumes the shell on return.
|
||||
public static func run() {
|
||||
let ln: LineNoise = LineNoise()
|
||||
ln.setHistoryMaxLength(historyMaxLength)
|
||||
try? ln.loadHistory(fromFile: historyFilePath)
|
||||
|
||||
ln.setCompletionCallback { currentLine in
|
||||
completions(for: currentLine)
|
||||
}
|
||||
|
||||
printHelp()
|
||||
|
||||
// Labeled loop so `.quit` can break directly without a redundant re-parse.
|
||||
shellLoop: while true {
|
||||
let input: String
|
||||
do {
|
||||
input = try ln.getLine(prompt: "lyrebird> ")
|
||||
} catch LinenoiseError.CTRL_C, LinenoiseError.EOF {
|
||||
// Ctrl+C or Ctrl+D — clean exit.
|
||||
break shellLoop
|
||||
} catch {
|
||||
fputs("lyrebird: input error: \(error)\n", stderr)
|
||||
break shellLoop
|
||||
}
|
||||
|
||||
ln.addHistory(input)
|
||||
|
||||
switch command(from: input) {
|
||||
case .repl:
|
||||
do {
|
||||
try REPLLauncher.launch()
|
||||
} catch CLIError.swiftNotFound {
|
||||
fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr)
|
||||
} catch CLIError.buildFailed(let code) {
|
||||
fputs("error: swift build failed (exit code \(code)). REPL not started.\n", stderr)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
}
|
||||
|
||||
case .new(let name, let template, let lyrebirdPath):
|
||||
let resolvedPath: String? = lyrebirdPath.map {
|
||||
URL(fileURLWithPath: $0).standardizedFileURL.path
|
||||
}
|
||||
do {
|
||||
try ProjectScaffolder.scaffold(
|
||||
name: name,
|
||||
template: template,
|
||||
lyrebirdPath: resolvedPath
|
||||
)
|
||||
print("Created \(name)/")
|
||||
} catch ProjectScaffolder.Error.projectExists(let n) {
|
||||
print("error: directory '\(n)' already exists.")
|
||||
} catch ProjectScaffolder.Error.invalidName(let n) {
|
||||
print("error: '\(n)' is not a valid Swift module name.")
|
||||
} catch ProjectScaffolder.Error.fileSystemError(let path, let reason) {
|
||||
print("error: could not create '\(path)': \(reason)")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
|
||||
case .run(let release):
|
||||
do {
|
||||
try ProjectRunner.run(release: release)
|
||||
} catch ProjectRunner.Error.swiftNotFound {
|
||||
fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr)
|
||||
} catch ProjectRunner.Error.buildFailed(let code) {
|
||||
print("Build failed (exit code \(code)).")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
|
||||
case .export(let name, let toPath, let overwrite):
|
||||
do {
|
||||
try SynthExporter.export(name: name, to: toPath, overwrite: overwrite)
|
||||
let dest: String = toPath ?? SynthExporter.defaultOutputPath(for: name)
|
||||
print("Exported \(dest)")
|
||||
} catch SynthExporter.Error.invalidName(let n) {
|
||||
print("error: '\(n)' is not a valid Swift identifier.")
|
||||
} catch SynthExporter.Error.fileExists(let p) {
|
||||
print("error: '\(p)' already exists. Pass --overwrite to replace it.")
|
||||
} catch SynthExporter.Error.fileSystemError(let p, let reason) {
|
||||
print("error: could not write '\(p)': \(reason)")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
|
||||
case .installTemplates(let force):
|
||||
do {
|
||||
let count: Int = try TemplateInstaller.install(force: force)
|
||||
print("Installed \(count) Lyrebird Xcode templates → \(TemplateInstaller.destinationURL.path)")
|
||||
} catch TemplateInstaller.Error.destinationExists(let path) {
|
||||
print("error: '\(path)' already exists. Pass --force to replace it.")
|
||||
} catch TemplateInstaller.Error.bundleMissingTemplates(let path) {
|
||||
print("error: bundled templates not found at \(path).")
|
||||
} catch TemplateInstaller.Error.fileSystemError(let p, let reason) {
|
||||
print("error: could not write '\(p)': \(reason)")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
|
||||
case .uninstallTemplates:
|
||||
do {
|
||||
let removed: Bool = try TemplateInstaller.uninstall()
|
||||
if removed {
|
||||
print("Removed Lyrebird templates from \(TemplateInstaller.destinationURL.path)")
|
||||
} else {
|
||||
print("Nothing to remove. Templates not installed at \(TemplateInstaller.destinationURL.path)")
|
||||
}
|
||||
} catch TemplateInstaller.Error.fileSystemError(let p, let reason) {
|
||||
print("error: could not remove '\(p)': \(reason)")
|
||||
} catch {
|
||||
print("error: \(error)")
|
||||
}
|
||||
|
||||
case .help:
|
||||
printHelp()
|
||||
case .version:
|
||||
print("lyrebird \(lyrebirdVersion)")
|
||||
case .quit:
|
||||
break shellLoop
|
||||
case .none:
|
||||
continue shellLoop
|
||||
case .unknown(let cmd):
|
||||
print("unknown command '\(cmd)'. Type 'help' for options.")
|
||||
}
|
||||
}
|
||||
|
||||
try? ln.saveHistory(toFile: historyFilePath)
|
||||
}
|
||||
|
||||
private static func printHelp() {
|
||||
print("""
|
||||
Commands:
|
||||
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
|
||||
Templates: basic (default), demo, ui-demo, nrt
|
||||
run [--release] Build and run the current project
|
||||
export <name> [--to p] Export a Synthesizer template to a .swift file
|
||||
install-templates [--force] Install Xcode file templates to user dir
|
||||
uninstall-templates Remove installed Xcode file templates
|
||||
repl Launch Swift REPL with Lyrebird available
|
||||
version Print lyrebird version
|
||||
help Show this help
|
||||
quit Exit (also Ctrl+D)
|
||||
""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,198 @@
|
||||
// LyrebirdCLI.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Entry point for the `lyrebird` command-line tool.
|
||||
///
|
||||
/// Uses `@main` (not `main.swift`) so the module can be `@testable import`ed by
|
||||
/// `LyrebirdCLITests` without triggering top-level code execution.
|
||||
@main
|
||||
struct LyrebirdCLIMain {
|
||||
static func main() {
|
||||
let command: CLICommand = CLICommand.parse(CommandLine.arguments)
|
||||
switch command {
|
||||
case .repl:
|
||||
runREPL()
|
||||
case .interactive:
|
||||
print(welcomeBanner)
|
||||
print()
|
||||
InteractiveShell.run()
|
||||
case .version:
|
||||
print("lyrebird \(lyrebirdVersion)")
|
||||
case .help:
|
||||
printHelp()
|
||||
case .new(let name, let template, let lyrebirdPath):
|
||||
runNew(name: name, template: template, lyrebirdPath: lyrebirdPath)
|
||||
case .run(let release):
|
||||
runProject(release: release)
|
||||
case .export(let name, let toPath, let overwrite):
|
||||
runExport(name: name, to: toPath, overwrite: overwrite)
|
||||
case .installTemplates(let force):
|
||||
runInstallTemplates(force: force)
|
||||
case .uninstallTemplates:
|
||||
runUninstallTemplates()
|
||||
}
|
||||
}
|
||||
|
||||
private static func runInstallTemplates(force: Bool) {
|
||||
do {
|
||||
let count: Int = try TemplateInstaller.install(force: force)
|
||||
print("Installed \(count) Lyrebird Xcode templates →")
|
||||
print(" \(TemplateInstaller.destinationURL.path)")
|
||||
print("")
|
||||
print("Open Xcode → File → New → File from Template…")
|
||||
print("→ scroll to the 'Lyrebird' section.")
|
||||
} catch TemplateInstaller.Error.destinationExists(let path) {
|
||||
fputs("error: '\(path)' already exists. Pass --force to replace it.\n", stderr)
|
||||
exit(1)
|
||||
} catch TemplateInstaller.Error.bundleMissingTemplates(let path) {
|
||||
fputs("error: bundled templates not found at \(path).\n", stderr)
|
||||
fputs(" This usually means the lyrebird binary was built without\n", stderr)
|
||||
fputs(" its resource bundle. Rebuild with `swift build`.\n", stderr)
|
||||
exit(1)
|
||||
} catch TemplateInstaller.Error.fileSystemError(let path, let reason) {
|
||||
fputs("error: could not write '\(path)': \(reason)\n", stderr)
|
||||
exit(1)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func runUninstallTemplates() {
|
||||
do {
|
||||
let removed: Bool = try TemplateInstaller.uninstall()
|
||||
if removed {
|
||||
print("Removed Lyrebird templates from")
|
||||
print(" \(TemplateInstaller.destinationURL.path)")
|
||||
} else {
|
||||
print("Nothing to remove. Templates not installed at")
|
||||
print(" \(TemplateInstaller.destinationURL.path)")
|
||||
}
|
||||
} catch TemplateInstaller.Error.fileSystemError(let path, let reason) {
|
||||
fputs("error: could not remove '\(path)': \(reason)\n", stderr)
|
||||
exit(1)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func runREPL() {
|
||||
print("""
|
||||
Lyrebird \(lyrebirdVersion) — building package, then starting Swift REPL
|
||||
Run `import LyrebirdSynth` to access the framework.
|
||||
Type :help for Swift REPL help. Ctrl+D to exit.
|
||||
|
||||
""")
|
||||
do {
|
||||
try REPLLauncher.launch()
|
||||
} catch CLIError.swiftNotFound {
|
||||
fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr)
|
||||
exit(1)
|
||||
} catch CLIError.buildFailed(let code) {
|
||||
fputs("error: swift build failed (exit code \(code)). REPL not started.\n", stderr)
|
||||
exit(code)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func runNew(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
lyrebirdPath: String?
|
||||
) {
|
||||
let resolvedPath: String?
|
||||
if let p: String = lyrebirdPath {
|
||||
// Resolve to absolute. `URL(fileURLWithPath:)` keeps absolute as-is
|
||||
// and roots relative paths at the current working directory.
|
||||
resolvedPath = URL(fileURLWithPath: p).standardizedFileURL.path
|
||||
} else {
|
||||
resolvedPath = nil
|
||||
}
|
||||
do {
|
||||
try ProjectScaffolder.scaffold(
|
||||
name: name,
|
||||
template: template,
|
||||
lyrebirdPath: resolvedPath
|
||||
)
|
||||
print("Created \(name)/")
|
||||
} catch ProjectScaffolder.Error.projectExists(let n) {
|
||||
fputs("error: directory '\(n)' already exists.\n", stderr)
|
||||
exit(1)
|
||||
} catch ProjectScaffolder.Error.invalidName(let n) {
|
||||
fputs("error: '\(n)' is not a valid Swift module name.\n", stderr)
|
||||
exit(1)
|
||||
} catch ProjectScaffolder.Error.fileSystemError(let path, let reason) {
|
||||
fputs("error: could not create '\(path)': \(reason)\n", stderr)
|
||||
exit(1)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func runProject(release: Bool) {
|
||||
do {
|
||||
try ProjectRunner.run(release: release)
|
||||
} catch ProjectRunner.Error.swiftNotFound {
|
||||
fputs("error: swift not found. Install Xcode or a Swift toolchain.\n", stderr)
|
||||
exit(1)
|
||||
} catch ProjectRunner.Error.buildFailed(let code) {
|
||||
exit(code)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func runExport(
|
||||
name: String,
|
||||
to path: String?,
|
||||
overwrite: Bool
|
||||
) {
|
||||
do {
|
||||
try SynthExporter.export(name: name, to: path, overwrite: overwrite)
|
||||
let dest: String = path ?? SynthExporter.defaultOutputPath(for: name)
|
||||
print("Exported \(dest)")
|
||||
} catch SynthExporter.Error.invalidName(let n) {
|
||||
fputs("error: '\(n)' is not a valid Swift identifier.\n", stderr)
|
||||
exit(1)
|
||||
} catch SynthExporter.Error.fileExists(let p) {
|
||||
fputs("error: '\(p)' already exists. Pass --overwrite to replace it.\n", stderr)
|
||||
exit(1)
|
||||
} catch SynthExporter.Error.fileSystemError(let p, let reason) {
|
||||
fputs("error: could not write '\(p)': \(reason)\n", stderr)
|
||||
exit(1)
|
||||
} catch {
|
||||
fputs("error: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
private static func printHelp() {
|
||||
print("""
|
||||
Usage: lyrebird [command]
|
||||
|
||||
Commands:
|
||||
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
|
||||
Templates: basic (default), demo, ui-demo, nrt
|
||||
run [--release] Build and run the current project
|
||||
export <name> [--to p] Export a Synthesizer template to a .swift file
|
||||
install-templates [--force] Install Xcode file templates (Generator,
|
||||
Synthesizer, Task, …) to the user template dir
|
||||
uninstall-templates Remove the installed Xcode file templates
|
||||
repl Launch Swift REPL with Lyrebird available
|
||||
version Print lyrebird version
|
||||
help Show this help
|
||||
|
||||
Run `lyrebird` with no arguments for an interactive shell.
|
||||
""")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// NameValidation.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Swift identifier validation
|
||||
|
||||
/// Validates that `name` is a non-empty, valid Swift module/type identifier.
|
||||
///
|
||||
/// A valid identifier:
|
||||
/// - Is non-empty
|
||||
/// - Contains only letters, digits, and underscores
|
||||
/// - Does not start with a digit
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The string to validate.
|
||||
/// - invalidNameError: The error to throw when validation fails. Callers
|
||||
/// supply their own typed error so error messages carry the correct domain.
|
||||
/// - Throws: `invalidNameError` if any rule is violated.
|
||||
func validateSwiftIdentifier(_ name: String, invalidNameError: some Error) throws {
|
||||
guard !name.isEmpty else {
|
||||
throw invalidNameError
|
||||
}
|
||||
// Restrict to ASCII [A-Za-z0-9_] — SPM module names and filesystem directory names
|
||||
// must be ASCII-safe. Using CharacterSet.alphanumerics would incorrectly accept
|
||||
// Cyrillic, CJK, Arabic, etc., which break `swift package resolve` and toolchain paths.
|
||||
let asciiAlphanumerics: CharacterSet = CharacterSet(
|
||||
charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
|
||||
)
|
||||
let validChars: CharacterSet = asciiAlphanumerics.union(CharacterSet(charactersIn: "_"))
|
||||
let hasInvalidChars: Bool = name.unicodeScalars.contains { !validChars.contains($0) }
|
||||
let startsWithDigit: Bool = name.first.map({ $0 >= "0" && $0 <= "9" }) ?? false
|
||||
guard !hasInvalidChars && !startsWithDigit else {
|
||||
throw invalidNameError
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
// ProjectRunner.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectRunner
|
||||
|
||||
/// Wraps `swift run` to build and launch the current Lyrebird project.
|
||||
///
|
||||
/// `lyrebird run` and `lyrebird run --release` are thin wrappers: they locate the
|
||||
/// `swift` binary and exec `swift run` (optionally with `-c release`) in the current
|
||||
/// working directory. stdin / stdout / stderr are inherited so compiler output and
|
||||
/// runtime output appear directly in the user's terminal.
|
||||
///
|
||||
/// The runner does **not** verify that a `Package.swift` is present before launching —
|
||||
/// SPM provides a clear error message in that case.
|
||||
public enum ProjectRunner {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectRunner`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// The process exited with a non-zero status.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Build and run the Swift package in `directory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, passes `-c release` to `swift run` for an optimised build.
|
||||
/// - directory: The directory containing `Package.swift`.
|
||||
/// Defaults to the current working directory.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent;
|
||||
/// `ProjectRunner.Error.buildFailed` if `swift run` exits non-zero.
|
||||
public static func run(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(release: release, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
let exitCode: Int32 = process.terminationStatus
|
||||
guard exitCode == 0 else {
|
||||
throw Error.buildFailed(exitCode: exitCode)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Internal
|
||||
|
||||
/// Builds a `Process` configured to run `swift run` (or `swift run -c release`).
|
||||
///
|
||||
/// Exposed for testing so callers can inspect the process configuration without
|
||||
/// actually launching a build.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - release: When `true`, appends `-c release` to the swift arguments.
|
||||
/// - directory: Working directory for the SPM invocation.
|
||||
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent.
|
||||
public static func makeProcess(
|
||||
release: Bool = false,
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
var arguments: [String] = ["run"]
|
||||
if release {
|
||||
arguments += ["-c", "release"]
|
||||
}
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
// stdin / stdout / stderr intentionally not set — inherited for interactive output.
|
||||
return process
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks, in order:
|
||||
/// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
|
||||
/// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default)
|
||||
/// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon
|
||||
///
|
||||
/// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist.
|
||||
static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw Error.swiftNotFound
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,757 @@
|
||||
// ProjectScaffolder+AUv3.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - auv3 template
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
/// Write the full `auv3` template tree at `projectRoot`.
|
||||
///
|
||||
/// Two targets:
|
||||
/// - Host app `<name>` (SwiftUI; instantiates the extension once so the
|
||||
/// system registers it, then offers a "Try in AUM/GarageBand/Logic" UI)
|
||||
/// - Extension `<name>Extension` (`.appex`, type `aumu`, principal class
|
||||
/// `<name>AudioUnitViewController`). Wraps `<name>Synth` (a
|
||||
/// `SynthesizerBase` subclass) via `LyrebirdAudioUnit`.
|
||||
///
|
||||
/// `AudioComponentDescription` defaults: type `aumu`, subtype derived
|
||||
/// from the first 4 letters of `name` uppercased, manufacturer `LYRB`
|
||||
/// (placeholder — the user rewrites it to their own 4-char code).
|
||||
static func writeAUv3Files(
|
||||
name: String,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name)
|
||||
let extGroupDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name)Extension")
|
||||
let xcodeprojDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcodeproj")
|
||||
let schemeDir: String = (xcodeprojDir as NSString)
|
||||
.appendingPathComponent("xcshareddata/xcschemes")
|
||||
|
||||
for dir: String in [appGroupDir, extGroupDir, xcodeprojDir, schemeDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
let files: [(String, String)] = [
|
||||
// Host app
|
||||
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
auv3HostInfoPlist(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name).entitlements"),
|
||||
auv3HostEntitlements()),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name)App.swift"),
|
||||
auv3HostAppSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("ContentView.swift"),
|
||||
auv3HostContentView(name: name)),
|
||||
// Extension
|
||||
((extGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
auv3ExtensionInfoPlist(name: name)),
|
||||
((extGroupDir as NSString)
|
||||
.appendingPathComponent("\(name)Extension.entitlements"),
|
||||
auv3ExtensionEntitlements()),
|
||||
((extGroupDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
auv3SynthSwift(name: name)),
|
||||
((extGroupDir as NSString).appendingPathComponent("\(name)AudioUnit.swift"),
|
||||
auv3AudioUnitSwift(name: name)),
|
||||
((extGroupDir as NSString)
|
||||
.appendingPathComponent("\(name)AudioUnitViewController.swift"),
|
||||
auv3AudioUnitViewControllerSwift(name: name)),
|
||||
// Project
|
||||
((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"),
|
||||
auv3PBXProj(name: name, lyrebirdPath: lyrebirdPath)),
|
||||
((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"),
|
||||
appScheme(name: name, productExtension: "app")),
|
||||
]
|
||||
try writeFiles(files, fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: - Identifiers
|
||||
|
||||
/// 4-char AudioComponentDescription subtype derived from `name`. If `name`
|
||||
/// has fewer than 4 alphanumeric characters, pads with `X`. Always
|
||||
/// uppercase ASCII.
|
||||
static func auv3Subtype(for name: String) -> String {
|
||||
let alnum: String = name.unicodeScalars
|
||||
.filter { CharacterSet.alphanumerics.contains($0) }
|
||||
.prefix(4)
|
||||
.map { String($0).uppercased() }
|
||||
.joined()
|
||||
let padded: String = alnum + String(repeating: "X", count: max(0, 4 - alnum.count))
|
||||
return String(padded.prefix(4))
|
||||
}
|
||||
|
||||
/// Placeholder 4-char manufacturer code shipped in scaffolded projects.
|
||||
/// Users must rewrite this to their own registered manufacturer code
|
||||
/// before distributing the plugin.
|
||||
static let auv3DefaultManufacturer: String = "LYRB"
|
||||
|
||||
// MARK: - Source files
|
||||
|
||||
static func auv3HostInfoPlist(name: String) -> String {
|
||||
appInfoPlist(name: name, platform: .macOS)
|
||||
}
|
||||
|
||||
static func auv3HostEntitlements() -> 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.app-sandbox</key>
|
||||
<true/>
|
||||
<key>com.apple.security.files.user-selected.read-only</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3ExtensionEntitlements() -> 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.app-sandbox</key>
|
||||
<true/>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3HostAppSwift(name: String) -> String {
|
||||
"""
|
||||
// \(name) — AUv3 host app
|
||||
//
|
||||
// Launching this app once tells the system to register the bundled
|
||||
// `.appex` extension. After first launch the plugin appears in
|
||||
// Logic / GarageBand / AUM / Loopy Pro / any AUv3-capable host.
|
||||
import SwiftUI
|
||||
|
||||
@main
|
||||
struct \(name)App: App {
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
ContentView()
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3HostContentView(name: String) -> String {
|
||||
"""
|
||||
import SwiftUI
|
||||
|
||||
struct ContentView: View {
|
||||
var body: some View {
|
||||
VStack(spacing: 16) {
|
||||
Text("\(name)")
|
||||
.font(.largeTitle)
|
||||
Text("Bundled AUv3 plugin: \(auv3DefaultManufacturer) / \(auv3Subtype(for: name))")
|
||||
.font(.subheadline)
|
||||
.foregroundStyle(.secondary)
|
||||
Text("Run this app once to register the plugin, then load it in any AUv3 host (Logic, GarageBand, AUM, Loopy Pro).")
|
||||
.multilineTextAlignment(.center)
|
||||
.frame(maxWidth: 360)
|
||||
}
|
||||
.padding(40)
|
||||
.frame(minWidth: 480, minHeight: 320)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3SynthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
|
||||
/// Starter `SynthesizerBase` for the \(name) AUv3 plugin.
|
||||
///
|
||||
/// Sine oscillator with `@LiveParam` controls. Each `@LiveParam` is
|
||||
/// exposed as an AU parameter — see `parameterMetadata()` in
|
||||
/// ``\(name)AudioUnit``.
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.25
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq) * $amp
|
||||
output(bus: 0, source: osc)
|
||||
output(bus: 1, source: osc)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3AudioUnitSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
|
||||
/// AUv3 wrapper around ``\(name)Synth``. Subclasses
|
||||
/// ``LyrebirdAudioUnit`` and only overrides the two required hooks.
|
||||
public final class \(name)AudioUnit: LyrebirdAudioUnit {
|
||||
|
||||
public override class func makeSynthesizer() -> SynthesizerBase {
|
||||
\(name)Synth()
|
||||
}
|
||||
|
||||
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
|
||||
[
|
||||
"freq": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
|
||||
"amp": .init(min: 0, max: 1, unit: .linearGain, displayName: "Amplitude"),
|
||||
]
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3AudioUnitViewControllerSwift(name: String) -> String {
|
||||
"""
|
||||
import CoreAudioKit
|
||||
import AVFoundation
|
||||
|
||||
/// AUv3 principal class. Hosts use `AUAudioUnitFactory` conformance
|
||||
/// to instantiate ``\(name)AudioUnit`` via `createAudioUnit(with:)`.
|
||||
///
|
||||
/// Empty placeholder view — drop in ``LyrebirdUI.LyrebirdSynthView``
|
||||
/// (or your own SwiftUI) to render the parameter grid.
|
||||
public final class \(name)AudioUnitViewController: AUViewController, AUAudioUnitFactory {
|
||||
|
||||
public override func viewDidLoad() {
|
||||
super.viewDidLoad()
|
||||
}
|
||||
|
||||
nonisolated public func createAudioUnit(
|
||||
with componentDescription: AudioComponentDescription
|
||||
) throws -> AUAudioUnit {
|
||||
try \(name)AudioUnit(componentDescription: componentDescription)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func auv3ExtensionInfoPlist(name: String) -> String {
|
||||
let subtype: String = auv3Subtype(for: name)
|
||||
let manufacturer: String = auv3DefaultManufacturer
|
||||
return """
|
||||
<?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>CFBundleDevelopmentRegion</key>
|
||||
<string>$(DEVELOPMENT_LANGUAGE)</string>
|
||||
<key>CFBundleDisplayName</key>
|
||||
<string>\(name)</string>
|
||||
<key>CFBundleExecutable</key>
|
||||
<string>$(EXECUTABLE_NAME)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>$(PRODUCT_NAME)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>XPC!</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>NSExtension</key>
|
||||
<dict>
|
||||
<key>NSExtensionAttributes</key>
|
||||
<dict>
|
||||
<key>AudioComponentBundle</key>
|
||||
<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>
|
||||
<key>AudioComponents</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>name</key>
|
||||
<string>\(name): \(name)</string>
|
||||
<key>description</key>
|
||||
<string>\(name) — Lyrebird AUv3 synth</string>
|
||||
<key>type</key>
|
||||
<string>aumu</string>
|
||||
<key>subtype</key>
|
||||
<string>\(subtype)</string>
|
||||
<key>manufacturer</key>
|
||||
<string>\(manufacturer)</string>
|
||||
<key>version</key>
|
||||
<integer>\(auv3DefaultComponentVersion)</integer>
|
||||
<key>sandboxSafe</key>
|
||||
<true/>
|
||||
<key>tags</key>
|
||||
<array>
|
||||
<string>Synth</string>
|
||||
</array>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
<key>NSExtensionPointIdentifier</key>
|
||||
<string>com.apple.AudioUnit-UI</string>
|
||||
<key>NSExtensionPrincipalClass</key>
|
||||
<string>\(name)Extension.\(name)AudioUnitViewController</string>
|
||||
</dict>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - AUv3 pbxproj
|
||||
|
||||
/// `project.pbxproj` for the `auv3` template. Two targets: host app
|
||||
/// `<name>` and extension `<name>Extension`. Host embeds the extension
|
||||
/// via a `PBXCopyFilesBuildPhase` with `dstSubfolderSpec = 13` (Plug-ins).
|
||||
static func auv3PBXProj(name: String, lyrebirdPath: String? = nil) -> String {
|
||||
let hostBundleID: String = "\(defaultBundleIdentifierPrefix).\(name)"
|
||||
let extBundleID: String = "\(hostBundleID).\(name)Extension"
|
||||
let packageRefLabel: String = pbxPackageReferenceLabel(lyrebirdPath: lyrebirdPath)
|
||||
let packageRefSection: String = pbxPackageReferenceSection(lyrebirdPath: lyrebirdPath)
|
||||
return """
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
\tarchiveVersion = 1;
|
||||
\tclasses = {
|
||||
\t};
|
||||
\tobjectVersion = 60;
|
||||
\tobjects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
\t\t\(pbxIOSAppFileBuild) /* \(name)App.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxIOSAppFileRef) /* \(name)App.swift */; };
|
||||
\t\t\(pbxSynthBuild) /* ContentView.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSynthRef) /* ContentView.swift */; };
|
||||
\t\t\(pbxExtSynthBuild) /* \(name)Synth.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxExtSynthRef) /* \(name)Synth.swift */; };
|
||||
\t\t\(pbxExtAuBuild) /* \(name)AudioUnit.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxExtAuRef) /* \(name)AudioUnit.swift */; };
|
||||
\t\t\(pbxExtVCBuild) /* \(name)AudioUnitViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxExtVCRef) /* \(name)AudioUnitViewController.swift */; };
|
||||
\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxLyrebirdUIProductDep) /* LyrebirdUI */; };
|
||||
\t\t\(pbxExtAppexInAppFile) /* \(name)Extension.appex in Embed App Extensions */ = {isa = PBXBuildFile; fileRef = \(pbxExtProductRef) /* \(name)Extension.appex */; settings = {ATTRIBUTES = (RemoveHeadersOnCopy, ); }; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* Begin PBXContainerItemProxy section */
|
||||
\t\t\(pbxExtContainerProxy) /* PBXContainerItemProxy */ = {
|
||||
\t\t\tisa = PBXContainerItemProxy;
|
||||
\t\t\tcontainerPortal = \(pbxRootObject) /* Project object */;
|
||||
\t\t\tproxyType = 1;
|
||||
\t\t\tremoteGlobalIDString = \(pbxExtBlueprint);
|
||||
\t\t\tremoteInfo = \(name)Extension;
|
||||
\t\t};
|
||||
/* End PBXContainerItemProxy section */
|
||||
|
||||
/* Begin PBXCopyFilesBuildPhase section */
|
||||
\t\t\(pbxExtCopyAppexPhase) /* Embed App Extensions */ = {
|
||||
\t\t\tisa = PBXCopyFilesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tdstPath = "";
|
||||
\t\t\tdstSubfolderSpec = 13;
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxExtAppexInAppFile) /* \(name)Extension.appex in Embed App Extensions */,
|
||||
\t\t\t);
|
||||
\t\t\tname = "Embed App Extensions";
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXCopyFilesBuildPhase section */
|
||||
|
||||
/* Begin PBXFileReference section */
|
||||
\t\t\(pbxAppProductRef) /* \(name).app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = \(name).app; sourceTree = BUILT_PRODUCTS_DIR; };
|
||||
\t\t\(pbxExtProductRef) /* \(name)Extension.appex */ = {isa = PBXFileReference; explicitFileType = "wrapper.app-extension"; includeInIndex = 0; path = \(name)Extension.appex; 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\(pbxIOSAppFileRef) /* \(name)App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)App.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxSynthRef) /* ContentView.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ContentView.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxExtInfoPlistRef) /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
|
||||
\t\t\(pbxExtEntitlementsRef) /* \(name)Extension.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; path = \(name)Extension.entitlements; sourceTree = "<group>"; };
|
||||
\t\t\(pbxExtSynthRef) /* \(name)Synth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)Synth.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxExtAuRef) /* \(name)AudioUnit.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)AudioUnit.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxExtVCRef) /* \(name)AudioUnitViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)AudioUnitViewController.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
\t\t\(pbxFrameworksPhase) /* Frameworks (App) */ = {
|
||||
\t\t\tisa = PBXFrameworksBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
\t\t\(pbxExtFrameworksPhase) /* Frameworks (Extension) */ = {
|
||||
\t\t\tisa = PBXFrameworksBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
\t\t\(pbxMainGroup) /* Main */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppGroup) /* \(name) */,
|
||||
\t\t\t\t\(pbxExtGroup) /* \(name)Extension */,
|
||||
\t\t\t\t\(pbxProductsGroup) /* Products */,
|
||||
\t\t\t);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxProductsGroup) /* Products */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppProductRef) /* \(name).app */,
|
||||
\t\t\t\t\(pbxExtProductRef) /* \(name)Extension.appex */,
|
||||
\t\t\t);
|
||||
\t\t\tname = Products;
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxAppGroup) /* \(name) */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxIOSAppFileRef) /* \(name)App.swift */,
|
||||
\t\t\t\t\(pbxSynthRef) /* ContentView.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>";
|
||||
\t\t};
|
||||
\t\t\(pbxExtGroup) /* \(name)Extension */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxExtSynthRef) /* \(name)Synth.swift */,
|
||||
\t\t\t\t\(pbxExtAuRef) /* \(name)AudioUnit.swift */,
|
||||
\t\t\t\t\(pbxExtVCRef) /* \(name)AudioUnitViewController.swift */,
|
||||
\t\t\t\t\(pbxExtInfoPlistRef) /* Info.plist */,
|
||||
\t\t\t\t\(pbxExtEntitlementsRef) /* \(name)Extension.entitlements */,
|
||||
\t\t\t);
|
||||
\t\t\tpath = \(name)Extension;
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
\t\t\(pbxBlueprintIDApp) /* \(name) */ = {
|
||||
\t\t\tisa = PBXNativeTarget;
|
||||
\t\t\tbuildConfigurationList = \(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */;
|
||||
\t\t\tbuildPhases = (
|
||||
\t\t\t\t\(pbxSourcesPhase) /* Sources */,
|
||||
\t\t\t\t\(pbxFrameworksPhase) /* Frameworks */,
|
||||
\t\t\t\t\(pbxResourcesPhase) /* Resources */,
|
||||
\t\t\t\t\(pbxExtCopyAppexPhase) /* Embed App Extensions */,
|
||||
\t\t\t);
|
||||
\t\t\tbuildRules = (
|
||||
\t\t\t);
|
||||
\t\t\tdependencies = (
|
||||
\t\t\t\t\(pbxExtTargetDep) /* PBXTargetDependency */,
|
||||
\t\t\t);
|
||||
\t\t\tname = \(name);
|
||||
\t\t\tproductName = \(name);
|
||||
\t\t\tproductReference = \(pbxAppProductRef) /* \(name).app */;
|
||||
\t\t\tproductType = "com.apple.product-type.application";
|
||||
\t\t};
|
||||
\t\t\(pbxExtBlueprint) /* \(name)Extension */ = {
|
||||
\t\t\tisa = PBXNativeTarget;
|
||||
\t\t\tbuildConfigurationList = \(pbxExtBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)Extension" */;
|
||||
\t\t\tbuildPhases = (
|
||||
\t\t\t\t\(pbxExtSourcesPhase) /* Sources */,
|
||||
\t\t\t\t\(pbxExtFrameworksPhase) /* Frameworks */,
|
||||
\t\t\t\t\(pbxExtResourcesPhase) /* Resources */,
|
||||
\t\t\t);
|
||||
\t\t\tbuildRules = (
|
||||
\t\t\t);
|
||||
\t\t\tdependencies = (
|
||||
\t\t\t);
|
||||
\t\t\tname = \(name)Extension;
|
||||
\t\t\tpackageProductDependencies = (
|
||||
\t\t\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */,
|
||||
\t\t\t);
|
||||
\t\t\tproductName = \(name)Extension;
|
||||
\t\t\tproductReference = \(pbxExtProductRef) /* \(name)Extension.appex */;
|
||||
\t\t\tproductType = "com.apple.product-type.app-extension";
|
||||
\t\t};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
\t\t\(pbxRootObject) /* Project object */ = {
|
||||
\t\t\tisa = PBXProject;
|
||||
\t\t\tattributes = {
|
||||
\t\t\t\tBuildIndependentTargetsInParallel = 1;
|
||||
\t\t\t\tLastSwiftUpdateCheck = 1600;
|
||||
\t\t\t\tLastUpgradeCheck = 1600;
|
||||
\t\t\t\tTargetAttributes = {
|
||||
\t\t\t\t\t\(pbxBlueprintIDApp) = {
|
||||
\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;
|
||||
\t\t\t\t\t};
|
||||
\t\t\t\t\t\(pbxExtBlueprint) = {
|
||||
\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;
|
||||
\t\t\t\t\t};
|
||||
\t\t\t\t};
|
||||
\t\t\t};
|
||||
\t\t\tbuildConfigurationList = \(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */;
|
||||
\t\t\tcompatibilityVersion = "Xcode 14.0";
|
||||
\t\t\tdevelopmentRegion = en;
|
||||
\t\t\thasScannedForEncodings = 0;
|
||||
\t\t\tknownRegions = (
|
||||
\t\t\t\ten,
|
||||
\t\t\t\tBase,
|
||||
\t\t\t);
|
||||
\t\t\tmainGroup = \(pbxMainGroup);
|
||||
\t\t\tpackageReferences = (
|
||||
\t\t\t\t\(pbxRemoteSPMRef) /* \(packageRefLabel) */,
|
||||
\t\t\t);
|
||||
\t\t\tproductRefGroup = \(pbxProductsGroup) /* Products */;
|
||||
\t\t\tprojectDirPath = "";
|
||||
\t\t\tprojectRoot = "";
|
||||
\t\t\ttargets = (
|
||||
\t\t\t\t\(pbxBlueprintIDApp) /* \(name) */,
|
||||
\t\t\t\t\(pbxExtBlueprint) /* \(name)Extension */,
|
||||
\t\t\t);
|
||||
\t\t};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
\t\t\(pbxResourcesPhase) /* Resources (App) */ = {
|
||||
\t\t\tisa = PBXResourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
\t\t\(pbxExtResourcesPhase) /* Resources (Extension) */ = {
|
||||
\t\t\tisa = PBXResourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
\t\t\(pbxSourcesPhase) /* Sources (App) */ = {
|
||||
\t\t\tisa = PBXSourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxIOSAppFileBuild) /* \(name)App.swift in Sources */,
|
||||
\t\t\t\t\(pbxSynthBuild) /* ContentView.swift in Sources */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
\t\t\(pbxExtSourcesPhase) /* Sources (Extension) */ = {
|
||||
\t\t\tisa = PBXSourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxExtSynthBuild) /* \(name)Synth.swift in Sources */,
|
||||
\t\t\t\t\(pbxExtAuBuild) /* \(name)AudioUnit.swift in Sources */,
|
||||
\t\t\t\t\(pbxExtVCBuild) /* \(name)AudioUnitViewController.swift in Sources */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXTargetDependency section */
|
||||
\t\t\(pbxExtTargetDep) /* PBXTargetDependency */ = {
|
||||
\t\t\tisa = PBXTargetDependency;
|
||||
\t\t\ttarget = \(pbxExtBlueprint) /* \(name)Extension */;
|
||||
\t\t\ttargetProxy = \(pbxExtContainerProxy) /* PBXContainerItemProxy */;
|
||||
\t\t};
|
||||
/* End PBXTargetDependency section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
\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\tCURRENT_PROJECT_VERSION = 1;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEVELOPMENT_TEAM = "";
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tMARKETING_VERSION = 1.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(hostBundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\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\tCURRENT_PROJECT_VERSION = 1;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEVELOPMENT_TEAM = "";
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tMARKETING_VERSION = 1.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(hostBundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxExtDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)Extension/\(name)Extension.entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCURRENT_PROJECT_VERSION = 1;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEVELOPMENT_TEAM = "";
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)Extension/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t\t"@executable_path/../../../../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tMARKETING_VERSION = 1.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(extBundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSKIP_INSTALL = YES;
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxExtReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_ENTITLEMENTS = \(name)Extension/\(name)Extension.entitlements;
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCURRENT_PROJECT_VERSION = 1;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEVELOPMENT_TEAM = "";
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)Extension/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t\t"@executable_path/../../../../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tMARKETING_VERSION = 1.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(extBundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSKIP_INSTALL = YES;
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_TESTABILITY = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;
|
||||
\t\t\t\tONLY_ACTIVE_ARCH = YES;
|
||||
\t\t\t\tSDKROOT = macosx;
|
||||
\t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
\t\t\t\tENABLE_NS_ASSERTIONS = NO;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tSDKROOT = macosx;
|
||||
\t\t\t\tSWIFT_COMPILATION_MODE = wholemodule;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
\t\t\(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxAppDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxAppReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxExtBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)Extension" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxExtDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxExtReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxProjectDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxProjectReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
\(packageRefSection)
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */ = {
|
||||
\t\t\tisa = XCSwiftPackageProductDependency;
|
||||
\t\t\tpackage = \(pbxRemoteSPMRef) /* \(packageRefLabel) */;
|
||||
\t\t\tproductName = LyrebirdUI;
|
||||
\t\t};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
\t};
|
||||
\trootObject = \(pbxRootObject) /* Project object */;
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
// ProjectScaffolder+IOSUI.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ios-ui template
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
/// Write the full `ios-ui` template tree at `projectRoot`.
|
||||
///
|
||||
/// Single iOS application target. SwiftUI entry point (`@main`) wired
|
||||
/// to `iOSAudioDriver` via `AVAudioSession`. Lyrebird + LyrebirdUI
|
||||
/// pulled in via a remote SPM dependency.
|
||||
static func writeIOSUIFiles(
|
||||
name: String,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name)
|
||||
let xcodeprojDir: String = (projectRoot as NSString).appendingPathComponent("\(name).xcodeproj")
|
||||
let schemeDir: String = (xcodeprojDir as NSString)
|
||||
.appendingPathComponent("xcshareddata/xcschemes")
|
||||
|
||||
for dir: String in [appGroupDir, xcodeprojDir, schemeDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
let files: [(String, String)] = [
|
||||
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
iOSAppInfoPlist(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name)App.swift"),
|
||||
iOSAppSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
iOSAppSynthSwift(name: name)),
|
||||
((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"),
|
||||
iOSAppPBXProj(name: name, lyrebirdPath: lyrebirdPath)),
|
||||
((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"),
|
||||
appScheme(name: name, productExtension: "app")),
|
||||
]
|
||||
try writeFiles(files, fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: Source files
|
||||
|
||||
static func iOSAppInfoPlist(name: String) -> String {
|
||||
appInfoPlist(name: name, platform: .iOS)
|
||||
}
|
||||
|
||||
static func iOSAppSwift(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
import SwiftUI
|
||||
import AVFoundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
@main
|
||||
struct \(name)App: App {
|
||||
@State private var engine: SynthesisEngine?
|
||||
@State private var synth: \(name)Synth = \(name)Synth()
|
||||
|
||||
var body: some Scene {
|
||||
WindowGroup {
|
||||
VStack(spacing: 16) {
|
||||
Text("\(name)").font(.title)
|
||||
ParameterSlider("Frequency", node: synth.$freq, range: 110...1760)
|
||||
ParameterKnob("Amplitude", node: synth.$amp, range: 0...1)
|
||||
ParameterKnob("Pan", node: synth.$pan, range: -1...1)
|
||||
}
|
||||
.padding(24)
|
||||
.onAppear { startEngine() }
|
||||
}
|
||||
}
|
||||
|
||||
private func startEngine() {
|
||||
do {
|
||||
try AVAudioSession.sharedInstance().setCategory(.playback)
|
||||
try AVAudioSession.sharedInstance().setActive(true)
|
||||
} catch {
|
||||
print("AVAudioSession activation failed: \\(error)")
|
||||
return
|
||||
}
|
||||
|
||||
let hwRate = AVAudioSession.sharedInstance().sampleRate
|
||||
let e = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: hwRate,
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: iOSAudioDriver()
|
||||
)
|
||||
do {
|
||||
try e.start()
|
||||
try e.add(synth)
|
||||
} catch {
|
||||
print("Engine failed to start: \\(error)")
|
||||
return
|
||||
}
|
||||
engine = e
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func iOSAppSynthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.25
|
||||
@UIParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp, pan: $pan))
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - iOS pbxproj
|
||||
|
||||
/// `project.pbxproj` for the `ios-ui` template.
|
||||
///
|
||||
/// Single iOS application target. Differs from the macOS pbxproj in:
|
||||
/// `SDKROOT = iphoneos`, `IPHONEOS_DEPLOYMENT_TARGET = 18.0`,
|
||||
/// `TARGETED_DEVICE_FAMILY = "1,2"` (iPhone + iPad), and a SwiftUI
|
||||
/// `@main` entry-file instead of `main.swift` + `AppDelegate.swift`.
|
||||
static func iOSAppPBXProj(name: String, lyrebirdPath: String? = nil) -> String {
|
||||
let bundleID: String = "\(defaultBundleIdentifierPrefix).\(name)"
|
||||
let packageRefLabel: String = pbxPackageReferenceLabel(lyrebirdPath: lyrebirdPath)
|
||||
let packageRefSection: String = pbxPackageReferenceSection(lyrebirdPath: lyrebirdPath)
|
||||
return """
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
\tarchiveVersion = 1;
|
||||
\tclasses = {
|
||||
\t};
|
||||
\tobjectVersion = 60;
|
||||
\tobjects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
\t\t\(pbxIOSAppFileBuild) /* \(name)App.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxIOSAppFileRef) /* \(name)App.swift */; };
|
||||
\t\t\(pbxIOSSynthBuild) /* \(name)Synth.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxIOSSynthRef) /* \(name)Synth.swift */; };
|
||||
\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxLyrebirdUIProductDep) /* LyrebirdUI */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* 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\(pbxIOSAppFileRef) /* \(name)App.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)App.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxIOSSynthRef) /* \(name)Synth.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)Synth.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
\t\t\(pbxFrameworksPhase) /* Frameworks */ = {
|
||||
\t\t\tisa = PBXFrameworksBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
\t\t\(pbxMainGroup) = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppGroup) /* \(name) */,
|
||||
\t\t\t\t\(pbxProductsGroup) /* Products */,
|
||||
\t\t\t);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxProductsGroup) /* Products */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppProductRef) /* \(name).app */,
|
||||
\t\t\t);
|
||||
\t\t\tname = Products;
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxAppGroup) /* \(name) */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxIOSAppFileRef) /* \(name)App.swift */,
|
||||
\t\t\t\t\(pbxIOSSynthRef) /* \(name)Synth.swift */,
|
||||
\t\t\t\t\(pbxInfoPlistRef) /* Info.plist */,
|
||||
\t\t\t);
|
||||
\t\t\tpath = \(name);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
\t\t\(pbxBlueprintIDApp) /* \(name) */ = {
|
||||
\t\t\tisa = PBXNativeTarget;
|
||||
\t\t\tbuildConfigurationList = \(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */;
|
||||
\t\t\tbuildPhases = (
|
||||
\t\t\t\t\(pbxSourcesPhase) /* Sources */,
|
||||
\t\t\t\t\(pbxFrameworksPhase) /* Frameworks */,
|
||||
\t\t\t\t\(pbxResourcesPhase) /* Resources */,
|
||||
\t\t\t);
|
||||
\t\t\tbuildRules = (
|
||||
\t\t\t);
|
||||
\t\t\tdependencies = (
|
||||
\t\t\t);
|
||||
\t\t\tname = \(name);
|
||||
\t\t\tpackageProductDependencies = (
|
||||
\t\t\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */,
|
||||
\t\t\t);
|
||||
\t\t\tproductName = \(name);
|
||||
\t\t\tproductReference = \(pbxAppProductRef) /* \(name).app */;
|
||||
\t\t\tproductType = "com.apple.product-type.application";
|
||||
\t\t};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
\t\t\(pbxRootObject) /* Project object */ = {
|
||||
\t\t\tisa = PBXProject;
|
||||
\t\t\tattributes = {
|
||||
\t\t\t\tBuildIndependentTargetsInParallel = 1;
|
||||
\t\t\t\tLastSwiftUpdateCheck = 1600;
|
||||
\t\t\t\tLastUpgradeCheck = 1600;
|
||||
\t\t\t\tTargetAttributes = {
|
||||
\t\t\t\t\t\(pbxBlueprintIDApp) = {
|
||||
\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;
|
||||
\t\t\t\t\t};
|
||||
\t\t\t\t};
|
||||
\t\t\t};
|
||||
\t\t\tbuildConfigurationList = \(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */;
|
||||
\t\t\tcompatibilityVersion = "Xcode 14.0";
|
||||
\t\t\tdevelopmentRegion = en;
|
||||
\t\t\thasScannedForEncodings = 0;
|
||||
\t\t\tknownRegions = (
|
||||
\t\t\t\ten,
|
||||
\t\t\t\tBase,
|
||||
\t\t\t);
|
||||
\t\t\tmainGroup = \(pbxMainGroup);
|
||||
\t\t\tpackageReferences = (
|
||||
\t\t\t\t\(pbxRemoteSPMRef) /* \(packageRefLabel) */,
|
||||
\t\t\t);
|
||||
\t\t\tproductRefGroup = \(pbxProductsGroup) /* Products */;
|
||||
\t\t\tprojectDirPath = "";
|
||||
\t\t\tprojectRoot = "";
|
||||
\t\t\ttargets = (
|
||||
\t\t\t\t\(pbxBlueprintIDApp) /* \(name) */,
|
||||
\t\t\t);
|
||||
\t\t};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
\t\t\(pbxResourcesPhase) /* Resources */ = {
|
||||
\t\t\tisa = PBXResourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
\t\t\(pbxSourcesPhase) /* Sources */ = {
|
||||
\t\t\tisa = PBXSourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxIOSAppFileBuild) /* \(name)App.swift in Sources */,
|
||||
\t\t\t\t\(pbxIOSSynthBuild) /* \(name)Synth.swift in Sources */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
\t\t\(pbxAppDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.0;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t\tTARGETED_DEVICE_FAMILY = "1,2";
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxAppReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
\t\t\t\tGENERATE_INFOPLIST_FILE = NO;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 18.0;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t\tTARGETED_DEVICE_FAMILY = "1,2";
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_TESTABILITY = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;
|
||||
\t\t\t\tONLY_ACTIVE_ARCH = YES;
|
||||
\t\t\t\tSDKROOT = iphoneos;
|
||||
\t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
\t\t\t\tENABLE_NS_ASSERTIONS = NO;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tSDKROOT = iphoneos;
|
||||
\t\t\t\tSWIFT_COMPILATION_MODE = wholemodule;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
\t\t\(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxAppDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxAppReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxProjectDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxProjectReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
\(packageRefSection)
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */ = {
|
||||
\t\t\tisa = XCSwiftPackageProductDependency;
|
||||
\t\t\tpackage = \(pbxRemoteSPMRef) /* \(packageRefLabel) */;
|
||||
\t\t\tproductName = LyrebirdUI;
|
||||
\t\t};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
\t};
|
||||
\trootObject = \(pbxRootObject) /* Project object */;
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,297 @@
|
||||
// ProjectScaffolder+MacOSUIXcode.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - macos-ui-xcode pbxproj
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
/// `project.pbxproj` for the `macos-ui-xcode` template.
|
||||
///
|
||||
/// Single application target. Sources live under `<name>/` next to
|
||||
/// `Info.plist`. Lyrebird + LyrebirdUI pulled in via SPM — remote URL
|
||||
/// by default, or local `XCLocalSwiftPackageReference` when
|
||||
/// `lyrebirdPath` is set (`lyrebird new --lyrebird-path ...`).
|
||||
static func macOSAppPBXProj(name: String, lyrebirdPath: String? = nil) -> String {
|
||||
let bundleID: String = "\(defaultBundleIdentifierPrefix).\(name)"
|
||||
let packageRefLabel: String = pbxPackageReferenceLabel(lyrebirdPath: lyrebirdPath)
|
||||
let packageRefSection: String = pbxPackageReferenceSection(lyrebirdPath: lyrebirdPath)
|
||||
return """
|
||||
// !$*UTF8*$!
|
||||
{
|
||||
\tarchiveVersion = 1;
|
||||
\tclasses = {
|
||||
\t};
|
||||
\tobjectVersion = 60;
|
||||
\tobjects = {
|
||||
|
||||
/* Begin PBXBuildFile section */
|
||||
\t\t\(pbxMainSwiftBuild) /* main.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxMainSwiftRef) /* main.swift */; };
|
||||
\t\t\(pbxAppDelegateBuild) /* AppDelegate.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxAppDelegateRef) /* AppDelegate.swift */; };
|
||||
\t\t\(pbxSynthBuild) /* \(name)Synth.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxSynthRef) /* \(name)Synth.swift */; };
|
||||
\t\t\(pbxNoteControllerBuild) /* NoteController.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxNoteControllerRef) /* NoteController.swift */; };
|
||||
\t\t\(pbxViewBuild) /* \(name)View.swift in Sources */ = {isa = PBXBuildFile; fileRef = \(pbxViewRef) /* \(name)View.swift */; };
|
||||
\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */ = {isa = PBXBuildFile; productRef = \(pbxLyrebirdUIProductDep) /* LyrebirdUI */; };
|
||||
/* End PBXBuildFile section */
|
||||
|
||||
/* 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\(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>"; };
|
||||
\t\t\(pbxNoteControllerRef) /* NoteController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = NoteController.swift; sourceTree = "<group>"; };
|
||||
\t\t\(pbxViewRef) /* \(name)View.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = \(name)View.swift; sourceTree = "<group>"; };
|
||||
/* End PBXFileReference section */
|
||||
|
||||
/* Begin PBXFrameworksBuildPhase section */
|
||||
\t\t\(pbxFrameworksPhase) /* Frameworks */ = {
|
||||
\t\t\tisa = PBXFrameworksBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxLyrebirdUIFrameworkBuild) /* LyrebirdUI in Frameworks */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXFrameworksBuildPhase section */
|
||||
|
||||
/* Begin PBXGroup section */
|
||||
\t\t\(pbxMainGroup) = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppGroup) /* \(name) */,
|
||||
\t\t\t\t\(pbxProductsGroup) /* Products */,
|
||||
\t\t\t);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxProductsGroup) /* Products */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxAppProductRef) /* \(name).app */,
|
||||
\t\t\t);
|
||||
\t\t\tname = Products;
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
\t\t\(pbxAppGroup) /* \(name) */ = {
|
||||
\t\t\tisa = PBXGroup;
|
||||
\t\t\tchildren = (
|
||||
\t\t\t\t\(pbxMainSwiftRef) /* main.swift */,
|
||||
\t\t\t\t\(pbxAppDelegateRef) /* AppDelegate.swift */,
|
||||
\t\t\t\t\(pbxSynthRef) /* \(name)Synth.swift */,
|
||||
\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\t\tpath = \(name);
|
||||
\t\t\tsourceTree = "<group>";
|
||||
\t\t};
|
||||
/* End PBXGroup section */
|
||||
|
||||
/* Begin PBXNativeTarget section */
|
||||
\t\t\(pbxBlueprintIDApp) /* \(name) */ = {
|
||||
\t\t\tisa = PBXNativeTarget;
|
||||
\t\t\tbuildConfigurationList = \(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */;
|
||||
\t\t\tbuildPhases = (
|
||||
\t\t\t\t\(pbxSourcesPhase) /* Sources */,
|
||||
\t\t\t\t\(pbxFrameworksPhase) /* Frameworks */,
|
||||
\t\t\t\t\(pbxResourcesPhase) /* Resources */,
|
||||
\t\t\t);
|
||||
\t\t\tbuildRules = (
|
||||
\t\t\t);
|
||||
\t\t\tdependencies = (
|
||||
\t\t\t);
|
||||
\t\t\tname = \(name);
|
||||
\t\t\tpackageProductDependencies = (
|
||||
\t\t\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */,
|
||||
\t\t\t);
|
||||
\t\t\tproductName = \(name);
|
||||
\t\t\tproductReference = \(pbxAppProductRef) /* \(name).app */;
|
||||
\t\t\tproductType = "com.apple.product-type.application";
|
||||
\t\t};
|
||||
/* End PBXNativeTarget section */
|
||||
|
||||
/* Begin PBXProject section */
|
||||
\t\t\(pbxRootObject) /* Project object */ = {
|
||||
\t\t\tisa = PBXProject;
|
||||
\t\t\tattributes = {
|
||||
\t\t\t\tBuildIndependentTargetsInParallel = 1;
|
||||
\t\t\t\tLastSwiftUpdateCheck = 1600;
|
||||
\t\t\t\tLastUpgradeCheck = 1600;
|
||||
\t\t\t\tTargetAttributes = {
|
||||
\t\t\t\t\t\(pbxBlueprintIDApp) = {
|
||||
\t\t\t\t\t\tCreatedOnToolsVersion = 16.0;
|
||||
\t\t\t\t\t};
|
||||
\t\t\t\t};
|
||||
\t\t\t};
|
||||
\t\t\tbuildConfigurationList = \(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */;
|
||||
\t\t\tcompatibilityVersion = "Xcode 14.0";
|
||||
\t\t\tdevelopmentRegion = en;
|
||||
\t\t\thasScannedForEncodings = 0;
|
||||
\t\t\tknownRegions = (
|
||||
\t\t\t\ten,
|
||||
\t\t\t\tBase,
|
||||
\t\t\t);
|
||||
\t\t\tmainGroup = \(pbxMainGroup);
|
||||
\t\t\tpackageReferences = (
|
||||
\t\t\t\t\(pbxRemoteSPMRef) /* \(packageRefLabel) */,
|
||||
\t\t\t);
|
||||
\t\t\tproductRefGroup = \(pbxProductsGroup) /* Products */;
|
||||
\t\t\tprojectDirPath = "";
|
||||
\t\t\tprojectRoot = "";
|
||||
\t\t\ttargets = (
|
||||
\t\t\t\t\(pbxBlueprintIDApp) /* \(name) */,
|
||||
\t\t\t);
|
||||
\t\t};
|
||||
/* End PBXProject section */
|
||||
|
||||
/* Begin PBXResourcesBuildPhase section */
|
||||
\t\t\(pbxResourcesPhase) /* Resources */ = {
|
||||
\t\t\tisa = PBXResourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXResourcesBuildPhase section */
|
||||
|
||||
/* Begin PBXSourcesBuildPhase section */
|
||||
\t\t\(pbxSourcesPhase) /* Sources */ = {
|
||||
\t\t\tisa = PBXSourcesBuildPhase;
|
||||
\t\t\tbuildActionMask = \(pbxBuildActionMask);
|
||||
\t\t\tfiles = (
|
||||
\t\t\t\t\(pbxMainSwiftBuild) /* main.swift in Sources */,
|
||||
\t\t\t\t\(pbxAppDelegateBuild) /* AppDelegate.swift in Sources */,
|
||||
\t\t\t\t\(pbxSynthBuild) /* \(name)Synth.swift in Sources */,
|
||||
\t\t\t\t\(pbxNoteControllerBuild) /* NoteController.swift in Sources */,
|
||||
\t\t\t\t\(pbxViewBuild) /* \(name)View.swift in Sources */,
|
||||
\t\t\t);
|
||||
\t\t\trunOnlyForDeploymentPostprocessing = 0;
|
||||
\t\t};
|
||||
/* End PBXSourcesBuildPhase section */
|
||||
|
||||
/* Begin XCBuildConfiguration section */
|
||||
\t\t\(pbxAppDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxAppReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tCODE_SIGN_STYLE = Automatic;
|
||||
\t\t\t\tCOMBINE_HIDPI_IMAGES = YES;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tENABLE_HARDENED_RUNTIME = YES;
|
||||
\t\t\t\tINFOPLIST_FILE = \(name)/Info.plist;
|
||||
\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t\t"@executable_path/../Frameworks",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tMACOSX_DEPLOYMENT_TARGET = 15.0;
|
||||
\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \(bundleID);
|
||||
\t\t\t\tPRODUCT_NAME = "$(TARGET_NAME)";
|
||||
\t\t\t\tSWIFT_VERSION = 6.0;
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectDebugConfig) /* Debug */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = dwarf;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_TESTABILITY = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;
|
||||
\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (
|
||||
\t\t\t\t\t"DEBUG=1",
|
||||
\t\t\t\t\t"$(inherited)",
|
||||
\t\t\t\t);
|
||||
\t\t\t\tONLY_ACTIVE_ARCH = YES;
|
||||
\t\t\t\tSDKROOT = macosx;
|
||||
\t\t\t\tSWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-Onone";
|
||||
\t\t\t};
|
||||
\t\t\tname = Debug;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectReleaseConfig) /* Release */ = {
|
||||
\t\t\tisa = XCBuildConfiguration;
|
||||
\t\t\tbuildSettings = {
|
||||
\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;
|
||||
\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;
|
||||
\t\t\t\tCOPY_PHASE_STRIP = NO;
|
||||
\t\t\t\tDEAD_CODE_STRIPPING = YES;
|
||||
\t\t\t\tDEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
|
||||
\t\t\t\tENABLE_NS_ASSERTIONS = NO;
|
||||
\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;
|
||||
\t\t\t\tENABLE_USER_SCRIPT_SANDBOXING = YES;
|
||||
\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu17;
|
||||
\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;
|
||||
\t\t\t\tSDKROOT = macosx;
|
||||
\t\t\t\tSWIFT_COMPILATION_MODE = wholemodule;
|
||||
\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = "-O";
|
||||
\t\t\t};
|
||||
\t\t\tname = Release;
|
||||
\t\t};
|
||||
/* End XCBuildConfiguration section */
|
||||
|
||||
/* Begin XCConfigurationList section */
|
||||
\t\t\(pbxAppBuildConfigList) /* Build configuration list for PBXNativeTarget "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxAppDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxAppReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
\t\t\(pbxProjectBuildConfigList) /* Build configuration list for PBXProject "\(name)" */ = {
|
||||
\t\t\tisa = XCConfigurationList;
|
||||
\t\t\tbuildConfigurations = (
|
||||
\t\t\t\t\(pbxProjectDebugConfig) /* Debug */,
|
||||
\t\t\t\t\(pbxProjectReleaseConfig) /* Release */,
|
||||
\t\t\t);
|
||||
\t\t\tdefaultConfigurationIsVisible = 0;
|
||||
\t\t\tdefaultConfigurationName = Release;
|
||||
\t\t};
|
||||
/* End XCConfigurationList section */
|
||||
|
||||
\(packageRefSection)
|
||||
|
||||
/* Begin XCSwiftPackageProductDependency section */
|
||||
\t\t\(pbxLyrebirdUIProductDep) /* LyrebirdUI */ = {
|
||||
\t\t\tisa = XCSwiftPackageProductDependency;
|
||||
\t\t\tpackage = \(pbxRemoteSPMRef) /* \(packageRefLabel) */;
|
||||
\t\t\tproductName = LyrebirdUI;
|
||||
\t\t};
|
||||
/* End XCSwiftPackageProductDependency section */
|
||||
\t};
|
||||
\trootObject = \(pbxRootObject) /* Project object */;
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,605 @@
|
||||
// ProjectScaffolder+XcodeTemplates.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - Xcode template constants
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
/// SPM URL Lyrebird is resolved from. Single source of truth for both
|
||||
/// the generated `Package.swift` manifest and every embedded `.xcodeproj`.
|
||||
public static let lyrebirdPackageURL: String = "https://realizedsound.mooo.com/josh/Lyrebird"
|
||||
|
||||
/// Lower bound on the Lyrebird version range — `upToNextMajorVersion`.
|
||||
public static let lyrebirdMinimumVersion: String = "1.0.0"
|
||||
|
||||
/// Bundle identifier prefix used in `PRODUCT_BUNDLE_IDENTIFIER`. The
|
||||
/// scaffolded value is `<prefix>.<name>`. Users typically rewrite this
|
||||
/// to their own reverse-DNS before shipping.
|
||||
public static let defaultBundleIdentifierPrefix: String = "net.realizedsound"
|
||||
|
||||
/// PBX `buildActionMask` — all-build-actions mask used by every build
|
||||
/// phase in a vanilla pbxproj. Constant in PBX format; no semantic
|
||||
/// meaning beyond "this phase participates in every build action".
|
||||
static let pbxBuildActionMask: String = "2147483647"
|
||||
|
||||
/// AUv3 `AudioComponents` entry default `version` encoded as
|
||||
/// `0x00010000` (= `1.0.0`). Standard AU component-version encoding.
|
||||
static let auv3DefaultComponentVersion: Int = 65536
|
||||
|
||||
/// Escape an absolute filesystem path for safe embedding inside a
|
||||
/// pbxproj string literal. Escapes `"` and `\\` — the only two
|
||||
/// characters that would otherwise terminate or corrupt the literal.
|
||||
/// Newlines + control chars in paths are not realistic on macOS so
|
||||
/// not handled.
|
||||
static func pbxQuoteEscape(_ path: String) -> String {
|
||||
var s: String = path
|
||||
s = s.replacingOccurrences(of: "\\", with: "\\\\")
|
||||
s = s.replacingOccurrences(of: "\"", with: "\\\"")
|
||||
return s
|
||||
}
|
||||
|
||||
/// pbxproj snippet for the SPM package reference. Emits either an
|
||||
/// `XCRemoteSwiftPackageReference` (when `lyrebirdPath == nil`) or an
|
||||
/// `XCLocalSwiftPackageReference` pointing at the absolute path.
|
||||
static func pbxPackageReferenceSection(lyrebirdPath: String?) -> String {
|
||||
if let path: String = lyrebirdPath {
|
||||
let escaped: String = pbxQuoteEscape(path)
|
||||
return """
|
||||
/* Begin XCLocalSwiftPackageReference section */
|
||||
\t\t\(pbxRemoteSPMRef) /* XCLocalSwiftPackageReference "lyrebird" */ = {
|
||||
\t\t\tisa = XCLocalSwiftPackageReference;
|
||||
\t\t\trelativePath = "\(escaped)";
|
||||
\t\t};
|
||||
/* End XCLocalSwiftPackageReference section */
|
||||
"""
|
||||
} else {
|
||||
return """
|
||||
/* Begin XCRemoteSwiftPackageReference section */
|
||||
\t\t\(pbxRemoteSPMRef) /* XCRemoteSwiftPackageReference "lyrebird" */ = {
|
||||
\t\t\tisa = XCRemoteSwiftPackageReference;
|
||||
\t\t\trepositoryURL = "\(lyrebirdPackageURL)";
|
||||
\t\t\trequirement = {
|
||||
\t\t\t\tkind = upToNextMajorVersion;
|
||||
\t\t\t\tminimumVersion = \(lyrebirdMinimumVersion);
|
||||
\t\t\t};
|
||||
\t\t};
|
||||
/* End XCRemoteSwiftPackageReference section */
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
/// Comment label used in pbxproj for the SPM package reference.
|
||||
/// Tracks whether it's a remote or local ref so the label in comments
|
||||
/// matches the actual `isa = ...` value.
|
||||
static func pbxPackageReferenceLabel(lyrebirdPath: String?) -> String {
|
||||
lyrebirdPath == nil
|
||||
? #"XCRemoteSwiftPackageReference "lyrebird""#
|
||||
: #"XCLocalSwiftPackageReference "lyrebird""#
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - macos-ui-xcode template
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
// MARK: Public entry point
|
||||
|
||||
/// Write the full `macos-ui-xcode` template tree at `projectRoot`.
|
||||
///
|
||||
/// Emits, in addition to the standard `Package.swift` / `Sources` /
|
||||
/// `Tests` / `<name>.xcworkspace`:
|
||||
/// - `<name>.xcodeproj/project.pbxproj`
|
||||
/// - `<name>.xcodeproj/xcshareddata/xcschemes/<name>.xcscheme`
|
||||
/// - `<name>/Info.plist`
|
||||
/// - `<name>/main.swift`, `AppDelegate.swift`, `<name>Synth.swift` (under app group, not under `Sources/`)
|
||||
static func writeMacOSUIXcodeFiles(
|
||||
name: String,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let appGroupDir: String = (projectRoot as NSString).appendingPathComponent(name)
|
||||
let xcodeprojDir: String = (projectRoot as NSString).appendingPathComponent("\(name).xcodeproj")
|
||||
let schemeDir: String = (xcodeprojDir as NSString)
|
||||
.appendingPathComponent("xcshareddata/xcschemes")
|
||||
|
||||
for dir: String in [appGroupDir, xcodeprojDir, schemeDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
let files: [(String, String)] = [
|
||||
((appGroupDir as NSString).appendingPathComponent("Info.plist"),
|
||||
macOSAppInfoPlist(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("main.swift"),
|
||||
macOSAppMainSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
macOSAppDelegateSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
macOSAppSynthSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("NoteController.swift"),
|
||||
macOSAppNoteControllerSwift(name: name)),
|
||||
((appGroupDir as NSString).appendingPathComponent("\(name)View.swift"),
|
||||
macOSAppViewSwift(name: name)),
|
||||
((xcodeprojDir as NSString).appendingPathComponent("project.pbxproj"),
|
||||
macOSAppPBXProj(name: name, lyrebirdPath: lyrebirdPath)),
|
||||
((schemeDir as NSString).appendingPathComponent("\(name).xcscheme"),
|
||||
appScheme(name: name, productExtension: "app")),
|
||||
]
|
||||
try writeFiles(files, fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: Source files
|
||||
|
||||
static func macOSAppInfoPlist(name: String) -> String {
|
||||
appInfoPlist(name: name, platform: .macOS)
|
||||
}
|
||||
|
||||
static func macOSAppMainSwift(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
//
|
||||
// Engine is configured here but NOT started. The UI's "Start Engine"
|
||||
// button kicks the audio driver, which avoids the first-block dropout
|
||||
// that happens when start() races with the first window-draw frame.
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
NSApplication.shared.setActivationPolicy(.regular)
|
||||
NSApplication.shared.delegate = delegate
|
||||
NSApplication.shared.run()
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppDelegateSwift(name: String) -> String {
|
||||
"""
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let controller: NoteController
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
let scopeCapture = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scopeCapture
|
||||
self.engine = engine
|
||||
self.controller = NoteController(
|
||||
engine: engine,
|
||||
synth: \(name)Synth(),
|
||||
scopeCapture: scopeCapture
|
||||
)
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
window = LyrebirdWindow(title: "\(name)", width: 360, height: 560)
|
||||
window?.open {
|
||||
\(name)View(controller: self.controller)
|
||||
}
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
if controller.engineRunning { engine.stop() }
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppSynthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Live-controllable stereo sine tone.
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
|
||||
/// Frequency in Hz. Slider range 110–1760.
|
||||
@UIParam var frequency: Double = 440.0
|
||||
|
||||
/// Output amplitude (linear gain). Knob range 0–1.
|
||||
@UIParam var amplitude: Double = 0.25
|
||||
|
||||
/// Stereo pan position. -1 = hard left, 0 = center, +1 = hard right.
|
||||
@UIParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppNoteControllerSwift(name: String) -> String {
|
||||
"""
|
||||
import Observation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
/// Owns engine + synth + scope; mediates start/stop from the UI so the
|
||||
/// engine isn't kicked until user is ready (avoids first-block dropouts).
|
||||
@Observable
|
||||
final class NoteController {
|
||||
|
||||
let engine: SynthesisEngine
|
||||
let synth: \(name)Synth
|
||||
let scopeCapture: ScopeCapture
|
||||
|
||||
private(set) var engineRunning: Bool = false
|
||||
private(set) var isPlaying: Bool = false
|
||||
|
||||
init(engine: SynthesisEngine, synth: \(name)Synth, scopeCapture: ScopeCapture) {
|
||||
self.engine = engine
|
||||
self.synth = synth
|
||||
self.scopeCapture = scopeCapture
|
||||
}
|
||||
|
||||
func toggleEngine() {
|
||||
if engineRunning {
|
||||
if isPlaying {
|
||||
engine.remove(synth)
|
||||
isPlaying = false
|
||||
}
|
||||
engine.stop()
|
||||
engineRunning = false
|
||||
} else {
|
||||
do {
|
||||
try engine.start()
|
||||
engineRunning = true
|
||||
} catch {
|
||||
print("Engine failed to start: \\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func toggleNote() {
|
||||
if isPlaying {
|
||||
engine.remove(synth)
|
||||
isPlaying = false
|
||||
} else {
|
||||
do {
|
||||
try engine.add(synth)
|
||||
isPlaying = true
|
||||
} catch {
|
||||
print("engine.add failed: \\(error)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
static func macOSAppViewSwift(name: String) -> String {
|
||||
"""
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
struct \(name)View: View {
|
||||
|
||||
let controller: NoteController
|
||||
|
||||
var body: some View {
|
||||
VStack(alignment: .leading, spacing: 20) {
|
||||
|
||||
HStack {
|
||||
Text("Engine").font(.headline)
|
||||
Spacer()
|
||||
Button(controller.engineRunning ? "Stop Engine" : "Start Engine") {
|
||||
controller.toggleEngine()
|
||||
}
|
||||
.buttonStyle(.borderedProminent)
|
||||
.tint(controller.engineRunning ? .red : .green)
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
HStack {
|
||||
Text("Note").font(.headline)
|
||||
Spacer()
|
||||
Button(controller.isPlaying ? "Stop Note" : "Start Note") {
|
||||
controller.toggleNote()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(controller.isPlaying ? .red : .green)
|
||||
.disabled(!controller.engineRunning)
|
||||
}
|
||||
|
||||
ParameterSlider("Frequency",
|
||||
node: controller.synth.$frequency,
|
||||
range: 110.0...1760.0)
|
||||
|
||||
HStack(spacing: 24) {
|
||||
ParameterKnob("Amplitude",
|
||||
node: controller.synth.$amplitude,
|
||||
range: 0.0...1.0)
|
||||
ParameterKnob("Pan",
|
||||
node: controller.synth.$pan,
|
||||
range: -1.0...1.0)
|
||||
Spacer()
|
||||
}
|
||||
|
||||
Divider()
|
||||
|
||||
LyrebirdStatusView(engine: controller.engine)
|
||||
|
||||
Divider()
|
||||
|
||||
LyrebirdScopeView(capture: controller.scopeCapture)
|
||||
.frame(height: 120)
|
||||
}
|
||||
.padding(20)
|
||||
.frame(minWidth: 340)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Shared Info.plist + Scheme
|
||||
|
||||
extension ProjectScaffolder {
|
||||
|
||||
enum AppPlatform {
|
||||
case macOS
|
||||
case iOS
|
||||
}
|
||||
|
||||
/// `Info.plist` for an app bundle on macOS or iOS.
|
||||
static func appInfoPlist(name: String, platform: AppPlatform) -> String {
|
||||
let bundleIdSetting: String = "$(PRODUCT_BUNDLE_IDENTIFIER)"
|
||||
let bundleNameSetting: String = "$(PRODUCT_NAME)"
|
||||
let executableNameSetting: String = "$(EXECUTABLE_NAME)"
|
||||
let minOSKey: String
|
||||
let minOSValue: String
|
||||
let extras: String
|
||||
switch platform {
|
||||
case .macOS:
|
||||
minOSKey = "LSMinimumSystemVersion"
|
||||
minOSValue = "$(MACOSX_DEPLOYMENT_TARGET)"
|
||||
extras = """
|
||||
<key>NSPrincipalClass</key>
|
||||
<string>NSApplication</string>
|
||||
"""
|
||||
case .iOS:
|
||||
minOSKey = "MinimumOSVersion"
|
||||
minOSValue = "$(IPHONEOS_DEPLOYMENT_TARGET)"
|
||||
extras = """
|
||||
<key>UILaunchScreen</key>
|
||||
<dict/>
|
||||
<key>UISupportedInterfaceOrientations</key>
|
||||
<array>
|
||||
<string>UIInterfaceOrientationPortrait</string>
|
||||
</array>
|
||||
"""
|
||||
}
|
||||
return """
|
||||
<?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>CFBundleExecutable</key>
|
||||
<string>\(executableNameSetting)</string>
|
||||
<key>CFBundleIdentifier</key>
|
||||
<string>\(bundleIdSetting)</string>
|
||||
<key>CFBundleInfoDictionaryVersion</key>
|
||||
<string>6.0</string>
|
||||
<key>CFBundleName</key>
|
||||
<string>\(bundleNameSetting)</string>
|
||||
<key>CFBundlePackageType</key>
|
||||
<string>APPL</string>
|
||||
<key>CFBundleShortVersionString</key>
|
||||
<string>1.0</string>
|
||||
<key>CFBundleVersion</key>
|
||||
<string>1</string>
|
||||
<key>\(minOSKey)</key>
|
||||
<string>\(minOSValue)</string>
|
||||
\(extras)
|
||||
<key>NSHumanReadableCopyright</key>
|
||||
<string>Copyright © \(currentYearString()) \(name). All rights reserved.</string>
|
||||
</dict>
|
||||
</plist>
|
||||
"""
|
||||
}
|
||||
|
||||
/// Build/Test/Launch/Profile scheme XML for a single app target.
|
||||
static func appScheme(name: String, productExtension: String) -> String {
|
||||
let blueprintID: String = pbxBlueprintIDApp
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Scheme
|
||||
LastUpgradeVersion = "1600"
|
||||
version = "1.7">
|
||||
<BuildAction
|
||||
parallelizeBuildables = "YES"
|
||||
buildImplicitDependencies = "YES">
|
||||
<BuildActionEntries>
|
||||
<BuildActionEntry
|
||||
buildForTesting = "YES"
|
||||
buildForRunning = "YES"
|
||||
buildForProfiling = "YES"
|
||||
buildForArchiving = "YES"
|
||||
buildForAnalyzing = "YES">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "\(blueprintID)"
|
||||
BuildableName = "\(name).\(productExtension)"
|
||||
BlueprintName = "\(name)"
|
||||
ReferencedContainer = "container:\(name).xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildActionEntry>
|
||||
</BuildActionEntries>
|
||||
</BuildAction>
|
||||
<TestAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
</TestAction>
|
||||
<LaunchAction
|
||||
buildConfiguration = "Debug"
|
||||
selectedDebuggerIdentifier = "Xcode.DebuggerFoundation.Debugger.LLDB"
|
||||
selectedLauncherIdentifier = "Xcode.DebuggerFoundation.Launcher.LLDB"
|
||||
launchStyle = "0">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "\(blueprintID)"
|
||||
BuildableName = "\(name).\(productExtension)"
|
||||
BlueprintName = "\(name)"
|
||||
ReferencedContainer = "container:\(name).xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</LaunchAction>
|
||||
<ProfileAction
|
||||
buildConfiguration = "Release"
|
||||
shouldUseLaunchSchemeArgsEnv = "YES">
|
||||
<BuildableProductRunnable
|
||||
runnableDebuggingMode = "0">
|
||||
<BuildableReference
|
||||
BuildableIdentifier = "primary"
|
||||
BlueprintIdentifier = "\(blueprintID)"
|
||||
BuildableName = "\(name).\(productExtension)"
|
||||
BlueprintName = "\(name)"
|
||||
ReferencedContainer = "container:\(name).xcodeproj">
|
||||
</BuildableReference>
|
||||
</BuildableProductRunnable>
|
||||
</ProfileAction>
|
||||
<AnalyzeAction
|
||||
buildConfiguration = "Debug">
|
||||
</AnalyzeAction>
|
||||
<ArchiveAction
|
||||
buildConfiguration = "Release"
|
||||
revealArchiveInOrganizer = "YES">
|
||||
</ArchiveAction>
|
||||
</Scheme>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - PBX UUID constants
|
||||
|
||||
// Stable UUIDs used in every generated pbxproj. Layout chosen so the
|
||||
// hex matches semantically — last byte tells the role at a glance when
|
||||
// reading raw pbxproj output. Same scheme reused across all three
|
||||
// xcodeproj-bearing templates; the app-target UUID is referenced from
|
||||
// every scheme (`BlueprintIdentifier`).
|
||||
|
||||
static let pbxRootObject: String = "AABB000000000000000000A0"
|
||||
static let pbxMainGroup: String = "AABB000000000000000000A1"
|
||||
static let pbxProductsGroup: String = "AABB000000000000000000A2"
|
||||
static let pbxAppGroup: String = "AABB000000000000000000A3"
|
||||
static let pbxBlueprintIDApp: String = "AABB0000000000000000000A"
|
||||
static let pbxAppProductRef: String = "AABB000000000000000000A4"
|
||||
static let pbxAppBuildConfigList: String = "AABB000000000000000000A5"
|
||||
static let pbxProjectBuildConfigList: String = "AABB000000000000000000A6"
|
||||
static let pbxAppDebugConfig: String = "AABB000000000000000000A7"
|
||||
static let pbxAppReleaseConfig: String = "AABB000000000000000000A8"
|
||||
static let pbxProjectDebugConfig: String = "AABB000000000000000000A9"
|
||||
static let pbxProjectReleaseConfig: String = "AABB000000000000000000AA"
|
||||
static let pbxSourcesPhase: String = "AABB000000000000000000AB"
|
||||
static let pbxFrameworksPhase: String = "AABB000000000000000000AC"
|
||||
static let pbxResourcesPhase: String = "AABB000000000000000000AD"
|
||||
static let pbxRemoteSPMRef: String = "AABB000000000000000000AE"
|
||||
static let pbxLyrebirdUIProductDep: String = "AABB000000000000000000B0"
|
||||
static let pbxLyrebirdUIFrameworkBuild: String = "AABB000000000000000000B2"
|
||||
|
||||
// App-bundle source file IDs
|
||||
static let pbxMainSwiftRef: String = "AABB0000000000000000010A"
|
||||
static let pbxMainSwiftBuild: String = "AABB0000000000000000010B"
|
||||
static let pbxAppDelegateRef: String = "AABB0000000000000000010C"
|
||||
static let pbxAppDelegateBuild: String = "AABB0000000000000000010D"
|
||||
static let pbxSynthRef: String = "AABB0000000000000000010E"
|
||||
static let pbxSynthBuild: String = "AABB0000000000000000010F"
|
||||
static let pbxNoteControllerRef: String = "AABB0000000000000000011A"
|
||||
static let pbxNoteControllerBuild: String = "AABB0000000000000000011B"
|
||||
static let pbxViewRef: String = "AABB0000000000000000011C"
|
||||
static let pbxViewBuild: String = "AABB0000000000000000011D"
|
||||
static let pbxInfoPlistRef: String = "AABB000000000000000001A0"
|
||||
|
||||
// iOS app uses one fewer file (no separate AppDelegate)
|
||||
static let pbxIOSAppFileRef: String = "AABB0000000000000000020A"
|
||||
static let pbxIOSAppFileBuild: String = "AABB0000000000000000020B"
|
||||
static let pbxIOSSynthRef: String = "AABB0000000000000000020C"
|
||||
static let pbxIOSSynthBuild: String = "AABB0000000000000000020D"
|
||||
|
||||
// AUv3 extension target IDs (separate from the host app)
|
||||
static let pbxExtBlueprint: String = "AABB0000000000000000003A"
|
||||
static let pbxExtProductRef: String = "AABB000000000000000000C0"
|
||||
static let pbxExtGroup: String = "AABB000000000000000000C1"
|
||||
static let pbxExtBuildConfigList: String = "AABB000000000000000000C2"
|
||||
static let pbxExtDebugConfig: String = "AABB000000000000000000C3"
|
||||
static let pbxExtReleaseConfig: String = "AABB000000000000000000C4"
|
||||
static let pbxExtSourcesPhase: String = "AABB000000000000000000C5"
|
||||
static let pbxExtFrameworksPhase: String = "AABB000000000000000000C6"
|
||||
static let pbxExtResourcesPhase: String = "AABB000000000000000000C7"
|
||||
static let pbxExtCopyAppexPhase: String = "AABB000000000000000000C8"
|
||||
static let pbxExtAppexInAppFile: String = "AABB000000000000000000C9"
|
||||
static let pbxExtTargetDep: String = "AABB000000000000000000CA"
|
||||
static let pbxExtContainerProxy: String = "AABB000000000000000000CB"
|
||||
static let pbxExtSynthRef: String = "AABB000000000000000003A0"
|
||||
static let pbxExtSynthBuild: String = "AABB000000000000000003A1"
|
||||
static let pbxExtAuRef: String = "AABB000000000000000003A2"
|
||||
static let pbxExtAuBuild: String = "AABB000000000000000003A3"
|
||||
static let pbxExtVCRef: String = "AABB000000000000000003A4"
|
||||
static let pbxExtVCBuild: String = "AABB000000000000000003A5"
|
||||
static let pbxExtInfoPlistRef: String = "AABB000000000000000003A6"
|
||||
static let pbxAppEntitlementsRef: String = "AABB000000000000000003A7"
|
||||
static let pbxExtEntitlementsRef: String = "AABB000000000000000003A8"
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Year string for `NSHumanReadableCopyright`. Pulled out so tests can
|
||||
/// reason about output stability and the year doesn't get hardcoded.
|
||||
static func currentYearString() -> String {
|
||||
let calendar: Calendar = Calendar(identifier: .gregorian)
|
||||
let year: Int = calendar.component(.year, from: Date())
|
||||
return String(year)
|
||||
}
|
||||
|
||||
/// Atomic-write helper that cleans up `projectRoot` on first failure.
|
||||
/// Mirrors the cleanup behaviour of `scaffold(name:template:in:)`.
|
||||
static func writeFiles(
|
||||
_ files: [(String, String)],
|
||||
fm: FileManager,
|
||||
projectRoot: String
|
||||
) throws {
|
||||
for (path, content) in files {
|
||||
do {
|
||||
try content.write(toFile: path, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: path,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
// ProjectScaffolder.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - ProjectTemplate
|
||||
|
||||
/// Template style for a scaffolded Lyrebird project.
|
||||
public enum ProjectTemplate: String, CaseIterable, Equatable {
|
||||
/// Minimal engine setup with `CoreAudioDriver` and `RunLoop.main.run()`.
|
||||
case basic = "basic"
|
||||
/// Real-time demo: `SineTone` synthesizer with `@LiveParam` frequency and amplitude.
|
||||
case demo = "demo"
|
||||
/// GUI demo: `@UIParam` synthesizer with a `LyrebirdWindow` SwiftUI panel.
|
||||
case uiDemo = "ui-demo"
|
||||
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
|
||||
case nrt = "nrt"
|
||||
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case macosUIXcode = "macos-ui-xcode"
|
||||
/// iOS `.app` bundle with `iOSAudioDriver` + SwiftUI UI.
|
||||
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
|
||||
case iosUI = "ios-ui"
|
||||
/// AUv3 host `.app` + `aumu` plugin extension wrapping a Lyrebird synth.
|
||||
/// Generates a full `<name>.xcodeproj` with two targets and entitlements files.
|
||||
case auv3 = "auv3"
|
||||
|
||||
/// Case-insensitive init from a raw string. Accepts hyphen-free aliases too.
|
||||
public init?(string: String) {
|
||||
switch string.lowercased() {
|
||||
case "basic": self = .basic
|
||||
case "demo": self = .demo
|
||||
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
|
||||
case "nrt": self = .nrt
|
||||
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
|
||||
self = .macosUIXcode
|
||||
case "ios-ui", "iosui", "ios_ui":
|
||||
self = .iosUI
|
||||
case "auv3", "au-v3", "au_v3":
|
||||
self = .auv3
|
||||
default: return nil
|
||||
}
|
||||
}
|
||||
|
||||
/// True when the template emits a full `.xcodeproj` skeleton in addition
|
||||
/// to the Swift Package. The simpler four templates (basic/demo/ui-demo/nrt)
|
||||
/// rely on Xcode's "Open Package.swift" path; these three need a real
|
||||
/// `.xcodeproj` because they ship an `.app` bundle, app entitlements, or
|
||||
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
|
||||
public var shipsXcodeProject: Bool {
|
||||
switch self {
|
||||
case .basic, .demo, .uiDemo, .nrt: return false
|
||||
case .macosUIXcode, .iosUI, .auv3: return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ProjectScaffolder
|
||||
|
||||
/// Scaffolds a new Lyrebird project as a Swift Package.
|
||||
///
|
||||
/// `lyrebird new <name>` creates:
|
||||
///
|
||||
/// ```
|
||||
/// <name>/
|
||||
/// ├── Package.swift
|
||||
/// ├── <name>.xcworkspace/
|
||||
/// │ └── contents.xcworkspacedata (references Package.swift — open in Xcode)
|
||||
/// ├── Sources/
|
||||
/// │ └── <name>/
|
||||
/// │ └── main.swift (+ AppDelegate.swift, <name>Synth.swift for ui-demo)
|
||||
/// └── Tests/
|
||||
/// └── <name>Tests/
|
||||
/// └── <name>Tests.swift
|
||||
/// ```
|
||||
///
|
||||
/// Pass `--template demo`, `--template ui-demo`, or `--template nrt` to get richer
|
||||
/// starting points.
|
||||
public enum ProjectScaffolder {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `ProjectScaffolder`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The project directory already exists.
|
||||
case projectExists(name: String)
|
||||
/// The project name is empty or contains characters not valid in a Swift module name.
|
||||
case invalidName(name: String)
|
||||
/// A file or directory could not be created.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The project name. Must be a non-empty identifier valid as a Swift module name.
|
||||
/// - template: Starter template style (default `.basic`).
|
||||
/// - parentDirectory: Directory in which to create the project folder.
|
||||
/// Defaults to the current working directory.
|
||||
/// - lyrebirdPath: Optional absolute path to a local Lyrebird checkout
|
||||
/// to wire into the generated `Package.swift` as a `path:` dependency
|
||||
/// (useful when developing against an unmerged Lyrebird branch).
|
||||
/// `nil` → use the published GitHub package as the dependency.
|
||||
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
|
||||
public static func scaffold(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
in parentDirectory: String = FileManager.default.currentDirectoryPath,
|
||||
lyrebirdPath: String? = nil
|
||||
) throws {
|
||||
try validateName(name)
|
||||
|
||||
let projectRoot: String = (parentDirectory as NSString).appendingPathComponent(name)
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
guard !fm.fileExists(atPath: projectRoot) else {
|
||||
throw Error.projectExists(name: name)
|
||||
}
|
||||
|
||||
do {
|
||||
try fm.createDirectory(atPath: projectRoot,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: projectRoot,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
if template.shipsXcodeProject {
|
||||
try scaffoldXcodeProject(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
} else {
|
||||
try scaffoldSwiftPackage(name: name,
|
||||
template: template,
|
||||
projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath,
|
||||
fm: fm)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - SPM-only scaffold
|
||||
|
||||
private static func scaffoldSwiftPackage(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
let sourcesDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Sources/\(name)")
|
||||
let testsDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("Tests/\(name)Tests")
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
|
||||
for dir: String in [sourcesDir, testsDir, workspaceDir] {
|
||||
do {
|
||||
try fm.createDirectory(atPath: dir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: dir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
var files: [(path: String, content: String)] = [
|
||||
(
|
||||
(projectRoot as NSString).appendingPathComponent("Package.swift"),
|
||||
packageManifest(name: name, template: template, lyrebirdPath: lyrebirdPath)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("main.swift"),
|
||||
mainSwift(name: name, template: template)
|
||||
),
|
||||
(
|
||||
(testsDir as NSString).appendingPathComponent("\(name)Tests.swift"),
|
||||
testsSwift(name: name)
|
||||
),
|
||||
(
|
||||
(workspaceDir as NSString).appendingPathComponent("contents.xcworkspacedata"),
|
||||
workspaceContents()
|
||||
),
|
||||
]
|
||||
|
||||
if template == .uiDemo {
|
||||
files += [
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("AppDelegate.swift"),
|
||||
appDelegateSwift(name: name)
|
||||
),
|
||||
(
|
||||
(sourcesDir as NSString).appendingPathComponent("\(name)Synth.swift"),
|
||||
synthSwift(name: name)
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
try writeFiles(files.map { ($0.path, $0.content) },
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
}
|
||||
|
||||
// MARK: - Xcode-project scaffold dispatch
|
||||
|
||||
private static func scaffoldXcodeProject(
|
||||
name: String,
|
||||
template: ProjectTemplate,
|
||||
projectRoot: String,
|
||||
lyrebirdPath: String?,
|
||||
fm: FileManager
|
||||
) throws {
|
||||
// Every xcode-bearing template ships an `<name>.xcworkspace` that
|
||||
// references the generated `<name>.xcodeproj`. The workspace is
|
||||
// separate from the SPM-only `workspaceContents()` shape because
|
||||
// there is no `Package.swift` at the project root here.
|
||||
let workspaceDir: String = (projectRoot as NSString)
|
||||
.appendingPathComponent("\(name).xcworkspace")
|
||||
do {
|
||||
try fm.createDirectory(atPath: workspaceDir,
|
||||
withIntermediateDirectories: true,
|
||||
attributes: nil)
|
||||
} catch {
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(path: workspaceDir,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
let workspaceFile: String = (workspaceDir as NSString)
|
||||
.appendingPathComponent("contents.xcworkspacedata")
|
||||
try writeFiles([(workspaceFile,
|
||||
xcodeWorkspaceContents(name: name,
|
||||
lyrebirdPath: lyrebirdPath))],
|
||||
fm: fm, projectRoot: projectRoot)
|
||||
|
||||
switch template {
|
||||
case .macosUIXcode:
|
||||
try writeMacOSUIXcodeFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .iosUI:
|
||||
try writeIOSUIFiles(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .auv3:
|
||||
try writeAUv3Files(name: name, projectRoot: projectRoot,
|
||||
lyrebirdPath: lyrebirdPath, fm: fm)
|
||||
case .basic, .demo, .uiDemo, .nrt:
|
||||
// Unreachable — shipsXcodeProject filters these out at dispatch.
|
||||
try? fm.removeItem(atPath: projectRoot)
|
||||
throw Error.fileSystemError(
|
||||
path: projectRoot,
|
||||
reason: "scaffoldXcodeProject called with non-Xcode template \(template.rawValue)"
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Workspace XML for xcode-bearing templates — references the generated
|
||||
/// `<name>.xcodeproj`. When `lyrebirdPath` is set, the workspace also
|
||||
/// references the Lyrebird `Package.swift` at that absolute path so
|
||||
/// Xcode's IDE-level SPM resolver picks it up at workspace open.
|
||||
/// Without this extra FileRef, opening the workspace in Xcode (vs.
|
||||
/// running `xcodebuild` from the CLI) can fail with "Missing package
|
||||
/// product 'LyrebirdUI'" — the IDE resolver doesn't always crawl into
|
||||
/// member-project `XCLocalSwiftPackageReference` deps automatically.
|
||||
public static func xcodeWorkspaceContents(
|
||||
name: String,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
var refs: String = " <FileRef\n location = \"group:\(name).xcodeproj\">\n </FileRef>"
|
||||
if let path: String = lyrebirdPath {
|
||||
let escaped: String = pbxQuoteEscape(path)
|
||||
refs += "\n <FileRef\n location = \"absolute:\(escaped)\">\n </FileRef>"
|
||||
}
|
||||
return """
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
\(refs)
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Template constants
|
||||
|
||||
// Module-internal so extension files (Xcode-template generators) can
|
||||
// reach them. Single source of truth for the engine defaults written
|
||||
// into every scaffolded `main.swift` / app delegate / iOS app shell.
|
||||
static let scaffoldDefaultBlockSize: Int = 512
|
||||
static let scaffoldDefaultSampleRate: Int = 44100
|
||||
static let scaffoldDefaultOutputChannels: Int = 2
|
||||
static let scaffoldDefaultInputChannels: Int = 2
|
||||
static let scaffoldDefaultNRTDuration: Double = 4.0
|
||||
|
||||
// MARK: - Package manifest
|
||||
|
||||
/// `Package.swift` content for a project using the given template.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: Module / package name written into the generated manifest.
|
||||
/// Must already be validated as a legal Swift identifier.
|
||||
/// - template: Starter template the manifest is tailored for. Controls
|
||||
/// which target/product entries appear. Defaults to `.basic`.
|
||||
/// - lyrebirdPath: When non-nil, Lyrebird is declared as a local SPM
|
||||
/// dependency (`.package(path: ...)`) at this absolute path. When
|
||||
/// nil, falls back to the published Git URL (``lyrebirdPackageURL``).
|
||||
/// Used by `lyrebird new --lyrebird-path` for users who don't yet
|
||||
/// have access to the public repository.
|
||||
public static func packageManifest(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic,
|
||||
lyrebirdPath: String? = nil
|
||||
) -> String {
|
||||
// byName resolves only when the product name matches the package
|
||||
// name (`Lyrebird`). Sibling products (`LyrebirdUI`) need the
|
||||
// explicit `.product(name:package:)` form regardless of whether
|
||||
// the dep is local or remote.
|
||||
let targetDeps: String
|
||||
switch template {
|
||||
case .basic, .demo, .nrt:
|
||||
targetDeps = #""Lyrebird""#
|
||||
case .uiDemo:
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `Package.swift` — dispatch
|
||||
// never reaches this function for them. Defensive fallthrough.
|
||||
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
|
||||
}
|
||||
let depLine: String
|
||||
if let path: String = lyrebirdPath {
|
||||
// `name:` is required so byName target deps (e.g. `"Lyrebird"`)
|
||||
// resolve — SPM otherwise uses the directory basename as the
|
||||
// package identity, which is unlikely to match `"Lyrebird"`
|
||||
// (worktree paths, renamed checkouts, etc.).
|
||||
// Path escaped for safe embedding in a Swift string literal —
|
||||
// same `\\` then `"` escape semantics as `pbxQuoteEscape`.
|
||||
let escapedPath: String = pbxQuoteEscape(path)
|
||||
depLine = #".package(name: "Lyrebird", path: "\#(escapedPath)"),"#
|
||||
} else {
|
||||
depLine = #".package(url: "\#(lyrebirdPackageURL)", from: "\#(lyrebirdMinimumVersion)"),"#
|
||||
}
|
||||
return """
|
||||
// swift-tools-version: 6.0
|
||||
import PackageDescription
|
||||
|
||||
let package = Package(
|
||||
name: "\(name)",
|
||||
platforms: [.macOS(.v15)],
|
||||
dependencies: [
|
||||
\(depLine)
|
||||
],
|
||||
targets: [
|
||||
.executableTarget(
|
||||
name: "\(name)",
|
||||
dependencies: [\(targetDeps)]
|
||||
),
|
||||
.testTarget(
|
||||
name: "\(name)Tests",
|
||||
dependencies: ["\(name)"]
|
||||
),
|
||||
]
|
||||
)
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - main.swift templates
|
||||
|
||||
/// `main.swift` content for the given template (defaults to `.basic`).
|
||||
public static func mainSwift(
|
||||
name: String,
|
||||
template: ProjectTemplate = .basic
|
||||
) -> String {
|
||||
switch template {
|
||||
case .basic: return mainSwiftBasic(name: name)
|
||||
case .demo: return mainSwiftDemo(name: name)
|
||||
case .uiDemo: return mainSwiftUIDemo(name: name)
|
||||
case .nrt: return mainSwiftNRT(name: name)
|
||||
case .macosUIXcode, .iosUI, .auv3:
|
||||
// Xcode-bearing templates don't emit a `main.swift` under
|
||||
// `Sources/<name>/`. Dispatch never reaches this function for
|
||||
// them. Defensive fallthrough to the basic skeleton.
|
||||
return mainSwiftBasic(name: name)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: basic
|
||||
|
||||
private static func mainSwiftBasic(name: String) -> String {
|
||||
"""
|
||||
// \(name) — entry point
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// Configure the synthesis engine.
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
// Add your Synthesizers here.
|
||||
// try engine.add(MySynth())
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
print("\\(name) running — press Ctrl+C to stop")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: demo
|
||||
|
||||
private static func mainSwiftDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — real-time demo
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - SineTone
|
||||
|
||||
final class SineTone: SynthesizerBase {
|
||||
@LiveParam var freq: Double = 440.0
|
||||
@LiveParam var amp: Double = 0.25
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Main
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
fatalError("Engine failed to start: \\(error)")
|
||||
}
|
||||
|
||||
let tone = SineTone()
|
||||
do {
|
||||
try engine.add(tone)
|
||||
} catch {
|
||||
fatalError("Engine.add failed: \\(error)")
|
||||
}
|
||||
|
||||
print("\\(name) running — press Ctrl+C to stop")
|
||||
print("Update tone.freq or tone.amp from the REPL to change parameters.")
|
||||
RunLoop.main.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: ui-demo (main.swift only — AppDelegate and Synth are separate files)
|
||||
|
||||
private static func mainSwiftUIDemo(name: String) -> String {
|
||||
"""
|
||||
// \(name) — GUI demo
|
||||
import AppKit
|
||||
import LyrebirdSynth
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: CoreAudioDriver()
|
||||
)
|
||||
|
||||
let delegate = AppDelegate(engine: engine)
|
||||
NSApplication.shared.setActivationPolicy(.regular)
|
||||
NSApplication.shared.delegate = delegate
|
||||
NSApplication.shared.run()
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: nrt
|
||||
|
||||
private static func mainSwiftNRT(name: String) -> String {
|
||||
"""
|
||||
// \(name) — non-real-time render
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - \(name)Synth
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Audio(
|
||||
envelope: Envelope(
|
||||
levels: [0, 1, 0.6, 0],
|
||||
durations: [0.02, 0.46, 0.5],
|
||||
curves: [0, 0, 0]
|
||||
)
|
||||
)
|
||||
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
|
||||
output(bus: 0, source: Pan2(input: osc))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
let outputURL = URL(fileURLWithPath: "output.caf")
|
||||
let renderDuration = \(scaffoldDefaultNRTDuration)
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Add synthesizers BEFORE start() — NRTDriver renders synchronously inside start().
|
||||
do {
|
||||
try engine.add(\(name)Synth())
|
||||
} catch {
|
||||
fputs("engine.add failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
|
||||
do {
|
||||
try engine.start()
|
||||
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \\(error)\\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - ui-demo additional files
|
||||
|
||||
/// `AppDelegate.swift` content for a ui-demo project.
|
||||
public static func appDelegateSwift(name: String) -> String {
|
||||
"""
|
||||
import AppKit
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class AppDelegate: NSObject, NSApplicationDelegate {
|
||||
let engine: SynthesisEngine
|
||||
let synth: \(name)Synth
|
||||
var window: LyrebirdWindow?
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.synth = \(name)Synth()
|
||||
}
|
||||
|
||||
@MainActor
|
||||
func applicationDidFinishLaunching(_ notification: Notification) {
|
||||
do {
|
||||
try engine.start()
|
||||
} catch {
|
||||
print("Engine.start failed: \\(error)")
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
do {
|
||||
try engine.add(synth)
|
||||
} catch {
|
||||
print("Engine.add failed: \\(error)")
|
||||
engine.stop()
|
||||
NSApp.terminate(nil)
|
||||
return
|
||||
}
|
||||
|
||||
window = LyrebirdWindow(title: "\(name)", width: 320, height: 200)
|
||||
window?.open {
|
||||
VStack(spacing: 16) {
|
||||
ParameterSlider("Frequency", node: self.synth.$freq, range: 110...1760)
|
||||
ParameterKnob("Amplitude", node: self.synth.$amp, range: 0...1)
|
||||
ParameterKnob("Pan", node: self.synth.$pan, range: -1...1)
|
||||
}
|
||||
.padding(24)
|
||||
}
|
||||
}
|
||||
|
||||
func applicationShouldTerminateAfterLastWindowClosed(_ sender: NSApplication) -> Bool {
|
||||
true
|
||||
}
|
||||
|
||||
func applicationWillTerminate(_ notification: Notification) {
|
||||
engine.stop()
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
/// `<name>Synth.swift` content for a ui-demo project.
|
||||
public static func synthSwift(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
final class \(name)Synth: SynthesizerBase {
|
||||
@UIParam var freq: Double = 440.0
|
||||
@UIParam var amp: Double = 0.25
|
||||
@UIParam var pan: Double = 0.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $freq)
|
||||
output(bus: 0, source: Pan2(input: osc * $amp, pan: $pan))
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Xcode workspace
|
||||
|
||||
/// `contents.xcworkspacedata` body. Single `FileRef` to `Package.swift`
|
||||
/// so opening the workspace in Xcode loads the SPM package with full
|
||||
/// project navigation, debugging, and SwiftUI previews. Identical for
|
||||
/// every template — the file lives at `<name>.xcworkspace/contents.xcworkspacedata`.
|
||||
public static func workspaceContents() -> String {
|
||||
"""
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Workspace
|
||||
version = "1.0">
|
||||
<FileRef
|
||||
location = "group:Package.swift">
|
||||
</FileRef>
|
||||
</Workspace>
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Tests template
|
||||
|
||||
/// Starter test file content (shared across all templates).
|
||||
public static func testsSwift(name: String) -> String {
|
||||
"""
|
||||
import Testing
|
||||
import LyrebirdSynth
|
||||
|
||||
@Suite("\(name)")
|
||||
struct \(name)Tests {
|
||||
|
||||
@Test func engineStartsClean() throws {
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: \(scaffoldDefaultBlockSize),
|
||||
sampleRate: \(scaffoldDefaultSampleRate),
|
||||
numOutputChannels: \(scaffoldDefaultOutputChannels),
|
||||
numInputChannels: \(scaffoldDefaultInputChannels),
|
||||
driver: OfflineDriver()
|
||||
)
|
||||
try engine.start()
|
||||
engine.processBlock(inputSamples: [])
|
||||
engine.stop()
|
||||
#expect(engine.audioBuses[0].allSatisfy { $0 == 0.0 })
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Validate that `name` is a non-empty Swift-compatible identifier.
|
||||
static func validateName(_ name: String) throws {
|
||||
try validateSwiftIdentifier(name, invalidNameError: Error.invalidName(name: name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
// REPLLauncher.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Errors thrown by `REPLLauncher`.
|
||||
public enum CLIError: Error {
|
||||
/// The `swift` binary could not be found on this system.
|
||||
case swiftNotFound
|
||||
/// `swift build` exited non-zero. REPL launch was aborted.
|
||||
case buildFailed(exitCode: Int32)
|
||||
}
|
||||
|
||||
/// Locates the Swift toolchain, builds the current package, and launches `swift repl`
|
||||
/// with module/library flags pointing at the package's `.build/debug` artifacts so
|
||||
/// `import LyrebirdSynth` works immediately.
|
||||
///
|
||||
/// The Swift Package Manager's `swift package repl` subcommand was removed from the
|
||||
/// toolchain. The replacement is a two-step invocation: `swift build` to produce the
|
||||
/// package's `.swiftmodule` + library, then `swift repl` with `-I` / `-L` / `-l` flags
|
||||
/// pointing at `.build/debug`. See `docs/tooling/repl.md`.
|
||||
public enum REPLLauncher {
|
||||
|
||||
/// Arguments passed to `swift` for the build step that precedes the REPL.
|
||||
public static let buildArguments: [String] = ["build"]
|
||||
|
||||
/// Arguments passed to `swift` to start the REPL. Resolves modules from the package's
|
||||
/// `.build/debug` directory:
|
||||
/// - `-I .build/debug/Modules` — Swift modules (LyrebirdSynth.swiftmodule, ...)
|
||||
/// - `-I .build/debug/LyrebirdC.build` — LyrebirdC C-module modulemap
|
||||
/// - `-L .build/debug -lLyrebird` — link the Lyrebird dylib
|
||||
///
|
||||
/// Paths are relative; `makeProcess(in:)` sets the working directory so the user can
|
||||
/// run from a project root whose `Package.swift` depends on Lyrebird (or from the
|
||||
/// Lyrebird package directory itself).
|
||||
public static let replArguments: [String] = [
|
||||
"repl",
|
||||
"-I", ".build/debug/Modules",
|
||||
"-I", ".build/debug/LyrebirdC.build",
|
||||
"-L", ".build/debug",
|
||||
"-lLyrebird"
|
||||
]
|
||||
|
||||
/// Path to the shared Lyrebird history file used by the interactive shell
|
||||
/// and other tooling that needs persistent command history.
|
||||
public static var historyFilePath: String {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent(".lyrebird_history").path
|
||||
}
|
||||
|
||||
/// Returns the path to the `swift` binary.
|
||||
///
|
||||
/// Checks `/usr/bin/swift` (Xcode toolchain on macOS) and `/usr/local/bin/swift`
|
||||
/// (standalone toolchain). Throws `CLIError.swiftNotFound` if neither exists.
|
||||
public static func findSwift() throws -> String {
|
||||
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift"]
|
||||
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
|
||||
return path
|
||||
}
|
||||
throw CLIError.swiftNotFound
|
||||
}
|
||||
|
||||
/// Builds a `Process` that runs `swift` with the given arguments in `directory`.
|
||||
/// stdin / stdout / stderr inherited from the calling process.
|
||||
public static func makeProcess(
|
||||
arguments: [String],
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
let swiftPath: String = try findSwift()
|
||||
let process: Process = Process()
|
||||
process.executableURL = URL(fileURLWithPath: swiftPath)
|
||||
process.arguments = arguments
|
||||
process.currentDirectoryURL = URL(fileURLWithPath: directory)
|
||||
return process
|
||||
}
|
||||
|
||||
/// Builds a `Process` configured to run `swift repl` with module/library flags in `directory`.
|
||||
public static func makeProcess(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws -> Process {
|
||||
try makeProcess(arguments: replArguments, in: directory)
|
||||
}
|
||||
|
||||
/// Runs `swift build` and waits for it to finish. Throws `CLIError.buildFailed`
|
||||
/// if the build exited non-zero. If the build was killed by a signal,
|
||||
/// `exitCode` is reported as `1` (rather than the raw signal number, which
|
||||
/// would mislead callers that propagate it through `exit(_:)`).
|
||||
public static func build(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
let process: Process = try makeProcess(arguments: buildArguments, in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
if process.terminationReason != .exit {
|
||||
throw CLIError.buildFailed(exitCode: 1)
|
||||
}
|
||||
if process.terminationStatus != 0 {
|
||||
throw CLIError.buildFailed(exitCode: process.terminationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
/// Builds the package, then launches `swift repl` with Lyrebird available.
|
||||
/// Blocks until the REPL session ends.
|
||||
///
|
||||
/// - Parameter directory: Working directory for the SPM + REPL invocation.
|
||||
/// Defaults to the current directory. Must contain a `Package.swift`.
|
||||
public static func launch(
|
||||
in directory: String = FileManager.default.currentDirectoryPath
|
||||
) throws {
|
||||
try build(in: directory)
|
||||
let process: Process = try makeProcess(in: directory)
|
||||
try process.run()
|
||||
process.waitUntilExit()
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A pair: a SynthesizerBase subclass with @LiveParam slots + a LyrebirdAudioUnit subclass that wraps it as an AUv3 component. Override only makeSynthesizer() and parameterMetadata(); LyrebirdAudioUnit handles render setup, parameter ramping, and CoreMIDI 2.0 input. Pair with an Info.plist AudioComponents entry (type: aumu, your subtype + manufacturer) to register the AU with the host. See LyrebirdAUv3Demo for a complete project.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird AUv3 Source-Slot Synth (Synth + LyrebirdAudioUnit)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>35</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyAUSynth</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>AU synth name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the Synthesizer + AudioUnit pair (used as the file name and the Synthesizer class; the AU is named <Name>AudioUnit).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyAUSynth</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdAUv3SynthAU.xctemplate/___FILEBASENAME___.swift
Vendored
+68
@@ -0,0 +1,68 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import AVFoundation
|
||||
import AudioToolbox
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Synthesizer driven by the AUv3 host. Each `@LiveParam` slot maps to an
|
||||
/// `AUParameter` exposed by the wrapper class below via
|
||||
/// `parameterMetadata()`. The host writes parameter values through the AU's
|
||||
/// `AUParameterTree`; `LyrebirdAudioUnit` forwards each write to the matching
|
||||
/// `@LiveParam` (atomic, RT-safe).
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
|
||||
|
||||
/// Fundamental frequency in Hz. Range [20, 8000].
|
||||
@LiveParam public var frequency: Double = 440.0
|
||||
|
||||
/// Output amplitude (linear gain). Range [0, 1].
|
||||
@LiveParam public var amplitude: Double = 0.3
|
||||
|
||||
public override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
let voice = osc * $amplitude
|
||||
// Mono → stereo for AUv3 host compatibility (most hosts negotiate
|
||||
// stereo output buses).
|
||||
output(bus: 0, source: voice)
|
||||
output(bus: 1, source: voice)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___AudioUnit
|
||||
|
||||
/// AUv3 wrapper. Subclasses `LyrebirdAudioUnit`, which handles render setup,
|
||||
/// parameter ramping, and CoreMIDI 2.0 input. Override only the two class
|
||||
/// methods below.
|
||||
///
|
||||
/// To expose this AU to hosts (Logic, GarageBand, AUM, Loopy Pro, …):
|
||||
///
|
||||
/// 1. Make the containing target an Audio Unit App Extension (`.appex`).
|
||||
/// 2. Add an `AudioComponents` array to the extension's Info.plist:
|
||||
/// - `type: aumu` (music device) — change to `aufx` for effects
|
||||
/// - `subtype: ABCD` — 4-char identifier you choose
|
||||
/// - `manufacturer: WXYZ` — 4-char identifier you choose
|
||||
/// - `name: ___FILEBASENAMEASIDENTIFIER___`
|
||||
/// - `factoryFunction: $(PRODUCT_MODULE_NAME).___FILEBASENAMEASIDENTIFIER___AudioUnit`
|
||||
/// - `version: 1`
|
||||
/// 3. Set the extension's `NSExtensionPrincipalClass` to an
|
||||
/// `AUViewController` that returns this AU from `createAudioUnit(with:)`.
|
||||
/// 4. After build, validate with:
|
||||
/// auval -v aumu ABCD WXYZ
|
||||
///
|
||||
/// See `Demos/LyrebirdAUv3Demo/LyrebirdFMExtension/` for a complete working
|
||||
/// example with Info.plist, AUViewController, and a SwiftUI host app.
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___AudioUnit: LyrebirdAudioUnit {
|
||||
|
||||
public override class func makeSynthesizer() -> SynthesizerBase {
|
||||
___FILEBASENAMEASIDENTIFIER___()
|
||||
}
|
||||
|
||||
public override class func parameterMetadata() -> [String: LyrebirdAUParameterInfo] {
|
||||
[
|
||||
"frequency": .init(min: 20, max: 8000, unit: .hertz, displayName: "Frequency"),
|
||||
"amplitude": .init(min: 0, max: 1, unit: .linearGain, displayName: "Amplitude"),
|
||||
]
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A sample-playback Synthesizer that loads a LyrebirdBuffer from an audio file URL and plays it via PlayBuffer.Audio. Honours the file's native sample rate via nativeRateScale, supports loop / rate-modulation via @LiveParam. Loading runs at init (non-RT) and traps on file errors — convert to throwing init for production code.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Buffer Reader (file → PlayBuffer Synthesizer)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>33</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MySamplePlayer</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Synthesizer name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the sample-player Synthesizer (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MySamplePlayer</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Sample-playback Synthesizer that loads an audio file at init and plays it
|
||||
/// through `PlayBuffer.Audio`. Output channel count matches the loaded buffer.
|
||||
///
|
||||
/// `LyrebirdBuffer.loadAllChannels(url:)` reads every channel into a single
|
||||
/// multichannel buffer and records the file's sample rate on it; passing
|
||||
/// `buffer.nativeRateScale(engineSampleRate:)` to `PlayBuffer.Audio` rate:
|
||||
/// ensures the file plays back at the correct pitch / speed when the engine
|
||||
/// runs at a different sample rate than the file.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let player = try ___FILEBASENAMEASIDENTIFIER___(
|
||||
/// fileURL: URL(fileURLWithPath: "/path/to/sample.wav"),
|
||||
/// loop: true,
|
||||
/// engineSampleRate: engine.sampleRate
|
||||
/// )
|
||||
/// try engine.add(player)
|
||||
///
|
||||
/// // Modulate playback rate at runtime:
|
||||
/// player.rate = 0.5 // half speed / one octave down
|
||||
/// ```
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Playback rate multiplier. `1.0` = native pitch, `2.0` = +1 octave,
|
||||
/// `0.5` = −1 octave. Negative values reverse playback if the underlying
|
||||
/// PlayBuffer is configured to honour them.
|
||||
@LiveParam public var rate: Double = 1.0
|
||||
|
||||
/// Output amplitude (linear gain).
|
||||
@LiveParam public var amplitude: Double = 1.0
|
||||
|
||||
// MARK: - State
|
||||
|
||||
private let buffer: LyrebirdBuffer
|
||||
private let loop: Bool
|
||||
private let engineSampleRate: Double
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - fileURL: Path to a WAV / AIFF / CAF audio file. Loaded synchronously
|
||||
/// on a non-RT thread; do not call from the audio callback.
|
||||
/// - loop: When `true`, playback restarts from frame 0 after the end.
|
||||
/// When `false`, the generator emits silence after the final frame
|
||||
/// (or frees the node if `doneAction == .freeNode`).
|
||||
/// - engineSampleRate: The engine's sample rate. Passed at init so the
|
||||
/// `build()` closure (which has no engine reference) can compute the
|
||||
/// native-sample-rate compensation. Get from `engine.sampleRate`.
|
||||
public init(
|
||||
fileURL: URL,
|
||||
loop: Bool = false,
|
||||
engineSampleRate: Double
|
||||
) throws {
|
||||
self.buffer = try LyrebirdBuffer.loadAllChannels(url: fileURL)
|
||||
self.loop = loop
|
||||
self.engineSampleRate = engineSampleRate
|
||||
super.init()
|
||||
}
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
public override func build() {
|
||||
// Compose rate: user-controlled `rate` multiplier × the buffer's
|
||||
// native-sample-rate compensation. nativeRateScale falls back to 1.0
|
||||
// when the buffer carries no recorded rate.
|
||||
let nativeScale = buffer.nativeRateScale(engineSampleRate: engineSampleRate)
|
||||
let combinedRate = $rate * nativeScale
|
||||
|
||||
let player = PlayBuffer.Audio(
|
||||
buffer: buffer,
|
||||
loop: loop,
|
||||
doneAction: loop ? .nothing : .freeNode,
|
||||
rate: combinedRate
|
||||
)
|
||||
|
||||
output(bus: 0, source: player * $amplitude)
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A pure-value source conforming to DemandGenerator. Consumed by Demand.Audio / Demand.Control pullers — one value per ≤0→>0 trigger edge. Owned by exactly one puller. Provide nextValue(), reset(), and isExhausted.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Demand Generator (DemandGenerator conformer)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>20</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyDemand</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>DemandGenerator name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the DemandGenerator class (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyDemand</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+64
@@ -0,0 +1,64 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// A `DemandGenerator` is a pull-based value source — it is **not** a `Generator`
|
||||
/// and does not appear in the audio graph itself. It is consumed by a demand
|
||||
/// puller (`Demand.Audio` or `Demand.Control`) which calls `nextValue()` on each
|
||||
/// `≤ 0 → > 0` trigger edge. Each instance is owned by exactly one puller.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let demand = ___FILEBASENAMEASIDENTIFIER___()
|
||||
/// let pitchSeq = Demand.Control(
|
||||
/// trig: Impulse.Control(freq: 2.0),
|
||||
/// demand: demand
|
||||
/// )
|
||||
/// let osc = OscSin.Audio(freq: pitchSeq)
|
||||
/// ```
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: DemandGenerator {
|
||||
|
||||
// MARK: - State
|
||||
|
||||
/// Replace these stored properties with whatever state your value source needs
|
||||
/// (current step, RNG state, table indices, etc.). State is mutated only inside
|
||||
/// `nextValue()` and `reset()` — both run on the RT thread side of the demand
|
||||
/// puller, so keep everything allocation-free and lock-free.
|
||||
private var _step: Int = 0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
public init() {
|
||||
// Initialise state. No allocation paths should run after this point on the
|
||||
// RT thread.
|
||||
}
|
||||
|
||||
// MARK: - DemandGenerator
|
||||
|
||||
/// `true` once this source has produced its final value. Returning `nil` from
|
||||
/// `nextValue()` is also acceptable — pullers stop pulling when either signals
|
||||
/// exhaustion.
|
||||
public var isExhausted: Bool {
|
||||
// TODO: return true when this source has no more values to produce.
|
||||
return false
|
||||
}
|
||||
|
||||
/// Returns the next value to emit, or `nil` if exhausted.
|
||||
public func nextValue() -> Double? {
|
||||
// TODO: produce the next value. Replace this body with your formula.
|
||||
let value: Double = Double(_step)
|
||||
_step += 1
|
||||
return value
|
||||
}
|
||||
|
||||
/// Reset internal state so the next `nextValue()` produces the source's first
|
||||
/// value again. Called by demand pullers when their trigger source resets.
|
||||
public func reset() {
|
||||
_step = 0
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Lyrebird RBJ biquad filter (in-tree only — uses module-internal runRBJBiquadBlock helper and BiquadCoeffs / BiquadState types). Drop this file under Sources/Lyrebird/Generators/Filters/. Audio-rate only; signature (input, freq, q, mul, add). Replace the coefficient closure with the EQ Cookbook formula for your filter shape.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Filter (RBJ biquad, Audio-only)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>15</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyFilter</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Filter name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the filter enum (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyFilter</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+114
@@ -0,0 +1,114 @@
|
||||
//___FILEHEADER___
|
||||
//
|
||||
// In-tree template — drop this file under Sources/Lyrebird/Generators/Filters/.
|
||||
// Uses the module-internal `runRBJBiquadBlock` helper and BiquadCoeffs / BiquadState
|
||||
// types, so this template is not usable from a project that depends on Lyrebird
|
||||
// as a package. External users should declare their own biquad state inline.
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Second-order biquad filter using Robert Bristow-Johnson's Audio EQ Cookbook
|
||||
/// coefficient formulas. Replace the `computeCoefficients` closure body with the
|
||||
/// coefficient set for your filter shape (lowpass / highpass / bandpass / notch /
|
||||
/// allpass / peaking / shelf).
|
||||
///
|
||||
/// `freq` and `q` accept any `ValidGeneratorInput`. Generator inputs trigger
|
||||
/// block-boundary coefficient interpolation — 6 trig calls per block regardless
|
||||
/// of block size.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// ___FILEBASENAMEASIDENTIFIER___.Audio(input: sig, freq: 1000.0, q: 0.707)
|
||||
/// ___FILEBASENAMEASIDENTIFIER___.Audio(input: sig, freq: lfoGen, q: 2.0)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff (or centre / corner) frequency in Hz. No internal clamping;
|
||||
/// stay below Nyquist for alias-free output.
|
||||
/// - q: Resonance / bandwidth factor. `0.707` = Butterworth (no peak).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___ filter.
|
||||
public final class Audio: GeneratorBase, AudioGenerator {
|
||||
|
||||
private let inputSource: any ValidGeneratorInput
|
||||
private let freqInput: any ValidGeneratorInput
|
||||
private let qInput: any ValidGeneratorInput
|
||||
|
||||
private let freqIsGenerator: Bool
|
||||
private let qIsGenerator: Bool
|
||||
|
||||
private var cachedCoeffs: BiquadCoeffs = .zero
|
||||
private var prevFreq: Double = -1.0
|
||||
private var prevQ: Double = -1.0
|
||||
private var prevSampleRate: Double = -1.0
|
||||
|
||||
private var state: BiquadState = BiquadState()
|
||||
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Signal to filter.
|
||||
/// - freq: Cutoff frequency in Hz.
|
||||
/// - q: Resonance factor.
|
||||
/// - mul: Output multiplier.
|
||||
/// - add: Output offset.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
freq: any ValidGeneratorInput,
|
||||
q: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
self.inputSource = input
|
||||
self.freqInput = freq
|
||||
self.qInput = q
|
||||
self.freqIsGenerator = freq is any Generator
|
||||
self.qIsGenerator = q is any Generator
|
||||
self._mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
runRBJBiquadBlock(
|
||||
inputSource: inputSource, freqInput: freqInput, qInput: qInput,
|
||||
freqIsGenerator: freqIsGenerator, qIsGenerator: qIsGenerator,
|
||||
state: &state, cachedCoeffs: &cachedCoeffs,
|
||||
prevFreq: &prevFreq, prevQ: &prevQ, prevSampleRate: &prevSampleRate,
|
||||
mulAdd: _mulAdd, result: &_result,
|
||||
graph: graph, count: count,
|
||||
computeCoefficients: { freq, q, sampleRate in
|
||||
// Replace this body with the EQ Cookbook coefficient formula
|
||||
// for your filter shape. Below is the lowpass formula as a
|
||||
// starting reference — see RBJLowPass.swift for the canonical
|
||||
// implementation that already lives in Lyrebird.
|
||||
let w0 = 2.0 * .pi * freq / sampleRate
|
||||
let cosW0 = cos(w0)
|
||||
let sinW0 = sin(w0)
|
||||
let alpha = sinW0 / (2.0 * q)
|
||||
|
||||
let b0 = (1.0 - cosW0) * 0.5
|
||||
let b1 = 1.0 - cosW0
|
||||
let b2 = (1.0 - cosW0) * 0.5
|
||||
let a0 = 1.0 + alpha
|
||||
let a1 = -2.0 * cosW0
|
||||
let a2 = 1.0 - alpha
|
||||
|
||||
return BiquadCoeffs(
|
||||
nb0: b0 / a0, nb1: b1 / a0, nb2: b2 / a0,
|
||||
na1: a1 / a0, na2: a2 / a0
|
||||
)
|
||||
}
|
||||
)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// GeneratorEnum conformance intentionally omitted — Audio-only filter.
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Lyrebird Generator with both Audio-rate and Control-rate variants. Subclasses GeneratorBase and conforms to AudioGenerator / ControlGenerator. Includes the canonical _Base shared-state class, _checkCount guard, MulAddSpec wiring, and the sub-block linear-ramp pattern for the Control variant.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Generator (Audio + Control)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>10</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyGenerator</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Generator name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the Generator (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyGenerator</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+132
@@ -0,0 +1,132 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
@_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// Longer explanation: what the generator does, formula, edge cases.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let g = ___FILEBASENAMEASIDENTIFIER___.Audio(signal)
|
||||
/// let g = ___FILEBASENAMEASIDENTIFIER___.Control(signal)
|
||||
/// ```
|
||||
public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
/// Shared state between Audio and Control variants.
|
||||
///
|
||||
/// Holds input references + MulAddSpec. Stored properties live here so the
|
||||
/// two final classes share the same field layout (and the same designated init).
|
||||
public class _Base: GeneratorBase {
|
||||
let inputSource: any ValidGeneratorInput
|
||||
let _mulAdd: MulAddSpec
|
||||
|
||||
public init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
inputSource = signal
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
// GeneratorBase.init() allocates _result with one mono row of
|
||||
// lyrebirdDefaultResultBufferSize. Multi-channel generators call
|
||||
// super.init(channels: N) instead.
|
||||
}
|
||||
}
|
||||
|
||||
/// Per-sample transform shared by Audio + Control. Replace this with the
|
||||
/// generator's actual formula.
|
||||
@inline(__always)
|
||||
static func _transform(_ value: Double) -> Double {
|
||||
// TODO: implement.
|
||||
return value
|
||||
}
|
||||
|
||||
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(signal, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
let block = inputSource.calculatedSamples(graph: graph, count: count).first ?? []
|
||||
let n = block.count
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = ___FILEBASENAMEASIDENTIFIER___._transform(i < n ? block[i] : 0.0)
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-rate ___FILEBASENAMEASIDENTIFIER___. Output is linearly interpolated
|
||||
/// toward the block target.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
public var previousOutputValue: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - signal: Input signal.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
_ signal: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(signal, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
var target = ___FILEBASENAMEASIDENTIFIER___._transform(
|
||||
inputSource.floatValue(graph: graph)
|
||||
)
|
||||
if !_mulAdd.isIdentity {
|
||||
target = target * _mulAdd.mulInput.floatValue(graph: graph)
|
||||
+ _mulAdd.addInput.floatValue(graph: graph)
|
||||
}
|
||||
guard count > 0 else { return _result }
|
||||
let rampStart: Double = previousOutputValue
|
||||
previousOutputValue = target
|
||||
let step = (target - rampStart) / Double(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = rampStart + step * Double(i + 1)
|
||||
}
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
|
||||
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
|
||||
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Swift Testing @Suite that exercises a Generator across an engine block. Uses makeTestEngine / makeSynthGraph / advanceBlock helpers (live in Tests/LyrebirdTests/TestHelpers.swift). Includes finite-output + reset-state starter tests.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Generator Test Suite (@Suite + @Test)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>24</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyGeneratorTests</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Test suite name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the test suite type (also used as the file name). Convention: <Type>Tests.</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyGeneratorTests</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+55
@@ -0,0 +1,55 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Test suite for ___FILEBASENAMEASIDENTIFIER___'s subject Generator.
|
||||
///
|
||||
/// Add @Test methods for: parameter ranges, edge cases (zero / negative freq,
|
||||
/// out-of-range mul/add, exhausted state, reset), block-size correctness,
|
||||
/// channel-count claims (`outputChannelCount`), and any RT-safety invariants.
|
||||
///
|
||||
/// `makeTestEngine`, `makeSynthGraph`, and `advanceBlock` live in
|
||||
/// `Tests/LyrebirdTests/TestHelpers.swift` and are intentionally module-internal
|
||||
/// — this file only compiles when dropped under `Tests/LyrebirdTests/`.
|
||||
@Suite("___FILEBASENAMEASIDENTIFIER___")
|
||||
struct ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
/// Subject under test produces finite output for a single block.
|
||||
@Test func outputIsFinite() throws {
|
||||
let engine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
// Replace OscSin.Audio with the Generator you are testing.
|
||||
let gen = OscSin.Audio(freq: 440.0)
|
||||
|
||||
let g = makeSynthGraph(engine: engine)
|
||||
let out = gen.calculatedSamples(graph: g, count: 64)
|
||||
let samples = Array((out.first ?? []).prefix(64))
|
||||
|
||||
#expect(samples.count == 64)
|
||||
#expect(samples.allSatisfy { $0.isFinite })
|
||||
}
|
||||
|
||||
/// Subject under test advances state across blocks — output of block 2
|
||||
/// differs from output of block 1 for a non-DC signal.
|
||||
@Test func stateAdvancesAcrossBlocks() throws {
|
||||
let engine = makeTestEngine(blockSize: 64)
|
||||
try engine.start()
|
||||
defer { engine.stop() }
|
||||
|
||||
let gen = OscSin.Audio(freq: 440.0)
|
||||
|
||||
let g1 = makeSynthGraph(engine: engine)
|
||||
let block1 = Array((gen.calculatedSamples(graph: g1, count: 64).first ?? []).prefix(64))
|
||||
advanceBlock(engine)
|
||||
|
||||
let g2 = makeSynthGraph(engine: engine)
|
||||
let block2 = Array((gen.calculatedSamples(graph: g2, count: 64).first ?? []).prefix(64))
|
||||
|
||||
#expect(block1 != block2, "Generator should advance state between blocks")
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A MIDI setup factory that opens the CoreMIDI client, registers a handler for incoming MIDIMessage values (noteOn / noteOff / controlChange / …), and returns a started MIDI instance. The handler closure runs on the lyrebird.midi queue — not the RT thread.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird MIDI Handler (CoreMIDI input)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>31</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyMIDIHandler</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>MIDI handler name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the factory function / type (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyMIDIHandler</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdMIDIHandler.xctemplate/___FILEBASENAME___.swift
Vendored
+92
@@ -0,0 +1,92 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Factory that wires up CoreMIDI input for `engine` and returns a started
|
||||
/// `MIDI` instance.
|
||||
///
|
||||
/// The handler closure runs on the `lyrebird.midi` dispatch queue — not the
|
||||
/// RT audio thread. From here you can:
|
||||
/// - Mutate `@LiveParam` slots on Synthesizers (atomic, RT-safe)
|
||||
/// - Call `engine.add(_:)` / `engine.remove(_:)` (lock-free, applied at the
|
||||
/// next block boundary)
|
||||
/// - Start / stop / pause `LyrebirdTask`s
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let midi = try make___FILEBASENAMEASIDENTIFIER___(engine: engine)
|
||||
/// // …
|
||||
/// midi.stop() // before engine deallocates
|
||||
/// ```
|
||||
///
|
||||
/// - Parameter engine: Running `SynthesisEngine` whose Synthesizers receive
|
||||
/// MIDI-driven parameter changes.
|
||||
/// - Returns: Started `MIDI` with one handler registered.
|
||||
/// - Throws: `MIDIError.alreadyStarted` if `start()` is called twice.
|
||||
public func make___FILEBASENAMEASIDENTIFIER___(
|
||||
engine: SynthesisEngine,
|
||||
clientName: String = "Lyrebird"
|
||||
) throws -> MIDI {
|
||||
let midi = MIDI(engine: engine, clientName: clientName)
|
||||
|
||||
_ = midi.addHandler(name: "___FILEBASENAMEASIDENTIFIER___") { message, _ in
|
||||
switch message {
|
||||
case .noteOn(let channel, let note, let velocity):
|
||||
// velocity == 0 is a "running-status" note off — handle as note off.
|
||||
if velocity == 0 {
|
||||
handleNoteOff(channel: channel, note: note, velocity: 0)
|
||||
} else {
|
||||
handleNoteOn(channel: channel, note: note, velocity: velocity)
|
||||
}
|
||||
case .noteOff(let channel, let note, let velocity):
|
||||
handleNoteOff(channel: channel, note: note, velocity: velocity)
|
||||
case .controlChange(let channel, let controller, let value):
|
||||
handleControlChange(channel: channel, controller: controller, value: value)
|
||||
default:
|
||||
// pitch bend, channel pressure, polyphonic aftertouch, program
|
||||
// change, system messages — extend MIDIMessage handling here.
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
try midi.start()
|
||||
return midi
|
||||
}
|
||||
|
||||
// MARK: - Per-message handlers (replace bodies with your own)
|
||||
|
||||
private func handleNoteOn(channel: UInt8, note: UInt8, velocity: UInt8) {
|
||||
// TODO: convert (note, velocity) to (Hz, amp) and spawn a voice synth, e.g.
|
||||
//
|
||||
// let synth = MyVoice()
|
||||
// synth.frequency = midiNoteToHz(note)
|
||||
// synth.amplitude = Double(velocity) / 127.0
|
||||
// try engine.add(synth)
|
||||
// voicesByNote[note] = synth
|
||||
_ = (channel, note, velocity)
|
||||
}
|
||||
|
||||
private func handleNoteOff(channel: UInt8, note: UInt8, velocity: UInt8) {
|
||||
// TODO: release / remove the voice synth that handleNoteOn started.
|
||||
_ = (channel, note, velocity)
|
||||
}
|
||||
|
||||
private func handleControlChange(channel: UInt8, controller: UInt8, value: UInt8) {
|
||||
// TODO: map CCs to Synthesizer @LiveParams. E.g.:
|
||||
//
|
||||
// switch controller {
|
||||
// case 7: masterSynth.amp = Double(value) / 127.0 // CC7 = volume
|
||||
// case 74: filterSynth.cutoff = ccToCutoff(value) // CC74 = brightness
|
||||
// default: break
|
||||
// }
|
||||
_ = (channel, controller, value)
|
||||
}
|
||||
|
||||
/// Standard MIDI note number → Hz using the 12-tone equal-tempered scale
|
||||
/// anchored at A4 = 69 = 440 Hz.
|
||||
private func midiNoteToHz(_ note: UInt8) -> Double {
|
||||
440.0 * pow(2.0, (Double(note) - 69.0) / 12.0)
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A multi-channel audio Generator that returns N rows from _computeSamples. Calls super.init(channels: N) to allocate N pre-allocated result rows; overrides outputChannelCount to expose the fixed channel count. Modeled on Pan2's two-channel shape. Pass directly to output(bus:source:) — Out writes channel k to bus+k.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Multi-Channel Generator (N-row output)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>21</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyMultiChannel</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Generator name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the multi-channel Generator class (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyMultiChannel</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
@_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// Returns N output channels per render block. The channel count is fixed at
|
||||
/// init time via `super.init(channels: N)` — `GeneratorBase` pre-allocates the
|
||||
/// `_result` buffer with N rows. `outputChannelCount` returns the same N so
|
||||
/// downstream operators (`+`, `-`, `*`, `/`) treat this as multi-channel rather
|
||||
/// than mono.
|
||||
///
|
||||
/// Channel count must be derivable from a `let` at init — never runtime-mutable.
|
||||
/// To support a user-chosen channel count, accept it as an `Int` init parameter
|
||||
/// (see Pan4 etc).
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// override func build() {
|
||||
/// let src = OscSin.Audio(freq: 440.0)
|
||||
/// // Out writes channel k to bus+k:
|
||||
/// output(bus: 0, source: ___FILEBASENAMEASIDENTIFIER___(input: src))
|
||||
/// }
|
||||
/// ```
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: GeneratorBase, AudioGenerator {
|
||||
|
||||
// MARK: - Channel count (fixed at init)
|
||||
|
||||
/// Output channel count. Hard-coded here as a starting value — replace with an
|
||||
/// init parameter if your generator needs user-chosen channel counts.
|
||||
private static let outChannels: Int = 2
|
||||
|
||||
public override var outputChannelCount: Int { Self.outChannels }
|
||||
|
||||
// MARK: - Inputs
|
||||
|
||||
private let _input: any ValidGeneratorInput
|
||||
private let _mulAdd: MulAddSpec
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
/// - Parameters:
|
||||
/// - input: Source signal. Mono input fans out across all channels by
|
||||
/// default; multi-row input maps element-wise (mismatched channel counts
|
||||
/// should `precondition`-trap at init).
|
||||
/// - mul: Output multiplier. Defaults to `1.0`. Channel-aware: scalar
|
||||
/// broadcasts, equal-N multi-row applies element-wise.
|
||||
/// - add: Output offset. Defaults to `0.0`. Same channel-aware policy.
|
||||
public init(
|
||||
input: any ValidGeneratorInput,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
_input = input
|
||||
_mulAdd = MulAddSpec(mul: mul, add: add)
|
||||
super.init(channels: Self.outChannels)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let inputSamples = _input.calculatedSamples(graph: graph, count: count)
|
||||
guard let ins = inputSamples.first else { return _result }
|
||||
|
||||
// TODO: replace this body with whatever per-channel processing you want.
|
||||
// The starter logic copies the first input row into every output row —
|
||||
// i.e. fans a mono source out to N identical channels. Real generators
|
||||
// typically produce different content per channel (panning, decoder
|
||||
// matrices, multi-bus routing, etc.).
|
||||
for ch: Int in 0..<Self.outChannels {
|
||||
for i: Int in 0..<count {
|
||||
_result[ch][i] = ins[i]
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>Top-level main.swift that renders a Lyrebird Synthesizer to disk via NRTDriver. NRT mode renders the full duration synchronously inside engine.start(). Drop this into the Sources directory of an executableTarget — Synthesizers must be added BEFORE start().</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird NRT Render (main.swift offline driver)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>25</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>main</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>File name:</string>
|
||||
<key>Description</key>
|
||||
<string>File name. Conventional Swift entry-point name is "main" for executableTargets.</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>main</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+55
@@ -0,0 +1,55 @@
|
||||
//___FILEHEADER___
|
||||
//
|
||||
// Top-level main.swift — drop this into an executableTarget's Sources directory.
|
||||
// NRT mode renders synchronously inside engine.start(); the call blocks until
|
||||
// `duration` seconds of audio have been written to `outputURL`.
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - Synthesizer
|
||||
|
||||
/// Replace this with your own Synthesizer. NRT renders whatever is in the engine
|
||||
/// at the moment `start()` is called — Synthesizers added later via
|
||||
/// `engine.add(_:)` will not be heard because the render loop has already exited.
|
||||
final class ___FILEBASENAMEASIDENTIFIER______Synth: SynthesizerBase {
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Audio(
|
||||
envelope: Envelope(
|
||||
levels: [0.0, 1.0, 0.6, 0.0],
|
||||
durations: [0.02, 0.46, 0.5],
|
||||
curves: [.lin, .exponential, .exponential]
|
||||
),
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let osc = OscSin.Audio(freq: 440.0) * env * 0.3
|
||||
output(bus: 0, source: Pan2(input: osc))
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Render
|
||||
|
||||
let outputURL: URL = URL(fileURLWithPath: "output.caf")
|
||||
let renderDuration: Double = 4.0
|
||||
let blockSize: Int = 512
|
||||
let sampleRate: Double = 44100
|
||||
let numOutputChannels: Int = 2
|
||||
|
||||
let engine = SynthesisEngine(
|
||||
blockSize: blockSize,
|
||||
sampleRate: sampleRate,
|
||||
numOutputChannels: numOutputChannels,
|
||||
numInputChannels: 0,
|
||||
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
|
||||
)
|
||||
|
||||
// Synthesizers must be added BEFORE start() — NRTDriver renders the full
|
||||
// duration synchronously inside start() and returns once the file is closed.
|
||||
do {
|
||||
try engine.add(___FILEBASENAMEASIDENTIFIER______Synth())
|
||||
try engine.start()
|
||||
print("Rendered \(renderDuration)s → \(outputURL.path)")
|
||||
} catch {
|
||||
fputs("Render failed: \(error)\n", stderr)
|
||||
exit(1)
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Lyrebird noise generator extending NoiseBase. Inherits rngState and _mulAdd, and uses the xorshift64 PRNG. Audio variant draws one sample per output sample; Control variant draws once per audio block and emits a linear ramp.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Noise Generator (NoiseBase subclass)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>14</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyNoise</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Noise name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the noise enum (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyNoise</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
//___FILEHEADER___
|
||||
//
|
||||
// In-tree template — drop this file under Sources/Lyrebird/Generators/Noise/.
|
||||
// Extends `NoiseBase`, whose designated init is module-internal, so this
|
||||
// template is not usable from a project that depends on Lyrebird as a package.
|
||||
// External users should start from the basic `LyrebirdGenerator` template and
|
||||
// declare rngState + xorshift64 inline.
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// Extends `NoiseBase` so `rngState: UInt64` and `_mulAdd` are inherited.
|
||||
/// Use `xorshift64Next(&rngState)` to draw a `[-1, 1]` sample per call.
|
||||
///
|
||||
/// Each instance is independently seeded — concurrent instances produce
|
||||
/// uncorrelated output.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let n = ___FILEBASENAMEASIDENTIFIER___.Audio()
|
||||
/// let n = ___FILEBASENAMEASIDENTIFIER___.Audio(seed: 42) // deterministic for tests
|
||||
/// ```
|
||||
public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
/// Shared PRNG state and output buffer for both rate variants.
|
||||
public class _Base: NoiseBase {
|
||||
|
||||
override init(
|
||||
initialRngState: UInt64,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(initialRngState: initialRngState, mul: mul, add: add)
|
||||
}
|
||||
|
||||
/// Draw one sample in `[-1, 1]`. Replace this body with any
|
||||
/// distribution-shaping logic — clip, fold, threshold, etc.
|
||||
func nextSample() -> Double { xorshift64Next(&rngState) }
|
||||
}
|
||||
|
||||
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - seed: PRNG seed. Defaults to a time-derived value for unique instances.
|
||||
/// Pass an explicit seed for reproducible test output.
|
||||
/// - mul: Output multiplier applied after synthesis. Defaults to `1.0`.
|
||||
/// - add: Offset added after multiplier. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - seed: PRNG seed.
|
||||
/// - mul: Output multiplier.
|
||||
/// - add: Output offset.
|
||||
public init(
|
||||
seed: UInt64? = nil,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
// Pick a unique mix constant so this Audio variant doesn't correlate
|
||||
// with sibling Control / sibling generators when both default-seed
|
||||
// within the same nanosecond.
|
||||
let audioMixConstant: UInt64 = 0xA110_AAAA_5A5A_3C3C
|
||||
let initialRngState = lyrebirdSeedXorshift64(from: seed, mixConstant: audioMixConstant)
|
||||
super.init(initialRngState: initialRngState, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
for i: Int in 0..<count {
|
||||
_result[0][i] = nextSample()
|
||||
}
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-rate ___FILEBASENAMEASIDENTIFIER___ — draws one new value per
|
||||
/// audio block, emits a linear ramp to the new target. Override
|
||||
/// `calculatedSamples` bypasses the sub-block loop so the draw rate stays
|
||||
/// at one per audio block regardless of `controlBlockSize`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - seed: PRNG seed. Defaults to a time-derived value.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - seed: PRNG seed.
|
||||
/// - mul: Output multiplier.
|
||||
/// - add: Output offset.
|
||||
public init(
|
||||
seed: UInt64? = nil,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
let controlMixConstant: UInt64 = 0xB220_BBBB_A5A5_C3C3
|
||||
let initialRngState = lyrebirdSeedXorshift64(from: seed, mixConstant: controlMixConstant)
|
||||
super.init(initialRngState: initialRngState, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: one draw per audio block regardless of cbs.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let target: Double = nextSample()
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
|
||||
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
|
||||
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>An OSCServer setup factory that binds a UDP port, registers handlers for OSC address patterns (with glob/wildcard support), and returns a started server. Handler closures run on the lyrebird.osc.handlers queue — not the RT thread.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird OSC Handler (UDP server)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>32</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyOSCHandler</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>OSC handler name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the factory function (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyOSCHandler</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+73
@@ -0,0 +1,73 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Factory that opens a `OSCServer` on `port`, registers handlers for
|
||||
/// a few starter address patterns, and returns a started server.
|
||||
///
|
||||
/// Handler closures run on the `lyrebird.osc.handlers` dispatch queue — not
|
||||
/// the RT audio thread. From a handler you can:
|
||||
/// - Mutate `@LiveParam` slots on Synthesizers (atomic, RT-safe)
|
||||
/// - Call `engine.add(_:)` / `engine.remove(_:)` (lock-free)
|
||||
/// - Start / stop / pause `LyrebirdTask`s
|
||||
///
|
||||
/// `addHandler(address:)` accepts OSC 1.0 glob patterns:
|
||||
/// - `?` — any single character
|
||||
/// - `*` — any sequence excluding `/`
|
||||
/// - `[abc]` / `[a-z]` — character class
|
||||
/// - `{a,b}` — alternation
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let osc = try make___FILEBASENAMEASIDENTIFIER___(engine: engine, port: 57120)
|
||||
/// // …
|
||||
/// osc.stop()
|
||||
/// ```
|
||||
public func make___FILEBASENAMEASIDENTIFIER___(
|
||||
engine: SynthesisEngine,
|
||||
port: UInt16 = 57120
|
||||
) throws -> OSCServer {
|
||||
let server = OSCServer(port: port, engine: engine)
|
||||
|
||||
// /freq <float|int> → set a frequency parameter somewhere.
|
||||
server.addHandler(address: "/freq") { msg, _ in
|
||||
guard let arg = msg.arguments.first else { return }
|
||||
let hz = doubleValue(arg)
|
||||
// TODO: route `hz` to your Synthesizer's frequency @LiveParam.
|
||||
_ = hz
|
||||
}
|
||||
|
||||
// /amp <float|int> → set a gain parameter.
|
||||
server.addHandler(address: "/amp") { msg, _ in
|
||||
guard let arg = msg.arguments.first else { return }
|
||||
let gain = doubleValue(arg)
|
||||
// TODO: route `gain` (typically [0, 1]) to your master amplitude.
|
||||
_ = gain
|
||||
}
|
||||
|
||||
// /note/{on,off} → spawn / release voice synths.
|
||||
server.addHandler(address: "/note/{on,off}") { msg, _ in
|
||||
// Inspect msg.address to branch; arguments are [note: Int32, vel: Float].
|
||||
// TODO: spawn / release a voice synth.
|
||||
_ = msg
|
||||
}
|
||||
|
||||
try server.start()
|
||||
return server
|
||||
}
|
||||
|
||||
// MARK: - Argument helpers
|
||||
|
||||
/// Coerce an `OSCArgument` to `Double` for parameter assignment.
|
||||
/// Returns `0.0` for non-numeric types.
|
||||
private func doubleValue(_ arg: OSCArgument) -> Double {
|
||||
switch arg {
|
||||
case .int32(let v): return Double(v)
|
||||
case .float32(let v): return Double(v)
|
||||
case .bool(let v): return v ? 1.0 : 0.0
|
||||
default: return 0.0
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Lyrebird oscillator extending OscillatorBase (in-tree only — extends a module-internal base). Drop this file under Sources/Lyrebird/Generators/Oscillators/. Inherits _phase, _freqInput, _freqIsGenerator, and _mulAdd. Audio variant evaluates phase per sample; Control variant advances phase once per audio block via _calculatedSamplesBlockRate.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Oscillator (OscillatorBase subclass)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>13</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyOsc</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Oscillator name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the oscillator enum (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyOsc</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+177
@@ -0,0 +1,177 @@
|
||||
//___FILEHEADER___
|
||||
//
|
||||
// In-tree template — drop this file under Sources/Lyrebird/Generators/Oscillators/.
|
||||
// Extends `OscillatorBase`, whose designated init is module-internal, so this
|
||||
// template is not usable from a project that depends on Lyrebird as a package.
|
||||
// External users should start from the basic `LyrebirdGenerator` template and
|
||||
// declare phase / freq / MulAddSpec inline.
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// Extends `OscillatorBase` so the standard `_phase` / `_freqInput` /
|
||||
/// `_freqIsGenerator` / `_mulAdd` fields are inherited — no need to redeclare them.
|
||||
/// `super.init(freq:phase:mul:add:)` normalises `phase` into `[0, 1)`.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let osc = ___FILEBASENAMEASIDENTIFIER___.Audio(freq: 440.0)
|
||||
/// let lfo = ___FILEBASENAMEASIDENTIFIER___.Control(freq: 2.0)
|
||||
/// ```
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Frequency in Hz. No internal clamping; aliasing increases toward Nyquist.
|
||||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public enum ___FILEBASENAMEASIDENTIFIER___ {
|
||||
|
||||
/// Shared base — inherits all oscillator state from `OscillatorBase`.
|
||||
public class _Base: OscillatorBase {}
|
||||
|
||||
/// Per-sample waveform function. Replace the formula below — `phase` is in
|
||||
/// `[0, 1)`, output should typically be `[-1, 1]`.
|
||||
@inline(__always)
|
||||
static func _waveform(_ phase: Double) -> Double {
|
||||
// Default: sawtooth. Replace with your formula.
|
||||
return 2.0 * phase - 1.0
|
||||
}
|
||||
|
||||
/// Audio-rate ___FILEBASENAMEASIDENTIFIER___. Evaluates frequency per sample.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Frequency in Hz. No internal clamping.
|
||||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Audio: _Base, AudioGenerator {
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Frequency in Hz. No internal clamping.
|
||||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput,
|
||||
phase: Double = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, phase: phase, mul: mul, add: add)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let sampleRate = Double(graph.engine.sampleRate)
|
||||
|
||||
let freqSamples: [Double]?
|
||||
let scalarDt: Double
|
||||
if _freqIsGenerator {
|
||||
freqSamples = _freqInput.calculatedSamples(graph: graph, count: count).first
|
||||
scalarDt = 0
|
||||
} else {
|
||||
freqSamples = nil
|
||||
scalarDt = _freqInput.floatValue(graph: graph) / sampleRate
|
||||
}
|
||||
|
||||
for i: Int in 0..<count {
|
||||
let dt: Double
|
||||
if let fs: [Double] = freqSamples {
|
||||
dt = (i < fs.count ? fs[i] : 0) / sampleRate
|
||||
} else {
|
||||
dt = scalarDt
|
||||
}
|
||||
|
||||
_result[0][i] = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
|
||||
|
||||
_phase += dt
|
||||
if _phase >= 1.0 { _phase -= 1.0 }
|
||||
else if _phase < 0.0 { _phase += 1.0 }
|
||||
if _phase >= 1.0 || _phase < 0.0 {
|
||||
_phase = _phase.truncatingRemainder(dividingBy: 1.0)
|
||||
if _phase < 0.0 { _phase += 1.0 }
|
||||
}
|
||||
}
|
||||
|
||||
_mulAdd.applyIfNeeded(to: &_result, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
|
||||
/// Control-rate ___FILEBASENAMEASIDENTIFIER___. Advances phase once per audio block,
|
||||
/// emits a linear ramp toward the new target.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - freq: Frequency in Hz. No internal clamping.
|
||||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public final class Control: _Base, ControlGenerator {
|
||||
|
||||
public var previousOutputValue: Double = 0.0
|
||||
private var _rampTarget: Double = 0.0
|
||||
|
||||
/// - Parameters:
|
||||
/// - freq: Frequency in Hz. No internal clamping.
|
||||
/// - phase: Initial phase offset in normalized cycles `[0, 1)`. Defaults to `0.0`.
|
||||
/// - mul: Output multiplier. Defaults to `1.0`.
|
||||
/// - add: Output offset. Defaults to `0.0`.
|
||||
public override init(
|
||||
freq: any ValidGeneratorInput,
|
||||
phase: Double = 0.0,
|
||||
mul: any ValidGeneratorInput = 1.0,
|
||||
add: any ValidGeneratorInput = 0.0
|
||||
) {
|
||||
super.init(freq: freq, phase: phase, mul: mul, add: add)
|
||||
_setupSubBlockBuffer()
|
||||
}
|
||||
|
||||
// Bypass sub-block loop: phase advances exactly once per audio block.
|
||||
public func calculatedSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_calculatedSamplesBlockRate(graph: graph, count: count)
|
||||
}
|
||||
|
||||
public func _computeSamples(
|
||||
graph: SynthGraph,
|
||||
count: Int
|
||||
) -> [[Double]] {
|
||||
_checkCount(count)
|
||||
|
||||
let sampleRate = Double(graph.engine.sampleRate)
|
||||
let countFloat: Double = Double(count)
|
||||
|
||||
let freq: Double
|
||||
if _freqIsGenerator {
|
||||
freq = _freqInput.calculatedSamples(graph: graph, count: count).first?.first ?? 0
|
||||
} else {
|
||||
freq = _freqInput.floatValue(graph: graph)
|
||||
}
|
||||
|
||||
let dt = freq / sampleRate
|
||||
_phase += dt * countFloat
|
||||
normalizeLFPhase(&_phase)
|
||||
|
||||
let target = ___FILEBASENAMEASIDENTIFIER___._waveform(_phase)
|
||||
|
||||
let rampStart: Double = _rampTarget
|
||||
_rampTarget = target
|
||||
guard count > 0 else { return _result }
|
||||
previousOutputValue = fillRampedResult(
|
||||
into: &_result, from: rampStart, to: target, mulAdd: _mulAdd, graph: graph, count: count)
|
||||
return _result
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
extension ___FILEBASENAMEASIDENTIFIER___: GeneratorEnum {
|
||||
public typealias AudioType = ___FILEBASENAMEASIDENTIFIER___.Audio
|
||||
public typealias ControlType = ___FILEBASENAMEASIDENTIFIER___.Control
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A LyrebirdProcess factory function. Returns a configured process with an envelope-governed lifetime, an async body closure that adds synths and waits, and optional onRelease / onFinished callbacks. Equivalent to SuperCollider's ProcMod.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Process (envelope-governed audio process)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>34</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyProcess</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Process name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the process factory function (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyProcess</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+90
@@ -0,0 +1,90 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Factory for a self-contained `LyrebirdProcess`. The process allocates a
|
||||
/// private route bus, spawns an envelope-driven synth that mixes from that
|
||||
/// bus to `procOut`, and runs the `body` closure on an async task.
|
||||
///
|
||||
/// Lyrebird equivalent of SuperCollider's `ProcMod`.
|
||||
///
|
||||
/// ## Lifecycle
|
||||
/// 1. `play(engine:)` — allocate resources, start the envelope + body task.
|
||||
/// 2. While running — add synths via `ctx.add(_:)`, wait via `ctx.wait(_:)`,
|
||||
/// mutate `amp` from any thread.
|
||||
/// 3. `release()` — open the envelope gate; tail plays out, process auto-frees.
|
||||
/// (Only meaningful when the envelope has a `releaseNode`.)
|
||||
/// 4. `kill()` — force teardown regardless of envelope state.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let factory = ___FILEBASENAMEASIDENTIFIER___()
|
||||
/// let proc = factory.createProcess()
|
||||
/// proc.play(engine: engine)
|
||||
/// // …
|
||||
/// proc.release() // graceful — runs the envelope tail
|
||||
/// // or: proc.kill() // immediate
|
||||
/// ```
|
||||
public struct ___FILEBASENAMEASIDENTIFIER___: LyrebirdProcessFactory {
|
||||
|
||||
public init() {}
|
||||
|
||||
public func createProcess() -> LyrebirdProcess {
|
||||
LyrebirdProcess(
|
||||
id: "___FILEBASENAMEASIDENTIFIER___",
|
||||
envelope: Envelope(
|
||||
// 4-point envelope: attack → sustain → release → silence.
|
||||
// releaseNode index 2 means "hold at level[2] until release() is called",
|
||||
// then continue from there to the end.
|
||||
levels: [0.0, 1.0, 0.6, 0.0],
|
||||
durations: [0.05, 0.5, 1.5],
|
||||
curves: [.sine, .exponential, .exponential],
|
||||
releaseNode: 2
|
||||
),
|
||||
amp: 0.8,
|
||||
ampLag: 0.02,
|
||||
numChannels: 2,
|
||||
procOut: 0, // hardware output; overridden by a parent EventList
|
||||
target: .tail,
|
||||
body: { ctx in
|
||||
// The process body runs as an async Task. Schedule synths and
|
||||
// wait between events. The task is cancelled on `release()` /
|
||||
// `kill()` — `ctx.wait` re-throws CancellationError, which the
|
||||
// surrounding LyrebirdProcess infrastructure handles cleanly.
|
||||
//
|
||||
// Replace the starter body below with your event sequence.
|
||||
let synth: ExampleNote = ExampleNote()
|
||||
ctx.add(synth)
|
||||
await ctx.wait(0.1) // let the attack settle
|
||||
},
|
||||
onRelease: { ctx in
|
||||
// Optional. Called on main thread when release() is invoked,
|
||||
// before the envelope tail begins. Use to mutate / remove synths
|
||||
// before the fade.
|
||||
_ = ctx
|
||||
},
|
||||
onFinished: {
|
||||
// Optional. Called on main thread after the group and route bus
|
||||
// are freed. Resources are already gone — no context available.
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Example Synthesizer used by the process body
|
||||
|
||||
/// Replace this stub with your own Synthesizer. The body closure above adds
|
||||
/// one instance; rewrite the body to schedule whatever pattern fits your
|
||||
/// process.
|
||||
private final class ExampleNote: SynthesizerBase {
|
||||
|
||||
@LiveParam var frequency: Double = 440.0
|
||||
|
||||
override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: osc * 0.5)
|
||||
}
|
||||
}
|
||||
Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdSpectralProcessor.xctemplate/TemplateInfo.plist
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A SpectralProcessor — transforms a SpectralBuffer in-place after each FFT hop. Runs on the RT thread; mutate magnitude/phase per bin with no allocation, no locking. Use with SpectralChain.Audio as a .mono stage.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Spectral Processor (FFT-domain transform)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>30</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MySpectralProcessor</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>SpectralProcessor name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the SpectralProcessor class (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MySpectralProcessor</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// A `SpectralProcessor` transforms the FFT-domain `SpectralBuffer`
|
||||
/// in-place after each forward-FFT hop. Wire it into a `SpectralChain.Audio`
|
||||
/// as a `.mono` stage:
|
||||
///
|
||||
/// ```swift
|
||||
/// let proc = ___FILEBASENAMEASIDENTIFIER___()
|
||||
/// let chain = SpectralChain.Audio(
|
||||
/// input: source,
|
||||
/// fftSize: 2048,
|
||||
/// stages: [.mono(proc)]
|
||||
/// )
|
||||
/// output(bus: 0, source: chain)
|
||||
/// ```
|
||||
///
|
||||
/// ## RT contract
|
||||
///
|
||||
/// `process(spectral:)` runs on the RT thread. It must:
|
||||
/// - Not allocate
|
||||
/// - Not lock
|
||||
/// - Not call into Foundation / Swift stdlib methods that may allocate
|
||||
///
|
||||
/// Read parameters from `@LiveParam` slots on a Synthesizer that owns this
|
||||
/// processor — those reads are atomic and RT-safe.
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: SpectralProcessor {
|
||||
|
||||
// MARK: - Configuration
|
||||
|
||||
/// Internal state that controls the spectral transform. Mutate from non-RT
|
||||
/// threads via atomic operations or `@LiveParam`-style projections.
|
||||
private var _someParameter: Double = 1.0
|
||||
|
||||
// MARK: - Init
|
||||
|
||||
public init() {
|
||||
// No allocation paths should run after this point on the RT thread.
|
||||
}
|
||||
|
||||
// MARK: - SpectralProcessor
|
||||
|
||||
public func process(spectral: SpectralBuffer, engine: SynthesisEngine) {
|
||||
// Walk every bin in the half-spectrum [0, binCount). DC and Nyquist
|
||||
// are real-only — phase at those bins is undefined.
|
||||
//
|
||||
// The starter body below applies a uniform magnitude scale to every
|
||||
// bin. Replace with your transform (spectral filtering, formant shift,
|
||||
// freezing, cross-synthesis, etc.). The subscripts compile to direct
|
||||
// memory reads/writes through the buffer's pre-allocated storage.
|
||||
for bin in 0..<spectral.binCount {
|
||||
let mag = spectral[magnitude: bin]
|
||||
spectral[magnitude: bin] = mag * Float(_someParameter)
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A Lyrebird Synthesizer subclassing SynthesizerBase with @LiveParam parameter slots and a build() body wiring a small signal graph to output bus 0. Pair with engine.add(_:) to start audio.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Synthesizer (SynthesizerBase + @LiveParam)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>11</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MySynth</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Synthesizer name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the Synthesizer subclass (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MySynth</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Sources/LyrebirdCLI/Resources/XcodeTemplates/LyrebirdSynthesizer.xctemplate/___FILEBASENAME___.swift
Vendored
+41
@@ -0,0 +1,41 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// Subclasses `SynthesizerBase`. `@LiveParam` slots are atomic, RT-safe to
|
||||
/// assign from any thread; the audio thread reads them with acquiring loads.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let synth = ___FILEBASENAMEASIDENTIFIER___()
|
||||
/// try engine.add(synth)
|
||||
///
|
||||
/// // Mutate while audio runs — no try, no throws.
|
||||
/// synth.frequency = 880.0
|
||||
///
|
||||
/// engine.remove(synth)
|
||||
/// ```
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Fundamental frequency in Hz.
|
||||
@LiveParam public var frequency: Double = 440.0
|
||||
|
||||
/// Output amplitude (linear gain). `0.0` = silence, `1.0` = unity.
|
||||
@LiveParam public var amplitude: Double = 0.25
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
public override func build() {
|
||||
// Wire the signal graph here. Use `$paramName` (projected value) to
|
||||
// pass a LiveParam as a generator input — it tracks runtime changes.
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: osc * $amplitude)
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A SynthesizerBase subclass with @UIParam slots — exposes parameters that bind to ParameterKnob / ParameterSlider in SwiftUI. Includes a starter build() with sine + Pan2. Pair with a SwiftUI view that takes the synth and reads synth.$paramName for each control. Requires LyrebirdUI module.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Synthesizer (UI-bindable @UIParam)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>22</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyUISynth</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Synthesizer name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the Synthesizer subclass (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyUISynth</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// One-line description of ___FILEBASENAMEASIDENTIFIER___.
|
||||
///
|
||||
/// `@UIParam` slots expose both an atomic RT-safe parameter (like `@LiveParam`)
|
||||
/// AND a `UIParamNode` projected value that binds directly to SwiftUI controls
|
||||
/// in the LyrebirdUI module — `ParameterKnob`, `ParameterSlider`, `ParameterXY`.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let synth = ___FILEBASENAMEASIDENTIFIER___()
|
||||
/// try engine.add(synth)
|
||||
///
|
||||
/// // In a SwiftUI View:
|
||||
/// VStack {
|
||||
/// ParameterKnob("Freq", node: synth.$frequency, range: 110...880)
|
||||
/// ParameterKnob("Amp", node: synth.$amplitude, range: 0...1)
|
||||
/// ParameterKnob("Pan", node: synth.$pan, range: -1...1)
|
||||
/// }
|
||||
///
|
||||
/// // From code, mutate directly — atomic, RT-safe:
|
||||
/// synth.frequency = 660.0
|
||||
/// ```
|
||||
public final class ___FILEBASENAMEASIDENTIFIER___: SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
/// Fundamental frequency in Hz.
|
||||
@UIParam public var frequency: Double = 440.0
|
||||
|
||||
/// Output amplitude (linear gain). `0.0` = silence, `1.0` = unity.
|
||||
@UIParam public var amplitude: Double = 0.25
|
||||
|
||||
/// Stereo pan. `-1` = hard left, `0` = center, `+1` = hard right.
|
||||
@UIParam public var pan: Double = 0.0
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
public override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A LyrebirdTask factory function — emits a closure-bodied LyrebirdTask that schedules Synthesizer events on a background thread, with pause/resume/stop support. Use the LyrebirdRoutineContext to add nodes and wait between events.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird Task (scheduling factory)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>12</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MyTask</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>Task name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the task factory (also used as the file name). The factory function is named make<Name>().</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MyTask</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+61
@@ -0,0 +1,61 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import Foundation
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// Factory for a `LyrebirdTask` that runs a scheduled-event loop on its own
|
||||
/// background thread.
|
||||
///
|
||||
/// The task body receives a `LyrebirdRoutineContext` providing:
|
||||
/// - `add(_:)` — attach a Synthesizer to the engine
|
||||
/// - `wait(seconds:)` — sleep, respecting `pause()` / `stop()`
|
||||
/// - `wait(beats:tempo:)` — tempo-aware sleep
|
||||
///
|
||||
/// Throwing `LyrebirdRoutineError.stopped` (raised internally by `wait` when
|
||||
/// `stop()` is called) exits cleanly.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// let task = make___FILEBASENAMEASIDENTIFIER___()
|
||||
/// task.start(engine: engine)
|
||||
///
|
||||
/// task.pause() // freeze event stream
|
||||
/// task.resume() // continue from where it stopped
|
||||
/// task.stop() // exit the loop cleanly
|
||||
/// ```
|
||||
public func make___FILEBASENAMEASIDENTIFIER___() -> LyrebirdTask {
|
||||
LyrebirdTask { ctx in
|
||||
// Replace this with whatever event sequence the task should run.
|
||||
// The example below schedules one short Synthesizer every 250 ms
|
||||
// until `stop()` is called.
|
||||
while true {
|
||||
let note: ExampleNote = ExampleNote()
|
||||
ctx.add(note)
|
||||
try ctx.wait(seconds: 0.25)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Example Synthesizer used by the task
|
||||
|
||||
/// Minimal Synthesizer scheduled by `make___FILEBASENAMEASIDENTIFIER___`.
|
||||
/// Replace with your own Synthesizer type and remove this stub.
|
||||
private final class ExampleNote: SynthesizerBase {
|
||||
|
||||
@LiveParam var frequency: Double = 440.0
|
||||
|
||||
override func build() {
|
||||
let env = EnvelopeGen.Audio(
|
||||
envelope: Envelope(
|
||||
levels: [0.0, 1.0, 0.0],
|
||||
durations: [0.005, 0.2],
|
||||
curves: [.lin, .exponential]
|
||||
),
|
||||
doneAction: .freeNode
|
||||
)
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: osc * env * 0.2)
|
||||
}
|
||||
}
|
||||
+44
@@ -0,0 +1,44 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTD/PropertyList-1.0.dtd">
|
||||
<plist version="1.0">
|
||||
<dict>
|
||||
<key>Kind</key>
|
||||
<string>Xcode.IDEKit.TextSubstitutionFileTemplateKind</string>
|
||||
<key>Platforms</key>
|
||||
<array>
|
||||
<string>com.apple.platform.macosx</string>
|
||||
<string>com.apple.platform.iphoneos</string>
|
||||
</array>
|
||||
<key>Description</key>
|
||||
<string>A SwiftUI View bound to a SynthesizerBase subclass with @UIParam slots. Uses ParameterKnob to drive frequency / amplitude / pan and embeds a LyrebirdScopeView showing the engine's output. Requires LyrebirdUI module.</string>
|
||||
<key>Summary</key>
|
||||
<string>Lyrebird UI View (SwiftUI w/ ParameterKnob + Scope)</string>
|
||||
<key>SortOrder</key>
|
||||
<string>23</string>
|
||||
<key>AllowedTypes</key>
|
||||
<array>
|
||||
<string>public.swift-source</string>
|
||||
</array>
|
||||
<key>DefaultCompletionName</key>
|
||||
<string>MySynthView</string>
|
||||
<key>MainTemplateFile</key>
|
||||
<string>___FILEBASENAME___.swift</string>
|
||||
<key>Options</key>
|
||||
<array>
|
||||
<dict>
|
||||
<key>Identifier</key>
|
||||
<string>productName</string>
|
||||
<key>Required</key>
|
||||
<true/>
|
||||
<key>Name</key>
|
||||
<string>View name:</string>
|
||||
<key>Description</key>
|
||||
<string>Name of the SwiftUI View (also used as the file name).</string>
|
||||
<key>Type</key>
|
||||
<string>text</string>
|
||||
<key>Default</key>
|
||||
<string>MySynthView</string>
|
||||
</dict>
|
||||
</array>
|
||||
</dict>
|
||||
</plist>
|
||||
Vendored
+108
@@ -0,0 +1,108 @@
|
||||
//___FILEHEADER___
|
||||
|
||||
import SwiftUI
|
||||
import LyrebirdSynth
|
||||
import LyrebirdUI
|
||||
|
||||
// MARK: - ___FILEBASENAMEASIDENTIFIER___
|
||||
|
||||
/// SwiftUI view that drives a `SynthesizerBase` subclass with `@UIParam` slots
|
||||
/// and visualises its output via `LyrebirdScopeView`.
|
||||
///
|
||||
/// Owns a controller object that:
|
||||
/// 1. Holds the `SynthesisEngine` reference passed in.
|
||||
/// 2. Holds the synth (replace `MyUISynth` with your `@UIParam`-annotated
|
||||
/// synthesizer — see the `LyrebirdSynthesizer (UI)` file template).
|
||||
/// 3. Wires `engine.scopeTap` to a `ScopeCapture` so the scope view
|
||||
/// sees real audio.
|
||||
///
|
||||
/// ## Usage
|
||||
/// ```swift
|
||||
/// // In your App / scene root:
|
||||
/// ___FILEBASENAMEASIDENTIFIER___(engine: engine)
|
||||
/// ```
|
||||
public struct ___FILEBASENAMEASIDENTIFIER___: View {
|
||||
|
||||
@State private var controller: Controller
|
||||
|
||||
public init(engine: SynthesisEngine) {
|
||||
_controller = State(wrappedValue: Controller(engine: engine))
|
||||
}
|
||||
|
||||
public var body: some View {
|
||||
VStack(spacing: 20) {
|
||||
HStack {
|
||||
Text("___FILEBASENAMEASIDENTIFIER___").font(.headline)
|
||||
Spacer()
|
||||
Button(controller.isPlaying ? "Stop" : "Start") {
|
||||
controller.toggle()
|
||||
}
|
||||
.buttonStyle(.bordered)
|
||||
.tint(controller.isPlaying ? .red : .green)
|
||||
}
|
||||
|
||||
ParameterSlider(
|
||||
"Frequency",
|
||||
node: controller.synth.$frequency,
|
||||
range: 110...880
|
||||
)
|
||||
|
||||
HStack(spacing: 24) {
|
||||
ParameterKnob("Amplitude", node: controller.synth.$amplitude, range: 0...1)
|
||||
ParameterKnob("Pan", node: controller.synth.$pan, range: -1...1)
|
||||
}
|
||||
|
||||
Divider()
|
||||
LyrebirdStatusView(engine: controller.engine)
|
||||
Divider()
|
||||
LyrebirdScopeView(capture: controller.scope)
|
||||
.frame(height: 120)
|
||||
}
|
||||
.padding()
|
||||
}
|
||||
|
||||
// MARK: - Controller
|
||||
|
||||
/// Owns the synth, scope capture, and play/stop state. Lives for the
|
||||
/// lifetime of the view via `@State`.
|
||||
@Observable
|
||||
final class Controller {
|
||||
let engine: SynthesisEngine
|
||||
let synth: MyUISynth = MyUISynth()
|
||||
let scope: ScopeCapture
|
||||
var isPlaying: Bool = false
|
||||
|
||||
init(engine: SynthesisEngine) {
|
||||
self.engine = engine
|
||||
self.scope = ScopeCapture(buses: [0, 1], bufferSize: 2048)
|
||||
engine.scopeTap = scope
|
||||
}
|
||||
|
||||
func toggle() {
|
||||
if isPlaying {
|
||||
engine.remove(synth)
|
||||
} else {
|
||||
do { try engine.add(synth) } catch { print("[Lyrebird] engine.add failed: \(error)") }
|
||||
}
|
||||
isPlaying.toggle()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Placeholder synth (replace with your own)
|
||||
|
||||
/// Replace this with your own `@UIParam`-annotated SynthesizerBase subclass
|
||||
/// (generated from the `LyrebirdSynthesizer (UI)` template). The Controller
|
||||
/// above references it directly — keep the parameter names in sync, or rename
|
||||
/// the slot bindings above to match your synth.
|
||||
public final class MyUISynth: SynthesizerBase {
|
||||
|
||||
@UIParam public var frequency: Double = 440.0
|
||||
@UIParam public var amplitude: Double = 0.25
|
||||
@UIParam public var pan: Double = 0.0
|
||||
|
||||
public override func build() {
|
||||
let osc = OscSin.Audio(freq: $frequency)
|
||||
output(bus: 0, source: Pan2(input: osc * $amplitude, pan: $pan))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
// SynthExporter.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
// MARK: - SynthExporter
|
||||
|
||||
/// Exports a named `Synthesizer` subclass template to a Swift source file.
|
||||
///
|
||||
/// `lyrebird export <SynthName> [--to <path>]` generates a starter `.swift` file
|
||||
/// containing a concrete `SynthesizerBase` subclass with the given name. The
|
||||
/// generated file is ready to drop into any Lyrebird project's `Sources/` directory.
|
||||
///
|
||||
/// If `--to` is omitted, the file is written to `<SynthName>.swift` in the current
|
||||
/// working directory.
|
||||
///
|
||||
/// ## Generated file layout
|
||||
///
|
||||
/// ```
|
||||
/// import LyrebirdSynth
|
||||
///
|
||||
/// final class MySynth: SynthesizerBase {
|
||||
/// // MARK: - Parameters
|
||||
/// ...
|
||||
/// override func build() {
|
||||
/// ...
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
public enum SynthExporter {
|
||||
|
||||
// MARK: - Errors
|
||||
|
||||
/// Errors thrown by `SynthExporter`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// The synthesizer name is empty or not a valid Swift identifier.
|
||||
case invalidName(name: String)
|
||||
/// A file could not be written.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
/// A file already exists at the output path and would be overwritten.
|
||||
case fileExists(path: String)
|
||||
}
|
||||
|
||||
// MARK: - Public API
|
||||
|
||||
/// Export a Synthesizer template named `name` to `outputPath`.
|
||||
///
|
||||
/// - Parameters:
|
||||
/// - name: The Swift class name for the generated Synthesizer.
|
||||
/// Must be a valid, non-empty Swift identifier.
|
||||
/// - outputPath: Destination `.swift` file path.
|
||||
/// Defaults to `<name>.swift` in the current working directory.
|
||||
/// - overwrite: When `false` (default), throws `Error.fileExists` if the path
|
||||
/// is already occupied. Pass `true` to replace an existing file.
|
||||
/// - Throws: `SynthExporter.Error` on name validation failure or file system errors.
|
||||
public static func export(
|
||||
name: String,
|
||||
to outputPath: String? = nil,
|
||||
overwrite: Bool = false
|
||||
) throws {
|
||||
try validateName(name)
|
||||
|
||||
let resolvedPath: String = outputPath ?? defaultOutputPath(for: name)
|
||||
|
||||
if !overwrite && FileManager.default.fileExists(atPath: resolvedPath) {
|
||||
throw Error.fileExists(path: resolvedPath)
|
||||
}
|
||||
|
||||
let source: String = synthTemplate(name: name)
|
||||
do {
|
||||
try source.write(toFile: resolvedPath, atomically: true, encoding: .utf8)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: resolvedPath,
|
||||
reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Template
|
||||
|
||||
/// The Swift source template for a new Synthesizer named `name`.
|
||||
public static func synthTemplate(name: String) -> String {
|
||||
"""
|
||||
import LyrebirdSynth
|
||||
|
||||
// MARK: - \(name)
|
||||
|
||||
/// A Lyrebird synthesizer.
|
||||
///
|
||||
/// Add and wire generators in `build()`, then add this to a running engine:
|
||||
///
|
||||
/// ```swift
|
||||
/// let synth = \(name)()
|
||||
/// try engine.add(synth)
|
||||
/// ```
|
||||
final class \(name): SynthesizerBase {
|
||||
|
||||
// MARK: - Parameters
|
||||
|
||||
// Declare parameters here. Example:
|
||||
// let freq: Double = 440.0
|
||||
// let amp: Double = 0.5
|
||||
|
||||
// MARK: - Build
|
||||
|
||||
override func build() {
|
||||
// Wire your signal graph here. Example:
|
||||
// let osc = OscSin.Audio(freq: freq)
|
||||
// let env = EnvelopeGen(envelope: Envelope(
|
||||
// segmentCount: 2,
|
||||
// levels: [0.0, 1.0, 0.0],
|
||||
// durations: [0.01, 0.5]
|
||||
// ))
|
||||
// addOutputGenerator(osc * env)
|
||||
}
|
||||
}
|
||||
"""
|
||||
}
|
||||
|
||||
// MARK: - Helpers
|
||||
|
||||
/// Returns the default output file path: `<name>.swift` in the current directory.
|
||||
static func defaultOutputPath(for name: String) -> String {
|
||||
let cwd: String = FileManager.default.currentDirectoryPath
|
||||
return (cwd as NSString).appendingPathComponent("\(name).swift")
|
||||
}
|
||||
|
||||
/// Validate that `name` is a non-empty Swift-compatible identifier.
|
||||
///
|
||||
/// Allows letters, digits, and underscores; must not start with a digit.
|
||||
static func validateName(_ name: String) throws {
|
||||
try validateSwiftIdentifier(name, invalidNameError: Error.invalidName(name: name))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
// TemplateInstaller.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Foundation
|
||||
|
||||
/// Installs the bundled Lyrebird Xcode file templates into the user template
|
||||
/// directory so Xcode's New File dialog (⌘N) discovers them.
|
||||
///
|
||||
/// The templates ship as a copied SPM resource on the `LyrebirdCLI` target —
|
||||
/// `Bundle.module.resourceURL.appendingPathComponent("XcodeTemplates")` resolves
|
||||
/// to the directory holding every `.xctemplate` bundle.
|
||||
///
|
||||
/// User template destination:
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
///
|
||||
/// Apple guarantees this path is the user-scoped template scan root used by
|
||||
/// every recent Xcode version. No Xcode restart is required — the dialog
|
||||
/// rescans on next open.
|
||||
public enum TemplateInstaller {
|
||||
|
||||
/// Errors thrown by `install` / `uninstall`.
|
||||
public enum Error: Swift.Error, Equatable {
|
||||
/// Resource bundle did not contain the expected `XcodeTemplates` directory.
|
||||
/// Indicates a build configuration problem, not a user error.
|
||||
case bundleMissingTemplates(expectedPath: String)
|
||||
/// Destination exists already and `force` was `false`.
|
||||
case destinationExists(path: String)
|
||||
/// Underlying `FileManager` error wrapped with the path that failed.
|
||||
case fileSystemError(path: String, reason: String)
|
||||
}
|
||||
|
||||
/// Subdirectory name inside the LyrebirdCLI resource bundle.
|
||||
static let resourceSubdir: String = "XcodeTemplates"
|
||||
|
||||
/// Last path component under the user's Xcode template dir. The "File Templates"
|
||||
/// parent is fixed by Xcode; only this trailing segment is owned by Lyrebird and
|
||||
/// can therefore be safely removed by `uninstall`.
|
||||
public static let installDirName: String = "Lyrebird"
|
||||
|
||||
/// `~/Library/Developer/Xcode/Templates/File Templates/Lyrebird/`
|
||||
public static var destinationURL: URL {
|
||||
FileManager.default.homeDirectoryForCurrentUser
|
||||
.appendingPathComponent("Library/Developer/Xcode/Templates/File Templates/\(installDirName)", isDirectory: true)
|
||||
}
|
||||
|
||||
/// Resolves `Bundle.module`'s `XcodeTemplates` resource subdir, or throws if missing.
|
||||
static func sourceURL() throws -> URL {
|
||||
guard let resourceURL: URL = Bundle.module.resourceURL else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: "<no resourceURL>")
|
||||
}
|
||||
let candidate: URL = resourceURL.appendingPathComponent(resourceSubdir, isDirectory: true)
|
||||
guard FileManager.default.fileExists(atPath: candidate.path) else {
|
||||
throw Error.bundleMissingTemplates(expectedPath: candidate.path)
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
/// Lists the `.xctemplate` bundle names inside the source resource directory.
|
||||
public static func availableTemplates() throws -> [String] {
|
||||
let src: URL = try sourceURL()
|
||||
let contents: [String] = try FileManager.default.contentsOfDirectory(atPath: src.path)
|
||||
return contents.filter { $0.hasSuffix(".xctemplate") }.sorted()
|
||||
}
|
||||
|
||||
/// Copies every `.xctemplate` from the bundle to `destinationURL`.
|
||||
///
|
||||
/// - Parameter force: When `true`, overwrites an existing destination directory.
|
||||
/// When `false`, throws `Error.destinationExists` if the destination already
|
||||
/// exists. Per-template overwrite is unconditional once we've decided to write
|
||||
/// — `force` is the top-level guard.
|
||||
/// - Returns: Number of templates copied.
|
||||
@discardableResult
|
||||
public static func install(force: Bool = false) throws -> Int {
|
||||
let src: URL = try sourceURL()
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
|
||||
if fm.fileExists(atPath: dest.path) {
|
||||
if !force {
|
||||
throw Error.destinationExists(path: dest.path)
|
||||
}
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
// Recreate the destination dir.
|
||||
do {
|
||||
try fm.createDirectory(at: dest, withIntermediateDirectories: true)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
|
||||
// Copy each .xctemplate bundle.
|
||||
let templates: [String] = try availableTemplates()
|
||||
for name: String in templates {
|
||||
let from: URL = src.appendingPathComponent(name, isDirectory: true)
|
||||
let to: URL = dest.appendingPathComponent(name, isDirectory: true)
|
||||
do {
|
||||
try fm.copyItem(at: from, to: to)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: to.path, reason: error.localizedDescription)
|
||||
}
|
||||
}
|
||||
|
||||
return templates.count
|
||||
}
|
||||
|
||||
/// Removes the entire `~/Library/.../File Templates/Lyrebird/` directory.
|
||||
///
|
||||
/// - Returns: `true` if the directory existed and was removed; `false` if it
|
||||
/// was not installed.
|
||||
@discardableResult
|
||||
public static func uninstall() throws -> Bool {
|
||||
let dest: URL = destinationURL
|
||||
let fm: FileManager = FileManager.default
|
||||
guard fm.fileExists(atPath: dest.path) else { return false }
|
||||
do {
|
||||
try fm.removeItem(at: dest)
|
||||
} catch {
|
||||
throw Error.fileSystemError(path: dest.path, reason: error.localizedDescription)
|
||||
}
|
||||
return true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Version.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/// The current Lyrebird framework and CLI version.
|
||||
public let lyrebirdVersion: String = "1.0.0"
|
||||
|
||||
/// The banner printed when the interactive shell or REPL session starts.
|
||||
public let welcomeBanner: String = """
|
||||
Lyrebird \(lyrebirdVersion) — Swift audio synthesis
|
||||
Type 'help' for available commands, or 'repl' to start a Swift REPL session.
|
||||
"""
|
||||
Reference in New Issue
Block a user