Files
Lyrebird/Sources/Lyrebird/Buffers/AudioFileFormat+AudioToolbox.swift
T
josh b6fdee8bfc Lyrebird 2.0.0 — Linux support
Consolidated release: the cross-platform Linux port (engine, generators, CLI,
REPL, NRT, portable DSP), live ALSA audio + ALSA MIDI + POSIX OSC + portable
WAV codec, the GTK4 GUI (LyrebirdUI on the SwiftOpenUI backend), and the Linux
live-coding scratchpad (LiveCompile). Apple platforms unchanged; all additive.
See RELEASES.md and LINUX_README.md.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-09-10 21:09:11 -07:00

146 lines
5.9 KiB
Swift

// AudioFileFormat+AudioToolbox.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
// AudioToolbox-backed members of `AudioFileFormat`: `ExtAudioFile` container
// type IDs, the file/client `AudioStreamBasicDescription` factories, and the
// compressed-encoder configuration. Split out from the portable enum so the
// core (and every soundfile-format consumer) builds on platforms without
// AudioToolbox; on Linux/Windows these members simply do not exist and the
// portable WAV codec is used instead.
#if canImport(AudioToolbox)
import AudioToolbox
extension AudioFileFormat {
/// 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
}
}
}
// MARK: - ASBD factories (module-internal)
/// Encoder packet geometry (samples per packet) for the compressed codecs.
private let aacFramesPerPacket: UInt32 = 1024
private let alacFramesPerPacket: UInt32 = 4096
extension AudioFileFormat {
/// Build the *file* `AudioStreamBasicDescription` for this format: linear PCM
/// with the case's bit depth, encoding flags, and endianness, interleaved
/// across `channels`.
///
/// - 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 {
if isCompressed {
var asbd: AudioStreamBasicDescription = AudioStreamBasicDescription()
asbd.mSampleRate = sampleRate
asbd.mChannelsPerFrame = UInt32(channels)
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 / Self.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.
///
/// - 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.
///
/// Returns `noErr` on success (or when nothing needed doing), else the failing
/// `OSStatus`. Call from a non-RT thread, before the first `ExtAudioFileWrite`.
func applyEncoderConfig(to fileRef: ExtAudioFileRef) -> OSStatus {
guard let bitrate: Int = aacBitrate else { return noErr }
var converter: AudioConverterRef?
var converterSize: UInt32 = UInt32(MemoryLayout<AudioConverterRef?>.size)
let getStatus: OSStatus = ExtAudioFileGetProperty(
fileRef, kExtAudioFileProperty_AudioConverter, &converterSize, &converter
)
guard getStatus == noErr, let converter: AudioConverterRef else { return getStatus }
var rate: UInt32 = UInt32(bitrate)
let setStatus: OSStatus = AudioConverterSetProperty(
converter, kAudioConverterEncodeBitRate, UInt32(MemoryLayout<UInt32>.size), &rate
)
guard setStatus == noErr else { return setStatus }
var config: CFPropertyList? = nil
return withUnsafePointer(to: &config) { ptr in
ExtAudioFileSetProperty(
fileRef, kExtAudioFileProperty_ConverterConfig,
UInt32(MemoryLayout<CFPropertyList?>.size), ptr
)
}
}
}
#endif