Skip to content
Merged
2 changes: 1 addition & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
9 changes: 4 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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
Expand Down
17 changes: 17 additions & 0 deletions Sources/GraphiteSound/AudioOutput.swift
Original file line number Diff line number Diff line change
@@ -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<Float>) -> Void)

/// Stops playing and lets go of the `render` it was given.
func stop()
}
125 changes: 125 additions & 0 deletions Sources/GraphiteSound/ChannelState.swift
Original file line number Diff line number Diff line change
@@ -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<Int>?

/// 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
}
}
2 changes: 1 addition & 1 deletion Sources/GraphiteSound/SampledSound.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
76 changes: 76 additions & 0 deletions Sources/GraphiteSound/SoundChannel.swift
Original file line number Diff line number Diff line change
@@ -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)
}
}
125 changes: 125 additions & 0 deletions Sources/GraphiteSound/SoundCommand.swift
Original file line number Diff line number Diff line change
@@ -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
}
}
}
Loading
Loading