bugfixes, better MusicXML support and 1.1.0

This commit is contained in:
2026-06-10 08:41:07 -07:00
parent 6d3a0930a1
commit f59fd3b55a
228 changed files with 32271 additions and 2586 deletions
@@ -82,7 +82,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
/// Required override. Construct and return the synthesizer instance that this
/// AU should host.
///
/// `@MainActor` (Phase 201): the override constructs a `@MainActor` `SynthesizerBase`
/// `@MainActor`: the override constructs a `@MainActor` `SynthesizerBase`
/// subclass, so the factory must be main-actor-isolated for a consumer building under
/// the MainActor-default mode to override it with no concurrency annotations — the same
/// rationale as `SynthesizerBase.build()`. Invoked from `init` on the host's main thread.
@@ -443,7 +443,7 @@ open class LyrebirdAudioUnit: AUAudioUnit {
newEngine.auOutputBusOffsets = _outputBusOffsets
newEngine.auInputBusOffsets = _inputBusOffsets
try newEngine.start()
// `engine.add` is `@MainActor` (Phase 201). `allocateRenderResources()` overrides
// `engine.add` is `@MainActor`. `allocateRenderResources()` overrides
// `AUAudioUnit`'s nonisolated declaration, so this method cannot itself be
// `@MainActor`. AU hosts usually call render-resource allocation on the main thread,
// but the contract does not guarantee it — the bridge runs the add inline when on
@@ -9,7 +9,7 @@ import Foundation
/// Run a `@MainActor` node-tree mutation from a language-side dispatch adapter that may
/// execute either on the main thread or inline on a background NRT driver thread.
///
/// Phase 201 made the engine's add / schedule path and `Synthesizer.build`/`release`/`free`
/// The engine's add / schedule path and `Synthesizer.build`/`release`/`free` are
/// `@MainActor`. Most language-side adapters dispatch those mutations through
/// `DispatchQueue.main.async`, so they already run on main. Two adapters can run a mutation
/// **inline on the calling thread**:
@@ -1745,7 +1745,7 @@ public final class SynthesisEngine {
/// All allocation and `build()`/`rebuildGraph()` happen here on the calling thread;
/// the RT thread never allocates in `applyEvent`.
/// `@MainActor`: invokes `build()` / `rebuildGraph()` (the `@MainActor` language-side
/// add surface — Phase 201). The node-tree add path runs on the main thread by
/// add surface). The node-tree add path runs on the main thread by
/// contract (it also touches `nodeTreeMirror`, observed by SwiftUI).
@MainActor private func prepareNode(_ synth: any Synthesizer) -> PreparedNode {
if let base: SynthesizerBase = synth as? SynthesizerBase {
+2 -2
View File
@@ -57,7 +57,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
let args: SynthArgs = SynthArgs(engine, synth)
_dispatch {
// `_dispatch` runs this on main (default `DispatchQueue.main.async`) or inline on
// the NRT driver thread. `engine.add` is `@MainActor` (Phase 201); the bridge runs
// the NRT driver thread. `engine.add` is `@MainActor`; the bridge runs
// it inline when already on main and hops synchronously otherwise — never traps.
lyrebirdRunMainActorMutation {
do { try args.engine.add(args.synth) }
@@ -133,7 +133,7 @@ public struct LyrebirdMessageContext: @unchecked Sendable {
// but a warning posts to LyrebirdMessageCenter so debug builds get
// visibility into typo'd OSC / MIDI param names that would
// otherwise route silently to nowhere.
// `updateParameter` is `@MainActor` (Phase 201). `_dispatch` runs this on main
// `updateParameter` is `@MainActor`. `_dispatch` runs this on main
// (default) or inline on the NRT driver — the bridge runs inline on main and hops
// synchronously off-main, never trapping.
lyrebirdRunMainActorMutation {
@@ -522,3 +522,8 @@ extension ConvolutionReverb.Audio {
/// Right output channel (channel 1). Available only when IR has 2+ channels.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.
@@ -284,3 +284,8 @@ extension FreeVerb.Audio {
/// Right output channel (channel 1). Equivalent to `self[1]`.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.
@@ -538,3 +538,8 @@ extension GVerb.Audio {
/// Right output channel (channel 1). Equivalent to `self[1]`.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.
@@ -704,3 +704,8 @@ extension PlateReverb.Audio {
/// Right output channel (channel 1). Equivalent to `self[1]`.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.
@@ -404,3 +404,8 @@ extension SpringReverb.Audio {
/// Right output channel (channel 1). Only valid when `stereo: true`.
public var right: ChannelSelect.Audio { self[1] }
}
// MARK: - GeneratorEnum
// `GeneratorEnum` conformance is intentionally omitted — this is an Audio-only
// generator with no paired `Control` variant.
@@ -150,6 +150,10 @@ inside the range. In that case `self` is returned unchanged:
`self` is also returned unchanged when `modulo <= 0` or `high < low`.
RT-safe (pure scalar arithmetic, `O(1)`).
> Tip: ``Pitch/mapIntoRange(low:high:)`` is the spelling-aware counterpart for
> the Score theory layer — it folds a `Pitch` into a `[low, high]` register by
> whole octaves while preserving the note name (`B♭` stays `B♭`, never `A♯`).
---
## Tempo and Time
@@ -36,7 +36,7 @@ Every `Pattern<T>` variant is constructed via a static factory method on `Patter
| Factory | Behaviour |
|---|---|
| ``Pattern/sequence(_:repeats:)`` | Cycle through array `repeats` times. `-1` infinite. |
| ``Pattern/sequence(_:repeats:offset:)`` | Cycle through array `repeats` times. `-1` infinite. `offset` shifts only the first pass — opens at `values[offset]` (wraps modulo count), runs to the array end, then later cycles run full from index 0. |
| ``Pattern/shuffle(_:repeats:seed:)`` | Fisher-Yates permute once at init; cycle. Same permutation replays on reset. SC `Pshuf`. |
| ``Pattern/nonRepeatingRandom(_:repeats:seed:)`` | Random pick avoiding same *index* as previous. Index-vs-value caveat for duplicate-value pools. SC `Pxrand`. |
| ``Pattern/weightedRandom(_:weights:repeats:seed:)`` | Pick proportional to weight. Init preconditions: equal count, finite non-negative weights, positive sum. SC `Pwrand`. |
File diff suppressed because it is too large Load Diff
+2 -2
View File
@@ -32,7 +32,7 @@ Optional GUI module.
import LyrebirdUI
```
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode (Phase 202).
Provides: `LyrebirdWindow` (AppKit/SwiftUI host), `@SynthParam` property wrapper, and pre-built slider/knob views. Builds under Swift 6 language mode.
**Rule:** never import `LyrebirdUI` in `Lyrebird` — GUI code must stay in this module only.
@@ -49,7 +49,7 @@ lyrebird export MySynth
lyrebird repl
```
Provides an interactive `lyrebird>` shell with history and tab completion. Builds under Swift 6 language mode (Phase 202).
Provides an interactive `lyrebird>` shell with history and tab completion. Builds under Swift 6 language mode.
See <doc:CLIGuide> for a full walkthrough.
+2 -2
View File
@@ -109,7 +109,7 @@ public final class Group: Synthesizer {
///
/// Language-side only — do not call from the RT thread.
///
/// `@MainActor` (Phase 201): the child cascade calls the `@MainActor`
/// `@MainActor`: the child cascade calls the `@MainActor`
/// `child.release`/`child.free`. The self-free poll timer — which runs its handler on a
/// utility queue and therefore must NOT be main-actor-isolated — is installed by the
/// `nonisolated` helper `_startSelfFreeTimer(engine:)` so the handler does not inherit
@@ -161,7 +161,7 @@ public final class Group: Synthesizer {
/// count reaches zero.
///
/// `nonisolated` so the `setEventHandler` closure does NOT inherit `release`'s
/// `@MainActor` isolation (Phase 201) — a main-actor-isolated handler would trap
/// `@MainActor` isolation — a main-actor-isolated handler would trap
/// (`dispatch_assert_queue_fail`) when the timer fires on the utility queue. The handler
/// touches only the atomic count off-main and hops to main (via the `@unchecked Sendable`
/// ``GroupFreeArgs``) for the actual `free`.
@@ -4,24 +4,37 @@
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Engine backing ``Pattern/sequence(_:repeats:)``.
/// Engine backing ``Pattern/sequence(_:repeats:offset:)``.
///
/// Cycles through `values` in order. Each full pass increments the cycle counter.
/// `repeats` full cycles exhaust the source; `-1` is infinite.
///
/// `offset` shifts only the *first* pass: emission starts at `values[offset]`
/// and runs to the end of the array (a short opening pass), after which every
/// later cycle runs the full array from index `0`. `reset()` returns to the
/// offset start.
internal final class SequencePatternEngine<T>: _PatternEngine {
internal typealias Element = T
private let _values: [T]
private let _repeats: Int
private var _index: Int = 0
private let _offset: Int
private var _index: Int
private var _cycleCount: Int = 0
internal init(
values: [T],
repeats: Int
repeats: Int,
offset: Int = 0
) {
_values = values
_repeats = repeats
// Normalise the offset into [0, count) so out-of-range / negative
// offsets wrap rather than trap. Empty arrays pin to 0 (next() guards).
let count: Int = values.count
let normalized: Int = count > 0 ? ((offset % count) + count) % count : 0
_offset = normalized
_index = normalized
}
internal var isExhausted: Bool {
@@ -40,7 +53,7 @@ internal final class SequencePatternEngine<T>: _PatternEngine {
}
internal func reset() {
_index = 0
_index = _offset
_cycleCount = 0
}
}
@@ -14,11 +14,28 @@ public extension Pattern {
/// increments the cycle counter. `repeats` full cycles exhaust the source;
/// `-1` is infinite.
///
/// `offset` shifts only the *first* pass: emission starts at
/// `values[offset]` and runs to the end of the array (a short opening
/// pass), after which every later cycle runs the full array from index `0`.
/// `Pattern.sequence([.eighth, .eighth, .quarter], offset: 1)` opens with
/// `[.eighth, .quarter]` then loops the full list. The offset wraps
/// (modulo `values.count`) so out-of-range or negative values are legal.
///
/// - Parameters:
/// - values: Elements to cycle through. Copied at init time.
/// - repeats: Number of full cycles before exhaustion. `-1` = infinite.
static func sequence(_ values: [T], repeats: Int = -1) -> Pattern<T> {
Pattern(engine: SequencePatternEngine(values: values, repeats: repeats))
/// - offset: Starting index for the first pass only. Wraps modulo
/// `values.count`. Defaults to `0`.
static func sequence(
_ values: [T],
repeats: Int = -1,
offset: Int = 0
) -> Pattern<T> {
Pattern(engine: SequencePatternEngine(
values: values,
repeats: repeats,
offset: offset
))
}
/// Permutes `values` once at init via Fisher-Yates, then cycles through
@@ -62,7 +62,7 @@ final class ProcessRouteSynth: SynthesizerBase {
///
/// `nonisolated(unsafe)`: assigned in `build()` on main; the `LyrebirdProcess` watcher
/// reads `envGen?.needsFree` (an atomic flag) from a utility-queue timer. Effectively
/// immutable after `build()`; cross-thread read is safe (Phase 201).
/// immutable after `build()`; cross-thread read is safe.
nonisolated(unsafe) private(set) var envGen: EnvelopeGen.Audio?
init(
@@ -180,7 +180,7 @@ final class ProcessRouteSynth: SynthesizerBase {
/// `bus` (or to any other downstream consumer) if master amp control is wanted.
/// - target: Where to insert this process's group in the node tree.
/// - body: `async` closure invoked with a ``LyrebirdProcessContext``. Runs on the
/// `@MainActor` (Phase 201) so it can construct `@MainActor` `SynthesizerBase`
/// `@MainActor` so it can construct `@MainActor` `SynthesizerBase`
/// subclasses and call `ctx.add(_:)` directly — no `await MainActor.run { … }`
/// wrapping needed. `await ctx.wait(_:)` suspends without blocking the main thread.
/// - onRelease: Optional callback invoked when ``release(reltime:)`` is
@@ -782,7 +782,7 @@ public final class LyrebirdProcess: @unchecked Sendable {
/// from whichever thread drops the final process reference.
deinit {
guard let engine: SynthesisEngine = _engine else { return }
// `Group.free` is `@MainActor` (Phase 201) — it touches `nodeTreeMirror`. deinit is
// `Group.free` is `@MainActor` — it touches `nodeTreeMirror`. deinit is
// nonisolated and may run on any thread, so hop the group-free to main. The bus
// release + DiskOut close are nonisolated and run inline. Capture locals (not self,
// which is mid-deinit) for the async closure.
@@ -20,7 +20,7 @@ public protocol LyrebirdProcessFactory: Sendable {
/// Each call should return an independent process — callers may
/// invoke this repeatedly to spawn distinct concurrent processes.
///
/// `@MainActor` (Phase 201): conformers typically construct `@MainActor`
/// `@MainActor`: conformers typically construct `@MainActor`
/// `SynthesizerBase` subclasses here, so the factory method is main-actor-isolated.
/// The protocol stays `Sendable` (factories are stored / passed across actors); only
/// the build step is pinned to main.
+6 -6
View File
@@ -40,23 +40,23 @@ public enum Articulation: Hashable, Sendable {
// MARK: - Performance scaling constants
/// Duration multiplier for ``staccato``.
public static let staccatoDurationScale: Double = 0.5
static let staccatoDurationScale: Double = 0.5
/// Duration multiplier for ``staccatissimo``.
public static let staccatissimoDurationScale: Double = 0.25
static let staccatissimoDurationScale: Double = 0.25
/// Duration multiplier for ``legato`` — slight overlap into the next note.
/// Players that don't tolerate overlap should clamp to `1.0`.
public static let legatoDurationScale: Double = 1.05
static let legatoDurationScale: Double = 1.05
/// Duration multiplier for ``marcato``.
public static let marcatoDurationScale: Double = 0.85
static let marcatoDurationScale: Double = 0.85
/// Velocity bonus added by ``accent``.
public static let accentVelocityBonus: Double = 0.15
static let accentVelocityBonus: Double = 0.15
/// Velocity bonus added by ``marcato``.
public static let marcatoVelocityBonus: Double = 0.25
static let marcatoVelocityBonus: Double = 0.25
// MARK: - Performance scaling
+75
View File
@@ -0,0 +1,75 @@
// BarlineStyle.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Visual style of a measure's **right** barline, independent of repeat
/// structure.
///
/// Used to mark a section boundary (`.double`), the end of a movement or piece
/// (`.final`), or any of the other notation-standard barline glyphs. Set per
/// section via ``Section(_:meterMap:keySignature:tempoChanges:repeats:endBarline:parts:)``
/// (recorded at the section's last global measure), or directly on a flat score
/// via ``Score/measureBarlines``.
///
/// ## Precedence vs repeats
///
/// When a measure also carries a **backward repeat** (`:|`), the repeat's
/// `light-heavy` barline wins and the section style is suppressed — a repeat
/// barline is already a heavy barline and stacking a second bar-style produces
/// invalid notation. A `BarlineStyle` therefore only renders when no
/// backward-repeat / ending-stop barline already occupies the same right barline.
///
/// ## Round-trip
///
/// Like rehearsal marks, barline styles are **emit-only** — they are written to
/// MusicXML but are not reconstructed when a score is decoded from MusicXML.
///
/// Each case maps to a MusicXML 4.0 `<bar-style>` value via ``musicXMLBarStyle``.
public enum BarlineStyle: String, Sendable, Equatable, CaseIterable {
/// A normal thin barline (`<bar-style>regular</bar-style>`). Rarely needed
/// explicitly — it is the default barline drawn between measures.
case regular
/// A thin double barline (`light-light`). The conventional section divider.
case double
/// A thin-then-thick final barline (`light-heavy`). Marks the end of a
/// movement or the whole piece.
case final
/// A single thick barline (`heavy`).
case heavy
/// A dashed barline (`dashed`).
case dashed
/// A dotted barline (`dotted`).
case dotted
/// A short barline crossing only the middle staff lines (`tick`).
case tick
/// A short barline crossing the middle two staff spaces (`short`).
case short
/// An invisible (suppressed) barline (`none`).
case invisible
/// The MusicXML 4.0 `<bar-style>` token for this style.
public var musicXMLBarStyle: String {
switch self {
case .regular: return "regular"
case .double: return "light-light"
case .final: return "light-heavy"
case .heavy: return "heavy"
case .dashed: return "dashed"
case .dotted: return "dotted"
case .tick: return "tick"
case .short: return "short"
case .invisible: return "none"
}
}
}
+153
View File
@@ -0,0 +1,153 @@
// BeatPosition.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A musician-friendly position on a part timeline, resolved against a
/// ``MeterMap`` to an absolute quarter-note beat (the engine's one true unit,
/// see ``ScoreEvent/beat``).
///
/// **`beat` means the felt beat you conduct** — the felt beat defined by the
/// signature's ``TimeSignature/beatGrouping``. This keeps `beat` consistent
/// across meters: beat 1 is always the downbeat, beat 2 the next conducted beat.
/// In `4/4` the beat is the quarter; in compound `6/8` `[3,3]` the beat is the
/// dotted-quarter (two beats per bar); in additive `3+3+2` the three beats are
/// dotted-quarter, dotted-quarter, quarter. For the finer notated note-value
/// (the eighth in `6/8`) use `division`, the less-common granular addressing.
///
/// Addressing surfaces (all 1-based except `.quarters`):
///
/// - ``quarters(_:)-(Double)`` / ``quarters(_:)-(Fraction)`` — absolute 0-based
/// quarter beats, meter-free. `Fraction` form is exact (triplet positions).
/// - ``beat(_:)`` — flat 1-based felt beat, counted continuously across bars
/// (constant initial meter, anacrusis-free). In `4/4`, beat 5 → quarter 4; in
/// `6/8`, beat 3 → quarter 3 (bar-2 downbeat). The `from((1.0,…),(5.0,…))`
/// reading.
/// - ``bar(_:beat:)`` — 1-based bar + 1-based felt beat (via `beatGrouping`),
/// fully meter-aware (per-bar signature + anacrusis). Fractional beats
/// interpolate within the beat.
/// - ``bar(_:division:)`` — 1-based bar + 1-based denominator-note division. In
/// `6/8`, `bar 1, division 4` is the 4th eighth. The granular escape hatch.
///
/// Anacrusis (``MeterMap/anacrusis``): for `.bar(...)`, quarter `0` is the pickup
/// start, bar `1` is the first full measure (so `.bar(1, beat: 1)` resolves to
/// `anacrusis`); address pickup beats with `bar: 0`. Flat `.beat` ignores the
/// anacrusis.
public struct BeatPosition: Sendable, Hashable {
enum Kind: Sendable, Hashable {
case quarters(Fraction)
case beat(Fraction)
case barBeat(bar: Int, beat: Fraction)
case barDivision(bar: Int, division: Fraction)
}
let kind: Kind
// MARK: - Factories
/// Absolute 0-based quarter beats (meter-free). Quantized to
/// ``Fraction/beatApproxDenominator``.
public static func quarters(_ q: Double) -> BeatPosition {
BeatPosition(kind: .quarters(fractionFromBeats(q)))
}
/// Absolute 0-based quarter beats as an exact ``Fraction`` (meter-free).
/// Use for triplet / rational positions that must not round.
public static func quarters(_ q: Fraction) -> BeatPosition {
BeatPosition(kind: .quarters(q))
}
/// Flat 1-based felt beat, counted continuously across bars (constant initial
/// meter, anacrusis-free). `beat(1)` is the start; `beat(5)` in `4/4` is
/// quarter `4`; `beat(3)` in `6/8` is quarter `3`.
public static func beat(_ b: Double) -> BeatPosition {
BeatPosition(kind: .beat(fractionFromBeats(b)))
}
/// 1-based bar + 1-based felt beat (via ``TimeSignature/beatGrouping``),
/// fully meter-aware. `bar: 0` addresses the pickup. Fractional beats
/// interpolate within the beat; the integer part must be in
/// `[1, beatsPerBar]` (out-of-range traps).
public static func bar(_ bar: Int, beat: Double) -> BeatPosition {
BeatPosition(kind: .barBeat(bar: bar, beat: fractionFromBeats(beat)))
}
/// 1-based bar + 1-based denominator-note division (the granular notated
/// note-value). In `6/8`, `division 4` is the 4th eighth. `bar: 0` addresses
/// the pickup.
public static func bar(_ bar: Int, division: Double) -> BeatPosition {
BeatPosition(kind: .barDivision(bar: bar, division: fractionFromBeats(division)))
}
// MARK: - Resolution
/// Resolve to an absolute quarter-note beat against a meter map.
///
/// - Parameter meterMap: The governing meter map (provides per-bar signatures,
/// bar offsets, and the anacrusis).
/// - Returns: Absolute quarter beats (may be negative for malformed input —
/// callers should reject negatives).
public func resolve(in meterMap: MeterMap) -> Fraction {
let oneBeat: Fraction = .one
switch kind {
case .quarters(let q):
return q
case .beat(let b):
// Flat felt beat: wrap continuously across bars of the initial
// signature, anacrusis-free.
let ts: TimeSignature = meterMap.initial
let beatsPerBar: Int = ts.beatsPerBar
let bValue: Double = b.double
let integerBeat: Int = Int(bValue.rounded(.down))
precondition(integerBeat >= 1, "BeatPosition: beat must be >= 1, got \(bValue)")
let barIndex: Int = (integerBeat - 1) / beatsPerBar
let beatInBar: Int = (integerBeat - 1) % beatsPerBar
let frac: Double = bValue - Double(integerBeat)
let barStart: Fraction = Fraction(barIndex, 1) * ts.measureQuarters
let beatArg: Fraction = fractionFromBeats(Double(beatInBar + 1) + frac)
return barStart + BeatPosition.beatOffset(beatArg, in: ts)
case .barBeat(let bar, let beat):
let ts: TimeSignature = meterMap.timeSignature(atBar: bar)
return meterMap.barStartQuarters(bar) + BeatPosition.beatOffset(beat, in: ts)
case .barDivision(let bar, let division):
let ts: TimeSignature = meterMap.timeSignature(atBar: bar)
let unit: Fraction = ts.divisionQuarters
return meterMap.barStartQuarters(bar) + (division - oneBeat) * unit
}
}
/// Quarter-beat offset of a (possibly fractional, 1-based) felt beat within a
/// bar of the given signature.
///
/// - Precondition: the integer part of `beat` is in `[1, beatsPerBar]`. A
/// beat outside that range (e.g. `beat 3` in a 2-beat `6/8`, or `beat 0`)
/// is a placement error and traps rather than silently snapping to a wrong
/// beat. A fractional beat interpolates within its felt beat; `N.f` for the
/// last beat stays inside the bar.
private static func beatOffset(
_ beat: Fraction,
in ts: TimeSignature
) -> Fraction {
let beatValue: Double = beat.double
let floored: Int = Int(beatValue.rounded(.down))
let lastBeatIndex: Int = ts.beatsPerBar
precondition(
floored >= 1 && floored <= lastBeatIndex,
"BeatPosition: beat \(beatValue) out of range [1, \(lastBeatIndex)] for \(ts.numerator)/\(ts.denominator)"
)
let onset: Fraction = ts.beatOnsetsQuarters[floored - 1]
let frac: Double = beatValue - Double(floored)
if frac <= 0 {
return onset
}
// Interpolate within the felt beat by its quarter length.
return onset + fractionFromBeats(frac) * ts.beatLengthsQuarters[floored - 1]
}
}
+112
View File
@@ -0,0 +1,112 @@
// Clef.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// The clef assigned to a ``ScorePart`` for MusicXML encoding and display.
///
/// ### Cases
///
/// - ``treble`` — G clef on line 2. Standard treble staff. Use for soprano, alto,
/// violin, flute, piano right hand, etc.
/// - ``bass`` — F clef on line 4. Standard bass staff. Use for bass, cello, tuba,
/// piano left hand (low range), etc.
/// - ``alto`` — C clef on line 3. Alto clef. Use for viola.
/// - ``tenor`` — C clef on line 4. Tenor clef. Use for cello (upper register),
/// trombone (upper register), bassoon (upper register).
/// - ``treble8vb`` — G clef on line 2 with `clef-octave-change -1`. Octave-transposing
/// treble clef sounding an octave lower than written. Use for tenor voice, guitar.
/// - ``percussion`` — Percussion clef (no line). Use for unpitched percussion parts.
/// - ``auto`` — Infer the appropriate clef from the part's pitch content at encode time.
/// Resolves to `.treble` or `.bass` based on the median MIDI pitch of the part's
/// pitched events (median < ``autoBassThresholdMidi`` → `.bass`, else → `.treble`).
/// `.auto` is the default for the ``Part(_:channel:clef:elements:)`` DSL constructor.
public enum Clef: Sendable, Hashable {
/// G clef, line 2.
case treble
/// F clef, line 4.
case bass
/// C clef, line 3 (viola).
case alto
/// C clef, line 4 (tenor voice / cello upper register).
case tenor
/// G clef, line 2, `clef-octave-change -1` (tenor voice, guitar).
case treble8vb
/// Percussion clef (no line). For unpitched percussion parts.
case percussion
/// Infer treble or bass from the part's pitch range at encode time.
///
/// At ``Score/toMusicXMLString(divisions:)`` time the median MIDI pitch of the
/// part's non-rest pitched notes is computed. If the median is below
/// ``autoBassThresholdMidi`` (57 — A3), `.bass` is chosen; otherwise `.treble`.
/// If the part has no pitched notes, `.treble` is chosen.
case auto
// MARK: - Auto-inference threshold
/// MIDI note number (A3 = 57) below which the `.auto` case resolves to `.bass`.
///
/// The value 57 (A3) sits midway between the bass-clef sweet spot (D2–E4) and
/// the treble-clef sweet spot (F3–A5); it maps to the lowest note of an alto
/// voice and is a natural dividing point.
public static let autoBassThresholdMidi: Int = 57
// MARK: - MusicXML mapping
/// The MusicXML `<clef>` children for this clef case.
///
/// Returns `(sign:, line:, octaveChange:)`.
/// - `sign`: MusicXML `<sign>` text (`"G"`, `"F"`, `"C"`, `"percussion"`).
/// - `line`: MusicXML `<line>` integer, or `nil` when the element must be omitted
/// (e.g. percussion).
/// - `octaveChange`: MusicXML `<clef-octave-change>` integer, or `nil` when
/// the element must be omitted.
///
/// - Precondition: Do not call on `.auto`; resolve it first via
/// ``inferred(forMedianMidi:)``.
public var musicXMLClef: (sign: String, line: Int?, octaveChange: Int?) {
switch self {
case .treble:
return (sign: "G", line: 2, octaveChange: nil)
case .bass:
return (sign: "F", line: 4, octaveChange: nil)
case .alto:
return (sign: "C", line: 3, octaveChange: nil)
case .tenor:
return (sign: "C", line: 4, octaveChange: nil)
case .treble8vb:
return (sign: "G", line: 2, octaveChange: -1)
case .percussion:
return (sign: "percussion", line: nil, octaveChange: nil)
case .auto:
// Defensive fallback — callers should resolve .auto before calling
// this property. Return treble so output is always valid XML.
return (sign: "G", line: 2, octaveChange: nil)
}
}
// MARK: - Auto-inference
/// Return the appropriate concrete clef for a part given its median MIDI pitch.
///
/// - Parameter median: The median MIDI note number of the part's non-rest pitched
/// events, or `nil` / absent when the part contains no pitched events.
/// - Values below ``autoBassThresholdMidi`` (57) return `.bass`.
/// - Values at or above the threshold return `.treble`.
/// - `nil` (empty / rest-only part) returns `.treble`.
/// - Returns: `.treble` or `.bass` — never `.auto` or any other case.
public static func inferred(forMedianMidi median: Int?) -> Clef {
guard let m: Int = median else { return .treble }
return m < Clef.autoBassThresholdMidi ? .bass : .treble
}
}
+51 -2
View File
@@ -21,6 +21,14 @@ public enum Dynamic: Hashable, Sendable {
case ff
case fff
/// No sound — velocity zero, printed as `n` in MusicXML.
///
/// Use `.niente` at the start or end of a crescendo/diminuendo (al niente /
/// dal niente) or as the initial/final point of a ``dynamicCurve:`` to indicate
/// silence at that position. The `<n/>` MusicXML child element is the
/// standard MusicXML 4.0 representation.
case niente
/// Escape hatch — caller-supplied normalized `[0, 1]` velocity. The value
/// is clamped to `[0, 1]` when ``velocity`` is read.
case raw(Double)
@@ -37,12 +45,12 @@ public enum Dynamic: Hashable, Sendable {
public static let fffVelocity: Double = 1.00
/// Maximum MIDI velocity, used by ``midiVelocity``.
public static let midiMaxVelocity: Double = Double(Pitch.maxMidiNote)
static let midiMaxVelocity: Double = Double(Pitch.maxMidiNote)
// MARK: - Conversion
/// Normalized velocity in `[0, 1]`. `mf` anchored at `0.6` and `f` at
/// `0.85`. ``raw(_:)`` values are clamped to `[0, 1]`.
/// `0.85`. ``raw(_:)`` values are clamped to `[0, 1]`. ``niente`` returns `0.0`.
public var velocity: Double {
switch self {
case .ppp: return Dynamic.pppVelocity
@@ -53,6 +61,7 @@ public enum Dynamic: Hashable, Sendable {
case .f: return Dynamic.fVelocity
case .ff: return Dynamic.ffVelocity
case .fff: return Dynamic.fffVelocity
case .niente: return 0.0
case .raw(let v): return max(0.0, min(1.0, v))
}
}
@@ -63,4 +72,44 @@ public enum Dynamic: Hashable, Sendable {
UInt8(min(Dynamic.midiMaxVelocity,
max(0.0, (velocity * Dynamic.midiMaxVelocity).rounded())))
}
// MARK: - MusicXML mapping
/// The standard MusicXML `<dynamics>` child element name for this dynamic.
///
/// Named cases map to the nine standard MusicXML element names (`"ppp"` …
/// `"fff"` plus `"n"` for ``niente``). ``raw(_:)`` returns `nil` — the
/// caller must use `<other-dynamics>` with the raw value text.
public var musicXMLDynamic: String? {
switch self {
case .ppp: return "ppp"
case .pp: return "pp"
case .p: return "p"
case .mp: return "mp"
case .mf: return "mf"
case .f: return "f"
case .ff: return "ff"
case .fff: return "fff"
case .niente: return "n"
case .raw: return nil
}
}
/// Inverse of ``musicXMLDynamic``: map a standard MusicXML dynamics element
/// name to the corresponding ``Dynamic`` case. Returns `nil` for any name
/// that is not one of the nine standard names.
public static func fromMusicXMLName(_ name: String) -> Dynamic? {
switch name {
case "ppp": return .ppp
case "pp": return .pp
case "p": return .p
case "mp": return .mp
case "mf": return .mf
case "f": return .f
case "ff": return .ff
case "fff": return .fff
case "n": return .niente
default: return nil
}
}
}
+49
View File
@@ -0,0 +1,49 @@
// Ending.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A volta (1st/2nd/…) ending bracket that spans one or more measures.
///
/// Endings are score-level structural annotations used with a ``RepeatStructure``
/// to describe which measures belong to each volta bracket. They are
/// **notation-only** — ``ScorePart/flatten()`` is unaffected and does not
/// unfold repeats for playback (future work).
///
/// - Parameters:
/// - number: Volta number, starting at 1. A 1st ending uses `number: 1`, a
/// 2nd ending uses `number: 2`, and so on.
/// - startMeasure: 1-based measure number where the ending bracket begins (inclusive).
/// - stopMeasure: 1-based measure number where the ending bracket ends (inclusive).
/// Must be `>= startMeasure`.
public struct Ending: Sendable, Hashable {
/// Volta number (1, 2, …). Must be >= 1.
public let number: Int
/// 1-based measure number where the ending bracket starts (inclusive).
public let startMeasure: Int
/// 1-based measure number where the ending bracket stops (inclusive).
public let stopMeasure: Int
/// Create a volta ending bracket.
///
/// - Parameters:
/// - number: Volta number, starting at 1. Precondition: `>= 1`.
/// - startMeasure: 1-based measure number where the bracket begins. Precondition: `>= 1`.
/// - stopMeasure: 1-based measure number where the bracket ends (inclusive).
/// Precondition: `>= startMeasure`.
public init(number: Int, startMeasure: Int, stopMeasure: Int) {
precondition(number >= 1, "Ending: number must be >= 1, got \(number)")
precondition(startMeasure >= 1, "Ending: startMeasure must be >= 1, got \(startMeasure)")
precondition(
stopMeasure >= startMeasure,
"Ending: stopMeasure (\(stopMeasure)) must be >= startMeasure (\(startMeasure))"
)
self.number = number
self.startMeasure = startMeasure
self.stopMeasure = stopMeasure
}
}
+58
View File
@@ -0,0 +1,58 @@
// FermataShape.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// The shape of a fermata symbol, corresponding to MusicXML 4.0 fermata shape values.
///
/// Use as the associated value of ``NotationMark/fermata(_:)``.
///
/// Common shorthands:
/// - "Long fermata" = `.square`
/// - "Very long / longa fermata" = `.doubleSquare`
///
/// > Note: ``NotationMark`` is emit-only — ``Score/fromMusicXML(data:)`` does not
/// > parse fermata shapes back into `NotationMark` values.
public enum FermataShape: Hashable, Sendable {
/// Standard curved fermata (the most common kind). MusicXML `<fermata/>`.
case normal
/// Pointed / angled fermata. MusicXML body text: `angled`.
case angled
/// Square fermata — the conventional "long fermata". MusicXML body text: `square`.
case square
/// Double angled fermata. MusicXML body text: `double-angled`.
case doubleAngled
/// Double square fermata — the conventional "very long / longa fermata".
/// MusicXML body text: `double-square`.
case doubleSquare
/// Double dot fermata. MusicXML body text: `double-dot`.
case doubleDot
/// Half-curve fermata. MusicXML body text: `half-curve`.
case halfCurve
/// Curlew fermata. MusicXML body text: `curlew`.
case curlew
/// The MusicXML body text for shapes other than `.normal`.
/// Returns `nil` for `.normal` (which emits as self-closing `<fermata/>`).
var musicXMLBodyText: String? {
switch self {
case .normal: return nil
case .angled: return "angled"
case .square: return "square"
case .doubleAngled: return "double-angled"
case .doubleSquare: return "double-square"
case .doubleDot: return "double-dot"
case .halfCurve: return "half-curve"
case .curlew: return "curlew"
}
}
}
+19
View File
@@ -68,6 +68,13 @@ public struct Fraction: Hashable, Equatable, Sendable {
/// `1/1`.
public static let one: Fraction = Fraction(num: 1, den: 1)
/// Denominator used to quantize a `Double` beat value into an exact
/// ``Fraction`` (`2^20`). The single source of truth for the score system's
/// `.beats(Double)` → ``Fraction`` re-encoding — referenced by `ScorePart`,
/// the MusicXML parser, and the rest-fill helpers. Practical exact range
/// (paired with the ``<(_:_:)`` cross-product overflow note) is ~8 000 beats.
static let beatApproxDenominator: Int64 = 1 << 20
// MARK: - Arithmetic
/// `a/b + c/d = (ad + bc) / bd`, reduced.
@@ -109,6 +116,11 @@ public struct Fraction: Hashable, Equatable, Sendable {
lhs + Fraction(num: -rhs.num, den: rhs.den)
}
/// In-place subtraction.
public static func -= (lhs: inout Fraction, rhs: Fraction) {
lhs = lhs - rhs
}
// MARK: - Comparison
/// Compares cross-products of the two fractions in `Int64`.
@@ -156,3 +168,10 @@ public struct Fraction: Hashable, Equatable, Sendable {
// MARK: - Comparable conformance
extension Fraction: Comparable {}
// MARK: - AdditiveArithmetic conformance
/// `Fraction` is an exact additive-arithmetic type: it has `+`, `-`, `+=`, `-=`,
/// and ``zero``. The conformance lets generic algorithms (e.g. the score
/// rest-fill helper) operate uniformly over `Fraction` and `Double` cursors.
extension Fraction: AdditiveArithmetic {}
+85
View File
@@ -0,0 +1,85 @@
// Glissando.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A descriptor for a glissando or slide span between two notes.
///
/// `Glissando` is attached to a note via the ``Spanner/beginGlissando(_:)``
/// case on the START note of the span. The stop note carries
/// ``Spanner/endGlissando``.
///
/// ```swift
/// // Wavy glissando with default settings — G5 slides to C6:
/// Note(.g, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
/// Note(.c, 6, dur: .quarter, spanners: [.endGlissando])
///
/// // Measured slide with explicit text label:
/// Note(.c, 5, dur: .quarter,
/// spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .solid, text: "slide"))])
/// Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
/// ```
///
/// ## MusicXML output
///
/// On the start note, inside `<notations>`:
/// ```xml
/// <glissando type="start" line-type="wavy" number="1"/>
/// <!-- or, when text is present: -->
/// <glissando type="start" line-type="wavy" number="1">gliss.</glissando>
/// ```
///
/// On the stop note, inside `<notations>`:
/// ```xml
/// <glissando type="stop" number="1"/>
/// ```
///
/// `.slide` kind emits `<slide>` instead of `<glissando>`.
///
/// ## Decode note
///
/// `<glissando>` and `<slide>` elements from an imported MusicXML file are
/// **not** currently parsed back into ``Glissando`` spanners. This is an
/// emit-only feature.
public struct Glissando: Sendable, Hashable {
/// Whether to emit `<glissando>` (wavy/curved, unmeasured) or `<slide>`
/// (straight, measured portamento).
///
/// Defaults to `.glissando`.
public var kind: GlissandoKind
/// The visual line style for the glissando span.
///
/// Corresponds to the `line-type` attribute in MusicXML. Defaults to
/// `.wavy`, the conventional style for an unmeasured glissando.
public var lineType: GlissandoLineType
/// Optional text label emitted as element body text on the start note,
/// e.g. `"gliss."`.
///
/// When non-nil the start element is written in the non-self-closing form:
/// `<glissando …>gliss.</glissando>`. When `nil` the self-closing form is
/// used: `<glissando …/>`. Defaults to `nil`.
public var text: String?
/// Create a `Glissando` descriptor.
///
/// - Parameters:
/// - kind: ``GlissandoKind/glissando`` (wavy, unmeasured) or
/// ``GlissandoKind/slide`` (straight, measured). Defaults to
/// `.glissando`.
/// - lineType: Visual line style. Defaults to `.wavy`.
/// - text: Optional label emitted as element content on the start note
/// (e.g. `"gliss."`). Defaults to `nil`.
public init(
kind: GlissandoKind = .glissando,
lineType: GlissandoLineType = .wavy,
text: String? = nil
) {
self.kind = kind
self.lineType = lineType
self.text = text
}
}
@@ -0,0 +1,47 @@
// GlissandoKind.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// The kind of glissando notation span.
///
/// MusicXML provides two distinct glissando elements, both placed inside
/// `<notations>` with `type="start"` on the first note and `type="stop"` on
/// the second:
///
/// | `GlissandoKind` | MusicXML element |
/// |---|---|
/// | `.glissando` | `<glissando>` — wavy or curved, unmeasured portamento |
/// | `.slide` | `<slide>` — straight line, measured (portamento) |
///
/// Choose `.glissando` for an approximate or unmeasured pitch sweep (typically
/// drawn with a wavy or curved line). Choose `.slide` for a precisely measured
/// portamento (typically drawn with a straight line).
///
/// ## Decode note
///
/// `<glissando>` and `<slide>` elements from an imported MusicXML file are
/// **not** currently parsed back into ``Glissando`` spanners. This is an
/// emit-only feature.
public enum GlissandoKind: Sendable, Hashable {
/// A wavy or curved, unmeasured pitch sweep between two notes.
///
/// Maps to `<glissando>` in MusicXML.
case glissando
/// A straight-line, measured portamento between two notes.
///
/// Maps to `<slide>` in MusicXML.
case slide
/// The MusicXML element name for this glissando kind.
///
/// `"glissando"` for `.glissando`; `"slide"` for `.slide`.
public var musicXMLElementName: String {
switch self {
case .glissando: return "glissando"
case .slide: return "slide"
}
}
}
@@ -0,0 +1,45 @@
// GlissandoLineType.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// The visual line style for a glissando or slide span.
///
/// Corresponds to the MusicXML `line-type` attribute on `<glissando>` and
/// `<slide>` elements.
///
/// | `GlissandoLineType` | `line-type` attribute |
/// |---|---|
/// | `.solid` | `"solid"` |
/// | `.dashed` | `"dashed"` |
/// | `.dotted` | `"dotted"` |
/// | `.wavy` | `"wavy"` |
///
/// The default for a ``Glissando`` is `.wavy`, which is the conventional
/// notation for an unmeasured glissando. Use `.solid` for a measured slide.
///
/// ## Decode note
///
/// `line-type` attributes from an imported MusicXML file are **not** currently
/// parsed back into ``GlissandoLineType`` values. This is an emit-only feature.
public enum GlissandoLineType: Sendable, Hashable {
/// A continuous, unbroken line.
case solid
/// A dashed line.
case dashed
/// A dotted line.
case dotted
/// A wavy line — the conventional notation for an unmeasured glissando.
case wavy
/// The MusicXML `line-type` attribute value for this line style.
public var musicXMLValue: String {
switch self {
case .solid: return "solid"
case .dashed: return "dashed"
case .dotted: return "dotted"
case .wavy: return "wavy"
}
}
}
+143
View File
@@ -0,0 +1,143 @@
// KeySignature.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A Western tonal key signature expressed as a circle-of-fifths position and mode.
///
/// The ``fifths`` value follows the MusicXML 4.0 `<fifths>` convention:
///
/// - `0` — C major / A minor (no accidentals)
/// - Positive — sharps: `+1` = G major / E minor (one sharp), `+2` = D major, …, `+7` = C♯ major
/// - Negative — flats: `-1` = F major / D minor (one flat), `-2` = B♭ major, …, `-7` = C♭ major
///
/// Use the named static-let constants (e.g. `.gMajor`, `.aMinor`) rather than the raw
/// `fifths:` integer wherever possible — they document intent at the call site.
///
/// ```swift
/// let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor)
/// ```
///
/// `KeySignature` is score-level: the same key signature is emitted in every part's
/// measure-1 `<attributes>` block. Per-part transposing keys are not supported in
/// this release.
///
/// ## MusicXML round-trip
///
/// ``Score/toMusicXMLString(divisions:)`` emits `<key><fifths>N</fifths><mode>major|minor</mode></key>`
/// after `<divisions>` and before `<time>` in measure 1 of every part.
/// ``Score/fromMusicXML(data:)`` reads `<fifths>` and `<mode>` from the FIRST `<key>`
/// encountered in the document and restores the ``KeySignature`` on the parsed ``Score``.
/// Documents without a `<key>` element default to `.cMajor` (fifths 0, major).
public struct KeySignature: Hashable, Sendable {
/// Tonal mode: major or minor.
public enum Mode: String, Hashable, Sendable {
case major
case minor
}
/// Circle-of-fifths position. `0` = C major / A minor; positive = sharps; negative = flats.
/// Range: `−7…+7` (enforced by the initialiser precondition).
public let fifths: Int
/// Tonal mode (major or minor).
public let mode: Mode
/// Create a `KeySignature` from a raw circle-of-fifths value and mode.
///
/// - Parameters:
/// - fifths: Circle-of-fifths position. Must be in `−7...7`.
/// `0` = C major / A minor, `+N` = N sharps, `−N` = N flats.
/// - mode: `.major` (default) or `.minor`.
public init(
fifths: Int,
mode: Mode = .major
) {
precondition(
(-7...7).contains(fifths),
"KeySignature: fifths must be in -7...7, got \(fifths)"
)
self.fifths = fifths
self.mode = mode
}
}
// MARK: - Major key statics
extension KeySignature {
// Sharp major keys (0 to +7)
/// C major — no accidentals.
public static let cMajor: KeySignature = KeySignature(fifths: 0, mode: .major)
/// G major — 1 sharp (F♯).
public static let gMajor: KeySignature = KeySignature(fifths: 1, mode: .major)
/// D major — 2 sharps.
public static let dMajor: KeySignature = KeySignature(fifths: 2, mode: .major)
/// A major — 3 sharps.
public static let aMajor: KeySignature = KeySignature(fifths: 3, mode: .major)
/// E major — 4 sharps.
public static let eMajor: KeySignature = KeySignature(fifths: 4, mode: .major)
/// B major — 5 sharps.
public static let bMajor: KeySignature = KeySignature(fifths: 5, mode: .major)
/// F♯ major — 6 sharps.
public static let fSharpMajor: KeySignature = KeySignature(fifths: 6, mode: .major)
/// C♯ major — 7 sharps.
public static let cSharpMajor: KeySignature = KeySignature(fifths: 7, mode: .major)
// Flat major keys (-1 to -7)
/// F major — 1 flat (B♭).
public static let fMajor: KeySignature = KeySignature(fifths: -1, mode: .major)
/// B♭ major — 2 flats.
public static let bFlatMajor: KeySignature = KeySignature(fifths: -2, mode: .major)
/// E♭ major — 3 flats.
public static let eFlatMajor: KeySignature = KeySignature(fifths: -3, mode: .major)
/// A♭ major — 4 flats.
public static let aFlatMajor: KeySignature = KeySignature(fifths: -4, mode: .major)
/// D♭ major — 5 flats.
public static let dFlatMajor: KeySignature = KeySignature(fifths: -5, mode: .major)
/// G♭ major — 6 flats.
public static let gFlatMajor: KeySignature = KeySignature(fifths: -6, mode: .major)
/// C♭ major — 7 flats.
public static let cFlatMajor: KeySignature = KeySignature(fifths: -7, mode: .major)
}
// MARK: - Minor key statics
extension KeySignature {
// Sharp minor keys (0 to +7)
/// A minor — no accidentals.
public static let aMinor: KeySignature = KeySignature(fifths: 0, mode: .minor)
/// E minor — 1 sharp.
public static let eMinor: KeySignature = KeySignature(fifths: 1, mode: .minor)
/// B minor — 2 sharps.
public static let bMinor: KeySignature = KeySignature(fifths: 2, mode: .minor)
/// F♯ minor — 3 sharps.
public static let fSharpMinor: KeySignature = KeySignature(fifths: 3, mode: .minor)
/// C♯ minor — 4 sharps.
public static let cSharpMinor: KeySignature = KeySignature(fifths: 4, mode: .minor)
/// G♯ minor — 5 sharps.
public static let gSharpMinor: KeySignature = KeySignature(fifths: 5, mode: .minor)
/// D♯ minor — 6 sharps.
public static let dSharpMinor: KeySignature = KeySignature(fifths: 6, mode: .minor)
/// A♯ minor — 7 sharps.
public static let aSharpMinor: KeySignature = KeySignature(fifths: 7, mode: .minor)
// Flat minor keys (-1 to -7)
/// D minor — 1 flat.
public static let dMinor: KeySignature = KeySignature(fifths: -1, mode: .minor)
/// G minor — 2 flats.
public static let gMinor: KeySignature = KeySignature(fifths: -2, mode: .minor)
/// C minor — 3 flats.
public static let cMinor: KeySignature = KeySignature(fifths: -3, mode: .minor)
/// F minor — 4 flats.
public static let fMinor: KeySignature = KeySignature(fifths: -4, mode: .minor)
/// B♭ minor — 5 flats.
public static let bFlatMinor: KeySignature = KeySignature(fifths: -5, mode: .minor)
/// E♭ minor — 6 flats.
public static let eFlatMinor: KeySignature = KeySignature(fifths: -6, mode: .minor)
/// A♭ minor — 7 flats.
public static let aFlatMinor: KeySignature = KeySignature(fifths: -7, mode: .minor)
}
+26 -16
View File
@@ -116,7 +116,7 @@ extension MIDIFile {
return Score(
bpm: bpm,
timeSignature: timeSignature,
timeSignature: TimeSignature(timeSignature),
parts: parts
)
}
@@ -294,22 +294,32 @@ extension MIDIFile {
private static func elementsFromScoreEvents(
_ events: [ScoreEvent]
) -> [ScoreElement] {
var elements: [ScoreElement] = []
var cursor: Double = 0.0
let sorted: [ScoreEvent] = events.sorted { $0.beat < $1.beat }
for event: ScoreEvent in sorted {
if event.beat > cursor {
elements.append(.rest(duration: .beats(event.beat - cursor)))
}
elements.append(.note(
event.pitch,
duration: .beats(event.duration),
dynamic: .raw(event.velocity),
articulation: event.articulation,
voice: event.voice
))
cursor = event.beat + event.duration
let pairs: [(position: Double, element: ScoreElement)] = sorted.map { event in
(
position: event.beat,
element: ScoreElement.note(
event.pitch,
duration: .beats(event.duration),
dynamic: .raw(event.velocity),
articulation: event.articulation,
voice: event.voice,
tie: false
)
)
}
return elements
// Shared gap-fill in Double space (preserves `.beats` representation).
// onOverlap is a no-op to keep the documented lossy monophonic behavior
// for overlapping SMF input — overlaps are not rejected here.
return fillRests(
sorted: pairs,
duration: { element in
if case .note(_, let dur, _, _, _, _) = element { return dur.beats }
if case .rest(let dur) = element { return dur.beats }
return 0.0
},
makeRest: { gap in .rest(duration: .beats(gap)) },
onOverlap: { _, _, _ in }
)
}
}
+159
View File
@@ -0,0 +1,159 @@
// MeterMap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A segmented map of ``TimeSignature`` over bars, plus an optional anacrusis.
///
/// A meter map governs barline placement and beat addressing for a whole
/// ``Score`` (``Score/meterMap``) or, when a part overrides polymetrically, a
/// whole ``ScorePart`` (``ScorePart/meterMap``). A part override is
/// **all-or-nothing**: a part either inherits the score map entirely (`nil`) or
/// supplies its own *complete* map — it can never patch a single segment of the
/// score map.
///
/// Segments are 1-based by ``Segment/startBar``; the first segment must start at
/// bar 1, and segments are stored sorted. The signature governing any bar is the
/// last segment whose `startBar <= bar`.
///
/// ## Anacrusis (pickup)
///
/// ``anacrusis`` is the length of an incomplete pickup measure, in quarter-note
/// beats. Absolute quarter `0.0` is the start of the pickup; the first full
/// barline falls at `anacrusis` quarters. The pickup is **bar 0** (engraved
/// `implicit="yes"`); **bar 1** is the first complete measure. Existing 1-based
/// measure references (``TempoChange``, ``Ending``) continue to mean bar `>= 1`
/// (the pickup is excluded).
///
/// The MusicXML encoder renders the full map: a fresh `<time>` at each mid-piece
/// change, per-measure capacity, the anacrusis as an implicit pickup measure, and
/// per-part polymeter overrides. Round-trip reads meter score-globally (from the
/// first part), so per-part overrides do not survive ``Score/fromMusicXML(data:)``.
public struct MeterMap: Sendable, Hashable {
/// One `(startBar, TimeSignature)` segment of a meter map.
public struct Segment: Sendable, Hashable {
/// 1-based bar at which this signature takes effect (`>= 1`).
public let startBar: Int
/// The signature in force from ``startBar`` until the next segment.
public let timeSignature: TimeSignature
/// - Parameters:
/// - startBar: 1-based bar where this signature begins (`>= 1`).
/// - timeSignature: The signature taking effect at `startBar`.
public init(
startBar: Int,
_ timeSignature: TimeSignature
) {
precondition(startBar >= 1, "MeterMap.Segment: startBar must be >= 1, got \(startBar)")
self.startBar = startBar
self.timeSignature = timeSignature
}
}
/// Segments sorted by ``Segment/startBar``; the first starts at bar 1, and
/// no two segments share a `startBar`.
public let segments: [Segment]
/// Pickup length in quarter-note beats. `0` (the default) means no pickup.
public let anacrusis: Fraction
// MARK: - Construction
/// Designated initializer.
///
/// - Parameters:
/// - segments: One or more segments. Sorted internally; the earliest must
/// start at bar 1, and `startBar` values must be unique.
/// - anacrusis: Pickup length in quarter-note beats (`>= 0`). Defaults to `0`.
public init(
segments: [Segment],
anacrusis: Fraction = .zero
) {
precondition(!segments.isEmpty, "MeterMap: requires at least one segment")
let sorted: [Segment] = segments.sorted { $0.startBar < $1.startBar }
precondition(
sorted[0].startBar == 1,
"MeterMap: the first segment must start at bar 1, got \(sorted[0].startBar)"
)
var previousBar: Int = 0
for segment: Segment in sorted {
precondition(
segment.startBar != previousBar,
"MeterMap: duplicate startBar \(segment.startBar)"
)
previousBar = segment.startBar
}
precondition(anacrusis >= .zero, "MeterMap: anacrusis must be >= 0, got \(anacrusis.double)")
self.segments = sorted
self.anacrusis = anacrusis
}
/// Convenience initializer for a single constant meter across the whole piece.
///
/// - Parameters:
/// - timeSignature: The constant signature.
/// - anacrusis: Pickup length in quarter-note beats (`>= 0`). Defaults to `0`.
public init(
_ timeSignature: TimeSignature,
anacrusis: Fraction = .zero
) {
self.init(
segments: [Segment(startBar: 1, timeSignature)],
anacrusis: anacrusis
)
}
// MARK: - Lookup
/// The signature governing a given 1-based bar — the last segment whose
/// `startBar <= bar`. For `bar < 1` (e.g. the pickup, bar 0) returns
/// ``initial``.
///
/// - Parameter bar: 1-based bar number (or `0` for the pickup).
/// - Returns: The ``TimeSignature`` in force at that bar.
public func timeSignature(atBar bar: Int) -> TimeSignature {
// Segments are sorted ascending by startBar; the governing signature is
// the last whose startBar <= bar. Scan from the end and stop at the first
// match (falls back to the bar-1 signature for bar < 1, e.g. the pickup).
for segment: Segment in segments.reversed() where segment.startBar <= bar {
return segment.timeSignature
}
return segments[0].timeSignature
}
/// Absolute quarter-beat at which a given 1-based bar begins.
///
/// Bar 1 begins at ``anacrusis`` (after the pickup); each later bar adds the
/// ``TimeSignature/measureQuarters`` capacity of the bars before it (honoring
/// mid-piece meter changes). Bar `<= 0` (the pickup) begins at quarter `0`.
///
/// - Parameter bar: 1-based bar number (or `0`/negative for the pickup).
/// - Returns: The bar's start offset in quarter beats.
public func barStartQuarters(_ bar: Int) -> Fraction {
if bar <= 0 { return .zero }
var acc: Fraction = anacrusis
var k: Int = 1
while k < bar {
acc = acc + timeSignature(atBar: k).measureQuarters
k += 1
}
return acc
}
/// The bar-1 signature.
public var initial: TimeSignature {
segments[0].timeSignature
}
/// `true` when the map holds a single segment (one signature for the whole
/// piece).
public var isConstant: Bool {
segments.count == 1
}
}
@@ -0,0 +1,378 @@
// MusicXMLParser+Build.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension _MusicXMLParser {
func parsedScore() throws -> Score {
if let err: MusicXMLError = rootError { throw err }
// Build the RepeatStructure from accumulated barline data.
let sortedEndings: [Ending] = parsedEndings.sorted { $0.startMeasure < $1.startMeasure }
let repeatStructure: RepeatStructure
if parsedForwardRepeatMeasures.isEmpty
&& parsedBackwardRepeatMeasures.isEmpty
&& sortedEndings.isEmpty
{
repeatStructure = .none
} else {
repeatStructure = RepeatStructure(
forwardRepeatMeasures: parsedForwardRepeatMeasures,
backwardRepeatMeasures: parsedBackwardRepeatMeasures,
endings: sortedEndings
)
}
// Build sorted, deduplicated TempoChange array from the
// measure→bpm map collected from the first part. Excludes measure 1
// (that is Score.bpm). Sorted ascending by measure number so callers
// get a predictable ordering.
let sortedTempoChanges: [TempoChange] = parsedTempoChangesByMeasure
.filter { $0.key >= 2 }
.sorted { $0.key < $1.key }
.map { TempoChange(measure: $0.key, bpm: $0.value) }
// Compute the anacrusis from the pickup cursor if an implicit
// first measure was detected. `pickupCursorDivisionsAtEnd` is 0 for
// documents without a pickup (the default Fraction.zero path).
let resolvedAnacrusis: Fraction = {
guard firstMeasureIsImplicit && pickupCursorDivisionsAtEnd > 0 else {
return .zero
}
let divisor: Int = pickupDivisions > 0 ? pickupDivisions : _MusicXMLParser.defaultDivisions
return Fraction(
num: Int64(pickupCursorDivisionsAtEnd),
den: Int64(divisor)
)
}()
// Build a MeterMap from the per-measure <time> records.
//
// If no <time> was parsed at all, fall back to the default 4/4 constant map.
// If only one <time> was parsed (constant meter), produce a single-segment
// map so the Score round-trips byte-identical to the constant-meter behaviour.
// For multiple <time> blocks (mid-piece meter changes):
// 1. Sort segments by bar number.
// 2. Guarantee a bar-1 segment (prepend if the lowest key > 1 using the
// back-compat timeSignature tuple so the initial signature is preserved).
// 3. Deduplicate consecutive segments with an equal TimeSignature (spurious
// repeated identical <time> elements should not create extra segments).
//
// The `anacrusis` field is carried through from `resolvedAnacrusis`.
// For documents without a pickup it is Fraction.zero — MeterMap defaults to .zero
// so no-anacrusis output is byte-identical.
let parsedMeterMap: MeterMap = {
if parsedMeterByMeasure.isEmpty {
return MeterMap(TimeSignature(timeSignature), anacrusis: resolvedAnacrusis)
}
// Sort by measure number.
let sortedPairs: [(Int, TimeSignature)] = parsedMeterByMeasure
.sorted { $0.key < $1.key }
.map { ($0.key, $0.value) }
// Guarantee a bar-1 segment.
var pairs: [(Int, TimeSignature)] = sortedPairs
if pairs[0].0 > 1 {
pairs.insert((1, TimeSignature(timeSignature)), at: 0)
}
// Deduplicate consecutive identical TimeSignature values.
var deduped: [(Int, TimeSignature)] = []
for pair: (Int, TimeSignature) in pairs {
if let last: (Int, TimeSignature) = deduped.last, last.1 == pair.1 {
// Same signature as the previous kept segment — skip.
continue
}
deduped.append(pair)
}
// Build MeterMap.Segment array.
let segments: [MeterMap.Segment] = deduped.map { bar, ts in
MeterMap.Segment(startBar: bar, ts)
}
return MeterMap(segments: segments, anacrusis: resolvedAnacrusis)
}()
guard !parts.isEmpty else {
// Tolerate empty documents — produce an empty Score rather
// than throwing, so very-minimal MusicXML still parses.
return Score(
bpm: bpm,
meterMap: parsedMeterMap,
keySignature: keySignature,
repeats: repeatStructure,
tempoChanges: sortedTempoChanges,
parts: []
)
}
// The score-level key is the FIRST part's parsed key (first-wins,
// consistent with the single-key behaviour). Per-part key overrides are set when
// a part's key DIFFERS from the first part's key. Parts matching the first
// part's key get nil overrides so non-transposing scores round-trip byte-identical
// at the model level (no spurious overrides are created).
let firstPartKey: KeySignature = parts[0].keySignature ?? keySignature
// Update the score-level key to the first part's parsed key (if any), so
// the Score carries the same key as the global parser's `keySignature` field
// (which is set from the first `<key>` element document-wide — this is the
// same value but we re-derive it here for clarity).
let resolvedScoreKey: KeySignature = firstPartKey
let scoreParts: [ScorePart] = parts.map { builder in
// A per-part key override is set only when this part's key DIFFERS from the
// first part's key. Matching parts (or parts with no parsed key) get nil.
let partKey: KeySignature? = {
guard let pk: KeySignature = builder.keySignature else { return nil }
return pk != resolvedScoreKey ? pk : nil
}()
return ScorePart(
name: builder.name,
channel: 0,
clef: builder.clef,
keySignature: partKey,
transpose: builder.transpose,
elements: _MusicXMLParser.reconstructElements(from: builder.entries)
)
}
return Score(
bpm: bpm,
meterMap: parsedMeterMap,
keySignature: resolvedScoreKey,
repeats: repeatStructure,
tempoChanges: sortedTempoChanges,
parts: scoreParts
)
}
/// Reconstruct a flat `[ScoreElement]` from beat-stamped entries.
///
/// Single-voice parts (all entries share the same voice number, or the
/// entries are already in the legacy flat sequential order where voice numbers
/// don't require partitioning) return the elements in document order —
/// exactly the same list as the legacy single-voice parser produced.
///
/// Multi-voice parts group entries by voice number, sort each voice's
/// entries by absolute beat, reconstruct them with inter-event rests to
/// fill gaps, and wrap each voice in a `.voice(n, [...])` case. The part
/// then contains exactly one `.voice` element per distinct voice number.
///
/// **Single-voice invariant**: if only one voice is present the result is
/// byte-identical to the legacy single-voice flat element list (no `.voice`
/// wrapper, no structural change).
static func reconstructElements(from entries: [_PartEntry]) -> [ScoreElement] {
guard !entries.isEmpty else { return [] }
// Determine distinct voices.
var voiceSet: Set<Int> = Set<Int>()
for entry: _PartEntry in entries {
voiceSet.insert(entry.voice)
}
// SINGLE-VOICE FAST PATH: return elements in document order — identical
// to the legacy single-voice output, no structural change.
// Wrap any wedge spans present in the entries.
if voiceSet.count <= 1 {
let rawElements: [ScoreElement] = entries.map { $0.element }
return wrapWedgeSpans(in: rawElements, from: entries)
}
// MULTI-VOICE PATH: partition entries by voice, sort each partition by
// absolute beat, fill gaps with rests, and wrap in `.voice(n, [...])`.
let sortedVoices: [Int] = voiceSet.sorted()
var result: [ScoreElement] = []
for voice: Int in sortedVoices {
let voiceEntries: [_PartEntry] = entries
.filter { $0.voice == voice }
.sorted { lhs, rhs in
if lhs.beat != rhs.beat { return lhs.beat < rhs.beat }
// Tie-break at equal beat: zero-duration notational marks
// (clef changes, grace notes) sort before the sounding note
// they precede, so an inline clef change renders ahead of its
// following note rather than after it. Two zero-duration marks
// at the same beat compare equal both ways and keep document
// order — relies on `sorted` being stable (guaranteed since
// Swift 5).
let lhsZero: Bool = elementDuration(lhs.element) == .zero
let rhsZero: Bool = elementDuration(rhs.element) == .zero
return lhsZero && !rhsZero
}
// Build the element list for this voice, inserting rests for beat
// gaps via the shared rest-fill helper. `voiceEntries` is pre-sorted
// (with the zero-duration tiebreak above). The transform zeroes the
// voice field on each element so `_flatten` uses the Voice block's
// voiceFallback rather than the 0-based pendingChordVoice field.
// onOverlap is a no-op: a MusicXML voice is monophonic by
// construction, so overlaps don't arise here.
let voiceElements: [ScoreElement] = fillRests(
sorted: voiceEntries.map { (position: $0.beat, element: $0.element) },
duration: { elementDuration($0) },
makeRest: { .rest(duration: .fraction($0)) },
onOverlap: { _, _, _ in },
transform: { zeroVoice($0) }
)
// Wrap wedge spans within this voice's element list.
let wrappedVoiceElements: [ScoreElement] = wrapWedgeSpans(
in: voiceElements,
from: voiceEntries
)
result.append(.voice(voice, wrappedVoiceElements))
}
return result
}
/// Wrap runs of elements identified by wedge-start / wedge-stop annotations
/// in the corresponding `_PartEntry` list into `.wedge(kind, [...])` wrappers.
///
/// ## Algorithm
///
/// Scans the `entries` array for `wedgeStart` / `wedgeStop` markers. For each
/// non-overlapping span `[startIdx, stopIdx]`:
/// - Elements from `startIdx` through `stopIdx` (inclusive) are wrapped in
/// `.wedge(kind, [...])`.
/// - Elements before/between/after wedge spans are emitted as-is.
///
/// Index mapping requires `elements.count == entries.count`. This holds for
/// the single-voice path. For the multi-voice path `elements` includes
/// synthetic gap-fill rests that have NO corresponding entry, so the counts
/// DIFFER whenever a voice has inter-event gaps; in that case the guard below
/// triggers the safe fallback — NO wedge wrapping is applied and the
/// `elements` are returned unchanged. Event round-trip is unaffected either
/// way (wedges are transparent to `flatten()`); only the structural `.wedge`
/// wrapper is dropped for multi-voice parts. This is the documented
/// multi-voice wedge limitation (analogous to tuplets not round-tripping).
///
/// If an entry's `wedgeStart` cannot be matched to a subsequent `wedgeStop`
/// (malformed document), the span extends to the end of the array.
static func wrapWedgeSpans(
in elements: [ScoreElement],
from entries: [_PartEntry]
) -> [ScoreElement] {
// If neither the entries nor elements have wedge annotations, return as-is.
let hasWedge: Bool = entries.contains { $0.wedgeStart != nil || $0.wedgeStop }
guard hasWedge else { return elements }
// Build a parallel array of (wedgeStart, wedgeStop) using entries indices.
// For the single-voice path, elements.count == entries.count.
// For multi-voice, entries does not include gap-fill rests, so index
// alignment is only valid for the elements that came from entries.
// Since gap-fill rests never carry wedge annotations (they are synthetic),
// we treat the entries and elements arrays as parallel for wedge annotation
// purposes when they have the same length.
guard elements.count == entries.count else {
// Length mismatch (multi-voice with gap-fill rests): fall back to
// unannotated output — event round-trip is still correct because
// wedges are transparent to flattening.
return elements
}
var result: [ScoreElement] = []
var i: Int = 0
while i < elements.count {
if let kind: WedgeKind = entries[i].wedgeStart {
// Found a wedge-start. Collect elements up to and including the
// matching wedge-stop (or the end of the array if no stop is found).
var j: Int = i
// Search for the wedge-stop in the same voice (same-voice entries
// are already filtered for multi-voice; single-voice searches all).
while j < entries.count && !entries[j].wedgeStop {
j += 1
}
// j now points at the stop entry (or one past the end if not found).
// Cap at the last valid index.
let stopIdx: Int = min(j, elements.count - 1)
let spanElements: [ScoreElement] = Array(elements[i...stopIdx])
result.append(.wedge(kind, spanElements))
i = stopIdx + 1
} else {
result.append(elements[i])
i += 1
}
}
return result
}
/// Return a copy of `element` with its voice field zeroed out.
///
/// Used by `reconstructElements` when building per-voice element lists:
/// elements are wrapped in `.voice(n, [...])` blocks, so their own voice
/// field should be `0` (the fallback indicator) to let `_flatten` use the
/// enclosing Voice block's number via `voiceFallback`. The MusicXML parser
/// stores `pendingChordVoice = max(0, noteContext.voice-1)` in the voice field
/// (a 0-based offset) which would otherwise override the block's voiceFallback
/// for notes whose voice field is non-zero (e.g. MusicXML `<voice>2</voice>`
/// maps to `pendingChordVoice = 1`).
static func zeroVoice(_ element: ScoreElement) -> ScoreElement {
switch element {
case .note(let p, let dur, let dyn, let art, _, _):
return .note(p, duration: dur, dynamic: dyn, articulation: art, voice: 0, tie: false)
case .chord(let ps, let dur, let dyn, let art, _, _):
// Authored chord ties do not round-trip through zeroVoice (the parser
// flushes chords without a tie field; voice zeroing is a pre-Voice-block
// clean-up step and authored ties are already merged before reaching here).
return .chord(ps, duration: dur, dynamic: dyn, articulation: art, voice: 0, tie: false)
case .rest, .tuplet, .voice, .wedge, .grace, .clefChange, .staff, .pedal,
.slur, .spanned, .displayed, .marked, .dynamicCurve, .fillMeasure:
return element
}
}
/// Extract the duration of a `ScoreElement` as a `Fraction` (in quarter-beats).
/// Used by `reconstructElements` to compute per-voice cursor positions.
/// Only `.note`, `.rest`, and `.chord` carry durations; `.tuplet` and
/// `.voice` are not expected in parsed entry lists (the parser produces
/// only flat note/rest/chord elements).
static func elementDuration(_ element: ScoreElement) -> Fraction {
switch element {
case .note(_, let dur, _, _, _, _):
return dur.asFraction ?? .zero
case .rest(let dur):
return dur.asFraction ?? .zero
case .chord(_, let dur, _, _, _, _):
return dur.asFraction ?? .zero
case .tuplet:
return .zero
case .voice:
return .zero
case .wedge:
return .zero
case .grace:
// Grace notes have no duration — they do not advance the cursor.
return .zero
case .clefChange:
// Clef changes have no duration — they do not advance the cursor.
return .zero
case .staff:
// Staff blocks overlay from beat 0 — zero duration in this context.
return .zero
case .pedal:
// Pedal marks have no duration — they do not advance the cursor.
return .zero
case .slur:
// Slur blocks are not expected in the parser's flat entry list.
return .zero
case .spanned:
// Spanned elements are not expected in the parser's flat entry list.
return .zero
case .displayed:
// Displayed wrappers are not expected in the parser's flat entry list.
return .zero
case .marked:
// Marked wrappers are not expected in the parser's flat entry list.
return .zero
case .dynamicCurve:
// Dynamic curve wrappers are not expected in the parser's flat entry list.
return .zero
case .fillMeasure:
// FillMeasure is expanded at Score init time and never appears in the
// parser's flat entry list. Treat as zero duration (no-op).
return .zero
}
}
}
@@ -0,0 +1,500 @@
// MusicXMLParser+Commit.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension _MusicXMLParser {
// MARK: - Note commit
func commitCurrentNote() {
guard let partIndex: Int = currentPartIndex else { return }
// Grace notes have no <duration> and do not advance the cursor.
// Commit as a .grace element directly, bypassing tie-merge and chord buffering.
if noteContext.isGrace {
// Flush any pending chord BEFORE the grace note (the grace ornaments the
// FOLLOWING main note — it appears before it in document order).
flushPendingChord(into: partIndex)
// Build the pitch from the parsed step/alter/octave (or skip if unrecognised).
if let step: String = noteContext.pitchStep,
let pitch: Pitch = makePitch(
step: step,
alter: noteContext.pitchAlter,
octave: noteContext.pitchOctave
)
{
let absoluteBeatNow: Fraction = Fraction(
num: Int64(parts[partIndex].absoluteCursorDivisions),
den: Int64(currentDivisions)
)
let entry: _PartEntry = _PartEntry(
beat: absoluteBeatNow,
voice: noteContext.voice,
element: .grace(pitch, slashed: noteContext.graceSlashed)
)
parts[partIndex].entries.append(entry)
// Cursor does NOT advance — grace notes have no duration.
}
return
}
// Span model: resolve the effective articulation for this note.
// Slur state is tracked per-voice (via `slurActiveByVoice`) so that a slur
// open in voice 1 does not contaminate notes in voice 2 after a `<backup>`.
//
// Priority order:
// 1. If this note carries `<slur type="start"/>`: mark `.legato` and
// activate the span for this voice.
// 2. If `slurActiveByVoice[noteContext.voice]` is true and this note does NOT carry
// `stop`: mark `.legato` (interior span member).
// 3. If this note carries `<slur type="stop"/>`: do NOT force `.legato`
// (the stop note is the slur target, not a slur member). Clear the span
// for this voice.
// 4. Otherwise: use the articulation parsed from `<articulations>`.
//
// Note: `noteContext.articulation` may already be `.legato` from a genuine
// `<articulations><legato/>` element (hypothetical; not standard MusicXML)
// — we override only when slur markup requires it.
let voiceSlurActive: Bool = slurActiveByVoice[noteContext.voice, default: false]
if noteContext.hasSlurStart {
noteContext.articulation = .legato
slurActiveByVoice[noteContext.voice] = true
} else if voiceSlurActive && !noteContext.hasSlurStop {
// Interior span member — mark legato.
noteContext.articulation = .legato
}
if noteContext.hasSlurStop {
// Stop note is the span boundary — NOT marked `.legato`.
// The stop note keeps its own parsed articulation (usually `.normal`).
// If this note also has `start` (rare end-of-part edge where a run's
// last legato note carries start+stop), the `noteContext.hasSlurStart` branch
// above already set `.legato`, which is acceptable for that edge case.
slurActiveByVoice[noteContext.voice] = false
}
// Fix 1: build an exact rational duration rather than a Double.
// Fraction auto-reduces, so e.g. divisions=3/divisions=3 → 1/1 exactly,
// and a triplet-quarter (2 divisions out of 3) → 2/3 exactly.
let noteDuration: NoteDuration = .fraction(
Fraction(
num: Int64(noteContext.durationDivisions),
den: Int64(currentDivisions)
)
)
let pitch: Pitch? = (noteContext.pitchStep != nil && !noteContext.isRest)
? makePitch(
step: noteContext.pitchStep ?? "",
alter: noteContext.pitchAlter,
octave: noteContext.pitchOctave
)
: nil
// Capture the absolute beat from the cursor BEFORE advancing.
// For chord-mates the cursor is NOT advanced (it was already
// advanced by the chord lead note).
let absoluteCursorNow: Int = parts[partIndex].absoluteCursorDivisions
let absoluteBeatNow: Fraction = Fraction(
num: Int64(absoluteCursorNow),
den: Int64(currentDivisions)
)
if noteContext.isChord {
// Chord-mate: append pitch to the pending chord buffer. Cursor
// does not advance. If parsing produced no pitch (malformed
// chord-mate), drop the entry silently.
//
// If this chord-mate carries a tie-stop, attempt to merge it into
// the last emitted element that contains the same pitch in the
// same voice. When the merge succeeds the duration is already
// folded into the prior element, so we do NOT buffer this mate —
// buffering would produce a spurious extra chord element on flush.
// When the merge fails (no prior element carries this pitch) the
// pitch is new and must be buffered normally so it is not lost.
//
// Special case: if the lead note's tie-stop for this note group
// already merged a `.chord` element that contains this pitch (tracked
// via `lastMergedChordLocation`), the duration has already been
// extended for ALL pitches in that chord. Do not merge again.
if let p: Pitch = pitch {
if noteContext.tieStop {
// Check whether the lead note's merge already covered this pitch.
let alreadyCoveredByLeadMerge: Bool = {
guard let loc: (partIndex: Int, elementIndex: Int) = lastMergedChordLocation,
loc.partIndex == partIndex else { return false }
let elem: ScoreElement = parts[loc.partIndex].entries[loc.elementIndex].element
if case .chord(let pitches, _, _, _, _, _) = elem {
return pitches.contains(p)
}
return false
}()
if alreadyCoveredByLeadMerge {
// Skip — duration was already folded in by the lead merge.
} else {
let mergedIdx: Int? = tryMergeTieStop(
pitch: p,
extraDuration: noteDuration,
voice: max(0, noteContext.voice - 1),
partIndex: partIndex
)
if mergedIdx == nil {
pendingChordPitches.append(p)
}
}
} else {
pendingChordPitches.append(p)
}
}
return
}
// Non-chord note (lead) — flush any pending chord first, and reset
// the chord-merge-location tracker for this new lead group.
flushPendingChord(into: partIndex)
lastMergedChordLocation = nil
if noteContext.isRest {
// Rests use the current voice number for beat-grouping purposes.
let entry: _PartEntry = _PartEntry(
beat: absoluteBeatNow,
voice: noteContext.voice,
element: .rest(duration: noteDuration)
)
parts[partIndex].entries.append(entry)
// Advance cursor by this rest's duration.
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
} else if let p: Pitch = pitch {
// Tie-stop: try to merge this note into the last emitted element
// of the same pitch in the same voice, rather than emitting a new
// element. This collapses barline-split tied pairs back into one
// element so round-trips preserve element count + durations.
if noteContext.tieStop {
let mergedIdx: Int? = tryMergeTieStop(
pitch: p,
extraDuration: noteDuration,
voice: max(0, noteContext.voice - 1),
partIndex: partIndex
)
if let idx: Int = mergedIdx {
// Record the merge location so chord-mates in this note
// group can detect that their pitch was already extended.
if case .chord = parts[partIndex].entries[idx].element {
lastMergedChordLocation = (partIndex: partIndex, elementIndex: idx)
}
// Merged successfully — advance cursor and don't buffer a new chord lead.
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
return
}
}
// Buffer this note as the chord lead — flushed when the next
// non-chord-mate or end-of-part arrives.
// Capture currentDynamic NOW so a subsequent <direction> element
// that arrives before the flush does not overwrite this note's
// dynamic (the dynamic belongs to the note, not to the flush moment).
pendingChordPitches = [p]
pendingChordDuration = noteDuration
pendingChordVoice = max(0, noteContext.voice - 1)
pendingChordArticulation = noteContext.articulation
pendingChordDynamic = currentDynamic
pendingChordBeat = absoluteBeatNow
// Advance cursor for this lead note.
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
} else {
// Unrecognised pitch + not a rest — treat as rest to keep
// cursor advancing rather than dropping silently.
let entry: _PartEntry = _PartEntry(
beat: absoluteBeatNow,
voice: noteContext.voice,
element: .rest(duration: noteDuration)
)
parts[partIndex].entries.append(entry)
parts[partIndex].absoluteCursorDivisions += noteContext.durationDivisions
}
}
/// Attempt to merge a tie-stop note into the immediately-preceding
/// element of the same voice that carries the matching pitch.
///
/// Fix 2: the search is bounded to the IMMEDIATELY-preceding emitted
/// element of the same voice (the last note or chord in the voice at the
/// tail of the element list). If that element doesn't match pitch + voice,
/// no merge is performed — the tie-stop is emitted as a normal new element.
/// This prevents a stray `<tie type="stop"/>` on a later same-pitch note
/// from incorrectly extending an unrelated earlier note.
///
/// Returns the index of the merged element on success, or `nil` when no
/// matching immediately-prior element was found.
@discardableResult
func tryMergeTieStop(
pitch: Pitch,
extraDuration: NoteDuration,
voice: Int,
partIndex: Int
) -> Int? {
// Find the last emitted element that belongs to this voice (scanning
// backward to skip elements from other voices). If that element
// does NOT carry the expected pitch, do not merge — emit normally.
let entries: [_PartEntry] = parts[partIndex].entries
for i: Int in stride(from: entries.count - 1, through: 0, by: -1) {
let element: ScoreElement = entries[i].element
switch element {
case .note(let ep, let dur, let dyn, let art, let ev, _):
if ev != voice {
// Different voice — keep scanning to skip its notes.
continue
}
// This is the immediately-preceding note in this voice.
// Only merge if pitch matches; otherwise stop scanning.
guard ep == pitch else { return nil }
let newDur: NoteDuration = addDurations(dur, extraDuration)
parts[partIndex].replaceElement(
at: i,
with: .note(ep, duration: newDur, dynamic: dyn, articulation: art, voice: ev, tie: false)
)
return i
case .chord(let pitches, let dur, let dyn, let art, let ev, _):
if ev != voice {
continue
}
// Immediately-preceding chord in this voice.
guard pitches.contains(pitch) else { return nil }
let newDur: NoteDuration = addDurations(dur, extraDuration)
parts[partIndex].replaceElement(
at: i,
with: .chord(pitches, duration: newDur, dynamic: dyn, articulation: art, voice: ev, tie: false)
)
return i
case .rest:
// Rests don't carry pitches; continue scanning backwards for
// the immediately-preceding pitched event of this voice.
continue
case .tuplet:
// Don't look inside tuplets for merge targets.
return nil
case .voice:
// Voice wrapper elements are not expected in the parser's flat
// entry list — stop scanning at any unexpected case.
return nil
case .wedge:
// Wedge wrapper elements are not expected in the parser's flat
// entry list — stop scanning at any unexpected case.
return nil
case .grace:
// Grace notes are durationless and are not merge targets.
// Continue scanning backward past any preceding grace elements.
continue
case .clefChange:
// Clef changes are durationless and are not merge targets.
// Continue scanning past them.
continue
case .staff:
// Staff blocks are not expected in the parser's flat entry list.
return nil
case .pedal:
// Pedal marks are durationless and are not merge targets.
// Continue scanning backward past them.
continue
case .slur:
// Slur blocks are structural span wrappers, not notes, and never
// appear in the parser's flat entry list. Stop the backward scan
// here — matching the sibling wrappers `.wedge` / `.voice` /
// `.staff` — so a tie-merge never binds across a structural
// boundary if a future round-trip extension introduces one.
return nil
case .spanned:
// Spanned elements are structural wrappers, not notes. Stop the
// backward scan for the same reason as `.slur` above.
return nil
case .displayed:
// Displayed wrappers are structural span wrappers, not notes.
// Stop the backward scan here — the parser does not produce these
// in its flat entry list, and a tie-merge must not cross structural
// wrappers.
return nil
case .marked:
// Marked wrappers are structural span wrappers, not notes.
// Stop the backward scan here — the parser does not produce these
// in its flat entry list, and a tie-merge must not cross structural
// wrappers.
return nil
case .dynamicCurve:
// Dynamic curve wrappers are structural wrappers, not notes.
// Stop the backward scan here — the parser does not produce these
// in its flat entry list.
return nil
case .fillMeasure:
// FillMeasure is expanded at Score init time and never appears in
// the parser's flat entry list. Stop the backward scan to avoid
// crossing this marker if one ever appears by mistake.
return nil
}
}
return nil
}
/// Add two `NoteDuration` values using exact `Fraction` arithmetic when
/// both operands are `.fraction`. Falls back to `Double` only when
/// either operand is `.beats`.
///
/// Fix 1: this ensures tie-merge produces exact rational sums (e.g.
/// a triplet quarter 2/3 + 2/3 = 4/3) without floating-point drift.
func addDurations(
_ a: NoteDuration,
_ b: NoteDuration
) -> NoteDuration {
switch (a, b) {
case (.fraction(let fa), .fraction(let fb)):
return .fraction(fa + fb)
case (.fraction(let fa), .beats(let bb)):
// Convert the Double to a high-precision fraction and add exactly.
let denominator: Int64 = Fraction.beatApproxDenominator
let extraNum: Int64 = Int64((bb * Double(denominator)).rounded())
let extraFrac: Fraction = Fraction(num: extraNum, den: denominator)
return .fraction(fa + extraFrac)
case (.beats(let ba), .fraction(let fb)):
let denominator: Int64 = Fraction.beatApproxDenominator
let baseNum: Int64 = Int64((ba * Double(denominator)).rounded())
let baseFrac: Fraction = Fraction(num: baseNum, den: denominator)
return .fraction(baseFrac + fb)
case (.beats(let ba), .beats(let bb)):
return .beats(ba + bb)
}
}
/// Emit any buffered chord lead + chord-mate pitches as either a
/// `.note` (singleton) or `.chord(...)` (multi-pitch) element.
func flushPendingChord(into partIndex: Int) {
guard !pendingChordPitches.isEmpty else { return }
let dur: NoteDuration = pendingChordDuration
let beat: Fraction = pendingChordBeat
// The MusicXML voice number is the 1-based value from <voice>; the
// ScoreElement voice field stores the 0-based fallback index
// (pendingChordVoice = max(0, noteContext.voice - 1)). For the _PartEntry
// grouping we use the 1-based MusicXML voice (pendingChordVoice + 1)
// so entries in the same <voice> slot are partitioned together.
// ScoreElement's voice field stays 0-based as before.
let mxVoice: Int = pendingChordVoice + 1
// Use the dynamic captured at lead-note commit time (pendingChordDynamic),
// not the current dynamic at flush time. A <direction> arriving between
// commit and flush must not overwrite this note group's dynamic.
let element: ScoreElement
if pendingChordPitches.count == 1 {
element = .note(
pendingChordPitches[0],
duration: dur,
dynamic: pendingChordDynamic,
articulation: pendingChordArticulation,
voice: pendingChordVoice,
tie: false
)
} else {
element = .chord(
pendingChordPitches,
duration: dur,
dynamic: pendingChordDynamic,
articulation: pendingChordArticulation,
voice: pendingChordVoice,
tie: false
)
}
// Apply any pending wedge-start annotation to this entry.
// The wedge-start direction appeared before this note in the document.
let wedgeStartForThisNote: WedgeKind? = pendingWedgeStartForNextNote
pendingWedgeStartForNextNote = nil
var entry: _PartEntry = _PartEntry(beat: beat, voice: mxVoice, element: element)
entry.wedgeStart = wedgeStartForThisNote
parts[partIndex].entries.append(entry)
pendingChordPitches.removeAll(keepingCapacity: true)
}
/// Build a `Pitch.named(...)` from MusicXML primitives. Returns nil
/// when `step` is unrecognised or `alter` is outside the supported
/// 50-cent grid.
func makePitch(
step: String,
alter: Double,
octave: Int
) -> Pitch? {
guard let letter: Letter = _MusicXMLParser.letterForStep(step) else { return nil }
guard let accidental: Accidental = _MusicXMLParser.accidentalForAlter(alter) else { return nil }
return .named(NoteName(letter: letter, accidental: accidental), octave)
}
static func letterForStep(_ step: String) -> Letter? {
switch step.uppercased() {
case "A": return .a
case "B": return .b
case "C": return .c
case "D": return .d
case "E": return .e
case "F": return .f
case "G": return .g
default: return nil
}
}
static func accidentalForAlter(_ alter: Double) -> Accidental? {
switch alter {
case -2.0: return .doubleFlat
case -1.5: return .threeQuarterFlat
case -1.0: return .flat
case -0.5: return .quarterFlat
case 0.0: return .natural
case 0.5: return .quarterSharp
case 1.0: return .sharp
case 1.5: return .threeQuarterSharp
case 2.0: return .doubleSharp
default: return nil
}
}
/// Map a parsed `(sign, line, octaveChange)` triple to a ``Clef`` case.
///
/// Inverse of ``Clef/musicXMLClef``. Unknown combinations fall back to
/// `.treble` so parse results are always valid.
internal static func clefFromParsed(
sign: String,
line: Int?,
octaveChange: Int?
) -> Clef {
let normalised: String = sign.lowercased()
switch normalised {
case "g":
// G clef with octave-change -1 → treble8vb (guitar, tenor voice).
if octaveChange == -1 { return .treble8vb }
return .treble
case "f":
// Standard bass clef is line 4; other F-clef positions are unusual —
// treat any F clef as bass for now.
return .bass
case "c":
if line == 3 { return .alto }
if line == 4 { return .tenor }
// Other C-clef lines — fall through to treble.
return .treble
case "percussion":
return .percussion
default:
// Unknown sign (tab, jianpu, etc.) — safe fallback.
return .treble
}
}
}
@@ -0,0 +1,771 @@
// MusicXMLParser+Delegate.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension _MusicXMLParser {
// MARK: - XMLParserDelegate
func parser(
_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String] = [:]
) {
elementStack.append(elementName)
currentText = ""
// Root validation
if elementStack.count == 1 {
if elementName == _MusicXMLParser.timewiseRootName {
rootError = .unsupportedTimewiseDocument
parser.abortParsing()
return
}
guard elementName == _MusicXMLParser.rootElementName else {
rootError = .unsupportedRoot(elementName)
parser.abortParsing()
return
}
return
}
switch elementName {
case "part-list":
inPartList = true
case "score-part" where inPartList:
currentScorePartID = attributeDict["id"]
currentScorePartName = nil
case "part" where !inPartList:
// `<part id="P1">`. Resolve to a builder using the part-list.
let id: String = attributeDict["id"] ?? ""
if let entry: (id: String, name: String) = partListEntries.first(where: { $0.id == id }) {
let builder: _PartBuilder = _PartBuilder(id: entry.id, name: entry.name)
parts.append(builder)
currentPartIndex = parts.count - 1
} else {
// No matching score-part — synthesize a default builder so
// events still land somewhere.
let builder: _PartBuilder = _PartBuilder(id: id, name: "Part \(parts.count + 1)")
parts.append(builder)
currentPartIndex = parts.count - 1
}
currentDivisions = _MusicXMLParser.defaultDivisions
// Reset per-voice slur-span state at the start of each new part.
slurActiveByVoice = [:]
// Reset dynamic to the default at the start of each part, and
// clear any direction-parsing flags that a malformed prior part
// might have left set (defensive — a part ending mid-<direction>
// must not leak flag state into the next part).
currentDynamic = .mf
pendingDynamic = nil
inDirection = false
inDirectionType = false
inDynamics = false
// Reset wedge state at part start.
wedgeActiveByVoice = [:]
pendingWedgeStart = nil
pendingWedgeStop = false
pendingWedgeStartForNextNote = nil
// Reset per-part measure counter.
currentMeasureNumber = 0
// Reset per-part key + transpose accumulation state.
inTranspose = false
transposeDiatonic = 0
transposeChromatic = 0
transposeOctaveChange = 0
case "measure" where currentPartIndex != nil:
// Detect the first measure's implicit attribute.
// When `implicit="yes"` on the very first measure of the first part,
// the measure is the pickup (measure 0). We adjust `currentMeasureNumber`
// so it becomes 0 for the pickup instead of 1, keeping subsequent full
// bars at 1..N (all existing <time> / repeat / tempo-change maps remain
// correctly 1-based).
//
// The adjustment: decrement by 1 BEFORE the `+= 1` below so the
// effective result is 0. Only applied once (first measure of first part).
if isFirstPart && currentMeasureNumber == 0 {
let isImplicit: Bool = attributeDict["implicit"] == "yes"
if isImplicit {
firstMeasureIsImplicit = true
// Pre-decrement so +1 below produces 0 for the pickup measure.
currentMeasureNumber = -1
}
}
// Track measure number. Incremented here for every measure.
currentMeasureNumber += 1
case "barline" where currentPartIndex != nil && isFirstPart:
// Begin a barline block; capture location attribute.
inBarline = true
barlineLocation = attributeDict["location"] ?? ""
barlineHasRepeatForward = false
barlineHasRepeatBackward = false
barlineEndingNumber = 0
barlineEndingType = ""
case "repeat" where inBarline && isFirstPart:
// `<repeat direction="forward|backward"/>`.
if let direction: String = attributeDict["direction"] {
if direction == "forward" { barlineHasRepeatForward = true }
if direction == "backward" { barlineHasRepeatBackward = true }
}
case "ending" where inBarline && isFirstPart:
// `<ending number="N" type="start|stop|discontinue"/>`.
if let numStr: String = attributeDict["number"],
let num: Int = Int(numStr),
let type_: String = attributeDict["type"]
{
barlineEndingNumber = num
barlineEndingType = type_
}
case "note":
// Reset all per-note accumulator state in one shot.
noteContext = _NoteContext()
case "grace":
// `<grace/>` or `<grace slash="yes"/>` marks this note
// as a grace note. No `<duration>` is expected; the note will be
// committed as a `.grace(pitch, slashed:)` element that does not
// advance the beat cursor.
noteContext.isGrace = true
noteContext.graceSlashed = attributeDict["slash"] == "yes"
case "rest":
noteContext.isRest = true
case "chord":
noteContext.isChord = true
case "pitch":
inPitch = true
case "notations":
inNotations = true
case "time":
inTime = true
// Reset per-<time>-block accumulators so each <time> element is
// self-contained (matches the per-key reset pattern for <key>).
pendingTimeBeatCount = 0
pendingTimeBeatType = 0
case "key":
inKey = true
// Reset per-key accumulation state.
keyFifths = 0
keyMode = "major"
case "clef":
inClef = true
// Reset per-clef accumulation state.
clefSign = ""
clefLine = nil
clefOctaveChange = nil
case "transpose" where currentPartIndex != nil:
// Begin a <transpose> block. Reset accumulation state.
inTranspose = true
transposeDiatonic = 0
transposeChromatic = 0
transposeOctaveChange = 0
case "backup" where currentPartIndex != nil:
inBackup = true
backupForwardDivisions = 0
case "forward" where currentPartIndex != nil:
inForward = true
backupForwardDivisions = 0
case "direction" where currentPartIndex != nil:
// Begin a direction block; reset pending dynamic, wedge, pedal, and tempo for this block.
inDirection = true
pendingDynamic = nil
pendingWedgeStart = nil
pendingWedgeStop = false
pendingPedalKind = nil
// Reset the per-direction tempo accumulator.
pendingDirectionTempo = nil
case "direction-type" where inDirection:
inDirectionType = true
case "dynamics" where inDirectionType:
inDynamics = true
case "wedge" where inDirectionType:
// Parse <wedge type="crescendo|diminuendo|stop"/>.
// The type attribute determines whether this is a span open or close.
if let wedgeType: String = attributeDict["type"] {
switch wedgeType {
case "crescendo": pendingWedgeStart = .crescendo
case "diminuendo": pendingWedgeStart = .diminuendo
case "stop": pendingWedgeStop = true
default: break
}
}
case "pedal" where inDirectionType:
// Parse <pedal type="start|stop" line="yes"/>. Only "start" and "stop"
// are surfaced; "change" and "continue" are ignored for round-trip
// purposes (Lyrebird only emits start/stop).
if let pedalType: String = attributeDict["type"] {
switch pedalType {
case "start": pendingPedalKind = .start
case "stop": pendingPedalKind = .stop
default: break
}
}
case "staves" where currentPartIndex != nil:
// <staves>N</staves> inside <attributes> — accepted but not used for
// element reconstruction. The Staff(...) grouping is a notation-only
// structural layer documented as not round-tripping: the per-note
// <staff> value is parsed (see `noteContext.staff`) but currently discarded,
// so decoded notes come back partitioned only by <voice>, not regrouped
// into Staff blocks. Sounding pitches / durations / pedal marks survive.
break
// Standard MusicXML dynamics element names.
// The element name itself (e.g. `<mf/>`) is the dynamic — no text content.
case "ppp" where inDynamics: pendingDynamic = .ppp
case "pp" where inDynamics: pendingDynamic = .pp
case "p" where inDynamics: pendingDynamic = .p
case "mp" where inDynamics: pendingDynamic = .mp
case "mf" where inDynamics: pendingDynamic = .mf
case "f" where inDynamics: pendingDynamic = .f
case "ff" where inDynamics: pendingDynamic = .ff
case "fff" where inDynamics: pendingDynamic = .fff
case "n" where inDynamics: pendingDynamic = .niente
case "articulations":
inArticulations = true
case "staccato" where inArticulations: noteContext.articulation = .staccato
case "staccatissimo" where inArticulations: noteContext.articulation = .staccatissimo
case "tenuto" where inArticulations: noteContext.articulation = .tenuto
case "accent" where inArticulations: noteContext.articulation = .accent
case "strong-accent" where inArticulations: noteContext.articulation = .marcato
case "slur" where inNotations:
// Span-based slur tracking (no `continue`).
//
// Rule (matches the encoder's span-based convention):
// • On `start`: record that this note opens a slur span.
// The note itself is marked `.legato` in `commitCurrentNote`.
// `slurActiveByVoice[voice]` is set to `true` there too.
// • On `stop`: record that this note closes a slur span.
// The stop note is NOT marked legato. `slurActiveByVoice[voice]` is cleared.
// • Interior notes (no `start` or `stop`) are marked `.legato`
// automatically while `slurActiveByVoice[voice] == true` in
// `commitCurrentNote`.
// • `continue` elements (from legacy documents) are treated as
// interior-span markers: they do not change `slurActiveByVoice` and
// do not mark legato on their own note — the span tracking handles it.
if let kind: String = attributeDict["type"] {
if kind == "start" {
noteContext.hasSlurStart = true
} else if kind == "stop" {
noteContext.hasSlurStop = true
}
// `continue` is intentionally ignored — the span model makes it
// unnecessary. Interior notes are already covered by `slurActiveByVoice`.
}
case "tie":
// `<tie type="stop"/>` — the sounding tie signal that drives
// tie-merge: a tie-stop note is merged back into the prior note of
// the same pitch so that barline-split note pairs round-trip as a
// single ScoreElement. `<tie type="start"/>` carries no decode-side
// information (the merge is driven entirely by the stop), so it is
// not tracked. Ignore `<tied>` (the notation-only companion).
if let kind: String = attributeDict["type"] {
if kind == "stop" { noteContext.tieStop = true }
}
case "sound":
// Tempo can arrive as an attribute on `<sound tempo="X"/>` (common
// in MuseScore ≤ 3 and MIDI-to-MusicXML converters that omit the
// metronome block) OR as text inside `<metronome><per-minute>`.
// First-write-wins via `sawTempo`.
if let t: String = attributeDict["tempo"], let v: Double = Double(t), v > 0 {
if !sawTempo {
bpm = v
sawTempo = true
}
// For mid-piece directions (measure >= 2, first part only),
// capture the tempo value for TempoChange construction. First value
// seen inside this direction block wins (`pendingDirectionTempo` is nil
// until explicitly set here or in `per-minute`).
if isFirstPart && currentMeasureNumber >= 2 && inDirection && pendingDirectionTempo == nil {
pendingDirectionTempo = v
}
}
default:
break
}
}
func parser(
_ parser: XMLParser,
foundCharacters string: String
) {
currentText += string
}
func parser(
_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?
) {
defer {
if !elementStack.isEmpty { elementStack.removeLast() }
currentText = ""
}
let trimmed: String = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
switch elementName {
case "part-list":
inPartList = false
case "score-part" where inPartList:
if let id: String = currentScorePartID {
let name: String = currentScorePartName ?? "Part \(partListEntries.count + 1)"
partListEntries.append((id: id, name: name))
}
currentScorePartID = nil
currentScorePartName = nil
case "part-name" where inPartList:
currentScorePartName = trimmed
case "barline" where isFirstPart && inBarline:
// Commit the accumulated barline data for this measure.
inBarline = false
if barlineLocation == "left" && barlineHasRepeatForward {
parsedForwardRepeatMeasures.insert(currentMeasureNumber)
}
if barlineLocation == "right" && barlineHasRepeatBackward {
parsedBackwardRepeatMeasures.insert(currentMeasureNumber)
}
if barlineEndingNumber >= 1 {
if barlineEndingType == "start" {
pendingEndingStarts[barlineEndingNumber] = currentMeasureNumber
} else if barlineEndingType == "stop" || barlineEndingType == "discontinue" {
if let startMeasure: Int = pendingEndingStarts[barlineEndingNumber] {
let ending: Ending = Ending(
number: barlineEndingNumber,
startMeasure: startMeasure,
stopMeasure: currentMeasureNumber
)
parsedEndings.append(ending)
pendingEndingStarts.removeValue(forKey: barlineEndingNumber)
}
}
}
barlineEndingNumber = 0
barlineEndingType = ""
case "measure" where currentPartIndex != nil && isFirstPart && !firstMeasureEnded:
// Capture the absolute cursor position at the end of the
// first implicit measure (the pickup). This is only done once (first
// part, first measure). `firstMeasureEnded` prevents re-entry.
//
// `currentMeasureNumber == 0` when the pickup is present (see the
// `<measure>` open handler). We check this to avoid capturing the
// cursor for an ordinary measure-1 close in a no-anacrusis document.
firstMeasureEnded = true
if firstMeasureIsImplicit && currentMeasureNumber == 0 {
if let idx: Int = currentPartIndex {
// Flush any pending chord before reading the cursor so it is accurate.
flushPendingChord(into: idx)
pickupCursorDivisionsAtEnd = parts[idx].absoluteCursorDivisions
pickupDivisions = currentDivisions
}
}
case "part" where currentPartIndex != nil:
// Flush any chord still pending at end-of-part.
if let idx: Int = currentPartIndex {
flushPendingChord(into: idx)
}
// Barlines are read from the first part only.
isFirstPart = false
currentPartIndex = nil
case "divisions":
if let v: Int = Int(trimmed), v > 0 {
currentDivisions = v
}
case "beats" where inTime:
// Accumulate beat count for the CURRENT <time> block.
// Both the first-time-signature path (tuple) and all subsequent
// <time> blocks (MeterMap) use the per-block pendingTimeBeatCount
// accumulator so they don't overwrite each other prematurely.
if let v: Int = Int(trimmed), v > 0 {
pendingTimeBeatCount = v
// Back-compat: also update the tuple from the first <time>.
if !sawTimeSignature {
timeSignature = (v, timeSignature.1)
}
}
case "beat-type" where inTime:
// Accumulate beat-type for the CURRENT <time> block.
if let v: Int = Int(trimmed), v > 0 {
pendingTimeBeatType = v
// Back-compat: also update the tuple from the first <time>.
if !sawTimeSignature {
timeSignature = (timeSignature.0, v)
}
}
case "time":
// Commit the completed <time> block.
// Every <time> in the first part is recorded in parsedMeterByMeasure
// (keyed by 1-based measure number, first-wins per measure) so that
// parsedScore() can build a multi-segment MeterMap.
// The back-compat timeSignature tuple is locked by sawTimeSignature
// (unchanged behaviour: first <time> wins for the tuple).
inTime = false
if isFirstPart
&& pendingTimeBeatCount > 0
&& pendingTimeBeatType > 0
{
let measureKey: Int = max(1, currentMeasureNumber)
if parsedMeterByMeasure[measureKey] == nil {
// Default-grouping initializer — MusicXML carries no beat
// grouping, so grouping is re-inferred from num/den.
parsedMeterByMeasure[measureKey] = TimeSignature(
pendingTimeBeatCount,
pendingTimeBeatType
)
}
}
// Reset per-<time>-block accumulators.
pendingTimeBeatCount = 0
pendingTimeBeatType = 0
sawTimeSignature = true
case "fifths" where inKey:
if let v: Int = Int(trimmed) {
keyFifths = v
}
case "mode" where inKey:
keyMode = trimmed
case "key":
inKey = false
// Store the parsed key per part (first-key-per-part wins for
// each individual part). The global `keySignature` / `sawKeySignature`
// still record the first key seen document-wide (first-part's first key)
// so the Score-level key is unchanged for non-transposing scores.
let parsedMode: KeySignature.Mode = (keyMode == "minor") ? .minor : .major
// Clamp fifths to -7...7 defensively (malformed documents may have out-of-range values).
let parsedFifths: Int = max(-7, min(7, keyFifths))
let parsedKey: KeySignature = KeySignature(fifths: parsedFifths, mode: parsedMode)
if let idx: Int = currentPartIndex, parts[idx].keySignature == nil {
// First key in this part — record it on the builder.
parts[idx].keySignature = parsedKey
}
// First-wins document-wide: also set the global key from the very first
// <key> element seen (for backward-compat with Score.keySignature).
if !sawKeySignature {
keySignature = parsedKey
sawKeySignature = true
}
case "sign" where inClef:
clefSign = trimmed
case "line" where inClef:
if let v: Int = Int(trimmed) {
clefLine = v
}
case "clef-octave-change" where inClef:
if let v: Int = Int(trimmed) {
clefOctaveChange = v
}
case "clef":
inClef = false
// Map the parsed (sign, line, octaveChange) back to a Clef case.
if let idx: Int = currentPartIndex {
let parsedClef: Clef = _MusicXMLParser.clefFromParsed(
sign: clefSign,
line: clefLine,
octaveChange: clefOctaveChange
)
if !parts[idx].clefWasSet {
// First clef in the part → the part-level (measure-1) clef.
parts[idx].clef = parsedClef
parts[idx].clefWasSet = true
} else {
// A later <clef> is a mid-voice clef change. Commit it as a
// zero-duration `.clefChange` entry at the current cursor beat,
// in document order (between the surrounding notes). Flush any
// buffered chord first so ordering is preserved (mirrors the
// <forward> rest-insertion path).
//
// Assumptions (acceptable for the encoder's own output; both
// hold for every Lyrebird-emitted document):
// • `noteContext.voice` is the voice that owns this clef change. In a
// multi-voice part a mid-clef between two voices' streams is
// attributed to the most-recently-seen voice; this only
// affects sort-tiebreaker ordering, never sounding output.
// • `currentDivisions` is current. A <divisions> change in the
// same <attributes> block as a mid <clef> would stale the
// beat; Lyrebird only emits <divisions> in measure-1.
flushPendingChord(into: idx)
let beatNow: Fraction = Fraction(
num: Int64(parts[idx].absoluteCursorDivisions),
den: Int64(currentDivisions)
)
parts[idx].entries.append(_PartEntry(
beat: beatNow,
voice: noteContext.voice,
element: .clefChange(parsedClef)
))
}
}
case "diatonic" where inTranspose:
if let v: Int = Int(trimmed) {
transposeDiatonic = v
}
case "chromatic" where inTranspose:
if let v: Int = Int(trimmed) {
transposeChromatic = v
}
case "octave-change" where inTranspose:
if let v: Int = Int(trimmed) {
transposeOctaveChange = v
}
case "transpose":
inTranspose = false
// Commit the parsed transpose to the current part builder.
// First-transpose-per-part wins (mid-part transpose changes are ignored).
if let idx: Int = currentPartIndex, parts[idx].transpose == nil {
parts[idx].transpose = Transpose(
chromatic: transposeChromatic,
diatonic: transposeDiatonic,
octaveChange: transposeOctaveChange
)
}
case "per-minute":
if let v: Double = Double(trimmed), v > 0 {
if !sawTempo {
bpm = v
sawTempo = true
}
// For mid-piece directions (measure >= 2, first part only),
// capture from <per-minute>. The FIRST tempo element seen in document
// order within this direction block wins (`pendingDirectionTempo == nil`
// guard); the encoder emits <per-minute> before <sound tempo>, so
// per-minute wins for Lyrebird-produced documents.
if isFirstPart && currentMeasureNumber >= 2 && inDirection && pendingDirectionTempo == nil {
pendingDirectionTempo = v
}
}
case "step":
if inPitch { noteContext.pitchStep = trimmed }
case "alter":
if inPitch, let v: Double = Double(trimmed) {
noteContext.pitchAlter = v
}
case "octave":
if inPitch, let v: Int = Int(trimmed) {
noteContext.pitchOctave = v
}
case "pitch":
inPitch = false
case "duration":
if let v: Int = Int(trimmed), v >= 0 {
if inBackup || inForward {
backupForwardDivisions = v
} else {
noteContext.durationDivisions = v
}
}
case "backup":
inBackup = false
// Rewind the absolute cursor for the current part.
if let idx: Int = currentPartIndex, backupForwardDivisions > 0 {
parts[idx].absoluteCursorDivisions = max(
0,
parts[idx].absoluteCursorDivisions - backupForwardDivisions
)
}
backupForwardDivisions = 0
case "forward":
inForward = false
// Advance the absolute cursor for the current part by inserting a
// rest element. The rest ensures single-voice sequential flatten()
// positions subsequent notes correctly. Multi-voice reconstruction
// uses the stored absolute beat instead, but the rest is harmless.
if let idx: Int = currentPartIndex, backupForwardDivisions > 0 {
let beatBefore: Fraction = Fraction(
num: Int64(parts[idx].absoluteCursorDivisions),
den: Int64(currentDivisions)
)
let fwdDur: NoteDuration = .fraction(Fraction(
num: Int64(backupForwardDivisions),
den: Int64(currentDivisions)
))
let restEntry: _PartEntry = _PartEntry(
beat: beatBefore,
voice: noteContext.voice,
element: .rest(duration: fwdDur)
)
// Flush any pending chord before inserting the rest.
flushPendingChord(into: idx)
parts[idx].entries.append(restEntry)
parts[idx].absoluteCursorDivisions += backupForwardDivisions
}
backupForwardDivisions = 0
case "voice":
if let v: Int = Int(trimmed), v >= 1 {
noteContext.voice = v
}
case "staff" where !inBarline:
// <staff> inside a <note> element — which staff the note belongs to.
// Parsed for completeness but currently discarded: `_PartEntry` has no
// staff field, so decoded notes are not regrouped into Staff blocks
// (documented-lossy; see the <staves> case). Not to be confused with
// the unrelated <staves> inside <attributes>.
if let v: Int = Int(trimmed), v >= 1 {
noteContext.staff = v
}
case "other-dynamics" where inDynamics:
// `<other-dynamics>` text is a raw velocity Double encoded by the
// Lyrebird encoder (e.g. "0.42" for `.raw(0.42)`). Parse as Double
// and build `.raw(_:)` if valid; ignore otherwise.
if let v: Double = Double(trimmed), v.isFinite {
pendingDynamic = .raw(v)
}
case "dynamics":
inDynamics = false
case "direction-type":
inDirectionType = false
case "direction":
inDirection = false
// Commit the pending dynamic (if any) as the new current dynamic.
if let dyn: Dynamic = pendingDynamic {
currentDynamic = dyn
}
pendingDynamic = nil
// Commit pending pedal mark as a zero-duration entry at the current cursor.
// Pedal marks are notation-only — they do not advance the cursor.
if let kind: PedalKind = pendingPedalKind, let partIdx: Int = currentPartIndex {
flushPendingChord(into: partIdx)
let beatNow: Fraction = Fraction(
num: Int64(parts[partIdx].absoluteCursorDivisions),
den: Int64(currentDivisions)
)
parts[partIdx].entries.append(_PartEntry(
beat: beatNow,
voice: noteContext.voice,
element: .pedal(kind)
))
}
pendingPedalKind = nil
// Commit mid-piece tempo change.
// Record the first tempo seen in this direction block for this measure
// (first-wins: if `parsedTempoChangesByMeasure` already has a value for
// this measure number from an earlier direction, leave it untouched).
if isFirstPart && currentMeasureNumber >= 2 {
if let v: Double = pendingDirectionTempo {
if parsedTempoChangesByMeasure[currentMeasureNumber] == nil {
parsedTempoChangesByMeasure[currentMeasureNumber] = v
}
}
}
pendingDirectionTempo = nil
// Commit pending wedge state.
// A wedge-start is queued to attach to the NEXT flushed note/chord.
// A wedge-stop attaches to the LAST flushed entry in the active wedge voice.
if let startKind: WedgeKind = pendingWedgeStart {
pendingWedgeStartForNextNote = startKind
// Mark the active voice so subsequent notes are within the span.
// We use noteContext.voice (the voice of the note that will follow this direction).
wedgeActiveByVoice[noteContext.voice] = startKind
pendingWedgeStart = nil
}
if pendingWedgeStop {
pendingWedgeStop = false
// Attach the stop to the most-recently-flushed entry whose voice
// has an open wedge. ASSUMPTION: at most one wedge is open per part
// at a time (true for Lyrebird's own encoder, which marks wedge
// spans per voice with no cross-voice overlap). If a malformed
// third-party document opened two wedges in different voices
// simultaneously, this scan would close whichever has the
// latest entry — acceptable for the supported feature scope.
if let partIdx: Int = currentPartIndex {
for i: Int in stride(from: parts[partIdx].entries.count - 1, through: 0, by: -1) {
let entry: _PartEntry = parts[partIdx].entries[i]
let entryVoice: Int = entry.voice
if wedgeActiveByVoice[entryVoice] != nil {
parts[partIdx].entries[i].wedgeStop = true
wedgeActiveByVoice[entryVoice] = nil
break
}
}
}
}
case "articulations":
inArticulations = false
case "notations":
inNotations = false
case "note":
commitCurrentNote()
default:
break
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
if rootError == nil {
rootError = .xmlParseFailed(String(describing: parseError))
}
}
}
@@ -14,438 +14,284 @@ internal final class _MusicXMLParser: NSObject, XMLParserDelegate {
// MARK: - Output
private(set) var parts: [_PartBuilder] = []
private(set) var bpm: Double = _MusicXMLParser.defaultBPM
private(set) var timeSignature: (Int, Int) = (4, 4)
private(set) var sawTempo: Bool = false
private(set) var sawTimeSignature: Bool = false
private(set) var rootError: MusicXMLError?
var parts: [_PartBuilder] = []
var bpm: Double = _MusicXMLParser.defaultBPM
var timeSignature: (Int, Int) = (4, 4)
var keySignature: KeySignature = .cMajor
var sawTempo: Bool = false
var sawTimeSignature: Bool = false
var sawKeySignature: Bool = false
var rootError: MusicXMLError?
// MARK: - Parsing state
/// Element name stack — used to scope text accumulation.
private var elementStack: [String] = []
var elementStack: [String] = []
/// Accumulated text between current element's open and close tags.
private var currentText: String = ""
var currentText: String = ""
// <part-list> / <score-part> tracking
private var inPartList: Bool = false
private var partListEntries: [(id: String, name: String)] = []
private var currentScorePartID: String?
private var currentScorePartName: String?
var inPartList: Bool = false
var partListEntries: [(id: String, name: String)] = []
var currentScorePartID: String?
var currentScorePartName: String?
// <part> tracking
private var currentPartIndex: Int? // index into `parts`
private var currentDivisions: Int = _MusicXMLParser.defaultDivisions
var currentPartIndex: Int? // index into `parts`
var currentDivisions: Int = _MusicXMLParser.defaultDivisions
/// Buffer of chord-mate pitches accumulating from successive `<note>
/// <chord/>` elements. Flushed as a single `.chord(...)` element
/// when the next non-chord note (or end of part) arrives.
private var pendingChordPitches: [Pitch] = []
/// Articulation / duration / voice carried by the chord lead note.
private var pendingChordDuration: Double = 0.0
private var pendingChordVoice: Int = 0
private var pendingChordArticulation: Articulation = .normal
var pendingChordPitches: [Pitch] = []
/// Articulation / duration / voice / dynamic carried by the chord lead note.
var pendingChordDuration: NoteDuration = .zero
var pendingChordVoice: Int = 0
var pendingChordArticulation: Articulation = .normal
/// Dynamic captured at chord lead-note commit time (from `currentDynamic`).
/// Stored here so it is not overwritten if a `<direction>` arrives between
/// the lead note's commit and the flush.
var pendingChordDynamic: Dynamic = .mf
/// Absolute beat of the chord lead note (captured from the cursor at lead-note commit time).
var pendingChordBeat: Fraction = .zero
/// When the most-recent non-chord tie-stop lead note merged into a `.chord`
/// element, this records `(partIndex, elementIndex)` so that subsequent
/// chord-mate tie-stops in the same note group can detect that the chord
/// duration was already extended and must not merge again.
var lastMergedChordLocation: (partIndex: Int, elementIndex: Int)? = nil
// <note> tracking
private var noteIsRest: Bool = false
private var noteIsChord: Bool = false
private var notePitchStep: String?
private var notePitchAlter: Double = 0.0
private var notePitchOctave: Int = _MusicXMLParser.defaultMidiOctave
private var noteDurationDivisions: Int = 0
private var noteVoice: Int = 1
private var noteArticulation: Articulation = .normal
private var inPitch: Bool = false
private var inArticulations: Bool = false
private var inNotations: Bool = false
private var inTime: Bool = false
//
// All per-`<note>` accumulator state lives in ``_NoteContext`` and is reset
// in one assignment (`noteContext = _NoteContext()`) at each `<note>` open,
// then read in `commitCurrentNote()` — the "reset on open, commit on close"
// pattern. The `in…` nesting flags below are NOT per-note (they toggle on
// their own element open/close) and stay on the class.
var noteContext: _NoteContext = _NoteContext()
var inPitch: Bool = false
var inArticulations: Bool = false
var inNotations: Bool = false
var inTime: Bool = false
var inKey: Bool = false
var keyFifths: Int = 0
var keyMode: String = "major"
var inClef: Bool = false
var clefSign: String = ""
var clefLine: Int? = nil
var clefOctaveChange: Int? = nil
// <transpose> accumulation state (per part, reset in <part> open).
var inTranspose: Bool = false
var transposeDiatonic: Int = 0
var transposeChromatic: Int = 0
var transposeOctaveChange: Int = 0
// Pedal direction tracking.
//
// `<pedal type="start|stop" line="yes"/>` marks sustain-pedal marks.
// Parsed inside a `<direction>` block and committed as a `.pedal(kind)`
// zero-duration entry on `</direction>`.
//
// - `pendingPedalKind`: non-nil when a `<pedal>` element with a
// recognised `type` was seen in the current direction block.
var pendingPedalKind: PedalKind? = nil
// Slur span tracking (span-based, no `continue`).
//
// A slur span is a pair of ONE `<slur type="start"/>` and ONE
// `<slur type="stop"/>` (same `number="1"`). Interior notes carry no `<slur>`.
//
// Span tracking state that persists across note elements, keyed by
// MusicXML voice number (1-based). Using a per-voice dictionary rather than
// a single Bool prevents a slur open in voice 1 from contaminating voice 2
// after a `<backup>` rewinds the cursor to the start of the measure.
//
// - `slurActiveByVoice[v]` is `true` from the moment a `start` is seen in
// voice `v` until the corresponding `stop` is seen in voice `v`.
// - While `slurActiveByVoice[v] == true`, every committed non-stop note in
// voice `v` is marked `.legato`.
// - On `stop` in voice `v`: the stop note itself is NOT marked legato;
// `slurActiveByVoice[v]` is cleared.
//
// The per-note transient slur flags (`hasSlurStart` / `hasSlurStop`, this
// note element carries `<slur type="start|stop"/>`) live in ``_NoteContext``.
var slurActiveByVoice: [Int: Bool] = [:]
// Backup / forward cursor tracking (multi-voice support).
//
// `<backup><duration>D</duration></backup>` rewinds the absolute part cursor
// by D divisions so that a subsequent voice can write from the beginning of
// the rewound position.
// `<forward><duration>D</duration></forward>` advances the cursor by D
// divisions (used to skip silences).
//
// `inBackup` / `inForward` flag which element's `<duration>` text to
// accumulate into `backupForwardDivisions`.
var inBackup: Bool = false
var inForward: Bool = false
var backupForwardDivisions: Int = 0
// Dynamic direction tracking.
//
// A `<direction>/<direction-type>/<dynamics>` block sets the current
// dynamic that applies to subsequently-committed notes/chords (sticky).
// A `<direction>` without a `<dynamics>` child is ignored for dynamic
// purposes. Reset at part start to `.mf`.
//
// - `inDirection`: true from `<direction>` open to `</direction>`.
// - `inDirectionType`: true from `<direction-type>` open to close.
// - `inDynamics`: true from `<dynamics>` open to close.
// - `pendingDynamic`: dynamic parsed from the current `<direction>` block,
// or nil if no recognised dynamic was found yet.
// - `currentDynamic`: the last committed dynamic (sticky); applied to
// the next flushed note/chord.
var inDirection: Bool = false
var inDirectionType: Bool = false
var inDynamics: Bool = false
var pendingDynamic: Dynamic? = nil
var currentDynamic: Dynamic = .mf
// Wedge (hairpin) span tracking.
//
// `<wedge type="crescendo|diminuendo"/>` marks the start of a wedge span.
// `<wedge type="stop"/>` marks the end. Tracked per-voice so that a wedge
// in voice 1 does not contaminate voice 2.
//
// - `wedgeActiveByVoice`: maps voice number → WedgeKind when a wedge span
// is currently open for that voice; nil when no span is open.
// - `pendingWedgeStart`: wedge start parsed from the current `<direction>`
// block (set when `<wedge type="crescendo|diminuendo"/>` is seen).
// - `pendingWedgeStop`: true when `<wedge type="stop"/>` is seen in the
// current `<direction>` block.
//
// On `</direction>`:
// - If `pendingWedgeStart` is non-nil: record as `pendingWedgeStartForNextNote`,
// which is attached to the next committed note/chord's _PartEntry.
// - If `pendingWedgeStop`: attach a wedge-stop annotation to the LAST
// committed entry that is part of the active wedge span (the entry that
// was most recently flushed for the active voice).
//
// `pendingWedgeStartForNextNote` is consumed on the next `flushPendingChord`.
var wedgeActiveByVoice: [Int: WedgeKind] = [:]
var pendingWedgeStart: WedgeKind? = nil
var pendingWedgeStop: Bool = false
var pendingWedgeStartForNextNote: WedgeKind? = nil
// Anacrusis tracking.
//
// When the first measure of the first part is `implicit="yes"` it is the
// pickup (measure 0). `currentMeasureNumber` is set to 0 for it (see the
// `<measure>` handler for the adjustment logic) and subsequent full bars
// count as 1..N — so all existing `parsedMeterByMeasure` / repeat /
// tempo-change maps stay correctly 1-based.
//
// `pickupCursorDivisionsAtEnd`: cursor position (in divisions) of the first
// part's absolute cursor at the moment the implicit measure closes. Captured
// via `absoluteCursorDivisions` on the first part builder. Used to compute
// the resolved pickup Fraction (cursor / currentDivisions at that moment)
// in `parsedScore()`.
//
// - `firstMeasureIsImplicit`: set when the very first `<measure>` open of
// the first part carries `implicit="yes"`. Read-only after measure 0 ends.
// - `firstMeasureEnded`: set after the first `<measure>` end is processed.
// Prevents a second `<measure>` in the same part from being treated as
// another implicit measure.
// - `pickupCursorDivisionsAtEnd`: divisions cursor captured at the moment
// `</measure>` closes the first (implicit) measure of the first part.
var firstMeasureIsImplicit: Bool = false
var firstMeasureEnded: Bool = false
var pickupCursorDivisionsAtEnd: Int = 0
var pickupDivisions: Int = _MusicXMLParser.defaultDivisions
// Repeat / ending tracking.
//
// Read from the FIRST part only (all parts share the same barline structure).
// `isFirstPart` is set to false after the first part's `</part>` is seen.
//
// - `currentMeasureNumber`: normally 1-based; when a pickup (measure 0) is
// present the counter starts at 0 for the implicit measure, then 1..N for
// full bars. Reset to 0 at each `<part>` open; the pickup-adjustment
// subtracts 1 before the first `+= 1` so the result is 0.
// - `inBarline`: true from `<barline>` open to `</barline>`.
// - `barlineLocation`: "left" or "right" from the `location` attribute.
// - `barlineHasRepeatForward`: true when a `<repeat direction="forward"/>` was
// seen inside the current `<barline>`.
// - `barlineHasRepeatBackward`: true when a `<repeat direction="backward"/>` was seen.
// - `barlineEndingNumber`: the `number` attribute of `<ending>` (0 = none seen).
// - `barlineEndingType`: the `type` attribute of `<ending>` ("start", "stop",
// "discontinue").
//
// Accumulated repeat state (built from first-part barlines):
// - `parsedForwardRepeatMeasures`
// - `parsedBackwardRepeatMeasures`
// - `pendingEndingStarts`: number → startMeasure, waiting for a matching stop.
// - `parsedEndings`
var isFirstPart: Bool = true
var currentMeasureNumber: Int = 0
var inBarline: Bool = false
var barlineLocation: String = ""
var barlineHasRepeatForward: Bool = false
var barlineHasRepeatBackward: Bool = false
var barlineEndingNumber: Int = 0
var barlineEndingType: String = ""
var parsedForwardRepeatMeasures: Set<Int> = []
var parsedBackwardRepeatMeasures: Set<Int> = []
/// Volta starts waiting for a matching stop: endingNumber → startMeasure.
var pendingEndingStarts: [Int: Int] = [:]
var parsedEndings: [Ending] = []
// Mid-piece tempo-change tracking.
//
// Read from the FIRST part only (all parts share the same tempo directions).
// Within each `<direction>` block, `pendingDirectionTempo` accumulates the
// first tempo value seen — either from `<metronome><per-minute>` (preferred)
// or from `<sound tempo="X"/>`. On `</direction>`, if the current measure is
// >= 2 and the value is non-nil, a `TempoChange` is recorded.
//
// `seenTempoInCurrentDirection` prevents a single direction block that carries
// BOTH `<per-minute>` AND `<sound tempo>` from recording two changes.
// - `pendingDirectionTempo`: nil at direction start; set to the first
// tempo value read inside this direction block.
var pendingDirectionTempo: Double? = nil
/// Accumulated mid-piece tempo changes, keyed by measure number (first-wins).
var parsedTempoChangesByMeasure: [Int: Double] = [:]
// Mid-piece meter-change tracking.
//
// Read from the FIRST part only (all parts share the same time-signature
// attributes). Every `<time>` block from the first part is recorded here so
// that the resulting `MeterMap` can express mid-piece meter changes.
//
// Per-`<time>` accumulation:
// - `pendingTimeBeatCount`: the `<beats>` value parsed inside the CURRENT
// `<time>` block (0 = not yet seen).
// - `pendingTimeBeatType`: the `<beat-type>` value parsed inside the CURRENT
// `<time>` block (0 = not yet seen).
//
// On `</time>` the pair is committed to `parsedMeterByMeasure` keyed by the
// current 1-based measure number (first-wins per measure — a measure cannot
// carry two different `<time>` blocks in well-formed MusicXML). The back-compat
// `timeSignature` tuple is still set from the very FIRST `<time>` (unchanged).
//
// Grouping caveat: MusicXML `<time>` carries no beat-grouping information, so
// the `TimeSignature` stored here uses the default-grouping convenience
// initializer. A `6/8` authored as simple `[1,1,1,1,1,1]` round-trips as
// compound `[3,3]` — numerator/denominator are preserved, grouping is re-inferred.
var pendingTimeBeatCount: Int = 0
var pendingTimeBeatType: Int = 0
/// Accumulated mid-piece meter changes, keyed by 1-based measure number.
/// First-wins per measure (a `<time>` block inside measure N is the governing
/// signature starting at bar N). Only populated from the first part.
var parsedMeterByMeasure: [Int: TimeSignature] = [:]
// MARK: - Constants
private static let rootElementName: String = "score-partwise"
private static let timewiseRootName: String = "score-timewise"
private static let defaultBPM: Double = 120.0
private static let defaultDivisions: Int = 480
/// Octave used as the per-note reset for `notePitchOctave` before `<octave>` is read.
/// `4` is the middle-C octave in MIDI / MusicXML conventions.
private static let defaultMidiOctave: Int = 4
static let rootElementName: String = "score-partwise"
static let timewiseRootName: String = "score-timewise"
static let defaultBPM: Double = 120.0
static let defaultDivisions: Int = 480
/// Octave used as the per-note reset for ``_NoteContext/pitchOctave`` before
/// `<octave>` is read. `4` is the middle-C octave in MIDI / MusicXML conventions.
static let defaultMidiOctave: Int = 4
// MARK: - Public entry
func parsedScore() throws -> Score {
if let err: MusicXMLError = rootError { throw err }
guard !parts.isEmpty else {
// Tolerate empty documents — produce an empty Score rather
// than throwing, so very-minimal MusicXML still parses.
return Score(
bpm: bpm,
timeSignature: timeSignature,
parts: []
)
}
let scoreParts: [ScorePart] = parts.map { builder in
ScorePart(
name: builder.name,
channel: 0,
elements: builder.elements
)
}
return Score(
bpm: bpm,
timeSignature: timeSignature,
parts: scoreParts
)
}
// MARK: - XMLParserDelegate
func parser(
_ parser: XMLParser,
didStartElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?,
attributes attributeDict: [String: String] = [:]
) {
elementStack.append(elementName)
currentText = ""
// Root validation
if elementStack.count == 1 {
if elementName == _MusicXMLParser.timewiseRootName {
rootError = .unsupportedTimewiseDocument
parser.abortParsing()
return
}
guard elementName == _MusicXMLParser.rootElementName else {
rootError = .unsupportedRoot(elementName)
parser.abortParsing()
return
}
return
}
switch elementName {
case "part-list":
inPartList = true
case "score-part" where inPartList:
currentScorePartID = attributeDict["id"]
currentScorePartName = nil
case "part" where !inPartList:
// `<part id="P1">`. Resolve to a builder using the part-list.
let id: String = attributeDict["id"] ?? ""
if let entry: (id: String, name: String) = partListEntries.first(where: { $0.id == id }) {
let builder: _PartBuilder = _PartBuilder(id: entry.id, name: entry.name)
parts.append(builder)
currentPartIndex = parts.count - 1
} else {
// No matching score-part — synthesize a default builder so
// events still land somewhere.
let builder: _PartBuilder = _PartBuilder(id: id, name: "Part \(parts.count + 1)")
parts.append(builder)
currentPartIndex = parts.count - 1
}
currentDivisions = _MusicXMLParser.defaultDivisions
case "note":
// Reset per-note state.
noteIsRest = false
noteIsChord = false
notePitchStep = nil
notePitchAlter = 0.0
notePitchOctave = _MusicXMLParser.defaultMidiOctave
noteDurationDivisions = 0
noteVoice = 1
noteArticulation = .normal
case "rest":
noteIsRest = true
case "chord":
noteIsChord = true
case "pitch":
inPitch = true
case "notations":
inNotations = true
case "time":
inTime = true
case "articulations":
inArticulations = true
case "staccato" where inArticulations: noteArticulation = .staccato
case "staccatissimo" where inArticulations: noteArticulation = .staccatissimo
case "tenuto" where inArticulations: noteArticulation = .tenuto
case "accent" where inArticulations: noteArticulation = .accent
case "strong-accent" where inArticulations: noteArticulation = .marcato
case "slur" where inNotations:
// `<slur type="start"/>` (or "continue") sets legato on this note.
// Whole-span legato run tracking is deferred — every slur-bearing
// note is marked `.legato` so single-note round-trips work.
if let kind: String = attributeDict["type"], kind == "start" || kind == "continue" {
noteArticulation = .legato
}
case "sound":
// Tempo can arrive as an attribute on `<sound tempo="X"/>` (common
// in MuseScore ≤ 3 and MIDI-to-MusicXML converters that omit the
// metronome block) OR as text inside `<metronome><per-minute>`.
// First-write-wins via `sawTempo`.
if !sawTempo, let t: String = attributeDict["tempo"], let v: Double = Double(t), v > 0 {
bpm = v
sawTempo = true
}
default:
break
}
}
func parser(
_ parser: XMLParser,
foundCharacters string: String
) {
currentText += string
}
func parser(
_ parser: XMLParser,
didEndElement elementName: String,
namespaceURI: String?,
qualifiedName qName: String?
) {
defer {
if !elementStack.isEmpty { elementStack.removeLast() }
currentText = ""
}
let trimmed: String = currentText.trimmingCharacters(in: .whitespacesAndNewlines)
switch elementName {
case "part-list":
inPartList = false
case "score-part" where inPartList:
if let id: String = currentScorePartID {
let name: String = currentScorePartName ?? "Part \(partListEntries.count + 1)"
partListEntries.append((id: id, name: name))
}
currentScorePartID = nil
currentScorePartName = nil
case "part-name" where inPartList:
currentScorePartName = trimmed
case "part" where currentPartIndex != nil:
// Flush any chord still pending at end-of-part.
if let idx: Int = currentPartIndex {
flushPendingChord(into: idx)
}
currentPartIndex = nil
case "divisions":
if let v: Int = Int(trimmed), v > 0 {
currentDivisions = v
}
case "beats" where inTime && !sawTimeSignature:
if let v: Int = Int(trimmed), v > 0 {
timeSignature = (v, timeSignature.1)
}
case "beat-type" where inTime && !sawTimeSignature:
if let v: Int = Int(trimmed), v > 0 {
timeSignature = (timeSignature.0, v)
}
case "time":
// Lock in the first complete <time> block. Subsequent <time>
// elements (mid-piece time-signature changes) are ignored — Score
// carries a single timeSignature value in v1.
inTime = false
sawTimeSignature = true
case "per-minute":
if !sawTempo, let v: Double = Double(trimmed), v > 0 {
bpm = v
sawTempo = true
}
case "step":
if inPitch { notePitchStep = trimmed }
case "alter":
if inPitch, let v: Double = Double(trimmed) {
notePitchAlter = v
}
case "octave":
if inPitch, let v: Int = Int(trimmed) {
notePitchOctave = v
}
case "pitch":
inPitch = false
case "duration":
if let v: Int = Int(trimmed), v >= 0 {
noteDurationDivisions = v
}
case "voice":
if let v: Int = Int(trimmed), v >= 1 {
noteVoice = v
}
case "articulations":
inArticulations = false
case "notations":
inNotations = false
case "note":
commitCurrentNote()
default:
break
}
}
func parser(_ parser: XMLParser, parseErrorOccurred parseError: Error) {
if rootError == nil {
rootError = .xmlParseFailed(String(describing: parseError))
}
}
// MARK: - Note commit
private func commitCurrentNote() {
guard let partIndex: Int = currentPartIndex else { return }
let durationBeats: Double = Double(noteDurationDivisions) / Double(currentDivisions)
let pitch: Pitch? = (notePitchStep != nil && !noteIsRest)
? makePitch(
step: notePitchStep ?? "",
alter: notePitchAlter,
octave: notePitchOctave
)
: nil
if noteIsChord {
// Chord-mate: append pitch to the pending chord buffer. Cursor
// does not advance. If parsing produced no pitch (malformed
// chord-mate), drop the entry silently.
if let p: Pitch = pitch {
pendingChordPitches.append(p)
}
return
}
// Non-chord note (lead) — flush any pending chord first.
flushPendingChord(into: partIndex)
if noteIsRest {
parts[partIndex].elements.append(
.rest(duration: .beats(durationBeats))
)
} else if let p: Pitch = pitch {
// Buffer this note as the chord lead — flushed when the next
// chord-non-mate or end-of-part arrives. This lets a `<chord/>`
// continuation upgrade the buffered single-note into a multi-
// note `.chord(...)` element.
pendingChordPitches = [p]
pendingChordDuration = durationBeats
pendingChordVoice = max(0, noteVoice - 1)
pendingChordArticulation = noteArticulation
} else {
// Unrecognised pitch + not a rest — treat as rest to keep
// cursor advancing rather than dropping silently.
parts[partIndex].elements.append(
.rest(duration: .beats(durationBeats))
)
}
}
/// Emit any buffered chord lead + chord-mate pitches as either a
/// `.note` (singleton) or `.chord(...)` (multi-pitch) element.
private func flushPendingChord(into partIndex: Int) {
guard !pendingChordPitches.isEmpty else { return }
let dur: NoteDuration = NoteDuration.beats(pendingChordDuration)
if pendingChordPitches.count == 1 {
parts[partIndex].elements.append(
.note(
pendingChordPitches[0],
duration: dur,
dynamic: .mf,
articulation: pendingChordArticulation,
voice: pendingChordVoice
)
)
} else {
parts[partIndex].elements.append(
.chord(
pendingChordPitches,
duration: dur,
dynamic: .mf,
articulation: pendingChordArticulation,
voice: pendingChordVoice
)
)
}
pendingChordPitches.removeAll(keepingCapacity: true)
}
/// Build a `Pitch.named(...)` from MusicXML primitives. Returns nil
/// when `step` is unrecognised or `alter` is outside the supported
/// 50-cent grid.
private func makePitch(
step: String,
alter: Double,
octave: Int
) -> Pitch? {
guard let letter: Letter = _MusicXMLParser.letterForStep(step) else { return nil }
guard let accidental: Accidental = _MusicXMLParser.accidentalForAlter(alter) else { return nil }
return .named(NoteName(letter: letter, accidental: accidental), octave)
}
private static func letterForStep(_ step: String) -> Letter? {
switch step.uppercased() {
case "A": return .a
case "B": return .b
case "C": return .c
case "D": return .d
case "E": return .e
case "F": return .f
case "G": return .g
default: return nil
}
}
private static func accidentalForAlter(_ alter: Double) -> Accidental? {
switch alter {
case -2.0: return .doubleFlat
case -1.5: return .threeQuarterFlat
case -1.0: return .flat
case -0.5: return .quarterFlat
case 0.0: return .natural
case 0.5: return .quarterSharp
case 1.0: return .sharp
case 1.5: return .threeQuarterSharp
case 2.0: return .doubleSharp
default: return nil
}
}
}
/// Mutable per-part accumulator used during parsing.
internal struct _PartBuilder {
let id: String
let name: String
var elements: [ScoreElement] = []
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,290 @@
// Score+MusicXMLAtoms.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension Score {
// MARK: - Internal atom representation
/// The notated kind of a musical event.
enum _AtomKind: Equatable {
case note(Pitch)
case chord([Pitch])
case rest
/// A grace note — emitted as a `<note><grace>` element with no `<duration>`,
/// contributing zero to measure-fill accounting.
case grace(Pitch, slashed: Bool)
/// A mid-voice clef change — emitted as a mid-measure `<attributes><clef>`
/// block with no `<duration>`, contributing zero to measure-fill accounting.
case clefChange(Clef)
/// A sustain-pedal direction — emitted as a `<direction placement="below">`
/// block containing `<pedal type="start|stop" line="yes"/>`, contributing
/// zero to measure-fill accounting.
case pedal(PedalKind)
}
/// One tuplet-bracket annotation on an atom: a `(number, isStart, isStop, localActual, localNormal)` record.
///
/// A single atom can carry two bracket entries when it is simultaneously the
/// first/last note of both an inner and an outer tuplet level (nested tuplets).
///
/// `localActual` / `localNormal` hold the LOCAL ratio of THIS bracket level —
/// i.e. the immediate `Tuplet(actual, inTimeOf: normal)` that introduced this
/// bracket, NOT the cumulative product across all enclosing levels. These are
/// compared against the atom's cumulative `tupletRatio` at emission time: when
/// the two are equal (single-level or a level whose local matches the
/// cumulative) the existing bare self-closing `<tuplet …/>` form is used;
/// when they differ (a nested level whose local ≠ cumulative) the full
/// `<tuplet-actual>`/`<tuplet-normal>` child block is added so readers can
/// display the correct bracket number.
struct _TupletBracket {
/// Bracket number (1 = outermost, 2 = one level in, etc.).
let number: Int
/// True when this atom opens this bracket level.
let isStart: Bool
/// True when this atom closes this bracket level.
let isStop: Bool
/// The LOCAL actual count for this bracket level (not cumulative).
let localActual: Int
/// The LOCAL normal count for this bracket level (not cumulative).
let localNormal: Int
}
/// Slur span annotation placed on an atom by the pre-emission slur pass.
///
/// ## Convention (span-based, no `continue`)
///
/// A maximal run of N consecutive `.legato` notes in the same voice maps to
/// exactly one slur span with ONE `<slur type="start"/>` and ONE
/// `<slur type="stop"/>` (same `number="1"`):
///
/// - `<slur type="start"/>` on the FIRST legato note of the run.
/// - `<slur type="stop"/>` on the note IMMEDIATELY AFTER the run (the first
/// non-legato follower in the same voice). Interior legato notes (2nd..Nth)
/// carry NO `<slur>` element.
/// - When the run reaches the END of the part with no follower, `stop` is
/// placed on the LAST legato note (best-effort; the final note's legato
/// articulation is preserved in the source tree but that note reads
/// non-legato after round-trip — documented lossy edge).
/// - `continue` elements are never emitted.
///
/// Parser round-trip rule (span tracking, per voice):
/// - On `start`: mark current note `.legato`, set `slurActiveByVoice[v] = true`.
/// - While `slurActiveByVoice[v]` and next note carries no `stop`: mark it `.legato`.
/// - On `stop`: stop note is NOT marked legato; set `slurActiveByVoice[v] = false`.
struct _SlurAnnotation {
/// Emit `<slur number="1" type="start"/>` on this note.
let emitStart: Bool
/// Emit `<slur number="1" type="stop"/>` on this note.
let emitStop: Bool
static let none: _SlurAnnotation = _SlurAnnotation(
emitStart: false, emitStop: false
)
}
/// Wedge (hairpin) annotation placed on an atom by the tree-walk wedge pass.
///
/// ## Convention
///
/// When a `.wedge(kind, children)` element is encountered during atom collection,
/// the children are recursed normally and then the FIRST child atom receives
/// `wedgeStart = kind` and the LAST child atom receives `wedgeStop = true`.
///
/// Emission rules:
/// - BEFORE emitting a note that has `wedgeStart != nil`, emit a
/// `<direction placement="below"><direction-type><wedge type="crescendo|diminuendo"/></direction-type></direction>`.
/// - AFTER emitting a note that has `wedgeStop == true`, emit a
/// `<direction placement="below"><direction-type><wedge type="stop"/></direction-type></direction>`.
///
/// A note may simultaneously have both a dynamic direction and a wedge direction —
/// both are emitted (dynamic first, then wedge start). Wedges may cross barlines:
/// the start annotation stays on the original first atom and the stop on the
/// original last atom regardless of measure boundaries. Tied barline-continuation
/// pieces do NOT carry wedge annotations (only the head and tail boundary atoms do).
struct _WedgeAnnotation {
/// When non-nil, emit a wedge-start direction of this kind before this note.
let wedgeStart: WedgeKind?
/// When `true`, emit a wedge-stop direction after this note.
let wedgeStop: Bool
static let none: _WedgeAnnotation = _WedgeAnnotation(
wedgeStart: nil, wedgeStop: false
)
}
/// Glissando (or slide) span annotation placed on an atom by the spanner
/// application pass.
///
/// ## Convention
///
/// A glissando span is a two-note span: `.beginGlissando` on the first
/// note and `.endGlissando` on the second. The encoder emits:
///
/// - START atom: `<glissando type="start" line-type="…" number="1"/>` (or
/// `<slide …>`) inside `<notations>`.
/// - STOP atom: `<glissando type="stop" number="1"/>` (matching element name).
///
/// The stop atom needs to know whether to emit `<glissando>` or `<slide>`.
/// This is stored in `glissandoStopKind`, propagated from the opener's
/// ``Glissando/kind`` during ``Score/validateSpannerBalance(atoms:)`` when
/// the stop matches an open glissando.
struct _GlissandoAnnotation {
/// Non-nil on the START atom of a glissando span; carries the full descriptor.
var glissandoStart: Glissando?
/// `true` on the STOP atom of a glissando span.
var glissandoStop: Bool
/// The element kind (glissando vs slide) for the stop atom.
///
/// Propagated from the opener's ``Glissando/kind`` when the stop is
/// matched to an open span during balance validation. `nil` until validated.
var glissandoStopKind: GlissandoKind?
static let none: _GlissandoAnnotation = _GlissandoAnnotation(
glissandoStart: nil,
glissandoStop: false,
glissandoStopKind: nil
)
}
/// Beam grouping position for a note within a beam group.
///
/// ## Convention
///
/// A maximal run of consecutive beamable (eighth or shorter, non-rest) notes
/// that all fall within the SAME beat (integer quarter-beat from the measure
/// start) forms one beam group:
/// - First note of the group → `.begin`.
/// - Interior notes → `.continue`.
/// - Last note → `.end`.
/// - A lone beamable note (group size 1) → `.none` (flagged, not beamed).
///
/// Only one beam level is emitted (`number="1"`). Secondary beams (e.g. a
/// separate group for 16th sub-divisions within an eighth beam) are not
/// implemented in this phase — a single `number="1"` beam suffices.
///
/// The `<beam>` element is a child of `<note>` placed after `<type>`/`<dot>`/
/// `<time-modification>` and before `<notations>`, per MusicXML 4.0 §3.3.
enum _BeamKind: Equatable {
case none
case begin
case `continue`
case end
}
/// One atomic event produced by the tree walk, before barline splitting.
struct _Atom {
/// The kind of event (note, chord, or rest).
let kind: _AtomKind
/// The element's own nominal duration (used for `<type>`/`<dot>`
/// derivation; for tuplet members this is the printed type, e.g.
/// a triplet-quarter has rawDuration == .quarter).
let rawDuration: NoteDuration
/// Sounding duration in quarter-beats (rawDuration × accumulated
/// tuplet scale). Used for `<duration>` ticks and cursor advance.
let soundingDuration: Fraction
/// Dynamic marking for this event.
///
/// For rests the value is a sentinel (`.mf`) — no `<direction>` is
/// ever emitted for rest atoms regardless of this value.
let dynamic: Dynamic
/// Articulation for notation output.
let articulation: Articulation
/// Voice number (1-based in MusicXML).
let voiceMusicXML: Int
/// Immediate (actual, normal) tuplet ratio — nil when not inside a tuplet.
///
/// `normalType` carries the declared base note value of the enclosing
/// `Tuplet(..., noteDuration:)` at the IMMEDIATE bracket level. When non-nil
/// the encoder emits `<normal-type>` (and `<normal-dot/>` for dotted values)
/// inside `<time-modification>`. When nil (no `noteDuration:` was declared),
/// `<normal-type>` is omitted — output is byte-identical to the pre-existing
/// behaviour.
let tupletRatio: (actual: Int, normal: Int, normalType: NoteDuration?)?
/// Tuplet bracket annotations for this atom, ordered outermost-first.
/// Empty when not at any tuplet boundary.
let tupletBrackets: [_TupletBracket]
/// Slur annotation assigned by ``Score/annotateSlurs(atoms:)``.
///
/// Mutable annotation slot: the annotation passes set it after the atom
/// is collected (see the `withSlur`/`withBeam`/`withWedge…` mutators).
var slur: _SlurAnnotation
/// Beam grouping annotation assigned by ``Score/annotateBeams(atoms:meterMap:)``.
var beam: _BeamKind
/// Wedge (hairpin) annotation assigned during atom collection from `.wedge` elements.
var wedge: _WedgeAnnotation
/// When `true` this atom is a barline-split tied continuation piece;
/// it must NOT emit a `<direction>` even when its dynamic differs
/// from the tracked last-emitted dynamic.
var isTiedContinuation: Bool
/// When `true`, this atom is the START of an authored tie (from a
/// `.note(... tie: true)` element). The atom emits `<tie type="start"/>`
/// and `<tied type="start"/>` in addition to any barline-split ties.
///
/// Distinct from `isTiedContinuation` (barline-split mechanism) — an atom
/// can simultaneously be `tieAuthoredStart == true` and get barline-split
/// (in that case both tie elements are emitted correctly).
var tieAuthoredStart: Bool
/// When `true`, this atom is the STOP of an authored tie (the immediately-
/// following atom after a `tieAuthoredStart` atom, when the pitches match).
/// Emits `<tie type="stop"/>` and `<tied type="stop"/>`.
var tieAuthoredStop: Bool
/// Staff number for this atom (1-based). Used only in multi-staff parts
/// to emit `<staff>k</staff>` on notes and to route pedal directions to
/// the correct staff. In single-staff parts every atom has `staff == 1`
/// and no `<staff>` element is emitted.
let staff: Int
/// Notation display overrides for this atom.
///
/// Set during atom collection from a ``ScoreElement/displayed(_:_:)``
/// wrapper. An all-defaults `NoteDisplay()` (``NoteDisplay/hasOverrides``
/// == `false`) produces byte-identical MusicXML output — no extra elements
/// are emitted.
///
/// Outer `displayed` wins when two `displayed` wrappers nest: the outer
/// display is applied LAST and overwrites any inner display set earlier.
var display: NoteDisplay = NoteDisplay()
/// Glissando (or slide) span annotation assigned by the spanner application
/// pass and validated by ``Score/validateSpannerBalance(atoms:)``.
///
/// An all-defaults `.none` annotation produces byte-identical output — no
/// `<glissando>` or `<slide>` elements are emitted.
var glissando: _GlissandoAnnotation = .none
/// Notation-only marks (extra articulations, techniques, fermatas) set
/// during atom collection from a ``ScoreElement/marked(_:_:)`` wrapper.
///
/// An empty array produces byte-identical MusicXML output — no extra
/// elements are emitted.
var marks: [NotationMark] = []
/// Intra-note dynamic curve points set during atom collection from a
/// ``ScoreElement/dynamicCurve(_:_:)`` wrapper.
///
/// An empty array produces byte-identical MusicXML output — the curve
/// emission path is skipped entirely, and the normal single-`dyn:`
/// direction is emitted as usual.
///
/// For barline-crossing notes, only the HEAD (first) piece carries the
/// curve; the leftover continuation atom always carries an empty array.
var dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
}
/// Key identifying a dynamic direction by its position within a measure, for
/// the per-staff redundant-dynamic collapse in the multi-voice encoder path.
///
/// Two atoms that open at the same metric `onset` on the same `staff` share a
/// key; when ``toMusicXMLString(divisions:collapseRedundantDynamics:)`` collapse
/// is enabled, the second identical dynamic at that key is suppressed. The dict
/// is reset at the start of every measure, so a dynamic re-appearing in a later
/// bar is always emitted.
struct _DynamicDedupKey: Hashable {
/// Onset of the dynamic measured from the start of its measure, in quarter-beats.
let onset: Fraction
/// Staff the dynamic belongs to (1-based).
let staff: Int
}
}
@@ -21,33 +21,129 @@ extension Score {
/// - `<part>` `<measure>` `<note>` blocks with `<pitch>` (`<step>`,
/// `<alter>`, `<octave>`), `<rest/>`, `<duration>`, `<voice>`, and
/// `<chord/>`.
/// - `<attributes>` `<divisions>`, `<time>` (`<beats>` /
/// `<beat-type>`).
/// - `<attributes>` `<divisions>`, `<key>` (`<fifths>`, `<mode>` —
/// first-wins; missing `<key>` defaults to `.cMajor`), `<time>` (`<beats>` /
/// `<beat-type>`), `<clef>` (`<sign>`, `<line>`,
/// `<clef-octave-change>`) — first clef per part wins.
/// - `<direction>` `<sound tempo="X"/>` and `<metronome>`
/// `<per-minute>`.
/// `<per-minute>` — **measure 1** sets ``Score/bpm``; **measures ≥ 2**
/// produce ``TempoChange`` entries in ``Score/tempoChanges`` (first part
/// only; first-in-document wins per measure).
/// - `<notations>` `<articulations>` `<staccato/>` /
/// `<staccatissimo/>` / `<tenuto/>` / `<accent/>` /
/// `<strong-accent/>`.
/// - `<alter>` values on the 50-cent grid: `-2.0`, `-1.5`, `-1.0`,
/// `-0.5`, `0`, `0.5`, `1.0`, `1.5`, `2.0`. Out-of-grid values
/// are silently treated as a missing-pitch note (rest substitution).
/// - `<backup><duration>D</duration></backup>` — rewinds the absolute
/// cursor so that a subsequent voice can be read from the rewound
/// position. Parts that contain `<backup>` are reconstructed as
/// ``ScoreElement/voice(_:_:)`` blocks, one per distinct `<voice>`
/// number, each sorted by absolute beat. Single-voice parts (no
/// `<backup>`) are unaffected and return the same flat element list.
/// - `<forward><duration>D</duration></forward>` — advances the cursor
/// by inserting a silent rest element of the corresponding duration.
///
/// ## Mid-piece tempo changes
///
/// `<direction>` blocks in measures ≥ 2 that contain `<metronome><per-minute>`
/// or `<sound tempo="X"/>` are decoded as ``TempoChange`` entries in
/// ``Score/tempoChanges``. Reading is limited to the **first part** (all parts
/// share identical tempo directions). A measure-1 tempo is the base
/// ``Score/bpm`` and is NOT included in `tempoChanges`. When multiple
/// directions appear in the same measure, the first-in-document order wins
/// (same as `<per-minute>` is preferred over `<sound tempo>` for the base bpm).
///
/// `tempoChanges` is returned sorted ascending by measure number. Playback does
/// **not** realize mid-piece tempo changes — ``ScorePlayer`` and NRT rendering
/// use the single base ``Score/bpm`` throughout (future work).
///
/// ## Repeat / ending barlines
///
/// `<barline location="left">` carrying `<repeat direction="forward"/>` sets
/// a forward repeat at the containing measure number. `<barline location="right">`
/// carrying `<repeat direction="backward"/>` sets a backward repeat.
/// `<ending number="N" type="start"/>` inside a left barline and
/// `<ending number="N" type="stop|discontinue"/>` inside a right barline are
/// paired by number to construct ``Ending`` values. All barlines are read
/// from the **first part** (parts share identical barline structure). The
/// resulting ``RepeatStructure`` is stored on the decoded ``Score/repeats``
/// property. Documents without `<barline>` elements yield ``RepeatStructure/none``.
///
/// Playback does **not** unfold repeats — ``ScorePart/flatten()`` is unchanged
/// (notation-only, future work).
///
/// ## Currently NOT parsed
///
/// - `score-timewise` documents (use `score-partwise` only). Trips
/// ``MusicXMLError/unsupportedTimewiseDocument``.
/// - `<backup>` / `<forward>` (used to express polyphonic voice
/// layering) — voices share the cursor in the v1 parser; multi-
/// voice scores will land out of order.
/// - Tied notes — the `<tie>` element is ignored; a tied pair shows
/// up as two separate ``ScoreEvent``s in the resulting ``Score``.
/// - Tuplets via `<time-modification>` — not surfaced as a Tuplet
/// wrapper; durations come through verbatim, but note that
/// MusicXML triplets typically encode duration AS-IF triplet,
/// meaning `Score.flatten()` will reproduce the timings without
/// needing a Tuplet wrapper.
/// - `<key>`, `<clef>`, `<lyric>`, slurs, beams, ornaments,
/// dynamics directions.
/// wrapper; durations come through verbatim as ``NoteDuration/fraction(_:)``
/// values (exact rational from `<duration>` / `<divisions>`), so
/// `Score.flatten()` will reproduce the timings without needing a
/// Tuplet wrapper.
/// - **Staff grouping** — the `.staff(n, clef:){…}` block structure is not
/// reconstructed. `<staff>` numbers on `<note>` elements are read for clef
/// resolution but discarded for grouping; notes are reconstructed by
/// `<voice>` partitioning only. A grand-staff part round-trips its events
/// and pitches but flattens the explicit staff grouping (documented-lossy).
/// - **Per-part polymetric meter** (``ScorePart/meterMap``) — a part-level
/// meter override is export-faithful but not reconstructed on decode. The
/// decoded ``Score/meterMap`` is read from the first part only; per-part
/// overrides do not survive the round trip.
/// - **Sections / rehearsal marks** — ``ScoreSection`` values are not
/// reconstructed from MusicXML (the section boundaries and rehearsal-mark
/// labels are emit-only in v1). The decoded ``Score/rehearsalMarks`` map is
/// always empty after a round-trip; `<rehearsal>` elements in the source
/// document are silently skipped.
/// - `<lyric>`, ornaments.
/// - **`<defaults>` / `<page-layout>`** — page layout information is emit-only in v1.
/// The `<defaults>` block (including `<scaling>` and `<page-layout>`) is silently
/// skipped on decode; ``Score/pageLayout`` is always `nil` after a round-trip.
///
/// ## Dynamic directions
///
/// `<direction>/<direction-type>/<dynamics>` blocks set the current
/// dynamic that applies to subsequently-committed notes and chords
/// (sticky — the dynamic stays until the next direction). Named child
/// elements (`<pp/>` … `<fff/>`) map to the corresponding ``Dynamic``
/// case. `<other-dynamics>` text that parses as a `Double` maps to
/// ``Dynamic/raw(_:)``. Directions without a recognized `<dynamics>`
/// child are ignored for dynamic purposes.
///
/// The current dynamic is reset to `.mf` at the start of each part.
/// Multi-voice: a `<direction>` applies to all voices from the point it
/// appears in the document until the next direction. The sticky model is
/// correct for the common single-direction-per-note encoding produced by
/// Lyrebird's encoder, and for scores where dynamics are annotated once
/// per passage.
///
/// `<sound dynamics="X"/>` elements are NOT parsed for dynamic purposes —
/// velocity is the Lyrebird-side playback path (`ScoreEvent.velocity`).
///
/// ## Tie-merge
///
/// `<tie type="stop"/>` notes are merged into their immediately-preceding
/// same-pitch, same-voice note (the bounded backward scan in the parser
/// only matches the directly-adjacent predecessor). Merged durations
/// use exact ``Fraction`` arithmetic (Fix 1). A stray
/// `<tie type="stop"/>` with no immediately-adjacent matching predecessor
/// (Fix 2) is emitted as a normal new note rather than merging
/// into an unrelated earlier note of the same pitch.
///
/// ## Authored-tie round-trip
///
/// An authored tie (`Note(..., tie: true)` in the DSL) is encoded as two
/// tied noteheads — `<tie type="start"/>` on the first and `<tie type="stop"/>`
/// on the second, plus `<tied>` in `<notations>`. The parser's tie-merge
/// merges the two noteheads back into ONE ``ScoreElement`` with the summed
/// duration. This is **event-preserving** (the event round-trip is exact:
/// ``flatten()`` produces the same ``ScoreEvent`` list) but
/// **structure-collapsing** (the two-notehead authored tie is folded into
/// one element, consistent with how barline-split ties already round-trip).
/// The `tie: false` field on the round-tripped element reflects that the
/// structural authoring information is not preserved — only the sounding
/// event is.
///
/// - Parameter data: UTF-8 MusicXML byte data.
/// - Returns: A ``Score`` reconstructed from the document.
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,53 @@
// _NoteContext.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Per-`<note>` accumulator state for ``_MusicXMLParser``.
///
/// Every field is reset together at each `<note>` open (one
/// `noteContext = _NoteContext()` assignment instead of N individual resets)
/// and read in `commitCurrentNote()` — the "reset on open, commit on close"
/// pattern. Document- and part-level state (parts, meter map, repeat structure,
/// tempo changes, pickup tracking, the per-voice slur/wedge maps, the `in…`
/// element-nesting flags) stays on the parser class; only state that logically
/// belongs to the single note currently being parsed lives here.
///
/// The default values are the reset values, so `_NoteContext()` is the canonical
/// "fresh note" state.
internal struct _NoteContext {
/// `<rest/>` child seen — commit as a rest rather than a pitched note.
var isRest: Bool = false
/// `<chord/>` child seen — this note stacks onto the previous note's onset.
var isChord: Bool = false
/// `<grace>` child seen (no `<duration>`) — commit as a `.grace` element
/// without advancing the beat cursor.
var isGrace: Bool = false
/// `<grace slash="yes"/>`. `true` = acciaccatura; `false` = appoggiatura
/// (no slash attribute or `slash="no"`).
var graceSlashed: Bool = false
/// `<pitch><step>` letter (`"C"`…`"B"`); `nil` until `<step>` is read.
var pitchStep: String? = nil
/// `<pitch><alter>` chromatic offset in semitones (sharp `+`, flat `−`).
var pitchAlter: Double = 0.0
/// `<pitch><octave>`. Reset to the middle-C octave before `<octave>` is read.
var pitchOctave: Int = _MusicXMLParser.defaultMidiOctave
/// `<duration>` in divisions (ticks); `0` until read.
var durationDivisions: Int = 0
/// `<voice>` number (1-based). Default `1` when no `<voice>` is present.
var voice: Int = 1
/// `<staff>` number (1-based). Default `1` for single-staff parts.
var staff: Int = 1
/// Articulation parsed from `<notations><articulations>` children.
var articulation: Articulation = .normal
/// `<tie type="stop"/>` present on this note — drives tie-merge on decode.
/// (`<tie type="start"/>` is not tracked; the merge is stop-driven.)
var tieStop: Bool = false
/// `<slur type="start"/>` present on this note element.
var hasSlurStart: Bool = false
/// `<slur type="stop"/>` present on this note element.
var hasSlurStop: Bool = false
}
@@ -0,0 +1,38 @@
// _PartBuilder.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Mutable per-part accumulator used during parsing.
internal struct _PartBuilder {
let id: String
let name: String
/// Clef read from the first `<clef>` element in this part. Defaults to
/// `.treble`; set once (first-clef-per-part wins) when the first `<clef>`
/// block is encountered — `clefWasSet` distinguishes "not yet parsed" from
/// a legitimately-parsed treble clef, so a later mid-part `<clef>` change
/// does not overwrite the first.
var clef: Clef = .treble
var clefWasSet: Bool = false
/// Key signature read from the first `<key>` element in this part.
/// Nil until a `<key>` block is parsed. Used to set a per-part override
/// when this part's key differs from the first part's key.
var keySignature: KeySignature? = nil
/// Transpose read from the `<transpose>` element in this part.
/// Nil until a `<transpose>` block is parsed.
var transpose: Transpose? = nil
/// Absolute cursor position in divisions. Updated after each note / rest is
/// committed; rewound by `<backup>` and advanced by `<forward>`.
var absoluteCursorDivisions: Int = 0
/// Beat-stamped events collected in document order. Voice grouping and
/// element reconstruction happen in `_MusicXMLParser.parsedScore()`.
var entries: [_PartEntry] = []
/// Replace the ScoreElement at the given index (used by tie-merge).
mutating func replaceElement(at index: Int, with element: ScoreElement) {
entries[index].element = element
}
}
@@ -0,0 +1,33 @@
// _PartEntry.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// One parsed musical event stored with its absolute beat position and voice number.
///
/// The parser accumulates `_PartEntry` values instead of raw `ScoreElement` values
/// so that `<backup>` / `<forward>` cursor rewinds can be handled correctly:
/// each note's beat is captured from the absolute cursor at commit time, allowing
/// multi-voice parts to be reconstructed as `Voice(n){…}` blocks after all events
/// have been collected. Single-voice parts reconstruct the original flat element
/// list.
///
/// `wedgeStart` and `wedgeStop` carry wedge (hairpin) span boundaries parsed from
/// `<wedge>` direction elements. These are used by `reconstructElements` to wrap
/// wedge-spanned entry runs in `.wedge(kind, [...])` blocks.
internal struct _PartEntry {
/// Absolute beat position of this element (cursor / divisions at commit time).
let beat: Fraction
/// MusicXML voice number (`<voice>` text value, 1-based). Rests carry the
/// voice of the current note context (default 1).
let voice: Int
/// The unflattened element (note, rest, or chord).
var element: ScoreElement
/// When non-nil, a wedge span of this kind opens BEFORE this entry's note.
var wedgeStart: WedgeKind? = nil
/// When `true`, a wedge span closes AFTER this entry's note.
var wedgeStop: Bool = false
}
+104
View File
@@ -0,0 +1,104 @@
// NotationMark.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A notation-only mark applied to a note or chord via the `marks:` parameter
/// on ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` and the `Chord`
/// family of DSL functions.
///
/// Marks are **emit-only**: they produce MusicXML output inside `<notations>`
/// but do NOT affect playback, velocity, or the flattened ``ScoreEvent`` list.
/// ``Score/fromMusicXML(data:)`` does not parse marks back (same as ``NoteDisplay``).
///
/// ## Relationship to `art:`
///
/// The `art: Articulation` parameter remains unchanged — it still drives BOTH
/// performance scaling (velocity bonus, duration scale) AND its own notation glyph
/// in `<articulations>`. `marks:` is purely additive: it appends extra glyphs and
/// technique symbols without touching the `art:` articulation. When `art:` and
/// `marks:` overlap on the same articulation glyph (e.g. `art: .staccato` and
/// `marks: [.staccato]`), the glyph is emitted once (deduplicated).
///
/// ## DTD emission order inside `<notations>`
///
/// Technical markings are emitted first (`<technical>`), then articulations
/// (`<articulations>`), then fermatas (`<fermata>`), matching the MusicXML 4.0 DTD
/// child element order.
///
/// ## Cases
///
/// ### Articulation glyphs (notation only)
/// - ``staccato`` — a dot above/below the notehead.
/// - ``staccatissimo`` — a wedge-shaped dot (very short detachment).
/// - ``tenuto`` — a horizontal dash (held to full value).
/// - ``accent`` — a `>` mark (stressed attack).
/// - ``marcato`` — a `^` mark (strongly stressed, usually short).
///
/// ### String / instrumental techniques
/// - ``leftHandPizzicato`` — left-hand pizzicato (`+` sign); emitted as `<stopped/>`.
/// - ``snapPizzicato`` — snap (Bartók) pizzicato; emitted as `<snap-pizzicato/>`.
/// - ``upBow`` — up-bow stroke; emitted as `<up-bow/>`.
/// - ``downBow`` — down-bow stroke; emitted as `<down-bow/>`.
/// - ``harmonic`` — natural or artificial harmonic; emitted as `<harmonic/>`.
/// - ``openString`` — open string ring; emitted as `<open-string/>`.
///
/// ### Fermata
/// - ``fermata(_:)`` — a fermata with a ``FermataShape``.
public enum NotationMark: Hashable, Sendable {
// MARK: - Articulation glyphs (notation-only)
/// Staccato dot — short detachment. Emitted as `<staccato/>` in
/// `<articulations>`. Does NOT affect performance scaling (use `art:` for that).
case staccato
/// Staccatissimo — very short, wedge-shaped detachment. Emitted as
/// `<staccatissimo/>` in `<articulations>`.
case staccatissimo
/// Tenuto dash — held to full value. Emitted as `<tenuto/>` in
/// `<articulations>`.
case tenuto
/// Accent `>` — stressed attack. Emitted as `<accent/>` in `<articulations>`.
case accent
/// Marcato `^` — strongly stressed, usually short. Emitted as
/// `<strong-accent/>` in `<articulations>`.
case marcato
// MARK: - String / instrumental techniques
/// Left-hand pizzicato (the `+` glyph). Emitted as `<stopped/>` inside
/// `<technical>`.
///
/// > Note: MusicXML has no dedicated left-hand-pizzicato element; `<stopped/>`
/// > is the standard MusicXML element that produces the `+` glyph used for
/// > left-hand pizzicato in string notation.
case leftHandPizzicato
/// Snap (Bartók) pizzicato. Emitted as `<snap-pizzicato/>` inside `<technical>`.
case snapPizzicato
/// Up-bow stroke. Emitted as `<up-bow/>` inside `<technical>`.
case upBow
/// Down-bow stroke. Emitted as `<down-bow/>` inside `<technical>`.
case downBow
/// Harmonic (natural or artificial). Emitted as `<harmonic/>` inside `<technical>`.
case harmonic
/// Open string ring (circle glyph). Emitted as `<open-string/>` inside `<technical>`.
case openString
// MARK: - Fermata
/// A fermata with the given shape. Emitted as `<fermata>` (or self-closing
/// `<fermata/>` for `.normal`) directly inside `<notations>`.
///
/// - Parameter shape: The fermata shape (see ``FermataShape``).
case fermata(FermataShape)
}
+105
View File
@@ -0,0 +1,105 @@
// NoteDisplay.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Per-note notation display overrides — applied to a single note or chord
/// element via the `display:` parameter of the DSL constructors.
///
/// `NoteDisplay` controls four independent visual properties:
///
/// - ``notehead``: Shape of the notehead (`x`, `diamond`, `none` for hidden, etc.).
/// See ``Notehead`` for the full set. `nil` keeps the default notehead.
/// - ``size``: Note-type size scale (`cue`, `large`, or `nil`/`normal`). Maps to the
/// `size=` attribute on the MusicXML `<type>` element. Scales the whole note
/// (head + stem + beam) — MusicXML has no per-head percentage. See ``NoteSize``.
/// - ``hideStem``: When `true`, emits `<stem>none</stem>` on the note.
/// - ``hideBeam``: When `true`, treats the note as non-beamable so any beam run
/// breaks at this note and no `<beam>` element is emitted for it.
///
/// An all-defaults `NoteDisplay()` value has ``hasOverrides`` == `false`, so a
/// note wrapped in `.displayed(NoteDisplay(), .note(…))` produces **byte-identical**
/// MusicXML output to the same unwrapped note.
///
/// > Note: `NoteDisplay` is **emit-only**. ``Score/fromMusicXML(data:)`` does not
/// > parse `<notehead>`, `<stem>`, or the `size=` attribute back into `NoteDisplay`.
///
/// ## Usage
///
/// ```swift
/// // X notehead, cue size, no stem.
/// Note(.c, 5, dur: .quarter, display: NoteDisplay(
/// notehead: .x,
/// size: .cue,
/// hideStem: true
/// ))
///
/// // Hidden notehead.
/// Note(.e, 4, dur: .eighth, display: NoteDisplay(notehead: .hidden))
///
/// // Compose with spanners.
/// Note(.d, 5, dur: .quarter, spanners: [.beginSlur], display: NoteDisplay(hideStem: true))
/// ```
public struct NoteDisplay: Sendable, Hashable {
/// Custom notehead shape, or `nil` to keep the default notehead.
///
/// `.hidden` hides the notehead entirely. `.other(raw)` passes a raw MusicXML
/// notehead value through verbatim (XML-escaped at emission).
public var notehead: Notehead?
/// Note-type size scale, or `nil` for normal size (no `size=` attribute emitted).
///
/// Maps to the `size=` attribute on the MusicXML `<type>` element. `.cue` and
/// `.large` emit the attribute; `.normal` and `nil` both suppress it (no attribute).
public var size: NoteSize?
/// When `true`, emits `<stem>none</stem>` on this note (after `<time-modification>`
/// and before `<notehead>` / `<staff>`, per MusicXML 4.0 child-element order).
///
/// Ignored for rests (which have no stem in any case).
public var hideStem: Bool
/// When `true`, this note is excluded from beam grouping — any beam run
/// breaks at this note and no `<beam>` element is emitted for it.
///
/// Use for isolated flagged eighth notes that should not be beamed to their
/// neighbours, or for stemless notes that cannot be beamed.
public var hideBeam: Bool
/// Create a `NoteDisplay` with the given property overrides.
///
/// - Parameters:
/// - notehead: Notehead shape. `nil` = default. `.hidden` = hidden notehead.
/// - size: Note-type size. `nil` or `.normal` = default size (no attribute).
/// - hideStem: When `true`, emits `<stem>none</stem>`. Defaults to `false`.
/// - hideBeam: When `true`, breaks beam grouping at this note. Defaults to `false`.
public init(
notehead: Notehead? = nil,
size: NoteSize? = nil,
hideStem: Bool = false,
hideBeam: Bool = false
) {
self.notehead = notehead
self.size = size
self.hideStem = hideStem
self.hideBeam = hideBeam
}
/// `true` when any property differs from the all-defaults state.
///
/// An all-defaults `NoteDisplay()` with `hasOverrides == false` produces
/// byte-identical MusicXML output to a note without any display wrapper.
///
/// `size: .normal` is treated the same as `size: nil` for this check —
/// both produce no `size=` attribute and are therefore not overrides.
/// Similarly, `notehead: nil` and `size: nil` (or `.normal`) contribute
/// no override; only `hideStem`, `hideBeam`, a non-nil notehead, or a
/// size of `.cue` / `.large` activate an override.
public var hasOverrides: Bool {
notehead != nil || (size?.musicXMLTypeSize != nil) || hideStem || hideBeam
}
}
+59 -11
View File
@@ -14,15 +14,19 @@ import Foundation
/// to eliminate FP drift across nested tuplets; only the final
/// ``ScoreEvent/beat`` is converted to `Double`.
///
/// Values:
/// Values (American name — British name — beats):
///
/// - ``whole`` — 4 beats (`4/1`)
/// - ``half`` — 2 beats (`2/1`)
/// - ``quarter`` — 1 beat (`1/1`)
/// - ``eighth`` — 0.5 beats (`1/2`)
/// - ``sixteenth`` — 0.25 beats (`1/4`)
/// - ``thirtySecond`` — 0.125 beats (`1/8`)
/// - ``sixtyFourth`` — 0.0625 beats (`1/16`)
/// - ``doubleWhole`` / ``breve`` — 8 beats (`8/1`)
/// - ``whole`` / ``semibreve`` — 4 beats (`4/1`)
/// - ``half`` / ``minim`` — 2 beats (`2/1`)
/// - ``quarter`` / ``crotchet`` — 1 beat (`1/1`)
/// - ``eighth`` / ``quaver`` — 0.5 beats (`1/2`)
/// - ``sixteenth`` / ``semiquaver`` — 0.25 beats (`1/4`)
/// - ``thirtySecond`` / ``demisemiquaver`` — 0.125 beats (`1/8`)
/// - ``sixtyFourth`` / ``hemidemisemiquaver`` — 0.0625 beats (`1/16`)
///
/// The British names are aliases for the identical underlying values, so e.g.
/// `NoteDuration.crotchet == NoteDuration.quarter`.
public enum NoteDuration: Hashable, Sendable {
/// Exact rational value. Preferred — composes losslessly under tuplet scaling.
@@ -31,8 +35,11 @@ public enum NoteDuration: Hashable, Sendable {
/// Arbitrary floating-point beats. Lossy under nested tuplet scaling.
case beats(Double)
// MARK: - Named conveniences
// MARK: - Named conveniences (American names)
/// Double whole note (breve) — 8 beats (`8/1`). Exceeds a single 4/4 bar; the
/// MusicXML encoder splits it across barlines when it does not fit a measure.
public static let doubleWhole: NoteDuration = .fraction(Fraction(num: 8, den: 1))
public static let whole: NoteDuration = .fraction(Fraction(num: 4, den: 1))
public static let half: NoteDuration = .fraction(Fraction(num: 2, den: 1))
public static let quarter: NoteDuration = .fraction(Fraction(num: 1, den: 1))
@@ -42,13 +49,32 @@ public enum NoteDuration: Hashable, Sendable {
public static let sixtyFourth: NoteDuration = .fraction(Fraction(num: 1, den: 16))
public static let zero: NoteDuration = .fraction(.zero)
// MARK: - Named conveniences (British / traditional names)
/// Breve — British name for ``doubleWhole`` (8 beats).
public static let breve: NoteDuration = .doubleWhole
/// Semibreve — British name for ``whole`` (4 beats).
public static let semibreve: NoteDuration = .whole
/// Minim — British name for ``half`` (2 beats).
public static let minim: NoteDuration = .half
/// Crotchet — British name for ``quarter`` (1 beat).
public static let crotchet: NoteDuration = .quarter
/// Quaver — British name for ``eighth`` (0.5 beats).
public static let quaver: NoteDuration = .eighth
/// Semiquaver — British name for ``sixteenth`` (0.25 beats).
public static let semiquaver: NoteDuration = .sixteenth
/// Demisemiquaver — British name for ``thirtySecond`` (0.125 beats).
public static let demisemiquaver: NoteDuration = .thirtySecond
/// Hemidemisemiquaver — British name for ``sixtyFourth`` (0.0625 beats).
public static let hemidemisemiquaver: NoteDuration = .sixtyFourth
// MARK: - Modifier multipliers
/// Multiplier used by ``dotted(_:)``: `3/2`.
public static let dottedMultiplier: Double = 1.5
static let dottedMultiplier: Double = 1.5
/// Multiplier used by ``doubleDotted(_:)``: `7/4`.
public static let doubleDottedMultiplier: Double = 1.75
static let doubleDottedMultiplier: Double = 1.75
// MARK: - Modifiers
@@ -70,6 +96,28 @@ public enum NoteDuration: Hashable, Sendable {
}
}
// MARK: - Dot conveniences
/// This duration with one augmentation dot — `self × 3/2`.
///
/// Reads naturally at the call site as a property: `.quarter.dotted`,
/// `.half.dotted`, `.eighth.dotted`. Equivalent to ``dotted(_:)``.
public var dotted: NoteDuration {
NoteDuration.dotted(self)
}
/// This duration with two augmentation dots — `self × 7/4`.
///
/// Use `.quarter.doubleDotted` for a double-dotted note. Equivalent to
/// ``doubleDotted(_:)``.
///
/// > Note: A double-dotted note is `× 7/4` (a dot, then half that dot), NOT
/// > `× 9/4`. Chaining `.dotted.dotted` would give `× 9/4` (a dot of a dot),
/// > which is not the notated double dot — use `.doubleDotted` instead.
public var doubleDotted: NoteDuration {
NoteDuration.doubleDotted(self)
}
// MARK: - Arithmetic
/// Multiply by a fraction. `.beats` falls back to `Double × fraction.double`.
+42
View File
@@ -0,0 +1,42 @@
// NoteSize.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// The visual size scale of a note in MusicXML output.
///
/// Expressed as the `size` attribute on the MusicXML `<type>` element
/// (`<type size="cue">eighth</type>`). Scales the entire note (head, stem,
/// flag/beam, and ledger lines) — MusicXML has no per-notehead percentage
/// scaling separate from the note-type size attribute.
///
/// Set via ``NoteDisplay/size`` and applied through the `display:` parameter
/// of ``Note(_:dur:dyn:art:voice:tie:spanners:display:)`` or
/// ``Chord(_:dur:dyn:art:voice:tie:spanners:display:)``.
///
/// > Note: Note size is **emit-only** — ``Score/fromMusicXML(data:)`` does not
/// > parse the `size` attribute back into `NoteDisplay`.
public enum NoteSize: Sendable, Hashable {
/// Small cue-note size — the `size="cue"` attribute on `<type>`.
case cue
/// Normal (default) size — no `size` attribute is emitted on `<type>`.
case normal
/// Large note size — the `size="large"` attribute on `<type>`.
case large
/// The MusicXML `size` attribute value for the `<type>` element.
///
/// Returns `nil` for `.normal` (no attribute is written, keeping output
/// byte-identical to the default). Returns `"cue"` or `"large"` for the
/// named sizes.
public var musicXMLTypeSize: String? {
switch self {
case .cue: return "cue"
case .normal: return nil
case .large: return "large"
}
}
}
+77
View File
@@ -0,0 +1,77 @@
// Notehead.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// The visual shape of a notehead in MusicXML output.
///
/// Most scores use the default `.normal` notehead. Percussion, extended
/// technique, and educational notation frequently require alternative shapes.
/// `.hidden` suppresses the notehead entirely (invisible note). `.other(_:)`
/// passes a raw MusicXML notehead value through verbatim for any shape not
/// covered by the named cases.
///
/// The hidden case is named `.hidden` (not `.none`) deliberately: in a
/// `Notehead?` context — e.g. `NoteDisplay(notehead: .none)` — the bare `.none`
/// would resolve to `Optional<Notehead>.none` (i.e. `nil`, no override) rather
/// than the hidden notehead. `.hidden` has no such ambiguity.
///
/// Set via ``NoteDisplay/notehead`` and applied to note/chord elements through
/// the `display:` parameter of ``Note(_:dur:dyn:art:voice:tie:spanners:display:)``
/// or ``Chord(_:dur:dyn:art:voice:tie:spanners:display:)``.
///
/// > Note: Notehead shapes are **emit-only** — ``Score/fromMusicXML(data:)``
/// > does not parse `<notehead>` back into `NoteDisplay`.
public enum Notehead: Sendable, Hashable {
/// Standard filled notehead (default for most music).
case normal
/// X-shaped notehead — common for percussion or spoken-voice notation.
case x
/// Diamond-shaped notehead — natural harmonics, col legno, or Bartók pizzicato.
case diamond
/// Triangle-shaped notehead.
case triangle
/// Slash notehead — rhythmic notation / jazz comping.
case slash
/// Cross notehead (plus sign shape).
case cross
/// Circle-X notehead — choked cymbal or Bartók pizzicato variant.
case circleX
/// Square notehead.
case square
/// Hidden notehead — the note is present in the score data but rendered
/// with no visible head. Use for cue notes or spacer notes. Named `.hidden`
/// (not `.none`) to avoid colliding with `Optional<Notehead>.none`.
case hidden
/// Raw MusicXML notehead value passed through verbatim.
///
/// Use for any notehead shape not covered by the named cases. The value is
/// XML-escaped before emission so reserved characters (`<`, `&`, etc.) are safe.
///
/// Example: `Notehead.other("cluster")` → `<notehead>cluster</notehead>`.
case other(String)
/// The MusicXML `<notehead>` element body text for this shape.
///
/// `.normal` → `"normal"`, `.x` → `"x"`, `.diamond` → `"diamond"`,
/// `.triangle` → `"triangle"`, `.slash` → `"slash"`, `.cross` → `"cross"`,
/// `.circleX` → `"circle-x"`, `.square` → `"square"`, `.hidden` → `"none"`,
/// `.other(raw)` → the raw string (caller-controlled, XML-escaped at emission).
public var musicXMLValue: String {
switch self {
case .normal: return "normal"
case .x: return "x"
case .diamond: return "diamond"
case .triangle: return "triangle"
case .slash: return "slash"
case .cross: return "cross"
case .circleX: return "circle-x"
case .square: return "square"
case .hidden: return "none"
case .other(let s): return s
}
}
}
+299
View File
@@ -0,0 +1,299 @@
// PageLayout.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Score-level page layout specification.
///
/// A `PageLayout` value attached to a ``Score`` causes the MusicXML encoder to emit a
/// `<defaults>` block immediately after `<score-partwise>` and before `<part-list>`.
/// When `Score.pageLayout` is `nil` (the default), no `<defaults>` block is emitted
/// and the encoder output is byte-identical to scores built without this type.
///
/// ## Tenths model
///
/// MusicXML page dimensions are expressed in **tenths of a staff-space** — a unit that
/// scales with notation size. The ``PageLayout/Scaling`` sub-type declares the mapping:
/// ``PageLayout/Scaling/millimeters`` physical mm correspond to
/// ``PageLayout/Scaling/tenths`` staff-space tenths. All page dimensions and margin
/// values in this struct are stored as physical millimeters; the encoder converts them
/// to tenths automatically.
///
/// ## Orientation
///
/// MusicXML has no explicit landscape flag. Orientation is encoded by swapping the
/// physical width and height: portrait emits the size's natural `(width, height)`;
/// landscape emits `(height, width)`.
///
/// ## Usage
///
/// ```swift
/// let score = Score(bpm: 120, pageLayout: PageLayout(size: .a4, orientation: .landscape)) {
/// Part("lead") { Note(.c, 4, dur: .quarter) }
/// }
/// let xml = score.toMusicXMLString()
/// ```
public struct PageLayout: Sendable, Hashable {
// MARK: - Page size constants (portrait mm)
private static let letterWidthMM: Double = 215.9
private static let letterHeightMM: Double = 279.4
private static let legalWidthMM: Double = 215.9
private static let legalHeightMM: Double = 355.6
private static let tabloidWidthMM: Double = 279.4
private static let tabloidHeightMM: Double = 431.8
private static let a4WidthMM: Double = 210.0
private static let a4HeightMM: Double = 297.0
private static let a3WidthMM: Double = 297.0
private static let a3HeightMM: Double = 420.0
// MARK: - Default margin constants (mm)
private static let defaultLeftMarginMM: Double = 15.0
private static let defaultRightMarginMM: Double = 15.0
private static let defaultTopMarginMM: Double = 15.0
private static let defaultBottomMarginMM: Double = 15.0
// MARK: - Default scaling constants
private static let defaultScalingMillimeters: Double = 7.0
private static let defaultScalingTenths: Double = 40.0
// MARK: - PageSize
/// Standard and custom physical page sizes.
///
/// All cases store portrait (width ≤ height) physical dimensions.
/// ``PageLayout/Orientation`` controls whether width/height are swapped at encode time.
public enum PageSize: Sendable, Hashable {
/// US Letter: 215.9 × 279.4 mm portrait.
case letter
/// US Legal: 215.9 × 355.6 mm portrait.
case legal
/// US Tabloid / Ledger: 279.4 × 431.8 mm portrait.
case tabloid
/// ISO A4: 210 × 297 mm portrait.
case a4
/// ISO A3: 297 × 420 mm portrait.
case a3
/// Arbitrary page size.
///
/// Supply the **portrait** dimensions — width ≤ height by convention.
/// ``PageLayout/Orientation`` will swap them when encoding landscape.
///
/// - Parameters:
/// - widthMillimeters: Physical width of the portrait sheet, in mm. Must be > 0.
/// - heightMillimeters: Physical height of the portrait sheet, in mm. Must be > 0.
case custom(widthMillimeters: Double, heightMillimeters: Double)
/// Portrait (width ≤ height) physical dimensions for this page size, in mm.
public var portraitMillimeters: (width: Double, height: Double) {
switch self {
case .letter:
return (width: PageLayout.letterWidthMM, height: PageLayout.letterHeightMM)
case .legal:
return (width: PageLayout.legalWidthMM, height: PageLayout.legalHeightMM)
case .tabloid:
return (width: PageLayout.tabloidWidthMM, height: PageLayout.tabloidHeightMM)
case .a4:
return (width: PageLayout.a4WidthMM, height: PageLayout.a4HeightMM)
case .a3:
return (width: PageLayout.a3WidthMM, height: PageLayout.a3HeightMM)
case .custom(let w, let h):
return (width: w, height: h)
}
}
}
// MARK: - Orientation
/// Page orientation: portrait keeps the natural (width ≤ height) layout;
/// landscape swaps width and height in the MusicXML output.
public enum Orientation: Sendable, Hashable {
/// Natural portrait orientation — width ≤ height.
case portrait
/// Landscape orientation — width and height are swapped during encoding.
case landscape
}
// MARK: - Margins
/// Physical margins for one page side (odd or even), in millimeters.
public struct Margins: Sendable, Hashable {
/// Left margin in mm.
public var leftMillimeters: Double
/// Right margin in mm.
public var rightMillimeters: Double
/// Top margin in mm.
public var topMillimeters: Double
/// Bottom margin in mm.
public var bottomMillimeters: Double
/// Create margins with independent sides.
///
/// - Parameters:
/// - leftMillimeters: Left margin, in mm.
/// - rightMillimeters: Right margin, in mm.
/// - topMillimeters: Top margin, in mm.
/// - bottomMillimeters: Bottom margin, in mm.
public init(
leftMillimeters: Double,
rightMillimeters: Double,
topMillimeters: Double,
bottomMillimeters: Double
) {
self.leftMillimeters = leftMillimeters
self.rightMillimeters = rightMillimeters
self.topMillimeters = topMillimeters
self.bottomMillimeters = bottomMillimeters
}
/// Create margins with all four sides equal.
///
/// - Parameter uniformMillimeters: Margin applied to all four sides, in mm.
public init(uniformMillimeters: Double) {
self.leftMillimeters = uniformMillimeters
self.rightMillimeters = uniformMillimeters
self.topMillimeters = uniformMillimeters
self.bottomMillimeters = uniformMillimeters
}
/// Default margins: 15 mm on all sides.
public static let `default`: Margins = Margins(
leftMillimeters: PageLayout.defaultLeftMarginMM,
rightMillimeters: PageLayout.defaultRightMarginMM,
topMillimeters: PageLayout.defaultTopMarginMM,
bottomMillimeters: PageLayout.defaultBottomMarginMM
)
}
// MARK: - Scaling
/// MusicXML `<scaling>` specification: the physical–tenths conversion factor.
///
/// MusicXML represents distances in **tenths** of a staff-space. `millimeters`
/// states how many physical mm correspond to `tenths` staff-space tenths.
/// The conversion factor is `tenths / millimeters` tenths-per-mm.
///
/// Default: 7.0 mm = 40.0 tenths (≈ 5.714 tenths/mm), which gives a staff-space
/// height of 7 mm — a common engraving default.
public struct Scaling: Sendable, Hashable {
private static let defaultMillimeters: Double = 7.0
private static let defaultTenths: Double = 40.0
/// Physical millimeters represented by `tenths`. Default: `7.0`.
public var millimeters: Double
/// Staff-space tenths represented by `millimeters` physical mm. Default: `40.0`.
public var tenths: Double
/// Create a scaling spec.
///
/// - Parameters:
/// - millimeters: Physical mm that correspond to `tenths`. Must be > 0.
/// Defaults to `7.0`.
/// - tenths: Staff-space tenths that correspond to `millimeters`. Must be > 0.
/// Defaults to `40.0`.
// Note: the default-argument literals below intentionally duplicate
// `defaultMillimeters` / `defaultTenths` — Swift forbids referencing a
// static member in a default-parameter expression, so the values are
// repeated here as literals and kept in sync with the named constants.
public init(
millimeters: Double = 7.0,
tenths: Double = 40.0
) {
self.millimeters = millimeters
self.tenths = tenths
}
/// Default scaling: 7.0 mm = 40.0 tenths.
public static let `default`: Scaling = Scaling()
}
// MARK: - Properties
/// Physical page size (portrait dimensions).
public var size: PageSize
/// Page orientation. Landscape swaps width and height during MusicXML encoding.
public var orientation: Orientation
/// Margins for odd (recto) pages.
public var oddMargins: Margins
/// Margins for even (verso) pages.
public var evenMargins: Margins
/// Physical–tenths conversion used throughout this layout.
public var scaling: Scaling
// MARK: - Initialisers
/// Create a page layout with symmetric margins (odd == even).
///
/// - Parameters:
/// - size: Physical page size (portrait dimensions). Defaults to ``PageSize/letter``.
/// - orientation: Portrait or landscape. Defaults to ``Orientation/portrait``.
/// - margins: Margins applied to both odd and even pages. Defaults to
/// ``Margins/default`` (15 mm all sides).
/// - scaling: Physical–tenths conversion. Defaults to ``Scaling/default``
/// (7.0 mm = 40.0 tenths).
public init(
size: PageSize = .letter,
orientation: Orientation = .portrait,
margins: Margins = .default,
scaling: Scaling = .default
) {
self.size = size
self.orientation = orientation
self.oddMargins = margins
self.evenMargins = margins
self.scaling = scaling
}
/// Create a page layout with independent odd and even margins.
///
/// - Parameters:
/// - size: Physical page size (portrait dimensions).
/// - orientation: Portrait or landscape.
/// - oddMargins: Margins for odd (recto) pages.
/// - evenMargins: Margins for even (verso) pages.
/// - scaling: Physical–tenths conversion. Defaults to ``Scaling/default``.
public init(
size: PageSize,
orientation: Orientation,
oddMargins: Margins,
evenMargins: Margins,
scaling: Scaling = .default
) {
self.size = size
self.orientation = orientation
self.oddMargins = oddMargins
self.evenMargins = evenMargins
self.scaling = scaling
}
// MARK: - Internal encoder helpers
/// Tenths per millimeter derived from the scaling spec.
var tenthsPerMillimeter: Double {
scaling.tenths / scaling.millimeters
}
/// Page width in tenths, accounting for orientation.
///
/// Portrait: portrait width. Landscape: portrait height (swapped).
var pageWidthTenths: Double {
let portrait: (width: Double, height: Double) = size.portraitMillimeters
let physicalWidth: Double = orientation == .landscape ? portrait.height : portrait.width
return physicalWidth * tenthsPerMillimeter
}
/// Page height in tenths, accounting for orientation.
///
/// Portrait: portrait height. Landscape: portrait width (swapped).
var pageHeightTenths: Double {
let portrait: (width: Double, height: Double) = size.portraitMillimeters
let physicalHeight: Double = orientation == .landscape ? portrait.width : portrait.height
return physicalHeight * tenthsPerMillimeter
}
}
+40
View File
@@ -0,0 +1,40 @@
// PedalKind.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Sustain-pedal direction kind.
///
/// Used with the ``Pedal(_:)`` DSL constructor to insert a pedal notation mark
/// at a specific point in a ``ScorePart``. Pedal marks are **notation-only**:
/// they are emitted in MusicXML as `<pedal>` direction elements and are skipped
/// by ``ScorePart/flatten()`` without producing a ``ScoreEvent`` or advancing
/// the beat cursor.
///
/// ### Cases
///
/// - ``start`` — `<pedal type="start" line="yes"/>`. Draw a Ped symbol (or a
/// horizontal line start, depending on engraver settings) at this point.
/// - ``stop`` — `<pedal type="stop" line="yes"/>`. Draw the release symbol (or
/// the horizontal line end) at this point.
public enum PedalKind: Sendable, Hashable {
/// Pedal-down mark — `<pedal type="start" line="yes"/>`.
case start
/// Pedal-up mark — `<pedal type="stop" line="yes"/>`.
case stop
// MARK: - MusicXML mapping
/// The MusicXML `type` attribute value for this pedal kind.
public var musicXMLType: String {
switch self {
case .start: return "start"
case .stop: return "stop"
}
}
}
@@ -0,0 +1,79 @@
// RepeatStructure.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Score-level repeat and volta-ending structure for a ``Score``.
///
/// `RepeatStructure` is a **notation-only** annotation: it describes where
/// forward and backward repeat barlines appear and which measures belong to
/// which volta bracket (``Ending``). It does NOT affect ``ScorePart/flatten()``
/// — playback does not unfold repeats (future work).
///
/// Measure numbers are 1-based throughout.
///
/// ```swift
/// let score = Score(
/// bpm: 120,
/// repeats: RepeatStructure(
/// forwardRepeatMeasures: [1],
/// backwardRepeatMeasures: [4],
/// endings: [
/// Ending(number: 1, startMeasure: 3, stopMeasure: 3),
/// Ending(number: 2, startMeasure: 4, stopMeasure: 4)
/// ]
/// )
/// ) {
/// Part("melody") { … }
/// }
/// ```
///
/// The `repeats:` parameter on ``Score`` defaults to `RepeatStructure.none`, so
/// existing call sites that omit it are unchanged and emit zero `<barline>`
/// elements in MusicXML.
public struct RepeatStructure: Sendable, Hashable {
/// 1-based measure numbers whose **left** barline carries a forward repeat (`|:`).
public let forwardRepeatMeasures: Set<Int>
/// 1-based measure numbers whose **right** barline carries a backward repeat (`:|`).
public let backwardRepeatMeasures: Set<Int>
/// Volta brackets (1st ending, 2nd ending, …).
public let endings: [Ending]
/// Create a repeat structure.
///
/// - Parameters:
/// - forwardRepeatMeasures: 1-based measure numbers with a forward-repeat left barline.
/// Defaults to an empty set.
/// - backwardRepeatMeasures: 1-based measure numbers with a backward-repeat right barline.
/// Defaults to an empty set.
/// - endings: Volta brackets. Defaults to an empty array.
public init(
forwardRepeatMeasures: Set<Int> = [],
backwardRepeatMeasures: Set<Int> = [],
endings: [Ending] = []
) {
self.forwardRepeatMeasures = forwardRepeatMeasures
self.backwardRepeatMeasures = backwardRepeatMeasures
self.endings = endings
}
/// `true` when there is nothing to emit — the common default.
///
/// When `isEmpty` is `true`, ``Score/toMusicXMLString(divisions:)`` emits zero
/// `<barline>` elements (byte-identical output to a score without any
/// `RepeatStructure`).
public var isEmpty: Bool {
forwardRepeatMeasures.isEmpty
&& backwardRepeatMeasures.isEmpty
&& endings.isEmpty
}
/// The canonical empty repeat structure. Use as the ``Score`` default.
///
/// Equivalent to `RepeatStructure(forwardRepeatMeasures: [], backwardRepeatMeasures: [], endings: [])`.
public static let none: RepeatStructure = RepeatStructure()
}
+4 -4
View File
@@ -23,7 +23,7 @@ extension Score {
/// they parse back as note-ons rather than as MIDI's velocity-0
/// `noteOn → noteOff` sugar).
///
/// Note-offs are placed at `event.beat + event.duration` ticks.
/// Note-offs are placed at `event.beat + event.performedDuration` ticks.
/// Within a single track the on/off stream is sorted by `(tick,
/// off-before-on)` so that a note ending exactly when another begins
/// emits its off first.
@@ -52,8 +52,8 @@ extension Score {
)
SMFEncoder.appendTimeSignature(
delta: 0,
numerator: UInt8(clamping: max(1, timeSignature.0)),
denominatorPow2: SMFEncoder.encodeTimeSignatureDenominator(timeSignature.1),
numerator: UInt8(clamping: max(1, timeSignature.numerator)),
denominatorPow2: SMFEncoder.encodeTimeSignatureDenominator(timeSignature.denominator),
to: &conductor
)
SMFEncoder.appendEndOfTrack(delta: 0, to: &conductor)
@@ -110,7 +110,7 @@ extension Score {
for event: ScoreEvent in flat {
guard let midi: Int = event.pitch.midiNote else { continue }
let onTick: UInt32 = beatsToTicks(event.beat, ticksPerQuarter: ticksPerQuarter)
let offTick: UInt32 = beatsToTicks(event.beat + event.duration,
let offTick: UInt32 = beatsToTicks(event.beat + event.performedDuration,
ticksPerQuarter: ticksPerQuarter)
// Force at least 1 tick of duration so a 0-length event still
// emits both events in legal order.
+810 -14
View File
@@ -38,36 +38,289 @@ public struct Score: Sendable {
/// Default tempo in beats per minute. Players may override.
public let bpm: Double
/// Time signature `(numerator, denominator)`. `(4, 4)` by default. Used as
/// metadata only — does not affect beat math (one beat = one quarter note,
/// always).
public let timeSignature: (Int, Int)
/// Bar-1 time signature. `4/4` by default. Used as metadata only — does not
/// affect beat math (one beat = one quarter note, always).
///
/// Always equals ``meterMap``'s ``MeterMap/initial`` signature: this is a
/// convenience mirror of the bar-1 segment, not an independent value. For
/// mid-piece meter changes read ``meterMap`` directly; use
/// ``TimeSignature/tuple`` for a `(numerator, denominator)` pair.
public let timeSignature: TimeSignature
/// Segmented meter map governing barlines and beat addressing for the whole
/// score (the global default; a ``ScorePart`` may override it polymetrically
/// via ``ScorePart/meterMap``).
///
/// Defaults to a single-segment map built from ``timeSignature``. When you
/// supply a `meterMap` to ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:)``,
/// ``timeSignature`` is derived from its ``MeterMap/initial`` signature.
///
/// The MusicXML encoder renders the full map: a fresh `<time>` at each
/// mid-piece change, per-measure capacity, and an ``MeterMap/anacrusis`` as an
/// implicit pickup measure.
public let meterMap: MeterMap
/// Key signature for this score. Defaults to ``KeySignature/cMajor`` (C major,
/// fifths = 0). Used as score-level metadata: all parts share the same key
/// signature in measure-1 MusicXML attributes.
public let keySignature: KeySignature
/// Repeat and volta-ending structure for this score.
///
/// Defaults to ``RepeatStructure/none`` (no repeat barlines, no endings).
/// When non-empty, ``Score/toMusicXMLString(divisions:)`` emits `<barline>`
/// elements in every part's matching measures. ``ScorePart/flatten()`` is
/// **unaffected** — playback does not unfold repeats (notation-only).
public let repeats: RepeatStructure
/// Mid-piece tempo changes, sorted by measure number.
///
/// Each ``TempoChange`` specifies a new BPM that takes effect at a given
/// 1-based measure number. ``Score/bpm`` always provides the measure-1 tempo;
/// `tempoChanges` are intended for measures ≥ 2 (a change targeting measure 1
/// is superseded by `bpm` during encoding — `bpm` wins).
///
/// This is **notation-only**: ``ScorePart/flatten()`` and playback are
/// **unaffected**. ``ScorePlayer`` and NRT rendering use the base ``Score/bpm``
/// throughout. Segmented beat-to-seconds tempo-map playback is planned for a
/// future phase.
///
/// Defaults to `[]` (no mid-piece changes) so existing call sites are unchanged.
public let tempoChanges: [TempoChange]
/// Parts in document order.
public let parts: [ScorePart]
/// Rehearsal marks keyed by global 1-based measure number.
///
/// Empty for scores assembled via the flat ``init(parts:)`` path. When a score
/// is assembled from ``ScoreSection`` values, each section contributes one
/// entry: `rehearsalMarks[sectionFirstGlobalMeasure] = section.name`.
///
/// The MusicXML encoder emits a `<direction placement="above"><direction-type><rehearsal>LABEL</rehearsal></direction-type></direction>`
/// block at the opening of each measure that appears in this map. Existing
/// scores without sections have an empty map and produce zero extra `<direction>` elements.
public let rehearsalMarks: [Int: String]
/// Right-barline styles keyed by global 1-based measure number.
///
/// Empty by default. When a score is assembled from ``ScoreSection`` values,
/// each section that sets ``ScoreSection/endBarline`` contributes one entry at
/// its last global measure. Flat scores may populate this directly to draw a
/// `.double` section divider or a `.final` closing barline.
///
/// The MusicXML encoder emits the mapped `<bar-style>` inside the measure's
/// `<barline location="right">`. A backward repeat on the same measure takes
/// precedence (the section style is suppressed). Like ``rehearsalMarks``, this
/// map is **emit-only** and is not reconstructed on decode. Existing scores
/// have an empty map and produce byte-identical output.
public let measureBarlines: [Int: BarlineStyle]
/// Optional page layout specification.
///
/// When non-nil, the MusicXML encoder emits a `<defaults>` block (containing
/// `<scaling>` and `<page-layout>`) immediately after `<score-partwise>` and
/// before `<part-list>`. When `nil` (the default), **no `<defaults>` block is
/// emitted** and the encoder output is byte-identical to scores built without
/// this property.
public let pageLayout: PageLayout?
/// - Parameters:
/// - bpm: Default tempo (`> 0`). Defaults to `120`.
/// - timeSignature: Bar-1 ``TimeSignature`` convenience for the common
/// constant-meter case. **Ignored when `meterMap` is non-nil** — the map
/// governs and ``timeSignature`` is derived from its bar-1 segment, so do
/// not pass both expecting this to win. Defaults to `4/4`. Construct from
/// a numerator and denominator — `timeSignature: TimeSignature(3, 4)` — or
/// from a pair, `TimeSignature((3, 4))`.
/// - meterMap: Explicit segmented meter map. When non-nil it takes
/// precedence and the `timeSignature` argument is ignored.
/// Defaults to `nil` (a single-segment map built from `timeSignature`).
/// - keySignature: Score-level key. Defaults to ``KeySignature/cMajor``.
/// - repeats: Repeat / volta structure. Defaults to ``RepeatStructure/none``.
/// - tempoChanges: Mid-piece tempo changes. Defaults to `[]`.
/// - parts: Parts in document order.
/// - rehearsalMarks: Global measure → rehearsal-mark label. Defaults to `[:]`
/// (no marks). Populated automatically by the ``Score/init(sections:bpm:keySignature:)``
/// family of initializers; rarely supplied manually.
/// - measureBarlines: Global measure → right-barline style. Defaults to `[:]`
/// (no overrides). Populated automatically by the section initializers from
/// each section's ``ScoreSection/endBarline``; may also be supplied directly.
/// - pageLayout: Optional page layout for MusicXML encoding. When non-nil, a
/// `<defaults>` block is emitted before `<part-list>`. Defaults to `nil`
/// (no `<defaults>`, byte-identical output to existing scores).
public init(
bpm: Double = 120.0,
timeSignature: (Int, Int) = (4, 4),
parts: [ScorePart]
timeSignature: TimeSignature = TimeSignature(4, 4),
meterMap: MeterMap? = nil,
keySignature: KeySignature = .cMajor,
repeats: RepeatStructure = .none,
tempoChanges: [TempoChange] = [],
parts: [ScorePart],
rehearsalMarks: [Int: String] = [:],
measureBarlines: [Int: BarlineStyle] = [:],
pageLayout: PageLayout? = nil
) {
precondition(bpm > 0, "Score: bpm must be positive, got \(bpm)")
precondition(
timeSignature.0 >= 1 && timeSignature.1 >= 1,
"Score: timeSignature numerator and denominator must be >= 1"
)
// `TimeSignature` validates numerator / denominator at its own init, so
// no extra check is needed here. When a meterMap is supplied it governs
// and the timeSignature argument is ignored/derived.
let resolvedMap: MeterMap = meterMap ?? MeterMap(timeSignature)
self.bpm = bpm
self.timeSignature = timeSignature
self.parts = parts
self.timeSignature = resolvedMap.initial
self.meterMap = resolvedMap
self.keySignature = keySignature
self.repeats = repeats
self.tempoChanges = tempoChanges
// Expand FillMeasure markers against each part's effective meter.
// Parts with a per-part meterMap use their own map; others use the resolved
// score-level map. This is the final funnel for flat, DSL, and section paths.
self.parts = parts.map { part in
let effectiveMap: MeterMap = part.meterMap ?? resolvedMap
let expanded: [ScoreElement] = Score.expandFillMeasures(
in: part.elements,
meter: effectiveMap
)
return ScorePart(
name: part.name,
channel: part.channel,
clef: part.clef,
keySignature: part.keySignature,
transpose: part.transpose,
meterMap: part.meterMap,
elements: expanded,
id: part.id
)
}
self.rehearsalMarks = rehearsalMarks
self.measureBarlines = measureBarlines
self.pageLayout = pageLayout
}
/// DSL initializer.
///
/// See ``init(bpm:timeSignature:meterMap:keySignature:repeats:tempoChanges:parts:rehearsalMarks:pageLayout:)``
/// for parameter semantics.
public init(
bpm: Double = 120.0,
timeSignature: (Int, Int) = (4, 4),
timeSignature: TimeSignature = TimeSignature(4, 4),
meterMap: MeterMap? = nil,
keySignature: KeySignature = .cMajor,
repeats: RepeatStructure = .none,
tempoChanges: [TempoChange] = [],
pageLayout: PageLayout? = nil,
@ScorePartBuilder parts: () -> [ScorePart]
) {
self.init(bpm: bpm, timeSignature: timeSignature, parts: parts())
self.init(
bpm: bpm,
timeSignature: timeSignature,
meterMap: meterMap,
keySignature: keySignature,
repeats: repeats,
tempoChanges: tempoChanges,
parts: parts(),
pageLayout: pageLayout
)
}
// MARK: - Section-based initializers
/// Assemble a score from an ordered array of ``ScoreSection`` values.
///
/// Sections are stitched together sequentially. Each section contributes:
/// - A rehearsal mark at its first global measure.
/// - Its local meter map segments, tempo changes, and repeat structure —
/// all offset by the running measure count so they land at the correct
/// global bar numbers.
/// - Padded element lists for every instrument identity in the assembled
/// roster: if an instrument is TACET in a section it receives whole-measure
/// rests spanning the section's beat length.
///
/// See ``ScoreSection`` for v1 constraints (anacrusis, cross-section repeats,
/// per-part meterMap inside sections).
///
/// - Parameters:
/// - sections: Ordered array of sections. Must be non-empty.
/// - bpm: Score-level base tempo. Defaults to `120`.
/// - timeSignature: Score-level default meter applied to every section that does
/// NOT set its own ``ScoreSection/meterMap``. A section with a `meterMap` keeps
/// it (so per-section / polymetric meters still work). Defaults to 4/4.
/// - keySignature: Score-level key signature. Defaults to ``KeySignature/cMajor``.
/// Individual sections can carry their own ``ScoreSection/keySignature`` override.
/// - pageLayout: Optional page layout for MusicXML encoding. When non-nil, a
/// `<defaults>` block is emitted before `<part-list>`. Defaults to `nil`.
public init(
sections: [ScoreSection],
bpm: Double = 120.0,
timeSignature: TimeSignature = TimeSignature(4, 4),
keySignature: KeySignature = .cMajor,
pageLayout: PageLayout? = nil
) {
precondition(!sections.isEmpty, "Score(sections:): sections must be non-empty")
precondition(bpm > 0, "Score(sections:): bpm must be positive, got \(bpm)")
let lowered: _LoweredSections = Score._lowerSections(
sections,
keySignature: keySignature,
defaultTimeSignature: timeSignature
)
self.init(
bpm: bpm,
meterMap: lowered.meterMap,
keySignature: lowered.keySignature,
repeats: lowered.repeats,
tempoChanges: lowered.tempoChanges,
parts: lowered.parts,
rehearsalMarks: lowered.rehearsalMarks,
measureBarlines: lowered.measureBarlines,
pageLayout: pageLayout
)
}
/// DSL initializer for section-based scores.
///
/// See ``init(sections:bpm:keySignature:)`` for parameter semantics.
///
/// ```swift
/// // A score-level timeSignature applies to every section that does not set
/// // its own meterMap; section "B" overrides to 3/4.
/// let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .dMinor) {
/// Section("A") { // inherits 4/4
/// Part("lead") { Note(.c, 5, dur: .whole) }
/// Part("bass") { Note(.c, 2, dur: .whole) }
/// }
/// Section("B", meterMap: MeterMap(TimeSignature(3, 4))) { // overrides to 3/4
/// Part("lead") {
/// Note(.e, 5, dur: .quarter)
/// Note(.d, 5, dur: .quarter)
/// Note(.c, 5, dur: .quarter)
/// }
/// Part("bass") { Note(.g, 2, dur: .dotted(.half)) }
/// }
/// }
/// ```
///
/// - Parameters:
/// - bpm: Score-level base tempo. Defaults to `120`.
/// - keySignature: Score-level key signature. Defaults to ``KeySignature/cMajor``.
/// - timeSignature: Score-level default meter for sections without their own
/// ``ScoreSection/meterMap``. Defaults to 4/4. Per-section `meterMap` wins.
/// - pageLayout: Optional page layout for MusicXML encoding. When non-nil, a
/// `<defaults>` block is emitted before `<part-list>`. Defaults to `nil`.
/// - sections: Result-builder block of ``ScoreSection`` values.
public init(
bpm: Double = 120.0,
timeSignature: TimeSignature = TimeSignature(4, 4),
keySignature: KeySignature = .cMajor,
pageLayout: PageLayout? = nil,
@ScoreSectionBuilder sections: () -> [ScoreSection]
) {
self.init(
sections: sections(),
bpm: bpm,
timeSignature: timeSignature,
keySignature: keySignature,
pageLayout: pageLayout
)
}
// MARK: - Flattening
@@ -103,4 +356,547 @@ public struct Score: Sendable {
public var totalBeats: Double {
parts.map { $0.lastBeat() }.max() ?? 0.0
}
// MARK: - Section lowering
/// Intermediate value produced by ``_lowerSections(_:keySignature:)`` —
/// all the flat-Score fields ready to pass to `Score.init(…)`.
struct _LoweredSections {
let meterMap: MeterMap
let keySignature: KeySignature
let repeats: RepeatStructure
let tempoChanges: [TempoChange]
let parts: [ScorePart]
let rehearsalMarks: [Int: String]
let measureBarlines: [Int: BarlineStyle]
}
/// Lower an ordered array of ``ScoreSection`` values into the flat-Score fields.
///
/// Algorithm:
///
/// 1. Collect the ordered union of part `id` values (first-appearance order).
/// 2. For each section (in order):
/// a. Resolve the section's effective meter map (section.meterMap ?? MeterMap(defaultTimeSignature)).
/// For sections after the first, strip any anacrusis to zero (v1 constraint).
/// b. Compute the section's measure span: walk bar-by-bar under the effective
/// meter map until the largest part beat-sum is fully accounted for.
/// c. Compute the full beat span (quarters) of those measures so TACET rests
/// can be padded to an exact bar-aligned length.
/// d. For each part identity: if present in the section, append its elements
/// followed by rest-padding to the section beat span; if TACET, append
/// whole-measure rests spanning the section.
/// e. Shift the section's meter map, tempo changes, and repeats by
/// `measureOffset` and merge into the global accumulators.
/// f. Record the rehearsal mark at `measureOffset + 1`.
/// g. Advance `measureOffset` by `sectionMeasureSpan`.
/// 3. Assemble and return the lowered fields.
static func _lowerSections(
_ sections: [ScoreSection],
keySignature: KeySignature,
defaultTimeSignature: TimeSignature = TimeSignature(4, 4)
) -> _LoweredSections {
// --- Step 1: Ordered identity roster ---
var identityOrder: [String] = []
var identitySeen: Set<String> = []
// Also collect first-seen attributes for final ScorePart construction.
var identityName: [String: String] = [:]
var identityChannel: [String: Int] = [:]
var identityClef: [String: Clef] = [:]
var identityKeySignature: [String: KeySignature?] = [:]
var identityTranspose: [String: Transpose?] = [:]
for section: ScoreSection in sections {
for part: ScorePart in section.parts {
let partID: String = part.id
if !identitySeen.contains(partID) {
identitySeen.insert(partID)
identityOrder.append(partID)
identityName[partID] = part.name
identityChannel[partID] = part.channel
identityClef[partID] = part.clef
identityKeySignature[partID] = part.keySignature
identityTranspose[partID] = part.transpose
}
}
}
// Per-identity accumulated element lists.
var accumulatedElements: [String: [ScoreElement]] = [:]
for id: String in identityOrder {
accumulatedElements[id] = []
}
// Global merged accumulators.
var globalMeterSegments: [MeterMap.Segment] = []
var globalTempoChanges: [TempoChange] = []
var globalForwardRepeats: Set<Int> = []
var globalBackwardRepeats: Set<Int> = []
var globalEndings: [Ending] = []
var globalRehearsalMarks: [Int: String] = [:]
var globalMeasureBarlines: [Int: BarlineStyle] = [:]
var measureOffset: Int = 0
// --- Step 2: Walk sections ---
for (sectionIdx, section): (Int, ScoreSection) in sections.enumerated() {
// Step 2a: Resolve effective meter map for this section.
// A section without its own `meterMap` inherits the score-level
// `defaultTimeSignature`; a section that sets `meterMap` keeps it.
// For sections after index 0, strip anacrusis to zero (v1 constraint).
let rawSectionMap: MeterMap = section.meterMap ?? MeterMap(defaultTimeSignature)
let effectiveSectionMap: MeterMap
if sectionIdx == 0 {
effectiveSectionMap = rawSectionMap
} else {
// Later sections: ignore any anacrusis.
effectiveSectionMap = MeterMap(
segments: rawSectionMap.segments,
anacrusis: .zero
)
}
// Expand FillMeasure markers in this section's parts against the
// section's effective meter BEFORE the beat-span calculation so that
// the resolved rests count toward `_beatSpan` and `_measureSpan`.
// After expansion the section parts carry no `.fillMeasure` elements,
// so site-1's expansion in the designated init is a harmless no-op.
var sectionExpandedParts: [ScorePart] = []
sectionExpandedParts.reserveCapacity(section.parts.count)
for part: ScorePart in section.parts {
// A polymetric part inside a section fills to ITS OWN bar grid,
// matching the designated-init policy (`part.meterMap ?? score map`).
let partMeter: MeterMap = part.meterMap ?? effectiveSectionMap
let expanded: [ScoreElement] = Score.expandFillMeasures(
in: part.elements,
meter: partMeter
)
sectionExpandedParts.append(ScorePart(
name: part.name,
channel: part.channel,
clef: part.clef,
keySignature: part.keySignature,
transpose: part.transpose,
meterMap: part.meterMap,
elements: expanded,
id: part.id
))
}
// Step 2b: Compute the section beat-span from all parts present.
// Sum each part's total beat span, take the maximum.
var maxPartBeats: Fraction = .zero
for part: ScorePart in sectionExpandedParts {
let partBeats: Fraction = Score._beatSpan(ofElements: part.elements)
if partBeats > maxPartBeats {
maxPartBeats = partBeats
}
}
// Compute section measure count and full beat span under the effective map.
// The beat span accounts for the section's anacrusis (first section only).
//
// Floor to at least one measure. A section whose entire content fits
// within the pickup (`_measureSpan` returns 0) would otherwise leave
// `measureOffset` un-advanced — colliding the next section's meter
// segment at the same global `startBar` (which trips `MeterMap`'s
// duplicate-startBar precondition when the meters differ) and clobbering
// its rehearsal mark. Every section occupies at least one global measure.
let sectionMeasureSpan: Int = max(1, Score._measureSpan(
beats: maxPartBeats,
meterMap: effectiveSectionMap
))
// The beat span includes the section's anacrusis (pickup) beats so
// that present parts and TACET fills cover the SAME total beats and
// stay bar-aligned across the section boundary. Later sections have
// their anacrusis stripped to zero above, so only the first section
// contributes a pickup here.
let sectionAnacrusis: Fraction = effectiveSectionMap.anacrusis
let sectionBeatSpan: Fraction = Score._totalBeatSpan(
measureCount: sectionMeasureSpan,
meterMap: effectiveSectionMap
) + sectionAnacrusis
// Step 2c: Merge the section's meter map segments into the global list,
// offset by measureOffset (and incrementing startBar by measureOffset).
// The first section's anacrusis (if any) is kept at the offset it has
// in the effective map — bar numbering for the first section starts at 1
// (offset 0), so segments are appended as-is. For later sections the
// startBar values are shifted.
for segment: MeterMap.Segment in effectiveSectionMap.segments {
let globalStartBar: Int = segment.startBar + measureOffset
globalMeterSegments.append(
MeterMap.Segment(startBar: globalStartBar, segment.timeSignature)
)
}
// Step 2d: Shift and merge tempo changes.
for tc: TempoChange in section.tempoChanges {
let globalMeasure: Int = tc.measure + measureOffset
globalTempoChanges.append(TempoChange(measure: globalMeasure, bpm: tc.bpm))
}
// Step 2e: Shift and merge repeats.
let sectionRepeats: RepeatStructure = section.repeats
for measure: Int in sectionRepeats.forwardRepeatMeasures {
globalForwardRepeats.insert(measure + measureOffset)
}
for measure: Int in sectionRepeats.backwardRepeatMeasures {
globalBackwardRepeats.insert(measure + measureOffset)
}
for ending: Ending in sectionRepeats.endings {
globalEndings.append(Ending(
number: ending.number,
startMeasure: ending.startMeasure + measureOffset,
stopMeasure: ending.stopMeasure + measureOffset
))
}
// Step 2f: Record rehearsal mark at first global measure of this section.
// For the first section: if there is an anacrusis the first full bar is
// at global measure 1 (offset 0 + 1). For later sections the mark lands
// at measureOffset + 1.
let rehearsalMeasure: Int = measureOffset + 1
globalRehearsalMarks[rehearsalMeasure] = section.name
// Step 2f.1: Record the section's end-barline style at its LAST global
// measure (the bar just before the next section starts).
if let endBarline: BarlineStyle = section.endBarline {
let lastMeasure: Int = measureOffset + sectionMeasureSpan
globalMeasureBarlines[lastMeasure] = endBarline
}
// Step 2g: For each identity, append this section's content or rests.
// Build a lookup from part.id → part for this section, using the
// expanded parts (FillMeasure already resolved) so beat-span math is
// consistent with the expanded element lists that will be stored.
var sectionPartByID: [String: ScorePart] = [:]
for part: ScorePart in sectionExpandedParts {
sectionPartByID[part.id] = part
}
for partID: String in identityOrder {
if let sectionPart: ScorePart = sectionPartByID[partID] {
// Part is present: append its elements, then rest-pad to section beat span.
let partBeats: Fraction = Score._beatSpan(ofElements: sectionPart.elements)
var elems: [ScoreElement] = sectionPart.elements
let gap: Fraction = sectionBeatSpan - partBeats
if gap > .zero {
let padRests: [ScoreElement] = Score._makeRestElements(beats: gap)
elems.append(contentsOf: padRests)
}
accumulatedElements[partID, default: []].append(contentsOf: elems)
} else {
// TACET: fill the entire section with whole-measure rests,
// prefixed by an anacrusis-length rest when the section has a
// pickup (first section only) so the tacet instrument covers
// the same beat span as the present parts.
var tacetRests: [ScoreElement] = []
if sectionAnacrusis > .zero {
tacetRests.append(.rest(duration: .fraction(sectionAnacrusis)))
}
tacetRests.append(contentsOf: Score._makeTacetRests(
measureCount: sectionMeasureSpan,
meterMap: effectiveSectionMap
))
accumulatedElements[partID, default: []].append(contentsOf: tacetRests)
}
}
// Advance measure offset.
measureOffset += sectionMeasureSpan
}
// --- Step 3: Build global flat structures ---
// Deduplicate consecutive equal meter segments (eliminates repeated
// same-time-signature segments when multiple sections share the same meter).
let dedupedSegments: [MeterMap.Segment] = Score._deduplicateConsecutiveSegments(
globalMeterSegments
)
// Ensure segment list is valid: must have at least one segment starting at bar 1.
// globalMeterSegments always has at least one entry because sections.count >= 1.
let firstAnacrusis: Fraction = sections[0].meterMap?.anacrusis ?? .zero
let globalMeterMap: MeterMap = MeterMap(
segments: dedupedSegments,
anacrusis: firstAnacrusis
)
// Sort tempo changes ascending by measure.
let sortedTempoChanges: [TempoChange] = globalTempoChanges.sorted { $0.measure < $1.measure }
// Build global repeat structure.
let globalRepeats: RepeatStructure = RepeatStructure(
forwardRepeatMeasures: globalForwardRepeats,
backwardRepeatMeasures: globalBackwardRepeats,
endings: globalEndings
)
// Determine resolved key. The score-level key is rendered in measure 1,
// which belongs to the FIRST section — so the first section's override
// wins (falling back to the caller-supplied key). The model has no
// mid-piece key map, so a later section declaring a different key cannot
// be represented; that is a documented v1 limitation.
let resolvedKeySignature: KeySignature = sections[0].keySignature ?? keySignature
// Assemble final ScorePart values.
var flatParts: [ScorePart] = []
flatParts.reserveCapacity(identityOrder.count)
for partID: String in identityOrder {
let name: String = identityName[partID] ?? partID
let channel: Int = identityChannel[partID] ?? 0
let clef: Clef = identityClef[partID] ?? .auto
// `identityKeySignature` / `identityTranspose` are `[String: T?]`, so a
// present key yields `Optional(Optional(value))`; flatMap collapses the
// double-optional (an absent id and a present-but-nil override both → nil).
let partKey: KeySignature? = identityKeySignature[partID].flatMap { $0 }
let transpose: Transpose? = identityTranspose[partID].flatMap { $0 }
let elements: [ScoreElement] = accumulatedElements[partID] ?? []
flatParts.append(ScorePart(
name: name,
channel: channel,
clef: clef,
keySignature: partKey,
transpose: transpose,
meterMap: nil,
elements: elements,
id: partID
))
}
return _LoweredSections(
meterMap: globalMeterMap,
keySignature: resolvedKeySignature,
repeats: globalRepeats,
tempoChanges: sortedTempoChanges,
parts: flatParts,
rehearsalMarks: globalRehearsalMarks,
measureBarlines: globalMeasureBarlines
)
}
// MARK: - Section lowering helpers
/// Walk `elements` left-to-right tracking a beat cursor, replacing each
/// `.fillMeasure` marker with a concrete `.rest` spanning the remaining
/// beats of the current measure under `meter`.
///
/// - For `.fillMeasure` at the top level: compute the next barline position
/// from the cursor, insert a rest of `(nextBarStart − cursor)` beats,
/// advance the cursor. If the cursor is already on a barline (fill ≤ 0),
/// insert nothing.
/// - For `.voice(n, children)`: recurse with a FRESH cursor (the voice block
/// starts its own cursor at 0); rebuild the `.voice` case from the expanded
/// children. The OUTER cursor is NOT advanced (voice blocks overlay from 0).
/// - For all other elements: append unchanged and advance the cursor by
/// `scoreElementBeatSpan`. Do NOT recurse into `.tuplet` / `.wedge` etc.
/// (fills inside those are unsupported; any nested `.fillMeasure` is left
/// as-is and treated as zero-span downstream).
/// - Returns the input array unchanged when no `.fillMeasure` is present at
/// the top level or inside a voice block.
static func expandFillMeasures(
in elements: [ScoreElement],
meter: MeterMap
) -> [ScoreElement] {
var cursor: Fraction = .zero
return Score._expandFillMeasures(
elements: elements,
meter: meter,
cursor: &cursor
)
}
// Internal recursive core used by expandFillMeasures and the voice path.
private static func _expandFillMeasures(
elements: [ScoreElement],
meter: MeterMap,
cursor: inout Fraction
) -> [ScoreElement] {
var result: [ScoreElement] = []
result.reserveCapacity(elements.count)
for element: ScoreElement in elements {
switch element {
case .fillMeasure:
// Compute next barline from the cursor under this meter.
let fill: Fraction = Score._fillToNextBar(cursor: cursor, meter: meter)
if fill > .zero {
result.append(.rest(duration: .fraction(fill)))
cursor = cursor + fill
}
// fill <= .zero → cursor already on a barline; insert nothing.
case .voice(let number, let children):
// Voice block: fresh cursor for the recursion; outer cursor unchanged.
var voiceCursor: Fraction = .zero
let expandedChildren: [ScoreElement] = Score._expandFillMeasures(
elements: children,
meter: meter,
cursor: &voiceCursor
)
result.append(.voice(number, expandedChildren))
// Do NOT advance the outer cursor (voice blocks overlay from 0).
default:
// All other elements: append unchanged and advance cursor.
result.append(element)
cursor = cursor + scoreElementBeatSpan(element)
}
}
return result
}
/// Compute the quarter-beat distance from `cursor` to the next barline
/// under `meter`.
///
/// Bar 0 is the anacrusis `[0, anacrusis)`; bar 1 starts at `anacrusis`.
/// Subsequent bars are located via `MeterMap.barStartQuarters`. The
/// function walks bars forward until it finds one that starts strictly
/// after `cursor`, then returns `nextBarStart − cursor`.
///
/// Returns `.zero` when the cursor is already exactly on a barline.
private static func _fillToNextBar(
cursor: Fraction,
meter: MeterMap
) -> Fraction {
// Walk bar boundaries forward. Start at bar 0 (anacrusis pickup) when
// anacrusis > 0, otherwise start at bar 1.
let firstBar: Int = meter.anacrusis > .zero ? 0 : 1
// Catch the cursor sitting exactly on the FIRST bar's start (e.g. beat 0
// with no anacrusis): the loop below only checks each bar's END boundary,
// so this leading barline must be handled before it.
if meter.barStartQuarters(firstBar) == cursor {
return .zero
}
var bar: Int = firstBar
// Find the bar whose END is strictly greater than cursor — i.e. the bar
// that CONTAINS cursor. Its end = next bar's start.
while true {
let nextBarStart: Fraction = meter.barStartQuarters(bar + 1)
if nextBarStart > cursor {
return nextBarStart - cursor
}
if nextBarStart == cursor {
// Cursor already on this barline.
return .zero
}
bar += 1
// Safety: prevent infinite loop in degenerate zero-capacity meters.
guard bar < 100_000 else { return .zero }
}
}
/// Sum the sequential beat span of a flat element list (quarters).
///
/// Uses ``scoreElementBeatSpan`` from `ScoreRestFillHelpers.swift`.
static func _beatSpan(ofElements elements: [ScoreElement]) -> Fraction {
elements.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
}
/// Compute the number of full bars required to contain `beats` quarters
/// under `meterMap`.
///
/// When `meterMap.anacrusis > .zero`, the anacrusis is subtracted first and
/// counted as bar 0; the return value is the count of FULL bars (bars 1..N).
/// In that case content that fits entirely within the pickup returns `0`
/// full bars — callers that need a per-section floor (one global measure
/// minimum) apply `max(1, …)` themselves. With no anacrusis, an empty beat
/// count returns `1`.
static func _measureSpan(
beats: Fraction,
meterMap: MeterMap
) -> Int {
var remaining: Fraction = beats
if meterMap.anacrusis > .zero {
remaining = remaining - meterMap.anacrusis
if remaining <= .zero {
return 0
}
} else {
guard remaining > .zero else { return 1 }
}
var bar: Int = 1
while remaining > .zero {
let capacity: Fraction = meterMap.timeSignature(atBar: bar).measureQuarters
guard capacity > .zero else { break }
if remaining <= capacity {
remaining = .zero
} else {
remaining = remaining - capacity
}
bar += 1
}
return max(1, bar - 1)
}
/// Compute the total quarter-beat span of `measureCount` full bars under
/// `meterMap`, NOT including any anacrusis (those are separate).
static func _totalBeatSpan(
measureCount: Int,
meterMap: MeterMap
) -> Fraction {
guard measureCount > 0 else { return .zero }
var total: Fraction = .zero
for bar: Int in 1...measureCount {
total = total + meterMap.timeSignature(atBar: bar).measureQuarters
}
return total
}
/// Build rest elements to fill `beats` quarters.
///
/// Decomposes `beats` into a sum of standard note-duration fractions using
/// ``Score/decompose(_:)`` (used by the encoder's rest-fill logic) and
/// produces corresponding `ScoreElement.rest` values. Handles non-integer
/// beat values by working in the `Fraction` domain.
static func _makeRestElements(beats: Fraction) -> [ScoreElement] {
guard beats > .zero else { return [] }
var result: [ScoreElement] = []
let decomposed: [(Fraction, String, Int)] = Score.decompose(beats)
for (size, _, _): (Fraction, String, Int) in decomposed {
result.append(.rest(duration: .fraction(size)))
}
return result
}
/// Build whole-measure rest elements for `measureCount` bars under `meterMap`.
///
/// Each bar gets a single rest whose duration equals the bar's capacity.
static func _makeTacetRests(
measureCount: Int,
meterMap: MeterMap
) -> [ScoreElement] {
guard measureCount > 0 else { return [] }
var result: [ScoreElement] = []
result.reserveCapacity(measureCount)
for bar: Int in 1...measureCount {
let capacity: Fraction = meterMap.timeSignature(atBar: bar).measureQuarters
result.append(.rest(duration: .fraction(capacity)))
}
return result
}
/// Remove consecutive equal-signature segments (keeping the first occurrence
/// of each consecutive run). Two segments are considered equal when their
/// `timeSignature` is identical and neither represents a change in the
/// governing signature.
///
/// Input must be non-empty and sorted by `startBar`. Output has the same
/// ordering guarantee.
static func _deduplicateConsecutiveSegments(
_ segments: [MeterMap.Segment]
) -> [MeterMap.Segment] {
guard !segments.isEmpty else { return segments }
var result: [MeterMap.Segment] = [segments[0]]
for i: Int in 1..<segments.count {
let prev: MeterMap.Segment = result[result.count - 1]
let curr: MeterMap.Segment = segments[i]
if curr.timeSignature != prev.timeSignature {
result.append(curr)
}
// Same signature as the previous non-duplicate: skip (redundant).
}
return result
}
}
+404 -6
View File
@@ -14,35 +14,433 @@ import Foundation
///
/// Cases:
///
/// - ``note(_:duration:dynamic:articulation:voice:)`` — a single pitch.
/// - ``note(_:duration:dynamic:articulation:voice:tie:)`` — a single pitch.
/// - ``rest(duration:)`` — silence for one duration; advances the cursor only.
/// - ``chord(_:duration:dynamic:articulation:voice:)`` — N simultaneous pitches
/// - ``chord(_:duration:dynamic:articulation:voice:tie:)`` — N simultaneous pitches
/// sharing the same start beat, duration, dynamic, and articulation.
/// - ``tuplet(actual:normal:children:)`` — N children performed in the time of
/// - ``tuplet(actual:normal:normalType:children:)`` — N children performed in the time of
/// `normal × children's nominal-duration sum`. Ratios compose under nesting.
public enum ScoreElement: Sendable {
/// - ``voice(_:_:)`` — an independent polyphonic voice that overlays the part
/// from beat zero rather than advancing the outer cursor. Use multiple
/// `Voice(n) { … }` blocks at the top level of a ``Part`` to express
/// multi-voice staves. The voice number (`≥ 1`) becomes the MusicXML
/// `<voice>` number and is used to partition atoms into separate `<backup>`-
/// delimited streams during encoding.
///
/// The enum is `indirect` because ``spanned(_:_:)`` recursively embeds a
/// `ScoreElement`. `indirect` heap-boxes **all** cases, not just `.spanned` —
/// an acceptable cost for this non-RT, authoring-side model type.
public indirect enum ScoreElement: Sendable {
/// A single notated pitch.
///
/// When `tie` is `true` this note is tied to the immediately-following
/// same-pitch, same-voice note: the two notated noteheads sound as one
/// sustained note whose duration is their sum. A tie chain (A.tie→B.tie→C)
/// merges all three into one sounding event. A `tie==true` note whose
/// immediately-following element is not a same-pitch same-voice note is
/// treated as untied (no merge, no tie annotation emitted).
case note(
Pitch,
duration: NoteDuration,
dynamic: Dynamic,
articulation: Articulation,
voice: Int
voice: Int,
tie: Bool
)
/// A silent rest of the given duration.
///
/// Unlike ``note(_:duration:dynamic:articulation:voice:tie:)`` and
/// ``chord(_:duration:dynamic:articulation:voice:)``, a rest carries no
/// `voice`, `dynamic`, or `articulation` of its own — by design. A rest
/// inside a ``voice(_:_:)`` block takes that block's voice number from
/// context at encode time (a rest in `Voice(2){…}` is emitted with
/// `<voice>2</voice>`); dynamics and articulations are note-level marks with
/// no meaning on a rest. The case stays minimal so the common authoring path
/// (`Rest(.quarter)`) is unambiguous.
case rest(duration: NoteDuration)
/// N simultaneous pitches sharing the same start beat, duration, dynamic,
/// and articulation.
///
/// When `tie` is `true` this chord is tied to the immediately-following
/// chord that has the **same pitch set** (order-insensitive) and the same
/// voice: every notehead sustains across the bar and the two chord stacks
/// sound as one sustained chord whose duration is their sum. A tie chain
/// (A.tie→B.tie→C) merges all three into one sounding event. A `tie==true`
/// chord whose immediately-following element is not a same-pitch-set,
/// same-voice chord is treated as **untied** — separate events are emitted
/// and no tie annotation appears in MusicXML.
case chord(
[Pitch],
duration: NoteDuration,
dynamic: Dynamic,
articulation: Articulation,
voice: Int
voice: Int,
tie: Bool
)
/// N children performed in the time of `normal × children's nominal-duration sum`.
///
/// When `normalType` is non-nil it records the declared base note value of the
/// tuplet (e.g. `.half` for a half-note triplet). This value is carried through
/// to MusicXML emission as `<normal-type>` (and `<normal-dot/>` for dotted values)
/// inside each member's `<time-modification>` block. When `nil` (the default),
/// `<normal-type>` is not emitted — output is byte-identical to the pre-existing
/// behaviour. The field is notation-only and does not affect timing or flattening.
case tuplet(
actual: Int,
normal: Int,
normalType: NoteDuration?,
children: [ScoreElement]
)
/// An independent polyphonic voice within a part.
///
/// Children are flattened with a fresh cursor starting at beat zero, so
/// multiple `Voice(n)` blocks in the same ``Part`` overlay each other
/// rather than sequencing end-to-end. The outer part cursor is NOT
/// advanced by a `voice` block; ``ScorePart/lastBeat()`` takes the max
/// beat across all voices.
///
/// Voice numbers are 1-based and used directly as MusicXML `<voice>`
/// values. Encoding a part whose top-level elements contain any `voice`
/// case triggers the multi-voice MusicXML path (`<backup>` + per-voice
/// streams); single-voice parts emit the unchanged legacy output.
///
/// > Note: A ``tuplet(_:_:_:_:)`` nested *inside* a `voice` block has its
/// > `<time-modification>` and `<tuplet>` bracket dropped on the multi-voice
/// > encode path — only the sounding duration (already scaled by the tuplet
/// > ratio) is preserved. The playback timing is exact; the visual tuplet
/// > bracket is lost. Author tuplets at the top level of a part, or in a
/// > single-voice part, to keep the bracket.
///
/// - Parameters:
/// - voiceNumber: Voice identifier (≥ 1). Determines the MusicXML
/// `<voice>` number.
/// - children: Elements belonging to this voice stream.
case voice(Int, [ScoreElement])
/// A hairpin (wedge) span applied to a sequence of children.
///
/// A wedge is a **purely notational** decoration — it produces a `<wedge>`
/// direction in MusicXML but does **not** change timing, velocity, or the
/// flattened ``ScoreEvent`` list. Flattening a `wedge` block is identical to
/// flattening the unwrapped children directly.
///
/// The MusicXML encoder marks the FIRST child atom with a wedge-start and
/// the LAST child atom with a wedge-stop, emitting the corresponding
/// `<direction>` elements immediately before and after those notes.
///
/// ```swift
/// Crescendo {
/// Note(.c, 5, dur: .quarter, dyn: .p)
/// Note(.d, 5, dur: .quarter)
/// Note(.e, 5, dur: .quarter)
/// Note(.f, 5, dur: .quarter, dyn: .f)
/// }
/// ```
///
/// - Parameters:
/// - kind: Whether this is a crescendo or diminuendo hairpin.
/// - children: The notes / chords / rests spanned by the hairpin.
case wedge(WedgeKind, [ScoreElement])
/// A grace note — an ornamental notehead with no sounding duration.
///
/// Grace notes are **purely notational**: ``ScorePart/flatten()`` skips them
/// entirely and does **not** emit a ``ScoreEvent`` or advance the beat cursor.
/// The flattened ``ScoreEvent`` list is identical whether or not grace notes
/// are present.
///
/// Placement convention: author a `.grace` element immediately before the
/// main note it ornaments. A run of consecutive `.grace` elements preceding
/// a note form a grace-note group (multiple small noteheads before the main
/// note).
///
/// In MusicXML the grace note is emitted as:
/// ```xml
/// <note>
/// <grace slash="yes"/> <!-- or <grace/> when slashed == false -->
/// <pitch>…</pitch>
/// <voice>…</voice>
/// <type>eighth</type>
/// </note>
/// ```
///
/// There is **no** `<duration>` element on a grace note (MusicXML convention).
/// The grace note contributes zero to measure-fill accounting — it never
/// pushes content across a barline.
///
/// **Playback**: grace notes are currently notation-only. ``ScorePlayer``
/// and audio rendering do not realize them as sound events. Realized grace-note
/// playback (subtracting a small steal from the preceding or following main note
/// duration) is planned for a future phase.
///
/// - Parameters:
/// - pitch: The pitch of the grace note.
/// - slashed: When `true` (default), a slash through the stem indicates an
/// acciaccatura — a very short, crushed ornament. When `false`, an
/// appoggiatura — a leaning ornament that is played with more weight.
case grace(Pitch, slashed: Bool)
/// A mid-voice clef change — the staff switches clef from this point onward.
///
/// A clef change is **purely notational**: ``ScorePart/flatten()`` skips it
/// entirely and does **not** emit a ``ScoreEvent`` or advance the beat cursor.
/// MusicXML pitches are absolute, so the clef affects only how following
/// notes are *drawn* (staff line + ledger lines), never their sounding pitch.
/// The flattened ``ScoreEvent`` list is identical whether or not clef changes
/// are present.
///
/// Placement convention: author a `.clefChange` element immediately before the
/// first note that should appear under the new clef. Construct it with the
/// ``ClefChange(_:)`` DSL function; ``Clef/auto`` is rejected there because it
/// infers a clef from a part's median pitch and has no meaning at a point.
///
/// In MusicXML the change is emitted as a mid-measure attributes block:
/// ```xml
/// <attributes>
/// <clef><sign>C</sign><line>4</line></clef> <!-- e.g. tenor -->
/// </attributes>
/// ```
///
/// The clef change contributes zero to measure-fill accounting — it never
/// pushes content across a barline. The part's *initial* clef (measure-1
/// attributes) remains ``ScorePart/clef``; clef-change elements layer on top.
///
/// - Parameter clef: The clef to switch to. Never ``Clef/auto``.
case clefChange(Clef)
/// A multi-staff block (grand staff, e.g. piano left + right hand).
///
/// A `staff` block groups elements that belong to a specific notated staff
/// number within the part. Multiple `Staff(n) { }` blocks in the same ``Part``
/// body are rendered simultaneously — each has its own cursor starting at beat
/// zero and overlays the part from that point (analogous to ``voice(_:_:)``
/// for polyphony).
///
/// Staff numbers are 1-based and map to MusicXML `<staff>` element values on
/// every note. When more than one distinct staff is present in a part the
/// encoder emits `<staves>N</staves>` and one `<clef number="k">` per staff
/// in measure-1 `<attributes>`. Single-staff parts emit **unchanged** output
/// (no `<staves>`, bare `<clef>` without a `number=` attribute) — existing
/// tests are unaffected.
///
/// `flatten()` recurses into staff children so their notes DO produce
/// ``ScoreEvent`` instances — the staff assignment is purely a notation concern
/// and has no effect on sounding output.
///
/// ```swift
/// Staff(2, clef: .bass) {
/// Voice(3) { Note(.named(.c, 3), dur: .whole, dyn: .mp) }
/// }
/// ```
///
/// - Parameters:
/// - number: Staff number (≥ 1). Becomes the MusicXML `<staff>` value.
/// - clef: Optional clef override for this staff in measure-1 attributes.
/// `nil` = inherit the part's clef for this staff (staff 1 typically passes
/// `nil`; the part-level clef is used). Per-staff pitch-range inference is
/// not performed, so passing `Clef.auto` here falls back to treble — pass an
/// explicit `.bass` / `.treble` / etc. for non-default staves.
/// - children: Elements belonging to this staff.
case staff(Int, Clef?, [ScoreElement])
/// A sustain-pedal direction mark — notation-only, no sounding duration.
///
/// Pedal marks are **purely notational**: ``ScorePart/flatten()`` skips them
/// entirely and does **not** emit a ``ScoreEvent`` or advance the beat cursor.
/// They are emitted in MusicXML as `<direction placement="below">` elements
/// containing `<pedal type="start|stop" line="yes"/>`.
///
/// Author a `Pedal(.start)` element at the point where the sustain pedal is
/// depressed and `Pedal(.stop)` where it is released. When the part is
/// multi-staff the pedal direction carries the `<staff>` number of the staff
/// it was authored under.
///
/// ```swift
/// Staff(1, clef: .treble) {
/// Pedal(.start)
/// Note(.c, 4, dur: .whole)
/// Pedal(.stop)
/// }
/// ```
///
/// - Parameter kind: Whether to press (`.start`) or release (`.stop`) the pedal.
case pedal(PedalKind)
/// A slur span applied to a sequence of children.
///
/// A slur is a **purely notational** decoration — it produces `<slur>` elements
/// inside `<notations>` in MusicXML but does **not** change timing, velocity,
/// or the flattened ``ScoreEvent`` list. Flattening a `slur` block is identical
/// to flattening the unwrapped children directly.
///
/// The MusicXML encoder marks the FIRST child atom with
/// `<slur number="1" type="start"/>` and the LAST child atom with
/// `<slur number="1" type="stop"/>`. Grace notes and rests are excluded from
/// slur endpoints. A single-atom span receives both start and stop on one note.
///
/// Use ``slur(_:)`` for clean, non-overlapping spans. For spans that share a
/// boundary with a hairpin (e.g. a slur that begins on the same note where a
/// crescendo also begins), use the per-note ``spanned(_:_:)`` form instead.
///
/// ```swift
/// Slur {
/// Note(.c, 5, dur: .quarter)
/// Note(.d, 5, dur: .quarter)
/// Note(.e, 5, dur: .quarter)
/// Note(.f, 5, dur: .quarter)
/// }
/// ```
///
/// - Parameter children: The notes / chords / rests spanned by the slur.
case slur([ScoreElement])
/// Per-note notation display overrides applied to a single inner element.
///
/// Attaches a ``NoteDisplay`` to a single ``ScoreElement`` (typically a
/// `.note` or `.chord`). This is a **purely notational** wrapper:
/// ``ScorePart/flatten()`` recurses through it transparently — the
/// flattened ``ScoreEvent`` list is identical to the unwrapped inner element.
///
/// The encoder reads ``NoteDisplay/notehead``, ``NoteDisplay/size``,
/// ``NoteDisplay/hideStem``, and ``NoteDisplay/hideBeam`` when emitting
/// MusicXML for the atom(s) produced by `inner`.
///
/// Composes with ``spanned(_:_:)`` by nesting:
/// ```swift
/// // Slur AND a diamond notehead on the same note:
/// .displayed(NoteDisplay(notehead: .diamond), .spanned([.beginSlur], .note(…)))
/// ```
///
/// When ``NoteDisplay/hasOverrides`` is `false` the wrapper is a no-op and
/// produces byte-identical MusicXML output to the unwrapped inner element.
///
/// > Note: `NoteDisplay` is **emit-only** — ``Score/fromMusicXML(data:)``
/// > does not parse `<notehead>`/`<stem>`/`size=` back into `NoteDisplay`.
///
/// - Parameters:
/// - display: The notation overrides to apply to `inner`'s emittable atoms.
/// - inner: The single ``ScoreElement`` whose atoms receive the overrides.
case displayed(NoteDisplay, ScoreElement)
/// Explicit per-note span boundaries on a single inner element.
///
/// Attaches one or more ``Spanner`` boundary annotations to the inner
/// ``ScoreElement``. This is the **general/overlap escape hatch** — use it
/// when a note simultaneously needs to carry boundaries from different,
/// overlapping spans (e.g. a slur-start and a hairpin-stop on the same note).
///
/// The encoder applies each ``Spanner`` case to the first or last emittable
/// atom of `inner` (whichever is appropriate for each boundary direction).
/// Slur and wedge fields on an atom are independent, so multiple spanners
/// compose without conflict:
///
/// ```swift
/// // Slur starts on the same note where the crescendo ends:
/// spanned([.beginSlur, .endHairpin], Note(.c, 5, dur: .quarter))
/// ```
///
/// For clean, non-overlapping slur spans prefer the block form
/// ``slur(_:)``; for hairpin blocks prefer ``Crescendo`` / ``Diminuendo``.
///
/// Flatten transparency: a `spanned` wrapper produces the **same**
/// ``ScoreEvent`` list as the unwrapped inner element — span annotations
/// are notation-only.
///
/// - Parameters:
/// - spanners: One or more boundary annotations to apply to the inner
/// element's first / last emittable atom.
/// - inner: The single ``ScoreElement`` whose atoms receive the annotations.
case spanned([Spanner], ScoreElement)
/// Notation-only marks applied to a single inner element.
///
/// Attaches one or more ``NotationMark`` values to the inner
/// ``ScoreElement`` (typically a `.note` or `.chord`). This is a **purely
/// notational** wrapper: ``ScorePart/flatten()`` recurses through it
/// transparently — the flattened ``ScoreEvent`` list is identical to the
/// unwrapped inner element.
///
/// The encoder emits the marks into `<notations>` in DTD-correct child order
/// (technical → articulations → fermata). Articulation glyphs from `marks:`
/// are merged with any glyph from the note's `art:` parameter into a single
/// `<articulations>` block, deduplicated.
///
/// Constructed by ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` /
/// ``Chord(_:dur:dyn:art:voice:tie:spanners:display:marks:)`` when `marks` is
/// non-empty; an empty `marks:[]` produces the plain element (byte-identical).
///
/// > Note: `marks:` is **emit-only** — ``Score/fromMusicXML(data:)`` does not
/// > parse marks back into `NotationMark` values.
///
/// - Parameters:
/// - marks: One or more notation marks to apply to `inner`'s emittable atoms.
/// - inner: The single ``ScoreElement`` whose atoms receive the marks.
case marked([NotationMark], ScoreElement)
/// Intra-note dynamic curve (messa di voce / swell) on a single inner element.
///
/// Attaches an ordered sequence of `(position, dynamic)` points to the inner
/// ``ScoreElement`` (typically a `.note` or `.chord`). This is a **purely
/// notational** wrapper: ``ScorePart/flatten()`` recurses through it
/// transparently — the flattened ``ScoreEvent`` list and playback velocity are
/// identical to the unwrapped inner element. The note's own `dyn:` parameter
/// still drives the velocity at performance time.
///
/// The encoder emits a run of `<direction>` blocks BEFORE the note, using
/// `<offset>` to position each dynamic and hairpin within the note's sounding
/// duration. The note's normal single-`dyn:` direction is **suppressed** when
/// a curve is present (the curve fully owns the printed dynamics); the
/// per-voice `lastEmittedDynamic` tracker is updated to the curve's final point
/// so the next note's direction is emitted correctly when it differs.
///
/// Points are validated at construction time:
/// - Positions must be in `[0, 1]`.
/// - Positions must be sorted in ascending order.
/// An empty `dynamicCurve: []` produces the plain element (byte-identical).
///
/// > Note: `dynamicCurve:` is **emit-only** — ``Score/fromMusicXML(data:)``
/// > does not reconstruct this wrapper from the emitted `<direction>` /
/// > `<offset>` blocks.
///
/// > Important: The curve directions are emitted at the note's onset with
/// > `<offset>` = `position × note-duration-in-divisions`. On a note that
/// > **crosses a barline**, the larger offsets point past the current measure
/// > (valid MusicXML, but some readers clamp offsets to the bar). Curves are
/// > intended for single-bar notes; for a swell that spans a barline, author
/// > tied pieces with per-piece hairpins instead.
///
/// - Parameters:
/// - points: Ordered `(position: Double, dynamic: Dynamic)` pairs, with
/// `position` in `[0, 1]` relative to the note's sounding duration.
/// - inner: The single ``ScoreElement`` (note or chord) that receives the curve.
case dynamicCurve([(position: Double, dynamic: Dynamic)], ScoreElement)
/// Build-time-resolved measure-fill marker.
///
/// At ``Score`` init time (or ``ScoreSection`` lowering), `FillMeasure` is
/// expanded into a concrete ``.rest(duration:)`` spanning the remaining beats
/// of the current measure under the part's effective ``MeterMap``. If the
/// beat cursor already sits exactly on a barline, no rest is inserted (the
/// element is a no-op). The note following a `FillMeasure` therefore starts
/// on the next downbeat in both flatten and the printed score.
///
/// **Supported positions:** top level of a ``Part`` and inside a ``Voice``
/// block (the voice's local cursor is used for the fill calculation).
///
/// **Not supported inside a ``Tuplet``:** a `fillMeasure` nested inside a
/// tuplet is left unresolved by the expander (tuplet durations are
/// context-dependent and cannot be bar-aligned). It will be treated as a
/// zero-span no-op by flatten and the encoder — it emits nothing but also
/// does not cause an error. Avoid nesting `FillMeasure` inside a tuplet.
///
/// **Outside a ``Score``:** a ``ScorePart`` flattened directly (without being
/// assembled into a ``Score``) leaves `.fillMeasure` unresolved. It will be
/// skipped during flatten (no event, no cursor advance). Always assemble parts
/// into a ``Score`` to ensure fills are resolved.
case fillMeasure
}
+656 -12
View File
@@ -10,38 +10,208 @@ import Foundation
// nested under `ScoreElement`) so score authors can write `Note(.c, 4, dur: …)`
// rather than `ScoreElement.note(...)` or `ScoreElement.Note(...)`.
/// Single note. Defaults: `dynamic = .mf`, `articulation = .normal`, `voice = 0`.
/// Single note. Defaults: `dynamic = .mf`, `articulation = .normal`, `voice = 0`, `tie = false`.
///
/// - Parameters:
/// - pitch: The pitch of the note.
/// - dur: Notated duration (does not include performed length scaling by articulation).
/// - dyn: Dynamic marking. Defaults to `.mf`.
/// - art: Articulation. Defaults to `.normal`. Still drives performance scaling AND
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves (≥ 1, or 0 for the part default). Defaults to `0`.
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// The pair sounds as one sustained note of summed duration, but is notated as two tied
/// noteheads in MusicXML. Tie chains (A.tie→B.tie→C) merge all three into one event.
/// (Chords support ties too via ``Chord(_:dur:dyn:art:voice:tie:)``.) A `tie==true` note
/// whose next element is not a same-pitch same-voice note is treated as untied. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
/// note is returned unchanged (existing output is byte-identical). Use this to author
/// slur or hairpin boundaries that overlap with other spans. Defaults to `[]`.
/// - display: Notation display overrides (notehead shape, note size, stem/beam visibility).
/// When non-nil and ``NoteDisplay/hasOverrides`` is `true`, the note is wrapped in a
/// ``ScoreElement/displayed(_:_:)`` element. A `nil` or all-defaults value leaves the
/// output byte-identical to a note without a display wrapper. Defaults to `nil`.
/// - marks: Extra notation-only marks (additional articulation glyphs, string/instrument
/// technique symbols, fermatas) applied to this note. When non-empty the note is wrapped
/// in a ``ScoreElement/marked(_:_:)`` element; when empty the output is byte-identical to
/// a note without marks. Does NOT affect playback or the flattened ``ScoreEvent`` list.
/// Defaults to `[]`.
/// - dynamicCurve: Intra-note dynamic curve (messa di voce / swell). An ordered sequence of
/// `(position: Double, dynamic: Dynamic)` points, with `position` in `[0, 1]` relative to
/// the note's sounding duration. When non-empty the note is wrapped in a
/// ``ScoreElement/dynamicCurve(_:_:)`` element; when empty the output is byte-identical to
/// a note without a curve. Positions must be sorted ascending and each in `[0, 1]`.
/// Notation-only — does not affect playback or the flattened ``ScoreEvent`` list.
/// Defaults to `[]`.
public func Note(
_ pitch: Pitch,
dur: NoteDuration,
dyn: Dynamic = .mf,
art: Articulation = .normal,
voice: Int = 0
voice: Int = 0,
tie: Bool = false,
spanners: [Spanner] = [],
display: NoteDisplay? = nil,
marks: [NotationMark] = [],
dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
) -> ScoreElement {
.note(pitch, duration: dur, dynamic: dyn, articulation: art, voice: voice)
let base: ScoreElement = .note(
pitch,
duration: dur,
dynamic: dyn,
articulation: art,
voice: voice,
tie: tie
)
// Apply wrappers innermost-first:
// .dynamicCurve(curve, .marked(marks, .displayed(display, .spanned(spanners, .note(...)))))
let withSpanners: ScoreElement = spanners.isEmpty ? base : .spanned(spanners, base)
let withDisplay: ScoreElement = {
guard let disp: NoteDisplay = display, disp.hasOverrides else { return withSpanners }
return .displayed(disp, withSpanners)
}()
let withMarks: ScoreElement = marks.isEmpty ? withDisplay : .marked(marks, withDisplay)
guard !dynamicCurve.isEmpty else { return withMarks }
precondition(
dynamicCurve.allSatisfy({ $0.position >= 0.0 && $0.position <= 1.0 }),
"Note dynamicCurve: all positions must be in [0, 1]"
)
precondition(
zip(dynamicCurve, dynamicCurve.dropFirst()).allSatisfy({ $0.position <= $1.position }),
"Note dynamicCurve: positions must be sorted in ascending order"
)
return .dynamicCurve(dynamicCurve, withMarks)
}
/// Convenience: note via ``NoteName`` + octave.
///
/// - Parameters:
/// - name: Note name (letter + accidental).
/// - octave: Octave number (MIDI convention — C4 = middle C = MIDI 60).
/// - dur: Notated duration.
/// - dyn: Dynamic marking. Defaults to `.mf`.
/// - art: Articulation. Defaults to `.normal`. Still drives performance scaling AND
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// See ``Note(_:dur:dyn:art:voice:tie:)`` for full semantics. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
/// note is returned unchanged (existing output is byte-identical). Defaults to `[]`.
/// - display: Notation display overrides (notehead shape, note size, stem/beam visibility).
/// When non-nil and ``NoteDisplay/hasOverrides`` is `true`, the note is wrapped in a
/// ``ScoreElement/displayed(_:_:)`` element. A `nil` or all-defaults value leaves the
/// output byte-identical to a note without a display wrapper. Defaults to `nil`.
/// - marks: Extra notation-only marks (additional articulation glyphs, string/instrument
/// technique symbols, fermatas) applied to this note. When non-empty the note is wrapped
/// in a ``ScoreElement/marked(_:_:)`` element; when empty the output is byte-identical to
/// a note without marks. Does NOT affect playback or the flattened ``ScoreEvent`` list.
/// Defaults to `[]`.
/// - dynamicCurve: Intra-note dynamic curve (messa di voce / swell). See
/// ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full
/// semantics. Defaults to `[]`.
public func Note(
_ name: NoteName,
_ octave: Int,
dur: NoteDuration,
dyn: Dynamic = .mf,
art: Articulation = .normal,
voice: Int = 0
voice: Int = 0,
tie: Bool = false,
spanners: [Spanner] = [],
display: NoteDisplay? = nil,
marks: [NotationMark] = [],
dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
) -> ScoreElement {
.note(.named(name, octave), duration: dur, dynamic: dyn, articulation: art, voice: voice)
let base: ScoreElement = .note(
.named(name, octave),
duration: dur,
dynamic: dyn,
articulation: art,
voice: voice,
tie: tie
)
let withSpanners: ScoreElement = spanners.isEmpty ? base : .spanned(spanners, base)
let withDisplay: ScoreElement = {
guard let disp: NoteDisplay = display, disp.hasOverrides else { return withSpanners }
return .displayed(disp, withSpanners)
}()
let withMarks: ScoreElement = marks.isEmpty ? withDisplay : .marked(marks, withDisplay)
guard !dynamicCurve.isEmpty else { return withMarks }
precondition(
dynamicCurve.allSatisfy({ $0.position >= 0.0 && $0.position <= 1.0 }),
"Note dynamicCurve: all positions must be in [0, 1]"
)
precondition(
zip(dynamicCurve, dynamicCurve.dropFirst()).allSatisfy({ $0.position <= $1.position }),
"Note dynamicCurve: positions must be sorted in ascending order"
)
return .dynamicCurve(dynamicCurve, withMarks)
}
/// Convenience: note via MIDI integer.
///
/// - Parameters:
/// - midi: MIDI note number `[0, 127]`. Converted to the closest natural-letter spelling.
/// - dur: Notated duration.
/// - dyn: Dynamic marking. Defaults to `.mf`.
/// - art: Articulation. Defaults to `.normal`. Still drives performance scaling AND
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this note to the immediately-following same-pitch note.
/// See ``Note(_:dur:dyn:art:voice:tie:)`` for full semantics. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this note. When non-empty
/// the note is wrapped in a ``ScoreElement/spanned(_:_:)`` element; when empty the plain
/// note is returned unchanged (existing output is byte-identical). Defaults to `[]`.
/// - display: Notation display overrides (notehead shape, note size, stem/beam visibility).
/// When non-nil and ``NoteDisplay/hasOverrides`` is `true`, the note is wrapped in a
/// ``ScoreElement/displayed(_:_:)`` element. A `nil` or all-defaults value leaves the
/// output byte-identical to a note without a display wrapper. Defaults to `nil`.
/// - marks: Extra notation-only marks (additional articulation glyphs, string/instrument
/// technique symbols, fermatas) applied to this note. When non-empty the note is wrapped
/// in a ``ScoreElement/marked(_:_:)`` element; when empty the output is byte-identical to
/// a note without marks. Does NOT affect playback or the flattened ``ScoreEvent`` list.
/// Defaults to `[]`.
/// - dynamicCurve: Intra-note dynamic curve (messa di voce / swell). See
/// ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full
/// semantics. Defaults to `[]`.
public func Note(
midi: Int,
dur: NoteDuration,
dyn: Dynamic = .mf,
art: Articulation = .normal,
voice: Int = 0
voice: Int = 0,
tie: Bool = false,
spanners: [Spanner] = [],
display: NoteDisplay? = nil,
marks: [NotationMark] = [],
dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
) -> ScoreElement {
.note(.midi(midi), duration: dur, dynamic: dyn, articulation: art, voice: voice)
let base: ScoreElement = .note(
.midi(midi),
duration: dur,
dynamic: dyn,
articulation: art,
voice: voice,
tie: tie
)
let withSpanners: ScoreElement = spanners.isEmpty ? base : .spanned(spanners, base)
let withDisplay: ScoreElement = {
guard let disp: NoteDisplay = display, disp.hasOverrides else { return withSpanners }
return .displayed(disp, withSpanners)
}()
let withMarks: ScoreElement = marks.isEmpty ? withDisplay : .marked(marks, withDisplay)
guard !dynamicCurve.isEmpty else { return withMarks }
precondition(
dynamicCurve.allSatisfy({ $0.position >= 0.0 && $0.position <= 1.0 }),
"Note dynamicCurve: all positions must be in [0, 1]"
)
precondition(
zip(dynamicCurve, dynamicCurve.dropFirst()).allSatisfy({ $0.position <= $1.position }),
"Note dynamicCurve: positions must be sorted in ascending order"
)
return .dynamicCurve(dynamicCurve, withMarks)
}
/// Rest of the given duration.
@@ -51,26 +221,137 @@ public func Rest(dur: NoteDuration) -> ScoreElement {
/// Chord — multiple pitches sharing the same start, duration, dynamic, and
/// articulation. Splits into N ``ScoreEvent`` instances at flatten time.
///
/// - Parameters:
/// - pitches: Array of ``Pitch`` values for this chord.
/// - dur: Notated duration shared by all noteheads.
/// - dyn: Dynamic marking. Defaults to `.mf`.
/// - art: Articulation. Defaults to `.normal`. Still drives performance scaling AND
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this chord to the immediately-following chord
/// that has the **same pitch set** (order-insensitive) and the same voice.
/// Every notehead sustains across the notation boundary and the two chord
/// stacks sound as one chord of summed duration. A `tie==true` chord whose
/// next element is not a same-pitch-set same-voice chord is treated as
/// untied — no merge and no tie annotation. Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this chord. When
/// non-empty the chord is wrapped in a ``ScoreElement/spanned(_:_:)`` element;
/// when empty the plain chord is returned unchanged. Defaults to `[]`.
/// - display: Notation display overrides (notehead shape, note size, stem/beam visibility)
/// applied to all noteheads of the chord. When non-nil and ``NoteDisplay/hasOverrides``
/// is `true`, the chord is wrapped in a ``ScoreElement/displayed(_:_:)`` element.
/// A `nil` or all-defaults value leaves the output byte-identical. Defaults to `nil`.
/// - marks: Extra notation-only marks (additional articulation glyphs, string/instrument
/// technique symbols, fermatas) applied to all noteheads of the chord. When non-empty
/// the chord is wrapped in a ``ScoreElement/marked(_:_:)`` element; when empty the
/// output is byte-identical to a chord without marks. Does NOT affect playback.
/// Defaults to `[]`.
/// - dynamicCurve: Intra-note dynamic curve (messa di voce / swell). See
/// ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full
/// semantics. Defaults to `[]`.
public func Chord(
_ pitches: [Pitch],
dur: NoteDuration,
dyn: Dynamic = .mf,
art: Articulation = .normal,
voice: Int = 0
voice: Int = 0,
tie: Bool = false,
spanners: [Spanner] = [],
display: NoteDisplay? = nil,
marks: [NotationMark] = [],
dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
) -> ScoreElement {
.chord(pitches, duration: dur, dynamic: dyn, articulation: art, voice: voice)
let base: ScoreElement = .chord(
pitches,
duration: dur,
dynamic: dyn,
articulation: art,
voice: voice,
tie: tie
)
let withSpanners: ScoreElement = spanners.isEmpty ? base : .spanned(spanners, base)
let withDisplay: ScoreElement = {
guard let disp: NoteDisplay = display, disp.hasOverrides else { return withSpanners }
return .displayed(disp, withSpanners)
}()
let withMarks: ScoreElement = marks.isEmpty ? withDisplay : .marked(marks, withDisplay)
guard !dynamicCurve.isEmpty else { return withMarks }
precondition(
dynamicCurve.allSatisfy({ $0.position >= 0.0 && $0.position <= 1.0 }),
"Chord dynamicCurve: all positions must be in [0, 1]"
)
precondition(
zip(dynamicCurve, dynamicCurve.dropFirst()).allSatisfy({ $0.position <= $1.position }),
"Chord dynamicCurve: positions must be sorted in ascending order"
)
return .dynamicCurve(dynamicCurve, withMarks)
}
/// Convenience: chord built from `(name, octave)` pairs.
///
/// - Parameters:
/// - pairs: Array of `(NoteName, octave)` pairs describing chord pitches.
/// - dur: Notated duration shared by all noteheads.
/// - dyn: Dynamic marking. Defaults to `.mf`.
/// - art: Articulation. Defaults to `.normal`. Still drives performance scaling AND
/// emits its own notation glyph. Use `marks:` to add extra notation-only glyphs.
/// - voice: Voice number for multi-voice staves. Defaults to `0`.
/// - tie: When `true`, ties this chord to the immediately-following chord
/// that has the **same pitch set** (order-insensitive) and the same voice.
/// See ``Chord(_:dur:dyn:art:voice:tie:)`` for full semantics.
/// Defaults to `false`.
/// - spanners: Explicit span-boundary annotations to apply to this chord. When
/// non-empty the chord is wrapped in a ``ScoreElement/spanned(_:_:)`` element;
/// when empty the plain chord is returned unchanged. Defaults to `[]`.
/// - display: Notation display overrides applied to all noteheads of the chord.
/// When non-nil and ``NoteDisplay/hasOverrides`` is `true`, the chord is wrapped
/// in a ``ScoreElement/displayed(_:_:)`` element. Defaults to `nil`.
/// - marks: Extra notation-only marks (additional articulation glyphs, string/instrument
/// technique symbols, fermatas) applied to all noteheads of the chord. When non-empty
/// the chord is wrapped in a ``ScoreElement/marked(_:_:)`` element; when empty the
/// output is byte-identical to a chord without marks. Does NOT affect playback.
/// Defaults to `[]`.
/// - dynamicCurve: Intra-note dynamic curve (messa di voce / swell). See
/// ``Note(_:dur:dyn:art:voice:tie:spanners:display:marks:dynamicCurve:)`` for full
/// semantics. Defaults to `[]`.
public func Chord(
_ pairs: [(NoteName, Int)],
dur: NoteDuration,
dyn: Dynamic = .mf,
art: Articulation = .normal,
voice: Int = 0
voice: Int = 0,
tie: Bool = false,
spanners: [Spanner] = [],
display: NoteDisplay? = nil,
marks: [NotationMark] = [],
dynamicCurve: [(position: Double, dynamic: Dynamic)] = []
) -> ScoreElement {
let pitches: [Pitch] = pairs.map { Pitch.named($0.0, $0.1) }
return .chord(pitches, duration: dur, dynamic: dyn, articulation: art, voice: voice)
let base: ScoreElement = .chord(
pitches,
duration: dur,
dynamic: dyn,
articulation: art,
voice: voice,
tie: tie
)
let withSpanners: ScoreElement = spanners.isEmpty ? base : .spanned(spanners, base)
let withDisplay: ScoreElement = {
guard let disp: NoteDisplay = display, disp.hasOverrides else { return withSpanners }
return .displayed(disp, withSpanners)
}()
let withMarks: ScoreElement = marks.isEmpty ? withDisplay : .marked(marks, withDisplay)
guard !dynamicCurve.isEmpty else { return withMarks }
precondition(
dynamicCurve.allSatisfy({ $0.position >= 0.0 && $0.position <= 1.0 }),
"Chord dynamicCurve: all positions must be in [0, 1]"
)
precondition(
zip(dynamicCurve, dynamicCurve.dropFirst()).allSatisfy({ $0.position <= $1.position }),
"Chord dynamicCurve: positions must be sorted in ascending order"
)
return .dynamicCurve(dynamicCurve, withMarks)
}
/// Tuplet wrapper — `actual` notes performed in the time of `normal` notes.
@@ -78,13 +359,376 @@ public func Chord(
/// Triplet is `Tuplet(3, inTimeOf: 2) { … }`. Quintuplet is `Tuplet(5, inTimeOf: 4) { … }`.
/// Ratios compose under nesting via fraction multiplication; no FP drift.
///
/// Pass `noteDuration:` to declare the tuplet's base note value (e.g.
/// `Tuplet(3, inTimeOf: 2, noteDuration: .quarter)` = three quarter-notes in the
/// time of two). This is self-documenting AND validated: if the children's total
/// notated duration does not equal `actual × noteDuration` (e.g. a whole note
/// inside a quarter triplet), a warning is emitted to stderr and the
/// ``LyrebirdMessageCenter`` — the contents would over- or under-fill the bracket
/// and push the bar out of alignment. Without `noteDuration` (the default) the
/// tuplet accepts any contents and is not validated.
///
/// - Precondition: `actual >= 2` and `normal >= 1`.
public func Tuplet(
_ actual: Int,
inTimeOf normal: Int,
noteDuration: NoteDuration? = nil,
@ScoreBuilder children: () -> [ScoreElement]
) -> ScoreElement {
precondition(actual >= 2, "Tuplet: actual must be >= 2, got \(actual)")
precondition(normal >= 1, "Tuplet: normal must be >= 1, got \(normal)")
return .tuplet(actual: actual, normal: normal, children: children())
let kids: [ScoreElement] = children()
if let base: NoteDuration = noteDuration,
let warning: String = tupletContentsMismatchWarning(
actual: actual,
normal: normal,
noteDuration: base,
children: kids
) {
fputs("[Lyrebird] warning: \(warning)\n", stderr)
Task { @MainActor in
LyrebirdMessageCenter.shared.warning(warning, source: "Tuplet")
}
}
return .tuplet(actual: actual, normal: normal, normalType: noteDuration, children: kids)
}
/// Validate that a tuplet's children fill its declared `noteDuration` bracket.
///
/// The children's total occupancy (summed via ``scoreElementBeatSpan``) must equal
/// `actual × noteDuration` quarter-beats — the bracket's nominal length. A nested
/// tuplet contributes its **compressed** span (a 3:2 triplet occupies the time of
/// its `inTimeOf` value, not its note count), so nested tuplets validate correctly.
/// Returns a human-readable warning on mismatch, or `nil` when the contents fill
/// the bracket exactly.
///
/// - Parameters:
/// - actual: The tuplet's `actual` count (number of `noteDuration` notes).
/// - normal: The tuplet's `inTimeOf` count (for the message text).
/// - noteDuration: The declared base note value of the tuplet.
/// - children: The authored child elements.
/// - Returns: A warning string, or `nil` when the contents match.
func tupletContentsMismatchWarning(
actual: Int,
normal: Int,
noteDuration: NoteDuration,
children: [ScoreElement]
) -> String? {
let expected: Fraction = noteDurationFraction(noteDuration)
* Fraction(num: Int64(actual), den: 1)
let contentsTotal: Fraction = children.reduce(Fraction.zero) {
$0 + scoreElementBeatSpan($1)
}
guard contentsTotal != expected else { return nil }
let perNote: Double = noteDurationFraction(noteDuration).double
let direction: String = contentsTotal > expected ? "over-fill" : "under-fill"
return "Tuplet(\(actual), inTimeOf: \(normal)) declared noteDuration "
+ "\(perNote) quarter-beats: contents total \(contentsTotal.double) "
+ "quarter-beats, but \(actual) such notes span \(expected.double). The "
+ "contents \(direction) the tuplet bracket and will push the bar out of "
+ "alignment. (Nested tuplets count by their compressed span: a 3:2 "
+ "triplet occupies the time of its `inTimeOf` value, not its note count.)"
}
/// Independent polyphonic voice within a ``Part``.
///
/// Each `Voice` block starts its own cursor at beat zero rather than continuing
/// from where the previous block left off. Multiple `Voice` blocks in the same
/// `Part` body overlay each other: voice 1 is emitted first in MusicXML, then
/// a `<backup>` rewinds the cursor, then voice 2, and so on.
///
/// Single-voice parts (no `Voice` wrapper) continue to emit exactly as before
/// with no `<backup>` elements. The multi-voice encoder path is only activated
/// when the part's top-level element list contains at least one `.voice(...)` case.
///
/// ```swift
/// Part("piano") {
/// Voice(1) {
/// Note(.e, 5, dur: .half) // upper voice
/// Note(.d, 5, dur: .half)
/// }
/// Voice(2) {
/// Note(.c, 4, dur: .whole) // lower voice (overlays from beat 0)
/// }
/// }
/// ```
///
/// - Parameters:
/// - number: Voice number (≥ 1). Becomes the MusicXML `<voice>` value.
/// - elements: Result-builder block of ``ScoreElement`` for this voice.
public func Voice(
_ number: Int,
@ScoreBuilder elements: () -> [ScoreElement]
) -> ScoreElement {
precondition(number >= 1, "Voice: number must be >= 1, got \(number)")
return .voice(number, elements())
}
/// Crescendo hairpin span — draws a `<` wedge under the staff from the first
/// to the last child note in MusicXML.
///
/// A crescendo is **purely notational**: it does NOT change timing, velocity,
/// or the flattened ``ScoreEvent`` list. The encoder marks the first child atom
/// with `<wedge type="crescendo"/>` and the last with `<wedge type="stop"/>`;
/// intermediate notes carry no extra markup.
///
/// Nested inside a ``Tuplet`` or ``Voice``: the wedge still marks the first and
/// last atoms of the span, regardless of how many measures or tuplet groups they
/// span.
///
/// ```swift
/// Crescendo {
/// Note(.c, 5, dur: .quarter, dyn: .p)
/// Note(.d, 5, dur: .quarter)
/// Note(.e, 5, dur: .quarter)
/// Note(.f, 5, dur: .quarter, dyn: .f)
/// }
/// ```
///
/// - Parameter elements: Notes / rests / chords spanned by the hairpin.
public func Crescendo(
@ScoreBuilder _ elements: () -> [ScoreElement]
) -> ScoreElement {
.wedge(.crescendo, elements())
}
/// Diminuendo hairpin span — draws a `>` wedge under the staff from the first
/// to the last child note in MusicXML.
///
/// A diminuendo is **purely notational**: it does NOT change timing, velocity,
/// or the flattened ``ScoreEvent`` list. The encoder marks the first child atom
/// with `<wedge type="diminuendo"/>` and the last with `<wedge type="stop"/>`;
/// intermediate notes carry no extra markup.
///
/// ```swift
/// Diminuendo {
/// Note(.f, 5, dur: .quarter, dyn: .f)
/// Note(.e, 5, dur: .quarter)
/// Note(.d, 5, dur: .quarter)
/// Note(.c, 5, dur: .quarter, dyn: .p)
/// }
/// ```
///
/// - Parameter elements: Notes / rests / chords spanned by the hairpin.
public func Diminuendo(
@ScoreBuilder _ elements: () -> [ScoreElement]
) -> ScoreElement {
.wedge(.diminuendo, elements())
}
/// Grace note — a small ornamental notehead with no beat-grid duration.
///
/// Grace notes are **notation-only**: ``ScorePart/flatten()`` skips them and
/// produces no ``ScoreEvent``. They do **not** advance the beat cursor. Author
/// a `Grace` element immediately before the main note it ornaments.
///
/// When `slashed` is `true` (the default), a slash is drawn through the stem
/// indicating an **acciaccatura** — a quick, crushed ornament. When `slashed`
/// is `false`, an **appoggiatura** — a leaning ornament played with more weight.
///
/// ```swift
/// Grace(.fSharp, 5) // acciaccatura (slashed = true by default)
/// Note(.g, 5, dur: .quarter) // main note the grace ornaments
/// ```
///
/// Multiple consecutive `Grace` elements before a note form a grace-note group.
///
/// **Playback**: grace notes are currently notation-only. Sound realization is
/// planned for a future phase.
///
/// - Parameters:
/// - pitch: The pitch of the grace note.
/// - slashed: `true` = acciaccatura (slashed stem); `false` = appoggiatura.
/// Defaults to `true`.
public func Grace(
_ pitch: Pitch,
slashed: Bool = true
) -> ScoreElement {
.grace(pitch, slashed: slashed)
}
/// Convenience: grace note via ``NoteName`` + octave.
///
/// - Parameters:
/// - name: Note name (letter + accidental).
/// - octave: Octave number (MIDI convention — C4 = middle C = MIDI 60).
/// - slashed: `true` = acciaccatura (slashed stem); `false` = appoggiatura.
/// Defaults to `true`.
public func Grace(
_ name: NoteName,
_ octave: Int,
slashed: Bool = true
) -> ScoreElement {
.grace(.named(name, octave), slashed: slashed)
}
/// Multi-staff block — groups elements that belong to a specific notated staff
/// within a part (e.g. left/right hand of a piano grand staff).
///
/// Each `Staff` block starts its own cursor at beat zero and overlays the part
/// from that point, analogous to ``Voice(_:elements:)``. Multiple `Staff` blocks
/// at the top level of a `Part` body are rendered simultaneously.
///
/// Staff numbers are 1-based and map to MusicXML `<staff>` values. When more
/// than one distinct staff is present the encoder emits `<staves>N</staves>` and
/// one `<clef number="k">` per staff in measure-1 `<attributes>`. Single-staff
/// parts emit **unchanged** output (no `<staves>`, bare `<clef>` without a
/// `number=` attribute) — existing tests are unaffected.
///
/// `flatten()` recurses into staff children so their notes produce
/// ``ScoreEvent`` instances — the staff assignment is notation-only.
///
/// Voice numbers must be unique across ALL staves in the same part. The
/// recommended convention for a grand-staff piano is voices 1–2 on staff 1
/// and voices 3–4 on staff 2; MusicXML requires voices to be unique part-wide.
///
/// ```swift
/// Part("piano") {
/// Staff(1) {
/// Voice(1) { Note(.e, 5, dur: .half) }
/// Voice(2) { Note(.c, 4, dur: .whole) }
/// }
/// Staff(2, clef: .bass) {
/// Voice(3) { Note(.c, 3, dur: .whole) }
/// }
/// }
/// ```
///
/// - Parameters:
/// - number: Staff number (≥ 1). Becomes the MusicXML `<staff>` value on every
/// note authored under this block.
/// - clef: Optional clef for this staff in measure-1 `<attributes>`.
/// `nil` (default) inherits the part-level clef for staff 1 and renders
/// `.treble` for any additional staves unless overridden here. Per-staff
/// pitch-range inference is not performed, so `Clef.auto` falls back to
/// treble — pass an explicit clef (e.g. `.bass`) for non-default staves.
/// - elements: Result-builder block of ``ScoreElement`` for this staff.
public func Staff(
_ number: Int,
clef: Clef? = nil,
@ScoreBuilder elements: () -> [ScoreElement]
) -> ScoreElement {
precondition(number >= 1, "Staff: number must be >= 1, got \(number)")
return .staff(number, clef, elements())
}
/// Sustain-pedal direction mark — notation-only, no sounding duration.
///
/// Pedal marks are **purely notational**: ``ScorePart/flatten()`` skips them
/// and produces no ``ScoreEvent``. They do **not** advance the beat cursor.
/// Author `Pedal(.start)` at the point the pedal is pressed and `Pedal(.stop)`
/// where it is released. Emitted in MusicXML as:
///
/// ```xml
/// <direction placement="below">
/// <direction-type>
/// <pedal type="start" line="yes"/>
/// </direction-type>
/// </direction>
/// ```
///
/// When the part is multi-staff the direction carries `<staff>k</staff>`
/// matching the staff it was authored under.
///
/// **Playback**: pedal marks are currently notation-only. ``ScorePlayer``
/// and audio rendering do not realize them as controller messages.
///
/// - Parameter kind: ``PedalKind/start`` to depress or ``PedalKind/stop``
/// to release the sustain pedal.
public func Pedal(_ kind: PedalKind) -> ScoreElement {
.pedal(kind)
}
/// Mid-voice clef change — the staff switches clef from this point onward.
///
/// A clef change is **notation-only**: ``ScorePart/flatten()`` skips it and
/// produces no ``ScoreEvent``. It does **not** advance the beat cursor and never
/// alters sounding pitch (MusicXML pitches are absolute; the clef changes only
/// how following notes are drawn). Author a `ClefChange` element immediately
/// before the first note that should appear under the new clef.
///
/// ```swift
/// Part("cello", clef: .bass) {
/// Note(.named(.c, 2), dur: .half)
/// ClefChange(.tenor) // switch to tenor clef for the high passage
/// Note(.named(.c, 4), dur: .half)
/// }
/// ```
///
/// The part's *initial* clef stays the ``Part(_:channel:clef:keySignature:transpose:_:)``
/// `clef:` argument (emitted in measure-1 attributes); `ClefChange` layers on top.
///
/// - Parameter clef: The clef to switch to. Must **not** be ``Clef/auto`` —
/// `.auto` infers a clef from a part's median pitch and has no meaning at a
/// single point; passing it traps.
public func ClefChange(_ clef: Clef) -> ScoreElement {
precondition(
clef != .auto,
"ClefChange(.auto) is invalid — .auto infers a clef from a part's median pitch and has no meaning at a point. Pass an explicit clef (.treble / .bass / .alto / .tenor / .treble8vb / .percussion)."
)
return .clefChange(clef)
}
/// Measure-fill pad — inserts a rest from the current beat cursor to the next
/// barline of the part's effective meter.
///
/// `FillMeasure()` is resolved at ``Score`` init time into a concrete
/// ``.rest(duration:)`` equal to the beats remaining until the next barline.
/// If the cursor already sits exactly on a barline it is a no-op (no rest is
/// inserted). The element following a `FillMeasure()` therefore begins on the
/// next downbeat in both flatten output and the printed score.
///
/// ```swift
/// // 4/4: 3 beats of content → FillMeasure() inserts a 1-beat rest
/// Part("lead") {
/// Note(.c, 4, dur: .quarter) // beat 0
/// Note(.d, 4, dur: .quarter) // beat 1
/// Note(.e, 4, dur: .quarter) // beat 2
/// FillMeasure() // → Rest(.quarter) to beat 4
/// Note(.f, 4, dur: .quarter) // beat 4 (first beat of bar 2)
/// }
///
/// // Already on a barline: no rest inserted
/// Part("lead") {
/// Generate(4) { Note(.c, 4, dur: .quarter) } // fills 4/4 exactly
/// FillMeasure() // no-op
/// Note(.g, 4, dur: .quarter) // beat 4
/// }
/// ```
///
/// **Limitations:** not supported inside a ``Tuplet`` (left unresolved →
/// treated as a zero-span no-op). Always assemble the part inside a ``Score``
/// to trigger expansion; a ``ScorePart`` flattened in isolation leaves
/// `FillMeasure` unresolved and it will be silently skipped.
public func FillMeasure() -> ScoreElement {
.fillMeasure
}
/// Slur span — draws a slur arc from the first to the last child note in MusicXML.
///
/// A slur is **purely notational**: it does NOT change timing, velocity, or the
/// flattened ``ScoreEvent`` list. The encoder marks the first child atom with
/// `<slur number="1" type="start"/>` and the last child atom with
/// `<slur number="1" type="stop"/>` inside their `<notations>` blocks.
/// Grace notes and rests are excluded from slur endpoints. A single-atom span
/// receives both start and stop on the same note.
///
/// For overlapping spans — e.g. a slur that begins on the same note where a
/// crescendo ends — use the per-note ``spanners:`` parameter on ``Note`` or
/// ``Chord`` instead (wraps the note in a ``ScoreElement/spanned(_:_:)`` block).
///
/// ```swift
/// Slur {
/// Note(.c, 5, dur: .quarter)
/// Note(.d, 5, dur: .quarter)
/// Note(.e, 5, dur: .quarter)
/// Note(.f, 5, dur: .quarter)
/// }
/// ```
///
/// - Parameter elements: Notes / rests / chords spanned by the slur.
public func Slur(
@ScoreBuilder _ elements: () -> [ScoreElement]
) -> ScoreElement {
.slur(elements())
}
+19 -4
View File
@@ -7,18 +7,26 @@
import Foundation
/// One realized musical event after flattening — a note (or rest) with an
/// absolute beat position, played duration, normalized velocity, and optional
/// absolute beat position, notated duration, normalized velocity, and optional
/// articulation.
///
/// A `ScoreEvent` is the output of ``Score/flatten()`` — every tuplet has been
/// resolved, every chord has been split into one event per pitch, and every
/// articulation's effect on duration / velocity has already been applied.
/// resolved and every chord has been split into one event per pitch.
/// ``duration`` is the **notated** (pre-articulation) duration in beats;
/// articulation duration-scaling is **not** baked in. Use ``performedDuration``
/// for audio/MIDI note-length decisions, and ``duration`` for engraving and
/// MusicXML generation.
public struct ScoreEvent: Sendable, Equatable {
/// Absolute beat position from the start of the part (one beat = one quarter note).
public let beat: Double
/// Played duration in beats (after articulation scaling).
/// Notated duration in beats (pre-articulation, as written in the score).
///
/// This is the duration as written — for example, a staccato quarter note
/// has `duration == 1.0` regardless of the articulation's shortening.
/// Use ``performedDuration`` for audio note length, MIDI/SMF note-off
/// timing, and any sounding-length decision.
public let duration: Double
/// Pitch — `.rest` for rests.
@@ -65,5 +73,12 @@ public struct ScoreEvent: Sendable, Equatable {
if case .rest = pitch { return true }
return false
}
/// Performance (sounding) duration in beats: the notated ``duration``
/// scaled by the articulation's ``Articulation/durationScale``
/// (e.g. staccato shortens, legato lengthens). Use this for audio
/// note length, MIDI/SMF note-off timing, and any sounding-length
/// decision; use ``duration`` for engraving / MusicXML.
public var performedDuration: Double { duration * articulation.durationScale }
}
@@ -0,0 +1,147 @@
// ScoreGenerative.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// Algorithmic / programmatic generators for the score DSL. Each returns a flat
// `[ScoreElement]` array that drops straight into a `Part`/`Tuplet`/`Voice`
// body via the builder's `buildExpression(_:)` array overload — no new
// result-builder type required. Pair these with plain Swift `for` loops when a
// one-off run is enough; reach for `Generate`/`PatternNotes` when the run is
// reusable, index-driven, or fed by a `Pattern`.
/// Index-driven element generation. Maps each index `0 ..< count` through a
/// result-builder closure and flattens the results into one `[ScoreElement]`.
///
/// The closure body is a full ``ScoreBuilder`` block, so a single `Note(...)`
/// works, and so do loops, `if`/`else`, chords, and nested `Tuplet`/`Voice`
/// blocks — each index may emit zero, one, or many elements.
///
/// ```swift
/// Part("lead") {
/// // 1000 sixteenth notes walking a whole-tone scale.
/// Generate(1000) { i in
/// Note(midi: 48 + (i % 12), dur: .sixteenth, dyn: .mp)
/// }
/// }
/// ```
///
/// - Parameters:
/// - count: Number of indices to generate. Must be `>= 0`. `0` yields `[]`.
/// - body: Builder closure mapping an index to the element(s) at that index.
/// - Returns: The concatenated elements for indices `0 ..< count`.
public func Generate(
_ count: Int,
@ScoreBuilder _ body: (Int) -> [ScoreElement]
) -> [ScoreElement] {
precondition(count >= 0, "Generate: count must be >= 0, got \(count)")
return (0..<count).flatMap(body)
}
/// Notes pulled from a ``Pattern`` of ``Pitch`` values, with optional
/// per-note rhythm and dynamic patterns.
///
/// Up to `count` notes are emitted. The `pitches` pattern drives length: if it
/// exhausts (its ``Pattern/next()`` returns `nil`) before `count` is reached,
/// generation stops early. The `durations` and `dynamics` patterns, when given,
/// supply one value per note; when omitted — or when they exhaust before the
/// pitch pattern — the scalar `dur` / `dyn` fallback is used instead.
///
/// ```swift
/// let pitchPat: Pattern<Pitch> = Pattern.sequence(
/// [.named(.c, 5), .named(.e, 5), .named(.g, 5)], repeats: 8
/// )
/// let rhythmPat: Pattern<NoteDuration> = Pattern.sequence([.eighth, .eighth, .quarter])
/// Part("lead") {
/// PatternNotes(count: 24, pitches: pitchPat, durations: rhythmPat, dyn: .mp)
/// }
/// ```
///
/// - Parameters:
/// - count: Maximum number of notes to emit (`>= 0`). Generation may stop
/// earlier if `pitches` exhausts first.
/// - pitches: Pitch source. Drives the run length.
/// - dur: Fallback notated duration used when `durations` is `nil` or exhausted.
/// Defaults to `.quarter`.
/// - durations: Optional per-note duration source. Defaults to `nil`.
/// - dyn: Fallback dynamic used when `dynamics` is `nil` or exhausted.
/// Defaults to `.mf`.
/// - dynamics: Optional per-note dynamic source. Defaults to `nil`.
/// - art: Articulation applied to every note. Defaults to `.normal`.
/// - Returns: The generated notes as `[ScoreElement]`.
public func PatternNotes(
count: Int,
pitches: Pattern<Pitch>,
dur: NoteDuration = .quarter,
durations: Pattern<NoteDuration>? = nil,
dyn: Dynamic = .mf,
dynamics: Pattern<Dynamic>? = nil,
art: Articulation = .normal
) -> [ScoreElement] {
precondition(count >= 0, "PatternNotes: count must be >= 0, got \(count)")
var out: [ScoreElement] = []
out.reserveCapacity(count)
for _: Int in 0..<count {
guard let pitch: Pitch = pitches.next() else { break }
let noteDur: NoteDuration = durations?.next() ?? dur
let noteDyn: Dynamic = dynamics?.next() ?? dyn
out.append(.note(pitch, duration: noteDur, dynamic: noteDyn, articulation: art, voice: 0, tie: false))
}
return out
}
/// Notes pulled from a ``Pattern`` of MIDI numbers (as `Double`), with optional
/// per-note rhythm and dynamic patterns.
///
/// Convenience over ``PatternNotes(count:pitches:dur:durations:dyn:dynamics:art:)``
/// for the common case where the pitch source is a numeric pattern
/// (`series`, `brownian`, `uniformRandom`, …). Each pulled value is rounded to
/// the nearest integer and clamped to the valid MIDI range `[0, 127]`.
///
/// ```swift
/// // A 1000-note Brownian walk between MIDI 48 and 84.
/// let walk: Pattern<Double> = Pattern.brownian(low: 48, high: 84, step: 3, length: 1000)
/// Part("lead") {
/// PatternNotes(count: 1000, midi: walk, dur: .sixteenth, dyn: .mp)
/// }
/// ```
///
/// - Parameters:
/// - count: Maximum number of notes to emit (`>= 0`). Generation may stop
/// earlier if `midi` exhausts first.
/// - midi: MIDI-number source. Values are rounded and clamped to `[0, 127]`.
/// - dur: Fallback notated duration used when `durations` is `nil` or exhausted.
/// Defaults to `.quarter`.
/// - durations: Optional per-note duration source. Defaults to `nil`.
/// - dyn: Fallback dynamic used when `dynamics` is `nil` or exhausted.
/// Defaults to `.mf`.
/// - dynamics: Optional per-note dynamic source. Defaults to `nil`.
/// - art: Articulation applied to every note. Defaults to `.normal`.
/// - Returns: The generated notes as `[ScoreElement]`.
public func PatternNotes(
count: Int,
midi: Pattern<Double>,
dur: NoteDuration = .quarter,
durations: Pattern<NoteDuration>? = nil,
dyn: Dynamic = .mf,
dynamics: Pattern<Dynamic>? = nil,
art: Articulation = .normal
) -> [ScoreElement] {
precondition(count >= 0, "PatternNotes: count must be >= 0, got \(count)")
let midiLowerBound: Int = 0
let midiUpperBound: Int = 127
var out: [ScoreElement] = []
out.reserveCapacity(count)
for _: Int in 0..<count {
guard let raw: Double = midi.next() else { break }
let rounded: Int = Int(raw.rounded())
let clamped: Int = min(midiUpperBound, max(midiLowerBound, rounded))
let noteDur: NoteDuration = durations?.next() ?? dur
let noteDyn: Dynamic = dynamics?.next() ?? dyn
out.append(.note(.midi(clamped), duration: noteDur, dynamic: noteDyn, articulation: art, voice: 0, tie: false))
}
return out
}
+500 -24
View File
@@ -11,6 +11,20 @@ import Foundation
/// per-part list of ``ScoreEvent`` keyed off beat 0.
public struct ScorePart: Sendable {
/// Cross-section identity key used by ``ScoreSection`` lowering.
///
/// When a score is assembled from multiple ``ScoreSection`` values, sections
/// are stitched together by matching `id` values across sections — the same
/// instrument in two consecutive sections must carry the same `id` (even if its
/// `name` differs for display). When you author a ``ScorePart`` outside of a
/// ``ScoreSection`` context (the flat ``Score(parts:)`` path) the `id` has no
/// structural role, but it is still stored and accessible.
///
/// Defaults to `name` when not explicitly supplied — so existing call sites
/// (``Part(_:channel:clef:elements:)``) have their `id` automatically derived
/// from `name` and require no changes.
public let id: String
/// Human-readable part name (e.g. "lead", "bass", "drums").
public let name: String
@@ -18,18 +32,103 @@ public struct ScorePart: Sendable {
/// when they have their own routing.
public let channel: Int
/// The clef assigned to this part.
///
/// Used by ``Score/toMusicXMLString(divisions:)`` to emit the correct
/// `<clef>` block in the first measure's `<attributes>`. When set to
/// ``Clef/auto``, the encoder infers `.treble` or `.bass` from the
/// part's median MIDI pitch at encode time.
///
/// Defaults to ``Clef/treble`` on direct construction so existing code
/// that builds ``ScorePart`` values directly is unaffected. The DSL
/// constructor ``Part(_:channel:clef:elements:)`` defaults to
/// ``Clef/auto`` so authored scores self-classify.
public let clef: Clef
/// Per-part key signature override.
///
/// When non-nil, this part emits its OWN `<key>` block in measure-1
/// `<attributes>` rather than the score-level ``Score/keySignature``.
/// Useful for transposing instruments (e.g. a B♭ clarinet written in A
/// major while the concert key is G major).
///
/// When `nil` (the default), the part inherits ``Score/keySignature``.
///
/// This is **notation-only**: ``flatten()`` returns written pitches
/// regardless of any key override.
public let keySignature: KeySignature?
/// Transpose specification for this part.
///
/// When non-nil, a `<transpose>` block is emitted in the part's
/// measure-1 `<attributes>` after `<clef>` so notation software
/// (Dorico, MuseScore, Finale) can display and play back the correct
/// concert pitch.
///
/// The values describe written→sounding pitch: for a B♭ clarinet
/// `Transpose.bFlat` specifies `chromatic: -2, diatonic: -1` (written
/// C sounds B♭).
///
/// When `nil` (the default), no `<transpose>` element is emitted.
///
/// This is **notation-only**: ``flatten()`` returns events at the
/// **written** pitch. Concert-pitch playback (applying the transpose to
/// produce sounding pitches) is planned for a future phase.
public let transpose: Transpose?
/// Per-part meter-map override for polymetric music.
///
/// When non-nil, this part uses its OWN complete ``MeterMap`` instead of the
/// score-level ``Score/meterMap``. The override is **all-or-nothing**: a part
/// cannot patch a single segment of the score map — it either inherits the
/// score map entirely (`nil`, the default) or replaces it wholesale.
///
/// The MusicXML encoder renders each part against its own effective meter
/// map, so parts may carry different bar groupings (and bar counts) at the
/// same time. Round-trip reads meter score-globally (from the first part), so
/// per-part overrides are export-faithful but do not survive
/// ``Score/fromMusicXML(data:)``.
public let meterMap: MeterMap?
/// Top-level elements in document order.
public let elements: [ScoreElement]
/// - Parameters:
/// - name: Human-readable part name (e.g. "lead", "bass", "drums").
/// - channel: MIDI channel hint in `[0, 15]`. Defaults to `0`.
/// - clef: Clef for MusicXML encoding. Defaults to ``Clef/treble`` on direct
/// construction (the ``Part(_:channel:clef:keySignature:transpose:meterMap:elements:)``
/// DSL constructor defaults to ``Clef/auto`` instead).
/// - keySignature: Per-part key-signature override. `nil` (default) inherits
/// the score-level key. Notation-only.
/// - transpose: Transpose specification (written→sounding). `nil` (default)
/// emits no `<transpose>`. Notation-only.
/// - meterMap: Per-part meter-map override for polymeter — a complete,
/// all-or-nothing replacement of the score-level ``Score/meterMap``. `nil`
/// (default) inherits the score map.
/// - elements: Top-level ``ScoreElement`` values in document order.
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
/// instrument across sections even when the display `name` changes.
public init(
name: String,
channel: Int = 0,
elements: [ScoreElement]
clef: Clef = .treble,
keySignature: KeySignature? = nil,
transpose: Transpose? = nil,
meterMap: MeterMap? = nil,
elements: [ScoreElement],
id: String? = nil
) {
precondition(channel >= 0 && channel <= 15,
"ScorePart: channel must be in [0, 15], got \(channel)")
self.name = name
self.id = id ?? name
self.channel = channel
self.clef = clef
self.keySignature = keySignature
self.transpose = transpose
self.meterMap = meterMap
self.elements = elements
}
@@ -37,10 +136,30 @@ public struct ScorePart: Sendable {
///
/// Walks the element tree applying tuplet scale factors. Rests advance
/// the cursor without emitting an event. Chords split into one event per
/// pitch sharing the same start beat. Articulations scale the event's
/// played duration and bump velocity.
/// pitch sharing the same start beat. Articulations bump velocity and
/// set ``ScoreEvent/articulation``; the played (sounding) length is
/// derived on demand via ``ScoreEvent/performedDuration`` — the emitted
/// ``ScoreEvent/duration`` is the notated length.
///
/// ## Tie merge
///
/// A `.note` element with `tie == true` is merged with the immediately-
/// following same-pitch, same-voice element (if one exists). The merged
/// sounding event has the SUM of both durations; all other fields come
/// from the first note. Tie chains (A.tie→B.tie→C) propagate the merge
/// so that all three collapse into one event. A `tie == true` note whose
/// immediate follower is not a same-pitch same-voice note is treated as
/// untied — two separate events are emitted and no tie annotation is added.
///
/// A `.chord` element with `tie == true` is merged with the immediately-
/// following chord that has the **same pitch set** (order-insensitive) and
/// the same voice. All pitches sustain: each pitch event's duration is
/// extended by the matched following chord's duration. Tie chains propagate.
/// A `tie == true` chord whose immediate follower does not match is treated
/// as untied — all pitches are emitted separately with no merge.
public func flatten() -> [ScoreEvent] {
var output: [ScoreEvent] = []
var outputTied: [Bool] = []
var cursor: Fraction = Fraction.zero
ScorePart._flatten(
elements: elements,
@@ -48,72 +167,93 @@ public struct ScorePart: Sendable {
cursor: &cursor,
voiceFallback: 0,
channel: channel,
output: &output
output: &output,
outputTied: &outputTied
)
return output
return ScorePart._mergeTies(events: output, tieFlags: outputTied)
}
/// Last beat at which any event ends. `0.0` for an empty part.
/// Last beat at which any event stops *sounding*. `0.0` for an empty part.
///
/// Uses ``ScoreEvent/performedDuration`` (not the notated ``ScoreEvent/duration``)
/// so a legato ending (`durationScale > 1`) is not clipped when this value
/// sizes a render tail. For staccato endings the sounding end is earlier
/// than the notated end, which is likewise correct here.
public func lastBeat() -> Double {
let events: [ScoreEvent] = flatten()
return events.map { $0.beat + $0.duration }.max() ?? 0.0
return events.map { $0.beat + $0.performedDuration }.max() ?? 0.0
}
// MARK: - Internal flatten
/// Recursively flatten `elements` into `output`, recording whether each
/// emitted event originated from a tied note or tied chord in `outputTied`.
///
/// `outputTied` is a parallel array to `output`: `outputTied[i]` is `true`
/// when `output[i]` came from a tied element. For `.note(... tie: true)` each
/// emitted event carries `true`. For `.chord(... tie: true)` **all** pitch
/// events in that chord carry `true` (tied chords merge as a unit). The
/// post-pass ``_mergeTies(events:tieFlags:)`` coalesces consecutive tied pairs.
///
/// For chords, events are emitted as a contiguous run (same beat) so that
/// `_mergeTies` can group them back into per-chord stacks by beat + voice.
private static func _flatten(
elements: [ScoreElement],
scale: Fraction,
cursor: inout Fraction,
voiceFallback: Int,
channel: Int,
output: inout [ScoreEvent]
output: inout [ScoreEvent],
outputTied: inout [Bool]
) {
for element: ScoreElement in elements {
switch element {
case .note(let pitch, let dur, let dynamic, let articulation, let voice):
case .note(let pitch, let dur, let dynamic, let articulation, let voice, let tie):
let scaledDur: NoteDuration = dur.scaled(by: scale)
let beats: Double = scaledDur.beats
let velocity: Double = max(0.0, min(1.0,
dynamic.velocity + articulation.velocityBonus))
let playedDur: Double = beats * articulation.durationScale
output.append(ScoreEvent(
beat: cursor.double,
duration: playedDur,
duration: beats,
pitch: pitch,
velocity: velocity,
voice: voice == 0 ? voiceFallback : voice,
articulation: articulation,
channel: channel
))
outputTied.append(tie)
cursor = ScorePart._advance(cursor: cursor, by: scaledDur)
case .rest(let dur):
let scaledDur: NoteDuration = dur.scaled(by: scale)
cursor = ScorePart._advance(cursor: cursor, by: scaledDur)
case .chord(let pitches, let dur, let dynamic, let articulation, let voice):
case .chord(let pitches, let dur, let dynamic, let articulation, let voice, let tie):
let scaledDur: NoteDuration = dur.scaled(by: scale)
let beats: Double = scaledDur.beats
let velocity: Double = max(0.0, min(1.0,
dynamic.velocity + articulation.velocityBonus))
let playedDur: Double = beats * articulation.durationScale
let startBeat: Double = cursor.double
let resolvedVoice: Int = voice == 0 ? voiceFallback : voice
for pitch: Pitch in pitches {
output.append(ScoreEvent(
beat: startBeat,
duration: playedDur,
duration: beats,
pitch: pitch,
velocity: velocity,
voice: voice == 0 ? voiceFallback : voice,
voice: resolvedVoice,
articulation: articulation,
channel: channel
))
// All pitches in a tied chord carry the tie flag so _mergeTies
// can group the whole chord stack as a unit.
outputTied.append(tie)
}
cursor = ScorePart._advance(cursor: cursor, by: scaledDur)
case .tuplet(let actual, let normal, let children):
case .tuplet(let actual, let normal, _, let children):
// Tuplet ratio: `actual` notes played in the time of `normal`,
// so each child duration is multiplied by `normal/actual`.
let tupletScale: Fraction = scale * Fraction(num: Int64(normal), den: Int64(actual))
@@ -123,12 +263,352 @@ public struct ScorePart: Sendable {
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output
output: &output,
outputTied: &outputTied
)
case .voice(let voiceNumber, let children):
// Voice block: flatten children with a fresh cursor starting at
// zero. The OUTER cursor is NOT advanced — voice blocks overlay
// the part from beat zero.
var voiceCursor: Fraction = Fraction.zero
_flatten(
elements: children,
scale: scale,
cursor: &voiceCursor,
voiceFallback: voiceNumber,
channel: channel,
output: &output,
outputTied: &outputTied
)
// The outer cursor is intentionally not updated so subsequent
// Voice blocks also start from beat zero.
case .wedge(_, let children):
// Wedge (hairpin) block: purely notational — flatten children
// transparently with the same cursor and voiceFallback as the
// enclosing context. No scale change, no cursor reset, no
// velocity or timing change. A wedge changes only the MusicXML
// visual annotation; the flattened ScoreEvent list is identical
// to what the unwrapped children would produce.
_flatten(
elements: children,
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .grace:
// Grace notes are purely notational — no ScoreEvent is emitted
// and the beat cursor does NOT advance. Flatten output is identical
// whether or not grace notes are present. Realized grace-note
// playback (duration-steal from surrounding notes) is future work.
break
case .clefChange:
// Clef changes are purely notational — display only. No ScoreEvent
// is emitted and the beat cursor does NOT advance (MusicXML pitches
// are absolute; the clef affects only how following notes are drawn).
// Flatten output is identical whether or not clef changes are present.
break
case .staff(_, _, let children):
// Staff block: flatten children with a fresh cursor starting at zero,
// exactly like a Voice block. The outer cursor is NOT advanced — staff
// blocks overlay the part from beat zero. Staff assignment is purely a
// notation concern and has no effect on sounding output; flatten()
// recurses into staff children so their notes DO produce ScoreEvents.
var staffCursor: Fraction = Fraction.zero
_flatten(
elements: children,
scale: scale,
cursor: &staffCursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
// The outer cursor is intentionally not updated so subsequent
// Staff blocks also start from beat zero.
case .pedal:
// Pedal marks are purely notational — no ScoreEvent is emitted and
// the beat cursor does NOT advance. Flatten output is identical
// whether or not pedal marks are present.
break
case .slur(let children):
// Slur block: purely notational — flatten children transparently
// with the same cursor and voiceFallback as the enclosing context.
// No scale change, no cursor reset, no velocity or timing change.
// A slur changes only the MusicXML visual annotation; the flattened
// ScoreEvent list is identical to what the unwrapped children would
// produce.
_flatten(
elements: children,
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .spanned(_, let inner):
// Spanned element: purely notational — flatten the single inner
// element transparently. Span annotations are notation-only and
// do not affect the ScoreEvent list.
_flatten(
elements: [inner],
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .displayed(_, let inner):
// Displayed element: purely notational — flatten the single inner
// element transparently. Display overrides are notation-only and
// do not affect the ScoreEvent list.
_flatten(
elements: [inner],
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .marked(_, let inner):
// Marked element: purely notational — flatten the single inner
// element transparently. Notation marks do not affect playback,
// velocity, or the ScoreEvent list.
_flatten(
elements: [inner],
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .dynamicCurve(_, let inner):
// Dynamic curve: purely notational — flatten the single inner
// element transparently. The curve positions and dynamics are
// notation-only; they do not affect velocity, duration, or the
// flattened ScoreEvent list. The note's own dyn: still drives
// the ScoreEvent velocity.
_flatten(
elements: [inner],
scale: scale,
cursor: &cursor,
voiceFallback: voiceFallback,
channel: channel,
output: &output,
outputTied: &outputTied
)
case .fillMeasure:
// FillMeasure is expanded to a concrete .rest at Score init time.
// Any unresolved marker (e.g. a part flattened outside a Score)
// is treated as zero-span / no-op — no event emitted, cursor
// unchanged. Do not advance; the resolved form is a .rest already.
break
}
}
}
/// Post-flatten tie-merge pass.
///
/// Handles two merge patterns:
///
/// **Single-note ties**: When `tieFlags[i]` is `true` and `events[i+1]` is
/// a same-pitch, same-voice note, the two events are coalesced into one event
/// whose duration is their sum and whose other fields come from `events[i]`.
/// Tie chains propagate. A `tieFlag[i] == true` note whose next event is not
/// a same-pitch same-voice note is left unchanged (no merge).
///
/// **Chord ties**: A chord emits a contiguous run of N events at the same
/// `beat` and `voice`, all with `tieFlag == true`. The run is detected by
/// collecting all events sharing the same `beat` and `voice`. If the
/// immediately-following contiguous same-beat/voice run (the "next chord
/// stack") has the **same pitch set** (order-insensitive), every pitch's
/// duration is extended by the next stack's duration and the next stack is
/// consumed. Tie chains propagate until the pitch set changes or a non-tied
/// run is encountered. A tied chord run whose follower has a different pitch
/// set is left unchanged (no merge, no tie annotation).
///
/// - Parameters:
/// - events: Raw flat event list from ``_flatten``.
/// - tieFlags: Parallel array; `tieFlags[i]` is `true` when `events[i]`
/// came from a tied element.
/// - Returns: Merged event list.
private static func _mergeTies(
events: [ScoreEvent],
tieFlags: [Bool]
) -> [ScoreEvent] {
guard events.count == tieFlags.count else { return events }
guard !events.isEmpty else { return events }
var result: [ScoreEvent] = []
result.reserveCapacity(events.count)
var i: Int = 0
while i < events.count {
let event: ScoreEvent = events[i]
let isTied: Bool = tieFlags[i]
// ------------------------------------------------------------------
// Chord-tie path: detect when two or more consecutive events share
// the same beat and voice. When the run starts with a tied flag,
// attempt to match + merge with the immediately-following same-beat
// same-voice same-pitch-set run.
// ------------------------------------------------------------------
let runEnd: Int = ScorePart._chordRunEnd(
events: events,
from: i
)
let runSize: Int = runEnd - i + 1
if runSize > 1 && isTied {
// Gather pitches of this chord run (order-insensitive set match).
let currentPitches: [Pitch] = Array(events[i...runEnd]).map { $0.pitch }
let currentSet: Set<Pitch> = Set(currentPitches)
let currentVoice: Int = event.voice
let nextRunStart: Int = runEnd + 1
// Find the next same-beat/voice run (the "next chord").
let nextRunEnd: Int = ScorePart._chordRunEnd(
events: events,
from: nextRunStart
)
let nextRunSize: Int = nextRunStart <= nextRunEnd ? nextRunEnd - nextRunStart + 1 : 0
if nextRunSize > 0,
events[nextRunStart].voice == currentVoice,
Set(Array(events[nextRunStart...nextRunEnd]).map { $0.pitch }) == currentSet
{
// Pitch sets match — merge the chain. Accumulate extra duration
// from the follower chain (which may itself be tied).
var extraDuration: Double = events[nextRunStart].duration
var chainTail: Int = nextRunEnd
// Propagate the chain: keep consuming matching same-pitch-set
// runs, but ONLY while the run we most recently merged was
// itself tied. `lastConsumedRunStart` tracks that run's first
// index so the tie flag is re-evaluated per chain step — a
// non-tied middle chord correctly terminates the chain.
var lastConsumedRunStart: Int = nextRunStart
var followStart: Int = chainTail + 1
while followStart < events.count && tieFlags[lastConsumedRunStart] {
let followEnd: Int = ScorePart._chordRunEnd(
events: events,
from: followStart
)
let followSize: Int = followEnd - followStart + 1
guard followSize > 0,
events[followStart].voice == currentVoice,
Set(Array(events[followStart...followEnd]).map { $0.pitch }) == currentSet
else { break }
extraDuration += events[followStart].duration
chainTail = followEnd
lastConsumedRunStart = followStart
followStart = chainTail + 1
}
// Emit one merged event per pitch in the chord, all with
// summed duration and fields from the first run's events.
for k: Int in i...runEnd {
let src: ScoreEvent = events[k]
result.append(ScoreEvent(
beat: src.beat,
duration: src.duration + extraDuration,
pitch: src.pitch,
velocity: src.velocity,
voice: src.voice,
articulation: src.articulation,
channel: src.channel
))
}
i = chainTail + 1
continue
}
// Pitch-set mismatch — fall through to emit run as-is.
}
// ------------------------------------------------------------------
// Single-note tie path (or untied events including chord runs that
// did not find a match above).
// ------------------------------------------------------------------
if isTied && i + 1 < events.count && runSize <= 1 {
// Check if the next event is a same-pitch same-voice match.
let next: ScoreEvent = events[i + 1]
let pitchMatch: Bool = event.pitch == next.pitch
let voiceMatch: Bool = event.voice == next.voice
if pitchMatch && voiceMatch {
// Merge: accumulate duration from the chain.
var mergedDuration: Double = event.duration
var j: Int = i
while j < events.count && tieFlags[j] {
let stillMatches: Bool = (j + 1 < events.count)
&& (events[j + 1].pitch == events[j].pitch)
&& (events[j + 1].voice == events[j].voice)
if stillMatches {
mergedDuration += events[j + 1].duration
j += 1
} else {
break
}
}
result.append(ScoreEvent(
beat: event.beat,
duration: mergedDuration,
pitch: event.pitch,
velocity: event.velocity,
voice: event.voice,
articulation: event.articulation,
channel: event.channel
))
i = j + 1
continue
}
}
// No merge — emit the event as-is.
result.append(event)
i += 1
}
return result
}
/// Return the index of the last event in the contiguous run of events that
/// share the same `beat` and `voice` as `events[from]`. Returns `from` when
/// no subsequent event shares the same beat + voice (singleton or start of
/// a mixed sequence).
private static func _chordRunEnd(events: [ScoreEvent], from: Int) -> Int {
// Out-of-bounds start → return `from` unchanged; callers guard with a
// `nextRunStart <= nextRunEnd` size check before using the run.
guard from < events.count else { return from }
let baseBeat: Double = events[from].beat
let baseVoice: Int = events[from].voice
var end: Int = from
while end + 1 < events.count
&& events[end + 1].beat == baseBeat
&& events[end + 1].voice == baseVoice
{
end += 1
}
return end
}
/// Advance `cursor` by a duration. Stays in `Fraction` math when the
/// duration is exact; falls back to `Double` (re-encoded as a fraction
/// approximation) when it isn't.
@@ -143,12 +623,8 @@ public struct ScorePart: Sendable {
// entire cursor through Double space. Acceptable since user opted into
// imprecise durations by passing .beats.
let approx: Double = cursor.double + duration.beats
return Fraction(num: Int64((approx * Double(ScorePart.beatApproxDenominator)).rounded()),
den: Int64(ScorePart.beatApproxDenominator))
let denominator: Int64 = Fraction.beatApproxDenominator
return Fraction(num: Int64((approx * Double(denominator)).rounded()),
den: denominator)
}
/// Denominator used to re-encode `Double` durations as fractions when an
/// `.beats(Double)` duration is mixed into otherwise-rational arithmetic.
/// `2^20 = 1_048_576` — sub-microsecond resolution at any reasonable BPM.
private static let beatApproxDenominator: Int = 1_048_576
}
+38 -2
View File
@@ -9,7 +9,7 @@ import Foundation
/// Result-builder for composing ``ScorePart`` arrays inline at the
/// ``Score`` level.
///
/// Paired with the free-function DSL constructor ``Part(_:channel:elements:)``.
/// Paired with the free-function DSL constructor ``Part(_:channel:clef:elements:)``.
@resultBuilder
public enum ScorePartBuilder {
@@ -47,11 +47,47 @@ public enum ScorePartBuilder {
/// - Parameters:
/// - name: Part name (e.g. "lead", "bass", "drums").
/// - channel: MIDI channel hint `[0, 15]`. Default `0`.
/// - clef: Clef for MusicXML encoding. Default ``Clef/auto``, which infers
/// ``Clef/treble`` or ``Clef/bass`` from the part's median MIDI pitch at
/// encode time. Pass an explicit value to override (e.g. `clef: .bass` for
/// a bass-voice part that might start on high notes).
/// - keySignature: Per-part key signature override. When non-nil, this part
/// emits its own `<key>` block instead of inheriting ``Score/keySignature``.
/// Use for transposing instruments whose written key differs from the
/// concert key (e.g. a B♭ clarinet written in A major when the concert key
/// is G major). Defaults to `nil` (inherit score-level key).
/// - transpose: Transpose specification for this part. When non-nil, a
/// `<transpose>` block is emitted in measure-1 `<attributes>` after
/// `<clef>`. Describes written→sounding pitch interval. Use one of the
/// named conveniences on ``Transpose`` (e.g. `.bFlat`, `.fHorn`) or
/// provide custom `chromatic`/`diatonic`/`octaveChange` values.
/// Defaults to `nil` (non-transposing, no `<transpose>` element emitted).
/// - meterMap: Per-part meter-map override for polymetric music. When non-nil,
/// this part uses its own complete ``MeterMap`` instead of the score-level
/// ``Score/meterMap`` — an all-or-nothing override. Defaults to `nil`
/// (inherit the score map).
/// - id: Cross-section identity key. When `nil` (the default), `id` is set
/// equal to `name`. Used by ``ScoreSection`` lowering to match the same
/// instrument across sections even when the display `name` changes.
/// - elements: Result-builder block of ``ScoreElement``.
public func Part(
_ name: String,
channel: Int = 0,
clef: Clef = .auto,
keySignature: KeySignature? = nil,
transpose: Transpose? = nil,
meterMap: MeterMap? = nil,
id: String? = nil,
@ScoreBuilder elements: () -> [ScoreElement]
) -> ScorePart {
ScorePart(name: name, channel: channel, elements: elements())
ScorePart(
name: name,
channel: channel,
clef: clef,
keySignature: keySignature,
transpose: transpose,
meterMap: meterMap,
elements: elements(),
id: id
)
}
+6 -5
View File
@@ -20,8 +20,8 @@ import Foundation
/// `articulation`. Use this when driving Lyrebird synthesizers directly.
/// - ``playMIDI(applyScoreTempo:handler:)`` — splits each event into a paired note-on /
/// note-off and dispatches them as ``MIDIMessage``s. Note-offs are
/// scheduled at `event.beat + event.duration` so the player walks the
/// merged on/off stream in beat order.
/// scheduled at `event.beat + event.performedDuration` so the player walks
/// the merged on/off stream in beat order.
///
/// ## Tempo
///
@@ -104,7 +104,8 @@ public final class ScorePlayer: @unchecked Sendable {
/// Start playback, dispatching one ``ScoreEvent`` per notated event in
/// beat order. Caller is responsible for any note-off / sustain
/// behaviour — `event.duration` carries the played length.
/// behaviour — `event.performedDuration` carries the played (sounding)
/// length; `event.duration` is the notated length.
///
/// - Parameters:
/// - applyScoreTempo: When `true` (default), set `clock.bpm` to
@@ -151,7 +152,7 @@ public final class ScorePlayer: @unchecked Sendable {
/// Start playback, emitting paired noteOn / noteOff ``MIDIMessage``s
/// for every channel-message event. Note-offs are scheduled at
/// `event.beat + event.duration` so the routine walks the merged
/// `event.beat + event.performedDuration` so the routine walks the merged
/// on/off stream in beat order.
///
/// Events whose ``Pitch/midiNote`` is `nil` (rests, out-of-range
@@ -268,7 +269,7 @@ public final class ScorePlayer: @unchecked Sendable {
velocity: 0
)
entries.append(MIDIBeatEntry(beat: event.beat, message: onMessage))
entries.append(MIDIBeatEntry(beat: event.beat + event.duration,
entries.append(MIDIBeatEntry(beat: event.beat + event.performedDuration,
message: offMessage))
}
@@ -0,0 +1,140 @@
// ScoreRestFillHelpers.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// Shared gap-filling helper for the score system. A list of positioned
// `ScoreElement` values (each at an absolute beat) is walked in order; rests are
// inserted to bridge any gap between the running cursor and the next element's
// position. Three call sites route through this helper: `ScoreTimeline.fill`
// (Fraction cursor), `MusicXMLParser` voice reconstruction (Fraction cursor),
// and `MIDIFile+Score` event→element conversion (Double cursor). Genericity over
// `Comparable & AdditiveArithmetic` lets each caller keep its native
// representation — `Fraction` callers emit `.rest(.fraction(_))`, the Double
// caller emits `.rest(.beats(_))` — with no lossy cross-conversion.
/// Convert a ``NoteDuration`` to a ``Fraction`` — exact for the `.fraction`
/// case, quantized to ``Fraction/beatApproxDenominator`` for the `.beats(Double)`
/// case.
///
/// - Parameter duration: The duration to convert.
/// - Returns: The duration in quarter-note beats as a ``Fraction``.
func noteDurationFraction(_ duration: NoteDuration) -> Fraction {
if let exact: Fraction = duration.asFraction {
return exact
}
return fractionFromBeats(duration.beats)
}
/// Convert a `Double` beat value to a ``Fraction`` (quantized to
/// ``Fraction/beatApproxDenominator``).
///
/// - Parameter beats: Beat value in quarter notes.
/// - Returns: The value as a ``Fraction``.
func fractionFromBeats(_ beats: Double) -> Fraction {
let denominator: Int64 = Fraction.beatApproxDenominator
let quantized: Int64 = Int64((beats * Double(denominator)).rounded())
return Fraction(num: quantized, den: denominator)
}
/// Total beat span of a ``ScoreElement`` as a ``Fraction`` — how far it advances
/// a sequential cursor.
///
/// - `.note` / `.rest` / `.chord` → their notated duration.
/// - `.tuplet` → the sum of child spans scaled by `normal / actual`.
/// - `.wedge` → the sum of child spans (hairpins are transparent to timing).
/// - `.voice` / `.staff` → `0` (a voice or staff block overlays from beat 0; it
/// does not advance the enclosing cursor).
/// - `.grace` / `.clefChange` / `.pedal` → `0` (notation-only, zero-duration).
///
/// - Parameter element: The element to measure.
/// - Returns: The element's beat span.
func scoreElementBeatSpan(_ element: ScoreElement) -> Fraction {
switch element {
case .note(_, let dur, _, _, _, _):
return noteDurationFraction(dur)
case .rest(let dur):
return noteDurationFraction(dur)
case .chord(_, let dur, _, _, _, _):
return noteDurationFraction(dur)
case .tuplet(let actual, let normal, _, let children):
let inner: Fraction = children.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
return inner * Fraction(normal, actual)
case .wedge(_, let children):
return children.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
case .voice, .staff, .grace, .clefChange, .pedal:
// Voice and staff blocks overlay from beat 0; grace / clef change / pedal
// are notation-only. None advance the enclosing sequential cursor.
return .zero
case .slur(let children):
// Slur blocks are purely notational wrappers — the span contributes
// whatever beat span the children produce sequentially.
return children.reduce(Fraction.zero) { $0 + scoreElementBeatSpan($1) }
case .spanned(_, let inner):
// Spanned elements are purely notational wrappers — the beat span is
// that of the inner element.
return scoreElementBeatSpan(inner)
case .displayed(_, let inner):
// Displayed elements are purely notational wrappers — the beat span is
// that of the inner element.
return scoreElementBeatSpan(inner)
case .marked(_, let inner):
// Marked elements are purely notational wrappers — the beat span is
// that of the inner element.
return scoreElementBeatSpan(inner)
case .dynamicCurve(_, let inner):
// Dynamic curve wrappers are purely notational — the beat span is
// that of the inner element.
return scoreElementBeatSpan(inner)
case .fillMeasure:
// FillMeasure is expanded to a concrete .rest at Score init time.
// Any unresolved marker is treated as zero-span (no cursor advance).
return .zero
}
}
/// Walk pre-sorted positioned elements, inserting rests to bridge gaps.
///
/// Starting from a cursor at ``AdditiveArithmetic/zero``, for each item: if its
/// `position` is past the cursor, a rest of the gap is emitted (via `makeRest`);
/// if its `position` is before the cursor (an overlap), `onOverlap` is invoked
/// (which may throw); then the element is appended (after `transform`) and the
/// cursor advances by `duration(element)`.
///
/// The input **must already be sorted** by `position` — callers control sort
/// order (e.g. the MusicXML parser places zero-duration marks before the note
/// they precede). This helper never sorts.
///
/// - Parameters:
/// - items: Positioned elements, pre-sorted by `position`.
/// - duration: Beat span of an element (how far it advances the cursor).
/// - makeRest: Builds a rest element spanning the given gap.
/// - onOverlap: Invoked when an element starts before the cursor. Receives the
/// element's position, the cursor (previous element's end), and the element.
/// May throw to reject the overlap.
/// - transform: Applied to each element before appending. Defaults to identity.
/// - Returns: The flattened element list with gap rests inserted.
func fillRests<P: Comparable & AdditiveArithmetic>(
sorted items: [(position: P, element: ScoreElement)],
duration: (ScoreElement) -> P,
makeRest: (P) -> ScoreElement,
onOverlap: (_ position: P, _ cursorEnd: P, _ element: ScoreElement) throws -> Void,
transform: (ScoreElement) -> ScoreElement = { $0 }
) rethrows -> [ScoreElement] {
var output: [ScoreElement] = []
output.reserveCapacity(items.count * 2)
var cursor: P = .zero
for item: (position: P, element: ScoreElement) in items {
if item.position > cursor {
output.append(makeRest(item.position - cursor))
} else if item.position < cursor {
try onOverlap(item.position, cursor, item.element)
}
output.append(transform(item.element))
cursor = item.position + duration(item.element)
}
return output
}
+143
View File
@@ -0,0 +1,143 @@
// ScoreSection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// One named section of a sectioned score — an authoring block that carries
/// locally-numbered bars (bar 1..N within the section) together with its own
/// meter, key, tempo changes, and repeat structure.
///
/// Sections are an **authoring layer** that lowers to the existing flat ``Score``
/// representation. Call ``Score/init(sections:bpm:keySignature:)`` (or the DSL
/// initializers) to assemble sections into a score. The lowering algorithm:
///
/// 1. Collects an ordered union of part `id` values across all sections (first-
/// appearance order) to determine the full instrument roster.
/// 2. Walks sections in order. For each section, pads every identity's element
/// list to the section's beat span — either with the part's own elements, or
/// with whole-measure rests when the instrument is TACET in that section.
/// 3. Shifts the section's `meterMap` segments, `tempoChanges`, and `repeats`
/// measure indices by the running `measureOffset` so they land at global
/// measure numbers in the assembled ``Score``.
/// 4. Records `section.name` as a rehearsal mark at `measureOffset + 1` in the
/// global ``Score/rehearsalMarks`` map.
///
/// ## Local vs global measure numbering
///
/// All measure references on a `ScoreSection` value are **local** — bar 1 is
/// the first bar of the section, bar 2 the second, and so on. The lowering step
/// adds the running `measureOffset` to every measure reference before merging
/// into the global maps.
///
/// ## v1 constraints (documented)
///
/// - **Repeats**: repeat structures on a section are shifted by `measureOffset`
/// before merging. Repeats that span two sections are not supported — a
/// backward-repeat on the last bar of one section and a forward-repeat on the
/// first bar of the next section will produce independent repeat blocks that
/// notation software treats as adjacent, not as one spanning repeat.
/// - **Anacrusis**: only the FIRST section's `meterMap` anacrusis is honored in
/// the global assembled score. Anacrusis values on later sections are silently
/// ignored (set to `.zero`) during lowering.
/// - **Per-part meterMap inside a section**: a ``ScorePart`` with its own
/// `meterMap` override inside a `ScoreSection` is accepted, but the section
/// beat-span calculation uses only the section-level `meterMap` (or the default
/// 4/4 when no section meterMap is provided). The per-part override is
/// preserved in the final flat ``ScorePart`` and affects MusicXML encoding for
/// that part, but the TACET-fill length for other instruments is derived from
/// the section-level map — a part with a divergent per-part meterMap may
/// therefore extend beyond the section's rest-fill length.
/// - **Decode**: `ScoreSection` values are NOT reconstructed from MusicXML.
/// Rehearsal marks are emit-only in v1 and are not parsed back on decode.
public struct ScoreSection: Sendable {
/// Label rendered as a rehearsal mark at the first measure of the section.
///
/// Prefer **single letters** (`"A"`, `"B"`, `"C"`). Rehearsal marks are MusicXML
/// system objects, and notation editors typically render them as an auto-advanced
/// sequence of letters — single-letter labels round-trip predictably. Custom words
/// (`"Intro"`, `"Chorus"`) are emitted faithfully but many editors (e.g. Dorico)
/// re-sequence imported rehearsal marks and hide the authored text, so words are
/// not reliably displayed.
public let name: String
/// Segmented meter map for this section. Local (measure indices start at 1
/// within the section). When `nil` the section uses the default 4/4 meter
/// (`MeterMap(TimeSignature(4, 4))`).
///
/// Anacrusis: only the first section's anacrusis is honored. Later sections
/// must set `anacrusis` to `.zero` (or leave `meterMap` as `nil`).
public let meterMap: MeterMap?
/// Per-section key signature. When non-nil on the FIRST section, it becomes
/// the assembled ``Score``'s global ``Score/keySignature`` (rendered in
/// measure 1). The model has no mid-piece key map, so a later section
/// declaring a different key cannot be represented — that is a documented v1
/// limitation; the first section's key (falling back to the caller-supplied
/// key) wins. For mid-score key changes use ``ScorePart/keySignature``
/// per-part overrides (future work: emit key
/// changes in MusicXML at each section boundary).
public let keySignature: KeySignature?
/// Mid-section tempo changes, sorted ascending by local measure number.
///
/// Measure indices are LOCAL (bar 1 = first bar of this section). The
/// lowering algorithm offsets them by the running `measureOffset`.
public let tempoChanges: [TempoChange]
/// Repeat and volta-ending structure, with LOCAL measure numbers.
///
/// The lowering algorithm offsets every measure reference by `measureOffset`.
/// Repeats spanning two sections are not supported — see v1 constraints above.
public let repeats: RepeatStructure
/// Right-barline style drawn at the section's **last** measure.
///
/// `nil` (the default) leaves the normal thin barline. Set `.double` to
/// divide sections visually, `.final` to close a movement or the piece. The
/// lowering algorithm records this at the section's last global measure in
/// ``Score/measureBarlines``. Suppressed when a backward repeat occupies the
/// same barline (the repeat's heavy barline wins) — see ``BarlineStyle``.
public let endBarline: BarlineStyle?
/// Parts that appear in this section.
///
/// Parts not listed here are TACET for the section and receive a
/// rest-fill spanning the section's full beat length.
public let parts: [ScorePart]
/// Create a score section.
///
/// - Parameters:
/// - name: Rehearsal-mark label. Prefer single letters (`"A"`, `"B"`, `"C"`) —
/// see ``name`` for why custom words are not reliably displayed by editors.
/// Rendered at the section's first global measure in MusicXML output.
/// - meterMap: Local meter map (`nil` → default 4/4). See ``meterMap``.
/// - keySignature: Optional key for this section. See ``keySignature``.
/// - tempoChanges: Local tempo changes (measure-indexed within the section).
/// Defaults to `[]`.
/// - repeats: Local repeat structure. Defaults to ``RepeatStructure/none``.
/// - endBarline: Right-barline style at the section's last measure. `nil`
/// (the default) leaves a normal barline. See ``endBarline``.
/// - parts: Parts present in this section.
public init(
name: String,
meterMap: MeterMap? = nil,
keySignature: KeySignature? = nil,
tempoChanges: [TempoChange] = [],
repeats: RepeatStructure = .none,
endBarline: BarlineStyle? = nil,
parts: [ScorePart]
) {
self.name = name
self.meterMap = meterMap
self.keySignature = keySignature
self.tempoChanges = tempoChanges
self.repeats = repeats
self.endBarline = endBarline
self.parts = parts
}
}
@@ -0,0 +1,102 @@
// ScoreSectionBuilder.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Result-builder for composing ``ScoreSection`` arrays inline at the
/// ``Score`` level.
///
/// Paired with the free-function DSL constructor ``Section(_:meterMap:keySignature:tempoChanges:repeats:endBarline:parts:)``.
///
/// ```swift
/// let score = Score(bpm: 120) {
/// Section("A") {
/// Part("lead") { Note(.c, 4, dur: .whole) }
/// }
/// Section("B", meterMap: MeterMap(TimeSignature(3, 4))) {
/// Part("lead") { Note(.g, 4, dur: .half); Note(.e, 4, dur: .quarter) }
/// }
/// }
/// ```
@resultBuilder
public enum ScoreSectionBuilder {
public static func buildBlock(_ components: [ScoreSection]...) -> [ScoreSection] {
components.flatMap { $0 }
}
public static func buildExpression(_ expression: ScoreSection) -> [ScoreSection] {
[expression]
}
public static func buildExpression(_ expression: [ScoreSection]) -> [ScoreSection] {
expression
}
public static func buildOptional(_ component: [ScoreSection]?) -> [ScoreSection] {
component ?? []
}
public static func buildEither(first component: [ScoreSection]) -> [ScoreSection] {
component
}
public static func buildEither(second component: [ScoreSection]) -> [ScoreSection] {
component
}
public static func buildArray(_ components: [[ScoreSection]]) -> [ScoreSection] {
components.flatMap { $0 }
}
}
/// DSL constructor for a ``ScoreSection``.
///
/// All measure indices (`tempoChanges`, `repeats`) are LOCAL — bar 1 is the
/// first bar of this section. The ``Score`` assembler offsets them to global
/// measure numbers during lowering.
///
/// - Parameters:
/// - name: Rehearsal-mark label rendered at the section's first global measure.
/// Prefer single letters (`"A"`, `"B"`, `"C"`): rehearsal marks are MusicXML
/// system objects that editors render as an auto-advanced letter sequence, so
/// single letters round-trip reliably while custom words (`"Intro"`, `"Chorus"`)
/// are often re-sequenced and hidden by editors such as Dorico.
/// - meterMap: Local meter map. `nil` (the default) inherits the score-level
/// `timeSignature` (which itself defaults to 4/4 at ``Score`` init); provide an
/// explicit map to override regardless of the score-level setting. All measure
/// indices in `tempoChanges` and `repeats` are resolved against this map.
/// - keySignature: Optional key signature override for this section.
/// Defaults to `nil` (no per-section key override).
/// - tempoChanges: Mid-section tempo changes, local measure-indexed. Defaults
/// to `[]`.
/// - repeats: Local repeat structure. Defaults to ``RepeatStructure/none``.
/// - endBarline: Right-barline style drawn at the section's last measure.
/// `nil` (the default) leaves a normal thin barline; `.double` divides
/// sections, `.final` closes a movement / the piece. Suppressed when a
/// backward repeat sits on the same barline. See ``BarlineStyle``.
/// - parts: Result-builder block of ``ScorePart`` values present in this
/// section. Instruments absent from this section are TACET and receive
/// whole-measure rest fill.
public func Section(
_ name: String,
meterMap: MeterMap? = nil,
keySignature: KeySignature? = nil,
tempoChanges: [TempoChange] = [],
repeats: RepeatStructure = .none,
endBarline: BarlineStyle? = nil,
@ScorePartBuilder parts: () -> [ScorePart]
) -> ScoreSection {
ScoreSection(
name: name,
meterMap: meterMap,
keySignature: keySignature,
tempoChanges: tempoChanges,
repeats: repeats,
endBarline: endBarline,
parts: parts()
)
}
+407
View File
@@ -0,0 +1,407 @@
// ScoreTimeline.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Builds a gap-filled ``ScoreElement`` array from elements placed at explicit
/// beat positions — you give the notes and the beats they start on, and the
/// timeline fills the rests in between.
///
/// Positions are either absolute quarter-note beats (the `(beat: Double, …)`
/// overloads, 0-based, matching ``ScoreEvent/beat``) or musical ``BeatPosition``
/// values resolved against a ``MeterMap`` (the `meter:` overloads).
///
/// The result is a flat `[ScoreElement]` that drops straight into a ``Part``.
/// Because the score result-builders are non-throwing, bind the timeline to a
/// `let` before the `Part`:
///
/// ```swift
/// let lead: [ScoreElement] = try ScoreTimeline.from(
/// (beat: 0.0, Note(.e, 5, dur: .quarter)),
/// (beat: 4.0, Note(.e, 5, dur: .quarter))
/// )
/// let score = Score {
/// Part("lead") { lead } // → Note(quarter), Rest(dotted-half), Note(quarter)
/// }
/// ```
///
/// ## Overlap
///
/// A single-timeline call is monophonic. When elements overlap, the
/// ``ScoreTimelineOverlap`` policy decides: `.trap` (default) throws; `.truncatePrevious`
/// shortens the previous element. For genuinely simultaneous material use a chord,
/// ``fillVoices(_:)`` (explicit voice numbers), or ``fillAutoVoiced(_:)``
/// (overlaps distributed into voices automatically).
public enum ScoreTimeline {
// MARK: - Single-voice, absolute beats
/// Lay out positioned elements onto a single timeline, inserting rests for
/// the gaps.
///
/// - Parameters:
/// - placed: `(beat, element)` pairs. Order does not matter — the timeline
/// sorts by beat. Beats must be `>= 0`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: A flat `[ScoreElement]` with gap rests inserted (and a leading
/// rest if the earliest element starts after beat 0).
/// - Throws: ``ScoreTimelineError/negativeBeat(beat:)`` for a negative
/// position; ``ScoreTimelineError/overlap(atBeat:previousEndsAtBeat:elementDescription:)``
/// per the `overlap` policy.
public static func fill(
_ placed: [(beat: Double, element: ScoreElement)],
overlap: ScoreTimelineOverlap = .trap
) throws -> [ScoreElement] {
try fillCore(absoluteItems(placed), overlap: overlap)
}
/// Variadic convenience over ``fill(_:overlap:)``.
///
/// - Parameters:
/// - placed: `(beat, element)` pairs.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
public static func from(
_ placed: (beat: Double, element: ScoreElement)...,
overlap: ScoreTimelineOverlap = .trap
) throws -> [ScoreElement] {
try fillCore(absoluteItems(placed), overlap: overlap)
}
/// Lay out positioned elements from a `[beat: element]` dictionary.
///
/// - Parameters:
/// - placed: Map of absolute beat → element. Beats must be `>= 0`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
public static func fill(
_ placed: [Double: ScoreElement],
overlap: ScoreTimelineOverlap = .trap
) throws -> [ScoreElement] {
let pairs: [(beat: Double, element: ScoreElement)] =
placed.map { (beat: $0.key, element: $0.value) }
return try fillCore(absoluteItems(pairs), overlap: overlap)
}
// MARK: - Single-voice, musical addressing
/// Lay out elements placed at ``BeatPosition`` values, resolved against a
/// ``MeterMap``, inserting rests for the gaps.
///
/// ```swift
/// // 4/4: beat 1 → downbeat, beat 5 → bar-2 downbeat.
/// let lead: [ScoreElement] = try ScoreTimeline.fill([
/// (.beat(1.0), Note(.e, 5, dur: .quarter)),
/// (.beat(5.0), Note(.e, 5, dur: .quarter)),
/// ], meter: MeterMap(.fourFour))
/// ```
///
/// - Parameters:
/// - placed: `(BeatPosition, element)` pairs. Order does not matter.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:overlap:)``.
public static func fill(
_ placed: [(BeatPosition, ScoreElement)],
meter: MeterMap = MeterMap(.fourFour),
overlap: ScoreTimelineOverlap = .trap
) throws -> [ScoreElement] {
try fillCore(resolvedItems(placed, meter: meter), overlap: overlap)
}
/// Variadic convenience over ``fill(_:meter:overlap:)``.
///
/// - Parameters:
/// - placed: `(BeatPosition, element)` pairs.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - overlap: How to resolve overlapping elements. Defaults to `.trap`.
/// - Returns: See ``fill(_:overlap:)``.
/// - Throws: See ``fill(_:meter:overlap:)``.
public static func from(
_ placed: (BeatPosition, ScoreElement)...,
meter: MeterMap = MeterMap(.fourFour),
overlap: ScoreTimelineOverlap = .trap
) throws -> [ScoreElement] {
try fillCore(resolvedItems(placed, meter: meter), overlap: overlap)
}
// MARK: - Multi-voice (explicit voice numbers)
/// Lay out positioned elements across explicit voices. Each voice is filled
/// independently (rest-filled, overlap within a voice traps) and wrapped in a
/// `.voice(_:_:)` block, so the parts sound simultaneously.
///
/// - Parameter placed: `(beat, voice, element)` triples. `voice >= 1`.
/// - Returns: A `[ScoreElement]` of `.voice` blocks (one per voice, ascending),
/// ready to drop into a multi-voice ``Part``.
/// - Throws: ``ScoreTimelineError/invalidVoice(voice:)`` for `voice < 1`;
/// otherwise see ``fill(_:overlap:)`` (per-voice).
public static func fillVoices(
_ placed: [(beat: Double, voice: Int, element: ScoreElement)]
) throws -> [ScoreElement] {
var items: [(position: Fraction, voice: Int, element: ScoreElement)] = []
items.reserveCapacity(placed.count)
for entry: (beat: Double, voice: Int, element: ScoreElement) in placed {
guard entry.beat >= 0 else {
throw ScoreTimelineError.negativeBeat(beat: entry.beat)
}
items.append((position: fractionFromBeats(entry.beat), voice: entry.voice, element: entry.element))
}
return try fillVoicesCore(items)
}
/// Meter-aware ``fillVoices(_:)`` — placements addressed by ``BeatPosition``.
///
/// - Parameters:
/// - placed: `(BeatPosition, voice, element)` triples. `voice >= 1`.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - Returns: See ``fillVoices(_:)``.
/// - Throws: See ``fillVoices(_:)``.
public static func fillVoices(
_ placed: [(BeatPosition, voice: Int, element: ScoreElement)],
meter: MeterMap = MeterMap(.fourFour)
) throws -> [ScoreElement] {
var items: [(position: Fraction, voice: Int, element: ScoreElement)] = []
items.reserveCapacity(placed.count)
for entry: (BeatPosition, voice: Int, element: ScoreElement) in placed {
let resolved: Fraction = entry.0.resolve(in: meter)
guard resolved >= .zero else {
throw ScoreTimelineError.negativeBeat(beat: resolved.double)
}
items.append((position: resolved, voice: entry.voice, element: entry.element))
}
return try fillVoicesCore(items)
}
// MARK: - Multi-voice (automatic distribution)
/// Lay out positioned elements, distributing overlaps across voices
/// automatically (greedy first-fit: each element goes to the lowest-numbered
/// voice free at its start beat, else a new voice). Non-overlapping input
/// yields a single voice's worth of elements wrapped in one `.voice(1, …)`.
///
/// - Parameter placed: `(beat, element)` pairs. Beats must be `>= 0`.
/// - Returns: A `[ScoreElement]` of `.voice` blocks (voice 1…N).
/// - Throws: ``ScoreTimelineError/negativeBeat(beat:)`` for a negative position.
public static func fillAutoVoiced(
_ placed: [(beat: Double, element: ScoreElement)]
) throws -> [ScoreElement] {
try autoVoiceCore(absoluteItems(placed))
}
/// Meter-aware ``fillAutoVoiced(_:)`` — placements addressed by ``BeatPosition``.
///
/// - Parameters:
/// - placed: `(BeatPosition, element)` pairs.
/// - meter: The governing meter map. Defaults to constant `4/4`.
/// - Returns: See ``fillAutoVoiced(_:)``.
/// - Throws: See ``fillAutoVoiced(_:)``.
public static func fillAutoVoiced(
_ placed: [(BeatPosition, ScoreElement)],
meter: MeterMap = MeterMap(.fourFour)
) throws -> [ScoreElement] {
try autoVoiceCore(resolvedItems(placed, meter: meter))
}
// MARK: - Input resolution
/// Map `(beat: Double, element)` to resolved `(position: Fraction, element)`,
/// rejecting negative beats.
private static func absoluteItems(
_ placed: [(beat: Double, element: ScoreElement)]
) throws -> [(position: Fraction, element: ScoreElement)] {
var items: [(position: Fraction, element: ScoreElement)] = []
items.reserveCapacity(placed.count)
for entry: (beat: Double, element: ScoreElement) in placed {
guard entry.beat >= 0 else {
throw ScoreTimelineError.negativeBeat(beat: entry.beat)
}
items.append((position: fractionFromBeats(entry.beat), element: entry.element))
}
return items
}
/// Resolve `(BeatPosition, element)` against a meter map, rejecting positions
/// before beat 0.
private static func resolvedItems(
_ placed: [(BeatPosition, ScoreElement)],
meter: MeterMap
) throws -> [(position: Fraction, element: ScoreElement)] {
var items: [(position: Fraction, element: ScoreElement)] = []
items.reserveCapacity(placed.count)
for entry: (BeatPosition, ScoreElement) in placed {
let resolved: Fraction = entry.0.resolve(in: meter)
guard resolved >= .zero else {
throw ScoreTimelineError.negativeBeat(beat: resolved.double)
}
items.append((position: resolved, element: entry.1))
}
return items
}
// MARK: - Core
/// Stable-sort resolved items by position (input order breaks ties), apply the
/// overlap policy, and fill rest gaps.
private static func fillCore(
_ items: [(position: Fraction, element: ScoreElement)],
overlap: ScoreTimelineOverlap
) throws -> [ScoreElement] {
let sorted: [(position: Fraction, element: ScoreElement)] = stableSorted(items)
let prepared: [(position: Fraction, element: ScoreElement)] =
overlap == .truncatePrevious ? try truncateOverlaps(sorted) : sorted
return try fillRests(
sorted: prepared,
duration: scoreElementBeatSpan,
makeRest: { gap in .rest(duration: .fraction(gap)) },
onOverlap: { position, cursorEnd, element in
throw ScoreTimelineError.overlap(
atBeat: position.double,
previousEndsAtBeat: cursorEnd.double,
elementDescription: ScoreTimeline.kindName(element)
)
}
)
}
/// Group by voice, fill each voice independently (overlap traps within a
/// voice), and wrap each in a `.voice` block (voices ascending).
private static func fillVoicesCore(
_ items: [(position: Fraction, voice: Int, element: ScoreElement)]
) throws -> [ScoreElement] {
var byVoice: [Int: [(position: Fraction, element: ScoreElement)]] = [:]
for item: (position: Fraction, voice: Int, element: ScoreElement) in items {
guard item.voice >= 1 else {
throw ScoreTimelineError.invalidVoice(voice: item.voice)
}
byVoice[item.voice, default: []].append((position: item.position, element: item.element))
}
var result: [ScoreElement] = []
for voice: Int in byVoice.keys.sorted() {
let voiceItems: [(position: Fraction, element: ScoreElement)] = byVoice[voice] ?? []
let elements: [ScoreElement] = try fillCore(voiceItems, overlap: .trap)
result.append(.voice(voice, elements))
}
return result
}
/// Greedy first-fit voice distribution: each element goes to the lowest voice
/// free at its start, else a new voice. Each bucket is then rest-filled.
private static func autoVoiceCore(
_ items: [(position: Fraction, element: ScoreElement)]
) throws -> [ScoreElement] {
let sorted: [(position: Fraction, element: ScoreElement)] = stableSorted(items)
var cursors: [Fraction] = []
var buckets: [[(position: Fraction, element: ScoreElement)]] = []
for item: (position: Fraction, element: ScoreElement) in sorted {
var assigned: Int = -1
for i: Int in 0..<cursors.count where cursors[i] <= item.position {
assigned = i
break
}
if assigned == -1 {
cursors.append(.zero)
buckets.append([])
assigned = cursors.count - 1
}
buckets[assigned].append(item)
cursors[assigned] = item.position + scoreElementBeatSpan(item.element)
}
var result: [ScoreElement] = []
for (index, bucket): (Int, [(position: Fraction, element: ScoreElement)]) in buckets.enumerated() {
result.append(.voice(index + 1, try fillCore(bucket, overlap: .trap)))
}
return result
}
/// Stable sort by position; equal-position placements keep input order so a
/// deliberate same-beat chord-then-zero-duration mark stays ordered.
private static func stableSorted(
_ items: [(position: Fraction, element: ScoreElement)]
) -> [(position: Fraction, element: ScoreElement)] {
items.enumerated()
.sorted { lhs, rhs in
if lhs.element.position != rhs.element.position {
return lhs.element.position < rhs.element.position
}
return lhs.offset < rhs.offset
}
.map { $0.element }
}
/// Apply `.truncatePrevious`: shorten each element that overruns the next
/// element's start to end exactly there. Only note/chord/rest can be
/// truncated; otherwise (or when the truncation would be to zero) throws.
private static func truncateOverlaps(
_ sorted: [(position: Fraction, element: ScoreElement)]
) throws -> [(position: Fraction, element: ScoreElement)] {
var out: [(position: Fraction, element: ScoreElement)] = []
out.reserveCapacity(sorted.count)
var cursor: Fraction = .zero
for item: (position: Fraction, element: ScoreElement) in sorted {
if item.position < cursor, !out.isEmpty {
let prevIndex: Int = out.count - 1
let prev: (position: Fraction, element: ScoreElement) = out[prevIndex]
let newSpan: Fraction = item.position - prev.position
guard newSpan > .zero, let truncated: ScoreElement = withTruncatedDuration(prev.element, newSpan) else {
throw ScoreTimelineError.overlap(
atBeat: item.position.double,
previousEndsAtBeat: cursor.double,
elementDescription: ScoreTimeline.kindName(item.element)
)
}
out[prevIndex] = (position: prev.position, element: truncated)
}
out.append(item)
cursor = item.position + scoreElementBeatSpan(item.element)
}
return out
}
/// Return `element` with its duration replaced by `newSpan`, or `nil` if the
/// element kind has no single truncatable duration (tuplet/voice/wedge/grace/clef).
private static func withTruncatedDuration(
_ element: ScoreElement,
_ newSpan: Fraction
) -> ScoreElement? {
let dur: NoteDuration = .fraction(newSpan)
switch element {
case .note(let pitch, _, let dynamic, let articulation, let voice, let tie):
return .note(pitch, duration: dur, dynamic: dynamic, articulation: articulation, voice: voice, tie: tie)
case .chord(let pitches, _, let dynamic, let articulation, let voice, let tie):
return .chord(pitches, duration: dur, dynamic: dynamic, articulation: articulation, voice: voice, tie: tie)
case .rest:
return .rest(duration: dur)
default:
return nil
}
}
/// Short diagnostic name for an element kind, for overlap error messages.
private static func kindName(_ element: ScoreElement) -> String {
switch element {
case .note: return "note"
case .rest: return "rest"
case .chord: return "chord"
case .tuplet: return "tuplet"
case .voice: return "voice"
case .wedge: return "wedge"
case .grace: return "grace"
case .clefChange: return "clefChange"
case .staff: return "staff"
case .pedal: return "pedal"
case .slur: return "slur"
case .spanned: return "spanned"
case .displayed: return "displayed"
case .marked: return "marked"
case .dynamicCurve: return "dynamicCurve"
case .fillMeasure: return "fillMeasure"
}
}
}
@@ -0,0 +1,36 @@
// ScoreTimelineError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Error thrown by ``ScoreTimeline`` when positioned elements cannot be laid out
/// onto a single sequential timeline.
public enum ScoreTimelineError: Error, Hashable, Sendable {
/// Two elements overlap: an element starts before the previous element
/// finishes sounding. The timeline is monophonic-per-call, so overlapping
/// placements are rejected rather than silently truncated or re-voiced.
///
/// - Parameters:
/// - atBeat: Absolute beat (quarter notes) where the offending element
/// starts.
/// - previousEndsAtBeat: Absolute beat where the running cursor sits — the
/// end of the previously placed element. This is `> atBeat`.
/// - elementDescription: A short textual description of the offending
/// element (e.g. `"note"`, `"chord"`), for diagnostics.
case overlap(atBeat: Double, previousEndsAtBeat: Double, elementDescription: String)
/// A placement specified a negative beat position.
///
/// - Parameter beat: The offending negative beat value.
case negativeBeat(beat: Double)
/// A ``ScoreTimeline/fillVoices(_:)`` placement specified a voice number `< 1`.
/// Voice numbers are 1-based (matching MusicXML `<voice>`).
///
/// - Parameter voice: The offending voice number.
case invalidVoice(voice: Int)
}
@@ -0,0 +1,26 @@
// ScoreTimelineOverlap.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// How ``ScoreTimeline`` resolves two elements that overlap on a single-voice
/// timeline — an element starting before the previous one finishes sounding.
///
/// For genuinely simultaneous material (chords, independent lines) use a chord
/// or the multi-voice timeline (``ScoreTimeline/fillVoices(_:)`` /
/// ``ScoreTimeline/fillAutoVoiced(_:)``) instead of an overlap policy.
public enum ScoreTimelineOverlap: Sendable, Hashable {
/// Reject the overlap by throwing
/// ``ScoreTimelineError/overlap(atBeat:previousEndsAtBeat:elementDescription:)``.
/// The default — a loud signal that the placement is wrong.
case trap
/// Shorten the previous element so it ends exactly where the overlapping
/// element begins, then continue. Only `.note` / `.chord` / `.rest` can be
/// truncated; truncating a `.tuplet` / `.voice` / `.wedge` (or two elements
/// sharing a start beat, which would truncate to zero) instead throws
/// ``ScoreTimelineError/overlap(atBeat:previousEndsAtBeat:elementDescription:)``.
case truncatePrevious
}
+82
View File
@@ -0,0 +1,82 @@
// Spanner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Explicit per-note span boundary annotations used with the
/// ``ScoreElement/spanned(_:_:)`` DSL element.
///
/// `Spanner` values are applied to a single inner ``ScoreElement``, marking
/// that element's first or last emittable atom as a boundary of a slur or
/// hairpin span. This is the fine-grained authoring path intended for
/// **overlapping** or **shared-boundary** spans — e.g. a slur that starts on
/// the same note where a crescendo ends.
///
/// For clean, non-overlapping spans prefer the block constructors
/// ``Slur(_:)`` (for slurs) and ``Crescendo(_:)`` / ``Diminuendo(_:)`` (for
/// hairpins), which compose more naturally under the result-builder DSL.
///
/// MusicXML notes:
/// - A wedge-stop (`<wedge type="stop"/>`) is type-agnostic in MusicXML — it
/// terminates any open hairpin regardless of whether it was opened as a
/// crescendo or diminuendo. Hence a single `.endHairpin` case rather than
/// separate endCrescendo / endDiminuendo variants.
/// - Slur and hairpin annotations are independent on a single atom: a note can
/// simultaneously carry `.beginSlur` (slur-start) and `.endHairpin`
/// (wedge-stop) without conflict.
public enum Spanner: Sendable, Hashable {
/// Mark the first emittable atom of the inner element as the START of a slur span.
///
/// Emits `<slur number="1" type="start"/>` inside `<notations>` on that note.
case beginSlur
/// Mark the last emittable atom of the inner element as the STOP of a slur span.
///
/// Emits `<slur number="1" type="stop"/>` inside `<notations>` on that note.
case endSlur
/// Mark the first emittable atom of the inner element as the START of a crescendo hairpin.
///
/// Emits `<wedge type="crescendo"/>` in a `<direction>` immediately before that note.
case beginCrescendo
/// Mark the first emittable atom of the inner element as the START of a diminuendo hairpin.
///
/// Emits `<wedge type="diminuendo"/>` in a `<direction>` immediately before that note.
case beginDiminuendo
/// Mark the last emittable atom of the inner element as the STOP of an open hairpin.
///
/// Emits `<wedge type="stop"/>` in a `<direction>` immediately after that note.
/// MusicXML `<wedge type="stop"/>` is type-agnostic — it terminates any open
/// crescendo or diminuendo, so a single unified stop is correct regardless of
/// which kind of hairpin was opened.
case endHairpin
/// Mark the first emittable atom of the inner element as the START of a glissando span.
///
/// The associated ``Glissando`` value carries the kind (`.glissando` or `.slide`),
/// line type, and optional text label. Emits the appropriate element inside
/// `<notations>` with `type="start"` on that note:
///
/// ```xml
/// <glissando type="start" line-type="wavy" number="1"/>
/// <!-- or for a slide: -->
/// <slide type="start" line-type="solid" number="1"/>
/// ```
///
/// Pair this with ``Spanner/endGlissando`` on the STOP note to form a complete
/// two-note span.
case beginGlissando(Glissando)
/// Mark the last emittable atom of the inner element as the STOP of a glissando span.
///
/// Emits the matching `<glissando type="stop" number="1"/>` (or `<slide …/>`)
/// inside `<notations>` on that note. The element name (glissando vs slide) is
/// propagated from the START note's ``Glissando`` descriptor at annotation time.
///
/// Always pair with a preceding ``Spanner/beginGlissando(_:)`` on the START note.
case endGlissando
}
+65
View File
@@ -0,0 +1,65 @@
// TempoChange.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// A mid-piece tempo change anchored to a 1-based measure number.
///
/// `TempoChange` is a **score-level, measure-indexed, notation-only** annotation.
/// It describes where a new tempo takes effect in the engraved score. It does
/// **not** affect ``ScorePart/flatten()`` or playback — ``ScorePlayer`` and NRT
/// rendering use the single base ``Score/bpm`` throughout. Segmented beat-to-seconds
/// conversion (tempo-map playback) is planned for a future phase.
///
/// ## Usage
///
/// ```swift
/// let score = Score(
/// bpm: 120,
/// tempoChanges: [
/// TempoChange(measure: 5, bpm: 160), // allegro at bar 5
/// TempoChange(measure: 9, bpm: 72) // slow down at bar 9
/// ]
/// ) {
/// Part("melody") { … }
/// }
/// ```
///
/// ## Measure-1 rule
///
/// ``Score/bpm`` always provides the measure-1 tempo. A `TempoChange` targeting
/// measure 1 is silently superseded by `Score.bpm` during encoding — the encoder
/// always uses `Score.bpm` for measure 1 and ignores any `TempoChange` at that
/// measure. Callers should use tempo changes for measures ≥ 2.
///
/// ## Deduplication
///
/// When two `TempoChange` values target the same measure, the encoder uses
/// first-in-array order (the one that appears earlier in the `tempoChanges` array
/// wins). The parser deduplicates on the same basis.
public struct TempoChange: Sendable, Hashable {
/// 1-based measure number where the new tempo takes effect (≥ 1).
public let measure: Int
/// New tempo in quarter-note beats per minute (> 0).
public let bpm: Double
/// Create a tempo change.
///
/// - Parameters:
/// - measure: 1-based measure number where the new tempo takes effect. Must be ≥ 1.
/// - bpm: New tempo in quarter-note beats per minute. Must be > 0.
public init(
measure: Int,
bpm: Double
) {
precondition(
measure >= 1 && bpm > 0,
"TempoChange: measure must be >= 1 and bpm must be > 0, got measure=\(measure) bpm=\(bpm)"
)
self.measure = measure
self.bpm = bpm
}
}
@@ -0,0 +1,29 @@
// Accidental+Theory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension Accidental {
/// The accidental whose ``semitones`` matches `value`, or `nil` when `value`
/// falls outside the representable range (beyond double-flat … double-sharp)
/// or between grid steps (not a multiple of `0.5`).
///
/// Used by spelling-preserving transposition to pick the accidental that
/// makes a target chromatic distance land on the chosen letter.
static func from(semitones value: Double) -> Accidental? {
for candidate: Accidental in Accidental.allCases
where abs(candidate.semitones - value) < matchTolerance {
return candidate
}
return nil
}
/// Half-step tolerance for floating-point matching in ``from(semitones:)``.
/// Accidental grid steps are `0.5` apart, so a tolerance well below that
/// rejects between-step values while absorbing rounding noise.
private static let matchTolerance: Double = 1e-6
}
@@ -0,0 +1,72 @@
// Interval+Catalog.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Static conveniences for the common simple intervals. Each is a
/// compile-time-known-valid `(number, quality)` pair, so they use the
/// validation-free initializer rather than forcing `try`.
extension Interval {
/// Perfect unison (`0` semitones).
public static let unison: Interval = .init(unchecked: 1, .perfect)
/// Augmented unison / chromatic semitone (`1` semitone), spelled across one
/// letter (e.g. `C → C♯`).
public static let augmentedUnison: Interval = .init(unchecked: 1, .augmented(1))
/// Minor second (`1` semitone).
public static let minorSecond: Interval = .init(unchecked: 2, .minor)
/// Major second (`2` semitones).
public static let majorSecond: Interval = .init(unchecked: 2, .major)
/// Augmented second (`3` semitones) — same sound as a minor third, spelled
/// across one letter instead of two.
public static let augmentedSecond: Interval = .init(unchecked: 2, .augmented(1))
/// Minor third (`3` semitones).
public static let minorThird: Interval = .init(unchecked: 3, .minor)
/// Major third (`4` semitones).
public static let majorThird: Interval = .init(unchecked: 3, .major)
/// Perfect fourth (`5` semitones).
public static let perfectFourth: Interval = .init(unchecked: 4, .perfect)
/// Augmented fourth (`6` semitones) — the tritone spelled upward.
public static let augmentedFourth: Interval = .init(unchecked: 4, .augmented(1))
/// Diminished fifth (`6` semitones) — the tritone spelled downward.
public static let diminishedFifth: Interval = .init(unchecked: 5, .diminished(1))
/// Perfect fifth (`7` semitones).
public static let perfectFifth: Interval = .init(unchecked: 5, .perfect)
/// Augmented fifth (`8` semitones).
public static let augmentedFifth: Interval = .init(unchecked: 5, .augmented(1))
/// Minor sixth (`8` semitones).
public static let minorSixth: Interval = .init(unchecked: 6, .minor)
/// Major sixth (`9` semitones).
public static let majorSixth: Interval = .init(unchecked: 6, .major)
/// Augmented sixth (`10` semitones).
public static let augmentedSixth: Interval = .init(unchecked: 6, .augmented(1))
/// Diminished seventh (`9` semitones).
public static let diminishedSeventh: Interval = .init(unchecked: 7, .diminished(1))
/// Minor seventh (`10` semitones).
public static let minorSeventh: Interval = .init(unchecked: 7, .minor)
/// Major seventh (`11` semitones).
public static let majorSeventh: Interval = .init(unchecked: 7, .major)
/// Perfect octave (`12` semitones).
public static let octave: Interval = .init(unchecked: 8, .perfect)
}
@@ -0,0 +1,50 @@
// Interval+PitchAnalysis.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension Interval {
/// The directed, possibly-compound spelled interval from named pitch `a` to
/// named pitch `b`.
///
/// The interval *number* comes from the signed letter distance across
/// octaves (`C4 → E5` spans a tenth); the *quality* from the chromatic gap.
/// The direction reflects whether `b` sounds above (`.up`) or below
/// (`.down`) `a`. Inverting (`b.transposed(by: interval, direction.reversed)`
/// applied to `a`) round-trips back to `b`.
///
/// - Throws: ``IntervalError/quarterToneUnsupported`` for quarter-tone input;
/// ``ScaleError/nonNamedPitch(_:)`` if either pitch is not ``Pitch/named(_:_:)``.
public static func directed(
from a: Pitch,
to b: Pitch
) throws -> (interval: Interval, direction: IntervalDirection) {
guard case .named(let aName, let aOctave) = a else {
throw ScaleError.nonNamedPitch(a)
}
guard case .named(let bName, let bOctave) = b else {
throw ScaleError.nonNamedPitch(b)
}
guard !aName.accidental.isQuarterTone, !bName.accidental.isQuarterTone else {
throw IntervalError.quarterToneUnsupported
}
let letterSteps: Int = (bOctave - aOctave) * Letter.lettersPerOctave
+ (bName.letter.diatonicIndex - aName.letter.diatonicIndex)
let aAbs: Double = Double((aOctave + Pitch.midiOctaveOffset) * Pitch.semitonesPerOctave)
+ aName.semitones
let bAbs: Double = Double((bOctave + Pitch.midiOctaveOffset) * Pitch.semitonesPerOctave)
+ bName.semitones
let semitoneDelta: Int = Int((bAbs - aAbs).rounded())
let direction: IntervalDirection =
(semitoneDelta < 0 || (semitoneDelta == 0 && letterSteps < 0)) ? .down : .up
let number: Int = abs(letterSteps) + 1
let quality: IntervalQuality = Interval.quality(number: number, semitones: abs(semitoneDelta))
return (try Interval(number: number, quality: quality), direction)
}
}
@@ -0,0 +1,181 @@
// Interval.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A spelled diatonic interval — an interval *number* (unison = 1, second = 2,
/// … octave = 8, ninth = 9, compounds allowed) paired with an
/// ``IntervalQuality``.
///
/// The number drives the *letter distance* of a transposition (``diatonicSteps``)
/// and the quality drives the chromatic size (``semitones``). Keeping both lets
/// transposition preserve correct enharmonic spelling: an augmented second up
/// from `A` advances one letter (to `B`) and three semitones, giving `B♯` — not
/// `C♮`, which a purely chromatic shift would produce.
///
/// Intervals are 12-TET. Quarter-tone accidentals are not part of the interval
/// model; transposing across them throws ``IntervalError/quarterToneUnsupported``.
public struct Interval: Sendable, Hashable {
/// Diatonic interval number, 1-indexed: `1` = unison, `2` = second, …
/// `8` = octave, `9` = ninth. Compound intervals (`> 8`) are allowed.
public let number: Int
/// Quality applied to the number's perfect / major reference size.
public let quality: IntervalQuality
/// Designated initializer. Validates the number (`≥ 1`), the
/// augmented / diminished degree (`≥ 1`), and the quality-class pairing
/// (perfect-class numbers reject major / minor and vice versa).
///
/// - Parameters:
/// - number: Diatonic interval number (`≥ 1`).
/// - quality: Interval quality; must match the number's class.
/// - Throws: ``IntervalError`` on an invalid number, degree, or
/// quality-class mismatch.
public init(
number: Int,
quality: IntervalQuality
) throws {
guard number >= 1 else { throw IntervalError.invalidNumber(number) }
switch quality {
case .augmented(let degree), .diminished(let degree):
guard degree >= 1 else { throw IntervalError.invalidDegree(degree) }
case .perfect:
guard Interval.isPerfectClass(number: number) else {
throw IntervalError.qualityNumberMismatch(number: number, quality: quality)
}
case .major, .minor:
guard !Interval.isPerfectClass(number: number) else {
throw IntervalError.qualityNumberMismatch(number: number, quality: quality)
}
}
self.number = number
self.quality = quality
}
/// Validation-free initializer for compile-time-known-valid intervals
/// (the static catalogue below). Bypasses the class-pairing checks; never
/// expose to callers — use ``init(number:quality:)``.
init(
unchecked number: Int,
_ quality: IntervalQuality
) {
self.number = number
self.quality = quality
}
/// Letter distance the interval spans: `number - 1`. A third moves two
/// letters; an octave moves seven (a full wrap).
public var diatonicSteps: Int { number - 1 }
/// Chromatic size in semitones, derived from `number + quality` via the
/// perfect / major reference table. A major third is `4`; an augmented
/// second is `3`; a major ninth is `14`.
public var semitones: Int {
let reference: Int = Interval.referenceSemitones(number: number)
switch quality {
case .perfect, .major:
return reference
case .minor:
return reference + Interval.minorOffsetFromMajor
case .augmented(let degree):
return reference + degree
case .diminished(let degree):
// Perfect-class diminishes one step below perfect; imperfect-class
// diminishes one step below minor (two below major).
return Interval.isPerfectClass(number: number)
? reference - degree
: reference + Interval.minorOffsetFromMajor - degree
}
}
// MARK: - Spelled interval between two names
/// The ascending spelled interval from `a` up to `b`, reduced to a simple
/// interval (unison … seventh) by letter distance. Both names must use
/// integer accidentals.
///
/// The number comes from the forward letter distance `a → b` (mod 7,
/// `+1`); the quality comes from the chromatic gap. `C → E` is a major
/// third, `C → E♭` a minor third, `A → B♯` an augmented second.
///
/// - Throws: ``IntervalError/quarterToneUnsupported`` if either name carries
/// a quarter-tone accidental.
public static func between(_ a: NoteName, _ b: NoteName) throws -> Interval {
guard !a.accidental.isQuarterTone, !b.accidental.isQuarterTone else {
throw IntervalError.quarterToneUnsupported
}
let letterDistance: Int = ((b.letter.diatonicIndex - a.letter.diatonicIndex)
% Letter.lettersPerOctave + Letter.lettersPerOctave) % Letter.lettersPerOctave
let number: Int = letterDistance + 1
// Natural semitone span for the ascending letter move, wrapped into a
// single octave so the accidental difference layers on cleanly.
var naturalSpan: Int = b.letter.rootSemitone - a.letter.rootSemitone
if naturalSpan < 0 { naturalSpan += Pitch.semitonesPerOctave }
let aAcc: Int = Int(a.accidental.semitones.rounded())
let bAcc: Int = Int(b.accidental.semitones.rounded())
let actualSemitones: Int = naturalSpan + (bAcc - aAcc)
let quality: IntervalQuality = Interval.quality(number: number, semitones: actualSemitones)
return try Interval(number: number, quality: quality)
}
// MARK: - Reference tables & class rules
/// Whether a diatonic number is perfect-class (unison / 4th / 5th / octave
/// and their compounds) rather than imperfect-class (2nd / 3rd / 6th / 7th).
static func isPerfectClass(number: Int) -> Bool {
let simple: Int = simpleNumber(number)
return simple == 1 || simple == 4 || simple == 5
}
/// Simple (non-compound) form of an interval number, `1 … 7`.
/// A ninth (`9`) reduces to a second (`2`); an octave (`8`) to a unison (`1`).
static func simpleNumber(_ number: Int) -> Int {
((number - 1) % Letter.lettersPerOctave) + 1
}
/// Reference (perfect for perfect-class, major for imperfect-class)
/// semitone size for a — possibly compound — interval number.
static func referenceSemitones(number: Int) -> Int {
let simple: Int = simpleNumber(number)
let octaves: Int = (number - 1) / Letter.lettersPerOctave
let base: Int
switch simple {
case 1: base = 0 // perfect unison
case 2: base = 2 // major second
case 3: base = 4 // major third
case 4: base = 5 // perfect fourth
case 5: base = 7 // perfect fifth
case 6: base = 9 // major sixth
default: base = 11 // major seventh (simple == 7)
}
return base + octaves * Pitch.semitonesPerOctave
}
/// Inverse of ``semitones``: the quality that, paired with `number`, yields
/// the given chromatic size. Used by ``between(_:_:)``.
static func quality(number: Int, semitones: Int) -> IntervalQuality {
let reference: Int = referenceSemitones(number: number)
let offset: Int = semitones - reference
if isPerfectClass(number: number) {
if offset == 0 { return .perfect }
return offset > 0 ? .augmented(offset) : .diminished(-offset)
} else {
if offset == 0 { return .major }
if offset == minorOffsetFromMajor { return .minor }
// offset > 0 → augmented; offset < -1 → diminished one step below minor.
return offset > 0 ? .augmented(offset) : .diminished(-offset - 1)
}
}
// MARK: - Constants
/// Semitone offset of a minor interval below its major reference (`-1`).
static let minorOffsetFromMajor: Int = -1
}
@@ -0,0 +1,36 @@
// IntervalDirection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Direction of an ``Interval`` when applied to a ``NoteName`` or ``Pitch``.
///
/// `.up` raises the pitch (advances the letter forward through the alphabet);
/// `.down` lowers it (advances the letter backward). Direction is kept separate
/// from the interval itself so a single ``Interval`` value (e.g. a major third)
/// can be applied either way without duplicating the catalogue.
public enum IntervalDirection: Sendable, Hashable, CaseIterable {
case up
case down
/// Signed multiplier (`+1` for ``up``, `-1` for ``down``) used when adding
/// an interval's semitone or diatonic-step span to a pitch.
public var sign: Int {
switch self {
case .up: return 1
case .down: return -1
}
}
/// The opposite direction.
public var reversed: IntervalDirection {
switch self {
case .up: return .down
case .down: return .up
}
}
}
@@ -0,0 +1,31 @@
// IntervalError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown when constructing or applying an ``Interval``.
public enum IntervalError: Error, Sendable, Hashable {
/// The interval `number` is below `1` (numbers are 1-indexed: unison = 1).
case invalidNumber(Int)
/// The `quality` does not belong to the interval number's class — e.g.
/// ``IntervalQuality/major`` on a perfect-class number (4th / 5th), or
/// ``IntervalQuality/perfect`` on an imperfect-class number (2nd / 3rd).
case qualityNumberMismatch(number: Int, quality: IntervalQuality)
/// An augmented / diminished degree was `≤ 0` (degrees are 1-indexed).
case invalidDegree(Int)
/// Transposition produced a pitch whose correct spelling falls outside the
/// representable accidental range (beyond double-flat … double-sharp).
/// Carries the would-be accidental offset in semitones.
case unrepresentableSpelling(requiredAccidentalSemitones: Double)
/// Transposition was requested across a quarter-tone accidental, which the
/// 12-TET interval model does not define.
case quarterToneUnsupported
}
@@ -0,0 +1,66 @@
// IntervalQuality.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// The quality of a diatonic ``Interval`` — the chromatic adjustment applied to
/// the perfect / major reference size of an interval number.
///
/// Two families of interval number take different reference qualities:
///
/// - **Perfect-class** numbers (unison, 4th, 5th, octave, and their compounds)
/// reference the *perfect* size. They take ``perfect``, ``augmented(_:)``, or
/// ``diminished(_:)`` — never ``major`` / ``minor``.
/// - **Imperfect-class** numbers (2nd, 3rd, 6th, 7th, and compounds) reference
/// the *major* size. They take ``major``, ``minor``, ``augmented(_:)``, or
/// ``diminished(_:)`` — never ``perfect``.
///
/// ``augmented(_:)`` and ``diminished(_:)`` carry a *degree* (`1` = singly,
/// `2` = doubly, …) so doubly-augmented / doubly-diminished intervals are
/// representable. The degree must be `≥ 1`.
///
/// ``Interval/init(number:quality:)`` enforces the class rules and throws on a
/// mismatched pairing.
public enum IntervalQuality: Sendable, Hashable {
/// Diminished by `degree` semitones below the minor (imperfect class) or
/// perfect (perfect class) reference. `degree ≥ 1`.
case diminished(Int)
/// Minor — one semitone below the major reference. Imperfect class only.
case minor
/// Perfect — the reference size for unison / 4th / 5th / octave. Perfect
/// class only.
case perfect
/// Major — the reference size for 2nd / 3rd / 6th / 7th. Imperfect class only.
case major
/// Augmented by `degree` semitones above the major / perfect reference.
/// `degree ≥ 1`.
case augmented(Int)
/// Whether this quality belongs to the perfect class (``perfect``) rather
/// than the imperfect class (``major`` / ``minor``). ``augmented(_:)`` and
/// ``diminished(_:)`` belong to neither class exclusively and return `false`.
public var isPerfectClassReference: Bool {
if case .perfect = self { return true }
return false
}
/// Single-letter abbreviation used by analysis / display: `P`, `M`, `m`,
/// `A`(`AA`…) for augmented, `d`(`dd`…) for diminished.
public var abbreviation: String {
switch self {
case .perfect: return "P"
case .major: return "M"
case .minor: return "m"
case .augmented(let n): return String(repeating: "A", count: max(1, n))
case .diminished(let n): return String(repeating: "d", count: max(1, n))
}
}
}
@@ -0,0 +1,46 @@
// Letter+Theory.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// Internal diatonic-position helpers shared by the theory layer (Interval,
// transposition, Scale). The position is the letter's index in C-based order
// (`C = 0` … `B = 6`), which matches both `Letter.allCases` order and the
// monotonic `rootSemitone` progression.
extension Letter {
/// Diatonic position in C-based order: `C = 0`, `D = 1`, … `B = 6`.
var diatonicIndex: Int {
switch self {
case .c: return 0
case .d: return 1
case .e: return 2
case .f: return 3
case .g: return 4
case .a: return 5
case .b: return 6
}
}
/// Letter at a C-based diatonic position, wrapping mod 7. Negative indices
/// wrap correctly (`-1 → B`).
static func at(diatonicIndex index: Int) -> Letter {
let wrapped: Int = ((index % lettersPerOctave) + lettersPerOctave) % lettersPerOctave
switch wrapped {
case 0: return .c
case 1: return .d
case 2: return .e
case 3: return .f
case 4: return .g
case 5: return .a
default: return .b
}
}
/// Number of diatonic letters per octave (`7`).
static let lettersPerOctave: Int = 7
}
@@ -0,0 +1,78 @@
// NoteName+Transpose.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension NoteName {
/// Transpose this note name by a spelled ``Interval``, preserving correct
/// enharmonic spelling.
///
/// The letter advances by the interval's ``Interval/diatonicSteps`` (in the
/// given direction); the accidental is then chosen so the actual chromatic
/// distance equals ``Interval/semitones``. Transposing `A` up an augmented
/// second advances one letter (to `B`) and three semitones, giving `B♯` —
/// never `C♮`.
///
/// The result is a pitch-class spelling only; octave bookkeeping (letter
/// wrap + compound octaves) lives on ``Pitch/transposed(by:_:)``.
///
/// - Parameters:
/// - interval: The spelled interval to apply.
/// - direction: ``IntervalDirection/up`` (default) raises, ``IntervalDirection/down`` lowers.
/// - Returns: The transposed, correctly-spelled note name.
/// - Throws: ``IntervalError/quarterToneUnsupported`` if this name carries a
/// quarter-tone accidental; ``IntervalError/unrepresentableSpelling(requiredAccidentalSemitones:)``
/// if the correct spelling needs an accidental beyond double-flat … double-sharp.
public func transposed(
by interval: Interval,
_ direction: IntervalDirection = .up
) throws -> NoteName {
guard !accidental.isQuarterTone else {
throw IntervalError.quarterToneUnsupported
}
let sign: Int = direction.sign
// New letter: advance the diatonic position by ±letter steps.
let rawIndex: Int = letter.diatonicIndex + sign * interval.diatonicSteps
let newLetter: Letter = Letter.at(diatonicIndex: rawIndex)
// Octave wraps crossed by the letter move (floored, so negatives work).
let octaveShift: Int = Int(
(Double(rawIndex) / Double(Letter.lettersPerOctave)).rounded(.down)
)
// The new letter's natural chromatic value, relative to this note's
// octave-zero C, including any octave the letter wrapped through.
let newLetterNaturalSemis: Double =
Double(newLetter.rootSemitone) + Double(octaveShift * Pitch.semitonesPerOctave)
// Target chromatic value: this note shifted by the signed interval size.
let targetSemis: Double = semitones + Double(sign * interval.semitones)
let requiredAccidentalSemis: Double = targetSemis - newLetterNaturalSemis
guard let newAccidental: Accidental = Accidental.from(semitones: requiredAccidentalSemis) else {
throw IntervalError.unrepresentableSpelling(
requiredAccidentalSemitones: requiredAccidentalSemis
)
}
return NoteName(letter: newLetter, accidental: newAccidental)
}
/// Return this note name with its accidental shifted by `semitones` (the
/// letter is unchanged). Used to re-apply a ``ScaleDegree`` chromatic
/// alteration after diatonic transposition / mapping.
///
/// - Throws: ``IntervalError/unrepresentableSpelling(requiredAccidentalSemitones:)``
/// if the resulting accidental falls outside double-flat … double-sharp.
func altered(bySemitones semitones: Int) throws -> NoteName {
if semitones == 0 { return self }
let target: Double = accidental.semitones + Double(semitones)
guard let newAccidental: Accidental = Accidental.from(semitones: target) else {
throw IntervalError.unrepresentableSpelling(requiredAccidentalSemitones: target)
}
return NoteName(letter: letter, accidental: newAccidental)
}
}
@@ -0,0 +1,68 @@
// Pitch+MapIntoRange.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension Pitch {
/// Folds this pitch into the inclusive register `[low, high]` by shifting it
/// whole octaves up or down, taking the fewest octaves.
///
/// The pitch class is preserved: only the octave changes. For ``named(_:_:)``
/// pitches the ``NoteName`` is carried through verbatim, so spelling survives
/// the fold — a `B♭` maps to a `B♭`, never an `A♯`:
///
/// ```swift
/// Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 5))
/// // → Pitch.named(.c, 5)
/// ```
///
/// `.midi` and `.freq` pitches fold numerically (by `±12` semitones / a
/// factor of two), returning the same case; sub-semitone `.freq` cents are
/// kept.
///
/// When no octave transposition lands inside the range — the bounds span
/// less than an octave and this pitch class has no representative there, or
/// either bound (or this pitch) is a rest / out-of-MIDI-range value — the
/// **original pitch is returned unchanged**.
///
/// - Parameters:
/// - low: Inclusive lower bound of the target register.
/// - high: Inclusive upper bound of the target register.
/// - Returns: The octave-folded pitch, or `self` when it cannot be mapped.
public func mapIntoRange(
low: Pitch,
high: Pitch
) -> Pitch {
// Any rest / non-MIDI-representable endpoint (or self) → no-op.
guard
let value: Double = midiNoteFractional,
let lo: Double = low.midiNoteFractional,
let hi: Double = high.midiNoteFractional,
hi >= lo
else { return self }
// Reuse the scalar octave-fold; the result differs from `value` only by
// whole multiples of the octave, so the octave count is exact.
let octave: Double = Double(Pitch.semitonesPerOctave)
let folded: Double = value.mapIntoRange(low: lo, high: hi, modulo: octave)
// No representative in range → folded == value but value is outside it.
guard folded >= lo, folded <= hi else { return self }
let octaveShift: Int = Int(((folded - value) / octave).rounded())
if octaveShift == 0 { return self }
switch self {
case .named(let name, let oct):
return .named(name, oct + octaveShift)
case .midi(let n):
return .midi(n + octaveShift * Pitch.semitonesPerOctave)
case .freq(let hz):
return .freq(hz * pow(2.0, Double(octaveShift)))
}
}
}
@@ -0,0 +1,54 @@
// Pitch+Transpose.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
extension Pitch {
/// Transpose this pitch by a spelled ``Interval``.
///
/// - For ``named(_:_:)`` the note name is re-spelled via
/// ``NoteName/transposed(by:_:)`` (preserving enharmonic spelling) and the
/// octave is adjusted for the letter wrap and any compound-interval
/// octaves. `E4 +M3↑` → `G♯4`; `B4 +P4↑` → `E5`.
/// - For ``midi(_:)`` and ``freq(_:)`` the pitch is shifted numerically by
/// ``Interval/semitones``. **Spelling is lost** — the result has no letter
/// name. ``rest`` is returned unchanged.
///
/// - Parameters:
/// - interval: The spelled interval to apply.
/// - direction: ``IntervalDirection/up`` (default) raises, ``IntervalDirection/down`` lowers.
/// - Returns: The transposed pitch.
/// - Throws: ``IntervalError`` from ``NoteName/transposed(by:_:)`` for the
/// ``named(_:_:)`` case (quarter-tone input or unrepresentable spelling).
public func transposed(
by interval: Interval,
_ direction: IntervalDirection = .up
) throws -> Pitch {
let signedSemitones: Int = direction.sign * interval.semitones
switch self {
case .midi(let n):
if isRest { return self }
return .midi(n + signedSemitones)
case .freq(let hz):
let ratio: Double = pow(2.0, Double(signedSemitones) / Double(Pitch.semitonesPerOctave))
return .freq(hz * ratio)
case .named(let name, let octave):
let newName: NoteName = try name.transposed(by: interval, direction)
// Solve the octave so the transposed pitch's chromatic value equals
// the original shifted by the (signed) interval size.
let originalAbs: Double =
Double((octave + Pitch.midiOctaveOffset) * Pitch.semitonesPerOctave) + name.semitones
let targetAbs: Double = originalAbs + Double(signedSemitones)
let newOctave: Int =
Int(((targetAbs - newName.semitones) / Double(Pitch.semitonesPerOctave)).rounded())
- Pitch.midiOctaveOffset
return .named(newName, newOctave)
}
}
}
@@ -0,0 +1,63 @@
// PitchCollection+Map.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Scale-to-scale mapping — re-assigning a collection's pitches from an original
/// scale to a target scale by degree, preserving correct spelling (item d).
extension PitchCollection {
/// Map every pitch from `original` to `target` by scale degree.
///
/// Each named pitch is located in `original` via ``Scale/degree(of:)`` and
/// re-spelled at the same degree index (and chromatic alteration) in
/// `target`, carrying its octave register. `C-E-G` (degrees 0-2-4 of C major)
/// maps to `D-F♯-A` in D major and `E♭-G-B♭` in E♭ major.
///
/// **Degree-count mismatch** (e.g. pentatonic → heptatonic): mapping is
/// **by index with wrap** — a degree index beyond `target.count` wraps modulo
/// the target's degree count and adds an octave. No error is raised; the
/// caller chooses scales of matching size when a 1:1 mapping is required.
///
/// - Parameters:
/// - original: The scale the collection currently lives in.
/// - target: The scale to map into. The result's
/// ``PitchCollection/referenceScale`` is set to this.
/// - Returns: The mapped collection.
/// - Throws: ``ScaleError/nonNamedPitch(_:)`` for a non-named pitch;
/// ``IntervalError/unrepresentableSpelling(requiredAccidentalSemitones:)``
/// if carrying an alteration overflows the accidental range.
public func mapped(from original: Scale, to target: Scale) throws -> PitchCollection {
var out: [Pitch] = []
out.reserveCapacity(pitches.count)
for pitch: Pitch in pitches {
out.append(try PitchCollection.map(pitch, from: original, to: target))
}
return PitchCollection(pitches: out, referenceScale: target)
}
static func map(_ pitch: Pitch, from original: Scale, to target: Scale) throws -> Pitch {
if pitch.isRest { return pitch }
guard case .named(let name, let octave) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
guard let located: ScaleDegree = original.degree(of: name) else {
throw ScaleError.nonNamedPitch(pitch)
}
// Octave region the pitch occupies in the original scale's degree space.
let octaveRegion: Int = octave - original.letterBump(name)
// Same degree index + region, re-expressed in the target's degree count.
let targetStep: Int = located.index + target.count * octaveRegion
let baseName: NoteName = target.noteName(atDegree: targetStep)
let alteredName: NoteName = try baseName.altered(bySemitones: located.alteration)
let octaveSpan: Int = Int((Double(targetStep) / Double(target.count)).rounded(.down))
let newOctave: Int = octaveSpan + target.letterBump(baseName)
return .named(alteredName, newOctave)
}
}
@@ -0,0 +1,150 @@
// PitchCollection+Row.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Twelve-tone (dodecaphonic) row operations.
///
/// A valid row is twelve named pitches covering all twelve pitch-classes. The
/// row's own spelling defines a pitch-class → note-name map; every derived form
/// (transposition, inversion, matrix) spells its pitch-classes through that map,
/// so the whole serial complex stays spelling-consistent with the prime row.
///
/// Derived rows are returned as pitch-class collections at
/// ``PitchCollection/pitchClassOctave``.
extension PitchCollection {
/// `true` when the collection is a valid 12-tone row (twelve named pitches,
/// all twelve pitch-classes present).
public var isToneRow: Bool {
(try? rowSpelling()) != nil
}
/// The prime form P0 — the row re-expressed as pitch-class note names.
public func toneRowPrime() throws -> PitchCollection {
let row: RowSpelling = try rowSpelling()
return PitchCollection.row(from: row.pitchClasses, spelling: row.spelling)
}
/// The inversion I0 — each pitch-class mirrored about the first.
public func toneRowInversion() throws -> PitchCollection {
let row: RowSpelling = try rowSpelling()
let inverted: [Int] = row.pitchClasses.map { row.invert($0) }
return PitchCollection.row(from: inverted, spelling: row.spelling)
}
/// The retrograde R0 — the prime form reversed.
public func toneRowRetrograde() throws -> PitchCollection {
try toneRowPrime().retrograde
}
/// The retrograde-inversion RI0 — the inversion reversed.
public func toneRowRetrogradeInversion() throws -> PitchCollection {
try toneRowInversion().retrograde
}
/// Transposition Tn — the prime form shifted up `n` semitones (mod 12).
public func toneRowTransposed(_ n: Int) throws -> PitchCollection {
let row: RowSpelling = try rowSpelling()
let moved: [Int] = row.pitchClasses.map { RowSpelling.mod12($0 + n) }
return PitchCollection.row(from: moved, spelling: row.spelling)
}
/// Transposed inversion TnI — the inversion shifted up `n` semitones.
public func toneRowTransposedInversion(_ n: Int) throws -> PitchCollection {
let row: RowSpelling = try rowSpelling()
let moved: [Int] = row.pitchClasses.map { RowSpelling.mod12(row.invert($0) + n) }
return PitchCollection.row(from: moved, spelling: row.spelling)
}
/// The 12×12 row matrix. Row `0` is P0 (top), column `0` is I0 (left);
/// cell `[i][j]` is the prime form transposed to start on I0's `i`-th
/// pitch-class. Every cell is spelled through the prime row's map.
public func toneRowMatrix() throws -> [[NoteName]] {
let row: RowSpelling = try rowSpelling()
let firstPc: Int = row.pitchClasses[0]
var matrix: [[NoteName]] = []
matrix.reserveCapacity(row.pitchClasses.count)
for i: Int in row.pitchClasses.indices {
let startPc: Int = row.invert(row.pitchClasses[i])
let transposition: Int = RowSpelling.mod12(startPc - firstPc)
var line: [NoteName] = []
line.reserveCapacity(row.pitchClasses.count)
for j: Int in row.pitchClasses.indices {
let pc: Int = RowSpelling.mod12(row.pitchClasses[j] + transposition)
line.append(row.spell(pc))
}
matrix.append(line)
}
return matrix
}
// MARK: - Row spelling extraction
/// A validated row: its ordered pitch-classes plus a pitch-class → note-name
/// spelling map derived from the row itself.
struct RowSpelling {
let pitchClasses: [Int]
let spelling: [Int: NoteName]
func spell(_ pc: Int) -> NoteName {
// Every pitch-class is present in a valid row, so this never misses;
// the natural-letter fallback keeps the lookup non-optional.
spelling[pc] ?? NoteName(letter: .c, accidental: .natural)
}
/// Mirror a pitch-class about the row's first pitch-class.
func invert(_ pc: Int) -> Int {
RowSpelling.mod12(2 * pitchClasses[0] - pc)
}
static func mod12(_ value: Int) -> Int {
((value % Scale.semitonesPerOctave) + Scale.semitonesPerOctave) % Scale.semitonesPerOctave
}
}
func rowSpelling() throws -> RowSpelling {
guard pitches.count == Scale.semitonesPerOctave else {
throw ToneRowError.notTwelveToneRow(
pitchCount: pitches.count, distinctClasses: distinctPitchClassCount
)
}
var pcs: [Int] = []
var spelling: [Int: NoteName] = [:]
for pitch: Pitch in pitches {
guard case .named(let name, _) = pitch else {
throw ToneRowError.nonNamedPitch(pitch)
}
let pc: Int = Scale.pitchClass(name)
pcs.append(pc)
spelling[pc] = name
}
guard spelling.count == Scale.semitonesPerOctave else {
throw ToneRowError.notTwelveToneRow(
pitchCount: pitches.count, distinctClasses: spelling.count
)
}
return RowSpelling(pitchClasses: pcs, spelling: spelling)
}
private var distinctPitchClassCount: Int {
var seen: Set<Int> = []
for pitch: Pitch in pitches {
if case .named(let name, _) = pitch {
seen.insert(Scale.pitchClass(name))
}
}
return seen.count
}
/// Build a pitch-class collection from pitch-classes and a spelling map.
static func row(from pitchClasses: [Int], spelling: [Int: NoteName]) -> PitchCollection {
let named: [Pitch] = pitchClasses.map { pc in
.named(spelling[pc] ?? NoteName(letter: .c, accidental: .natural), pitchClassOctave)
}
return PitchCollection(pitches: named)
}
}
@@ -0,0 +1,134 @@
// PitchCollection.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// An ordered list of pitches — a melodic cell, an atonal set, or a 12-tone
/// row — with spelling-preserving transformations.
///
/// Order is significant: ``retrograde`` reverses it, ``inverted(around:)``
/// mirrors each pitch about an axis, ``transposedChromatic(by:_:)`` shifts every
/// pitch by a spelled interval. An optional ``referenceScale`` ties the
/// collection to a scale for diatonic operations (T4) and scale mapping (T6).
public struct PitchCollection: Sendable, Hashable {
/// The ordered pitches.
public var pitches: [Pitch]
/// Optional scale the collection is heard against — used by diatonic
/// transposition and scale-to-scale mapping.
public var referenceScale: Scale?
public init(
pitches: [Pitch],
referenceScale: Scale? = nil
) {
self.pitches = pitches
self.referenceScale = referenceScale
}
/// Number of pitches.
public var count: Int { pitches.count }
// MARK: - Spelled transformations
/// The collection in reverse order. The ``referenceScale`` is preserved.
public var retrograde: PitchCollection {
PitchCollection(pitches: pitches.reversed(), referenceScale: referenceScale)
}
/// Every pitch transposed by a spelled ``Interval`` (item f), preserving
/// enharmonic spelling on ``Pitch/named(_:_:)`` pitches.
///
/// - Parameters:
/// - interval: The spelled interval to apply.
/// - direction: ``IntervalDirection/up`` (default) or ``IntervalDirection/down``.
/// - Throws: ``IntervalError`` from a per-pitch transposition.
public func transposedChromatic(
by interval: Interval,
_ direction: IntervalDirection = .up
) throws -> PitchCollection {
let moved: [Pitch] = try pitches.map { try $0.transposed(by: interval, direction) }
return PitchCollection(pitches: moved, referenceScale: referenceScale)
}
/// Every pitch mirrored about `axis` (pitch inversion), preserving spelling
/// for named pitches: a pitch a major third above the axis maps to a major
/// third below it.
///
/// Named pitches invert through ``Interval/directed(from:to:)``; non-named
/// pitches (``Pitch/midi(_:)`` / ``Pitch/freq(_:)``) mirror numerically and
/// keep their representation. Rests pass through unchanged.
///
/// - Parameter axis: The pitch the collection is reflected about.
/// - Throws: ``IntervalError`` / ``ScaleError`` from a per-pitch inversion.
public func inverted(around axis: Pitch) throws -> PitchCollection {
var out: [Pitch] = []
out.reserveCapacity(pitches.count)
for pitch: Pitch in pitches {
out.append(try PitchCollection.invert(pitch, around: axis))
}
return PitchCollection(pitches: out, referenceScale: referenceScale)
}
/// The collection folded into a single octave (pitch-classes): every named
/// pitch keeps its spelling at ``pitchClassOctave``; ``Pitch/midi(_:)`` and
/// ``Pitch/freq(_:)`` fold into the middle-C octave; rests pass through.
public var octaveReduced: PitchCollection {
let folded: [Pitch] = pitches.map { PitchCollection.reduceOctave($0) }
return PitchCollection(pitches: folded, referenceScale: referenceScale)
}
// MARK: - Internal per-pitch helpers
static func invert(_ pitch: Pitch, around axis: Pitch) throws -> Pitch {
if pitch.isRest { return pitch }
if case .named(let pn, _) = pitch, case .named(let an, _) = axis,
!pn.accidental.isQuarterTone, !an.accidental.isQuarterTone {
let analysis: (interval: Interval, direction: IntervalDirection) =
try Interval.directed(from: axis, to: pitch)
return try axis.transposed(by: analysis.interval, analysis.direction.reversed)
}
// Numeric mirror: 2·axis − pitch.
guard let pm: Double = pitch.midiNoteFractional,
let am: Double = axis.midiNoteFractional else {
return pitch
}
let mirror: Double = 2.0 * am - pm
if case .freq = pitch {
let hz: Double = Pitch.referenceFrequencyHz
* pow(2.0, (mirror - Pitch.referenceMidiNote) / Double(Pitch.semitonesPerOctave))
return .freq(hz)
}
return .midi(Int(mirror.rounded()))
}
static func reduceOctave(_ pitch: Pitch) -> Pitch {
if pitch.isRest { return pitch }
switch pitch {
case .named(let name, _):
return .named(name, pitchClassOctave)
case .midi(let n):
let pc: Int = ((n % Scale.semitonesPerOctave) + Scale.semitonesPerOctave)
% Scale.semitonesPerOctave
return .midi(middleCMidi + pc)
case .freq:
guard let f: Double = pitch.midiNoteFractional else { return pitch }
let pc: Int = ((Int(f.rounded()) % Scale.semitonesPerOctave) + Scale.semitonesPerOctave)
% Scale.semitonesPerOctave
return .midi(middleCMidi + pc)
}
}
// MARK: - Constants
/// Octave used for the named representatives of ``octaveReduced`` (4 =
/// middle-C octave).
public static let pitchClassOctave: Int = 4
/// MIDI note of middle C (`60`), the base for folded numeric pitch-classes.
static let middleCMidi: Int = 60
}
@@ -0,0 +1,69 @@
// Scale+Diatonic.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Diatonic (modal) transposition — shifting a collection by SCALE DEGREES,
/// staying inside the scale (item e).
///
/// Unlike chromatic transposition (which moves every pitch by the same spelled
/// interval), diatonic transposition moves every pitch by the same number of
/// *scale steps*. In C major, up a third (`+2` degrees) sends `C-D-E` to
/// `E-F-G` — the thirds are major, minor, minor as the scale dictates, **not**
/// three identical major thirds (`E-F♯-G♯`).
extension Scale {
/// Transpose `collection` by `degrees` scale steps within this scale.
///
/// Each named pitch is located by ``degree(of:)``, its index is shifted by
/// `degrees` (octave wraps handled), and it is re-spelled via
/// ``noteName(atDegree:)``. A chromatic (non-scale) pitch carries its
/// ``ScaleDegree/alteration`` through to the new degree. Rests pass through.
///
/// - Parameters:
/// - collection: The pitches to transpose. Every pitch must be
/// ``Pitch/named(_:_:)`` (or a rest).
/// - degrees: Signed number of scale steps (`+2` = up a third, `-1` = down
/// a second).
/// - Returns: The transposed collection (the input's ``PitchCollection/referenceScale`` is kept).
/// - Throws: ``ScaleError/nonNamedPitch(_:)`` for a non-named pitch;
/// ``IntervalError/unrepresentableSpelling(requiredAccidentalSemitones:)``
/// if carrying an alteration overflows the accidental range.
public func transposeDiatonic(
_ collection: PitchCollection,
byDegrees degrees: Int
) throws -> PitchCollection {
var out: [Pitch] = []
out.reserveCapacity(collection.pitches.count)
for pitch: Pitch in collection.pitches {
out.append(try transposeDiatonic(pitch, byDegrees: degrees))
}
return PitchCollection(pitches: out, referenceScale: collection.referenceScale)
}
/// Diatonically transpose a single pitch by `degrees` scale steps.
func transposeDiatonic(_ pitch: Pitch, byDegrees degrees: Int) throws -> Pitch {
if pitch.isRest { return pitch }
guard case .named(let name, let octave) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
guard let located: ScaleDegree = degree(of: name) else {
throw ScaleError.nonNamedPitch(pitch)
}
// Absolute scale-step number that reproduces this pitch's register when
// fed back through `pitch(atDegree:octave:)` with a zero anchor octave.
let absoluteStep: Int = located.index + count * (octave - letterBump(name))
let targetStep: Int = absoluteStep + degrees
let baseName: NoteName = noteName(atDegree: targetStep)
let alteredName: NoteName = try baseName.altered(bySemitones: located.alteration)
let octaveSpan: Int = Int((Double(targetStep) / Double(count)).rounded(.down))
let newOctave: Int = octaveSpan + letterBump(baseName)
return .named(alteredName, newOctave)
}
}
@@ -0,0 +1,171 @@
// Scale+Factories.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Convenience factories building a ``Scale`` from a tonic and a fixed interval
/// pattern (item a1).
///
/// **Diatonic modes** (7 notes) use seven distinct letters, so the interval
/// pattern alone guarantees correct spelling for every tonic.
///
/// **Symmetric scales** (whole-tone / octatonic / augmented / chromatic) have
/// more notes than letters, so a letter must repeat. Each factory fixes a
/// **canonical spelling** via its interval pattern — ascending intervals from
/// the tonic spell sharps going up and flats per the pattern's choices (e.g.
/// `wholeTone(.c)` → `C D E F♯ G♯ A♯`; `octatonicHalfWhole(.c)` →
/// `C D♭ E♭ E F♯ G A B♭`). Transpose the tonic and the whole spelling follows.
extension Scale {
// MARK: - Diatonic modes (7 notes, 7 letters)
/// Major (Ionian): `P1 M2 M3 P4 P5 M6 M7`.
public static func major(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .majorThird, .perfectFourth,
.perfectFifth, .majorSixth, .majorSeventh,
])
}
/// Alias for ``major(_:)``.
public static func ionian(_ tonic: NoteName) throws -> Scale { try major(tonic) }
/// Dorian: `P1 M2 m3 P4 P5 M6 m7`.
public static func dorian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .minorThird, .perfectFourth,
.perfectFifth, .majorSixth, .minorSeventh,
])
}
/// Phrygian: `P1 m2 m3 P4 P5 m6 m7`.
public static func phrygian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorSecond, .minorThird, .perfectFourth,
.perfectFifth, .minorSixth, .minorSeventh,
])
}
/// Lydian: `P1 M2 M3 A4 P5 M6 M7`.
public static func lydian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .majorThird, .augmentedFourth,
.perfectFifth, .majorSixth, .majorSeventh,
])
}
/// Mixolydian: `P1 M2 M3 P4 P5 M6 m7`.
public static func mixolydian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .majorThird, .perfectFourth,
.perfectFifth, .majorSixth, .minorSeventh,
])
}
/// Aeolian (natural minor): `P1 M2 m3 P4 P5 m6 m7`.
public static func aeolian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .minorThird, .perfectFourth,
.perfectFifth, .minorSixth, .minorSeventh,
])
}
/// Alias for ``aeolian(_:)``.
public static func naturalMinor(_ tonic: NoteName) throws -> Scale { try aeolian(tonic) }
/// Locrian: `P1 m2 m3 P4 d5 m6 m7`.
public static func locrian(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorSecond, .minorThird, .perfectFourth,
.diminishedFifth, .minorSixth, .minorSeventh,
])
}
/// Harmonic minor: `P1 M2 m3 P4 P5 m6 M7`.
public static func harmonicMinor(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .minorThird, .perfectFourth,
.perfectFifth, .minorSixth, .majorSeventh,
])
}
/// Melodic minor (ascending): `P1 M2 m3 P4 P5 M6 M7`.
public static func melodicMinor(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .minorThird, .perfectFourth,
.perfectFifth, .majorSixth, .majorSeventh,
])
}
// MARK: - Symmetric scales (canonical spelling per pattern)
/// Whole-tone (6 notes): `P1 M2 M3 A4 A5 A6` → `C D E F♯ G♯ A♯`.
public static func wholeTone(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .majorThird,
.augmentedFourth, .augmentedFifth, .augmentedSixth,
])
}
/// Chromatic (12 notes): ascending sharps → `C C♯ D D♯ E F F♯ G G♯ A A♯ B`.
public static func chromatic(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .augmentedUnison, .majorSecond, .augmentedSecond,
.majorThird, .perfectFourth, .augmentedFourth, .perfectFifth,
.augmentedFifth, .majorSixth, .augmentedSixth, .majorSeventh,
])
}
/// Octatonic, half-step first (8 notes): `P1 m2 m3 M3 A4 P5 M6 m7`
/// → `C D♭ E♭ E F♯ G A B♭`.
public static func octatonicHalfWhole(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorSecond, .minorThird, .majorThird,
.augmentedFourth, .perfectFifth, .majorSixth, .minorSeventh,
])
}
/// Octatonic, whole-step first (8 notes): `P1 M2 m3 P4 d5 m6 M6 M7`
/// → `C D E♭ F G♭ A♭ A B`.
public static func octatonicWholeHalf(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .minorThird, .perfectFourth,
.diminishedFifth, .minorSixth, .majorSixth, .majorSeventh,
])
}
/// Augmented (hexatonic, 6 notes): `P1 m3 M3 P5 m6 M7` → `C E♭ E G A♭ B`.
public static func augmentedScale(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorThird, .majorThird,
.perfectFifth, .minorSixth, .majorSeventh,
])
}
// MARK: - Pentatonic / blues
/// Major pentatonic (5 notes): `P1 M2 M3 P5 M6` → `C D E G A`.
public static func majorPentatonic(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .majorSecond, .majorThird, .perfectFifth, .majorSixth,
])
}
/// Minor pentatonic (5 notes): `P1 m3 P4 P5 m7` → `C E♭ F G B♭`.
public static func minorPentatonic(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorThird, .perfectFourth, .perfectFifth, .minorSeventh,
])
}
/// Blues (6 notes): `P1 m3 P4 d5 P5 m7` → `C E♭ F G♭ G B♭`.
public static func blues(_ tonic: NoteName) throws -> Scale {
try Scale(tonic: tonic, intervals: [
.unison, .minorThird, .perfectFourth,
.diminishedFifth, .perfectFifth, .minorSeventh,
])
}
}
+182
View File
@@ -0,0 +1,182 @@
// Scale.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// An ordered set of spelled pitch-classes built on a tonic — a diatonic mode,
/// a symmetric scale, or any arbitrary collection treated as a scale.
///
/// `degrees[0]` is always the tonic; each subsequent entry is one scale degree,
/// correctly spelled. Diatonic 7-note scales use seven distinct letters (the
/// interval pattern guarantees the letter progression — `D major` →
/// `D E F♯ G A B C♯`). Symmetric scales (whole-tone, octatonic, …) have no
/// one-letter-per-degree mapping; their factories define a canonical spelling.
///
/// Pure value type — no octave is stored; degrees are pitch-classes. Octave is
/// supplied per query via ``pitch(atDegree:octave:)``.
public struct Scale: Sendable, Hashable {
/// The tonic — always equal to `degrees[0]`.
public let tonic: NoteName
/// The spelled scale degrees in ascending order, one per degree.
public let degrees: [NoteName]
/// Number of degrees in the scale.
public var count: Int { degrees.count }
// MARK: - Initializers
/// Build a scale from a tonic and a list of intervals measured from the
/// tonic. The first interval is normally ``Interval/unison`` so
/// `degrees[0] == tonic`. Each degree is spelled by transposing the tonic
/// by its interval, which guarantees the per-degree letter progression.
///
/// - Parameters:
/// - tonic: The tonic note name.
/// - intervals: Intervals from the tonic, ascending. Must be non-empty.
/// - Throws: ``ScaleError/emptyDegrees`` if `intervals` is empty; any
/// ``IntervalError`` from spelling a degree.
public init(
tonic: NoteName,
intervals: [Interval]
) throws {
guard !intervals.isEmpty else { throw ScaleError.emptyDegrees }
self.tonic = tonic
self.degrees = try intervals.map { try tonic.transposed(by: $0, .up) }
}
/// Build a scale from an explicit list of spelled degrees.
///
/// - Parameters:
/// - tonic: The tonic; must equal `degrees[0]`.
/// - degrees: Ascending spelled degrees. Must be non-empty.
/// - Throws: ``ScaleError/emptyDegrees`` or ``ScaleError/tonicMismatch(tonic:firstDegree:)``.
public init(
tonic: NoteName,
degrees: [NoteName]
) throws {
guard let first: NoteName = degrees.first else { throw ScaleError.emptyDegrees }
guard first == tonic else {
throw ScaleError.tonicMismatch(tonic: tonic, firstDegree: first)
}
self.tonic = tonic
self.degrees = degrees
}
/// Build a scale from an arbitrary ordered set of named pitches (item a).
/// Octaves are discarded — only the spelled note names are kept.
///
/// - Parameters:
/// - tonic: The tonic; must equal the first pitch's note name.
/// - pitches: Ordered pitches. Each must be ``Pitch/named(_:_:)``.
/// - Throws: ``ScaleError/emptyDegrees``, ``ScaleError/nonNamedPitch(_:)``,
/// or ``ScaleError/tonicMismatch(tonic:firstDegree:)``.
public init(
tonic: NoteName,
pitches: [Pitch]
) throws {
guard !pitches.isEmpty else { throw ScaleError.emptyDegrees }
var names: [NoteName] = []
names.reserveCapacity(pitches.count)
for pitch: Pitch in pitches {
guard case .named(let name, _) = pitch else {
throw ScaleError.nonNamedPitch(pitch)
}
names.append(name)
}
try self.init(tonic: tonic, degrees: names)
}
// MARK: - Queries
/// Whether `name` is a member of the scale, by pitch-class (enharmonic
/// equivalents count — `F♯` matches a `G♭` degree).
public func contains(_ name: NoteName) -> Bool {
let pc: Int = Scale.pitchClass(name)
return degrees.contains { Scale.pitchClass($0) == pc }
}
/// Locate `name` within the scale as a ``ScaleDegree`` — a degree index plus
/// the chromatic alteration needed to reach a non-scale pitch.
///
/// Resolution order: exact spelling → enharmonic pitch-class → same letter
/// (alteration = accidental difference) → nearest pitch-class by signed
/// semitone distance. Returns `nil` only for an empty scale (which the
/// initializers forbid).
public func degree(of name: NoteName) -> ScaleDegree? {
guard !degrees.isEmpty else { return nil }
// 1. Exact spelling.
if let i: Int = degrees.firstIndex(of: name) {
return ScaleDegree(index: i, alteration: 0)
}
let targetPc: Int = Scale.pitchClass(name)
// 2. Enharmonic pitch-class.
if let i: Int = degrees.firstIndex(where: { Scale.pitchClass($0) == targetPc }) {
return ScaleDegree(index: i, alteration: 0)
}
// 3. Same letter — alteration is the accidental difference.
if let i: Int = degrees.firstIndex(where: { $0.letter == name.letter }) {
let alteration: Int = Int((name.semitones - degrees[i].semitones).rounded())
return ScaleDegree(index: i, alteration: alteration)
}
// 4. Nearest pitch-class by signed circular distance. The seed exceeds
// every valid signed distance ([-6, 5]) and is always overwritten on the
// first degree (the scale is non-empty), so it is a sentinel only.
var bestIndex: Int = 0
var bestDistance: Int = Scale.semitonesPerOctave
for (i, degree): (Int, NoteName) in degrees.enumerated() {
let raw: Int = targetPc - Scale.pitchClass(degree)
let signed: Int = ((raw + Scale.semitonesPerOctave + Scale.semitonesPerOctave / 2)
% Scale.semitonesPerOctave) - Scale.semitonesPerOctave / 2
if abs(signed) < abs(bestDistance) {
bestDistance = signed
bestIndex = i
}
}
return ScaleDegree(index: bestIndex, alteration: bestDistance)
}
/// The spelled note name at a degree index, wrapping modulo ``count`` so
/// indices beyond the scale (or negative) map back into it.
public func noteName(atDegree index: Int) -> NoteName {
let wrapped: Int = ((index % count) + count) % count
return degrees[wrapped]
}
/// The pitch at a degree index in a given base octave. Degree indices beyond
/// the scale add octaves; degrees whose letter sits below the tonic's letter
/// are placed in the next octave so the scale ascends from the tonic.
///
/// - Parameters:
/// - index: Degree index (0 = tonic); may exceed ``count`` or be negative.
/// - octave: Base octave of the tonic (4 = middle-C octave).
public func pitch(atDegree index: Int, octave: Int) -> Pitch {
let octaveSpan: Int = Int((Double(index) / Double(count)).rounded(.down))
let name: NoteName = noteName(atDegree: index)
return .named(name, octave + octaveSpan + letterBump(name))
}
// MARK: - Helpers
/// `1` when `name`'s letter sits below the tonic's letter (so it belongs in
/// the next octave when ascending from the tonic), else `0`. Shared by the
/// octave bookkeeping in ``pitch(atDegree:octave:)`` and diatonic / mapping
/// operations.
func letterBump(_ name: NoteName) -> Int {
name.letter.diatonicIndex < tonic.letter.diatonicIndex ? 1 : 0
}
/// Pitch-class `[0, 11]` of a note name (`C = 0`), folding the octave wrap
/// of `C♭` / `B♯` and any accidental back into range.
static func pitchClass(_ name: NoteName) -> Int {
let raw: Int = Int(name.semitones.rounded())
return ((raw % semitonesPerOctave) + semitonesPerOctave) % semitonesPerOctave
}
/// Semitones per octave (`12`).
static let semitonesPerOctave: Int = 12
}
@@ -0,0 +1,33 @@
// ScaleDegree.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// The position of a pitch within a ``Scale``: a degree `index` plus a
/// chromatic `alteration`.
///
/// `index` is 0-based (`0` = tonic, `1` = second degree, …). `alteration` is the
/// semitone offset needed to reach a *non-scale* (chromatic) pitch from the
/// nearest scale degree — `0` for a pitch that is in the scale, `+1` for a pitch
/// a semitone above its degree, `-1` for a semitone below. This lets diatonic
/// transposition (T4) and scale-to-scale mapping (T6) carry chromatic pitches
/// through the degree machinery without losing them.
public struct ScaleDegree: Sendable, Hashable {
/// 0-based degree index within the scale (`0` = tonic).
public let index: Int
/// Chromatic alteration in semitones from the degree (`0` if in-scale).
public let alteration: Int
public init(
index: Int,
alteration: Int = 0
) {
self.index = index
self.alteration = alteration
}
}
@@ -0,0 +1,21 @@
// ScaleError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown when constructing a ``Scale``.
public enum ScaleError: Error, Sendable, Hashable {
/// The degree list was empty — a scale needs at least its tonic.
case emptyDegrees
/// The supplied `tonic` did not match `degrees[0]`.
case tonicMismatch(tonic: NoteName, firstDegree: NoteName)
/// A ``Pitch`` in a `pitches:` initializer was not a ``Pitch/named(_:_:)``
/// value, so it carries no spelled note name to use as a scale degree.
case nonNamedPitch(Pitch)
}
@@ -0,0 +1,19 @@
// ToneRowError.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Errors thrown by the 12-tone row operations on ``PitchCollection``.
public enum ToneRowError: Error, Sendable, Hashable {
/// The collection is not a valid 12-tone row: it does not contain exactly
/// twelve named pitches spanning all twelve distinct pitch-classes.
case notTwelveToneRow(pitchCount: Int, distinctClasses: Int)
/// A pitch in the row was not a ``Pitch/named(_:_:)`` value, so it has no
/// spelled note name.
case nonNamedPitch(Pitch)
}
+196
View File
@@ -0,0 +1,196 @@
// TimeSignature.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// A time signature with an explicit beat grouping.
///
/// The grouping is the primitive: a partition of the `numerator` into beats,
/// each value counting how many denominator-notes the beat spans. Simple,
/// compound, and complex/additive meters are all just different groupings — no
/// special-casing.
///
/// - **Simple** `4/4` → `[1, 1, 1, 1]` (four quarter-note beats).
/// - **Compound** `6/8` → `[3, 3]` (two dotted-quarter beats). Auto-inferred.
/// - **Compound-but-felt-simple** slow `6/8` → pass `grouping: [1, 1, 1, 1, 1, 1]`
/// for six eighth-note beats.
/// - **Complex / additive** `8/8` as 3+3+2 → pass `grouping: [3, 3, 2]`
/// (dotted-quarter, dotted-quarter, quarter).
///
/// One Lyrebird beat is always one quarter note (see ``ScoreEvent/beat``); this
/// type carries no beat-math of its own beyond ``measureQuarters``. It is
/// notation/positioning metadata consumed by the MusicXML encoder and the
/// beat-timeline resolver.
public struct TimeSignature: Hashable, Sendable {
/// Beats per measure (top number). `>= 1`.
public let numerator: Int
/// Beat unit (bottom number): `1`, `2`, `4`, `8`, `16`, … `>= 1`.
public let denominator: Int
/// Partition of `numerator` into felt beats, in denominator-note units.
/// Every entry is `>= 1` and the entries sum to `numerator`.
public let beatGrouping: [Int]
// MARK: - Construction
/// Designated initializer with an explicit beat grouping.
///
/// - Parameters:
/// - numerator: Top number, `>= 1`.
/// - denominator: Bottom number, `>= 1`.
/// - grouping: Partition of `numerator`; each entry `>= 1`, sum `== numerator`.
public init(
_ numerator: Int,
_ denominator: Int,
grouping: [Int]
) {
precondition(numerator >= 1, "TimeSignature: numerator must be >= 1, got \(numerator)")
precondition(denominator >= 1, "TimeSignature: denominator must be >= 1, got \(denominator)")
precondition(
grouping.allSatisfy { $0 >= 1 },
"TimeSignature: every beatGrouping entry must be >= 1, got \(grouping)"
)
let sum: Int = grouping.reduce(0, +)
precondition(
sum == numerator,
"TimeSignature: beatGrouping must sum to the numerator (\(numerator)), got \(grouping) summing to \(sum)"
)
self.numerator = numerator
self.denominator = denominator
self.beatGrouping = grouping
}
/// Convenience initializer that infers a default beat grouping.
///
/// Compound default (groups of three) when `denominator` is `8` or `16`,
/// `numerator` is divisible by three, and `numerator > 3` (so `6/8`, `9/8`,
/// `12/8`, `6/16`, … become `[3, 3, …]`). Otherwise simple — one beat per
/// denominator-note (`[1, 1, …]`). Override with the `grouping:` initializer
/// for slow-compound-felt-simple or complex/additive meters.
///
/// - Parameters:
/// - numerator: Top number, `>= 1`.
/// - denominator: Bottom number, `>= 1`.
public init(
_ numerator: Int,
_ denominator: Int
) {
self.init(
numerator,
denominator,
grouping: TimeSignature.defaultGrouping(numerator: numerator, denominator: denominator)
)
}
/// Convenience initializer from a `(numerator, denominator)` tuple. Infers
/// the default grouping (see ``init(_:_:)``). Bridges legacy
/// `Score(timeSignature:)` call sites.
///
/// - Parameter tuple: `(numerator, denominator)` pair.
public init(_ tuple: (Int, Int)) {
self.init(tuple.0, tuple.1)
}
/// Default grouping for `numerator`/`denominator` — groups of three for a
/// compound meter, otherwise one beat per denominator-note.
static func defaultGrouping(
numerator: Int,
denominator: Int
) -> [Int] {
let compoundUnit: Int = 3
let isCompoundDefault: Bool =
(denominator == 8 || denominator == 16)
&& numerator % compoundUnit == 0
&& numerator > compoundUnit
if isCompoundDefault {
return Array(repeating: compoundUnit, count: numerator / compoundUnit)
}
return Array(repeating: 1, count: numerator)
}
// MARK: - Derived
/// Measure capacity in quarter-note beats: `numerator * 4 / denominator`.
/// `4/4 → 4`, `3/4 → 3`, `6/8 → 3`, `7/8 → 3½`.
public var measureQuarters: Fraction {
Fraction(numerator * 4, denominator)
}
/// `true` when any felt beat spans more than one denominator-note (i.e. the
/// beat is dotted / grouped). `6/8` as `[3, 3]` is compound; `6/8` as
/// `[1, 1, 1, 1, 1, 1]` is not.
public var isCompound: Bool {
beatGrouping.contains { $0 > 1 }
}
/// Number of felt beats per measure — `beatGrouping.count`.
public var beatsPerBar: Int {
beatGrouping.count
}
/// Duration of one denominator-note in quarter beats — `4 / denominator`.
/// `den 4 → 1` (quarter), `den 8 → 1/2` (eighth), `den 2 → 2` (half).
public var divisionQuarters: Fraction {
Fraction(4, denominator)
}
/// Quarter-beat onset of each felt beat within a bar (0-based offsets).
/// `count == beatsPerBar`. For `6/8` `[3,3]` → `[0, 3/2]` (the two
/// dotted-quarter beats); for `8/8` `[3,3,2]` → `[0, 3/2, 3]`.
public var beatOnsetsQuarters: [Fraction] {
let unit: Fraction = divisionQuarters
var onsets: [Fraction] = []
onsets.reserveCapacity(beatGrouping.count)
var accDenomUnits: Int = 0
for group: Int in beatGrouping {
onsets.append(Fraction(accDenomUnits, 1) * unit)
accDenomUnits += group
}
return onsets
}
/// Quarter-beat length of each felt beat within a bar. `count == beatsPerBar`.
/// For `6/8` `[3,3]` → `[3/2, 3/2]`; for `8/8` `[3,3,2]` → `[3/2, 3/2, 1]`.
public var beatLengthsQuarters: [Fraction] {
let unit: Fraction = divisionQuarters
return beatGrouping.map { Fraction($0, 1) * unit }
}
/// `(numerator, denominator)` tuple. For legacy call sites and MusicXML
/// `<time>` emission.
public var tuple: (Int, Int) {
(numerator, denominator)
}
// MARK: - Common signatures
/// `4/4` — common time. Grouping `[1, 1, 1, 1]`.
public static let fourFour: TimeSignature = TimeSignature(4, 4)
/// `3/4` — waltz time. Grouping `[1, 1, 1]`.
public static let threeFour: TimeSignature = TimeSignature(3, 4)
/// `2/4`. Grouping `[1, 1]`.
public static let twoFour: TimeSignature = TimeSignature(2, 4)
/// `2/2` — cut time. Grouping `[1, 1]`.
public static let cutTime: TimeSignature = TimeSignature(2, 2)
/// `6/8` compound — two dotted-quarter beats. Grouping `[3, 3]`.
public static let sixEightCompound: TimeSignature = TimeSignature(6, 8)
/// `6/8` felt simple — six eighth-note beats (slow tempo). Grouping
/// `[1, 1, 1, 1, 1, 1]`.
public static let sixEightSimple: TimeSignature = TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1])
/// `9/8` compound — three dotted-quarter beats. Grouping `[3, 3, 3]`.
public static let nineEight: TimeSignature = TimeSignature(9, 8)
/// `12/8` compound — four dotted-quarter beats. Grouping `[3, 3, 3, 3]`.
public static let twelveEight: TimeSignature = TimeSignature(12, 8)
}
+102
View File
@@ -0,0 +1,102 @@
// Transpose.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Describes the relationship between written (notated) pitch and sounding
/// (concert) pitch for a transposing instrument.
///
/// The values follow the MusicXML 4.0 `<transpose>` convention:
/// **add chromatic/diatonic to the WRITTEN pitch to get the SOUNDING pitch.**
///
/// - A B♭ clarinet plays written C but sounds B♭ — one major second lower.
/// Written → sounding is `−2` semitones / `−1` diatonic step → `chromatic: -2, diatonic: -1`.
/// - A horn in F sounds a perfect fifth (7 semitones) below written pitch →
/// `chromatic: -7, diatonic: -4`.
///
/// ## Notation-only
///
/// `Transpose` is **purely notational**. It instructs the engraver to draw the
/// instrument's key signature at the per-part override, and embeds a `<transpose>`
/// block in the first-measure `<attributes>` so notation software (Dorico, Finale,
/// MuseScore) can render the transposing part correctly.
///
/// ``ScorePart/flatten()`` returns events at the **written** pitch; the transpose
/// interval is **not** applied to produce sounding pitches. Concert-pitch playback
/// (shifting events by the transpose interval) is planned for a future phase.
///
/// ## MusicXML child order
///
/// ```xml
/// <transpose>
/// <diatonic>D</diatonic>
/// <chromatic>C</chromatic>
/// <octave-change>K</octave-change> <!-- omitted when 0 -->
/// </transpose>
/// ```
public struct Transpose: Sendable, Hashable {
/// Chromatic semitone shift from written to sounding pitch.
///
/// Negative when the instrument sounds below written (B♭ = `-2`, F horn = `-7`).
/// Positive when the instrument sounds above written (E♭ sax written a minor 3rd
/// below sounding would have `chromatic: +3`).
public let chromatic: Int
/// Diatonic step shift from written to sounding pitch (staff lines/spaces).
///
/// A major 2nd down is `−1` diatonic step; a perfect 5th down is `−4` diatonic steps.
/// Defaults to `0` when omitted (caller is responsible for providing the correct value).
public let diatonic: Int
/// Additional octave shift beyond the chromatic/diatonic interval.
///
/// `0` for unison or single-octave transpositions; `−1` for bass clarinet relative to
/// B♭ soprano (sounds an octave + major 2nd below written pitch = same chromatic/diatonic
/// as B♭ but `octaveChange: -1`). Omitted from MusicXML when `0`.
public let octaveChange: Int
/// Create a `Transpose` from explicit interval components.
///
/// - Parameters:
/// - chromatic: Semitone shift written→sounding. Negative = sounds below written.
/// - diatonic: Diatonic step shift written→sounding. Defaults to `0`.
/// - octaveChange: Additional octave shift. Defaults to `0`.
public init(
chromatic: Int,
diatonic: Int = 0,
octaveChange: Int = 0
) {
self.chromatic = chromatic
self.diatonic = diatonic
self.octaveChange = octaveChange
}
}
// MARK: - Named instrument conveniences
extension Transpose {
/// B♭ clarinet / B♭ trumpet — written pitch sounds a major 2nd below.
///
/// Written C → sounds B♭. `chromatic: -2, diatonic: -1`.
/// Write a major 2nd UP from the concert pitch to get the written part.
public static let bFlat: Transpose = Transpose(chromatic: -2, diatonic: -1)
/// Clarinet in A — written pitch sounds a minor 3rd below.
///
/// Written C → sounds A. `chromatic: -3, diatonic: -2`.
public static let a: Transpose = Transpose(chromatic: -3, diatonic: -2)
/// Alto saxophone in E♭ — written pitch sounds a major 6th below.
///
/// Written C → sounds E♭ below (9 semitones, 5 diatonic steps down).
/// `chromatic: -9, diatonic: -5`.
public static let eFlat: Transpose = Transpose(chromatic: -9, diatonic: -5)
/// Horn in F — written pitch sounds a perfect 5th below.
///
/// Written C → sounds F below. `chromatic: -7, diatonic: -4`.
public static let fHorn: Transpose = Transpose(chromatic: -7, diatonic: -4)
}
+34
View File
@@ -0,0 +1,34 @@
// WedgeKind.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// The direction of a hairpin (wedge) marking in a score.
///
/// Used by ``ScoreElement/wedge(_:_:)`` to specify whether the span is a
/// crescendo or diminuendo. The kind maps directly to the MusicXML
/// `<wedge type>` attribute values `"crescendo"` and `"diminuendo"`.
///
/// ## MusicXML values
///
/// | `WedgeKind` | `<wedge type>` |
/// |---|---|
/// | `.crescendo` | `"crescendo"` |
/// | `.diminuendo` | `"diminuendo"` |
///
/// A span close always emits `<wedge type="stop"/>` regardless of kind.
public enum WedgeKind: Sendable, Hashable {
/// A growing dynamic wedge `<` — played progressively louder.
case crescendo
/// A narrowing dynamic wedge `>` — played progressively softer.
case diminuendo
/// The MusicXML `type` attribute value for the wedge open event.
internal var musicXMLType: String {
switch self {
case .crescendo: return "crescendo"
case .diminuendo: return "diminuendo"
}
}
}
@@ -13,7 +13,7 @@
/// The default evaluate() implementation is a no-op. Most users subclass SynthesizerBase,
/// which wires evaluate() to a set of registered output generators.
///
/// ## Actor isolation (Phase 201)
/// ## Actor isolation
///
/// The language-side surface (`build`, `release`, `free`) is `@MainActor`-isolated so a
/// consumer building under Xcode 26's default `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor`
@@ -21,7 +21,7 @@
/// annotations — the consumer's MainActor default now *matches* the base instead of
/// conflicting with a nonisolated override. The single RT-thread entry point, `evaluate`,
/// is explicitly `nonisolated` so the engine's render callback reaches it with no actor
/// hop. See `ARCHITECTURE.md` §9 and `docs/00-working-order.md` Phase 201.
/// hop. See `ARCHITECTURE.md` §9.
///
/// Isolation is declared **per-requirement** rather than at the protocol level on purpose:
/// the consumer guarantee comes from `SynthesizerBase` being a `@MainActor` class (so its
@@ -75,7 +75,7 @@ import Synchronization
/// the RT thread. Always `engine.remove(synth)` and allow at least one `processBlock` to
/// pass before re-adding the same instance.
///
/// ## Actor isolation (Phase 201)
/// ## Actor isolation
///
/// The class is `@MainActor`-isolated so consumer subclasses building under Xcode 26's
/// `SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor` default override `build()` / `init()` with
@@ -623,7 +623,7 @@ open class SynthesizerBase: Synthesizer {
/// File-scope holder for the `build()`-context task-local.
///
/// The task-local cannot live as a static on `SynthesizerBase` because that class is
/// `@MainActor` (Phase 201): `@TaskLocal` would synthesise a main-actor-isolated
/// `@MainActor`: `@TaskLocal` would synthesise a main-actor-isolated
/// `$`-projected accessor, which the **nonisolated** generator-init read path
/// (`RootRegistering` / `DoneActionWatchable` self-registration) cannot reach. Hoisting it
/// into this plain `enum` keeps both the `withValue` writer (on main, inside `rebuildGraph`)
@@ -0,0 +1,147 @@
// LyrebirdPaths.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
/// Filesystem-location conveniences for Lyrebird projects.
///
/// A small namespace of URLs you commonly need when writing render output,
/// presets, recordings, or caches — without hand-rolling `FileManager`
/// boilerplate at every call site.
///
/// Two groups:
///
/// 1. **Source-anchored** — ``projectRoot(from:marker:)``. Resolves the package
/// directory by walking up from the *calling* source file at compile time.
/// Dev-time only: the returned path is the location of your source on the
/// machine that **built** the binary. It will not exist on another user's
/// machine, so do not use it for shipped apps writing user data — use
/// ``documents`` (or ``applicationSupport``) there.
///
/// 2. **Sandbox-standard** — ``documents`` / ``applicationSupport`` / ``caches``
/// / ``temporary`` / ``home`` / ``currentWorkingDirectory`` (and macOS-only
/// ``desktop``). These resolve at runtime via `FileManager` and are correct
/// on both macOS and iOS, including sandboxed apps.
///
/// All members are non-RT — never call from a render callback.
public enum LyrebirdPaths {
// MARK: Source-anchored
/// The project root, found by walking up from the **calling** source file
/// until a directory containing `marker` is reached.
///
/// `#filePath` is a magic literal: as a *default argument* it expands at the
/// call site, so `LyrebirdPaths.projectRoot()` captures the caller's source
/// path, not this file's. Walking up to a marker (default `Package.swift`)
/// survives moving the source file to any depth under the project.
///
/// - Important: Dev-time only. The path reflects where the binary was built;
/// it will not exist on another machine. For shipped apps writing user
/// data, use ``documents`` instead.
///
/// - Parameters:
/// - file: The calling source file. Leave at the `#filePath` default.
/// - marker: What marks the project root. Either an exact filename
/// (default `"Package.swift"`) or — when it begins with a dot — a path
/// extension matched against directory contents, so `".xcodeproj"`
/// matches `MyApp.xcodeproj` (use for an Xcode-project layout with no
/// `Package.swift`).
/// - Returns: The project-root URL, or `nil` if no `marker` is found up to
/// the filesystem root.
public static func projectRoot(
from file: String = #filePath,
marker: String = "Package.swift"
) -> URL? {
var dir: URL = URL(fileURLWithPath: file).deletingLastPathComponent()
while !directory(dir, contains: marker) {
let parent: URL = dir.deletingLastPathComponent()
if parent.path == dir.path { return nil } // reached "/" — not found
dir = parent
}
return dir
}
/// Whether `dir` directly contains `marker` — by exact filename, or, when
/// `marker` begins with a dot, by any entry with that path extension
/// (so `".xcodeproj"` matches `MyApp.xcodeproj`).
private static func directory(_ dir: URL, contains marker: String) -> Bool {
let fm: FileManager = FileManager.default
if fm.fileExists(atPath: dir.appendingPathComponent(marker).path) {
return true
}
guard marker.hasPrefix(".") else { return false }
let ext: String = String(marker.dropFirst())
let entries: [String] = (try? fm.contentsOfDirectory(atPath: dir.path)) ?? []
return entries.contains { (entry: String) in
(entry as NSString).pathExtension == ext
}
}
// MARK: Sandbox-standard
/// The user Documents directory (`.documentDirectory`).
///
/// The canonical writable, user-visible location on iOS; `~/Documents` on
/// macOS. Falls back to ``temporary`` in the unlikely event the lookup fails.
public static var documents: URL {
searchPath(.documentDirectory)
}
/// The Application Support directory (`.applicationSupportDirectory`).
///
/// For app-managed data not meant to be user-visible. Falls back to
/// ``temporary`` if the lookup fails.
public static var applicationSupport: URL {
searchPath(.applicationSupportDirectory)
}
/// The Caches directory (`.cachesDirectory`).
///
/// For regenerable data the system may purge. Falls back to ``temporary``
/// if the lookup fails.
public static var caches: URL {
searchPath(.cachesDirectory)
}
/// The per-process temporary directory.
public static var temporary: URL {
FileManager.default.temporaryDirectory
}
/// The current user's home directory.
public static var home: URL {
FileManager.default.homeDirectoryForCurrentUser
}
/// The process current working directory.
///
/// Equals the project root when launched via `lyrebird run` / `swift run`,
/// but is `DerivedData` under Xcode and arbitrary for a bare binary — prefer
/// ``projectRoot(from:marker:)`` for dev output.
public static var currentWorkingDirectory: URL {
URL(fileURLWithPath: FileManager.default.currentDirectoryPath)
}
#if os(macOS)
/// The user Desktop directory (`.desktopDirectory`). macOS only.
///
/// - Returns: The Desktop URL, or `nil` if it cannot be resolved (e.g. a
/// sandboxed app without the corresponding entitlement).
public static var desktop: URL? {
FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask).first
}
#endif
// MARK: Private
/// First URL for `directory` in the user domain, or ``temporary`` as a
/// last-resort fallback (the standard sandbox dirs always resolve).
private static func searchPath(_ directory: FileManager.SearchPathDirectory) -> URL {
let urls: [URL] = FileManager.default.urls(for: directory, in: .userDomainMask)
return urls.first ?? FileManager.default.temporaryDirectory
}
}
-109
View File
@@ -1,109 +0,0 @@
// CLICommand.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
/// Top-level commands parsed from `CommandLine.arguments`.
public enum CLICommand: Equatable {
/// Build the current package, then launch `swift repl` with Lyrebird available.
case repl
/// Enter the LineNoise-powered `lyrebird>` interactive shell (no subcommand given).
case interactive
/// Print usage help.
case help
/// Print the lyrebird version string.
case version
/// Scaffold a new Lyrebird project in a directory named `name` using `template`.
/// When `lyrebirdPath` is set, the generated `Package.swift` and (where
/// applicable) `.xcodeproj` reference Lyrebird as a local SPM package at
/// that absolute path instead of pulling from the published Git URL.
case new(name: String, template: ProjectTemplate, lyrebirdPath: String?)
/// Run the current project with `swift run`.
case run(release: Bool)
/// Export a named Synthesizer template to a Swift source file.
/// When `overwrite` is `true`, an existing file at the destination is replaced.
case export(name: String, to: String?, overwrite: Bool)
/// Install Lyrebird Xcode file templates to the user template directory.
/// When `force` is `true`, replaces any existing installation.
case installTemplates(force: Bool)
/// Remove Lyrebird Xcode file templates from the user template directory.
case uninstallTemplates
/// Parse the command from a raw arguments array (typically `CommandLine.arguments`).
///
/// - Parameter arguments: The full argument vector. `arguments[0]` is the binary name;
/// `arguments[1]` (if present) is the subcommand.
/// - Returns: The matching command, or `.help` for unrecognised or malformed subcommands.
public static func parse(_ arguments: [String]) -> CLICommand {
guard arguments.count > 1 else { return .interactive }
switch arguments[1].lowercased() {
case "repl":
return .repl
case "version", "--version":
return .version
case "help", "--help", "-h":
return .help
case "new":
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
// If the positional argument looks like a flag, the user omitted the name.
guard !arguments[2].hasPrefix("-") else { return .help }
let template: ProjectTemplate
if let tIdx: Array<String>.Index = arguments.firstIndex(of: "--template"),
tIdx + 1 < arguments.count,
let t: ProjectTemplate = ProjectTemplate(string: arguments[tIdx + 1]) {
template = t
} else {
template = .basic
}
// Optional `--lyrebird-path <abs-path>` for local-checkout use.
// Value must not be a flag token.
let lyrebirdPath: String?
if let pIdx: Array<String>.Index = arguments.firstIndex(of: "--lyrebird-path"),
pIdx + 1 < arguments.count,
!arguments[pIdx + 1].hasPrefix("-") {
lyrebirdPath = arguments[pIdx + 1]
} else {
lyrebirdPath = nil
}
return .new(name: arguments[2],
template: template,
lyrebirdPath: lyrebirdPath)
case "run":
let release: Bool = arguments.contains("--release")
return .run(release: release)
case "install-templates":
let force: Bool = arguments.contains("--force")
return .installTemplates(force: force)
case "uninstall-templates":
return .uninstallTemplates
case "export":
guard arguments.count > 2, !arguments[2].isEmpty else { return .help }
let synthName: String = arguments[2]
// If the positional argument looks like a flag, the user omitted the name.
guard !synthName.hasPrefix("-") else { return .help }
// Look for `--to <path>` anywhere after the subcommand.
// Guard that the value following `--to` is not itself a flag token.
let toPath: String?
if let toIdx: Array<String>.Index = arguments.firstIndex(of: "--to"),
toIdx + 1 < arguments.count,
!arguments[toIdx + 1].hasPrefix("-") {
toPath = arguments[toIdx + 1]
} else {
toPath = nil
}
let overwrite: Bool = arguments.contains("--overwrite")
return .export(name: synthName, to: toPath, overwrite: overwrite)
default:
return .help
}
}
}
+1 -1
View File
@@ -285,7 +285,7 @@ public enum InteractiveShell {
print("""
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: basic (default), demo, ui-demo, nrt
Templates: basic (default), demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates to user dir
+15 -2
View File
@@ -116,11 +116,24 @@ struct LyrebirdCLIMain {
} else {
resolvedPath = nil
}
// Report which Lyrebird dependency the generated Package.swift will pin.
let effectivePath: String? = resolvedPath ?? ProjectScaffolder.defaultLyrebirdCheckoutPath
if let path: String = effectivePath {
print("Lyrebird dependency: local checkout at \(path)")
} else {
fputs("""
warning: no local Lyrebird checkout found; pinning published \
\(ProjectScaffolder.lyrebirdPackageURL)@\(ProjectScaffolder.lyrebirdMinimumVersion). \
The generated template may use API newer than that release — if it \
fails to build, re-run with --lyrebird-path <checkout>.
""", stderr)
}
do {
try ProjectScaffolder.scaffold(
name: name,
template: template,
lyrebirdPath: resolvedPath
lyrebirdPath: effectivePath
)
print("Created \(name)/")
} catch ProjectScaffolder.Error.projectExists(let n) {
@@ -182,7 +195,7 @@ struct LyrebirdCLIMain {
Commands:
new <name> [--template <t>] Scaffold a new Lyrebird Swift Package
Templates: basic (default), demo, ui-demo, nrt
Templates: basic (default), demo, ui-demo, nrt, score
run [--release] Build and run the current project
export <name> [--to p] Export a Synthesizer template to a .swift file
install-templates [--force] Install Xcode file templates (Generator,
-100
View File
@@ -1,100 +0,0 @@
// ProjectRunner.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Foundation
// MARK: - ProjectRunner
/// Wraps `swift run` to build and launch the current Lyrebird project.
///
/// `lyrebird run` and `lyrebird run --release` are thin wrappers: they locate the
/// `swift` binary and exec `swift run` (optionally with `-c release`) in the current
/// working directory. stdin / stdout / stderr are inherited so compiler output and
/// runtime output appear directly in the user's terminal.
///
/// The runner does **not** verify that a `Package.swift` is present before launching —
/// SPM provides a clear error message in that case.
public enum ProjectRunner {
// MARK: - Errors
/// Errors thrown by `ProjectRunner`.
public enum Error: Swift.Error, Equatable {
/// The `swift` binary could not be found on this system.
case swiftNotFound
/// The process exited with a non-zero status.
case buildFailed(exitCode: Int32)
}
// MARK: - Public API
/// Build and run the Swift package in `directory`.
///
/// - Parameters:
/// - release: When `true`, passes `-c release` to `swift run` for an optimised build.
/// - directory: The directory containing `Package.swift`.
/// Defaults to the current working directory.
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent;
/// `ProjectRunner.Error.buildFailed` if `swift run` exits non-zero.
public static func run(
release: Bool = false,
in directory: String = FileManager.default.currentDirectoryPath
) throws {
let process: Process = try makeProcess(release: release, in: directory)
try process.run()
process.waitUntilExit()
let exitCode: Int32 = process.terminationStatus
guard exitCode == 0 else {
throw Error.buildFailed(exitCode: exitCode)
}
}
// MARK: - Internal
/// Builds a `Process` configured to run `swift run` (or `swift run -c release`).
///
/// Exposed for testing so callers can inspect the process configuration without
/// actually launching a build.
///
/// - Parameters:
/// - release: When `true`, appends `-c release` to the swift arguments.
/// - directory: Working directory for the SPM invocation.
/// - Throws: `ProjectRunner.Error.swiftNotFound` if the toolchain is absent.
public static func makeProcess(
release: Bool = false,
in directory: String = FileManager.default.currentDirectoryPath
) throws -> Process {
let swiftPath: String = try findSwift()
var arguments: [String] = ["run"]
if release {
arguments += ["-c", "release"]
}
let process: Process = Process()
process.executableURL = URL(fileURLWithPath: swiftPath)
process.arguments = arguments
process.currentDirectoryURL = URL(fileURLWithPath: directory)
// stdin / stdout / stderr intentionally not set — inherited for interactive output.
return process
}
// MARK: - Helpers
/// Returns the path to the `swift` binary.
///
/// Checks, in order:
/// - `/usr/bin/swift` — Xcode Command Line Tools / Xcode toolchain
/// - `/usr/local/bin/swift` — standalone toolchain (Intel Mac default)
/// - `/opt/homebrew/bin/swift` — Homebrew toolchain on Apple Silicon
///
/// Throws `ProjectRunner.Error.swiftNotFound` if none of the candidates exist.
static func findSwift() throws -> String {
let candidates: [String] = ["/usr/bin/swift", "/usr/local/bin/swift", "/opt/homebrew/bin/swift"]
for path: String in candidates where FileManager.default.isExecutableFile(atPath: path) {
return path
}
throw Error.swiftNotFound
}
}
+230 -14
View File
@@ -18,6 +18,9 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case uiDemo = "ui-demo"
/// Non-real-time render: `NRTDriver` writes a `.caf` file and exits.
case nrt = "nrt"
/// Score / MusicXML render: builds a `Score` with the DSL, exports a
/// `.musicxml` document, and renders the score offline with `NRTDriver`.
case score = "score"
/// macOS `.app` bundle wrapping an AppKit + SwiftUI host of a `@UIParam` synth.
/// Generates a full `<name>.xcodeproj` referencing Lyrebird via remote SPM dep.
case macosUIXcode = "macos-ui-xcode"
@@ -35,6 +38,8 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
case "demo": self = .demo
case "ui-demo", "uidemo", "ui_demo": self = .uiDemo
case "nrt": self = .nrt
case "score", "score-musicxml", "scoremusicxml", "musicxml":
self = .score
case "macos-ui-xcode", "macosuixcode", "macos_ui_xcode":
self = .macosUIXcode
case "ios-ui", "iosui", "ios_ui":
@@ -52,7 +57,7 @@ public enum ProjectTemplate: String, CaseIterable, Equatable {
/// (auv3) an `.appex` extension target — none of which SwiftPM can express.
public var shipsXcodeProject: Bool {
switch self {
case .basic, .demo, .uiDemo, .nrt: return false
case .basic, .demo, .uiDemo, .nrt, .score: return false
case .macosUIXcode, .iosUI, .auv3: return true
}
}
@@ -95,6 +100,44 @@ public enum ProjectScaffolder {
// MARK: - Public API
/// Absolute path to the Lyrebird checkout this CLI was *built* from, derived
/// from the compile-time source location of this file
/// (`<root>/Sources/LyrebirdCLI/ProjectScaffolder.swift`).
///
/// Used as the default SPM dependency for scaffolded projects when the caller
/// passes no explicit `--lyrebird-path`, so generated projects track the
/// current `main` API rather than the published `from:` tag — which lags
/// unreleased Score/Generator features (e.g. `Part(clef:)`,
/// `ScoreEvent.performedDuration`). This is the pre-1.0-stable policy: the
/// template source and the dependency it pins both come from one checkout, so
/// they never drift.
///
/// Returns `nil` when the derived root no longer holds the Lyrebird
/// `Package.swift` (the binary was installed away from its source tree);
/// callers then fall back to the remote versioned dependency.
static var defaultLyrebirdCheckoutPath: String? {
lyrebirdCheckoutRoot(forSourceFile: #filePath)
}
/// Testable core of ``defaultLyrebirdCheckoutPath``. Given a source file at
/// `<root>/Sources/LyrebirdCLI/<file>.swift`, walks up three directory
/// levels to `<root>` and returns it iff `<root>/Package.swift` exists and
/// names Lyrebird. Returns `nil` otherwise. Split out so the happy- and
/// nil-paths can be unit-tested with synthetic paths (the computed property
/// is hard-wired to its own `#filePath`).
static func lyrebirdCheckoutRoot(forSourceFile sourceFile: String) -> String? {
let root: URL = URL(fileURLWithPath: sourceFile)
.deletingLastPathComponent() // strip <file>.swift → Sources/LyrebirdCLI/
.deletingLastPathComponent() // → Sources/
.deletingLastPathComponent() // → <root>/
let manifest: String = root.appendingPathComponent("Package.swift").path
guard FileManager.default.fileExists(atPath: manifest) else { return nil }
// Guard against pointing at an unrelated parent Package.swift.
guard let contents: String = try? String(contentsOfFile: manifest, encoding: .utf8),
contents.contains("Lyrebird") else { return nil }
return root.path
}
/// Scaffold a new Lyrebird project named `name` inside `parentDirectory`.
///
/// - Parameters:
@@ -102,10 +145,13 @@ public enum ProjectScaffolder {
/// - template: Starter template style (default `.basic`).
/// - parentDirectory: Directory in which to create the project folder.
/// Defaults to the current working directory.
/// - lyrebirdPath: Optional absolute path to a local Lyrebird checkout
/// to wire into the generated `Package.swift` as a `path:` dependency
/// (useful when developing against an unmerged Lyrebird branch).
/// `nil` → use the published GitHub package as the dependency.
/// - lyrebirdPath: Absolute path to a local Lyrebird checkout to wire into
/// the generated `Package.swift` as a `path:` dependency. `nil` → use
/// the published remote package. This is a faithful passthrough: the
/// `new` CLI command resolves `nil` to ``defaultLyrebirdCheckoutPath``
/// *before* calling this (see `LyrebirdCLI.runNew`), so default
/// scaffolds track current `main`; direct library callers get the
/// documented `nil` → remote behaviour.
/// - Throws: `ProjectScaffolder.Error` on name validation failure or file system errors.
public static func scaffold(
name: String,
@@ -252,7 +298,7 @@ public enum ProjectScaffolder {
case .auv3:
try writeAUv3Files(name: name, projectRoot: projectRoot,
lyrebirdPath: lyrebirdPath, fm: fm)
case .basic, .demo, .uiDemo, .nrt:
case .basic, .demo, .uiDemo, .nrt, .score:
// Unreachable — shipsXcodeProject filters these out at dispatch.
try? fm.removeItem(atPath: projectRoot)
throw Error.fileSystemError(
@@ -324,7 +370,7 @@ public enum ProjectScaffolder {
// the dep is local or remote.
let targetDeps: String
switch template {
case .basic, .demo, .nrt:
case .basic, .demo, .nrt, .score:
targetDeps = #""Lyrebird""#
case .uiDemo:
targetDeps = #""Lyrebird", .product(name: "LyrebirdUI", package: "Lyrebird")"#
@@ -382,6 +428,7 @@ public enum ProjectScaffolder {
case .demo: return mainSwiftDemo(name: name)
case .uiDemo: return mainSwiftUIDemo(name: name)
case .nrt: return mainSwiftNRT(name: name)
case .score: return mainSwiftScore(name: name)
case .macosUIXcode, .iosUI, .auv3:
// Xcode-bearing templates don't emit a `main.swift` under
// `Sources/<name>/`. Dispatch never reaches this function for
@@ -416,7 +463,7 @@ public enum ProjectScaffolder {
fatalError("Engine failed to start: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
RunLoop.main.run()
"""
}
@@ -464,7 +511,7 @@ public enum ProjectScaffolder {
fatalError("Engine.add failed: \\(error)")
}
print("\\(name) running — press Ctrl+C to stop")
print("\(name) running — press Ctrl+C to stop")
print("Update tone.freq or tone.amp from the REPL to change parameters.")
RunLoop.main.run()
"""
@@ -548,6 +595,170 @@ public enum ProjectScaffolder {
"""
}
// MARK: score
private static func mainSwiftScore(name: String) -> String {
"""
// \(name) — Score / MusicXML render
import Foundation
import LyrebirdSynth
// MARK: - ScoreVoice
/// One self-freeing voice per score event. The envelope's `freeNode`
/// done-action removes the synth when its note finishes, so scheduled
/// voices never accumulate during the offline render.
final class ScoreVoice: SynthesizerBase {
let freqHz: Double
let amp: Double
let durSeconds: Double
let pan: Double
init(freqHz: Double, amp: Double, durSeconds: Double, pan: Double = 0.0) {
self.freqHz = freqHz
self.amp = amp
self.durSeconds = durSeconds
self.pan = pan
super.init()
}
override func build() {
let attack = 0.01
let release = 0.06
let sustain = max(0.0, durSeconds - attack - release)
let envelope = Envelope(
levels: [0.0, 1.0, 0.8, 0.0],
durations: [attack, sustain, release],
curves: [-4.0, 0.0, -6.0]
)
let osc = OscSawtooth.Audio(freq: freqHz)
let env = EnvelopeGen.Control(envelope: envelope, doneAction: .freeNode)
output(bus: 0, source: Pan2(input: osc * env * amp, pan: pan))
}
}
// MARK: - Build the score
let bpm = 120.0
let secondsPerBeat = 60.0 / bpm
// Author music with the Score DSL: Note, Rest, Chord, Tuplet, dynamics,
// and articulations. Pitch spelling (letter + accidental) is preserved
// through MusicXML export. `Generate` and `PatternNotes` add algorithmic
// generation (see the "texture" part below).
//
// Further notation (see the Lyrebird ScoreSystem docs): Slur / Crescendo /
// Diminuendo spans, per-note `spanners:` (overlapping spans, glissandi /
// slides), per-note `display:` (NoteDisplay — notehead/size/hide stem or
// beam), `Section("…") { }` blocks with rehearsal marks, and a `pageLayout:`
// (PageLayout — page size, orientation, margins).
let score = Score(bpm: bpm, timeSignature: TimeSignature(4, 4)) {
Part("lead") {
// A crescendo hairpin over the opening arpeggio (notation-only).
Crescendo {
Note(.named(.c, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.e, 5), dur: .quarter, dyn: .mf, art: .staccato)
Note(.named(.g, 5), dur: .quarter, dyn: .f, art: .accent)
}
Rest(dur: .quarter)
Tuplet(3, inTimeOf: 2) {
Note(.named(.b, 5), dur: .quarter, dyn: .mp)
Note(.named(.a, 5), dur: .quarter, dyn: .mp)
Note(.named(.g, 5), dur: .quarter, dyn: .mp)
}
Chord([.named(.c, 5), .named(.e, 5), .named(.g, 5)], dur: .half, dyn: .f, art: .tenuto)
}
Part("bass", channel: 1, clef: .bass) {
Note(.named(.c, 3), dur: .whole, dyn: .mp)
Note(.named(.g, 2), dur: .half, dyn: .p)
Note(.named(.c, 3), dur: .half, dyn: .mp, art: .tenuto)
}
// Texture — algorithmic generation. `Generate` maps an index range
// through the builder; `PatternNotes` pulls from a `Pattern` source.
Part("texture", channel: 2) {
Generate(8) { i in
Note(midi: 72 + (i % 6) * 2, dur: .sixteenth, dyn: .pp, art: .staccato)
}
PatternNotes(count: 4, midi: Pattern.series(start: 60, step: 3, length: 4), dur: .eighth, dyn: .p)
}
}
// MARK: - Output location
// Write next to this project's source rather than the launch directory.
// `LyrebirdPaths.projectRoot()` walks up from this file to the folder
// containing Package.swift, so output lands in the project regardless of
// how the binary is launched (lyrebird run, swift run, or Xcode — whose
// working directory is DerivedData). Dev-time convenience; for a shipped
// app writing user data, use `LyrebirdPaths.documents` instead.
let outputDir = LyrebirdPaths.projectRoot() ?? LyrebirdPaths.currentWorkingDirectory
// MARK: - Export MusicXML
let xmlURL = outputDir.appendingPathComponent("score.musicxml")
do {
let xml = score.toMusicXMLString()
try xml.write(to: xmlURL, atomically: true, encoding: .utf8)
print("MusicXML written → \\(xmlURL.path)")
} catch {
fputs("MusicXML export failed: \\(error)\\n", stderr)
exit(1)
}
// Round-trip sanity check: parse the document back in and compare counts.
do {
let restored = try Score.fromMusicXML(data: score.toMusicXMLData())
print("Round-trip events: \\(score.allEvents.count) → \\(restored.allEvents.count)")
} catch {
fputs("MusicXML round-trip failed: \\(error)\\n", stderr)
}
// MARK: - Render the score offline
let tailSeconds = 1.5
let renderDuration = score.totalBeats * secondsPerBeat + tailSeconds
let outputURL = outputDir.appendingPathComponent("score.caf")
let engine = SynthesisEngine(
blockSize: \(scaffoldDefaultBlockSize),
sampleRate: \(scaffoldDefaultSampleRate),
numOutputChannels: \(scaffoldDefaultOutputChannels),
numInputChannels: 0,
driver: NRTDriver(outputURL: outputURL, duration: renderDuration)
)
// Schedule one voice per sounding event BEFORE start() — NRTDriver
// renders synchronously inside start().
var scheduled = 0
for event in score.allEvents {
guard !event.isRest else { continue }
guard let freqHz = event.pitch.frequency else { continue }
let pan = event.channel == 0 ? -0.4 : 0.5
let voice = ScoreVoice(
freqHz: freqHz,
amp: event.velocity * 0.35,
durSeconds: event.performedDuration * secondsPerBeat,
pan: pan
)
do {
try engine.schedule(voice, after: event.beat * secondsPerBeat)
scheduled += 1
} catch {
fputs("engine.schedule failed: \\(error)\\n", stderr)
}
}
print("Scheduled \\(scheduled) voices.")
do {
try engine.start()
print("Rendered \\(renderDuration)s → \\(outputURL.path)")
} catch {
fputs("Render failed: \\(error)\\n", stderr)
exit(1)
}
"""
}
// MARK: - ui-demo additional files
/// `AppDelegate.swift` content for a ui-demo project.
@@ -563,6 +774,7 @@ public enum ProjectScaffolder {
let synth: \(name)Synth
var window: LyrebirdWindow?
@MainActor
init(engine: SynthesisEngine) {
self.engine = engine
self.synth = \(name)Synth()
@@ -629,17 +841,21 @@ public enum ProjectScaffolder {
// MARK: - Xcode workspace
/// `contents.xcworkspacedata` body. Single `FileRef` to `Package.swift`
/// so opening the workspace in Xcode loads the SPM package with full
/// project navigation, debugging, and SwiftUI previews. Identical for
/// every template — the file lives at `<name>.xcworkspace/contents.xcworkspacedata`.
/// `contents.xcworkspacedata` body. The single `FileRef` points at the
/// workspace's enclosing directory (`group:.`) — the package root that
/// holds `Package.swift` — so Xcode recognises it as a Swift package and
/// opens the full `Sources/` / `Tests/` tree with a runnable scheme.
/// (Referencing the `Package.swift` *file* instead loads a single loose
/// document with no schemes — `xcodebuild -list` reports "no schemes".)
/// Identical for every SPM template — the file lives at
/// `<name>.xcworkspace/contents.xcworkspacedata`.
public static func workspaceContents() -> String {
"""
<?xml version="1.0" encoding="UTF-8"?>
<Workspace
version = "1.0">
<FileRef
location = "group:Package.swift">
location = "group:.">
</FileRef>
</Workspace>
"""

Some files were not shown because too many files have changed in this diff Show More