From 8eb64f883f0bb9695f3ba533ea44f9eee63906c4 Mon Sep 17 00:00:00 2001 From: Joshua Parmenter Date: Wed, 22 Jul 2026 17:45:34 -0700 Subject: [PATCH] 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 --- .../LyrebirdLiveCompileUI.docc/LiveCoding.md | 2 +- .../LyrebirdScratchMenuController.swift | 41 +- .../LyrebirdScratchModel.swift | 16 +- .../RenderOptionsAccessory.swift | 186 +++++++++ .../RenderOptionsAccessoryTests.swift | 105 +++++ .../ScratchModelRenderTests.swift | 27 ++ RELEASES.md | 63 +++ Sources/Lyrebird/AudioDrivers/NRTDriver.swift | 192 +++++++--- .../Lyrebird/Buffers/AudioFileFormat.swift | 361 ++++++++++++++++++ .../Buffers/LyrebirdBufferFileIO.swift | 141 ++++--- Sources/Lyrebird/Buffers/RF64Writer.swift | 259 +++++++++++++ .../Lyrebird/Buffers/RF64WriterError.swift | 20 + Sources/Lyrebird/Engine/EngineHost.swift | 1 + Sources/Lyrebird/Engine/NRTJob.swift | 13 +- .../Generators/BufferIO/DiskOut.swift | 237 +++++++----- .../Generators/BufferIO/DiskOutError.swift | 5 + .../Generators/BufferIO/DiskOutFormat.swift | 91 +---- Sources/Lyrebird/Lyrebird.docc/NRTGuide.md | 43 ++- .../Lyrebird/Lyrebird.docc/ProcessSystem.md | 10 +- Sources/Lyrebird/Math/LyrebirdConstants.swift | 15 + .../Lyrebird/Process/LyrebirdEventList.swift | 25 +- .../Process/ProcessRecordingConfig.swift | 2 +- .../Buffers/AudioFileCompressedTests.swift | 177 +++++++++ .../Buffers/AudioFileFormatTests.swift | 278 ++++++++++++++ .../Buffers/RF64WriterTests.swift | 157 ++++++++ Tests/LyrebirdTests/DiskInOutTests.swift | 102 +++++ Tests/LyrebirdTests/EngineHostTests.swift | 39 ++ .../LyrebirdBufferFileIOTests.swift | 109 ++++++ Tests/LyrebirdTests/NRTDriverTests.swift | 209 ++++++++++ .../LyrebirdEventListRecordingTests.swift | 22 ++ docs/engine/multi-engine-host.md | 1 + docs/stdlib/generators.md | 14 +- docs/tooling/nrt-guide.md | 39 +- 33 files changed, 2650 insertions(+), 352 deletions(-) create mode 100644 LiveCompile/Sources/LyrebirdLiveCompileUI/RenderOptionsAccessory.swift create mode 100644 LiveCompile/Tests/LyrebirdLiveCompileUITests/RenderOptionsAccessoryTests.swift create mode 100644 Sources/Lyrebird/Buffers/AudioFileFormat.swift create mode 100644 Sources/Lyrebird/Buffers/RF64Writer.swift create mode 100644 Sources/Lyrebird/Buffers/RF64WriterError.swift create mode 100644 Tests/LyrebirdTests/Buffers/AudioFileCompressedTests.swift create mode 100644 Tests/LyrebirdTests/Buffers/AudioFileFormatTests.swift create mode 100644 Tests/LyrebirdTests/Buffers/RF64WriterTests.swift diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md index ed5ce50..0566ce1 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdLiveCompileUI.docc/LiveCoding.md @@ -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 diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift index f02c281..bf1026e 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchMenuController.swift @@ -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]) } } } diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift index a553d5c..057759c 100644 --- a/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/LyrebirdScratchModel.swift @@ -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 { diff --git a/LiveCompile/Sources/LyrebirdLiveCompileUI/RenderOptionsAccessory.swift b/LiveCompile/Sources/LyrebirdLiveCompileUI/RenderOptionsAccessory.swift new file mode 100644 index 0000000..7730b04 --- /dev/null +++ b/LiveCompile/Sources/LyrebirdLiveCompileUI/RenderOptionsAccessory.swift @@ -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 diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/RenderOptionsAccessoryTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/RenderOptionsAccessoryTests.swift new file mode 100644 index 0000000..f611bd3 --- /dev/null +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/RenderOptionsAccessoryTests.swift @@ -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 diff --git a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRenderTests.swift b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRenderTests.swift index 1fe9f95..5f764f9 100644 --- a/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRenderTests.swift +++ b/LiveCompile/Tests/LyrebirdLiveCompileUITests/ScratchModelRenderTests.swift @@ -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.size) + #expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr) + #expect(asbd.mBitsPerChannel == bits) + #expect((asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) == isFloat) + } } #endif diff --git a/RELEASES.md b/RELEASES.md index cde31e9..d6f764f 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -7,6 +7,69 @@ functionality in a backward-compatible way. --- +## 1.6.0 — Soundfile format expansion + +A minor release. Backward-compatible — the existing default write formats are +unchanged; everything here is additive. One shared `AudioFileFormat` enum now +drives every writer (`LyrebirdBuffer.write`, offline `NRTDriver` renders, and the +real-time `DiskOut.Audio` recorder). + +### New — audio output formats + +```swift +// Buffer / NRT / DiskOut (PCM): +try buf.write(to: url, format: .wavInt24, sampleRate: 48000) // 16 / 24-bit WAV +try buf.write(to: url, format: .aiffFloat32, sampleRate: 48000) // AIFF-C float +try buf.write(to: url, format: .cafFloat32, sampleRate: 48000) // CAF (uncapped) + +// Files past 4 GB — RF64/BW64, keeps the .wav extension: +try buf.write(to: url, format: .rf64Float32, sampleRate: 96000) +try buf.write(to: url, format: .rf64Int24, sampleRate: 96000) + +// Compressed .m4a — offline writers only (LyrebirdBuffer.write / NRTDriver): +try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps +try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps +try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless +``` + +- **WAV bit depths** — 16-bit and 24-bit signed-integer PCM alongside 32-bit float. +- **AIFF-C** and **CAF** float output across all writers. +- **RF64 / BW64** (EBU Tech 3306) — the 64-bit-sized WAV variant for files past the + 4 GB limit, written by Lyrebird's own `RF64Writer` (CoreAudio has no RF64 *writer*; + it reads them back fine). Opt-in `.rf64Float32` / `.rf64Int24`. +- **Compressed AAC + Apple Lossless** (`.m4a`) — encoded natively through + `ExtAudioFile`/`AudioConverter`, no third-party dependency. **Offline writers only** + (`LyrebirdBuffer.write`, `NRTDriver`); `DiskOut.Audio` streams PCM/RF64 only. (MP3 is + not offered — CoreAudio has no MP3 encoder.) +- **Selectable NRT output** — `NRTDriver` / `NRTJob` take a `format:` (default CAF/float, + unchanged), so offline renders and the multi-engine batch pool can bounce to any format. + +### New — large-file safety + +Plain WAV and AIFF-C carry 32-bit size fields (a 4 GB cap). A write projected past +that now **throws `fileTooLargeForContainer`** (buffer / NRT) or stops cleanly and sets +a pollable `fileTooLarge` flag (streaming `DiskOut`) instead of silently producing a +truncated file. CAF and RF64 are 64-bit-sized and uncapped. `NRTDriver` also validates +its `duration` (finite, non-negative) — `NRTDriverError.invalidDuration`. + +### New — Live Scratch: Render-to-File format picker + +The Scratch **Render to File** (⌥⌘R) save dialog now carries a **Format** popup (WAV +32-bit float / 16-bit / 24-bit, AIFF, CAF, RF64 WAV, and compressed AAC / Apple +Lossless) plus the duration field, folded into one dialog. It remembers the last +format. Sample rate and channel count still mirror the live engine. + +### Changed + +- **`DiskOutFormat` is deprecated** — it is now a type alias for `AudioFileFormat`. + Existing `DiskOutFormat.wavFloat32` / `.aiff` / etc. spellings keep compiling (with a + deprecation warning); migrate to `AudioFileFormat` directly. +- `LyrebirdEventList.record(directory:format:)` now takes an `AudioFileFormat`. Stem + recording is PCM/RF64 only — a compressed format is rejected with a logged message + (stems stream through `DiskOut`, which does not do compressed). + +--- + ## 1.5.0 — `LyrebirdRandom` + the Live Scratch editor grows up A minor release. Backward-compatible — new public API plus a wave of Live Scratch diff --git a/Sources/Lyrebird/AudioDrivers/NRTDriver.swift b/Sources/Lyrebird/AudioDrivers/NRTDriver.swift index f905dd4..0eeea64 100644 --- a/Sources/Lyrebird/AudioDrivers/NRTDriver.swift +++ b/Sources/Lyrebird/AudioDrivers/NRTDriver.swift @@ -7,11 +7,13 @@ import Foundation import AudioToolbox -/// Non-Real-Time audio driver. Renders synchronously to a CAF file. +/// Non-Real-Time audio driver. Renders synchronously to a soundfile in the +/// container/encoding chosen at init (``AudioFileFormat``, default `.cafFloat32`). /// `start()` blocks until rendering is complete — suitable for score/script workflows. public final class NRTDriver: AudioDriver { private let outputURL: URL + private let outputFormat: AudioFileFormat private let duration: Double // Optional soundfile fed into the engine as simulated hardware input. @@ -38,8 +40,13 @@ public final class NRTDriver: AudioDriver { public var triggerListener: TriggerListener? /// - Parameters: - /// - outputURL: Destination CAF file path. + /// - outputURL: Destination file path. The extension should match `format` + /// (`.caf` / `.wav` / `.aiff`); see ``AudioFileFormat/fileExtension``. /// - duration: Render duration in seconds. + /// - format: Container and PCM encoding for the output file. Defaults to + /// `.cafFloat32`. CAF is 64-bit-sized (no 4 GB cap) and carries any channel + /// count, so it suits long or multichannel offline renders; `.wavFloat32` / + /// `.aiffFloat32` / the integer WAV cases are available for interchange. /// - inputURL: Optional soundfile whose samples are written to the engine's input buses /// each block, as if they came from a microphone. Channels are mapped in order starting /// at input bus 0. The engine's `numInputChannels` must be ≥ the file's channel count @@ -50,11 +57,13 @@ public final class NRTDriver: AudioDriver { public init( outputURL: URL, duration: Double, + format: AudioFileFormat = .cafFloat32, inputURL: URL? = nil, inputStartOffset: Double = 0.0 ) { self.outputURL = outputURL + self.outputFormat = format self.duration = duration self.inputURL = inputURL self.inputStartOffset = max(0.0, inputStartOffset) @@ -128,54 +137,112 @@ public final class NRTDriver: AudioDriver { count: inputChannelCount) } + /// Render synchronously to the output file. + /// + /// - Throws: `NRTDriverError.invalidDuration` if `duration` is negative, NaN, + /// or infinite; `NRTDriverError.fileTooLargeForContainer` if a WAV/AIFF render + /// is projected past the 4 GB RIFF cap (use `.cafFloat32` for long renders); + /// or the file/IO error cases on create/write failure. For the `.rf64*` + /// formats, a ``RF64WriterError`` may surface instead of an `NRTDriverError`. public func start() throws { guard let engine: SynthesisEngine else { return } - // Create and configure an ExtAudioFile for CAF / 32-bit float interleaved output - var fileRef: ExtAudioFileRef? - var format: AudioStreamBasicDescription = AudioStreamBasicDescription( - mSampleRate: engine.sampleRate, - mFormatID: kAudioFormatLinearPCM, - mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, - mBytesPerPacket: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels), - mFramesPerPacket: 1, - mBytesPerFrame: lyrebirdBytesPerSample * UInt32(engine.numOutputChannels), - mChannelsPerFrame: UInt32(engine.numOutputChannels), - mBitsPerChannel: 32, - mReserved: 0 - ) - - var status: OSStatus = ExtAudioFileCreateWithURL( - outputURL as CFURL, - kAudioFileCAFType, - &format, - nil, - AudioFileFlags.eraseFile.rawValue, - &fileRef - ) - guard status == noErr, let fileRef: ExtAudioFileRef else { - throw NRTDriverError.cannotCreateFile(status) + // Validate duration before any Double→Int conversion: Int(_:) traps on a + // non-finite or out-of-range value, and a negative duration would make the + // render loop's `0..= 0, blocksDouble < Double(Int.max) else { + throw NRTDriverError.invalidDuration(duration) } - // Guarantee disposal even if an error is thrown mid-render. + + // Total render blocks — computed once and shared by the large-file guard and + // the render loop below, so the two can never drift out of sync. + let totalBlocks: Int = Int(blocksDouble) + + // Large-file guard: reject a WAV/AIFF render projected past the 4 GB RIFF/AIFF + // cap before opening the file, so we never emit a truncated/corrupt output. + // CAF is exempt. `projectedByteCount` (inside riffOverflow) saturates on + // overflow, so a frame count near Int.max still yields the correct decision. + let (projectedFrames, framesOverflow): (Int, Bool) = + totalBlocks.multipliedReportingOverflow(by: engine.blockSize) + let effectiveFrames: Int = framesOverflow ? Int.max : projectedFrames + if let overflow: (projected: Int, cap: Int) = outputFormat.riffOverflow( + frameCount: effectiveFrames, channels: engine.numOutputChannels + ) { + throw NRTDriverError.fileTooLargeForContainer( + projectedBytes: overflow.projected, cap: overflow.cap + ) + } + + // Dispose the input file regardless of which output backend construction (or + // the render) throws below — registered before backend selection so an early + // throw can't leak it. defer { - ExtAudioFileDispose(fileRef) if let ref: ExtAudioFileRef = inputFileRef { ExtAudioFileDispose(ref) } inputFileRef = nil } - // Set client format (same as file format — already float32 interleaved) - status = ExtAudioFileSetProperty( - fileRef, - kExtAudioFileProperty_ClientDataFormat, - UInt32(MemoryLayout.size), - &format - ) - guard status == noErr else { - throw NRTDriverError.cannotSetFormat(status) + // Choose the output backend: RF64Writer (hand-rolled 64-bit WAV) for the RF64 + // cases, else ExtAudioFile for CAF / WAV / AIFF. The engine renders Float32, so + // both back-ends receive native Float32 interleaved samples. + let rf64Writer: RF64Writer? = outputFormat.usesRF64Writer + ? try RF64Writer(url: outputURL, format: outputFormat, + sampleRate: engine.sampleRate, channels: engine.numOutputChannels) + : nil + + var extFileRef: ExtAudioFileRef? = nil + if rf64Writer == nil { + var fileFormat: AudioStreamBasicDescription = outputFormat.makeFileASBD( + sampleRate: engine.sampleRate, + channels: engine.numOutputChannels + ) + var createdRef: ExtAudioFileRef? + var status: OSStatus = ExtAudioFileCreateWithURL( + outputURL as CFURL, + outputFormat.audioFileTypeID, + &fileFormat, + nil, + AudioFileFlags.eraseFile.rawValue, + &createdRef + ) + guard status == noErr, let createdRef: ExtAudioFileRef else { + throw NRTDriverError.cannotCreateFile(status) + } + // Client format: always native Float32 interleaved. ExtAudioFile converts + // Float32 → int16/int24 on write for the integer WAV formats. + var clientFormat: AudioStreamBasicDescription = outputFormat.makeClientASBD( + sampleRate: engine.sampleRate, + channels: engine.numOutputChannels + ) + status = ExtAudioFileSetProperty( + createdRef, + kExtAudioFileProperty_ClientDataFormat, + UInt32(MemoryLayout.size), + &clientFormat + ) + guard status == noErr else { + ExtAudioFileDispose(createdRef) + throw NRTDriverError.cannotSetFormat(status) + } + // Compressed (AAC) formats: push the target bitrate into the encoder. + let encoderStatus: OSStatus = outputFormat.applyEncoderConfig(to: createdRef) + guard encoderStatus == noErr else { + ExtAudioFileDispose(createdRef) + throw NRTDriverError.cannotSetFormat(encoderStatus) + } + extFileRef = createdRef } - // Render loop — synchronous, no RT constraints - let totalBlocks: Int = Int(ceil(duration * engine.sampleRate / Double(engine.blockSize))) + // Guarantee disposal even if an error is thrown mid-render. + defer { + if let ref: ExtAudioFileRef = extFileRef { ExtAudioFileDispose(ref) } + try? rf64Writer?.close() // idempotent; explicit close below patches ds64 sizes + } + + // Render loop — synchronous, no RT constraints. `totalBlocks` was computed + // once above (shared with the large-file guard). let bs: Int = engine.blockSize let nch: Int = engine.numOutputChannels @@ -222,25 +289,35 @@ public final class NRTDriver: AudioDriver { } } - // Write interleaved block to file — check status; a failure means a corrupt - // or truncated file, so we throw rather than silently swallow the error. - let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in - let frameCount: UInt32 = UInt32(bs) - var bufList: AudioBufferList = AudioBufferList( - mNumberBuffers: 1, - mBuffers: AudioBuffer( - mNumberChannels: UInt32(nch), - mDataByteSize: UInt32(ptr.count * MemoryLayout.size), - mData: ptr.baseAddress + // Write interleaved block to file — a failure means a corrupt or truncated + // file, so we throw rather than silently swallow the error. + if let rf64Writer: RF64Writer { + try writeBuffer.withUnsafeBufferPointer { ptr in + try rf64Writer.writeFloat32Interleaved(ptr, frames: bs) + } + } else if let extFileRef: ExtAudioFileRef { + let writeStatus: OSStatus = writeBuffer.withUnsafeMutableBufferPointer { ptr in + let frameCount: UInt32 = UInt32(bs) + var bufList: AudioBufferList = AudioBufferList( + mNumberBuffers: 1, + mBuffers: AudioBuffer( + mNumberChannels: UInt32(nch), + mDataByteSize: UInt32(ptr.count * MemoryLayout.size), + mData: ptr.baseAddress + ) ) - ) - return ExtAudioFileWrite(fileRef, frameCount, &bufList) - } - guard writeStatus == noErr else { - throw NRTDriverError.writeFailed(writeStatus) + return ExtAudioFileWrite(extFileRef, frameCount, &bufList) + } + guard writeStatus == noErr else { + throw NRTDriverError.writeFailed(writeStatus) + } } } + // Patch the RF64 ds64 sizes now (idempotent with the defer) so the file is + // finalised before this method returns. + try rf64Writer?.close() + // Synchronous render is done and the freeWorker timer only starts after this // returns — emit any per-block event-drop warning here so it reaches the console // even if the process exits before that timer (or `stop()`) runs. @@ -267,4 +344,11 @@ public enum NRTDriverError: Error { case cannotSetInputClientFormat(OSStatus) case cannotSeekInputFile(OSStatus) case inputReadFailed(OSStatus) + /// `duration` was negative, NaN, or infinite. Pass a finite, non-negative value. + case invalidDuration(Double) + /// The render is projected to exceed the output container's 4 GB (32-bit size + /// field) limit. Only WAV/AIFF are capped; CAF is exempt. `projectedBytes` is + /// the estimated audio-data size, `cap` is `lyrebirdMaxRIFFBytes`. Re-run with + /// `format: .cafFloat32` (64-bit sizes, uncapped) or shorten the duration. + case fileTooLargeForContainer(projectedBytes: Int, cap: Int) } diff --git a/Sources/Lyrebird/Buffers/AudioFileFormat.swift b/Sources/Lyrebird/Buffers/AudioFileFormat.swift new file mode 100644 index 0000000..1c6324a --- /dev/null +++ b/Sources/Lyrebird/Buffers/AudioFileFormat.swift @@ -0,0 +1,361 @@ +// AudioFileFormat.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import AudioToolbox + +/// Container-and-encoding format shared by every Lyrebird soundfile writer: +/// ``LyrebirdBuffer/write(to:format:sampleRate:)`` (offline buffer dump), +/// ``DiskOut/Audio`` (real-time streaming recorder), and the NRT driver +/// (offline score render). +/// +/// Each case pins both the container (WAV / AIFF-C / CAF) and the PCM sample +/// encoding (Float32, or signed-integer 16/24-bit). Writers always hand +/// `ExtAudioFile` native-Float32 samples as the *client* format (see +/// `makeClientASBD(sampleRate:channels:)`) and let it convert to the *file* +/// format (`makeFileASBD(sampleRate:channels:)`) — so integer encodings cost +/// the caller nothing beyond selecting the case. +/// +/// ## Container notes +/// - **WAV** — little-endian, cross-platform standard. Supports Float32 and +/// signed-integer PCM. Classic RIFF caps total file size at 4 GB (32-bit size +/// fields); large renders should fall back to `.cafFloat32`. +/// - **AIFF-C** (`.aiffFloat32`) — big-endian by spec. Uses `kAudioFileAIFCType` +/// (not classic `kAudioFileAIFFType`, which is integer-only) so it can carry +/// Float32 while keeping the `.aiff` extension. Best restricted to ≤ 2 channels +/// for compatibility with legacy readers; also 4 GB-capped. +/// - **CAF** (`.cafFloat32`) — Apple's flexible container: any sample rate, any +/// channel count up to `lyrebirdMaxFileChannelCount`, 64-bit sizes (no 4 GB +/// cap). Default for buffer and NRT writes. +public enum AudioFileFormat: Sendable { + + // MARK: - WAV variants + + /// WAV container, 32-bit IEEE-754 float, little-endian. + case wavFloat32 + /// WAV container, 16-bit signed integer, little-endian. + case wavInt16 + /// WAV container, 24-bit signed integer (packed), little-endian. + case wavInt24 + + // MARK: - AIFF-C variants + + /// AIFF-C container, 32-bit IEEE-754 float, big-endian. + case aiffFloat32 + + // MARK: - CAF variants + + /// CAF container, 32-bit IEEE-754 float, little-endian. + case cafFloat32 + + // MARK: - RF64 / BW64 variants (64-bit-sized WAV, no 4 GB cap) + + /// RF64 (BW64) container, 32-bit IEEE-754 float, little-endian. WAV extension. + /// Emitted by ``RF64Writer`` (not `ExtAudioFile`); readable by CoreAudio. + case rf64Float32 + /// RF64 (BW64) container, 24-bit signed integer (packed), little-endian. + case rf64Int24 + + // MARK: - Compressed variants (M4A container — offline writers only) + + /// AAC in an M4A container, ~256 kbps. Lossy; **not sample-accurate** (encoder + /// priming/padding). Encoded by `ExtAudioFile`/`AudioConverter`. Offline writers + /// only (`LyrebirdBuffer.write`, `NRTDriver`); ``DiskOut/Audio`` rejects it. + case aacHigh + /// AAC in an M4A container, ~128 kbps. See ``aacHigh``. + case aacMedium + /// Apple Lossless (ALAC) in an M4A container, 24-bit source. Lossless of the + /// 24-bit-quantised signal. Offline writers only; ``DiskOut/Audio`` rejects it. + case alac + + // MARK: - Back-compat shorthands + + /// WAV / Float32. Alias for ``wavFloat32``. + public static let wav: AudioFileFormat = .wavFloat32 + /// AIFF-C / Float32. Alias for ``aiffFloat32``. + public static let aiff: AudioFileFormat = .aiffFloat32 + /// CAF / Float32. Alias for ``cafFloat32``. + public static let caf: AudioFileFormat = .cafFloat32 + + // MARK: - Derived properties + + /// AudioToolbox container type ID passed to `ExtAudioFileCreateWithURL`. + /// + /// Not meaningful for the RF64 cases (they are written by ``RF64Writer``, not + /// `ExtAudioFile`); those return `kAudioFileWAVEType` as an inert default. + public var audioFileTypeID: AudioFileTypeID { + switch self { + case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: + return kAudioFileWAVEType + case .aiffFloat32: + return kAudioFileAIFCType // AIFF-C: carries Float32; classic AIFF does not + case .cafFloat32: + return kAudioFileCAFType + case .aacHigh, .aacMedium, .alac: + return kAudioFileM4AType + } + } + + /// Filesystem extension for the output file (no leading dot). + public var fileExtension: String { + switch self { + case .wavFloat32, .wavInt16, .wavInt24, .rf64Float32, .rf64Int24: return "wav" + case .aiffFloat32: return "aiff" + case .cafFloat32: return "caf" + case .aacHigh, .aacMedium, .alac: return "m4a" + } + } + + /// Bits per sample in the *PCM* encoded file. Not meaningful for the compressed + /// cases (they carry no fixed per-sample bit width); returns `0` there. + public var fileBitsPerChannel: UInt32 { + switch self { + case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return 32 + case .wavInt16: return 16 + case .wavInt24, .rf64Int24: return 24 + case .aacHigh, .aacMedium, .alac: return 0 + } + } + + /// `true` when the file encoding is IEEE-754 float; `false` for signed-integer PCM + /// or a compressed codec. + public var isFloatEncoding: Bool { + switch self { + case .wavFloat32, .aiffFloat32, .cafFloat32, .rf64Float32: return true + case .wavInt16, .wavInt24, .rf64Int24, .aacHigh, .aacMedium, .alac: return false + } + } + + /// `true` when the container stores big-endian sample data (AIFF-C spec). + public var isBigEndian: Bool { + switch self { + case .aiffFloat32: + return true + case .wavFloat32, .wavInt16, .wavInt24, .cafFloat32, .rf64Float32, .rf64Int24, + .aacHigh, .aacMedium, .alac: + return false + } + } + + /// `true` for the compressed codecs (AAC, ALAC) — encoded by + /// `ExtAudioFile`/`AudioConverter` into an M4A container. + public var isCompressed: Bool { + switch self { + case .aacHigh, .aacMedium, .alac: + return true + case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32, + .rf64Float32, .rf64Int24: + return false + } + } + + /// Target AAC encode bitrate in bits/second, or `nil` for non-AAC formats. + public var aacBitrate: Int? { + switch self { + case .aacHigh: return aacHighBitrate + case .aacMedium: return aacMediumBitrate + case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32, + .rf64Float32, .rf64Int24, .alac: + return nil + } + } + + /// `true` when the container can address files larger than 4 GB. + /// + /// WAV (classic RIFF) and AIFF-C carry unsigned **32-bit** size fields, so + /// their total file size is capped at 4 GB (see `lyrebirdMaxRIFFBytes`). CAF + /// (64-bit sizes) and RF64/BW64 (64-bit sizes via the `ds64` chunk) have no such + /// cap. `ExtAudioFile` cannot emit RF64, so those cases are written by + /// ``RF64Writer`` — see ``usesRF64Writer``. + public var supportsLargeFiles: Bool { + switch self { + // CAF/RF64 are 64-bit-sized; the compressed M4A cases are not RIFF at all, + // so the 4 GB RIFF/AIFF guard never applies to them either. + case .cafFloat32, .rf64Float32, .rf64Int24, .aacHigh, .aacMedium, .alac: + return true + case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32: + return false + } + } + + /// `true` when this format is emitted by ``RF64Writer`` (hand-rolled 64-bit WAV) + /// rather than `ExtAudioFile`. The three soundfile writers branch on this. + public var usesRF64Writer: Bool { + switch self { + case .rf64Float32, .rf64Int24: + return true + case .wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32, + .aacHigh, .aacMedium, .alac: + return false + } + } +} + +// MARK: - Large-file guard + +extension AudioFileFormat { + + /// Projected on-disk audio-data size in bytes for `frameCount` interleaved + /// frames across `channels`, at this format's bit depth. Excludes container + /// header/metadata (accounted for by the slack baked into `lyrebirdMaxRIFFBytes`). + /// + /// Pure integer arithmetic — safe to evaluate for hypothetical sizes without + /// allocating anything. **Saturates to `Int.max` on overflow** rather than + /// trapping: any frame count large enough to overflow the byte product is, by + /// definition, far past any container cap, so a saturated value gives the guard + /// the correct "over cap" answer without a crash. + func projectedByteCount(frameCount: Int, channels: Int) -> Int { + let bytesPerSample: Int = Int(fileBitsPerChannel / bitsPerByte) + let (samples, sampleOverflow): (Int, Bool) = frameCount.multipliedReportingOverflow(by: channels) + if sampleOverflow { return Int.max } + let (bytes, byteOverflow): (Int, Bool) = samples.multipliedReportingOverflow(by: bytesPerSample) + return byteOverflow ? Int.max : bytes + } + + /// Returns `(projected, cap)` when writing `frameCount × channels` frames in + /// this format would overflow the container's addressable size, or `nil` when + /// the write fits (or the container is 64-bit — see ``supportsLargeFiles``). + /// + /// The single decision point behind both the `LyrebirdBuffer.write` and + /// `NRTDriver` large-file guards, so the guard reads off the format rather + /// than a hardcoded case list. + func riffOverflow(frameCount: Int, channels: Int) -> (projected: Int, cap: Int)? { + guard !supportsLargeFiles else { return nil } + let projected: Int = projectedByteCount(frameCount: frameCount, channels: channels) + return projected > lyrebirdMaxRIFFBytes ? (projected, lyrebirdMaxRIFFBytes) : nil + } +} + +// MARK: - ASBD factories (module-internal) + +/// Number of bits in a byte — names the `/ 8` in bytes-per-sample derivations. +private let bitsPerByte: UInt32 = 8 + +/// Encoder packet geometry (samples per packet) for the compressed codecs. +private let aacFramesPerPacket: UInt32 = 1024 +private let alacFramesPerPacket: UInt32 = 4096 + +/// AAC target bitrates (bits/second) for the two quality tiers. +private let aacHighBitrate: Int = 256_000 +private let aacMediumBitrate: Int = 128_000 + +extension AudioFileFormat { + + /// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM + /// with the case's bit depth, encoding flags, and endianness, interleaved + /// across `channels`. + /// + /// This is the descriptor handed to `ExtAudioFileCreateWithURL`. Pair it with + /// `makeClientASBD(sampleRate:channels:)` as the client format so + /// `ExtAudioFile` performs any Float32 → integer / endian conversion. + /// + /// - Parameters: + /// - sampleRate: Sample rate embedded in the file header, in Hz. + /// - channels: Interleaved channel count. Must be ≥ 1. + func makeFileASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { + // Compressed codecs (AAC / ALAC): the encoder fills in the packet geometry. + // We supply the format ID, channel count, sample rate, and frames-per-packet; + // `AudioConverter` (behind `ExtAudioFile`) computes the rest. + if isCompressed { + var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() + asbd.mSampleRate = sampleRate + asbd.mChannelsPerFrame = UInt32(channels) + // AAC vs ALAC: the AAC tiers carry a bitrate, ALAC does not. Deriving the + // codec from `aacBitrate` avoids a `switch self` with an unreachable + // default that could silently leave `mFormatID == 0` for a future case. + if aacBitrate != nil { + asbd.mFormatID = kAudioFormatMPEG4AAC + asbd.mFramesPerPacket = aacFramesPerPacket + } else { + asbd.mFormatID = kAudioFormatAppleLossless + asbd.mFramesPerPacket = alacFramesPerPacket + asbd.mFormatFlags = kAppleLosslessFormatFlag_24BitSourceData + } + return asbd + } + + let bytesPerSample: UInt32 = fileBitsPerChannel / bitsPerByte + let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channels) + + var flags: AudioFormatFlags = kAudioFormatFlagIsPacked + flags |= isFloatEncoding ? kAudioFormatFlagIsFloat : kAudioFormatFlagIsSignedInteger + if isBigEndian { flags |= kAudioFormatFlagIsBigEndian } + + return AudioStreamBasicDescription( + mSampleRate: sampleRate, + mFormatID: kAudioFormatLinearPCM, + mFormatFlags: flags, + mBytesPerPacket: bytesPerFrame, + mFramesPerPacket: 1, + mBytesPerFrame: bytesPerFrame, + mChannelsPerFrame: UInt32(channels), + mBitsPerChannel: fileBitsPerChannel, + mReserved: 0 + ) + } + + /// Build the *client* `AudioStreamBasicDescription`: always native-endian + /// Float32 interleaved across `channels`, independent of the file encoding. + /// + /// Every Lyrebird writer feeds `ExtAudioFile` Float32 samples; the file format + /// (from `makeFileASBD(sampleRate:channels:)`) drives the conversion. + /// + /// - Parameters: + /// - sampleRate: Sample rate, in Hz. Should match the file ASBD. + /// - channels: Interleaved channel count. Must be ≥ 1. + func makeClientASBD(sampleRate: Double, channels: Int) -> AudioStreamBasicDescription { + let bytesPerFrame: UInt32 = lyrebirdBytesPerSample * UInt32(channels) + return AudioStreamBasicDescription( + mSampleRate: sampleRate, + mFormatID: kAudioFormatLinearPCM, + mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, + mBytesPerPacket: bytesPerFrame, + mFramesPerPacket: 1, + mBytesPerFrame: bytesPerFrame, + mChannelsPerFrame: UInt32(channels), + mBitsPerChannel: lyrebirdBitsPerSample, + mReserved: 0 + ) + } +} + +// MARK: - Compressed encoder configuration + +extension AudioFileFormat { + + /// After an `ExtAudioFile` for a compressed format has been created and its client + /// (Float32) format set, push the target AAC bitrate into the underlying + /// `AudioConverter`. No-op for non-AAC formats (ALAC has no bitrate; PCM has none). + /// + /// Returns `noErr` on success (or when nothing needed doing), else the failing + /// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`. + func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus { + guard let bitrate: Int = aacBitrate else { return noErr } + + var converter: AudioConverterRef? + var converterSize: UInt32 = UInt32(MemoryLayout.size) + let getStatus: OSStatus = ExtAudioFileGetProperty( + fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter + ) + guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus } + + var rate: UInt32 = UInt32(bitrate) + let setStatus: OSStatus = AudioConverterSetProperty( + converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout.size), &rate + ) + guard setStatus == noErr else { return setStatus } + + // Notify ExtAudioFile that the converter config changed so it re-reads it. + // The property value is a `CFPropertyList?` = NULL; pass a pointer to a nil + // variable (NOT a null data pointer — CoreAudio dereferences the pointer). + var config: CFPropertyList? = nil + return withUnsafePointer(to: &config) { ptr in + ExtAudioFileSetProperty( + fileRef, kExtAudioFileProperty_ConverterConfig, + UInt32(MemoryLayout.size), ptr + ) + } + } +} diff --git a/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift b/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift index 9b83b85..04a3ce8 100644 --- a/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift +++ b/Sources/Lyrebird/Buffers/LyrebirdBufferFileIO.swift @@ -7,44 +7,6 @@ import Foundation import AudioToolbox -// MARK: - AudioFileFormat - -/// Container format for `LyrebirdBuffer.write(to:format:sampleRate:)`. -public enum AudioFileFormat { - /// AIFF-C container (`.aiff`) — lossless Float32, big-endian. Common on macOS. - /// - /// Uses `kAudioFileAIFCType` (AIFF-C), not classic `kAudioFileAIFFType`. Classic AIFF - /// supports only integer PCM; AIFF-C adds float and other sample types while retaining - /// the same `.aiff` file extension and broad macOS/iOS compatibility. - /// - /// Note: AIFF-C has practical interoperability limits beyond 2 channels. For - /// multichannel (3–8 ch) output, prefer `.caf` or `.wav`. - case aiff - /// WAV container (`.wav`) — lossless Float32, little-endian. Cross-platform standard. - /// Supports up to `lyrebirdMaxFileChannelCount` channels via WAVE_FORMAT_EXTENSIBLE. - case wav - /// Core Audio Format (`.caf`) — Apple's flexible container; supports any sample rate - /// and any channel count up to `lyrebirdMaxFileChannelCount`. Default for writes. - case caf - - fileprivate var audioFileTypeID: AudioFileTypeID { - switch self { - case .aiff: return kAudioFileAIFCType // AIFF-C: supports Float32 (classic AIFF does not) - case .wav: return kAudioFileWAVEType - case .caf: return kAudioFileCAFType - } - } - - /// Whether the container requires big-endian sample data in the file format descriptor. - /// AIFF-C is big-endian by spec; WAV and CAF use native/little-endian. - fileprivate var requiresBigEndian: Bool { - switch self { - case .aiff: return true - case .wav, .caf: return false - } - } -} - // MARK: - LyrebirdBufferIOError /// Errors thrown by `LyrebirdBuffer` file I/O methods. @@ -70,6 +32,11 @@ public enum LyrebirdBufferIOError: Error, Equatable { case cannotSetOutputFormat(OSStatus) /// `ExtAudioFileWrite` returned a non-zero status. case writeFailed(OSStatus) + /// The requested WAV/AIFF write is projected to exceed the container's 4 GB + /// (32-bit size field) limit. `projectedBytes` is the estimated audio-data + /// size; `cap` is `lyrebirdMaxRIFFBytes`. Re-issue the write with `.cafFloat32` + /// (64-bit sizes, uncapped), shorten the buffer, or split it. + case fileTooLargeForContainer(projectedBytes: Int, cap: Int) } // MARK: - Constants @@ -251,18 +218,27 @@ public extension LyrebirdBuffer { /// Write the buffer's contents to an audio file. /// - /// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]`. The file will - /// contain interleaved Float32 samples at the specified sample rate. For multichannel - /// buffers, `.caf` or `.wav` are recommended; `.aiff` (AIFF-C) is best limited to - /// stereo for maximum compatibility with external readers. - /// - /// Converts `Double` (Double) samples to Float32 on the way out. + /// Supports any `channelCount` in `[1, lyrebirdMaxFileChannelCount]` and any + /// ``AudioFileFormat`` case. The buffer's `Double` samples are handed to the + /// writer as native Float32; the container's on-disk encoding (Float32, or + /// signed-integer 16/24-bit for the WAV cases) is produced by its conversion. + /// Most formats go through `ExtAudioFile`; the RF64 cases (`.rf64Float32` / + /// `.rf64Int24`) are written by ``RF64Writer`` instead, since `ExtAudioFile` + /// cannot emit RF64. For multichannel buffers, `.cafFloat32` or `.wavFloat32` are + /// recommended; `.aiffFloat32` (AIFF-C) is best limited to stereo for maximum + /// compatibility with external readers. `.wavFloat32` / `.wavInt16` / `.wavInt24` + /// / `.aiffFloat32` throw ``LyrebirdBufferIOError/fileTooLargeForContainer(projectedBytes:cap:)`` + /// past 4 GB — use `.rf64*` or `.cafFloat32` for larger files. /// /// - Parameters: /// - url: Destination file. Any existing file at this path is overwritten. - /// - format: Container format. Defaults to `.caf`. + /// - format: Container and PCM encoding. Defaults to `.cafFloat32`. /// - sampleRate: Sample rate embedded in the file header. Defaults to 44100. /// + /// - Throws: ``LyrebirdBufferIOError`` (`.fileTooLargeForContainer` when a + /// WAV/AIFF write is projected past 4 GB, or the create/write cases on I/O + /// failure). For the `.rf64*` formats, a ``RF64WriterError`` may surface instead. + /// /// **Not RT-safe.** Must be called from a non-RT thread (main thread or background queue). /// /// For session-end dumps from a ``LyrebirdEventList`` teardown, see the @@ -282,39 +258,50 @@ public extension LyrebirdBuffer { + "lyrebirdMaxFileChannelCount (\(lyrebirdMaxFileChannelCount))" ) - let bytesPerSample: UInt32 = lyrebirdFileIOBitsPerSample / 8 // 4 bytes for Float32 - let bytesPerFrame: UInt32 = bytesPerSample * UInt32(channelCount) + // Large-file guard: WAV/AIFF are 4 GB-capped (32-bit size fields). Reject a + // write that would overflow rather than emit a truncated/corrupt file. CAF + // is 64-bit and exempt (riffOverflow returns nil). + if let overflow: (projected: Int, cap: Int) = + format.riffOverflow(frameCount: count, channels: channelCount) { + throw LyrebirdBufferIOError.fileTooLargeForContainer( + projectedBytes: overflow.projected, cap: overflow.cap + ) + } - // File format: big-endian flags for AIFF-C; native-endian for WAV/CAF. - let fileFlags: AudioFormatFlags = format.requiresBigEndian - ? kAudioFormatFlagIsFloat | kAudioFormatFlagIsBigEndian | kAudioFormatFlagIsPacked - : kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked + // RF64 / BW64 is not an ExtAudioFile-writable container — hand it to RF64Writer. + // Client samples are native Float32 interleaved, same as the ExtAudioFile path. + if format.usesRF64Writer { + let writer: RF64Writer = try RF64Writer( + url: url, format: format, sampleRate: sampleRate, channels: channelCount + ) + let samplesPerChunk: Int = lyrebirdFileIOChunkFrames * channelCount + var chunkBuf: [Float] = [Float](repeating: 0, count: samplesPerChunk) + try withStorage { storage, frameCount, nch in + var frameOffset: Int = 0 + while frameOffset < frameCount { + let framesThisChunk: Int = min(lyrebirdFileIOChunkFrames, frameCount - frameOffset) + let samplesThisChunk: Int = framesThisChunk * nch + for i: Int in 0..= 1, "RF64Writer requires channels >= 1, got \(channels)") + self.format = format + self.channels = channels + let bytes: Int = Int(format.fileBitsPerChannel) / RF64Writer.bitsPerByte + self.bytesPerSample = bytes + self.blockAlign = channels * bytes + + // Create (truncate) the file, then open a handle for writing. + guard FileManager.default.createFile(atPath: url.path, contents: nil) else { + throw RF64WriterError.cannotCreateFile(url) + } + do { + self.fileHandle = try FileHandle(forWritingTo: url) + } catch { + throw RF64WriterError.cannotCreateFile(url) + } + + let header: [UInt8] = RF64Writer.buildHeader( + format: format, sampleRate: sampleRate, channels: channels, + blockAlign: blockAlign, bitsPerChannel: Int(format.fileBitsPerChannel) + ) + do { + try fileHandle.write(contentsOf: Data(header)) + } catch { + try? fileHandle.close() + throw RF64WriterError.writeFailed(error) + } + } + + // MARK: - Header construction + + /// Build the fixed 104-byte header by appending chunks in order, so no absolute + /// byte offsets appear here. `close()` later patches the three `ds64` sizes at + /// `ds64RiffSizeOffset` — which is fixed precisely because this layout is fixed. + private static func buildHeader( + format: AudioFileFormat, + sampleRate: Double, + channels: Int, + blockAlign: Int, + bitsPerChannel: Int + ) -> [UInt8] { + var h: [UInt8] = [] + h.reserveCapacity(headerByteCount) + + func fourCC(_ s: String) { h.append(contentsOf: Array(s.utf8)) } + func u16(_ v: UInt16) { + h.append(UInt8(truncatingIfNeeded: v)) + h.append(UInt8(truncatingIfNeeded: v >> 8)) + } + func u32(_ v: UInt32) { + for i: Int in 0..<4 { h.append(UInt8(truncatingIfNeeded: v >> (8 * i))) } + } + + // RF64 / RIFF-size sentinel / WAVE + fourCC("RF64"); u32(sizeFieldSentinel); fourCC("WAVE") + + // ds64 chunk — 64-bit sizes zero for now; patched on close(). + fourCC("ds64"); u32(ds64ChunkBodySize) + u32(0); u32(0) // riffSize (8) + u32(0); u32(0) // dataSize (8) + u32(0); u32(0) // sampleCount (8) + u32(0) // tableLength + + // fmt chunk — WAVE_FORMAT_EXTENSIBLE + fourCC("fmt "); u32(fmtChunkBodySize) + let avgBytesPerSec: UInt32 = UInt32(sampleRate.rounded()) * UInt32(blockAlign) + u16(waveFormatExtensible) // wFormatTag + u16(UInt16(channels)) // nChannels + u32(UInt32(sampleRate.rounded())) // nSamplesPerSec + u32(avgBytesPerSec) // nAvgBytesPerSec + u16(UInt16(blockAlign)) // nBlockAlign + u16(UInt16(bitsPerChannel)) // wBitsPerSample + u16(fmtExtensionSize) // cbSize + u16(UInt16(bitsPerChannel)) // wValidBitsPerSample + u32(0) // dwChannelMask + let guid: [UInt8] = format.isFloatEncoding ? subFormatIEEEFloat : subFormatPCM + h.append(contentsOf: guid) // SubFormat GUID (16) + + // data chunk — size sentinel; real size in ds64. + fourCC("data"); u32(sizeFieldSentinel) + + return h + } + + // MARK: - Write + + /// Append `frames` interleaved frames of native Float32 samples, converting to the + /// file encoding. `samples` must contain at least `frames * channels` values. + public func writeFloat32Interleaved(_ samples: UnsafeBufferPointer, frames: Int) throws { + guard frames > 0 else { return } + let sampleCount: Int = frames * channels + + let payload: Data + if format.isFloatEncoding { + // Float32 little-endian passthrough (Apple platforms are little-endian). + guard let base: UnsafePointer = samples.baseAddress else { return } + payload = Data(buffer: UnsafeBufferPointer(start: base, count: sampleCount)) + } else { + // Signed 24-bit packed little-endian. Round to nearest (matches ExtAudioFile). + let byteCount: Int = sampleCount * bytesPerSample + if scratch.count < byteCount { scratch = [UInt8](repeating: 0, count: byteCount) } + for i: Int in 0..> 8) + scratch[i * 3 + 2] = UInt8(truncatingIfNeeded: s >> 16) + } + payload = Data(scratch[0.. 0 ? dataSize / UInt64(blockAlign) : 0 + + func u64LE(_ v: UInt64) -> Data { + var bytes: [UInt8] = [UInt8](repeating: 0, count: 8) + for i: Int in 0..<8 { bytes[i] = UInt8(truncatingIfNeeded: v >> (8 * i)) } + return Data(bytes) + } + + do { + try fileHandle.seek(toOffset: RF64Writer.ds64RiffSizeOffset) + try fileHandle.write(contentsOf: u64LE(riffSize)) // ds64.riffSize + try fileHandle.write(contentsOf: u64LE(dataSize)) // ds64.dataSize + try fileHandle.write(contentsOf: u64LE(sampleCount)) // ds64.sampleCount + } catch { + throw RF64WriterError.seekFailed(error) + } + if let padError: Error = padError { + throw RF64WriterError.writeFailed(padError) + } + } + + deinit { + // Best-effort: if the owner forgot to close(), still patch sizes so the file + // is readable. Errors are unrecoverable here and deliberately swallowed. + if !closed { try? close() } + } +} diff --git a/Sources/Lyrebird/Buffers/RF64WriterError.swift b/Sources/Lyrebird/Buffers/RF64WriterError.swift new file mode 100644 index 0000000..582de04 --- /dev/null +++ b/Sources/Lyrebird/Buffers/RF64WriterError.swift @@ -0,0 +1,20 @@ +// RF64WriterError.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Foundation + +/// Errors thrown by ``RF64Writer``. +public enum RF64WriterError: Error { + /// The output file could not be created at the given URL. + case cannotCreateFile(URL) + /// A `FileHandle` write failed; carries the underlying error. + case writeFailed(Error) + /// Seeking back to patch the `ds64` sizes on ``RF64Writer/close()`` failed. + case seekFailed(Error) + /// The format passed to ``RF64Writer/init(url:format:sampleRate:channels:)`` is not + /// an RF64 case. Only `.rf64Float32` / `.rf64Int24` are supported. + case unsupportedFormat(AudioFileFormat) +} diff --git a/Sources/Lyrebird/Engine/EngineHost.swift b/Sources/Lyrebird/Engine/EngineHost.swift index b74a0d2..22dfa34 100644 --- a/Sources/Lyrebird/Engine/EngineHost.swift +++ b/Sources/Lyrebird/Engine/EngineHost.swift @@ -495,6 +495,7 @@ public final class EngineHost: @unchecked Sendable { let driver: NRTDriver = NRTDriver( outputURL: job.outputURL, duration: job.duration, + format: job.format, inputURL: job.inputURL, inputStartOffset: job.inputStartOffset ) diff --git a/Sources/Lyrebird/Engine/NRTJob.swift b/Sources/Lyrebird/Engine/NRTJob.swift index 30c1933..a56a43c 100644 --- a/Sources/Lyrebird/Engine/NRTJob.swift +++ b/Sources/Lyrebird/Engine/NRTJob.swift @@ -26,11 +26,16 @@ import Foundation /// fires automatically. public struct NRTJob: Sendable { - /// Destination file URL the rendered audio writes to. CAF format - /// per `NRTDriver`'s contract; the file is created by the driver - /// at `engine.start()` time. + /// Destination file URL the rendered audio writes to. The file is + /// created by the driver at `engine.start()` time, using ``format``. public let outputURL: URL + /// Container and PCM encoding for ``outputURL``. Maps to + /// `NRTDriver.init(format:)`. Defaults to `.cafFloat32` — CAF is + /// 64-bit-sized (no 4 GB cap) and carries any channel count, which + /// suits long offline renders and multichannel stems. + public let format: AudioFileFormat + /// Render duration in seconds. Maps to `NRTDriver.init(duration:)`. public let duration: Double @@ -86,6 +91,7 @@ public struct NRTJob: Sendable { public init( outputURL: URL, duration: Double, + format: AudioFileFormat = .cafFloat32, blockSize: Int = lyrebirdDefaultResultBufferSize, sampleRate: Double = lyrebirdDefaultSampleRate, numOutputChannels: Int = 2, @@ -95,6 +101,7 @@ public struct NRTJob: Sendable { build: @escaping @Sendable (SynthesisEngine) throws -> Void ) { self.outputURL = outputURL + self.format = format self.duration = duration self.blockSize = blockSize self.sampleRate = sampleRate diff --git a/Sources/Lyrebird/Generators/BufferIO/DiskOut.swift b/Sources/Lyrebird/Generators/BufferIO/DiskOut.swift index e79b078..a4a367e 100644 --- a/Sources/Lyrebird/Generators/BufferIO/DiskOut.swift +++ b/Sources/Lyrebird/Generators/BufferIO/DiskOut.swift @@ -40,7 +40,8 @@ public enum DiskOut { /// The overflow guard (`used + count <= _ringSize`) ensures indices never alias. /// - `_framesWritten` is stored by RT with `.releasing`; BG loads with `.acquiring`. /// - `_framesRead` is stored by BG with `.releasing`; RT loads with `.acquiring`. - /// - `_fileRef` and `_interleavedWriteBuf` are BG-only after `init`. + /// - `_fileRef`, `_rf64Writer`, `_cumulativeFramesWritten`, and + /// `_interleavedWriteBuf` are BG-only after `init`. /// /// ## Usage /// ```swift @@ -58,6 +59,16 @@ public enum DiskOut { /// try engine.start() // render / play /// diskOut.close() // flush remaining frames and close the file /// ``` + /// + /// - Parameters: + /// - source: Audio source to record and pass through. + /// - channelCount: Number of channels to record and pass through. Must be ≥ 1. + /// - url: Output file path. Created (or overwritten) immediately in `init`. + /// - sampleRate: Sample rate written into the file header. Defaults to 48000 Hz. + /// - format: Container and PCM encoding (``AudioFileFormat``). Defaults to `.aiffFloat32`. + /// - bufferFrames: Ring buffer capacity in frames. Must be a power of two. Defaults to 8192. + /// - mul: Output scale factor. Defaults to `1.0`. + /// - add: Output offset. Defaults to `0.0`. public final class Audio: GeneratorBase, @unchecked Sendable, AudioGenerator, RootRegistering { // MARK: - Generator protocol @@ -100,6 +111,10 @@ public enum DiskOut { private var _interleavedWriteBuf: [Float] + /// Cumulative frames written to the file across the whole session. BG-only + /// (touched only in `_drainAndWrite`). Drives the large-file guard. + private var _cumulativeFramesWritten: Int = 0 + // MARK: - Pass-through output private var _mulAdd: MulAddSpec @@ -109,14 +124,30 @@ public enum DiskOut { private var _fileRef: ExtAudioFileRef? + /// RF64 backend for the `.rf64Float32` / `.rf64Int24` formats (`ExtAudioFile` + /// can't write RF64). Exactly one of `_fileRef` / `_rf64Writer` is non-nil. + private var _rf64Writer: RF64Writer? + + /// Output container/encoding — fixed at init. Read by the BG drain's + /// large-file guard (`riffOverflow`); CAF/RF64 are exempt. + private let _outputFormat: AudioFileFormat + private let _backgroundQueue: DispatchQueue private let _stopped: Atomic = Atomic(false) private let _writeError: Atomic = Atomic(false) + private let _fileTooLarge: Atomic = Atomic(false) /// `true` if any `ExtAudioFileWrite` call failed during recording. /// Poll from a non-RT context after `close()` to detect disk write errors. public var writeError: Bool { _writeError.load(ordering: .acquiring) } + /// `true` if recording stopped early because the file reached the WAV/AIFF + /// 4 GB container cap (see `lyrebirdMaxRIFFBytes`). Frames past the cap are + /// dropped rather than corrupting the file; audio already written stays + /// valid. Always `false` for `.cafFloat32` (CAF is 64-bit, uncapped). Poll + /// from a non-RT context. + public var fileTooLarge: Bool { _fileTooLarge.load(ordering: .acquiring) } + // MARK: - Init /// Create a streaming disk recorder. @@ -131,17 +162,21 @@ public enum DiskOut { /// - url: Output file path. Created or overwritten immediately. /// - sampleRate: Engine sample rate written into the file header. Defaults /// to 48 000 Hz. - /// - format: Container format. Defaults to `.aiff`. + /// - format: Container and PCM encoding. Defaults to `.aiffFloat32`. /// - bufferFrames: Ring buffer capacity in frames. Must be a power of two. /// Default 8 192 (≈ 170 ms at 48 kHz). /// - mul: Output scale factor. Defaults to `1.0`. /// - add: Output offset. Defaults to `0.0`. + /// + /// - Throws: ``DiskOutError`` on file-create/format failure for the + /// `ExtAudioFile`-backed formats. For the `.rf64*` formats, a + /// ``RF64WriterError`` may surface instead. public init( source: any ValidGeneratorInput, channelCount: Int, url: URL, sampleRate: Double = 48000, - format: DiskOutFormat = .aiff, + format: AudioFileFormat = .aiffFloat32, bufferFrames: Int = 8192, mul: any ValidGeneratorInput = 1.0, add: any ValidGeneratorInput = 0.0 @@ -152,10 +187,16 @@ public enum DiskOut { bufferFrames > 0 && bufferFrames & (bufferFrames - 1) == 0, "DiskOut.Audio: bufferFrames \(bufferFrames) must be a power of two" ) + // Streaming a compressed encoder (priming/latency/flush) is out of scope — + // reject before any allocation. AAC / ALAC render offline instead. + guard !format.isCompressed else { + throw DiskOutError.compressedFormatNotSupported(format) + } let resolvedSource: any ValidGeneratorInput = source._resolvedInput() self.channelCount = channelCount self._source = resolvedSource + self._outputFormat = format self._ringSize = bufferFrames self._ringMask = bufferFrames - 1 @@ -170,78 +211,60 @@ public enum DiskOut { _backgroundQueue = DispatchQueue(label: "com.lyrebird.diskout", qos: .userInitiated) - // Create the output file. - // - // File format is derived from `format` (may be integer-encoded). - // Client format is always Float32 interleaved — ExtAudioFile handles - // the Float32 → int16/int24 conversion transparently. - let fileBytesPerSample: UInt32 = UInt32(format.fileBitsPerChannel / 8) - var fileFormatFlags: AudioFormatFlags = kAudioFormatFlagIsPacked - if format.isFloatEncoding { - fileFormatFlags |= kAudioFormatFlagIsFloat + // Create the output file. RF64 (64-bit WAV) goes through RF64Writer; + // everything else through ExtAudioFile. Client samples are always native + // Float32 interleaved — ExtAudioFile handles Float32 → int16/int24, and + // RF64Writer handles Float32 → RF64 float/int24, transparently. + if format.usesRF64Writer { + do { + _rf64Writer = try RF64Writer( + url: url, format: format, sampleRate: sampleRate, channels: channelCount + ) + } catch { + // Pre-`super.init()` throw — `deinit` won't run; free the ring. + // Rethrow the RF64WriterError directly (init throws are untyped). + _ringStorage.deallocate() + throw error + } } else { - fileFormatFlags |= kAudioFormatFlagIsSignedInteger - } - if format.isBigEndian { - fileFormatFlags |= kAudioFormatFlagIsBigEndian - } + var fileFmt: AudioStreamBasicDescription = + format.makeFileASBD(sampleRate: sampleRate, channels: channelCount) + var rawRef: ExtAudioFileRef? + let createStatus: OSStatus = ExtAudioFileCreateWithURL( + url as CFURL, + format.audioFileTypeID, + &fileFmt, + nil, + AudioFileFlags.eraseFile.rawValue, + &rawRef + ) + guard createStatus == noErr, let rawRef: ExtAudioFileRef else { + // These guards throw before `super.init()`, so `deinit` will not + // run — free the raw ring storage explicitly or it leaks. (The + // former `[[Float]]` ring was ARC-managed and torn down here for + // free; raw memory is not.) + _ringStorage.deallocate() + throw DiskOutError.cannotCreateFile(createStatus) + } + _fileRef = rawRef - var fileFmt: AudioStreamBasicDescription = AudioStreamBasicDescription( - mSampleRate: sampleRate, - mFormatID: kAudioFormatLinearPCM, - mFormatFlags: fileFormatFlags, - mBytesPerPacket: fileBytesPerSample * UInt32(channelCount), - mFramesPerPacket: 1, - mBytesPerFrame: fileBytesPerSample * UInt32(channelCount), - mChannelsPerFrame: UInt32(channelCount), - mBitsPerChannel: format.fileBitsPerChannel, - mReserved: 0 - ) - var rawRef: ExtAudioFileRef? - let createStatus: OSStatus = ExtAudioFileCreateWithURL( - url as CFURL, - format.audioFileType, - &fileFmt, - nil, - AudioFileFlags.eraseFile.rawValue, - &rawRef - ) - guard createStatus == noErr, let rawRef: ExtAudioFileRef else { - // These guards throw before `super.init()`, so `deinit` will not - // run — free the raw ring storage explicitly or it leaks. (The - // former `[[Float]]` ring was ARC-managed and torn down here for - // free; raw memory is not.) - _ringStorage.deallocate() - throw DiskOutError.cannotCreateFile(createStatus) - } - _fileRef = rawRef - - // Client format is always Float32 interleaved, regardless of the file - // encoding. ExtAudioFile converts float→int when writing to the file. - let float32ByteSize: UInt32 = UInt32(MemoryLayout.size) - var clientFmt: AudioStreamBasicDescription = AudioStreamBasicDescription( - mSampleRate: sampleRate, - mFormatID: kAudioFormatLinearPCM, - mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, - mBytesPerPacket: float32ByteSize * UInt32(channelCount), - mFramesPerPacket: 1, - mBytesPerFrame: float32ByteSize * UInt32(channelCount), - mChannelsPerFrame: UInt32(channelCount), - mBitsPerChannel: lyrebirdBitsPerSample, - mReserved: 0 - ) - let setFmtStatus: OSStatus = ExtAudioFileSetProperty( - rawRef, - kExtAudioFileProperty_ClientDataFormat, - UInt32(MemoryLayout.size), - &clientFmt - ) - guard setFmtStatus == noErr else { - ExtAudioFileDispose(rawRef) - _fileRef = nil - // Pre-`super.init()` throw — `deinit` won't run; free the ring. - _ringStorage.deallocate() - throw DiskOutError.cannotSetFormat(setFmtStatus) + // Client format is always Float32 interleaved, regardless of the file + // encoding. ExtAudioFile converts float→int when writing to the file. + var clientFmt: AudioStreamBasicDescription = + format.makeClientASBD(sampleRate: sampleRate, channels: channelCount) + let setFmtStatus: OSStatus = ExtAudioFileSetProperty( + rawRef, + kExtAudioFileProperty_ClientDataFormat, + UInt32(MemoryLayout.size), + &clientFmt + ) + guard setFmtStatus == noErr else { + ExtAudioFileDispose(rawRef) + _fileRef = nil + // Pre-`super.init()` throw — `deinit` won't run; free the ring. + _ringStorage.deallocate() + throw DiskOutError.cannotSetFormat(setFmtStatus) + } } super.init(channels: channelCount) @@ -264,6 +287,12 @@ public enum DiskOut { ExtAudioFileDispose(ref) _fileRef = nil } + if let writer: RF64Writer = _rf64Writer { + // Patch the ds64 sizes and close. A failure here means the size fields + // stay unpatched; surface it via the same flag as write errors. + do { try writer.close() } catch { _writeError.store(true, ordering: .releasing) } + _rf64Writer = nil + } } deinit { @@ -275,6 +304,10 @@ public enum DiskOut { // finished its current iteration before deinit can start, so _fileRef // is not being accessed concurrently; direct disposal is safe. if let ref: ExtAudioFileRef = _fileRef { ExtAudioFileDispose(ref) } + // RF64Writer.close() patches the ds64 sizes; its own deinit is a + // best-effort fallback, but call it here so a forgotten close() still + // finalises the file. Safe for the same no-concurrent-BG reason above. + try? _rf64Writer?.close() } // Free the raw ring storage. Safe here for the same reason the file // disposal is: the BG loop upgrades its `[weak self]` to a strong @@ -309,7 +342,14 @@ public enum DiskOut { let rHead: Int = _framesRead.load(ordering: .relaxed) let wHead: Int = _framesWritten.load(ordering: .acquiring) let available: Int = wHead - rHead - guard available > 0, let fileRef: ExtAudioFileRef = _fileRef else { return } + guard available > 0, (_fileRef != nil || _rf64Writer != nil) else { return } + + // Once the file has hit the container cap, discard remaining frames + // without writing (keeps the ring draining so the RT side never stalls). + if _fileTooLarge.load(ordering: .acquiring) { + _framesRead.store(rHead + available, ordering: .releasing) + return + } // Drain in chunks no larger than the interleaved write buffer capacity. let chunkFrames: Int = _interleavedWriteBuf.count / channelCount // == _ringSize @@ -317,32 +357,53 @@ public enum DiskOut { while totalDrained < available { let toWrite: Int = min(chunkFrames, available - totalDrained) + + // Large-file guard: for WAV/AIFF (32-bit-sized), stop before a write + // that would push the file past the 4 GB cap. CAF → riffOverflow nil, + // so this is a no-op for the default streaming format. + if _outputFormat.riffOverflow( + frameCount: _cumulativeFramesWritten + toWrite, channels: channelCount + ) != nil { + _fileTooLarge.store(true, ordering: .releasing) + break + } + for f: Int in 0.. = ptr.baseAddress else { return } - let frames: UInt32 = UInt32(toWrite) - var bufList: AudioBufferList = AudioBufferList( - mNumberBuffers: 1, - mBuffers: AudioBuffer( - mNumberChannels: UInt32(channelCount), - mDataByteSize: UInt32( - toWrite * channelCount * MemoryLayout.size), - mData: base + if let rf64Writer: RF64Writer = _rf64Writer { + _interleavedWriteBuf.withUnsafeBufferPointer { ptr in + do { try rf64Writer.writeFloat32Interleaved(ptr, frames: toWrite) } + catch { _writeError.store(true, ordering: .releasing) } + } + } else if let fileRef: ExtAudioFileRef = _fileRef { + _interleavedWriteBuf.withUnsafeMutableBufferPointer { ptr in + guard let base: UnsafeMutablePointer = ptr.baseAddress else { return } + let frames: UInt32 = UInt32(toWrite) + var bufList: AudioBufferList = AudioBufferList( + mNumberBuffers: 1, + mBuffers: AudioBuffer( + mNumberChannels: UInt32(channelCount), + mDataByteSize: UInt32( + toWrite * channelCount * MemoryLayout.size), + mData: base + ) ) - ) - let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList) - if writeStatus != noErr { - _writeError.store(true, ordering: .releasing) + let writeStatus: OSStatus = ExtAudioFileWrite(fileRef, frames, &bufList) + if writeStatus != noErr { + _writeError.store(true, ordering: .releasing) + } } } + _cumulativeFramesWritten += toWrite totalDrained += toWrite } + // Advance the read head by everything that was available — including any + // frames skipped after an overflow break — so the ring keeps draining. _framesRead.store(rHead + available, ordering: .releasing) } diff --git a/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift b/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift index 9d11554..34e0b83 100644 --- a/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift +++ b/Sources/Lyrebird/Generators/BufferIO/DiskOutError.swift @@ -11,4 +11,9 @@ import AudioToolbox public enum DiskOutError: Error { case cannotCreateFile(OSStatus) case cannotSetFormat(OSStatus) + /// A compressed format (AAC / ALAC) was passed to ``DiskOut/Audio``. Real-time + /// streaming to a compressed codec is not supported — use a PCM or RF64 format + /// for `DiskOut`, and render offline (`LyrebirdBuffer.write` / `NRTDriver`) for + /// AAC / ALAC output. + case compressedFormatNotSupported(AudioFileFormat) } diff --git a/Sources/Lyrebird/Generators/BufferIO/DiskOutFormat.swift b/Sources/Lyrebird/Generators/BufferIO/DiskOutFormat.swift index 9662599..30d9046 100644 --- a/Sources/Lyrebird/Generators/BufferIO/DiskOutFormat.swift +++ b/Sources/Lyrebird/Generators/BufferIO/DiskOutFormat.swift @@ -4,87 +4,12 @@ // Copyright (c) 2026 Joshua Parmenter / realizedsound // SPDX-License-Identifier: MIT -import AudioToolbox - -/// Container-and-encoding format for ``DiskOut/Audio``. +/// Deprecated alias for the framework-wide ``AudioFileFormat``. /// -/// Each case encodes both the container (WAV or AIFF) and the PCM bit depth. -/// ``DiskOut/Audio`` always accepts Float32 from the signal graph (the client -/// data format) and delegates any necessary conversion to `ExtAudioFile`. -public enum DiskOutFormat: Sendable { - - // MARK: - WAV variants - - /// WAV container with 32-bit IEEE-754 float encoding. - case wavFloat32 - /// WAV container with 16-bit signed integer encoding. - case wavInt16 - /// WAV container with 24-bit signed integer encoding. - case wavInt24 - - // MARK: - AIFF-C variants - - /// AIFF-C container with 32-bit IEEE-754 float encoding. - case aiffFloat32 - - // MARK: - Deprecated shorthands (kept for DiskOut.Audio default parameter) - - /// AIFF-C container with 32-bit float encoding. Alias for ``aiffFloat32``. - public static let aiff: DiskOutFormat = .aiffFloat32 - /// WAV container with 32-bit float encoding. Alias for ``wavFloat32``. - public static let wav: DiskOutFormat = .wavFloat32 - - // MARK: - Derived properties - - /// AudioToolbox container type ID used when creating the `ExtAudioFile`. - var audioFileType: AudioFileTypeID { - switch self { - case .wavFloat32, .wavInt16, .wavInt24: - return kAudioFileWAVEType - case .aiffFloat32: - return kAudioFileAIFCType - } - } - - /// Filesystem extension for the output file (without the leading dot). - public var fileExtension: String { - switch self { - case .wavFloat32, .wavInt16, .wavInt24: - return "wav" - case .aiffFloat32: - return "aiff" - } - } - - /// Bits per sample in the encoded file. - var fileBitsPerChannel: UInt32 { - switch self { - case .wavFloat32, .aiffFloat32: - return 32 - case .wavInt16: - return 16 - case .wavInt24: - return 24 - } - } - - /// `true` when the file encoding is IEEE-754 float. - var isFloatEncoding: Bool { - switch self { - case .wavFloat32, .aiffFloat32: - return true - case .wavInt16, .wavInt24: - return false - } - } - - /// `true` when the container stores big-endian samples (AIFF-C spec). - var isBigEndian: Bool { - switch self { - case .aiffFloat32: - return true - case .wavFloat32, .wavInt16, .wavInt24: - return false - } - } -} +/// The container/encoding enum is shared across ``DiskOut/Audio``, +/// ``LyrebirdBuffer/write(to:format:sampleRate:)``, and the NRT driver, so it now +/// lives under one name. This alias keeps existing `DiskOutFormat.wavFloat32` / +/// `.aiffFloat32` / `.wav` / `.aiff` spellings compiling; migrate to +/// ``AudioFileFormat`` directly. +@available(*, deprecated, message: "Use AudioFileFormat instead.") +public typealias DiskOutFormat = AudioFileFormat diff --git a/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md b/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md index 369138d..e9688e6 100644 --- a/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md +++ b/Sources/Lyrebird/Lyrebird.docc/NRTGuide.md @@ -250,12 +250,44 @@ afconvert -f WAVE -d LEF32 output.caf output.wav ### LyrebirdBuffer.write() — AIFF, WAV, or CAF ```swift -try buf.write(to: url, format: .caf, sampleRate: 44100) -try buf.write(to: url, format: .aiff, sampleRate: 44100) -try buf.write(to: url, format: .wav, sampleRate: 44100) +try buf.write(to: url, format: .cafFloat32, sampleRate: 44100) +try buf.write(to: url, format: .aiffFloat32, sampleRate: 44100) +try buf.write(to: url, format: .wavFloat32, sampleRate: 44100) + +// Integer WAV encodings, for smaller files / DAW interchange: +try buf.write(to: url, format: .wavInt16, sampleRate: 44100) +try buf.write(to: url, format: .wavInt24, sampleRate: 44100) + +// RF64 / BW64 — WAV extension, 64-bit sizes, no 4 GB cap: +try buf.write(to: url, format: .rf64Float32, sampleRate: 44100) +try buf.write(to: url, format: .rf64Int24, sampleRate: 44100) + +// Compressed M4A (offline writers only — LyrebirdBuffer.write / NRTDriver): +try buf.write(to: url, format: .aacHigh, sampleRate: 44100) // AAC ~256 kbps (lossy) +try buf.write(to: url, format: .aacMedium, sampleRate: 44100) // AAC ~128 kbps (lossy) +try buf.write(to: url, format: .alac, sampleRate: 44100) // Apple Lossless ``` -All formats write 32-bit float (Float32). `Double` (Double) values are downcast on the way out. +The buffer's `Double` samples are handed to `ExtAudioFile` as native Float32; the +container's on-disk encoding drives the conversion. The `.cafFloat32` / +`.aiffFloat32` / `.wavFloat32` cases are lossless 32-bit float; `.wavInt16` / +`.wavInt24` quantise to signed 16/24-bit PCM. (`.caf` / `.aiff` / `.wav` remain +as Float32 shorthands.) + +**Files past 4 GB**: plain `.wav`/`.aiff` are limited to 4 GB (32-bit size fields) and +throw `fileTooLargeForContainer` past that. For a big file that must keep the `.wav` +extension, use `.rf64Float32` / `.rf64Int24` — RF64/BW64 (EBU Tech 3306) carries 64-bit +sizes in a `ds64` chunk (written by Lyrebird's own ``RF64Writer``; CoreAudio reads it +back). `.cafFloat32` is the other uncapped option. + +**Compressed output** (`.aacHigh` / `.aacMedium` / `.alac`): AAC and Apple Lossless in an +`.m4a` container, encoded by `ExtAudioFile`/`AudioConverter`. **Offline writers only** — +`LyrebirdBuffer.write` and `NRTDriver`; ``DiskOut/Audio`` throws `compressedFormatNotSupported` +(real-time streaming of a compressed encoder is out of scope). AAC is lossy and **not +sample-accurate** (encoder priming/padding shifts the signal a few ms), so frame-count +round-trips aren't exact; ALAC is lossless of a 24-bit-quantised source. Introspect a +format with ``AudioFileFormat/isCompressed`` (true for these three) and, for AAC, its +target rate via ``AudioFileFormat/aacBitrate``. ## Complete Example — NRT Bounce to AIFF @@ -316,6 +348,9 @@ do { | `NRTDriverError.cannotOpenInputFile` | `inputURL` not found or unreadable | Verify the file path exists | | `NRTDriverError.cannotSeekInputFile` | `inputStartOffset` beyond file end | Reduce `inputStartOffset` | | `NRTDriverError.inputReadFailed` | Disk I/O error reading input file | Check disk health | +| `NRTDriverError.invalidDuration` | `duration` is negative, NaN, or infinite | Pass a finite, non-negative duration | +| `NRTDriverError.fileTooLargeForContainer` | WAV/AIFF render projected past the 4 GB RIFF cap | Use `format: .cafFloat32`, or shorten `duration` | +| `LyrebirdBufferIOError.fileTooLargeForContainer` | `LyrebirdBuffer.write` to WAV/AIFF projected past 4 GB | Use `.cafFloat32`, or split/shorten the buffer | | Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` before `start()` | | File truncated short | `duration` too short | Increase `NRTDriver` duration | diff --git a/Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md b/Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md index 40f6557..22736c6 100644 --- a/Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md +++ b/Sources/Lyrebird/Lyrebird.docc/ProcessSystem.md @@ -455,11 +455,13 @@ list.stopRecord() // Inspect state: list.isRecording // Bool list.recordDirectory // URL? -list.recordFormat // DiskOutFormat +list.recordFormat // AudioFileFormat ``` **Late-start behavior**: calling `record(directory:format:)` after the first event has already fired is valid. Processes already running do not start recording retroactively — only new ``LyrebirdProcess/play(engine:)`` calls after this point produce stem files. +**4 GB cap on WAV/AIFF stems**: the default `format` is a WAV encoding, and WAV/AIFF-C containers are limited to 4 GB (32-bit size fields). A very long performance can hit that ceiling — the affected stem stops growing at the cap (frames past it are silently dropped; audio already written stays valid) rather than corrupting. For multi-hour sessions record to a 64-bit container: `.cafFloat32`, or `.rf64Float32` / `.rf64Int24` (RF64/BW64 — keeps the `.wav` extension, uncapped). Each stem's ``DiskOut/Audio`` exposes `fileTooLarge` if you need to detect the condition after teardown. + ### Stem Filename Scheme Each stem file is named: @@ -484,12 +486,16 @@ The offset field is zero-padded to a fixed width (7 integer digits, 4 decimal pl ### Format Options -| ``DiskOutFormat`` case | Container | Encoding | Use when | +| ``AudioFileFormat`` case | Container | Encoding | Use when | |------------------------|-----------|----------|----------| | `.wavFloat32` | WAV | 32-bit float | Default. Lossless, DAW-compatible. | | `.wavInt16` | WAV | 16-bit PCM | Smallest file; -96 dB noise floor. | | `.wavInt24` | WAV | 24-bit PCM | Balanced. | | `.aiffFloat32` | AIFF | 32-bit float | Legacy Mac/ProTools compatibility. | +| `.cafFloat32` | CAF | 32-bit float | Long sessions — 64-bit sizes, no 4 GB cap. | +| `.rf64Float32` / `.rf64Int24` | WAV (RF64) | 32-bit float / 24-bit PCM | Long sessions needing the `.wav` extension. | + +> Note: The compressed codecs (`.aacHigh` / `.aacMedium` / `.alac`) are **not** available for stem recording — ``DiskOut/Audio`` (which backs stems) rejects them. Compressed output is offline-only (`LyrebirdBuffer.write` / `NRTDriver`). > Note: A master file that captures the mixed master bus (after the `EventListMasterSynth`) is planned for a future phase. Currently only per-process dry stems are recorded. diff --git a/Sources/Lyrebird/Math/LyrebirdConstants.swift b/Sources/Lyrebird/Math/LyrebirdConstants.swift index ecb5587..6f720b8 100644 --- a/Sources/Lyrebird/Math/LyrebirdConstants.swift +++ b/Sources/Lyrebird/Math/LyrebirdConstants.swift @@ -72,6 +72,21 @@ public let lyrebirdBufferMonoChannelCount: Int = 1 /// multichannel configurations. public let lyrebirdMaxFileChannelCount: Int = 8 +/// Largest audio-data payload (bytes) a classic RIFF (WAV) or AIFF-C container can +/// address. Both use unsigned **32-bit** size fields, so the whole file must fit in +/// 4 GB (`0xFFFF_FFFF`). We subtract a header slack so header + data together stay +/// within range regardless of the exact chunk layout. +/// +/// `ExtAudioFile` writes only classic RIFF / AIFF — CoreAudio has no RF64 / BW64 / +/// W64 writer — so a WAV/AIFF write past this cap is unreachable and is rejected by +/// the `LyrebirdBuffer.write` / `NRTDriver` large-file guards (throwing +/// `fileTooLargeForContainer`). Use `.cafFloat32` (64-bit sizes, uncapped) instead. +/// +/// Rule of thumb: 4 ch × Float32 × 48 kHz ≈ 4 GB in ~43 minutes. +private let riffSizeFieldMax: Int = 0xFFFF_FFFF +private let riffHeaderSlackBytes: Int = 1024 +public let lyrebirdMaxRIFFBytes: Int = riffSizeFieldMax - riffHeaderSlackBytes + // MARK: - Granular synthesis /// Pre-allocated grain pool size for `BufferGrain`. diff --git a/Sources/Lyrebird/Process/LyrebirdEventList.swift b/Sources/Lyrebird/Process/LyrebirdEventList.swift index 6b0b561..e945a76 100644 --- a/Sources/Lyrebird/Process/LyrebirdEventList.swift +++ b/Sources/Lyrebird/Process/LyrebirdEventList.swift @@ -246,7 +246,7 @@ public final class LyrebirdEventList: @unchecked Sendable { /// Non-nil while recording is enabled. Set by ``record(directory:format:)`` /// and cleared by ``stopRecord()``. private var _recordingDirectory: URL? - private var _recordingFormat: DiskOutFormat = .wavFloat32 + private var _recordingFormat: AudioFileFormat = .wavFloat32 private var _isRecording: Bool = false // MARK: - Timeline state (main-thread only) @@ -515,8 +515,8 @@ public final class LyrebirdEventList: @unchecked Sendable { /// Container-and-encoding format used for stem files. /// - /// Defaults to ``DiskOutFormat/wavFloat32``. Set via ``record(directory:format:)``. - public var recordFormat: DiskOutFormat { _recordingFormat } + /// Defaults to ``AudioFileFormat/wavFloat32``. Set via ``record(directory:format:)``. + public var recordFormat: AudioFileFormat { _recordingFormat } // MARK: - Playback @@ -818,11 +818,26 @@ public final class LyrebirdEventList: @unchecked Sendable { /// eagerly (including intermediate directories) before this call returns. /// A failure to create the directory is logged but does not throw — recording /// will simply fail silently when the first process attempts to write. - /// - format: Container and PCM encoding. Defaults to ``DiskOutFormat/wavFloat32``. + /// - format: Container and PCM encoding. Defaults to ``AudioFileFormat/wavFloat32``. + /// Must be a PCM or RF64 format — compressed formats (`.aacHigh` / `.aacMedium` + /// / `.alac`) are **rejected** (stems stream through ``DiskOut/Audio``, which is + /// PCM/RF64 only); passing one logs a warning and leaves recording disabled. public func record( directory: URL, - format: DiskOutFormat = .wavFloat32 + format: AudioFileFormat = .wavFloat32 ) { + // Stems are written by DiskOut, which streams PCM/RF64 only — a compressed + // format would make every per-process DiskOut.init throw and recording fail + // silently. Reject it up front with a clear message and do not enable + // recording (render offline for compressed output). + guard !format.isCompressed else { + print("[LyrebirdEventList '\(id)'] Compressed formats (AAC/ALAC) are not " + + "supported for stem recording — DiskOut streams PCM/RF64 only. " + + "Recording NOT enabled. Use a PCM/RF64 format for stems, or render " + + "offline (LyrebirdBuffer.write / NRTDriver) for AAC/ALAC.") + return + } + // Eagerly create the directory so the contract "directory exists when the // first process plays" is guaranteed regardless of whether any event fires. do { diff --git a/Sources/Lyrebird/Process/ProcessRecordingConfig.swift b/Sources/Lyrebird/Process/ProcessRecordingConfig.swift index e09f798..086d4ff 100644 --- a/Sources/Lyrebird/Process/ProcessRecordingConfig.swift +++ b/Sources/Lyrebird/Process/ProcessRecordingConfig.swift @@ -20,7 +20,7 @@ struct ProcessRecordingConfig { let directory: URL /// Output file encoding/container format. - let format: DiskOutFormat + let format: AudioFileFormat /// The EventList's `id`, pre-sanitised for filesystem use. let sanitisedEventListID: String diff --git a/Tests/LyrebirdTests/Buffers/AudioFileCompressedTests.swift b/Tests/LyrebirdTests/Buffers/AudioFileCompressedTests.swift new file mode 100644 index 0000000..4c6c1fd --- /dev/null +++ b/Tests/LyrebirdTests/Buffers/AudioFileCompressedTests.swift @@ -0,0 +1,177 @@ +// AudioFileCompressedTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import AudioToolbox +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@Suite("AudioFileFormat compressed (AAC / ALAC)") +struct AudioFileCompressedTests { + + // MARK: - Derived properties + + @Test("Compressed derived properties") + func compressedProps() { + for format: AudioFileFormat in [.aacHigh, .aacMedium, .alac] { + #expect(format.audioFileTypeID == kAudioFileM4AType) + #expect(format.fileExtension == "m4a") + #expect(format.isCompressed == true) + #expect(format.isFloatEncoding == false) + #expect(format.usesRF64Writer == false) + #expect(format.supportsLargeFiles == true) // not RIFF → 4 GB guard N/A + #expect(format.riffOverflow(frameCount: Int.max / 4, channels: 8) == nil) + } + #expect(AudioFileFormat.aacHigh.aacBitrate == 256_000) + #expect(AudioFileFormat.aacMedium.aacBitrate == 128_000) + #expect(AudioFileFormat.alac.aacBitrate == nil) + } + + // MARK: - Container type on disk + + @Test("Written m4a carries the requested codec", arguments: [ + (AudioFileFormat.aacHigh, kAudioFormatMPEG4AAC), + (AudioFileFormat.aacMedium, kAudioFormatMPEG4AAC), + (AudioFileFormat.alac, kAudioFormatAppleLossless), + ]) + func writtenCodecMatches(format: AudioFileFormat, formatID: AudioFormatID) throws { + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 4096) + buffer.fillSine() + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a") + defer { try? FileManager.default.removeItem(at: url) } + + try buffer.write(to: url, format: format, sampleRate: 44100) + + var fileRef: ExtAudioFileRef? + #expect(ExtAudioFileOpenURL(url as CFURL, &fileRef) == noErr) + let ref: ExtAudioFileRef = try #require(fileRef) + defer { ExtAudioFileDispose(ref) } + var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() + var size: UInt32 = UInt32(MemoryLayout.size) + #expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr) + #expect(asbd.mFormatID == formatID) + } + + // MARK: - ALAC round-trip (lossless of the 24-bit source) + + @Test("ALAC round-trips through CoreAudio within 24-bit tolerance") + func alacRoundTrip() throws { + let frameCount: Int = 4096 + let values: [Double] = (0.. frameCount / 2) // most of the signal survived + var maxErr: Double = 0 + for i: Int in 0.. frameCount / 2) + + // RMS of the decoded interior (skip the primed head) should be near the + // input sine's RMS (amplitude / sqrt(2)); AAC is lossy so allow a wide band. + let skip: Int = 2048 + guard loaded.count > skip else { Issue.record("decoded too short"); return } + var sumSquares: Double = 0 + var n: Int = 0 + for i: Int in skip.. 0) ? (sumSquares / Double(n)).squareRoot() : 0 + let expectedRMS: Double = amplitude / 2.0.squareRoot() + #expect(rms > expectedRMS * 0.6 && rms < expectedRMS * 1.4, + "AAC decoded RMS \(rms) not near expected \(expectedRMS)") + } + + // MARK: - Bitrate config actually takes effect + + /// The AAC bitrate tiers must differ on disk — proves `applyEncoderConfig` set the + /// encoder bitrate rather than silently no-opping (both would otherwise default). + @Test("aacHigh produces a larger file than aacMedium") + func aacBitrateTiersDiffer() throws { + let frameCount: Int = 44100 // ~1 s of broadband content at 44.1 kHz + var rng: UInt64 = 0x1234_5678 + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount) + buffer.fill { _, _ in + // Cheap white-ish noise (xorshift) — broadband so bitrate matters. + rng ^= rng << 13; rng ^= rng >> 7; rng ^= rng << 17 + return (Double(rng % 20000) / 10000.0 - 1.0) * 0.3 + } + + func fileSize(_ format: AudioFileFormat) throws -> Int { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a") + defer { try? FileManager.default.removeItem(at: url) } + try buffer.write(to: url, format: format, sampleRate: 44100) + let attrs: [FileAttributeKey: Any] = try FileManager.default.attributesOfItem(atPath: url.path) + return (attrs[.size] as? Int) ?? 0 + } + + let highSize: Int = try fileSize(.aacHigh) + let mediumSize: Int = try fileSize(.aacMedium) + #expect(highSize > mediumSize, + "aacHigh (\(highSize) B) should exceed aacMedium (\(mediumSize) B)") + } + + // MARK: - DiskOut rejects compressed + + @MainActor + @Test("DiskOut.Audio rejects compressed formats", arguments: [ + AudioFileFormat.aacHigh, .aacMedium, .alac + ]) + func diskOutRejectsCompressed(format: AudioFileFormat) { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a") + defer { try? FileManager.default.removeItem(at: url) } + #expect { + _ = try DiskOut.Audio(source: 0.0 as Double, channelCount: 1, url: url, + sampleRate: 44100, format: format) + } throws: { error in + guard case DiskOutError.compressedFormatNotSupported(let rejected) = error + else { return false } + return rejected == format + } + // The guard fires before file creation — no file should exist. + #expect(!FileManager.default.fileExists(atPath: url.path)) + } +} diff --git a/Tests/LyrebirdTests/Buffers/AudioFileFormatTests.swift b/Tests/LyrebirdTests/Buffers/AudioFileFormatTests.swift new file mode 100644 index 0000000..c05c1cb --- /dev/null +++ b/Tests/LyrebirdTests/Buffers/AudioFileFormatTests.swift @@ -0,0 +1,278 @@ +// AudioFileFormatTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import AudioToolbox +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@Suite("AudioFileFormat") +struct AudioFileFormatTests { + + // MARK: - Derived properties (golden per case) + + @Test("Container type IDs per case") + func containerTypeIDs() { + #expect(AudioFileFormat.wavFloat32.audioFileTypeID == kAudioFileWAVEType) + #expect(AudioFileFormat.wavInt16.audioFileTypeID == kAudioFileWAVEType) + #expect(AudioFileFormat.wavInt24.audioFileTypeID == kAudioFileWAVEType) + #expect(AudioFileFormat.aiffFloat32.audioFileTypeID == kAudioFileAIFCType) + #expect(AudioFileFormat.cafFloat32.audioFileTypeID == kAudioFileCAFType) + } + + @Test("File extensions per case") + func fileExtensions() { + #expect(AudioFileFormat.wavFloat32.fileExtension == "wav") + #expect(AudioFileFormat.wavInt16.fileExtension == "wav") + #expect(AudioFileFormat.wavInt24.fileExtension == "wav") + #expect(AudioFileFormat.aiffFloat32.fileExtension == "aiff") + #expect(AudioFileFormat.cafFloat32.fileExtension == "caf") + } + + @Test("Bit depth per case") + func bitDepths() { + #expect(AudioFileFormat.wavFloat32.fileBitsPerChannel == 32) + #expect(AudioFileFormat.wavInt16.fileBitsPerChannel == 16) + #expect(AudioFileFormat.wavInt24.fileBitsPerChannel == 24) + #expect(AudioFileFormat.aiffFloat32.fileBitsPerChannel == 32) + #expect(AudioFileFormat.cafFloat32.fileBitsPerChannel == 32) + } + + @Test("Float vs integer encoding per case") + func floatEncoding() { + #expect(AudioFileFormat.wavFloat32.isFloatEncoding == true) + #expect(AudioFileFormat.aiffFloat32.isFloatEncoding == true) + #expect(AudioFileFormat.cafFloat32.isFloatEncoding == true) + #expect(AudioFileFormat.wavInt16.isFloatEncoding == false) + #expect(AudioFileFormat.wavInt24.isFloatEncoding == false) + } + + @Test("Endianness per case (only AIFF-C is big-endian)") + func endianness() { + #expect(AudioFileFormat.aiffFloat32.isBigEndian == true) + #expect(AudioFileFormat.wavFloat32.isBigEndian == false) + #expect(AudioFileFormat.wavInt16.isBigEndian == false) + #expect(AudioFileFormat.wavInt24.isBigEndian == false) + #expect(AudioFileFormat.cafFloat32.isBigEndian == false) + } + + // MARK: - Back-compat shorthands + + @Test("Back-compat shorthands map to Float32 cases") + func backCompatShorthands() { + #expect(AudioFileFormat.wav == .wavFloat32) + #expect(AudioFileFormat.aiff == .aiffFloat32) + #expect(AudioFileFormat.caf == .cafFloat32) + } + + /// The deprecated `DiskOutFormat` alias still resolves for external source + /// compatibility. Annotated deprecated so the alias reference does not raise an + /// in-tree deprecation warning (the whole point of the alias is out-of-tree use). + @available(*, deprecated, message: "Exercises the deprecated DiskOutFormat alias.") + @Test("DiskOutFormat alias still resolves to AudioFileFormat") + func diskOutFormatAliasResolves() { + #expect(DiskOutFormat.wavFloat32 == AudioFileFormat.wavFloat32) + #expect(DiskOutFormat.aiff == AudioFileFormat.aiffFloat32) + } + + // MARK: - makeFileASBD golden fields + + @Test("File ASBD — WAV Float32 stereo") + func fileASBDWavFloat32() { + let asbd: AudioStreamBasicDescription = + AudioFileFormat.wavFloat32.makeFileASBD(sampleRate: 48000, channels: 2) + #expect(asbd.mSampleRate == 48000) + #expect(asbd.mFormatID == kAudioFormatLinearPCM) + #expect(asbd.mBitsPerChannel == 32) + #expect(asbd.mChannelsPerFrame == 2) + #expect(asbd.mFramesPerPacket == 1) + #expect(asbd.mBytesPerFrame == 8) // 4 bytes/sample × 2 ch + #expect(asbd.mBytesPerPacket == 8) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0) + } + + @Test("File ASBD — WAV Int16 mono") + func fileASBDWavInt16() { + let asbd: AudioStreamBasicDescription = + AudioFileFormat.wavInt16.makeFileASBD(sampleRate: 44100, channels: 1) + #expect(asbd.mBitsPerChannel == 16) + #expect(asbd.mBytesPerFrame == 2) // 2 bytes/sample × 1 ch + #expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0) + } + + @Test("File ASBD — WAV Int24 packed stereo") + func fileASBDWavInt24() { + let asbd: AudioStreamBasicDescription = + AudioFileFormat.wavInt24.makeFileASBD(sampleRate: 96000, channels: 2) + #expect(asbd.mBitsPerChannel == 24) + #expect(asbd.mBytesPerFrame == 6) // 3 bytes/sample × 2 ch (packed) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsPacked != 0) + } + + @Test("File ASBD — AIFF-C Float32 is big-endian") + func fileASBDAiffFloat32() { + let asbd: AudioStreamBasicDescription = + AudioFileFormat.aiffFloat32.makeFileASBD(sampleRate: 48000, channels: 1) + #expect(asbd.mBitsPerChannel == 32) + #expect(asbd.mBytesPerFrame == 4) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian != 0) + } + + // MARK: - makeClientASBD always native Float32 + + @Test("Client ASBD is native-endian Float32 regardless of file encoding") + func clientASBDAlwaysFloat32() { + for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32] { + let asbd: AudioStreamBasicDescription = + format.makeClientASBD(sampleRate: 48000, channels: 2) + #expect(asbd.mFormatID == kAudioFormatLinearPCM) + #expect(asbd.mBitsPerChannel == 32) + #expect(asbd.mBytesPerFrame == 8) // Float32 × 2 ch + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsBigEndian == 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger == 0) + } + } + + // MARK: - Large-file guard + + @Test("supportsLargeFiles is true only for CAF") + func supportsLargeFiles() { + #expect(AudioFileFormat.cafFloat32.supportsLargeFiles == true) + for format: AudioFileFormat in [.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32] { + #expect(format.supportsLargeFiles == false) + } + } + + @Test("projectedByteCount tracks the format's bit depth") + func projectedByteCount() { + let frames: Int = 100 + let channels: Int = 2 + let bytesFloat32: Int = 4 + let bytesInt16: Int = 2 + let bytesInt24: Int = 3 + #expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32) + #expect(AudioFileFormat.wavInt16.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt16) + #expect(AudioFileFormat.wavInt24.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesInt24) + #expect(AudioFileFormat.aiffFloat32.projectedByteCount(frameCount: frames, channels: channels) == frames * channels * bytesFloat32) + } + + @Test("riffOverflow flags an oversize WAV at the boundary and exempts CAF") + func riffOverflowBoundary() { + let cap: Int = lyrebirdMaxRIFFBytes + let bytesPerSampleFloat32: Int = 4 + // Largest mono Float32 frame count that still fits under the cap. + let underFrames: Int = cap / bytesPerSampleFloat32 + #expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames, channels: 1) == nil) + + // One frame past that overflows (the cap's remainder mod 4 < 4 guarantees crossing). + let over: (projected: Int, cap: Int)? = + AudioFileFormat.wavFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1) + #expect(over != nil) + #expect(over?.cap == cap) + #expect((over?.projected ?? 0) > cap) + + // AIFF-C is likewise 32-bit-capped. + #expect(AudioFileFormat.aiffFloat32.riffOverflow(frameCount: underFrames + 1, channels: 1) != nil) + + // CAF is 64-bit — never flagged, even for absurd sizes. (Returns nil before + // projectedByteCount runs, so the multiply cannot overflow Int.) + #expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: Int.max / 8, channels: 8) == nil) + } + + @Test("projectedByteCount / riffOverflow saturate instead of trapping on overflow") + func projectedByteCountOverflowSafe() { + // A frame count large enough to overflow the byte product must saturate to + // Int.max (no trap) and be reported as over-cap for a 32-bit container. + #expect(AudioFileFormat.wavFloat32.projectedByteCount(frameCount: Int.max, channels: 8) == Int.max) + let over: (projected: Int, cap: Int)? = + AudioFileFormat.wavFloat32.riffOverflow(frameCount: Int.max, channels: 8) + #expect(over != nil) + #expect(over?.projected == Int.max) + } + + @Test("LyrebirdBuffer.write throws fileTooLargeForContainer for oversize WAV projection") + func bufferWriteGuardDecision() { + // The decision the buffer guard makes is exactly riffOverflow — asserted here + // without allocating a multi-GB buffer. A 200M-frame × 8ch Float32 projection + // is ~6.4 GB > cap. + let frames: Int = 200_000_000 + let channels: Int = 8 + #expect(AudioFileFormat.wavFloat32.riffOverflow(frameCount: frames, channels: channels) != nil) + #expect(AudioFileFormat.cafFloat32.riffOverflow(frameCount: frames, channels: channels) == nil) + } + + // MARK: - Round-trip: write via factory-backed LyrebirdBuffer.write, reload + + /// Write a mono ramp buffer in each Float32 container and reload it, confirming + /// sample rate, frame count, and channel count survive the round-trip. + @Test("Round-trip write→load preserves rate/frames/channels", arguments: [ + AudioFileFormat.wavFloat32, .aiffFloat32, .cafFloat32 + ]) + func roundTripFloat32(format: AudioFileFormat) throws { + let frameCount: Int = 256 + let sampleRate: Double = 44100 + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: frameCount) + for i: Int in 0...size) + let status: OSStatus = ExtAudioFileGetProperty( + fileRef2, kExtAudioFileProperty_FileDataFormat, &size, &fileASBD + ) + #expect(status == noErr) + #expect(fileASBD.mBitsPerChannel == format.fileBitsPerChannel) + let isFloat: Bool = fileASBD.mFormatFlags & kAudioFormatFlagIsFloat != 0 + #expect(isFloat == format.isFloatEncoding) + } +} diff --git a/Tests/LyrebirdTests/Buffers/RF64WriterTests.swift b/Tests/LyrebirdTests/Buffers/RF64WriterTests.swift new file mode 100644 index 0000000..310e7e3 --- /dev/null +++ b/Tests/LyrebirdTests/Buffers/RF64WriterTests.swift @@ -0,0 +1,157 @@ +// RF64WriterTests.swift +// Lyrebird +// +// Copyright (c) 2026 Joshua Parmenter / realizedsound +// SPDX-License-Identifier: MIT + +import Testing +import Foundation +import AudioToolbox +@testable @_spi(LyrebirdExtensions) import LyrebirdSynth + +@Suite("RF64Writer") +struct RF64WriterTests { + + // MARK: - Header golden bytes + + @Test("RF64 header has RF64/WAVE/ds64/fmt/data structure") + func headerStructure() throws { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("wav") + defer { try? FileManager.default.removeItem(at: url) } + + let buffer: LyrebirdBuffer = LyrebirdBuffer(count: 8, channelCount: 2) + try buffer.write(to: url, format: .rf64Float32, sampleRate: 48000) + + let data: Data = try Data(contentsOf: url) + #expect(data.count >= 104) + func fourCC(_ off: Int) -> String { String(decoding: data[off.. UInt32 { + data[off.. 0) + for f: Int in 1.. Void) = try makeScratchDir() + defer { cleanup() } + + let host: EngineHost = EngineHost() + // A non-default format (WAV / Int16) must reach the output file. + let outURL: URL = dir.appendingPathComponent("stem.wav") + let jobs: [NRTJob] = [ + NRTJob( + outputURL: outURL, + duration: 0.05, + format: .wavInt16, + blockSize: 64, + sampleRate: 44100, + numOutputChannels: 2 + ) { engine in + try nrtBuildAdd(engine) { ConstSynth(value: 0.25) } + } + ] + + var results: [NRTResult] = [] + for try await result: NRTResult in host.renderConcurrent(jobs: jobs) { + results.append(result) + } + #expect(results.count == 1) + + var fileRef: ExtAudioFileRef? + #expect(ExtAudioFileOpenURL(outURL as CFURL, &fileRef) == noErr) + let ref: ExtAudioFileRef = try #require(fileRef) + defer { ExtAudioFileDispose(ref) } + var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() + var size: UInt32 = UInt32(MemoryLayout.size) + #expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr) + #expect(asbd.mBitsPerChannel == 16) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsSignedInteger != 0) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat == 0) + } + @Test func renderConcurrentPropagatesBuildFailure() async throws { let (dir, cleanup): (URL, () -> Void) = try makeScratchDir() defer { cleanup() } diff --git a/Tests/LyrebirdTests/LyrebirdBufferFileIOTests.swift b/Tests/LyrebirdTests/LyrebirdBufferFileIOTests.swift index cab34c0..35ad1d5 100644 --- a/Tests/LyrebirdTests/LyrebirdBufferFileIOTests.swift +++ b/Tests/LyrebirdTests/LyrebirdBufferFileIOTests.swift @@ -176,6 +176,21 @@ private func writeTempMultichannelWAV(channels: [[Float]], sampleRate: Double = return url } +/// Reopen a written file and assert its on-disk PCM bit depth. A pure error-tolerance +/// check cannot tell "correctly quantised to N-bit" from "quantiser silently disabled, +/// still Float32" — a lossless Float32 round-trip has error smaller than the N-bit LSB +/// tolerance and would pass. This positively confirms the integer encoding happened. +private func expectFileBitDepth(_ url: URL, _ expected: UInt32) throws { + 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.size) + #expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr) + #expect(asbd.mBitsPerChannel == expected) +} + // MARK: - load(url:channel:normalise:) @MainActor @@ -409,6 +424,62 @@ struct LyrebirdBufferWriteTests { } } + @Test("write + load round-trip for WAV Int16 stays within one LSB") + func roundTripWavInt16() throws { + // A ramp across [-1, 1] exercises the quantiser over its full range. + let frameCount: Int = 64 + let values: [Double] = (0.. SynthesisEngine { + let driver: NRTDriver = NRTDriver(outputURL: outputURL, duration: duration, + format: format) + return SynthesisEngine( + blockSize: 512, + sampleRate: sampleRate, + numOutputChannels: numOutputChannels, + numInputChannels: 0, + numAudioBuses: 128, + numControlBuses: 4096, + driver: driver + ) + } + + /// Render a short job in each container/encoding, then reopen the file and + /// assert its on-disk data format matches the requested case, plus the frame + /// count and channel count survive. + @Test("NRT output honours the requested container/encoding", arguments: [ + AudioFileFormat.wavFloat32, .wavInt16, .wavInt24, .aiffFloat32, .cafFloat32 + ]) + func nrtOutputFormat(format: AudioFileFormat) throws { + let sampleRate: Double = 44100 + let numOutputChannels: Int = 2 + let duration: Double = 0.1 + // Matches NRTDriver's block math: ceil(duration * SR / blockSize) * blockSize. + let blockSize: Int = 512 + let totalBlocks: Int = Int((duration * sampleRate / Double(blockSize)).rounded(.up)) + let expectedFrames: Int = totalBlocks * blockSize + + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString) + .appendingPathExtension(format.fileExtension) + defer { try? FileManager.default.removeItem(at: url) } + + let engine: SynthesisEngine = makeFormatEngine( + outputURL: url, format: format, duration: duration, + sampleRate: sampleRate, numOutputChannels: numOutputChannels + ) + try engine.add(ConstantThrough()) + try engine.start() + #expect(FileManager.default.fileExists(atPath: url.path)) + + var fileRef: ExtAudioFileRef? + let openStatus: OSStatus = ExtAudioFileOpenURL(url as CFURL, &fileRef) + #expect(openStatus == noErr) + let ref: ExtAudioFileRef = try #require(fileRef) + defer { ExtAudioFileDispose(ref) } + + var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription() + var propSize: UInt32 = UInt32(MemoryLayout.size) + let fmtStatus: OSStatus = ExtAudioFileGetProperty( + ref, kExtAudioFileProperty_FileDataFormat, &propSize, &asbd + ) + #expect(fmtStatus == noErr) + #expect(asbd.mChannelsPerFrame == UInt32(numOutputChannels)) + #expect(asbd.mBitsPerChannel == format.fileBitsPerChannel) + let isFloat: Bool = asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0 + #expect(isFloat == format.isFloatEncoding) + + var frameCount: Int64 = 0 + var countSize: UInt32 = UInt32(MemoryLayout.size) + let countStatus: OSStatus = ExtAudioFileGetProperty( + ref, kExtAudioFileProperty_FileLengthFrames, &countSize, &frameCount + ) + #expect(countStatus == noErr) + #expect(Int(frameCount) == expectedFrames) + } + + /// A WAV render projected past the 4 GB RIFF cap must throw before rendering — + /// no file created, no per-block allocation. Driven by an absurd duration so the + /// guard fires immediately (the render loop is never entered). + @Test("NRT throws fileTooLargeForContainer for an oversize WAV render") + func nrtRejectsOversizeWav() { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("wav") + defer { try? FileManager.default.removeItem(at: url) } + + let engine: SynthesisEngine = makeFormatEngine( + outputURL: url, format: .wavFloat32, duration: 100_000_000, + sampleRate: 48000, numOutputChannels: 2 + ) + #expect { + try engine.start() + } throws: { error in + guard case NRTDriverError.fileTooLargeForContainer(let projected, let cap) = error + else { return false } + return cap == lyrebirdMaxRIFFBytes && projected > cap + } + // Guard runs before ExtAudioFileCreateWithURL — the file must not exist. + #expect(!FileManager.default.fileExists(atPath: url.path)) + } + + /// NRT can render to the compressed M4A codecs (AAC / ALAC) via ExtAudioFile. + /// Read back through CoreAudio to prove the container is valid and non-silent. + @Test("NRT compressed (AAC / ALAC) render round-trips through CoreAudio", arguments: [ + AudioFileFormat.aacHigh, .alac + ]) + func nrtCompressedRoundTrip(format: AudioFileFormat) throws { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("m4a") + defer { try? FileManager.default.removeItem(at: url) } + + let engine: SynthesisEngine = makeFormatEngine( + outputURL: url, format: format, duration: 0.2, + sampleRate: 44100, numOutputChannels: 2 + ) + try engine.add(ConstantThrough()) + try engine.start() + #expect(FileManager.default.fileExists(atPath: url.path)) + + let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url) + #expect(reloaded.channelCount == 2) + #expect(reloaded.count > 0) + // Non-silent: the constant-0.5 source should decode to meaningful energy. + var peak: Double = 0 + for f: Int in 0.. 0.1, "compressed NRT render decoded near-silent (peak \(peak))") + } + + /// A non-finite, negative, or astronomically large duration must throw + /// `invalidDuration` rather than trapping in the `Int(Double)` block-count + /// conversion or the render range. `1e20` is finite and positive but its block + /// count exceeds `Int.max`, exercising the `< Double(Int.max)` bound. + @Test("NRT throws invalidDuration for NaN / negative / astronomical duration", arguments: [ + Double.nan, -1.0, -0.001, Double.infinity, 1e20 + ]) + func nrtRejectsInvalidDuration(duration: Double) { + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("caf") + defer { try? FileManager.default.removeItem(at: url) } + let engine: SynthesisEngine = makeFormatEngine( + outputURL: url, format: .cafFloat32, duration: duration + ) + #expect { + try engine.start() + } throws: { error in + guard case NRTDriverError.invalidDuration = error else { return false } + return true + } + } + + /// NRT can render to RF64 (64-bit WAV via RF64Writer). Read back through the + /// CoreAudio reader to prove the container is valid. + @Test("NRT RF64 render round-trips through CoreAudio reader", arguments: [ + AudioFileFormat.rf64Float32, .rf64Int24 + ]) + func nrtRF64RoundTrip(format: AudioFileFormat) throws { + let sampleRate: Double = 44100 + let numOutputChannels: Int = 2 + let duration: Double = 0.05 + let url: URL = FileManager.default.temporaryDirectory + .appendingPathComponent(UUID().uuidString).appendingPathExtension("wav") + defer { try? FileManager.default.removeItem(at: url) } + + let engine: SynthesisEngine = makeFormatEngine( + outputURL: url, format: format, duration: duration, + sampleRate: sampleRate, numOutputChannels: numOutputChannels + ) + try engine.add(ConstantThrough()) + try engine.start() + #expect(FileManager.default.fileExists(atPath: url.path)) + + // Reopen with CoreAudio (RF64-aware reader) and verify the constant 0.5 output. + let reloaded: LyrebirdBuffer = try LyrebirdBuffer.loadAllChannels(url: url) + #expect(reloaded.channelCount == numOutputChannels) + #expect(reloaded.count > 0) + let tolerance: Double = format == .rf64Int24 ? 2.0 / 8388608.0 : 1e-5 + // Interior frames (skip the very first, which can be a startup zero). + for f: Int in 1...size) + #expect(ExtAudioFileGetProperty(ref, kExtAudioFileProperty_FileDataFormat, &size, &asbd) == noErr) + #expect(asbd.mBitsPerChannel == 32) + #expect(asbd.mFormatFlags & kAudioFormatFlagIsFloat != 0) + } +} + +/// A synth that writes a constant to both output buses so the rendered file is +/// non-silent and integer encodings carry a verifiable non-zero value. +private final class ConstantThrough: SynthesizerBase { + override func build() { + output(bus: 0, source: 0.5) + output(bus: 1, source: 0.5) + } } diff --git a/Tests/LyrebirdTests/Process/LyrebirdEventListRecordingTests.swift b/Tests/LyrebirdTests/Process/LyrebirdEventListRecordingTests.swift index 0e29fc8..c40b9cd 100644 --- a/Tests/LyrebirdTests/Process/LyrebirdEventListRecordingTests.swift +++ b/Tests/LyrebirdTests/Process/LyrebirdEventListRecordingTests.swift @@ -282,6 +282,28 @@ struct LyrebirdEventListRecordingTests { eventList.killAll() } + @Test("record() rejects compressed formats — recording stays disabled", arguments: [ + AudioFileFormat.aacHigh, .aacMedium, .alac + ]) + func testRecordRejectsCompressed(format: AudioFileFormat) throws { + let tempDir: URL = makeTempDir() + defer { removeTempDir(tempDir) } + + let engine: SynthesisEngine = makeRecordingTestEngine() + let eventList: LyrebirdEventList = try LyrebirdEventList( + id: "compressed-reject-list", + events: [], + engine: engine, + bus: AudioBus(index: 0, channelCount: 2) + ) + + // Compressed stems are unsupported (DiskOut is PCM/RF64 only) — record() must + // refuse and leave recording disabled rather than fail silently per-process. + eventList.record(directory: tempDir, format: format) + #expect(eventList.isRecording == false) + #expect(eventList.recordDirectory == nil) + } + // MARK: - Test 2: filename format verification @Test("stem filename encodes eventListID, offset, processID, playIndex") diff --git a/docs/engine/multi-engine-host.md b/docs/engine/multi-engine-host.md index 0de0d47..6ec06c1 100644 --- a/docs/engine/multi-engine-host.md +++ b/docs/engine/multi-engine-host.md @@ -122,6 +122,7 @@ let jobs: [NRTJob] = mixes.enumerated().map { i, mix in NRTJob( outputURL: outDir.appendingPathComponent("mix_\(i).caf"), duration: 4.0, + format: .cafFloat32, // default; use .wavFloat32 / .aiffFloat32 / .wavInt16 / .wavInt24 for interchange blockSize: 512, sampleRate: 48000, numOutputChannels: 2 diff --git a/docs/stdlib/generators.md b/docs/stdlib/generators.md index e2aee3f..83091ae 100644 --- a/docs/stdlib/generators.md +++ b/docs/stdlib/generators.md @@ -2052,13 +2052,21 @@ let writer = try DiskOut.Audio( channelCount: 2, url: url, sampleRate: engine.sampleRate, - format: .wavFloat32, // .aiff / .wavFloat32 / .wavInt16 / .wavInt24 / .aiffFloat32 + format: .wavFloat32, // .wavFloat32 / .wavInt16 / .wavInt24 / .aiffFloat32 / .cafFloat32 / .rf64Float32 / .rf64Int24 bufferFrames: 8192 ) ``` -- Format encoded by `DiskOutFormat` enum (file extension + sample format). -- Writes from a background thread; RT pushes to a lock-free SPSC queue. +- Format encoded by the `AudioFileFormat` enum (`DiskOutFormat` is an alias) — file extension + sample format. +- **PCM / RF64 only**: the compressed codecs (`.aacHigh` / `.aacMedium` / `.alac`) throw `DiskOutError.compressedFormatNotSupported` — real-time streaming of a compressed encoder is out of scope. Render AAC/ALAC offline via `LyrebirdBuffer.write` or `NRTDriver`. +- Writes from a background thread; the RT thread publishes into a lock-free ring buffer via atomic frame counters (not an `SPSCQueue`). +- **4 GB cap on WAV/AIFF**: a long streaming recording to a WAV or AIFF-C target stops + growing once the file reaches the 4 GB container limit (`lyrebirdMaxRIFFBytes`) — a + recording already in flight can't retroactively throw, so frames past the cap are + **silently dropped** and the audio already written stays valid. Poll `writer.fileTooLarge` + after `close()` to detect it. For long sessions record to a 64-bit container: + `.cafFloat32`, or `.rf64Float32` / `.rf64Int24` (RF64/BW64 — keeps the `.wav` extension, + streamed via `RF64Writer` with the `ds64` sizes patched on `close()`). --- diff --git a/docs/tooling/nrt-guide.md b/docs/tooling/nrt-guide.md index b0ef36b..71657a8 100644 --- a/docs/tooling/nrt-guide.md +++ b/docs/tooling/nrt-guide.md @@ -329,18 +329,36 @@ afconvert -f WAVE -d LEF32 output.caf output.wav ### `LyrebirdBuffer.write()` — AIFF, WAV, or CAF ```swift -try buf.write(to: url, format: .caf, sampleRate: 44100) // default -try buf.write(to: url, format: .aiff, sampleRate: 44100) // AIFF-C, Float32 -try buf.write(to: url, format: .wav, sampleRate: 44100) // WAV, Float32 +try buf.write(to: url, format: .cafFloat32, sampleRate: 44100) // default +try buf.write(to: url, format: .aiffFloat32, sampleRate: 44100) // AIFF-C, Float32 +try buf.write(to: url, format: .wavFloat32, sampleRate: 44100) // WAV, Float32 + +// Integer WAV encodings, for smaller files / DAW interchange: +try buf.write(to: url, format: .wavInt16, sampleRate: 44100) // WAV, 16-bit PCM +try buf.write(to: url, format: .wavInt24, sampleRate: 44100) // WAV, 24-bit PCM ``` -| Format | Extension | Endian | Channels | Notes | -|---|---|---|---|---| -| `.caf` | `.caf` | little-endian | up to 8 | Best for macOS; default | -| `.aiff` | `.aiff` | big-endian | ≤ 2 recommended | Broad DAW compatibility | -| `.wav` | `.wav` | little-endian | up to 8 | Cross-platform standard | +| Format | Extension | Endian | Encoding | Channels | Notes | +|---|---|---|---|---|---| +| `.cafFloat32` | `.caf` | little-endian | 32-bit float | up to 8 | Best for macOS; default | +| `.aiffFloat32` | `.aiff` | big-endian | 32-bit float | ≤ 2 recommended | Broad DAW compatibility | +| `.wavFloat32` | `.wav` | little-endian | 32-bit float | up to 8 | Cross-platform standard | +| `.wavInt16` | `.wav` | little-endian | 16-bit PCM | up to 8 | Smaller files; lossy quantise | +| `.wavInt24` | `.wav` | little-endian | 24-bit PCM | up to 8 | Common DAW interchange depth | +| `.rf64Float32` | `.wav` | little-endian | 32-bit float | up to 8 | RF64/BW64 — 64-bit sizes, **no 4 GB cap** | +| `.rf64Int24` | `.wav` | little-endian | 24-bit PCM | up to 8 | RF64/BW64 — 64-bit sizes, **no 4 GB cap** | +| `.aacHigh` / `.aacMedium` | `.m4a` | — | AAC (lossy) ~256 / ~128 kbps | up to 8 | Compressed. **Offline writers only.** Not sample-accurate. | +| `.alac` | `.m4a` | — | Apple Lossless (24-bit source) | up to 8 | Compressed lossless. **Offline writers only.** | -All formats write 32-bit float samples (Float32). The `Double` (Double) values in the buffer are converted to Float32 on the way out. +The buffer's `Double` samples are handed to `ExtAudioFile` as native Float32; the +container's on-disk encoding drives the conversion — the Float32 cases are lossless, +the integer cases quantise to signed 16/24-bit PCM. (`.caf` / `.aiff` / `.wav` remain +as Float32 shorthands for the corresponding `…Float32` cases.) + +The `.rf64*` cases keep the `.wav` extension but use RF64/BW64 (EBU Tech 3306) — 64-bit +sizes in a `ds64` chunk — so they are exempt from the 4 GB limit that makes plain +`.wav`/`.aiff` throw `fileTooLargeForContainer`. Lyrebird emits RF64 with its own +`RF64Writer` (`ExtAudioFile` has no RF64 writer); CoreAudio reads it back. --- @@ -423,6 +441,9 @@ if task.terminationStatus == 0 { | `NRTDriverError.cannotCreateFile` | Bad URL, permissions, or full disk | Check the path and disk space | | `NRTDriverError.writeFailed` | Disk I/O error during render | Check disk space and path permissions | | `LyrebirdBufferIOError.cannotCreateOutputFile` | Same as above for `write()` | | +| `NRTDriverError.invalidDuration` | `duration` is negative, NaN, or infinite | Pass a finite, non-negative duration | +| `NRTDriverError.fileTooLargeForContainer` | WAV/AIFF render projected past the 4 GB RIFF cap | Use `format: .cafFloat32`, or shorten `duration` | +| `LyrebirdBufferIOError.fileTooLargeForContainer` | `LyrebirdBuffer.write` to WAV/AIFF projected past 4 GB | Use `.cafFloat32`, or split/shorten the buffer | | Silent output / all-zeros file | Synthesizers added after `start()` | Move all `engine.add()` calls before `start()` | | File truncated short | `duration` too short for the patch | Increase `NRTDriver` duration |