v1.6.0 release: soundfile format expansion (WAV int depths + RF64 >4GB, AIFF/CAF, AAC/ALAC compressed, 4GB guard, unified AudioFileFormat)

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-22 17:45:34 -07:00
parent 62b2f5dbec
commit 8eb64f883f
33 changed files with 2650 additions and 352 deletions
@@ -46,7 +46,7 @@ window.open {
| ⌘E | Compile + run just the **selection**, always additively — adds it to whatever is already playing. No-op with no selection. Works in both Swift and Graph DSL modes. |
| Esc / F5 | Invoke code completion at the caret (Swift mode). Manual only — never auto-triggered on `.`. See the Code completion section below. |
| ⌥⌘F | **Format Code** — pretty-print the buffer with the toolchain's `swift-format`. No-op on a blank buffer; a parse error is logged to the console and leaves the text untouched. |
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to a CAF audio file offline instead of playing it live. Prompts for a path and a duration, renders faster-than-real-time via `NRTDriver`, and reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
| ⌥⌘R | **Render to File…** — bounce the selection (or the whole buffer) to an audio file offline instead of playing it live. The save dialog carries a **Format** popup (WAV 32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV for files past 4 GB, or compressed AAC / Apple Lossless `.m4a`) and a **Duration** field; it remembers the last format. Renders faster-than-real-time via `NRTDriver` at the live engine's sample rate and channel count, then reveals the file in Finder. Only **sample-clock** timing renders — see *NRT: sample-clock timing only* under Functional snippets & scheduling. |
The toolbar exposes both as buttons plus a `Clear Synths` button that calls
``LyrebirdScratchModel/clearTracked()`` — a full reset that removes both the
@@ -323,29 +323,19 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
}
@objc private func renderToFile(_ sender: Any?) {
// 1. Output path.
// Single save dialog: an accessory view carries the format popup + duration,
// and keeps the filename extension in sync with the chosen container.
let defaultRenderDuration: Double = 5.0
let panel: NSSavePanel = NSSavePanel()
if let caf: UTType = UTType(filenameExtension: "caf") {
panel.allowedContentTypes = [caf]
}
panel.nameFieldStringValue = "render.caf"
panel.message = "Render the snippet (or selection) to a CAF audio file"
guard panel.runModal() == .OK, let url: URL = panel.url else { return }
panel.message = "Render the snippet (or selection) to an audio file"
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
baseName: "render", initialDuration: defaultRenderDuration, savePanel: panel
)
panel.accessoryView = accessory
// 2. Duration.
let alert: NSAlert = NSAlert()
alert.messageText = "Render duration"
alert.informativeText = "Length to render, in seconds:"
let durationFieldWidth: CGFloat = 200
let durationFieldHeight: CGFloat = 24
let field: NSTextField = NSTextField(frame: NSRect(x: 0, y: 0, width: durationFieldWidth, height: durationFieldHeight))
field.stringValue = "5.0"
alert.accessoryView = field
alert.addButton(withTitle: "Render")
alert.addButton(withTitle: "Cancel")
guard alert.runModal() == .alertFirstButtonReturn else { return } // cancelled
guard let duration: Double = Double(field.stringValue.trimmingCharacters(in: .whitespaces)),
duration > 0 else {
guard panel.runModal() == .OK, let chosenURL: URL = panel.url else { return }
guard let duration: Double = accessory.durationSeconds else {
let invalid: NSAlert = NSAlert()
invalid.messageText = "Invalid duration"
invalid.informativeText = "Enter a positive number of seconds (e.g. 5.0)."
@@ -353,8 +343,15 @@ public final class LyrebirdScratchMenuController: NSObject, NSMenuItemValidation
return
}
let format: AudioFileFormat = accessory.selectedFormat
// This is the source of truth for the final extension: force it to match the
// chosen format so a hand-typed name with the wrong (or no) extension still
// produces a correctly-named file. (The accessory's own panel-name sync is a
// live-preview convenience; enforcement happens here.)
let url: URL = chosenURL.deletingPathExtension().appendingPathExtension(format.fileExtension)
Task { @MainActor in
let ok: Bool = await model.renderToFile(url: url, duration: duration)
let ok: Bool = await model.renderToFile(url: url, format: format, duration: duration)
if ok { NSWorkspace.shared.activateFileViewerSelecting([url]) }
}
}
@@ -553,14 +553,24 @@ public final class LyrebirdScratchModel: ObservableObject {
}
/// Render the current selection (or the whole buffer when nothing is
/// selected) to a CAF audio file, offline. Builds the snippet graph on a
/// selected) to an audio file, offline. Builds the snippet graph on a
/// throwaway engine driven by an `NRTDriver` — matching the live engine's
/// sample rate / channel count / bus layout — then renders `duration`
/// seconds off the main thread (`NRTDriver.start()` blocks). Logs the
/// outcome to the console.
///
/// - Parameters:
/// - url: Destination file. Its extension should match `format`.
/// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to
/// `.cafFloat32`. RF64/CAF are uncapped; plain WAV/AIFF throw past 4 GB.
/// - duration: Render length in seconds. Must be finite and > 0.
/// - Returns: `true` when the file was rendered (so the caller can reveal it).
@discardableResult
public func renderToFile(url: URL, duration: Double) async -> Bool {
public func renderToFile(
url: URL,
format: AudioFileFormat = .cafFloat32,
duration: Double
) async -> Bool {
guard !isCompiling else { return false }
guard duration > 0, duration.isFinite else {
appendConsole(.error, "Render duration must be a positive number of seconds.")
@@ -589,7 +599,7 @@ public final class LyrebirdScratchModel: ObservableObject {
numInputChannels: 0,
numAudioBuses: live.numAudioBuses,
numControlBuses: live.numControlBuses,
driver: NRTDriver(outputURL: url, duration: duration)
driver: NRTDriver(outputURL: url, duration: duration, format: format)
)
let offlineSession: LiveSession = LiveSession(engine: offline, attachScope: false)
do {
@@ -0,0 +1,186 @@
// RenderOptionsAccessory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import AppKit
import LyrebirdSynth
/// Accessory view embedded in the "Render to File" `NSSavePanel`: a container/encoding
/// popup and a duration field. Selecting a format rewrites the panel's filename
/// extension and remembers the choice (`UserDefaults`) so the next render defaults to it.
///
/// The sample rate and channel count are intentionally **not** exposed here — the
/// offline render mirrors the live engine (WYSIWYG with what was just heard).
@MainActor
final class RenderOptionsAccessory: NSView {
// MARK: - Format catalogue
/// One selectable output format. `token` is the persistence key (stable across
/// reordering / re-titling of the list, unlike a raw index or the display title).
private struct Option {
let title: String
let format: AudioFileFormat
let token: String
}
private static let options: [Option] = [
Option(title: "WAV — 32-bit float", format: .wavFloat32, token: "wavF32"),
Option(title: "WAV — 16-bit integer", format: .wavInt16, token: "wavI16"),
Option(title: "WAV — 24-bit integer", format: .wavInt24, token: "wavI24"),
Option(title: "AIFF — 32-bit float", format: .aiffFloat32, token: "aiffF32"),
Option(title: "CAF — 32-bit float (uncapped)", format: .cafFloat32, token: "cafF32"),
Option(title: "RF64 WAV — 32-bit float (>4 GB)", format: .rf64Float32, token: "rf64F32"),
Option(title: "RF64 WAV — 24-bit integer (>4 GB)", format: .rf64Int24, token: "rf64I24"),
Option(title: "AAC — 256 kbps (M4A)", format: .aacHigh, token: "aacHigh"),
Option(title: "AAC — 128 kbps (M4A)", format: .aacMedium, token: "aacMedium"),
Option(title: "Apple Lossless (M4A)", format: .alac, token: "alac"),
]
/// Persisted last-used format token. Defaults to CAF (the pre-accessory behaviour).
private static let defaultsKey: String = "com.lyrebird.scratch.renderFormatToken"
private static let fallbackToken: String = "cafF32"
// MARK: - Layout metrics
private static let accessoryWidth: CGFloat = 380
private static let accessoryHeight: CGFloat = 96
private static let contentMargin: CGFloat = 16
private static let gridSpacing: CGFloat = 8
private static let minDurationFieldWidth: CGFloat = 80
// MARK: - Subviews
private let formatPopup: NSPopUpButton = NSPopUpButton(frame: .zero, pullsDown: false)
private let durationField: NSTextField = NSTextField(frame: .zero)
private let baseName: String
private weak var savePanel: NSSavePanel?
// MARK: - Public read-out
/// The format for the currently selected popup item.
var selectedFormat: AudioFileFormat {
let index: Int = formatPopup.indexOfSelectedItem
guard index >= 0 && index < RenderOptionsAccessory.options.count else {
return .cafFloat32
}
return RenderOptionsAccessory.options[index].format
}
/// Parsed duration in seconds, or `nil` when the field is not a positive number.
var durationSeconds: Double? { RenderOptionsAccessory.parseDuration(durationField.stringValue) }
/// Parse a duration string to a positive, finite seconds value (or `nil`). Pure —
/// extracted so it can be unit-tested without the modal panel.
static func parseDuration(_ raw: String) -> Double? {
let trimmed: String = raw.trimmingCharacters(in: .whitespaces)
guard let value: Double = Double(trimmed), value > 0, value.isFinite else { return nil }
return value
}
// MARK: - Init
/// - Parameters:
/// - baseName: Filename stem (no extension); the format's extension is appended.
/// - initialDuration: Seconds pre-filled in the duration field.
/// - savePanel: The panel to keep the filename extension in sync with.
init(baseName: String, initialDuration: Double, savePanel: NSSavePanel) {
self.baseName = baseName
self.savePanel = savePanel
super.init(frame: NSRect(x: 0, y: 0,
width: RenderOptionsAccessory.accessoryWidth,
height: RenderOptionsAccessory.accessoryHeight))
let startIndex: Int = RenderOptionsAccessory.persistedIndex()
formatPopup.addItems(withTitles: RenderOptionsAccessory.options.map(\.title))
formatPopup.selectItem(at: startIndex)
formatPopup.target = self
formatPopup.action = #selector(formatChanged)
formatPopup.translatesAutoresizingMaskIntoConstraints = false
durationField.stringValue = String(format: "%.2f", initialDuration)
durationField.translatesAutoresizingMaskIntoConstraints = false
let formatLabel: NSTextField = RenderOptionsAccessory.makeLabel("Format:")
let durationLabel: NSTextField = RenderOptionsAccessory.makeLabel("Duration (s):")
let grid: NSGridView = NSGridView(views: [
[formatLabel, formatPopup],
[durationLabel, durationField],
])
grid.translatesAutoresizingMaskIntoConstraints = false
grid.rowSpacing = RenderOptionsAccessory.gridSpacing
grid.columnSpacing = RenderOptionsAccessory.gridSpacing
grid.column(at: 0).xPlacement = .trailing
addSubview(grid)
let margin: CGFloat = RenderOptionsAccessory.contentMargin
NSLayoutConstraint.activate([
grid.leadingAnchor.constraint(equalTo: leadingAnchor, constant: margin),
grid.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -margin),
grid.topAnchor.constraint(equalTo: topAnchor, constant: margin),
grid.bottomAnchor.constraint(equalTo: bottomAnchor, constant: -margin),
durationField.widthAnchor.constraint(
greaterThanOrEqualToConstant: RenderOptionsAccessory.minDurationFieldWidth),
])
// Seed the panel filename once from baseName + the initial format's extension.
savePanel.nameFieldStringValue = baseName + "." + selectedFormat.fileExtension
}
@available(*, unavailable)
required init?(coder: NSCoder) { fatalError("init(coder:) is not used") }
// MARK: - Actions
@objc private func formatChanged() {
syncPanelExtension()
let index: Int = formatPopup.indexOfSelectedItem
if index >= 0 && index < RenderOptionsAccessory.options.count {
UserDefaults.standard.set(RenderOptionsAccessory.options[index].token,
forKey: RenderOptionsAccessory.defaultsKey)
}
}
/// Re-extension the panel's current filename to match the selected format,
/// **preserving any stem the user typed** — only the extension is replaced.
private func syncPanelExtension() {
guard let panel: NSSavePanel = savePanel else { return }
let currentStem: String = (panel.nameFieldStringValue as NSString).deletingPathExtension
let stem: String = currentStem.isEmpty ? baseName : currentStem
panel.nameFieldStringValue = stem + "." + selectedFormat.fileExtension
}
/// Test seam: select a format by index as if the user picked it from the popup
/// (fires the same `formatChanged` side effects — panel re-extension + persistence).
func selectFormatForTesting(at index: Int) {
formatPopup.selectItem(at: index)
formatChanged()
}
/// Test seam: clear the persisted last-format so a test can start from the
/// default and not leak state into other tests or the real app.
static func clearPersistedFormatForTesting() {
UserDefaults.standard.removeObject(forKey: defaultsKey)
}
// MARK: - Helpers
private static func persistedIndex() -> Int {
let token: String = UserDefaults.standard.string(forKey: defaultsKey) ?? fallbackToken
if let index: Int = options.firstIndex(where: { $0.token == token }) { return index }
return options.firstIndex(where: { $0.token == fallbackToken }) ?? 0
}
private static func makeLabel(_ text: String) -> NSTextField {
let label: NSTextField = NSTextField(labelWithString: text)
label.translatesAutoresizingMaskIntoConstraints = false
return label
}
}
#endif
@@ -0,0 +1,105 @@
// RenderOptionsAccessoryTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
#if os(macOS)
import Testing
import AppKit
import LyrebirdSynth
@testable import LyrebirdLiveCompileUI
// Serialized: these tests mutate a shared `UserDefaults` key (the persisted
// last-format), so they must not interleave.
@Suite("RenderOptionsAccessory", .serialized)
@MainActor
struct RenderOptionsAccessoryTests {
// Popup order (see RenderOptionsAccessory.options).
private let wavFloat32Index: Int = 0
private let wavInt24Index: Int = 2
private let rf64Float32Index: Int = 5
private func makeAccessory() -> (RenderOptionsAccessory, NSSavePanel) {
let panel: NSSavePanel = NSSavePanel()
let accessory: RenderOptionsAccessory = RenderOptionsAccessory(
baseName: "render", initialDuration: 5.0, savePanel: panel
)
return (accessory, panel)
}
// MARK: - Duration parsing
@Test("parseDuration accepts positive finite numbers and rejects the rest")
func durationParsing() {
#expect(RenderOptionsAccessory.parseDuration("5.0") == 5.0)
#expect(RenderOptionsAccessory.parseDuration(" 2.5 ") == 2.5)
#expect(RenderOptionsAccessory.parseDuration("0") == nil)
#expect(RenderOptionsAccessory.parseDuration("-1") == nil)
#expect(RenderOptionsAccessory.parseDuration("") == nil)
#expect(RenderOptionsAccessory.parseDuration("abc") == nil)
#expect(RenderOptionsAccessory.parseDuration("nan") == nil)
#expect(RenderOptionsAccessory.parseDuration("inf") == nil)
}
// MARK: - Format read-out
@Test("Selecting a format updates selectedFormat")
func selectedFormatReflectsPopup() {
RenderOptionsAccessory.clearPersistedFormatForTesting()
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
let (accessory, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
accessory.selectFormatForTesting(at: wavFloat32Index)
#expect(accessory.selectedFormat == .wavFloat32)
accessory.selectFormatForTesting(at: wavInt24Index)
#expect(accessory.selectedFormat == .wavInt24)
accessory.selectFormatForTesting(at: rf64Float32Index)
#expect(accessory.selectedFormat == .rf64Float32)
}
// MARK: - Panel filename sync
@Test("Changing format preserves a user-typed filename stem")
func formatChangePreservesUserStem() {
RenderOptionsAccessory.clearPersistedFormatForTesting()
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
// User renames the target, then switches format.
panel.nameFieldStringValue = "mySound.caf"
accessory.selectFormatForTesting(at: wavFloat32Index)
#expect(panel.nameFieldStringValue == "mySound.wav")
// Switching again keeps the stem, swaps only the extension.
accessory.selectFormatForTesting(at: rf64Float32Index)
#expect(panel.nameFieldStringValue == "mySound.wav") // RF64 keeps .wav
}
@Test("Empty filename falls back to the base name")
func emptyStemFallsBackToBaseName() {
RenderOptionsAccessory.clearPersistedFormatForTesting()
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
let (accessory, panel): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
panel.nameFieldStringValue = ""
accessory.selectFormatForTesting(at: wavInt24Index)
#expect(panel.nameFieldStringValue == "render.wav")
}
// MARK: - Persistence
@Test("Last-selected format persists to a fresh accessory")
func formatSelectionPersists() {
RenderOptionsAccessory.clearPersistedFormatForTesting()
defer { RenderOptionsAccessory.clearPersistedFormatForTesting() }
let (first, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
first.selectFormatForTesting(at: rf64Float32Index) // persists "rf64F32"
// A brand-new accessory should open on the remembered format.
let (second, _): (RenderOptionsAccessory, NSSavePanel) = makeAccessory()
#expect(second.selectedFormat == .rf64Float32)
}
}
#endif
@@ -93,6 +93,33 @@ struct ScratchModelRenderTests {
#expect(!ok)
#expect(!FileManager.default.fileExists(atPath: url.path))
}
/// The `format:` argument reaches the NRT driver: rendering to a WAV Int24 target
/// and an RF64 target produces files with the requested on-disk encoding.
@Test(arguments: [
(AudioFileFormat.wavInt24, "wav", UInt32(24), false),
(AudioFileFormat.rf64Float32, "wav", UInt32(32), true),
])
func rendersHonourFormat(format: AudioFileFormat, ext: String, bits: UInt32, isFloat: Bool) async throws {
let model: LyrebirdScratchModel = makeModel(text: "context.play { OscSin.Audio(freq: 440) * 0.1 }")
let url: URL = FileManager.default.temporaryDirectory
.appendingPathComponent("LBRenderTest-\(UUID().uuidString)").appendingPathExtension(ext)
defer { try? FileManager.default.removeItem(at: url) }
let ok: Bool = await model.renderToFile(url: url, format: format, duration: 0.1)
#expect(ok)
#expect(FileManager.default.fileExists(atPath: url.path))
var fileRef: ExtAudioFileRef?
#expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr)
let ref: ExtAudioFileRef = try #require(fileRef)
defer { ExtAudioFileDispose(ref) }
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
var size: UInt32 = UInt32(MemoryLayout<AudioStreamBasicDescription>.size)
#expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr)
#expect(asbd.mBitsPerChannel == bits)
#expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat)
}
}
#endif