Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@ import PackageDescription
/// transfer modes, ports, devices and offscreen worlds.
/// - `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.
/// - `Graphite`: re-exports the modules above.
///
/// Everything here depends only on the Swift standard library, the C
Expand Down Expand Up @@ -64,6 +66,10 @@ let package = Package(
.library(
name: "GraphiteText",
targets: ["GraphiteText"]
),
.library(
name: "GraphiteSound",
targets: ["GraphiteSound"]
)
],
// FreeType reads outline fonts; builds without it keep the bitmap font.
Expand Down Expand Up @@ -115,9 +121,13 @@ let package = Package(
.product(name: "FreeTypeSwift", package: "swift-freetype", condition: .when(traits: ["FreeType"])),
]
),
.target(
name: "GraphiteSound",
dependencies: ["GraphiteBase"]
),
.target(
name: "Graphite",
dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText"]
dependencies: ["GraphiteBase", "GraphiteTasks", "GraphiteFiles", "GraphiteResources", "GraphiteAppleEvents", "GraphiteQuickDraw", "GraphiteText", "GraphiteSound"]
),
.testTarget(
name: "GraphiteBaseTests",
Expand Down Expand Up @@ -146,6 +156,10 @@ let package = Package(
.testTarget(
name: "GraphiteTextTests",
dependencies: ["GraphiteText"]
),
.testTarget(
name: "GraphiteSoundTests",
dependencies: ["GraphiteSound"]
)
]
)
19 changes: 12 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,11 @@ the layer that exports Carbon.
Any UI it shows will be drawn with [Cacao](https://github.com/PureSwift/Cacao).

> **Status:** early development. `GraphiteBase`, `GraphiteTasks`,
> `GraphiteFiles`, `GraphiteResources`, `GraphiteAppleEvents` and
> `GraphiteQuickDraw` are in place, and `GraphiteText` has begun; FreeType
> faces, ATSUI layouts, the Toolbox's windows, menus, controls and dialogs,
> and the Sound Manager come next.
> `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.

## Modules

Expand All @@ -42,12 +43,16 @@ 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. |
| `Graphite` | Re-exports the modules above. |

Everything depends only on the Swift standard library, the C library
(Glibc, Musl or Darwin) and System: Apple's on macOS, or one installed
with CMake, else [swift-system](https://github.com/apple/swift-system)'s
package. Graphite builds for Linux on x86_64, arm64, i686
(Glibc, Musl or Darwin), Foundation (for bytes and property lists) and System:
Apple's on macOS, or one installed with CMake, else
[swift-system](https://github.com/apple/swift-system)'s package. With the
`FreeType` trait, `GraphiteText` also depends on
[swift-freetype](https://github.com/PureSwift/swift-freetype). Graphite builds
for Linux on x86_64, arm64, i686
and 32-bit PowerPC, and for macOS, where it can be compared with Apple's
CarbonCore.

Expand Down
1 change: 1 addition & 0 deletions Sources/Graphite/Graphite.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,4 @@
@_exported import GraphiteAppleEvents
@_exported import GraphiteQuickDraw
@_exported import GraphiteText
@_exported import GraphiteSound
30 changes: 30 additions & 0 deletions Sources/GraphiteBase/MacError.swift
Original file line number Diff line number Diff line change
Expand Up @@ -190,8 +190,38 @@ extension MacError: CustomStringConvertible {
-1707: "errAENotAppleEvent", -1708: "errAEEventNotHandled", -1709: "errAEReplyNotValid",
-1710: "errAEUnknownSendMode", -1712: "errAETimeout", -1717: "errAEHandlerNotFound",
-1719: "errAEIllegalIndex",
-201: "notEnoughHardwareErr", -203: "queueFull", -204: "resProblem", -205: "badChannel",
-206: "badFormat", -207: "notEnoughBufferSpace", -208: "badFileFormat", -209: "channelBusy",
-210: "buffersTooSmall", -223: "siInvalidCompression",
]
guard let name = names[code] else { return "\(code)" }
return "\(name) (\(code))"
}
}

// MARK: - Sound Manager

public extension MacError {

/// notEnoughHardwareErr: the hardware can't do it.
static var notEnoughHardware: MacError { MacError(-201) }
/// queueFull: a channel's command queue has no room.
static var queueFull: MacError { MacError(-203) }
/// resProblem: a sound resource couldn't be loaded.
static var soundResourceProblem: MacError { MacError(-204) }
/// badChannel: the channel is corrupt or can't be used.
static var badChannel: MacError { MacError(-205) }
/// badFormat: a 'snd ' resource is corrupt or can't be used.
static var badFormat: MacError { MacError(-206) }
/// notEnoughBufferSpace: not enough memory for the sound.
static var notEnoughBufferSpace: MacError { MacError(-207) }
/// badFileFormat: a sound file is corrupt, or not AIFF or AIFF-C.
static var badFileFormat: MacError { MacError(-208) }
/// channelBusy: the channel is in use.
static var channelBusy: MacError { MacError(-209) }
/// buffersTooSmall: a double buffer's buffers are too small.
static var buffersTooSmall: MacError { MacError(-210) }
/// siInvalidCompression: the compression type isn't one the sound
/// manager has.
static var invalidCompression: MacError { MacError(-223) }
}
115 changes: 115 additions & 0 deletions Sources/GraphiteSound/AIFF.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
// AIFF and AIFF-C files: the common chunk's format, the sound data chunk,
// and the markers and instrument chunk that loop a sound.
//
// Ported from Pomme's SoundFormats/AIFF.cpp:
// 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 protocol Foundation.ContiguousBytes
import struct Foundation.Data
import GraphiteBase

public extension SampledSound {

/// The sound of an AIFF or AIFF-C file, which is what SndStartFilePlay
/// plays. The samples are a slice of the file's bytes, not a copy. A
/// loop is the instrument chunk's sustain loop where it has one, between
/// markers the file has. `badFileFormat` for bytes that aren't one, that
/// end early, have no common chunk or sound data, or name a compression
/// type that isn't here.
init(aiff bytes: some ContiguousBytes) throws(MacError) {
let data = Data(sharing: bytes)
var reader = BigEndianReader(data)
do {
guard try reader.read(UInt32.self) == FourCharCode("FORM").rawValue else { throw MacError.badFileFormat }
let formSize = Int(try reader.read(UInt32.self))
let end = min(data.count, 8 + formSize)
let formType = FourCharCode(try reader.read(UInt32.self))
guard formType == "AIFF" || formType == "AIFC" else { throw MacError.badFileFormat }

var format: (channels: Int, frames: Int, bits: Int, rate: Double, encoding: SoundEncoding)?
var samples: Range<Int>?
var markers: [UInt16: Int] = [:]
var baseNote = 60
var loopMarkers: (begin: UInt16, end: UInt16)?

while reader.offset + 8 <= end {
let id = FourCharCode(try reader.read(UInt32.self))
let size = Int(try reader.read(UInt32.self))
let body = reader.offset
guard size <= data.count - body else { throw MacError.badFileFormat }
switch id {
case "COMM":
let channels = Int(try reader.read(UInt16.self))
let frames = Int(try reader.read(UInt32.self))
let bits = Int(try reader.read(UInt16.self))
let rate = try reader.readExtended80().doubleValue
var encoding = SoundEncoding.signedBigEndian
if formType == "AIFC" {
guard let known = SoundEncoding(compressionType: FourCharCode(try reader.read(UInt32.self))) else {
throw MacError.badFileFormat
}
encoding = known
}
format = (channels, frames, encoding.isCompressed ? 16 : bits, rate, encoding)
case "MARK":
let count = Int(try reader.read(UInt16.self))
for _ in 0 ..< count {
let marker = try reader.read(UInt16.self)
markers[marker] = Int(try reader.read(UInt32.self))
// The name, a Pascal string padded to an even length.
let length = Int(try reader.read(UInt8.self))
try reader.skip(length + (length + 1) % 2)
}
case "INST":
baseNote = Int(try reader.read(Int8.self))
try reader.skip(1 + 1 + 1 + 1 + 1 + 2) // detune to gain
let playMode = try reader.read(UInt16.self)
let begin = try reader.read(UInt16.self)
let loopEnd = try reader.read(UInt16.self)
if playMode == 1 { loopMarkers = (begin, loopEnd) }
case "SSND":
let offset = Int(try reader.read(UInt32.self))
try reader.skip(4) // blockSize
let start = body + 8 + offset
if start <= body + size { samples = start ..< body + size }
default:
break
}
// Chunks are padded to an even length.
let next = body + size + size % 2
guard next <= data.count else { break }
try reader.seek(to: next)
}
guard let format, let samples, format.channels >= 1, format.channels <= 256 else { throw MacError.badFileFormat }
var loop: Range<Int>?
if let loopMarkers, let begin = markers[loopMarkers.begin], let finish = markers[loopMarkers.end], finish > begin {
loop = begin ..< finish
}
self.init(encoding: format.encoding, sampleRate: format.rate, channels: format.channels, bitsPerSample: format.bits,
count: format.frames, data: data[data.startIndex + samples.lowerBound ..< data.startIndex + samples.upperBound],
baseNote: baseNote, loop: loop)
} catch let error as MacError {
throw error
} catch {
throw .badFileFormat
}
}
}
39 changes: 39 additions & 0 deletions Sources/GraphiteSound/MIDINote.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// The pitch of the MIDI note numbers a sound's base note and a note
// command use (Inside Macintosh: Sound, Table 2-2).
//
// Ported from Pomme's SoundFormats/Midi.cpp:
// 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 Foundation

public enum MIDINote {

/// kMiddleC.
public static var middleC: Int { 60 }

/// The frequency in hertz of a note of 0 to 127, in equal temperament
/// with note 69 the A of 440 Hz; 440 for a note outside that range, as
/// the Sound Manager's table answers.
public static func frequency(of note: Int) -> Double {
guard (0 ..< 128).contains(note) else { return 440 }
return 440 * pow(2, Double(note - 69) / 12)
}
}
114 changes: 114 additions & 0 deletions Sources/GraphiteSound/SampledSound.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// A sampled sound: what a 'snd ' resource's sampled sound header and an
// AIFF file both describe: samples and how to read them.

import protocol Foundation.ContiguousBytes
import struct Foundation.Data
import GraphiteBase

public struct SampledSound: Sendable {

public var encoding: SoundEncoding

/// Samples a second.
public var sampleRate: Double

public var channels: Int

/// The bits of an uncompressed sample (8, 16, 24 or 32); 16 for a
/// compressed one, which decodes to that.
public var bitsPerSample: Int

/// The sample frames of an uncompressed sound; the packets of a
/// compressed one.
public var count: Int

/// The samples as they are stored. It may be a slice of the resource or
/// file it came from, and so need not start at index 0.
public var data: Data

/// The MIDI note the sound plays at its own rate, 60 for middle C.
public var baseNote: Int

/// The sample frames to repeat, from the loop's start to its end.
public var loop: Range<Int>?

public init(encoding: SoundEncoding, sampleRate: Double, channels: Int, bitsPerSample: Int, count: Int,
data: some ContiguousBytes, baseNote: Int = 60, loop: Range<Int>? = nil) {
self.encoding = encoding
self.sampleRate = sampleRate
self.channels = channels
self.bitsPerSample = bitsPerSample
self.count = count
self.data = Data(sharing: data)
self.baseNote = baseNote
self.loop = loop
}

/// The sample frames the sound plays for: its count, or its packets'
/// worth.
public var frameCount: Int {
Self.product(count, encoding.packet?.frames ?? 1)
}

/// Seconds.
public var duration: Double {
sampleRate > 0 ? Double(frameCount) / sampleRate : 0
}

/// The samples as 16-bit signed integers, one frame's channels after
/// another. A sound with less data than its count says gives the frames
/// there are. `badFormat` for no channels or an odd sample size, and
/// `unimplemented` for MACE.
public func pcm16() throws(MacError) -> [Int16] {
guard channels >= 1, count >= 0 else { throw .badFormat }
switch encoding {
case .mace3, .mace6:
throw .unimplemented
case .unsigned8:
guard bitsPerSample == 8 else { throw .badFormat }
case .signedBigEndian, .signedLittleEndian:
guard [8, 16, 24, 32].contains(bitsPerSample) else { throw .badFormat }
case .ulaw, .alaw, .ima4:
break
}
return data.withUnsafeBytes { raw in
if let codec = encoding.codec, let packet = encoding.packet {
let needed = Self.product(Self.product(count, packet.bytes), channels)
return codec.decode(channels: channels, packets: UnsafeRawBufferPointer(rebasing: raw[..<min(raw.count, needed)]))
}
let width = encoding == .unsigned8 ? 1 : bitsPerSample / 8
let total = min(Self.product(count, channels), raw.count / width)
var samples = [Int16](repeating: 0, count: total)
for index in 0 ..< total {
let at = index * width
switch encoding {
case .unsigned8:
samples[index] = Int16((Int(raw[at]) - 128) << 8)
case .signedBigEndian:
samples[index] = width == 1 ? Int16(Int8(bitPattern: raw[at])) << 8
: Int16(bitPattern: UInt16(raw[at]) << 8 | UInt16(raw[at + 1]))
default:
samples[index] = width == 1 ? Int16(Int8(bitPattern: raw[at])) << 8
: Int16(bitPattern: UInt16(raw[at + width - 1]) << 8 | UInt16(raw[at + width - 2]))
}
}
return samples
}
}

/// A product that stops at the largest Int, so that a count a hostile
/// resource gives can't overflow on a 32-bit CPU.
private static func product(_ a: Int, _ b: Int) -> Int {
let (value, overflow) = a.multipliedReportingOverflow(by: b)
return overflow ? Int.max : value
}
}

extension Data {

/// A Data of any contiguous bytes: the same one if they are, so a slice
/// of a mapped file stays a slice of it.
init(sharing bytes: some ContiguousBytes) {
self = bytes as? Data ?? bytes.withUnsafeBytes { Data($0) }
}
}
Loading
Loading