From 566fa72d9a81ee87774397c9d8dde40a70ed9790 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 01/11] Made sampled sounds comparable --- Sources/GraphiteSound/SampledSound.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Sources/GraphiteSound/SampledSound.swift b/Sources/GraphiteSound/SampledSound.swift index 777b8d2..9b25348 100644 --- a/Sources/GraphiteSound/SampledSound.swift +++ b/Sources/GraphiteSound/SampledSound.swift @@ -5,7 +5,7 @@ import protocol Foundation.ContiguousBytes import struct Foundation.Data import GraphiteBase -public struct SampledSound: Sendable { +public struct SampledSound: Hashable, Sendable { public var encoding: SoundEncoding From 427090e53caed5dd07285310649aae57d1f6700c Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 02/11] Added sound commands, init bits and synthesizers --- Sources/GraphiteSound/SoundCommand.swift | 125 +++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Sources/GraphiteSound/SoundCommand.swift diff --git a/Sources/GraphiteSound/SoundCommand.swift b/Sources/GraphiteSound/SoundCommand.swift new file mode 100644 index 0000000..4ffd8c9 --- /dev/null +++ b/Sources/GraphiteSound/SoundCommand.swift @@ -0,0 +1,125 @@ +// The commands a sound channel takes: what SndDoCommand queues and +// SndDoImmediate runs at once, and the init bits and synthesizers a channel +// is made with. + +import GraphiteBase + +/// A channel's init bits (SndNewChannel's `init`, and reInitCmd's). +public struct SoundInit: OptionSet, Hashable, Sendable { + + public var rawValue: UInt32 + + public init(rawValue: UInt32) { + self.rawValue = rawValue + } + + /// initNoInterp: resample without interpolating between samples. + public static var noInterpolation: SoundInit { SoundInit(rawValue: 0x0004) } + /// initNoDrop: no drop-sample conversion. + public static var noDrop: SoundInit { SoundInit(rawValue: 0x0008) } + /// initMono. + public static var mono: SoundInit { SoundInit(rawValue: 0x0080) } + /// initStereo. + public static var stereo: SoundInit { SoundInit(rawValue: 0x00C0) } + /// initMACE3: 3:1 compression. + public static var mace3: SoundInit { SoundInit(rawValue: 0x0300) } + /// initMACE6: 6:1 compression. + public static var mace6: SoundInit { SoundInit(rawValue: 0x0400) } +} + +/// The synthesizers a channel can be made for: only sampled sounds are played. +public enum SoundSynth: Int16, Hashable, Sendable { + case squareWave = 1 + case waveTable = 3 + case sampled = 5 +} + +/// A sound command. A channel runs its queued commands in order: a +/// sampled sound holds the queue until it has played, a wait holds it for its +/// time, a sync until the other channels of the sync reach it, and the rest +/// run as they are reached. Immediate commands run at once. +public enum SoundCommand: Hashable, Sendable { + + /// nullCmd. + case null + + /// quietCmd: stops the sound that is playing. The queue goes on. + case quiet + + /// flushCmd: empties the queue. + case flush + + /// reInitCmd: the channel's init bits again, of which interpolation is + /// the one used. + case reInit(SoundInit) + + /// waitCmd: nothing, for a time in half-milliseconds. + case wait(halfMilliseconds: Int) + + /// pauseCmd: the queue holds still. The sound that is playing goes on. + case pause + + /// resumeCmd: the queue goes on. + case resume + + /// callBackCmd: the channel's callback is called with the command. + case callBack(param1: Int16, param2: Int32) + + /// syncCmd: waits until `count` channels have reached a sync of the same + /// identifier, then they all go on together. + case sync(count: Int16, identifier: Int32) + + /// bufferCmd and soundCmd: plays a sound, stopping the one that was playing. + case buffer(SampledSound) + + /// ampCmd: the channel's amplitude, 256 for as recorded. + case amplitude(Int) + + /// volumeCmd: the left and right volumes, 256 for as recorded; the channel + /// plays at the louder, panned toward the louder. + case volume(left: UInt16, right: UInt16) + + /// freqCmd: the MIDI note to play the sound at; its own base note plays it + /// as recorded. + case frequency(note: Int) + + /// rateCmd: the playback rate as a 16.16 multiplier of the sound's. + case rate(Int32) + + /// rateMultiplierCmd: the same. + case rateMultiplier(Int32) + + /// Repeats the sound whole, or as its loop says, until it is stopped + /// (false stops a loop the sound's header sets). + case loop(Bool) + + /// Holds the sound that is playing where it is, as SndPauseFilePlay does. + case pausePlayback + + /// Goes on from where the sound was held. + case resumePlayback + + /// The command of a command word and its two parameters, for the ones + /// that carry no sound: nil for bufferCmd and soundCmd, which point at a + /// sound, and for a command that isn't here. The word's high bit, which + /// says an 'snd ' resource has data for it, is ignored. + public init?(code: UInt16, param1: Int16, param2: Int32) { + switch code & 0x7FFF { + case 0: self = .null + case 3: self = .quiet + case 4: self = .flush + case 5: self = .reInit(SoundInit(rawValue: UInt32(bitPattern: param2))) + case 10: self = .wait(halfMilliseconds: Int(param1)) + case 11: self = .pause + case 12: self = .resume + case 13: self = .callBack(param1: param1, param2: param2) + case 14: self = .sync(count: param1, identifier: param2) + case 42: self = .frequency(note: Int(param2)) + case 43: self = .amplitude(Int(param1)) + case 46: self = .volume(left: UInt16(truncatingIfNeeded: param2), right: UInt16(truncatingIfNeeded: param2 >> 16)) + case 82: self = .rate(param2) + case 86: self = .rateMultiplier(param2) + default: return nil + } + } +} From 7ccdc34181951e01d49b0979c521973e23a76d05 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 03/11] Added the audio output a host provides --- Sources/GraphiteSound/AudioOutput.swift | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Sources/GraphiteSound/AudioOutput.swift diff --git a/Sources/GraphiteSound/AudioOutput.swift b/Sources/GraphiteSound/AudioOutput.swift new file mode 100644 index 0000000..43ff085 --- /dev/null +++ b/Sources/GraphiteSound/AudioOutput.swift @@ -0,0 +1,17 @@ +// Where a mixer's frames go: an audio device the host provides. + +/// A device that takes the mixer's output. The host implements it over +/// whatever it plays sound with. +public protocol AudioOutput: AnyObject, Sendable { + + /// The frames a second the device plays at, which the mixer renders at. + var sampleRate: Int { get } + + /// Starts playing: the device calls `render` with a buffer to fill for + /// each block it needs, of stereo frames, left then right, as floats of + /// -1 to 1. + func start(render: @escaping @Sendable (UnsafeMutableBufferPointer) -> Void) + + /// Stops playing and lets go of the `render` it was given. + func stop() +} From 7d002b17c514e4fe12ee1827dcde7b665b8faddb Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 04/11] Added what a sound channel plays and keeps --- Sources/GraphiteSound/ChannelState.swift | 125 +++++++++++++++++++++++ 1 file changed, 125 insertions(+) create mode 100644 Sources/GraphiteSound/ChannelState.swift diff --git a/Sources/GraphiteSound/ChannelState.swift b/Sources/GraphiteSound/ChannelState.swift new file mode 100644 index 0000000..ec813d7 --- /dev/null +++ b/Sources/GraphiteSound/ChannelState.swift @@ -0,0 +1,125 @@ +// What a channel plays and where it is: the sound as 16-bit frames ready to +// mix, the voice playing it, and the channel's settings and queue. Used only +// with the mixer's lock held. +// +// Adapted from cmixer by rxi (https://github.com/rxi/cmixer) and from Pomme: +// +// Copyright (c) 2017 rxi +// Copyright (c) 2020 Iliyas Jorio +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import GraphiteBase + +/// A sound decoded and checked, so that playing it can't fail. +struct PreparedSound { + + /// The frames' samples, a frame's channels after another. + var samples: [Int16] + var channels: Int + var frames: Int + var sampleRate: Double + var baseNote: Int + + /// The frames to repeat: a loop the sound's header has that is two frames + /// or more, and ends no later than the sound does. + var loop: Range? + + /// The rate of a sound that says none: 22254.54545, the rate of the + /// original Macintosh's 22 kHz. + static let defaultSampleRate = 22254.545 + + init(_ sound: SampledSound) throws(MacError) { + let samples = try sound.pcm16() + // pcm16 has refused a sound with no channels. + channels = sound.channels + frames = samples.count / sound.channels + self.samples = samples + sampleRate = sound.sampleRate > 0 ? sound.sampleRate : Self.defaultSampleRate + baseNote = sound.baseNote + if let loop = sound.loop { + let start = max(loop.lowerBound, 0) + let end = min(loop.upperBound, frames) + self.loop = end - start >= 2 ? start ..< end : nil + } + } +} + +/// A sound playing in a channel. +struct Voice { + var sound: PreparedSound + + /// The frame about to play, with a fraction of one. + var position = 0.0 + + var isPaused = false + + /// Called when the sound plays to its end; not when it is stopped. + var completion: (@Sendable () -> Void)? +} + +/// A channel's state. The mixer's lock guards it, which is why it is safe to +/// hand around. +final class ChannelState: @unchecked Sendable { + + /// The most commands a queue holds. + static let queueCapacity = 128 + + /// The most a channel amplifies a sound by. + static let maximumGain = 2.5 + + /// The handle the program has; the callback is called with it. + weak var handle: SoundChannel? + + var callBack: (@Sendable (SoundChannel, SoundCommand) -> Void)? + + var queue: [(command: SoundCommand, prepared: PreparedSound?)] = [] + + var voice: Voice? + + /// pauseCmd was run and resumeCmd hasn't been. + var isQueuePaused = false + + /// The frames a waitCmd has left. + var waitRemaining: Int? + + /// The identifier of the syncCmd the channel waits at. + var syncIdentifier: Int32? + + var gain = 1.0 + var pan = 0.0 + var playbackNote = 60 + var pitchMultiplier = 1.0 + var interpolates = true + + /// What loopCmd said, which stands until the next sound; nil goes by the + /// sound's header. + var loopOverride: Bool? + + /// Gone: its commands are errors. + var isDisposed = false + + /// To be gone when it has nothing left to do (SndDisposeChannel with + /// quietNow false). + var retiresWhenIdle = false + + var isIdle: Bool { + voice == nil && queue.isEmpty && waitRemaining == nil && syncIdentifier == nil + } +} From fb278ac5db31938f7c28cc41c87653af4371a54c Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 05/11] Added the mixer, with channels' queues, waits and syncs --- Sources/GraphiteSound/SoundMixer.swift | 405 +++++++++++++++++++++++++ 1 file changed, 405 insertions(+) create mode 100644 Sources/GraphiteSound/SoundMixer.swift diff --git a/Sources/GraphiteSound/SoundMixer.swift b/Sources/GraphiteSound/SoundMixer.swift new file mode 100644 index 0000000..d329f6c --- /dev/null +++ b/Sources/GraphiteSound/SoundMixer.swift @@ -0,0 +1,405 @@ +// The mixer: channels' sounds resampled to the device's rate, panned, +// amplified and added into stereo float frames. +// +// Adapted from cmixer by rxi (https://github.com/rxi/cmixer) and from Pomme: +// +// Copyright (c) 2017 rxi +// Copyright (c) 2020 Iliyas Jorio +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without restriction, including without limitation the rights +// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +// copies of the Software, and to permit persons to whom the Software is +// furnished to do so, subject to the following conditions: +// +// The above copyright notice and this permission notice shall be included in all +// copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +// SOFTWARE. + +import Synchronization +import GraphiteBase + +public final class SoundMixer: Sendable { + + /// The frames a second it renders. + public let sampleRate: Int + + private let state: Mutex + + /// The frames mixed between a channel's changes of what it is doing, which + /// is how closely channels that wait for each other start together. + static let slice = 64 + + /// A mixer that renders at a rate, for a program to pull frames from. + public init(sampleRate: Int = 44100) { + self.sampleRate = max(1, sampleRate) + state = Mutex(MixerState()) + } + + /// A mixer that plays through an audio device, at its rate, until `stop`. + /// The device holds the mixer while it plays. + public convenience init(output: any AudioOutput) { + self.init(sampleRate: output.sampleRate) + state.withLock { $0.output = output } + output.start { [self] buffer in render(into: buffer) } + } + + /// Stops the device the mixer plays through. + public func stop() { + let output = state.withLock { state in + defer { state.output = nil } + return state.output + } + output?.stop() + } + + // MARK: Volume + + /// The output's volume, each side, 1 for as mixed. Its default is 1. + public var outputVolume: (left: Double, right: Double) { + get { state.withLock { $0.volume } } + set { state.withLock { $0.volume = (max(0, newValue.left), max(0, newValue.right)) } } + } + + /// GetDefaultOutputVolume and SetDefaultOutputVolume: the output's volume + /// as the Sound Manager says it, the left in the low word and the right in + /// the high, 256 for full. + public var defaultOutputVolume: UInt32 { + get { + let volume = outputVolume + let left = UInt32(min(volume.left * 256, 65535)), right = UInt32(min(volume.right * 256, 65535)) + return right << 16 | left + } + set { + outputVolume = (Double(newValue & 0xFFFF) / 256, Double(newValue >> 16) / 256) + } + } + + /// SndSoundManagerVersion: 3.0.9, a final release, as a NumVersion. + public static var version: (major: UInt8, minorAndBugFix: UInt8, stage: UInt8, nonRelease: UInt8) { (3, 0x09, 0x80, 0) } + + // MARK: Channels + + /// SndNewChannel: a channel of a synthesizer. `unimplemented` for any but + /// sampled sounds. + public func newChannel( + synth: SoundSynth = .sampled, initBits: SoundInit = [], + callBack: (@Sendable (SoundChannel, SoundCommand) -> Void)? = nil + ) throws(MacError) -> SoundChannel { + guard synth == .sampled else { throw .unimplemented } + let channel = ChannelState() + channel.callBack = callBack + channel.interpolates = !initBits.contains(.noInterpolation) + let handle = SoundChannel(mixer: self, state: channel) + channel.handle = handle + state.withLock { $0.channels.append(channel) } + return handle + } + + /// The channels there are. + public var channelCount: Int { + state.withLock { $0.channels.count } + } + + // MARK: Rendering + + /// The next `frames` frames: stereo, left then right, as floats of -1 to + /// 1, with the output's volume applied and clipped. + public func render(frames: Int) -> [Float] { + var frames = [Float](repeating: 0, count: max(0, frames) * 2) + frames.withUnsafeMutableBufferPointer { render(into: $0) } + return frames + } + + /// Fills a buffer of stereo frames. Callbacks and completions it calls for + /// are called after the mixer is let go, so they can use its channels. + public func render(into buffer: UnsafeMutableBufferPointer) { + let frames = buffer.count / 2 + var events: [@Sendable () -> Void] = [] + state.withLock { state in + for index in 0 ..< frames * 2 { buffer[index] = 0 } + var offset = 0 + while offset < frames { + let count = min(Self.slice, frames - offset) + for channel in state.pendingReleases { channel.syncIdentifier = nil } + state.pendingReleases.removeAll() + for channel in state.channels { + state.advance(channel, frames: count, into: buffer, at: offset, sampleRate: sampleRate, events: &events) + } + offset += count + } + state.removeRetiredChannels() + let left = Float(state.volume.left), right = Float(state.volume.right) + for frame in 0 ..< frames { + buffer[frame * 2] = min(max(buffer[frame * 2] * left, -1), 1) + buffer[frame * 2 + 1] = min(max(buffer[frame * 2 + 1] * right, -1), 1) + } + } + for event in events { event() } + } + + // MARK: Channel operations, from SoundChannel + + func run(_ command: SoundCommand, completion: (@Sendable () -> Void)? = nil, on channel: ChannelState) throws(MacError) { + let prepared = try Self.prepare(command) + var events: [@Sendable () -> Void] = [] + try state.withLock { (state: inout MixerState) throws(MacError) in + guard !channel.isDisposed else { throw MacError.badChannel } + state.execute(command, prepared: prepared, completion: completion, on: channel, sampleRate: sampleRate, events: &events) + } + for event in events { event() } + } + + func enqueue(_ command: SoundCommand, on channel: ChannelState) throws(MacError) { + let prepared = try Self.prepare(command) + try state.withLock { (state: inout MixerState) throws(MacError) in + guard !channel.isDisposed else { throw MacError.badChannel } + guard channel.queue.count < ChannelState.queueCapacity else { throw MacError.queueFull } + channel.queue.append((command, prepared)) + } + } + + func status(of channel: ChannelState) -> ChannelStatus { + state.withLock { _ in + ChannelStatus( + isBusy: !channel.isDisposed && !channel.isIdle, + isPaused: channel.isQueuePaused || channel.voice?.isPaused == true, + queuedCommands: channel.queue.count) + } + } + + func dispose(_ channel: ChannelState, quietNow: Bool) { + state.withLock { state in + if quietNow || channel.isIdle { + state.remove(channel) + } else { + channel.retiresWhenIdle = true + } + } + } + + /// A sound command's sound decoded and checked, where it has one. + private static func prepare(_ command: SoundCommand) throws(MacError) -> PreparedSound? { + if case .buffer(let sound) = command { return try PreparedSound(sound) } + return nil + } +} + +// MARK: - Running channels + +/// The mixer's channels and what they share, used with its lock held. +struct MixerState { + + var channels: [ChannelState] = [] + + /// Channels at a sync, by its identifier. + var syncGroups: [Int32: [ChannelState]] = [:] + + /// Channels whose sync is complete, which go on at the start of the next + /// slice, all together. + var pendingReleases: [ChannelState] = [] + + var volume: (left: Double, right: Double) = (1, 1) + + var output: (any AudioOutput)? + + mutating func remove(_ channel: ChannelState) { + channel.isDisposed = true + channel.voice = nil + channel.queue.removeAll() + channel.waitRemaining = nil + channel.syncIdentifier = nil + channels.removeAll { $0 === channel } + for (identifier, group) in syncGroups { + let rest = group.filter { $0 !== channel } + syncGroups[identifier] = rest.isEmpty ? nil : rest + } + pendingReleases.removeAll { $0 === channel } + } + + mutating func removeRetiredChannels() { + for channel in channels where channel.retiresWhenIdle && channel.isIdle { remove(channel) } + } + + /// Runs one command on a channel: queued commands as they are reached, + /// immediate ones at once. + mutating func execute( + _ command: SoundCommand, prepared: PreparedSound?, completion: (@Sendable () -> Void)? = nil, + on channel: ChannelState, sampleRate: Int, events: inout [@Sendable () -> Void] + ) { + switch command { + case .null: + break + case .flush: + channel.queue.removeAll() + case .quiet: + channel.voice = nil + case .reInit(let bits): + channel.interpolates = !bits.contains(.noInterpolation) + case .wait(let halfMilliseconds): + let frames = Int(Double(max(0, halfMilliseconds)) * Double(sampleRate) / 2000) + channel.waitRemaining = frames > 0 ? frames : nil + case .pause: + channel.isQueuePaused = true + case .resume: + channel.isQueuePaused = false + case .callBack: + let callBack = channel.callBack + let handle = channel.handle + events.append { if let handle, let callBack { callBack(handle, command) } } + case .sync(let count, let identifier): + guard count > 1 else { break } + channel.syncIdentifier = identifier + var group = syncGroups[identifier, default: []] + group.append(channel) + if group.count >= Int(count) { + pendingReleases.append(contentsOf: group) + syncGroups[identifier] = nil + } else { + syncGroups[identifier] = group + } + case .buffer: + guard let prepared else { break } + if prepared.frames > 0 { + channel.voice = Voice(sound: prepared, completion: completion) + channel.loopOverride = nil + } else if let completion { + channel.voice = nil + events.append(completion) + } + case .amplitude(let value): + channel.gain = min(Double(max(value, 0)) / 256, ChannelState.maximumGain) + case .volume(let left, let right): + let sum = Int(left) + Int(right) + channel.pan = sum == 0 ? 0 : 2 * Double(right) / Double(sum) - 1 + channel.gain = min(Double(max(left, right)) / 256, ChannelState.maximumGain) + case .frequency(let note): + channel.playbackNote = note + case .rate(let value), .rateMultiplier(let value): + channel.pitchMultiplier = Double(value) / 65536 + case .loop(let on): + channel.loopOverride = on + case .pausePlayback: + channel.voice?.isPaused = true + case .resumePlayback: + channel.voice?.isPaused = false + } + } + + /// Runs a channel's queued commands until one holds it up. + private mutating func runQueue(_ channel: ChannelState, sampleRate: Int, events: inout [@Sendable () -> Void]) { + while !channel.isQueuePaused, channel.voice == nil, channel.waitRemaining == nil, channel.syncIdentifier == nil, + !channel.queue.isEmpty { + let next = channel.queue.removeFirst() + execute(next.command, prepared: next.prepared, on: channel, sampleRate: sampleRate, events: &events) + } + } + + /// Moves a channel `frames` frames on, mixing its sound into the buffer + /// from `offset` and running its commands as they come up. + mutating func advance( + _ channel: ChannelState, frames: Int, into buffer: UnsafeMutableBufferPointer, at offset: Int, + sampleRate: Int, events: inout [@Sendable () -> Void] + ) { + var remaining = frames + var position = offset + var turns = 0 + while remaining > 0, turns < 10_000 { + turns += 1 + runQueue(channel, sampleRate: sampleRate, events: &events) + var span = remaining + if let wait = channel.waitRemaining { span = min(span, wait) } + var advanced = span + if var voice = channel.voice, !voice.isPaused { + let pitch = channel.pitchMultiplier * MIDINote.frequency(of: channel.playbackNote) + / MIDINote.frequency(of: voice.sound.baseNote) + let step = max(0.001, voice.sound.sampleRate / Double(sampleRate) * pitch) + let left = Float(channel.gain * (channel.pan <= 0 ? 1 : 1 - channel.pan)) + let right = Float(channel.gain * (channel.pan >= 0 ? 1 : 1 + channel.pan)) + // A channel on its way out plays a loop once: nothing is left to stop it. + let looping = !channel.retiresWhenIdle && (channel.loopOverride ?? (voice.sound.loop != nil)) + let result = Self.mix(&voice, frames: span, step: step, left: left, right: right, + interpolates: channel.interpolates, looping: looping, into: buffer, at: position) + if result.ended { + channel.voice = nil + if let completion = voice.completion { events.append(completion) } + advanced = result.produced + } else { + channel.voice = voice + } + } + if let wait = channel.waitRemaining { + channel.waitRemaining = wait > advanced ? wait - advanced : nil + } + if advanced == 0 && channel.voice == nil && channel.queue.isEmpty { break } + // A channel with nothing to run goes quiet for the rest of the slice. + if channel.voice == nil && channel.waitRemaining == nil && (channel.queue.isEmpty || channel.isQueuePaused || channel.syncIdentifier != nil) { + break + } + position += advanced + remaining -= advanced + } + } + + /// Adds up to `frames` frames of a voice to the buffer, resampled at a + /// step of source frames a frame, panned by the gains. Returns the frames + /// it added, and whether the sound ended. + private static func mix( + _ voice: inout Voice, frames: Int, step: Double, left: Float, right: Float, interpolates: Bool, looping: Bool, + into buffer: UnsafeMutableBufferPointer, at offset: Int + ) -> (produced: Int, ended: Bool) { + let sound = voice.sound + let count = sound.frames + let region = sound.loop ?? 0 ..< count + let regionStart = Double(region.lowerBound), regionEnd = Double(region.upperBound) + var position = voice.position + var produced = 0 + var ended = false + let scale: Float = 1 / 32768 + sound.samples.withUnsafeBufferPointer { samples in + while produced < frames { + if looping { + if position >= regionEnd { + position = regionStart + (position - regionStart).truncatingRemainder(dividingBy: Double(region.count)) + } + } else if position >= Double(count) { + ended = true + break + } + let index = Int(position) + let base = index * sound.channels + var l = Float(samples[base]) + var r = sound.channels > 1 ? Float(samples[base + 1]) : l + let fraction = Float(position - Double(index)) + if interpolates, fraction > 0 { + var next = index + 1 + if looping { + if next >= region.upperBound { next = region.lowerBound } + } else if next >= count { + next = index + } + let nextBase = next * sound.channels + let l2 = Float(samples[nextBase]) + let r2 = sound.channels > 1 ? Float(samples[nextBase + 1]) : l2 + l += (l2 - l) * fraction + r += (r2 - r) * fraction + } + buffer[(offset + produced) * 2] += l * scale * left + buffer[(offset + produced) * 2 + 1] += r * scale * right + position += step + produced += 1 + } + } + if !looping && position >= Double(count) { ended = true } + voice.position = position + return (produced, ended) + } +} From 08eafe89bc30644ec1c963c5c633bbcb34b1a497 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 06/11] Added sound channels --- Sources/GraphiteSound/SoundChannel.swift | 76 ++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Sources/GraphiteSound/SoundChannel.swift diff --git a/Sources/GraphiteSound/SoundChannel.swift b/Sources/GraphiteSound/SoundChannel.swift new file mode 100644 index 0000000..ddc6be5 --- /dev/null +++ b/Sources/GraphiteSound/SoundChannel.swift @@ -0,0 +1,76 @@ +// A sound channel: what a program makes with SndNewChannel to play sounds +// through, and sends commands to. + +import GraphiteBase + +/// SndChannelStatus. +public struct ChannelStatus: Hashable, Sendable { + + /// scChannelBusy: a sound is playing, or commands are waiting or running. + public var isBusy: Bool + + /// scChannelPaused: the queue was paused with pauseCmd, or the sound that is + /// playing is held. + public var isPaused: Bool + + /// The commands in the queue that haven't run. + public var queuedCommands: Int + + public init(isBusy: Bool, isPaused: Bool, queuedCommands: Int) { + self.isBusy = isBusy + self.isPaused = isPaused + self.queuedCommands = queuedCommands + } +} + +/// A channel the program lets go of is disposed with `quietNow` false: it +/// plays what it was given, and runs what it had queued, and is then gone. +/// A sound that loops plays through once then, since nothing is left to stop it. +public final class SoundChannel: @unchecked Sendable { + + let mixer: SoundMixer + let state: ChannelState + + init(mixer: SoundMixer, state: ChannelState) { + self.mixer = mixer + self.state = state + } + + deinit { + mixer.dispose(state, quietNow: false) + } + + /// SndChannelStatus. + public var status: ChannelStatus { + mixer.status(of: state) + } + + /// SndDoImmediate: a command run at once, whatever the channel is doing. + /// `badFormat` or another error of a sound that can't be played; + /// `badChannel` for a channel that has been disposed. + public func doImmediate(_ command: SoundCommand) throws(MacError) { + try mixer.run(command, on: state) + } + + /// SndDoCommand: a command put at the end of the queue, to run when the + /// ones before it have. It doesn't wait for room: `queueFull` for a queue + /// of 128, and the sound of a command that can't be played is refused here, + /// not when it is reached. + public func doCommand(_ command: SoundCommand) throws(MacError) { + try mixer.enqueue(command, on: state) + } + + /// Plays a sound at once, in place of the one playing, and calls + /// `completion` when it plays to its end, not if it is stopped first. + /// SndStartFilePlay and SndPlay do this. + public func play(_ sound: SampledSound, completion: (@Sendable () -> Void)? = nil) throws(MacError) { + try mixer.run(.buffer(sound), completion: completion, on: state) + } + + /// SndDisposeChannel: the channel is gone. With `quietNow` false it first + /// plays what it is playing and runs what it has queued; a sound that + /// loops plays through once. + public func dispose(quietNow: Bool = true) { + mixer.dispose(state, quietNow: quietNow) + } +} From e2c1ac6d07cb3bef2abea1368536feb64b2f4a3d Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 07/11] Tested mixing, resampling, volume, loops and completion --- Tests/GraphiteSoundTests/MixerTests.swift | 290 ++++++++++++++++++++++ 1 file changed, 290 insertions(+) create mode 100644 Tests/GraphiteSoundTests/MixerTests.swift diff --git a/Tests/GraphiteSoundTests/MixerTests.swift b/Tests/GraphiteSoundTests/MixerTests.swift new file mode 100644 index 0000000..fedc921 --- /dev/null +++ b/Tests/GraphiteSoundTests/MixerTests.swift @@ -0,0 +1,290 @@ +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct MixerTests { + + let mixer = SoundMixer(sampleRate: 8000) + + /// 16-bit mono (or interleaved) samples as a sound. + private func sound(_ samples: [Int16], rate: Double = 8000, channels: Int = 1, baseNote: Int = 60, loop: Range? = nil) -> SampledSound { + var bytes: [UInt8] = [] + for sample in samples { + bytes.append(UInt8(truncatingIfNeeded: sample >> 8)) + bytes.append(UInt8(truncatingIfNeeded: sample)) + } + return SampledSound(encoding: .signedBigEndian, sampleRate: rate, channels: channels, bitsPerSample: 16, + count: samples.count / channels, data: bytes, baseNote: baseNote, loop: loop) + } + + /// The left and right of rendered frames, as the 16-bit values they came from. + private func render(_ frames: Int, _ mixer: SoundMixer? = nil) -> (left: [Float], right: [Float]) { + let out = (mixer ?? self.mixer).render(frames: frames) + return (stride(from: 0, to: out.count, by: 2).map { out[$0] * 32768 }, stride(from: 1, to: out.count, by: 2).map { out[$0] * 32768 }) + } + + private func floats(_ values: [Int]) -> [Float] { values.map(Float.init) } + + // MARK: Playing + + @Test func aMonoSoundPlaysToBothSides() throws { + let channel = try mixer.newChannel() + try channel.play(sound([100, -200, 300, 400])) + let out = render(6) + #expect(out.left == floats([100, -200, 300, 400, 0, 0])) + #expect(out.right == out.left) + } + + @Test func aStereoSoundKeepsItsSides() throws { + let channel = try mixer.newChannel() + try channel.play(sound([1, -1, 2, -2, 3, -3], channels: 2)) + let out = render(4) + #expect(out.left == floats([1, 2, 3, 0])) + #expect(out.right == floats([-1, -2, -3, 0])) + } + + @Test func silenceWithNothingPlaying() { + #expect(render(100).left == [Float](repeating: 0, count: 100)) + #expect(mixer.render(frames: 0).isEmpty) + #expect(mixer.render(frames: -5).isEmpty) + } + + @Test func rendersContinueWhereTheLastLeftOff() throws { + let samples = (0 ..< 300).map { Int16($0 * 10) } + try mixer.newChannel().play(sound(samples)) + var all: [Float] = [] + for count in [1, 63, 64, 65, 200, 7] { all += render(count).left } + #expect(all.count == 400) + #expect(Array(all.prefix(300)) == floats(samples.map(Int.init))) + #expect(all.suffix(100).allSatisfy { $0 == 0 }) + } + + @Test func channelsAreAddedAndClipped() throws { + let a = try mixer.newChannel(), b = try mixer.newChannel() + try a.play(sound([100, 20000])) + try b.play(sound([200, 20000])) + let out = render(3) + #expect(out.left == [300, 32768, 0]) + } + + @Test func anotherSoundTakesTheChannelOver() throws { + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3, 4, 5, 6])) + _ = render(2) + try channel.doImmediate(.buffer(sound([9, 8]))) + #expect(render(3).left == floats([9, 8, 0])) + } + + // MARK: Resampling + + @Test func aSlowerSoundIsInterpolated() throws { + try mixer.newChannel().play(sound([0, 1000], rate: 4000)) + #expect(render(5).left == floats([0, 500, 1000, 1000, 0])) + } + + @Test func withoutInterpolationSamplesRepeat() throws { + try mixer.newChannel(initBits: .noInterpolation).play(sound([0, 1000], rate: 4000)) + #expect(render(5).left == floats([0, 0, 1000, 1000, 0])) + } + + @Test func reInitChangesInterpolation() throws { + let channel = try mixer.newChannel() + try channel.doImmediate(.reInit(.noInterpolation)) + try channel.play(sound([0, 1000], rate: 4000)) + #expect(render(4).left == floats([0, 0, 1000, 1000])) + } + + @Test func aFasterSoundSkipsSamples() throws { + try mixer.newChannel().play(sound([10, 20, 30, 40, 50, 60], rate: 16000)) + #expect(render(4).left == floats([10, 30, 50, 0])) + } + + @Test func aNoteAnOctaveUpPlaysTwiceAsFast() throws { + let channel = try mixer.newChannel() + try channel.play(sound([10, 20, 30, 40, 50, 60])) + try channel.doImmediate(.frequency(note: 72)) + let out = render(4).left + for (got, wanted) in zip(out, floats([10, 30, 50, 0])) { #expect(abs(got - wanted) < 0.01) } + } + + @Test func theBaseNoteIsTheNoteItPlaysAsRecorded() throws { + let channel = try mixer.newChannel() + try channel.play(sound([10, 20, 30, 40], baseNote: 72)) + try channel.doImmediate(.frequency(note: 72)) + #expect(render(5).left == floats([10, 20, 30, 40, 0])) + } + + @Test func rateMultipliesThePitch() throws { + for command in [SoundCommand.rate(0x2_0000), .rateMultiplier(0x2_0000)] { + let mixer = SoundMixer(sampleRate: 8000) + let channel = try mixer.newChannel() + try channel.play(sound([10, 20, 30, 40, 50, 60])) + try channel.doImmediate(command) + #expect(render(4, mixer).left == floats([10, 30, 50, 0])) + } + } + + // MARK: Volume and pan + + @Test func panAndVolume() throws { + func play(_ command: SoundCommand) throws -> (left: [Float], right: [Float]) { + let mixer = SoundMixer(sampleRate: 8000) + let channel = try mixer.newChannel() + try channel.play(sound([1000, 1000])) + try channel.doImmediate(command) + return render(2, mixer) + } + let left = try play(.volume(left: 256, right: 0)) + #expect(left.left == floats([1000, 1000]) && left.right == floats([0, 0])) + let right = try play(.volume(left: 0, right: 256)) + #expect(right.left == floats([0, 0]) && right.right == floats([1000, 1000])) + let half = try play(.volume(left: 128, right: 128)) + #expect(half.left == floats([500, 500]) && half.right == half.left) + // The louder side sets the amplitude and the pan moves toward it. + let mostlyLeft = try play(.volume(left: 256, right: 64)) + #expect(mostlyLeft.left == floats([1000, 1000])) + #expect(mostlyLeft.right == floats([400, 400])) + let silent = try play(.volume(left: 0, right: 0)) + #expect(silent.left == floats([0, 0]) && silent.right == silent.left) + } + + @Test func amplitude() throws { + func play(_ amplitude: Int) throws -> [Float] { + let mixer = SoundMixer(sampleRate: 8000) + let channel = try mixer.newChannel() + try channel.play(sound([1000])) + try channel.doImmediate(.amplitude(amplitude)) + return render(1, mixer).left + } + #expect(try play(256) == [1000]) + #expect(try play(128) == [500]) + #expect(try play(0) == [0]) + #expect(try play(-5) == [0]) + // Capped at 2.5 times as recorded. + #expect(try play(100_000) == [2500]) + } + + @Test func theOutputVolume() throws { + try mixer.newChannel().play(sound([1000, 1000])) + mixer.outputVolume = (0.5, 0) + let out = render(2) + #expect(out.left == floats([500, 500]) && out.right == floats([0, 0])) + mixer.outputVolume = (-1, -1) + #expect(mixer.outputVolume.left == 0 && mixer.outputVolume.right == 0) + } + + @Test func theDefaultOutputVolumeIsAWordASide() { + #expect(mixer.defaultOutputVolume == 0x0100_0100) + mixer.defaultOutputVolume = 0x0100_0080 + #expect(mixer.outputVolume.left == 0.5 && mixer.outputVolume.right == 1) + #expect(mixer.defaultOutputVolume == 0x0100_0080) + mixer.defaultOutputVolume = 0xFFFF_FFFF + #expect(mixer.defaultOutputVolume == 0xFFFF_FFFF) + } + + // MARK: Loops and the end + + @Test func aHeaderLoopRepeats() throws { + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3, 4, 5, 6].map { $0 * 1000 }, loop: 2 ..< 5)) + #expect(withExtendedLifetime(channel) { render(10).left } == floats([1, 2, 3, 4, 5, 3, 4, 5, 3, 4].map { $0 * 1000 })) + } + + @Test func loopCanBeStoppedAndForced() throws { + let samples = [1, 2, 3, 4, 5, 6].map { Int16($0 * 1000) } + let stopped = SoundMixer(sampleRate: 8000) + let channel = try stopped.newChannel() + try channel.play(sound(samples, loop: 2 ..< 5)) + try channel.doImmediate(.loop(false)) + #expect(render(8, stopped).left == floats([1, 2, 3, 4, 5, 6, 0, 0].map { $0 * 1000 })) + + let forced = SoundMixer(sampleRate: 8000) + let other = try forced.newChannel() + try other.play(sound(samples)) + try other.doImmediate(.loop(true)) + #expect(render(8, forced).left == floats([1, 2, 3, 4, 5, 6, 1, 2].map { $0 * 1000 })) + } + + @Test func aLoopTooShortOrPastTheEndIsNoLoop() throws { + let samples = [1, 2, 3, 4].map { Int16($0 * 1000) } + let one = SoundMixer(sampleRate: 8000) + let first = try one.newChannel() + try first.play(sound(samples, loop: 1 ..< 2)) + #expect(withExtendedLifetime(first) { render(6, one).left } == floats([1, 2, 3, 4, 0, 0].map { $0 * 1000 })) + // One past the end stops at the end. + let past = SoundMixer(sampleRate: 8000) + let second = try past.newChannel() + try second.play(sound(samples, loop: 2 ..< 40)) + #expect(withExtendedLifetime(second) { render(8, past).left } == floats([1, 2, 3, 4, 3, 4, 3, 4].map { $0 * 1000 })) + } + + @Test func aLoopWorksAtOtherRates() throws { + let mixer = SoundMixer(sampleRate: 8000) + let channel = try mixer.newChannel(initBits: .noInterpolation) + try channel.play(sound([10, 20, 30, 40], rate: 4000, loop: 2 ..< 4)) + // Each frame twice, then the loop's two frames, twice each. + #expect(withExtendedLifetime(channel) { render(12, mixer).left } == floats([10, 10, 20, 20, 30, 30, 40, 40, 30, 30, 40, 40])) + } + + @Test func aChannelLetGoOfPlaysItsSoundOutAndGoes() throws { + // Nothing holds the channel, which is no reason to cut the sound off. + try mixer.newChannel().play(sound([1, 2, 3, 4])) + #expect(mixer.channelCount == 1) + #expect(render(6).left == floats([1, 2, 3, 4, 0, 0])) + #expect(mixer.channelCount == 0) + } + + @Test func aChannelLetGoOfPlaysALoopOnce() throws { + try mixer.newChannel().play(sound([1, 2, 3, 4, 5, 6].map { $0 * 1000 }, loop: 2 ..< 5)) + #expect(render(8).left == floats([1, 2, 3, 4, 5, 6, 0, 0].map { $0 * 1000 })) + #expect(mixer.channelCount == 0) + } + + @Test func aChannelLetGoOfRunsItsQueueToo() throws { + do { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2]))) + try channel.doCommand(.buffer(sound([3, 4]))) + } + #expect(render(6).left == floats([1, 2, 3, 4, 0, 0])) + #expect(mixer.channelCount == 0) + } + + @Test func completionIsCalledOnceAtTheEnd() throws { + let calls = Counter() + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3])) { calls.increment() } + #expect(calls.value == 0) + _ = render(2) + #expect(calls.value == 0) + _ = render(2) + #expect(calls.value == 1) + _ = render(100) + #expect(calls.value == 1) + } + + @Test func completionIsNotCalledWhenStopped() throws { + let calls = Counter() + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3, 4, 5, 6])) { calls.increment() } + _ = render(2) + try channel.doImmediate(.quiet) + _ = render(20) + #expect(calls.value == 0) + #expect(!channel.status.isBusy) + } + + @Test func aSoundWithNoFramesCompletesAtOnce() throws { + let calls = Counter() + let empty = SampledSound(encoding: .signedBigEndian, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 0, data: [UInt8]()) + try mixer.newChannel().play(empty) { calls.increment() } + #expect(calls.value == 1) + #expect(render(2).left == floats([0, 0])) + } +} + +/// A count a callback can add to. +final class Counter: @unchecked Sendable { + private(set) var value = 0 + func increment() { value += 1 } +} From 602e4f478cd1759585ffac72cf6497b7342c9322 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 08/11] Tested channels' queues, waits, syncs and errors --- Tests/GraphiteSoundTests/ChannelTests.swift | 328 ++++++++++++++++++++ 1 file changed, 328 insertions(+) create mode 100644 Tests/GraphiteSoundTests/ChannelTests.swift diff --git a/Tests/GraphiteSoundTests/ChannelTests.swift b/Tests/GraphiteSoundTests/ChannelTests.swift new file mode 100644 index 0000000..8a842e6 --- /dev/null +++ b/Tests/GraphiteSoundTests/ChannelTests.swift @@ -0,0 +1,328 @@ +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct ChannelTests { + + let mixer = SoundMixer(sampleRate: 8000) + + private func sound(_ samples: [Int16], rate: Double = 8000) -> SampledSound { + var bytes: [UInt8] = [] + for sample in samples { + bytes.append(UInt8(truncatingIfNeeded: sample >> 8)) + bytes.append(UInt8(truncatingIfNeeded: sample)) + } + return SampledSound(encoding: .signedBigEndian, sampleRate: rate, channels: 1, bitsPerSample: 16, count: samples.count, data: bytes) + } + + private func render(_ frames: Int, _ mixer: SoundMixer? = nil) -> (left: [Float], right: [Float]) { + let out = (mixer ?? self.mixer).render(frames: frames) + return (stride(from: 0, to: out.count, by: 2).map { out[$0] * 32768 }, stride(from: 1, to: out.count, by: 2).map { out[$0] * 32768 }) + } + + private func floats(_ values: [Int]) -> [Float] { values.map(Float.init) } + + // MARK: The queue + + @Test func commandsRunInOrderAndASoundHoldsTheQueue() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2, 3]))) + try channel.doCommand(.buffer(sound([4, 5]))) + try channel.doCommand(.buffer(sound([6]))) + #expect(channel.status.queuedCommands == 3) + #expect(render(8).left == floats([1, 2, 3, 4, 5, 6, 0, 0])) + #expect(channel.status.queuedCommands == 0) + } + + @Test func settingsRunWhenTheyAreReached() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1000, 1000]))) + try channel.doCommand(.amplitude(128)) + try channel.doCommand(.buffer(sound([1000, 1000]))) + // The amplitude is for the second sound, not the first. + #expect(render(4).left == floats([1000, 1000, 500, 500])) + } + + @Test func aWaitIsSilenceOfItsTime() throws { + let channel = try mixer.newChannel() + // Two half-milliseconds is a millisecond: 8 frames at 8000. + try channel.doCommand(.wait(halfMilliseconds: 2)) + try channel.doCommand(.buffer(sound([7, 8, 9]))) + let out = render(14).left + #expect(out == floats([0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0])) + } + + @Test func waitsAreExactAcrossRenders() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.wait(halfMilliseconds: 40)) // 160 frames + try channel.doCommand(.buffer(sound([5]))) + var all: [Float] = [] + for _ in 0 ..< 8 { all += render(25).left } + #expect(all.firstIndex { $0 != 0 } == 160) + } + + @Test func aWaitOfNothingIsNothing() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.wait(halfMilliseconds: 0)) + try channel.doCommand(.wait(halfMilliseconds: -4)) + try channel.doCommand(.buffer(sound([3]))) + #expect(render(2).left == floats([3, 0])) + } + + @Test func callBacksComeWhenReachedWithTheChannelAndCommand() throws { + let log = Log() + let channel = try mixer.newChannel { channel, command in log.record(channel, command) } + try channel.doCommand(.buffer(sound([1, 2, 3]))) + try channel.doCommand(.callBack(param1: 7, param2: 99)) + try channel.doCommand(.buffer(sound([4]))) + _ = render(2) + #expect(log.commands.isEmpty) + #expect(render(3).left == floats([3, 4, 0])) + #expect(log.commands == [.callBack(param1: 7, param2: 99)]) + #expect(log.channels.first === channel) + _ = render(10) + #expect(log.commands.count == 1) + } + + @Test func anImmediateCallBackIsCalledAtOnce() throws { + let log = Log() + let channel = try mixer.newChannel { channel, command in log.record(channel, command) } + try channel.doImmediate(.callBack(param1: 1, param2: 2)) + #expect(log.commands == [.callBack(param1: 1, param2: 2)]) + } + + @Test func aCallBackCanUseTheChannel() throws { + // It's called after the mixer is let go, so it can send commands. + let next = sound([9, 9]) + let channel = try mixer.newChannel { channel, _ in try? channel.doCommand(.buffer(next)) } + try channel.doCommand(.buffer(sound([1]))) + try channel.doCommand(.callBack(param1: 0, param2: 0)) + #expect(render(2).left == floats([1, 0])) + #expect(render(3).left == floats([9, 9, 0])) + } + + // MARK: Flush, quiet and the two pauses + + @Test func flushEmptiesTheQueue() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2]))) + try channel.doCommand(.buffer(sound([3, 4]))) + try channel.doImmediate(.flush) + #expect(channel.status.queuedCommands == 0) + #expect(render(4).left == floats([0, 0, 0, 0])) + try channel.doCommand(.buffer(sound([5]))) + try channel.doCommand(.flush) + #expect(render(2).left == floats([5, 0])) + } + + @Test func quietStopsTheSoundAndTheQueueGoesOn() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2, 3, 4, 5, 6]))) + try channel.doCommand(.buffer(sound([7, 8]))) + #expect(render(2).left == floats([1, 2])) + try channel.doImmediate(.quiet) + #expect(render(3).left == floats([7, 8, 0])) + } + + @Test func pauseHoldsTheQueueNotTheSound() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2, 3]))) + try channel.doCommand(.pause) + try channel.doCommand(.buffer(sound([4, 5]))) + #expect(render(6).left == floats([1, 2, 3, 0, 0, 0])) + #expect(channel.status.isPaused) + #expect(channel.status.queuedCommands == 1) + try channel.doImmediate(.resume) + #expect(!channel.status.isPaused) + #expect(render(3).left == floats([4, 5, 0])) + } + + @Test func aQueuedResumeCantRunWhilePaused() throws { + let channel = try mixer.newChannel() + try channel.doImmediate(.pause) + try channel.doCommand(.resume) + try channel.doCommand(.buffer(sound([1]))) + #expect(render(2).left == floats([0, 0])) + try channel.doImmediate(.resume) + #expect(render(2).left == floats([1, 0])) + } + + @Test func pausingPlaybackHoldsTheSoundWhereItIs() throws { + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3, 4, 5])) + #expect(render(2).left == floats([1, 2])) + try channel.doImmediate(.pausePlayback) + #expect(channel.status.isPaused && channel.status.isBusy) + #expect(render(100).left == [Float](repeating: 0, count: 100)) + try channel.doImmediate(.resumePlayback) + #expect(!channel.status.isPaused) + #expect(render(4).left == floats([3, 4, 5, 0])) + } + + // MARK: Sync + + @Test func channelsAtASyncGoOnTogether() throws { + let one = try mixer.newChannel(), two = try mixer.newChannel() + try one.doImmediate(.volume(left: 256, right: 0)) + try two.doImmediate(.volume(left: 0, right: 256)) + try one.doCommand(.wait(halfMilliseconds: 40)) // 160 frames + try one.doCommand(.sync(count: 2, identifier: 7)) + try one.doCommand(.buffer(sound([1000, 1000, 1000, 1000]))) + try two.doCommand(.sync(count: 2, identifier: 7)) + try two.doCommand(.buffer(sound([2000, 2000, 2000, 2000]))) + let out = render(400) + // The first reaches the sync in the slice of frames 128 to 191, so both + // go on at 192, the start of the next. + #expect(out.left.firstIndex { $0 != 0 } == 192) + #expect(out.right.firstIndex { $0 != 0 } == 192) + #expect(Array(out.left[192 ..< 197]) == floats([1000, 1000, 1000, 1000, 0])) + #expect(Array(out.right[192 ..< 197]) == floats([2000, 2000, 2000, 2000, 0])) + #expect(out.left.filter { $0 != 0 }.count == 4 && out.right.filter { $0 != 0 }.count == 4) + } + + @Test func aSyncWaitsForEveryChannelItNames() throws { + let one = try mixer.newChannel(), two = try mixer.newChannel() + for channel in [one, two] { + try channel.doCommand(.sync(count: 3, identifier: 1)) + try channel.doCommand(.buffer(sound([5]))) + } + #expect(render(300).left == [Float](repeating: 0, count: 300)) + #expect(one.status.isBusy && two.status.isBusy) + // A third channel completes it, and all three go on. + let three = try mixer.newChannel() + try three.doCommand(.sync(count: 3, identifier: 1)) + try three.doCommand(.buffer(sound([5]))) + let out = render(128).left + #expect(out.firstIndex { $0 != 0 } == 64) + #expect(out[64] == 15) + } + + @Test func syncsOfOtherIdentifiersAreSeparate() throws { + let one = try mixer.newChannel(), two = try mixer.newChannel() + try one.doCommand(.sync(count: 2, identifier: 1)) + try one.doCommand(.buffer(sound([5]))) + try two.doCommand(.sync(count: 2, identifier: 2)) + try two.doCommand(.buffer(sound([5]))) + #expect(render(200).left == [Float](repeating: 0, count: 200)) + } + + @Test func aSyncOfOneIsNothing() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.sync(count: 1, identifier: 3)) + try channel.doCommand(.sync(count: 0, identifier: 3)) + try channel.doCommand(.buffer(sound([4]))) + #expect(render(2).left == floats([4, 0])) + } + + @Test func aDisposedChannelLeavesItsSync() throws { + let one = try mixer.newChannel(), two = try mixer.newChannel() + try one.doCommand(.sync(count: 2, identifier: 1)) + _ = render(10) + one.dispose() + try two.doCommand(.sync(count: 2, identifier: 1)) + try two.doCommand(.buffer(sound([5]))) + // The one that left doesn't count. + #expect(render(200).left == [Float](repeating: 0, count: 200)) + } + + // MARK: Status and disposal + + @Test func statusFollowsTheChannel() throws { + let channel = try mixer.newChannel() + #expect(channel.status == ChannelStatus(isBusy: false, isPaused: false, queuedCommands: 0)) + try channel.play(sound([1, 2, 3])) + #expect(channel.status.isBusy) + _ = render(2) + #expect(channel.status.isBusy) + _ = render(2) + #expect(!channel.status.isBusy) + try channel.doCommand(.wait(halfMilliseconds: 2000)) + #expect(channel.status.isBusy) + } + + @Test func disposingStopsItAtOnce() throws { + let channel = try mixer.newChannel() + try channel.play(sound([1, 2, 3, 4])) + try channel.doCommand(.buffer(sound([5]))) + channel.dispose() + #expect(mixer.channelCount == 0) + #expect(render(6).left == [Float](repeating: 0, count: 6)) + #expect(throws: MacError.badChannel) { try channel.doImmediate(.quiet) } + #expect(throws: MacError.badChannel) { try channel.doCommand(.null) } + #expect(throws: MacError.badChannel) { try channel.play(sound([1])) } + #expect(!channel.status.isBusy) + channel.dispose() + } + + @Test func disposingNotQuietPlaysWhatIsThere() throws { + let channel = try mixer.newChannel() + try channel.doCommand(.buffer(sound([1, 2, 3]))) + try channel.doCommand(.buffer(sound([4]))) + channel.dispose(quietNow: false) + #expect(mixer.channelCount == 1) + #expect(render(6).left == floats([1, 2, 3, 4, 0, 0])) + #expect(mixer.channelCount == 0) + #expect(throws: MacError.badChannel) { try channel.doCommand(.null) } + } + + @Test func disposingAnIdleChannelIsAtOnce() throws { + let channel = try mixer.newChannel() + channel.dispose(quietNow: false) + #expect(mixer.channelCount == 0) + } + + // MARK: Errors + + @Test func theQueueHoldsAHundredAndTwentyEight() throws { + let channel = try mixer.newChannel() + try channel.doImmediate(.pause) + for _ in 0 ..< 128 { try channel.doCommand(.null) } + #expect(throws: MacError.queueFull) { try channel.doCommand(.null) } + #expect(channel.status.queuedCommands == 128) + try channel.doImmediate(.flush) + try channel.doCommand(.null) + } + + @Test func soundsThatCantBePlayedAreRefused() throws { + let channel = try mixer.newChannel() + let mace = SampledSound(encoding: .mace3, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 1, data: [1, 2]) + let noChannels = SampledSound(encoding: .signedBigEndian, sampleRate: 8000, channels: 0, bitsPerSample: 16, count: 1, data: [1, 2]) + #expect(throws: MacError.unimplemented) { try channel.doCommand(.buffer(mace)) } + #expect(throws: MacError.unimplemented) { try channel.doImmediate(.buffer(mace)) } + #expect(throws: MacError.unimplemented) { try channel.play(mace) } + #expect(throws: MacError.badFormat) { try channel.doCommand(.buffer(noChannels)) } + #expect(channel.status.queuedCommands == 0) + } + + @Test func onlySampledSynthsAreChannels() { + #expect(throws: MacError.unimplemented) { try mixer.newChannel(synth: .squareWave) } + #expect(throws: MacError.unimplemented) { try mixer.newChannel(synth: .waveTable) } + #expect(mixer.channelCount == 0) + } + + @Test func channelsAreCounted() throws { + let a = try mixer.newChannel(), b = try mixer.newChannel() + #expect(mixer.channelCount == 2) + a.dispose() + #expect(mixer.channelCount == 1) + withExtendedLifetime(b) {} + } + + @Test func aSoundWithADecodedFormatPlays() throws { + // µ-law bytes, decoded when the command is given. + let ulaw = SampledSound(encoding: .ulaw, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 2, data: [0x80, 0x00]) + let channel = try mixer.newChannel() + try channel.play(ulaw) + #expect(render(3).left == floats([32124, -32124, 0])) + } +} + +/// What a callback was given. +final class Log: @unchecked Sendable { + private(set) var commands: [SoundCommand] = [] + private(set) var channels: [SoundChannel] = [] + func record(_ channel: SoundChannel, _ command: SoundCommand) { + channels.append(channel) + commands.append(command) + } +} From 47d8b7bea6d9c32c64d351bc2dbca393c781a7ea Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 09/11] Tested command words, devices and threads --- .../SoundCommandTests.swift | 135 ++++++++++++++++++ 1 file changed, 135 insertions(+) create mode 100644 Tests/GraphiteSoundTests/SoundCommandTests.swift diff --git a/Tests/GraphiteSoundTests/SoundCommandTests.swift b/Tests/GraphiteSoundTests/SoundCommandTests.swift new file mode 100644 index 0000000..a571525 --- /dev/null +++ b/Tests/GraphiteSoundTests/SoundCommandTests.swift @@ -0,0 +1,135 @@ +import Foundation +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct SoundCommandTests { + + // MARK: Command words + + @Test func commandsThatCarryNoSound() { + #expect(SoundCommand(code: 0, param1: 0, param2: 0) == .null) + #expect(SoundCommand(code: 3, param1: 0, param2: 0) == .quiet) + #expect(SoundCommand(code: 4, param1: 0, param2: 0) == .flush) + #expect(SoundCommand(code: 5, param1: 0, param2: 0x0004) == .reInit(.noInterpolation)) + #expect(SoundCommand(code: 10, param1: 40, param2: 0) == .wait(halfMilliseconds: 40)) + #expect(SoundCommand(code: 11, param1: 0, param2: 0) == .pause) + #expect(SoundCommand(code: 12, param1: 0, param2: 0) == .resume) + #expect(SoundCommand(code: 13, param1: 5, param2: 6) == .callBack(param1: 5, param2: 6)) + #expect(SoundCommand(code: 14, param1: 2, param2: 77) == .sync(count: 2, identifier: 77)) + #expect(SoundCommand(code: 42, param1: 0, param2: 67) == .frequency(note: 67)) + #expect(SoundCommand(code: 43, param1: 128, param2: 0) == .amplitude(128)) + #expect(SoundCommand(code: 82, param1: 0, param2: 0x1_0000) == .rate(0x1_0000)) + #expect(SoundCommand(code: 86, param1: 0, param2: 0x2_0000) == .rateMultiplier(0x2_0000)) + } + + @Test func theVolumeCommandsWordsAreLeftThenRight() { + // The low word is the left volume, the high word the right. + #expect(SoundCommand(code: 46, param1: 0, param2: Int32(bitPattern: 0x0040_0100)) == .volume(left: 0x0100, right: 0x0040)) + #expect(SoundCommand(code: 46, param1: 0, param2: Int32(bitPattern: 0xFFFF_0000)) == .volume(left: 0, right: 0xFFFF)) + } + + @Test func theHighBitOnlySaysThereIsSoundData() { + #expect(SoundCommand(code: 0x8003, param1: 0, param2: 0) == .quiet) + #expect(SoundCommand(code: 0x800D, param1: 1, param2: 2) == .callBack(param1: 1, param2: 2)) + } + + @Test func commandsThatAreSoundsOrUnknownAreNil() { + // soundCmd and bufferCmd point at a sound, with or without the high bit. + for code: UInt16 in [80, 81, 0x8050, 0x8051] { #expect(SoundCommand(code: code, param1: 0, param2: 20) == nil, "\(code)") } + // Synthesizer commands, and numbers that are no command. + for code: UInt16 in [1, 2, 24, 25, 40, 41, 44, 45, 47, 60, 61, 83, 84, 85, 87, 90, 91, 200, 0x7001] { + #expect(SoundCommand(code: code, param1: 0, param2: 0) == nil, "\(code)") + } + } + + @Test func initBits() { + #expect(SoundInit.noInterpolation.rawValue == 0x0004) + #expect(SoundInit.noDrop.rawValue == 0x0008) + #expect(SoundInit.mono.rawValue == 0x0080) + #expect(SoundInit.stereo.rawValue == 0x00C0) + #expect(SoundInit.mace3.rawValue == 0x0300) + #expect(SoundInit.mace6.rawValue == 0x0400) + #expect(SoundInit([.stereo, .noInterpolation]).contains(.noInterpolation)) + #expect(SoundSynth.sampled.rawValue == 5 && SoundSynth.squareWave.rawValue == 1 && SoundSynth.waveTable.rawValue == 3) + } + + @Test func versionIsThreePointNine() { + let version = SoundMixer.version + #expect(version.major == 3 && version.minorAndBugFix == 0x09 && version.stage == 0x80 && version.nonRelease == 0) + } + + // MARK: A device + + final class Device: AudioOutput, @unchecked Sendable { + let sampleRate: Int + private(set) var render: (@Sendable (UnsafeMutableBufferPointer) -> Void)? + private(set) var starts = 0 + private(set) var stops = 0 + init(sampleRate: Int) { self.sampleRate = sampleRate } + func start(render: @escaping @Sendable (UnsafeMutableBufferPointer) -> Void) { + starts += 1 + self.render = render + } + func stop() { + stops += 1 + render = nil + } + } + + @Test func aMixerPlaysThroughADevice() throws { + let device = Device(sampleRate: 22050) + let mixer = SoundMixer(output: device) + #expect(mixer.sampleRate == 22050) + #expect(device.starts == 1) + let sound = SampledSound(encoding: .signedBigEndian, sampleRate: 22050, channels: 1, bitsPerSample: 16, count: 2, data: [0x03, 0xE8, 0xFC, 0x18]) + let channel = try mixer.newChannel() + try channel.play(sound) + var buffer = [Float](repeating: 9, count: 8) + buffer.withUnsafeMutableBufferPointer { device.render?($0) } + #expect(buffer == [1000, 1000, -1000, -1000, 0, 0, 0, 0].map { Float($0) / 32768 }) + mixer.stop() + #expect(device.stops == 1 && device.render == nil) + mixer.stop() + #expect(device.stops == 1) + } + + @Test func aBufferOfAnOddCountHasNoHalfFrame() { + let mixer = SoundMixer(sampleRate: 8000) + var buffer = [Float](repeating: 5, count: 5) + buffer.withUnsafeMutableBufferPointer { mixer.render(into: $0) } + #expect(Array(buffer.prefix(4)) == [0, 0, 0, 0]) + #expect(buffer[4] == 5) + } + + // MARK: Threads + + @Test func commandsFromOtherThreadsWhileRendering() async throws { + let mixer = SoundMixer(sampleRate: 8000) + var bytes: [UInt8] = [] + for sample in 0 ..< 800 { bytes += [UInt8(sample >> 8 & 0x7F), UInt8(sample & 0xFF)] } + let sound = SampledSound(encoding: .signedBigEndian, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 800, data: bytes) + let played = Counter() + await withTaskGroup(of: Void.self) { group in + group.addTask { + for _ in 0 ..< 300 { _ = mixer.render(frames: 100) } + } + for worker in 0 ..< 4 { + group.addTask { + for round in 0 ..< 50 { + guard let channel = try? mixer.newChannel() else { continue } + try? channel.play(sound) { played.increment() } + try? channel.doCommand(.amplitude(worker * 40 + round)) + try? channel.doCommand(.wait(halfMilliseconds: 10)) + try? channel.doCommand(.sync(count: 2, identifier: Int32(round % 3))) + _ = channel.status + if round % 4 == 0 { channel.dispose() } + } + } + } + } + // Whatever the channels were doing, rendering goes on and ends. + for _ in 0 ..< 200 { _ = mixer.render(frames: 100) } + #expect(played.value <= 200) + } +} From cc4d1cc01d949fcab86dc34d8d50371f7db983e8 Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 10/11] Described the channels and mixer in the package's header --- Package.swift | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Package.swift b/Package.swift index 74ce438..12907a8 100644 --- a/Package.swift +++ b/Package.swift @@ -21,7 +21,7 @@ import PackageDescription /// - `GraphiteText`: fonts, the Font Manager's families, the built-in /// system font, and QuickDraw's text. /// - `GraphiteSound`: sampled sounds from 'snd ' resources and AIFF files, -/// and the codecs that decode them. +/// the codecs that decode them, and the channels and mixer that play them. /// - `Graphite`: re-exports the modules above. /// /// Everything here depends only on the Swift standard library, the C From 66cdd57d304f6ccf75ae8c8c418099993798f54e Mon Sep 17 00:00:00 2001 From: Alsey Coleman Miller Date: Thu, 26 Nov 2026 12:33:51 -0500 Subject: [PATCH 11/11] Described the sound channels and mixer in the README --- README.md | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 2485a4c..4d1cab4 100644 --- a/README.md +++ b/README.md @@ -27,10 +27,9 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). > **Status:** early development. `GraphiteBase`, `GraphiteTasks`, > `GraphiteFiles`, `GraphiteResources`, `GraphiteAppleEvents`, -> `GraphiteQuickDraw` and `GraphiteText` are in place, and `GraphiteSound` has -> begun: sampled sounds, their codecs and AIFF files. The Sound Manager's -> channels and mixer, and the Toolbox's windows, menus, controls and dialogs, -> come next. +> `GraphiteQuickDraw`, `GraphiteText` and `GraphiteSound` are in place, apart +> from the MACE codecs and double-buffered sound. The Toolbox's windows, menus, +> controls and dialogs come next. ## Modules @@ -43,7 +42,7 @@ Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao). | `GraphiteAppleEvents` | The Apple Event Manager: descriptors, lists, records and Apple events as values; coercions between text, numbers, booleans, codes, lists, records and file types (`furl`, `fss `, `alis`, and the host's), with installed handlers; the application's handlers by class and ID with wildcards; events sent to itself, and the required events. | | `GraphiteQuickDraw` | QuickDraw's pixels (1 to 8 bits indexed, 16 and 32 bits direct, big-endian on every CPU, in memory of its own or a program's), colors and the system's color tables, regions as real regions with QuickDraw's region records, patterns, transfer modes, ports, devices and offscreen worlds; drawing rectangles, ovals, round rectangles, arcs, polygons, regions and lines with the pen, and CopyBits, CopyMask and ScrollRect between any depths; PICT pictures, version 1 and 2, with PackBits and QuickTime-compressed images through a decoder the host gives. | | `GraphiteText` | Fonts: faces and their metrics, the Font Manager's family numbers and names with the classic fonts' and their substitutes, a built-in bitmap system font (from Pomme), and QuickDraw's text in a port's font, face, size and mode, with the styles a face hasn't drawn from its plain glyphs; ATSUI-style layouts with styled runs, line breaking, measuring, hit testing and drawing, and the text in PICT pictures; and, with the `FreeType` trait (on by default), faces from TrueType, OpenType and other outline fonts, found by family name in the system's font folders. | -| `GraphiteSound` | Sampled sounds: `'snd '` resources (formats 1 and 2, with the standard, compressed and extended headers) and AIFF and AIFF-C files, read to their samples as 16-bit PCM; the µ-law, A-law and IMA4 codecs (MACE is recognized but not decoded yet); and the frequencies of MIDI notes. | +| `GraphiteSound` | The Sound Manager: sampled sounds from `'snd '` resources (formats 1 and 2, with the standard, compressed and extended headers) and AIFF and AIFF-C files, read to 16-bit PCM; the µ-law, A-law and IMA4 codecs (MACE is recognized but not decoded yet); sound channels with queued commands (`SndDoCommand`) including `callBackCmd`, `waitCmd` and `syncCmd`, immediate ones, volume, pan, pitch, loops and completion; a mixer that renders them to stereo float frames, for an audio device the host provides; and the frequencies of MIDI notes. | | `Graphite` | Re-exports the modules above. | Everything depends only on the Swift standard library, the C library