diff --git a/Package.swift b/Package.swift index 7259d0d..74ce438 100644 --- a/Package.swift +++ b/Package.swift @@ -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 @@ -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. @@ -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", @@ -146,6 +156,10 @@ let package = Package( .testTarget( name: "GraphiteTextTests", dependencies: ["GraphiteText"] + ), + .testTarget( + name: "GraphiteSoundTests", + dependencies: ["GraphiteSound"] ) ] ) diff --git a/README.md b/README.md index 8bab054..2485a4c 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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. diff --git a/Sources/Graphite/Graphite.swift b/Sources/Graphite/Graphite.swift index fa03e51..060c21c 100644 --- a/Sources/Graphite/Graphite.swift +++ b/Sources/Graphite/Graphite.swift @@ -8,3 +8,4 @@ @_exported import GraphiteAppleEvents @_exported import GraphiteQuickDraw @_exported import GraphiteText +@_exported import GraphiteSound diff --git a/Sources/GraphiteBase/MacError.swift b/Sources/GraphiteBase/MacError.swift index 83d0732..372653e 100644 --- a/Sources/GraphiteBase/MacError.swift +++ b/Sources/GraphiteBase/MacError.swift @@ -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) } +} diff --git a/Sources/GraphiteSound/AIFF.swift b/Sources/GraphiteSound/AIFF.swift new file mode 100644 index 0000000..f45772c --- /dev/null +++ b/Sources/GraphiteSound/AIFF.swift @@ -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? + 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? + 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 + } + } +} diff --git a/Sources/GraphiteSound/MIDINote.swift b/Sources/GraphiteSound/MIDINote.swift new file mode 100644 index 0000000..3ed32b7 --- /dev/null +++ b/Sources/GraphiteSound/MIDINote.swift @@ -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) + } +} diff --git a/Sources/GraphiteSound/SampledSound.swift b/Sources/GraphiteSound/SampledSound.swift new file mode 100644 index 0000000..777b8d2 --- /dev/null +++ b/Sources/GraphiteSound/SampledSound.swift @@ -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? + + public init(encoding: SoundEncoding, sampleRate: Double, channels: Int, bitsPerSample: Int, count: Int, + data: some ContiguousBytes, baseNote: Int = 60, loop: Range? = 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[.. 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) } + } +} diff --git a/Sources/GraphiteSound/SoundCodec.swift b/Sources/GraphiteSound/SoundCodec.swift new file mode 100644 index 0000000..b45f5ff --- /dev/null +++ b/Sources/GraphiteSound/SoundCodec.swift @@ -0,0 +1,119 @@ +// Decoders of compressed sound: G.711 µ-law and A-law, and IMA ADPCM as +// Apple frames it ('ima4'). Written from the formats' descriptions. + +/// Turns packets of compressed samples into 16-bit ones. +public protocol SoundCodec: Sendable { + + /// The bytes one channel's packet takes. + var bytesPerPacket: Int { get } + + /// The samples one channel's packet holds. + var samplesPerPacket: Int { get } + + /// The samples of the packets, interleaved over the channels as the + /// packets are: a channel's packet after the other channels' of the same + /// time. A partial packet at the end is dropped. + func decode(channels: Int, packets: UnsafeRawBufferPointer) -> [Int16] +} + +// MARK: - µ-law and A-law + +/// G.711 companding: a byte a sample, expanded to 16 bits. +public struct XLawCodec: SoundCodec { + + public enum Law: Hashable, Sendable { + case mu + case a + } + + public let law: Law + + public init(_ law: Law) { + self.law = law + } + + public var bytesPerPacket: Int { 1 } + public var samplesPerPacket: Int { 1 } + + public func decode(channels: Int, packets: UnsafeRawBufferPointer) -> [Int16] { + let table = law == .mu ? Self.muTable : Self.aTable + return packets.map { table[Int($0)] } + } + + /// The 16-bit sample of each µ-law byte. + static let muTable: [Int16] = (0 ..< 256).map { byte in + let u = ~UInt8(byte) + var t = (Int(u & 0x0F) << 3) + 0x84 + t <<= Int(u & 0x70) >> 4 + return Int16(u & 0x80 != 0 ? 0x84 - t : t - 0x84) + } + + /// The 16-bit sample of each A-law byte. + static let aTable: [Int16] = (0 ..< 256).map { byte in + let a = UInt8(byte) ^ 0x55 + var t = Int(a & 0x0F) << 4 + let segment = Int(a & 0x70) >> 4 + switch segment { + case 0: t += 8 + case 1: t += 0x108 + default: + t += 0x108 + t <<= segment - 1 + } + return Int16(a & 0x80 != 0 ? t : -t) + } +} + +// MARK: - IMA4 + +/// Apple's IMA ADPCM. A channel's packet is 34 bytes of 64 samples: a +/// 16-bit header with the predictor in its top 9 bits and the step index +/// in its low 7, then 32 bytes of 4-bit samples, the low nibble first. +public struct IMA4Codec: SoundCodec { + + public init() {} + + public var bytesPerPacket: Int { 34 } + public var samplesPerPacket: Int { 64 } + + public func decode(channels: Int, packets: UnsafeRawBufferPointer) -> [Int16] { + guard channels >= 1 else { return [] } + let count = packets.count / (34 * channels) + var samples = [Int16](repeating: 0, count: count * 64 * channels) + for packet in 0 ..< count { + for channel in 0 ..< channels { + let start = (packet * channels + channel) * 34 + let header = Int(packets[start]) << 8 | Int(packets[start + 1]) + var predictor = Int(Int16(bitPattern: UInt16(header & 0xFF80))) + var index = min(header & 0x7F, 88) + for byte in 0 ..< 32 { + let value = Int(packets[start + 2 + byte]) + for half in 0 ..< 2 { + let nibble = half == 0 ? value & 0x0F : value >> 4 + let step = Self.steps[index] + var difference = step >> 3 + if nibble & 1 != 0 { difference += step >> 2 } + if nibble & 2 != 0 { difference += step >> 1 } + if nibble & 4 != 0 { difference += step } + predictor += nibble & 8 != 0 ? -difference : difference + predictor = min(max(predictor, -32768), 32767) + index = min(max(index + Self.adjustments[nibble & 7], 0), 88) + samples[(packet * 64 + byte * 2 + half) * channels + channel] = Int16(predictor) + } + } + } + } + return samples + } + + /// The step sizes of IMA ADPCM, by step index. + public static let steps: [Int] = [ + 7, 8, 9, 10, 11, 12, 13, 14, 16, 17, 19, 21, 23, 25, 28, 31, 34, 37, 41, 45, 50, 55, 60, 66, 73, 80, 88, 97, 107, 118, + 130, 143, 157, 173, 190, 209, 230, 253, 279, 307, 337, 371, 408, 449, 494, 544, 598, 658, 724, 796, 876, 963, 1060, + 1166, 1282, 1411, 1552, 1707, 1878, 2066, 2272, 2499, 2749, 3024, 3327, 3660, 4026, 4428, 4871, 5358, 5894, 6484, + 7132, 7845, 8630, 9493, 10442, 11487, 12635, 13899, 15289, 16818, 18500, 20350, 22385, 24623, 27086, 29794, 32767, + ] + + /// How a sample's low three bits move the step index. + public static let adjustments = [-1, -1, -1, -1, 2, 4, 6, 8] +} diff --git a/Sources/GraphiteSound/SoundEncoding.swift b/Sources/GraphiteSound/SoundEncoding.swift new file mode 100644 index 0000000..2285ffb --- /dev/null +++ b/Sources/GraphiteSound/SoundEncoding.swift @@ -0,0 +1,86 @@ +// How a sampled sound's samples are stored: the compression types a 'snd ' +// resource or an AIFF-C file names. + +import GraphiteBase + +public enum SoundEncoding: Hashable, Sendable { + + /// 'raw ': 8-bit, offset binary, where silence is 128. + case unsigned8 + + /// 'twos', and AIFF's 'NONE': signed, big-endian, of 8, 16, 24 or 32 bits. + case signedBigEndian + + /// 'sowt': signed, little-endian. + case signedLittleEndian + + /// 'ulaw': G.711 µ-law, a byte a sample. + case ulaw + + /// 'alaw': G.711 A-law, a byte a sample. + case alaw + + /// 'ima4': Apple's IMA ADPCM, 4:1. + case ima4 + + /// 'MAC3': MACE 3:1. + case mace3 + + /// 'MAC6': MACE 6:1. + case mace6 + + /// The encoding a compression type names: nil for one that isn't here. + public init?(compressionType: FourCharCode) { + switch compressionType { + case "raw ": self = .unsigned8 + case "twos", "NONE": self = .signedBigEndian + case "sowt": self = .signedLittleEndian + case "ulaw": self = .ulaw + case "alaw": self = .alaw + case "ima4": self = .ima4 + case "MAC3": self = .mace3 + case "MAC6": self = .mace6 + default: return nil + } + } + + /// The compression type of 'snd ' resources and AIFF-C files. + public var compressionType: FourCharCode { + switch self { + case .unsigned8: "raw " + case .signedBigEndian: "twos" + case .signedLittleEndian: "sowt" + case .ulaw: "ulaw" + case .alaw: "alaw" + case .ima4: "ima4" + case .mace3: "MAC3" + case .mace6: "MAC6" + } + } + + /// Whether the samples are in packets of a codec's, not one after another. + public var isCompressed: Bool { packet != nil } + + /// A compressed channel's packet: the bytes it takes and the samples it + /// holds. Nil for uncompressed samples. + public var packet: (bytes: Int, frames: Int)? { + switch self { + case .ulaw, .alaw: (1, 1) + case .ima4: (34, 64) + case .mace3: (2, 6) + case .mace6: (1, 6) + case .unsigned8, .signedBigEndian, .signedLittleEndian: nil + } + } + + /// The codec that decodes the encoding; nil for uncompressed samples and + /// for MACE, which isn't decoded yet. + public var codec: (any SoundCodec)? { + switch self { + case .ulaw: XLawCodec(.mu) + case .alaw: XLawCodec(.a) + case .ima4: IMA4Codec() + case .unsigned8, .signedBigEndian, .signedLittleEndian, .mace3, .mace6: nil + } + } +} diff --git a/Sources/GraphiteSound/SoundResource.swift b/Sources/GraphiteSound/SoundResource.swift new file mode 100644 index 0000000..1751e6e --- /dev/null +++ b/Sources/GraphiteSound/SoundResource.swift @@ -0,0 +1,214 @@ +// 'snd ' resources: format 1 and 2, the commands that point at a sampled +// sound header, and the standard, compressed and extended headers. +// +// Ported from Pomme's SoundFormats/SoundFormats.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 enum SoundResource { + + public static var resourceType: FourCharCode { "snd " } + + /// The synthesizer of sampled sounds, the only one read here. + private static let sampledSynth: UInt16 = 5 + + /// The sound commands that carry a sampled sound header: soundCmd and + /// bufferCmd. + private static let headerCommands: Set = [80, 81] + + /// initMACE6 in a format 1 resource's init bits: a compressed header + /// that names no compression is MACE 6:1 then, and MACE 3:1 otherwise. + static let initMACE6: UInt32 = 0x0400 + + /// GetSoundHeaderOffset: where the sampled sound header is in a 'snd ' + /// resource, from its start. `badFormat` for a resource of another + /// format, or with no command that has sound data. + public static func headerOffset(in bytes: some ContiguousBytes) throws(MacError) -> Int { + try locate(in: Data(sharing: bytes)).offset + } + + /// The header's offset, and the init bits of a format 1 resource's + /// sampled synthesizer, which the header can need. + static func locate(in data: Data) throws(MacError) -> (offset: Int, initBits: UInt32) { + var reader = BigEndianReader(data) + do { + var initBits: UInt32 = 0 + switch try reader.read(UInt16.self) { + case 1: + let modifiers = Int(try reader.read(UInt16.self)) + var sampled = false + for _ in 0 ..< modifiers { + let synth = try reader.read(UInt16.self) + let bits = try reader.read(UInt32.self) + if synth == sampledSynth { + sampled = true + initBits = bits + } + } + guard sampled else { throw MacError.badFormat } + case 2: + try reader.skip(2) // the reference count, the program's + default: + throw MacError.badFormat + } + let commands = Int(try reader.read(UInt16.self)) + for _ in 0 ..< commands { + let command = try reader.read(UInt16.self) + try reader.skip(2) // param1 + let parameter = Int(try reader.read(UInt32.self)) + // With its high bit set, a command's param2 is an offset + // from the resource's start to its sound data. + if command & 0x8000 != 0, headerCommands.contains(command & 0x7FFF) { + guard parameter < data.count else { throw MacError.badFormat } + return (parameter, initBits) + } + } + throw MacError.badFormat + } catch let error as MacError { + throw error + } catch { + throw .badFormat + } + } +} + +public extension SampledSound { + + /// The first sampled sound of a 'snd ' resource. + init(snd bytes: some ContiguousBytes) throws(MacError) { + let data = Data(sharing: bytes) + let (offset, initBits) = try SoundResource.locate(in: data) + try self.init(header: data[data.startIndex + offset ..< data.endIndex], initBits: initBits) + } + + /// A sampled sound header and the samples after it: standard (8-bit + /// mono), compressed or extended. `initBits` are the init bits of the + /// resource that has it, for a compressed header that doesn't say + /// which MACE it is. A sound with less data than its header says has + /// the data there is. `badFormat` for a header that isn't one. + init(header bytes: some ContiguousBytes, initBits: UInt32 = 0) throws(MacError) { + let data = Data(sharing: bytes) + var reader = BigEndianReader(data) + do { + guard try reader.read(UInt32.self) == 0 else { throw MacError.badFormat } // samplePtr + let length = Int(try reader.read(Int32.self)) // the byte count, or the channels + let rate = Double(try reader.read(UInt32.self)) / 65536 + let loopStart = Int(try reader.read(UInt32.self)) + let loopEnd = Int(try reader.read(UInt32.self)) + let encode = try reader.read(UInt8.self) + let baseNote = Int(try reader.read(UInt8.self)) + let encoding: SoundEncoding + let channels: Int + let bits: Int + let count: Int + switch encode { + case 0x00: + encoding = .unsigned8 + channels = 1 + bits = 8 + count = length + case 0xFE: + count = Int(try reader.read(Int32.self)) + try reader.skip(14) // AIFFSampleRate, markerChunk + let type = try reader.read(UInt32.self) + try reader.skip(20) // futureUse2 to sampleSize + if type == 0 { + encoding = initBits & SoundResource.initMACE6 != 0 ? .mace6 : .mace3 + } else if let known = SoundEncoding(compressionType: FourCharCode(type)), known.isCompressed { + encoding = known + } else { + throw MacError.invalidCompression + } + channels = length + bits = 16 + case 0xFF: + count = Int(try reader.read(Int32.self)) + try reader.skip(22) // AIFFSampleRate to AESRecording + bits = Int(try reader.read(Int16.self)) + try reader.skip(14) // futureUse1 to futureUse4 + encoding = bits == 8 ? .unsigned8 : .signedBigEndian + channels = length + default: + throw MacError.badFormat + } + // Bounded, so the arithmetic below can't overflow on a 32-bit CPU. + guard channels >= 1, channels <= 256, count >= 0, bits >= 1, bits <= 64 else { throw MacError.badFormat } + let width = encoding.packet?.bytes ?? (bits + 7) / 8 + let size = Int(clamping: Int64(channels) * Int64(count) * Int64(width)) + let start = data.startIndex + reader.offset + let end = start + min(size, data.endIndex - start) + self.init(encoding: encoding, sampleRate: rate, channels: channels, bitsPerSample: bits, count: count, + data: data[start ..< end], baseNote: baseNote, loop: loopEnd > loopStart ? loopStart ..< loopEnd : nil) + } catch let error as MacError { + throw error + } catch { + throw .badFormat + } + } + + /// The sound as a format 1 'snd ' resource: a sampled synthesizer, one + /// bufferCmd and the header and samples it points at, in the standard + /// header where it can be (8-bit mono), the compressed one for MACE and + /// the other codecs, and the extended one for other uncompressed sound. + var sndResource: [UInt8] { + var writer = BigEndianWriter() + var initBits: UInt32 = channels == 1 ? 0x0080 : (channels == 2 ? 0x00C0 : 0) + if encoding == .mace3 { initBits |= 0x0300 } + if encoding == .mace6 { initBits |= SoundResource.initMACE6 } + writer.write(UInt16(1)) // format + writer.write(UInt16(1)) // one modifier + writer.write(UInt16(5)) // sampledSynth + writer.write(initBits) + writer.write(UInt16(1)) // one command + writer.write(UInt16(0x8051)) // bufferCmd, its param2 an offset + writer.write(UInt16(0)) + writer.write(UInt32(20)) // the header, after these 20 bytes + writer.write(UInt32(0)) // samplePtr + let isStandard = encoding == .unsigned8 && channels == 1 && bitsPerSample == 8 + writer.write(Int32(clamping: isStandard ? count : channels)) + writer.write(UInt32(sampleRate.isFinite ? min(max(sampleRate, 0), 65535) * 65536 : 0)) + writer.write(UInt32(clamping: loop?.lowerBound ?? 0)) + writer.write(UInt32(clamping: loop?.upperBound ?? 0)) + writer.write(UInt8(isStandard ? 0x00 : (encoding.isCompressed ? 0xFE : 0xFF))) + writer.write(UInt8(clamping: baseNote)) + if !isStandard { + writer.write(Int32(clamping: count)) + writer.write(bytes: Extended80(sampleRate).bytes) // AIFFSampleRate + if encoding.isCompressed { + writer.writeZeros(4) // markerChunk + writer.write(encoding.compressionType.rawValue) + writer.writeZeros(4 + 4 + 4) // futureUse2, stateVars, leftOverSamples + writer.write(Int16(-1)) // compressionID: fixedCompression + writer.writeZeros(2 + 2) // packetSize, snthID + writer.write(Int16(16)) // sampleSize + } else { + writer.writeZeros(4 + 4 + 4) // markerChunk, instrumentChunks, AESRecording + writer.write(Int16(clamping: bitsPerSample)) // sampleSize + writer.writeZeros(14) // futureUse1 to futureUse4 + } + } + writer.write(bytes: data) + return writer.bytes + } +} diff --git a/Tests/GraphiteBaseTests/MacErrorTests.swift b/Tests/GraphiteBaseTests/MacErrorTests.swift index f3177e8..e39bb0b 100644 --- a/Tests/GraphiteBaseTests/MacErrorTests.swift +++ b/Tests/GraphiteBaseTests/MacErrorTests.swift @@ -18,6 +18,17 @@ import GraphiteBase #expect(MacError.mpDeleted.code == -29295) } + @Test func soundManagerCodes() { + #expect(MacError.queueFull.code == -203) + #expect(MacError.badChannel.code == -205) + #expect(MacError.badFormat.code == -206) + #expect(MacError.badFileFormat.code == -208) + #expect(MacError.channelBusy.code == -209) + #expect(MacError.invalidCompression.code == -223) + #expect(MacError.badFormat.description == "badFormat (-206)") + #expect(MacError.badFileFormat.description == "badFileFormat (-208)") + } + @Test func descriptionNamesKnownCodes() { #expect(MacError.parameter.description == "paramErr (-50)") #expect(MacError(-12345).description == "-12345") diff --git a/Tests/GraphiteSoundTests/AIFFTests.swift b/Tests/GraphiteSoundTests/AIFFTests.swift new file mode 100644 index 0000000..8e0d984 --- /dev/null +++ b/Tests/GraphiteSoundTests/AIFFTests.swift @@ -0,0 +1,239 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct AIFFTests { + + // MARK: Fixtures, from the AIFF and AIFF-C specifications + + private func chunk(_ id: FourCharCode, _ body: [UInt8]) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(id.rawValue) + writer.write(UInt32(body.count)) + writer.write(bytes: body) + if body.count % 2 == 1 { writer.write(UInt8(0)) } + return writer.bytes + } + + /// An AIFF file of chunks. + private func file(_ chunks: [[UInt8]]) -> [UInt8] { form("AIFF", chunks) } + + /// An AIFF-C file of chunks. + private func aifc(_ chunks: [[UInt8]]) -> [UInt8] { form("AIFC", chunks) } + + private func form(_ form: FourCharCode, _ chunks: [[UInt8]]) -> [UInt8] { + var body = BigEndianWriter() + body.write(form.rawValue) + for chunk in chunks { body.write(bytes: chunk) } + var writer = BigEndianWriter() + writer.write(FourCharCode("FORM").rawValue) + writer.write(UInt32(body.count)) + writer.write(bytes: body.bytes) + return writer.bytes + } + + private func common(channels: UInt16 = 1, frames: UInt32, bits: UInt16 = 16, rate: Double = 44100, compression: FourCharCode? = nil) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(channels) + writer.write(frames) + writer.write(bits) + writer.write(bytes: Extended80(rate).bytes) + if let compression { + writer.write(compression.rawValue) + // The name, a Pascal string padded to an even length. + writer.write(bytes: [4, 0x74, 0x65, 0x73, 0x74, 0]) + } + return chunk("COMM", writer.bytes) + } + + private func soundData(_ samples: [UInt8], offset: UInt32 = 0, padding: Int = 0) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(offset) + writer.write(UInt32(0)) + writer.writeZeros(padding) + writer.write(bytes: samples) + return chunk("SSND", writer.bytes) + } + + private func markers(_ markers: [(UInt16, UInt32, String)]) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(markers.count)) + for (id, position, name) in markers { + writer.write(id) + writer.write(position) + let bytes = Array(name.utf8) + writer.write(UInt8(bytes.count)) + writer.write(bytes: bytes) + if (bytes.count + 1) % 2 == 1 { writer.write(UInt8(0)) } + } + return chunk("MARK", writer.bytes) + } + + private func instrument(baseNote: Int8 = 60, playMode: UInt16, begin: UInt16, end: UInt16) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(baseNote) + writer.write(bytes: [0, 0, 127, 1, 127]) // detune, low and high note, low and high velocity + writer.write(Int16(0)) // gain + writer.write(playMode) + writer.write(begin) + writer.write(end) + writer.write(bytes: [0, 0, 0, 0, 0, 0]) // the release loop + return chunk("INST", writer.bytes) + } + + // MARK: Reading + + @Test func aStereoSixteenBitFile() throws { + let aiff = file([common(channels: 2, frames: 2, bits: 16), soundData([0, 1, 0, 2, 0, 3, 0, 4])]) + let sound = try SampledSound(aiff: aiff) + #expect(sound.encoding == .signedBigEndian && sound.channels == 2 && sound.bitsPerSample == 16 && sound.count == 2) + #expect(sound.sampleRate == 44100 && sound.baseNote == 60 && sound.loop == nil) + #expect(try sound.pcm16() == [1, 2, 3, 4]) + } + + @Test func eightBitAIFFIsSigned() throws { + let sound = try SampledSound(aiff: file([common(frames: 3, bits: 8), soundData([0, 0x7F, 0x80])])) + #expect(sound.encoding == .signedBigEndian && sound.bitsPerSample == 8) + #expect(try sound.pcm16() == [0, 0x7F00, -0x8000]) + } + + @Test func sampleRates() throws { + for rate in [8000.0, 11025, 22050, 22254.545, 44100, 48000, 96000] { + let sound = try SampledSound(aiff: file([common(frames: 1, rate: rate), soundData([0, 0])])) + #expect(abs(sound.sampleRate - rate) < 1e-9) + } + } + + @Test func aifcCompressionTypes() throws { + let cases: [(FourCharCode, SoundEncoding)] = [ + ("NONE", .signedBigEndian), ("twos", .signedBigEndian), ("sowt", .signedLittleEndian), ("raw ", .unsigned8), + ("ulaw", .ulaw), ("alaw", .alaw), ("ima4", .ima4), ("MAC3", .mace3), ("MAC6", .mace6), + ] + for (type, encoding) in cases { + let sound = try SampledSound(aiff: aifc([common(frames: 1, compression: type), soundData([0, 0])])) + #expect(sound.encoding == encoding, "\(type)") + } + #expect(try SampledSound(aiff: aifc([common(frames: 1, bits: 16, compression: "ima4"), soundData([0])])).bitsPerSample == 16) + } + + @Test func littleEndianAIFC() throws { + let sound = try SampledSound(aiff: aifc([common(frames: 2, compression: "sowt"), soundData([1, 0, 0xFF, 0x7F])])) + #expect(try sound.pcm16() == [1, 32767]) + } + + @Test func ulawAIFC() throws { + let sound = try SampledSound(aiff: aifc([common(frames: 3, bits: 8, compression: "ulaw"), soundData([0x00, 0x80, 0xFF])])) + #expect(try sound.pcm16() == [-32124, 32124, 0]) + } + + @Test func imaAIFCCountsPackets() throws { + var packet = [UInt8](repeating: 0, count: 34) + packet[2] = 0x77 + let sound = try SampledSound(aiff: aifc([common(frames: 1, bits: 16, compression: "ima4"), soundData(packet)])) + #expect(sound.count == 1 && sound.frameCount == 64) + #expect(try sound.pcm16().prefix(2) == [11, 41]) + } + + @Test func loopsBetweenMarkers() throws { + let aiff = file([ + common(frames: 8), markers([(1, 2, "begin"), (2, 6, "end")]), instrument(baseNote: 65, playMode: 1, begin: 1, end: 2), + soundData([UInt8](repeating: 0, count: 16)), + ]) + let sound = try SampledSound(aiff: aiff) + #expect(sound.loop == 2 ..< 6) + #expect(sound.baseNote == 65) + } + + @Test func noLoopWithoutPlayModeOrMarkers() throws { + let samples = soundData([UInt8](repeating: 0, count: 16)) + let marks = markers([(1, 2, "a"), (2, 6, "b")]) + #expect(try SampledSound(aiff: file([common(frames: 8), marks, instrument(playMode: 0, begin: 1, end: 2), samples])).loop == nil) + #expect(try SampledSound(aiff: file([common(frames: 8), instrument(playMode: 1, begin: 1, end: 2), samples])).loop == nil) + #expect(try SampledSound(aiff: file([common(frames: 8), marks, instrument(playMode: 1, begin: 1, end: 9), samples])).loop == nil) + // An end before the start is no loop. + #expect(try SampledSound(aiff: file([common(frames: 8), marks, instrument(playMode: 1, begin: 2, end: 1), samples])).loop == nil) + } + + @Test func oddChunksArePaddedAndUnknownOnesSkipped() throws { + let aiff = file([ + chunk("ANNO", [0x61, 0x62, 0x63]), // odd: a pad byte follows + common(frames: 2), chunk("FVER", [0xA2, 0x80, 0x51, 0x40]), + chunk("NAME", Array("a name!".utf8)), + soundData([0, 1, 0, 2]), + ]) + #expect(try SampledSound(aiff: aiff).pcm16() == [1, 2]) + } + + @Test func theSoundDataChunkMayStartPastItsOffset() throws { + // An offset of 4 skips four bytes of padding before the first sample. + let sound = try SampledSound(aiff: file([common(frames: 2), soundData([0, 1, 0, 2], offset: 4, padding: 4)])) + #expect(try sound.pcm16() == [1, 2]) + } + + @Test func samplesAreASliceOfTheFile() throws { + let aiff = Data(file([common(frames: 2), soundData([0, 1, 0, 2])])) + let sound = try SampledSound(aiff: aiff) + #expect(sound.data.startIndex > 0) + #expect(Array(sound.data) == [0, 1, 0, 2]) + } + + @Test func filesFromAnyBytes() throws { + let bytes = file([common(frames: 1), soundData([0, 9])]) + #expect(try SampledSound(aiff: Data(bytes)).pcm16() == [9]) + #expect(try SampledSound(aiff: Data([1, 2, 3, 4, 5] + bytes)[5...]).pcm16() == [9]) + #expect(try bytes.withUnsafeBytes { try SampledSound(aiff: $0) }.pcm16() == [9]) + } + + // MARK: Failures + + @Test func notAnAIFFFile() { + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: [UInt8]()) } + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: Array("RIFFxxxxWAVEfmt ".utf8)) } + var wrongForm = file([common(frames: 1), soundData([0, 0])]) + wrongForm[8] = 0x58 + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: wrongForm) } + } + + @Test func missingChunks() { + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: file([soundData([0, 0])])) } + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: file([common(frames: 1)])) } + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: file([])) } + } + + @Test func unknownCompressionAndBadChannels() { + #expect(throws: MacError.badFileFormat) { + try SampledSound(aiff: aifc([common(frames: 1, compression: "fl32"), soundData([0, 0])])) + } + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: file([common(channels: 0, frames: 1), soundData([0, 0])])) } + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: file([common(channels: 1000, frames: 1), soundData([0, 0])])) } + } + + @Test func chunksPastTheEnd() { + var aiff = file([common(frames: 1), soundData([0, 0])]) + aiff.removeLast(3) + #expect(throws: MacError.badFileFormat) { try SampledSound(aiff: aiff) } + } + + @Test func truncatedFilesNeverTrap() { + let files = [ + file([common(frames: 4), markers([(1, 0, "a"), (2, 3, "bb")]), instrument(playMode: 1, begin: 1, end: 2), soundData([1, 2, 3, 4, 5, 6, 7, 8])]), + aifc([common(frames: 1, compression: "ulaw"), soundData([1, 2])]), + ] + for aiff in files { + for length in 0 ... aiff.count { + if let sound = try? SampledSound(aiff: aiff.prefix(length)) { _ = try? sound.pcm16() } + } + } + } + + @Test func damagedBytesNeverTrap() { + var generator = QuickDrawRandom(seed: 11) + let original = file([common(frames: 4), markers([(1, 0, "a"), (2, 3, "bb")]), instrument(playMode: 1, begin: 1, end: 2), soundData([1, 2, 3, 4, 5, 6, 7, 8])]) + for _ in 0 ..< 400 { + var bytes = original + for _ in 0 ..< 4 { bytes[Int(UInt16(bitPattern: generator.next())) % bytes.count] = UInt8(truncatingIfNeeded: generator.next()) } + if let sound = try? SampledSound(aiff: bytes) { _ = try? sound.pcm16() } + } + } +} diff --git a/Tests/GraphiteSoundTests/CodecTests.swift b/Tests/GraphiteSoundTests/CodecTests.swift new file mode 100644 index 0000000..3e5774d --- /dev/null +++ b/Tests/GraphiteSoundTests/CodecTests.swift @@ -0,0 +1,215 @@ +import Foundation +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct CodecTests { + + private func decode(_ codec: some SoundCodec, channels: Int = 1, _ bytes: [UInt8]) -> [Int16] { + bytes.withUnsafeBytes { codec.decode(channels: channels, packets: $0) } + } + + // MARK: µ-law and A-law + + @Test func muLawMatchesG711() { + let codec = XLawCodec(.mu) + // The first and last of the positive half, and their mirrors. + #expect(decode(codec, [0x00, 0x01, 0x0F, 0x10, 0x7E, 0x7F]) == [-32124, -31100, -16764, -15996, -8, 0]) + #expect(decode(codec, [0x80, 0x81, 0x8F, 0x90, 0xFE, 0xFF]) == [32124, 31100, 16764, 15996, 8, 0]) + } + + @Test func aLawMatchesG711() { + let codec = XLawCodec(.a) + #expect(decode(codec, [0x00, 0x01, 0x02, 0x08, 0x55, 0x7F]) == [-5504, -5248, -6016, -7552, -8, -848]) + #expect(decode(codec, [0x80, 0x81, 0xD5, 0xFF]) == [5504, 5248, 8, 848]) + } + + @Test func everyByteIsTheNegativeOfItsMirror() { + for law in [XLawCodec.Law.mu, .a] { + let codec = XLawCodec(law) + let all = decode(codec, (0 ... 255).map(UInt8.init)) + #expect(all.count == 256) + for byte in 0 ..< 128 { #expect(all[byte] == -all[byte + 128]) } + } + } + + @Test func muLawIsMonotonicInItsMagnitude() { + let all = decode(XLawCodec(.mu), (0 ... 127).map(UInt8.init)) + #expect(all == all.sorted()) + #expect(all.first == -32124 && all.last == 0) + } + + @Test func xlawIgnoresChannels() { + let codec = XLawCodec(.mu) + #expect(decode(codec, channels: 2, [0x00, 0x80]) == [-32124, 32124]) + #expect(codec.bytesPerPacket == 1 && codec.samplesPerPacket == 1) + #expect(decode(codec, []).isEmpty) + } + + // MARK: IMA4 + + /// IMA4 as an encoder makes it, for the tests: the reconstruction a decoder + /// should give, and the bytes of packets, interleaved over channels. + private func encodeIMA4(_ channels: [[Int16]]) -> (bytes: [UInt8], reconstructed: [[Int16]]) { + let steps = IMA4Codec.steps + let adjustments = IMA4Codec.adjustments + var bytes: [UInt8] = [] + var reconstructed = channels.map { _ in [Int16]() } + var indices = [Int](repeating: 0, count: channels.count) + for block in 0 ..< channels[0].count / 64 { + for (channel, samples) in channels.enumerated() { + let slice = samples[block * 64 ..< (block + 1) * 64] + var predictor = min(max((Int(slice.first!) + 64) / 128 * 128, -32768), 32640) + var index = indices[channel] + let header = UInt16(truncatingIfNeeded: predictor) & 0xFF80 | UInt16(index) + bytes.append(UInt8(header >> 8)) + bytes.append(UInt8(header & 0xFF)) + var nibbles: [UInt8] = [] + for sample in slice { + var difference = Int(sample) - predictor + var nibble = 0 + if difference < 0 { + nibble = 8 + difference = -difference + } + var step = steps[index] + if difference >= step { nibble |= 4; difference -= step } + step >>= 1 + if difference >= step { nibble |= 2; difference -= step } + step >>= 1 + if difference >= step { nibble |= 1 } + // The decoder's own arithmetic, so what it gives is known. + let full = steps[index] + var delta = full >> 3 + if nibble & 1 != 0 { delta += full >> 2 } + if nibble & 2 != 0 { delta += full >> 1 } + if nibble & 4 != 0 { delta += full } + predictor = min(max(predictor + (nibble & 8 != 0 ? -delta : delta), -32768), 32767) + index = min(max(index + adjustments[nibble & 7], 0), 88) + nibbles.append(UInt8(nibble)) + reconstructed[channel].append(Int16(predictor)) + } + indices[channel] = index + for pair in stride(from: 0, to: 64, by: 2) { bytes.append(nibbles[pair] | nibbles[pair + 1] << 4) } + } + } + return (bytes, reconstructed) + } + + private func sine(_ count: Int, amplitude: Double, period: Double, phase: Double = 0) -> [Int16] { + (0 ..< count).map { index -> Int16 in + let angle = Double(index) / period * 2 * Double.pi + phase + return Int16(amplitude * Foundation.sin(angle)) + } + } + + @Test func decodesByTheStepTable() { + // Header 0: predictor 0, step index 0. A nibble of 7 adds the step's + // 7/8 and the step index moves by 8: 7, then 16, then 34. + var packet = [UInt8](repeating: 0, count: 34) + packet[2] = 0x77 + packet[3] = 0x77 + let samples = decode(IMA4Codec(), packet) + #expect(samples.count == 64) + // The fourth: index 24, a step of 73, adds 9 + 18 + 36 + 73. + #expect(Array(samples.prefix(4)) == [11, 41, 104, 240]) + } + + @Test func theHeaderGivesPredictorAndIndex() { + // Predictor 0x2000 (the top 9 bits of the header), index 0. A nibble of + // 8 is a negative zero difference and lowers the index, which stays 0. + var packet = [UInt8](repeating: 0x88, count: 34) + packet[0] = 0x20 + packet[1] = 0x00 + #expect(decode(IMA4Codec(), packet) == [Int16](repeating: 0x2000, count: 64)) + // The low 7 bits are the index, up to 88; more are clamped to it. + var clamped = [UInt8](repeating: 0, count: 34) + clamped[1] = 0x7F + #expect(decode(IMA4Codec(), clamped).count == 64) + } + + @Test func theStepTableIsIMAs() { + let steps = IMA4Codec.steps + #expect(steps.count == 89) + #expect(steps.first == 7 && steps.last == 32767) + #expect(steps == steps.sorted()) + // Each step is about a tenth more than the one before, past the first few. + for index in 16 ..< 88 { + let ratio = Double(steps[index + 1]) / Double(steps[index]) + #expect(ratio > 1.08 && ratio < 1.12, "step \(index)") + } + #expect(IMA4Codec.adjustments == [-1, -1, -1, -1, 2, 4, 6, 8]) + } + + @Test func nibblesAreLowFirst() { + var packet = [UInt8](repeating: 0, count: 34) + packet[2] = 0x70 // low nibble 0, high nibble 7 + let samples = decode(IMA4Codec(), packet) + #expect(samples[0] == 0) + #expect(samples[1] == 11) + } + + @Test func roundTripsASineWave() { + let wave = sine(640, amplitude: 8000, period: 50) + let (bytes, reconstructed) = encodeIMA4([wave]) + #expect(bytes.count == 10 * 34) + let decoded = decode(IMA4Codec(), bytes) + #expect(decoded == reconstructed[0]) + var sumOfSquares = 0.0 + for (got, wanted) in zip(decoded, wave) { + let difference = Double(Int(got) - Int(wanted)) + sumOfSquares += difference * difference + } + let rms = (sumOfSquares / Double(wave.count)).squareRoot() + #expect(rms < 400) + } + + @Test func channelsAreInterleavedFromTheirPackets() { + let left = sine(128, amplitude: 6000, period: 40) + let right = sine(128, amplitude: 3000, period: 25, phase: 1) + let (bytes, reconstructed) = encodeIMA4([left, right]) + let decoded = decode(IMA4Codec(), channels: 2, bytes) + #expect(decoded.count == 256) + #expect(stride(from: 0, to: 256, by: 2).map { decoded[$0] } == reconstructed[0]) + #expect(stride(from: 1, to: 256, by: 2).map { decoded[$0] } == reconstructed[1]) + } + + @Test func aPartialPacketIsDropped() { + let (bytes, reconstructed) = encodeIMA4([sine(64, amplitude: 5000, period: 30)]) + #expect(decode(IMA4Codec(), bytes + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) == reconstructed[0]) + #expect(decode(IMA4Codec(), Array(bytes.prefix(33))).isEmpty) + #expect(decode(IMA4Codec(), channels: 0, bytes).isEmpty) + #expect(IMA4Codec().bytesPerPacket == 34 && IMA4Codec().samplesPerPacket == 64) + } + + @Test func extremesStayInRange() { + // Every nibble the largest step up, and then down: no overflow. + let up = decode(IMA4Codec(), [0x7F, 0x00] + [UInt8](repeating: 0x77, count: 32)) + #expect(up.max()! <= 32767) + let down = decode(IMA4Codec(), [0x80, 0x00] + [UInt8](repeating: 0xFF, count: 32)) + #expect(down.min()! >= -32768) + } + + // MARK: Encodings + + @Test func compressionTypesRoundTrip() { + for encoding in [SoundEncoding.unsigned8, .signedBigEndian, .signedLittleEndian, .ulaw, .alaw, .ima4, .mace3, .mace6] { + #expect(SoundEncoding(compressionType: encoding.compressionType) == encoding) + } + #expect(SoundEncoding(compressionType: "NONE") == .signedBigEndian) + #expect(SoundEncoding(compressionType: "fl32") == nil) + #expect(SoundEncoding(compressionType: "zzzz") == nil) + } + + @Test func packetsAndCodecs() { + #expect(SoundEncoding.ima4.packet?.bytes == 34 && SoundEncoding.ima4.packet?.frames == 64) + #expect(SoundEncoding.mace3.packet?.bytes == 2 && SoundEncoding.mace3.packet?.frames == 6) + #expect(SoundEncoding.mace6.packet?.bytes == 1 && SoundEncoding.mace6.packet?.frames == 6) + #expect(SoundEncoding.ulaw.isCompressed && SoundEncoding.ima4.isCompressed && SoundEncoding.mace3.isCompressed) + #expect(!SoundEncoding.unsigned8.isCompressed && !SoundEncoding.signedLittleEndian.isCompressed) + #expect(SoundEncoding.ima4.codec is IMA4Codec) + #expect((SoundEncoding.ulaw.codec as? XLawCodec)?.law == .mu) + #expect((SoundEncoding.alaw.codec as? XLawCodec)?.law == .a) + #expect(SoundEncoding.mace3.codec == nil && SoundEncoding.unsigned8.codec == nil) + } +} diff --git a/Tests/GraphiteSoundTests/MIDINoteTests.swift b/Tests/GraphiteSoundTests/MIDINoteTests.swift new file mode 100644 index 0000000..dee3cd7 --- /dev/null +++ b/Tests/GraphiteSoundTests/MIDINoteTests.swift @@ -0,0 +1,36 @@ +import Testing +import GraphiteSound + +@Suite struct MIDINoteTests { + + @Test func aboveAndBelowTheA() { + #expect(MIDINote.frequency(of: 69) == 440) + #expect(abs(MIDINote.frequency(of: 81) - 880) < 1e-9) + #expect(abs(MIDINote.frequency(of: 57) - 220) < 1e-9) + #expect(abs(MIDINote.frequency(of: 45) - 110) < 1e-9) + } + + @Test func middleC() { + #expect(MIDINote.middleC == 60) + #expect(abs(MIDINote.frequency(of: MIDINote.middleC) - 261.6255653) < 1e-6) + } + + @Test func theEnds() { + #expect(abs(MIDINote.frequency(of: 0) - 8.1757989) < 1e-6) + #expect(abs(MIDINote.frequency(of: 127) - 12543.8539514) < 1e-4) + } + + @Test func eachSemitoneIsTheTwelfthRootOfTwoAbove() { + for note in 0 ..< 127 { + let ratio = MIDINote.frequency(of: note + 1) / MIDINote.frequency(of: note) + #expect(abs(ratio - 1.0594630943592953) < 1e-12) + } + } + + @Test func notesOutsideTheTableAre440() { + #expect(MIDINote.frequency(of: -1) == 440) + #expect(MIDINote.frequency(of: 128) == 440) + #expect(MIDINote.frequency(of: .max) == 440) + #expect(MIDINote.frequency(of: .min) == 440) + } +} diff --git a/Tests/GraphiteSoundTests/SampledSoundTests.swift b/Tests/GraphiteSoundTests/SampledSoundTests.swift new file mode 100644 index 0000000..234801a --- /dev/null +++ b/Tests/GraphiteSoundTests/SampledSoundTests.swift @@ -0,0 +1,99 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct SampledSoundTests { + + private func sound(_ encoding: SoundEncoding, channels: Int = 1, bits: Int = 16, count: Int, _ bytes: [UInt8]) -> SampledSound { + SampledSound(encoding: encoding, sampleRate: 22050, channels: channels, bitsPerSample: bits, count: count, data: bytes) + } + + @Test func unsignedEightBit() throws { + let pcm = try sound(.unsigned8, bits: 8, count: 5, [128, 255, 0, 129, 127]).pcm16() + #expect(pcm == [0, 127 << 8, -32768, 256, -256]) + } + + @Test func signedBigEndianInEveryWidth() throws { + #expect(try sound(.signedBigEndian, bits: 8, count: 3, [0x00, 0x7F, 0x80]).pcm16() == [0, 0x7F00, -0x8000]) + #expect(try sound(.signedBigEndian, bits: 16, count: 3, [0x00, 0x01, 0x7F, 0xFF, 0x80, 0x00]).pcm16() == [1, 32767, -32768]) + // The top 16 bits of the wider ones. + #expect(try sound(.signedBigEndian, bits: 24, count: 2, [0x12, 0x34, 0x56, 0xFF, 0xFF, 0xFF]).pcm16() == [0x1234, -1]) + #expect(try sound(.signedBigEndian, bits: 32, count: 2, [0x12, 0x34, 0x56, 0x78, 0x80, 0, 0, 0]).pcm16() == [0x1234, -32768]) + } + + @Test func signedLittleEndianInEveryWidth() throws { + #expect(try sound(.signedLittleEndian, bits: 16, count: 3, [0x01, 0x00, 0xFF, 0x7F, 0x00, 0x80]).pcm16() == [1, 32767, -32768]) + #expect(try sound(.signedLittleEndian, bits: 8, count: 2, [0x7F, 0x80]).pcm16() == [0x7F00, -0x8000]) + #expect(try sound(.signedLittleEndian, bits: 24, count: 1, [0x56, 0x34, 0x12]).pcm16() == [0x1234]) + #expect(try sound(.signedLittleEndian, bits: 32, count: 1, [0x78, 0x56, 0x34, 0x12]).pcm16() == [0x1234]) + } + + @Test func stereoFramesStayInterleaved() throws { + let pcm = try sound(.signedBigEndian, channels: 2, count: 2, [0, 1, 0, 2, 0, 3, 0, 4]).pcm16() + #expect(pcm == [1, 2, 3, 4]) + } + + @Test func compressedSoundsDecode() throws { + #expect(try sound(.ulaw, count: 3, [0x00, 0x80, 0xFF]).pcm16() == [-32124, 32124, 0]) + #expect(try sound(.alaw, count: 2, [0x55, 0xD5]).pcm16() == [-8, 8]) + var packet = [UInt8](repeating: 0, count: 34) + packet[2] = 0x77 + let ima = sound(.ima4, count: 1, packet) + #expect(try ima.pcm16().prefix(2) == [11, 41]) + #expect(ima.frameCount == 64) + } + + @Test func lessDataThanTheCountSaysGivesTheFramesThereAre() throws { + #expect(try sound(.signedBigEndian, count: 10, [0, 1, 0, 2, 0, 3, 9]).pcm16() == [1, 2, 3]) + #expect(try sound(.unsigned8, bits: 8, count: 100, [128, 129]).pcm16() == [0, 256]) + #expect(try sound(.ulaw, count: 9, [0x00]).pcm16() == [-32124]) + #expect(try sound(.signedBigEndian, count: 0, [1, 2, 3, 4]).pcm16().isEmpty) + // One whole packet of the two the count says; the stray bytes after it are dropped. + #expect(try sound(.ima4, count: 2, [UInt8](repeating: 0, count: 40)).pcm16().count == 64) + #expect(try sound(.ima4, count: 2, [UInt8](repeating: 0, count: 33)).pcm16().isEmpty) + } + + @Test func badSoundsAreBadFormat() { + #expect(throws: MacError.badFormat) { try sound(.signedBigEndian, channels: 0, count: 1, [0, 0]).pcm16() } + #expect(throws: MacError.badFormat) { try sound(.signedBigEndian, bits: 12, count: 1, [0, 0]).pcm16() } + #expect(throws: MacError.badFormat) { try sound(.unsigned8, bits: 16, count: 1, [0, 0]).pcm16() } + #expect(throws: MacError.badFormat) { try sound(.signedLittleEndian, count: -1, [0, 0]).pcm16() } + } + + @Test func maceIsNotDecodedYet() { + #expect(throws: MacError.unimplemented) { try sound(.mace3, count: 1, [0, 0]).pcm16() } + #expect(throws: MacError.unimplemented) { try sound(.mace6, count: 1, [0]).pcm16() } + #expect(sound(.mace3, count: 4, []).frameCount == 24) + #expect(sound(.mace6, count: 4, []).frameCount == 24) + } + + @Test func durationFollowsTheFrames() { + #expect(sound(.signedBigEndian, count: 22050, []).duration == 1) + #expect(sound(.ima4, count: 1, []).duration == 64.0 / 22050) + let silent = SampledSound(encoding: .unsigned8, sampleRate: 0, channels: 1, bitsPerSample: 8, count: 10, data: [UInt8]()) + #expect(silent.duration == 0) + } + + @Test func hostileCountsDontTrap() throws { + // Products of counts that overflow even a 64-bit Int stop at the data. + let huge = sound(.signedBigEndian, channels: 256, count: .max, [0, 1, 0, 2]) + #expect(try huge.pcm16() == [1, 2]) + #expect(huge.frameCount == Int.max) + let packets = sound(.ima4, channels: 256, count: .max, [UInt8](repeating: 0, count: 34)) + #expect(try packets.pcm16().isEmpty) + #expect(sound(.mace3, count: .max, []).frameCount == .max) + } + + @Test func dataIsKeptAsGivenIncludingSlices() throws { + let whole = Data([9, 9, 0, 1, 0, 2, 8]) + let slice = whole[2 ..< 6] + let sound = SampledSound(encoding: .signedBigEndian, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 2, data: slice) + #expect(sound.data.startIndex == 2) + #expect(try sound.pcm16() == [1, 2]) + let fromBuffer = try [UInt8]([0, 5]).withUnsafeBytes { + try SampledSound(encoding: .signedBigEndian, sampleRate: 8000, channels: 1, bitsPerSample: 16, count: 1, data: $0).pcm16() + } + #expect(fromBuffer == [5]) + } +} diff --git a/Tests/GraphiteSoundTests/SoundResourceTests.swift b/Tests/GraphiteSoundTests/SoundResourceTests.swift new file mode 100644 index 0000000..7154ce5 --- /dev/null +++ b/Tests/GraphiteSoundTests/SoundResourceTests.swift @@ -0,0 +1,283 @@ +import struct Foundation.Data +import Testing +import GraphiteBase +import GraphiteSound + +@Suite struct SoundResourceTests { + + // MARK: Fixtures, built from the layouts in Inside Macintosh: Sound + + /// The 22 bytes every sampled sound header begins with. + private func baseHeader(length: Int32, rate: UInt32, loopStart: UInt32 = 0, loopEnd: UInt32 = 0, encode: UInt8, baseNote: UInt8 = 60) -> BigEndianWriter { + var writer = BigEndianWriter() + writer.write(UInt32(0)) + writer.write(length) + writer.write(rate) + writer.write(loopStart) + writer.write(loopEnd) + writer.write(encode) + writer.write(baseNote) + return writer + } + + private let rate22k: UInt32 = 0x56EE_8BA3 // rate22khz, 22254.545… + private let rate44k: UInt32 = 44100 << 16 + + private func standard(_ samples: [UInt8], loopStart: UInt32 = 0, loopEnd: UInt32 = 0) -> [UInt8] { + var writer = baseHeader(length: Int32(samples.count), rate: rate22k, loopStart: loopStart, loopEnd: loopEnd, encode: 0x00) + writer.write(bytes: samples) + return writer.bytes + } + + private func extended(channels: Int32, frames: Int32, bits: Int16, samples: [UInt8]) -> [UInt8] { + var writer = baseHeader(length: channels, rate: rate44k, encode: 0xFF) + writer.write(frames) + writer.write(bytes: Extended80(44100).bytes) + writer.writeZeros(4 + 4 + 4) + writer.write(bits) + writer.writeZeros(14) + writer.write(bytes: samples) + return writer.bytes + } + + private func compressed(channels: Int32, packets: Int32, type: FourCharCode?, samples: [UInt8]) -> [UInt8] { + var writer = baseHeader(length: channels, rate: rate44k, encode: 0xFE) + writer.write(packets) + writer.writeZeros(10 + 4) + writer.write(type?.rawValue ?? 0) + writer.writeZeros(20) + writer.write(bytes: samples) + return writer.bytes + } + + /// A format 1 resource with a sampled synthesizer and one bufferCmd. + private func format1(_ header: [UInt8], initBits: UInt32 = 0x0080) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(1)) + writer.write(UInt16(1)) + writer.write(UInt16(5)) + writer.write(initBits) + writer.write(UInt16(1)) + writer.write(UInt16(0x8051)) + writer.write(UInt16(0)) + writer.write(UInt32(20)) + writer.write(bytes: header) + return writer.bytes + } + + /// A format 2 resource: a reference count and one soundCmd. + private func format2(_ header: [UInt8]) -> [UInt8] { + var writer = BigEndianWriter() + writer.write(UInt16(2)) + writer.write(UInt16(0x1234)) + writer.write(UInt16(1)) + writer.write(UInt16(0x8050)) + writer.write(UInt16(0)) + writer.write(UInt32(14)) + writer.write(bytes: header) + return writer.bytes + } + + // MARK: Reading + + @Test func standardHeaders() throws { + let sound = try SampledSound(snd: format1(standard([128, 255, 0, 128]))) + #expect(sound.encoding == .unsigned8 && sound.channels == 1 && sound.bitsPerSample == 8 && sound.count == 4) + #expect(abs(sound.sampleRate - 22254.545) < 0.01) + #expect(sound.baseNote == 60 && sound.loop == nil) + #expect(try sound.pcm16() == [0, 127 << 8, -32768, 0]) + } + + @Test func format2ResourcesToo() throws { + let sound = try SampledSound(snd: format2(standard([200, 100]))) + #expect(try sound.pcm16() == [72 << 8, -28 << 8]) + #expect(try SoundResource.headerOffset(in: format2(standard([]))) == 14) + #expect(try SoundResource.headerOffset(in: format1(standard([]))) == 20) + } + + @Test func extendedHeaders() throws { + let sound = try SampledSound(snd: format1(extended(channels: 2, frames: 3, bits: 16, + samples: [0, 1, 0, 2, 0, 3, 0, 4, 0, 5, 0, 6]), initBits: 0x00C0)) + #expect(sound.encoding == .signedBigEndian && sound.channels == 2 && sound.bitsPerSample == 16 && sound.count == 3) + #expect(sound.sampleRate == 44100) + #expect(try sound.pcm16() == [1, 2, 3, 4, 5, 6]) + // Eight bits, in an extended header, are unsigned. + let eight = try SampledSound(header: extended(channels: 1, frames: 2, bits: 8, samples: [128, 255])) + #expect(eight.encoding == .unsigned8) + #expect(try eight.pcm16() == [0, 127 << 8]) + } + + @Test func compressedHeaders() throws { + let ulaw = try SampledSound(snd: format1(compressed(channels: 1, packets: 3, type: "ulaw", samples: [0x00, 0x80, 0xFF]))) + #expect(ulaw.encoding == .ulaw && ulaw.bitsPerSample == 16 && ulaw.count == 3 && ulaw.frameCount == 3) + #expect(try ulaw.pcm16() == [-32124, 32124, 0]) + var packet = [UInt8](repeating: 0, count: 34) + packet[2] = 0x77 + let ima = try SampledSound(header: compressed(channels: 1, packets: 1, type: "ima4", samples: packet)) + #expect(ima.encoding == .ima4 && ima.frameCount == 64) + #expect(try ima.pcm16().prefix(2) == [11, 41]) + } + + @Test func noCompressionTypeIsMACEOfTheResourcesInitBits() throws { + let header = compressed(channels: 1, packets: 2, type: nil, samples: [1, 2, 3, 4]) + #expect(try SampledSound(snd: format1(header, initBits: 0x0080 | 0x0300)).encoding == .mace3) + #expect(try SampledSound(snd: format1(header, initBits: 0x0080 | 0x0400)).encoding == .mace6) + #expect(try SampledSound(header: header).encoding == .mace3) + #expect(try SampledSound(header: header).frameCount == 12) + } + + @Test func unknownCompressionIsInvalid() { + #expect(throws: MacError.invalidCompression) { try SampledSound(header: compressed(channels: 1, packets: 1, type: "zzzz", samples: [0])) } + // An uncompressed type isn't a compression a compressed header names. + #expect(throws: MacError.invalidCompression) { try SampledSound(header: compressed(channels: 1, packets: 1, type: "twos", samples: [0])) } + } + + @Test func loopsAndBaseNotes() throws { + let looped = try SampledSound(header: standard([1, 2, 3, 4, 5, 6], loopStart: 2, loopEnd: 5)) + #expect(looped.loop == 2 ..< 5) + #expect(try SampledSound(header: standard([1, 2], loopStart: 0, loopEnd: 0)).loop == nil) + #expect(try SampledSound(header: standard([1, 2], loopStart: 5, loopEnd: 3)).loop == nil) + var writer = baseHeader(length: 2, rate: rate22k, encode: 0, baseNote: 72) + writer.write(bytes: [1, 2]) + #expect(try SampledSound(header: writer.bytes).baseNote == 72) + } + + @Test func lessDataThanTheHeaderSaysIsWhatThereIs() throws { + var writer = baseHeader(length: 100, rate: rate22k, encode: 0) + writer.write(bytes: [128, 129, 130]) + let sound = try SampledSound(header: writer.bytes) + #expect(sound.count == 100) + #expect(sound.data.count == 3) + #expect(try sound.pcm16() == [0, 256, 512]) + } + + @Test func headerOffsetFailures() { + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: [UInt8]()) } + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: [0, 3, 0, 0]) } + // Format 1 with a synthesizer that isn't sampledSynth. + var squareWave = BigEndianWriter() + squareWave.write(UInt16(1)); squareWave.write(UInt16(1)); squareWave.write(UInt16(1)); squareWave.write(UInt32(0)) + squareWave.write(UInt16(1)); squareWave.write(UInt16(0x8051)); squareWave.write(UInt16(0)); squareWave.write(UInt32(20)) + squareWave.writeZeros(40) + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: squareWave.bytes) } + // No commands, a command without sound data, and an offset past the end. + var none = format1(standard([1])) + none[10] = 0 + none[11] = 0 + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: none) } + var noOffsetBit = format1(standard([1])) + noOffsetBit[12] = 0x00 + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: noOffsetBit) } + var past = format1(standard([1])) + past[18] = 0xFF + #expect(throws: MacError.badFormat) { try SoundResource.headerOffset(in: past) } + } + + @Test func headerFailures() { + #expect(throws: MacError.badFormat) { try SampledSound(header: [UInt8]()) } + #expect(throws: MacError.badFormat) { try SampledSound(header: [UInt8](repeating: 0, count: 21)) } + // A samplePtr that isn't zero, and an encoding that isn't a header's. + var pointer = standard([1]) + pointer[3] = 1 + #expect(throws: MacError.badFormat) { try SampledSound(header: pointer) } + var other = standard([1]) + other[20] = 0x42 + #expect(throws: MacError.badFormat) { try SampledSound(header: other) } + // No channels, and a negative count. + #expect(throws: MacError.badFormat) { try SampledSound(header: extended(channels: 0, frames: 1, bits: 16, samples: [0, 0])) } + #expect(throws: MacError.badFormat) { try SampledSound(header: extended(channels: 1, frames: -1, bits: 16, samples: [0, 0])) } + #expect(throws: MacError.badFormat) { try SampledSound(header: extended(channels: 1000, frames: 1, bits: 16, samples: [0, 0])) } + } + + @Test func hostileSizesDontTrap() throws { + let huge = try SampledSound(header: extended(channels: 256, frames: .max, bits: 32, samples: [0, 1, 0, 0])) + #expect(huge.data.count == 4) + #expect(try huge.pcm16() == [1]) + let packets = try SampledSound(header: compressed(channels: 256, packets: .max, type: "ima4", samples: [])) + #expect(packets.data.isEmpty) + } + + // MARK: Sources of bytes + + @Test func resourcesFromAnyBytes() throws { + let bytes = format1(standard([128, 129])) + #expect(try SampledSound(snd: Data(bytes)).count == 2) + #expect(try SampledSound(snd: Data([7, 7, 7] + bytes)[3...]).count == 2) + #expect(try bytes.withUnsafeBytes { try SampledSound(snd: $0) }.count == 2) + #expect(try SoundResource.headerOffset(in: Data([1, 2] + bytes)[2...]) == 20) + } + + @Test func samplesAreASliceOfTheResource() throws { + let resource = Data(format1(standard([128, 129, 130]))) + let sound = try SampledSound(snd: resource) + // After the 20 bytes and the 22 of header; not copied. + #expect(sound.data.startIndex == 42) + #expect(Array(sound.data) == [128, 129, 130]) + } + + // MARK: Writing + + @Test func writtenResourcesReadBack() throws { + let original = SampledSound(encoding: .unsigned8, sampleRate: 22254.545, channels: 1, bitsPerSample: 8, count: 4, + data: [128, 255, 0, 128], baseNote: 64, loop: 1 ..< 3) + let bytes = original.sndResource + #expect(try SoundResource.headerOffset(in: bytes) == 20) + #expect(bytes.count == 20 + 22 + 4) + let again = try SampledSound(snd: bytes) + #expect(again.encoding == .unsigned8 && again.count == 4 && again.baseNote == 64 && again.loop == 1 ..< 3) + #expect(abs(again.sampleRate - original.sampleRate) < 0.001) + #expect(Array(again.data) == [128, 255, 0, 128]) + } + + @Test func writtenStereoSixteenBitUsesTheExtendedHeader() throws { + let original = SampledSound(encoding: .signedBigEndian, sampleRate: 44100, channels: 2, bitsPerSample: 16, count: 2, + data: [0, 1, 0, 2, 0, 3, 0, 4]) + let bytes = original.sndResource + #expect(bytes.count == 20 + 64 + 8) + // initStereo in the init bits, then the extended encoding in the header. + #expect(Array(bytes[6 ..< 10]) == [0, 0, 0, 0xC0]) + #expect(bytes[20 + 20] == 0xFF) + let again = try SampledSound(snd: bytes) + #expect(again.encoding == .signedBigEndian && again.channels == 2 && again.bitsPerSample == 16 && again.sampleRate == 44100) + #expect(try again.pcm16() == [1, 2, 3, 4]) + } + + @Test func writtenCompressedSoundsUseTheCompressedHeader() throws { + for encoding in [SoundEncoding.ulaw, .alaw, .mace3, .mace6] { + let original = SampledSound(encoding: encoding, sampleRate: 11025, channels: 1, bitsPerSample: 16, count: 3, data: [1, 2, 3, 4, 5, 6]) + let bytes = original.sndResource + #expect(bytes[20 + 20] == 0xFE) + let again = try SampledSound(snd: bytes) + #expect(again.encoding == encoding && again.count == 3) + } + // MACE says which in the resource's init bits. + let mace6 = SampledSound(encoding: .mace6, sampleRate: 11025, channels: 1, bitsPerSample: 16, count: 1, data: [1]) + #expect(Array(mace6.sndResource[6 ..< 10]) == [0, 0, 0x04, 0x80]) + } + + // MARK: Damage + + @Test func truncatedResourcesNeverTrap() { + let resources = [ + format1(standard([128, 129, 130])), + format1(extended(channels: 2, frames: 2, bits: 16, samples: [0, 1, 0, 2, 0, 3, 0, 4])), + format2(compressed(channels: 1, packets: 2, type: "ulaw", samples: [1, 2])), + ] + for resource in resources { + for length in 0 ... resource.count { + if let sound = try? SampledSound(snd: resource.prefix(length)) { _ = try? sound.pcm16() } + _ = try? SoundResource.headerOffset(in: resource.prefix(length)) + } + } + } + + @Test func damagedBytesNeverTrap() { + var generator = QuickDrawRandom(seed: 7) + let original = format1(extended(channels: 2, frames: 2, bits: 16, samples: [0, 1, 0, 2, 0, 3, 0, 4])) + for _ in 0 ..< 400 { + var bytes = original + for _ in 0 ..< 4 { bytes[Int(UInt16(bitPattern: generator.next())) % bytes.count] = UInt8(truncatingIfNeeded: generator.next()) } + if let sound = try? SampledSound(snd: bytes) { _ = try? sound.pcm16() } + } + } +}