Files
josh 560724d116 v1.3.0 release: graceful-release fix, quickstart template + demo, documentation accuracy pass
- Fixed: SynthesizerBase subclasses' release/free now dispatch correctly (gated
  synths were hard-freed instead of released).
- New: quickstart project template + LyrebirdQuickstartDemo.
- Docs: every example typechecked or provably illustrative (426->542); ~20
  wrong-API examples fixed; root docs brought under the compile guard.
- Fixed: NRT/Score demo Package.swift build from terminal again.

See RELEASES.md for details.
2026-07-17 14:05:01 -07:00

341 lines
14 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# Pitch / Scale Theory Toolkit
A spelling-aware music-theory layer: intervals, scales and modes, pitch collections (melodic cells, atonal sets, 12-tone rows), and diatonic-vs-chromatic transposition — all preserving **correct enharmonic spelling**. Transposing `A` up an augmented second gives `B♯`, never `C♮`.
It is a pure, language-side value layer — no RT thread, no engine, no Generators. Everything is built on the existing `Letter` / `Accidental` / `NoteName` / `Pitch` foundation and outputs `NoteName` / `Pitch`, so results drop straight into the **Score DSL** for notation/MusicXML, or convert to **Hz and seconds** to drive synthesis parameters.
Files live under `Sources/Lyrebird/Score/Theory/`. All types are `Sendable` + `Hashable`.
```swift
import LyrebirdSynth
```
---
## Core types
| Type | Role |
|---|---|
| `Interval` | Spelled diatonic interval: `number` (1 = unison … 8 = octave, compounds allowed) + `IntervalQuality`. |
| `IntervalQuality` | `.diminished(n)` / `.minor` / `.perfect` / `.major` / `.augmented(n)`. |
| `IntervalDirection` | `.up` / `.down`. |
| `Scale` | A tonic + ordered spelled `degrees`. Modes, symmetric scales, pentatonics, or arbitrary pitch sets. |
| `ScaleDegree` | A located degree: `index` + chromatic `alteration` (semitones off the degree). |
| `PitchCollection` | An ordered list of `Pitch` (cell / set / row) + optional `referenceScale`. |
Most operations **throw** (`IntervalError`, `ScaleError`, `ToneRowError`). Intervals are 12-TET; quarter-tone accidentals are rejected (`IntervalError.quarterToneUnsupported`). A correct spelling that would need an accidental beyond double-flat / double-sharp throws `IntervalError.unrepresentableSpelling`.
---
## Intervals
A static catalogue covers the common simple intervals; build others with `init(number:quality:)`.
```swift
Interval.majorThird.semitones // 4
Interval.augmentedSecond.semitones // 3 (same SOUND as a minor third…)
Interval.minorThird.semitones // 3 (…but a different SPELLING)
Interval.majorThird.diatonicSteps // 2 (letter distance)
let majorNinth = try Interval(number: 9, quality: .major) // compound
majorNinth.semitones // 14
```
Validity is enforced: perfect-class numbers (unison / 4th / 5th / octave) reject `.major` / `.minor`; imperfect-class numbers (2nd / 3rd / 6th / 7th) reject `.perfect`.
```swift
try Interval(number: 5, quality: .major) // throws .qualityNumberMismatch
```
Analyse the spelled interval between two names or pitches:
```swift
try Interval.between(.c, .e) // major third
try Interval.between(.a, .bSharp) // augmented second (not minor third)
// Directed, possibly-compound, between two named pitches:
let (interval, dir) = try Interval.directed(from: .named(.c, 4), to: .named(.e, 5))
// interval = major tenth, dir = .up
```
### Transposition
`transposed(by:_:)` advances the letter by the interval's `diatonicSteps`, then picks the accidental that makes the chromatic distance equal `interval.semitones` — so the spelling is always correct.
```swift
try NoteName.a.transposed(by: .augmentedSecond) // B♯ (NOT C)
try NoteName.e.transposed(by: .majorThird) // G♯
try NoteName.fSharp.transposed(by: .minorThird, .down) // D♯
// Pitch keeps spelling AND tracks the octave:
try Pitch.named(.b, 4).transposed(by: .perfectFourth) // .named(.e, 5) (letter wraps past C)
try Pitch.named(.c, 4).transposed(by: majorNinth) // .named(.d, 5)
```
`.midi` / `.freq` pitches shift numerically (spelling is lost — documented on the method).
### Folding into a register
`Pitch.mapIntoRange(low:high:)` shifts a pitch into the inclusive register `[low, high]` by whole octaves, taking the fewest octaves. The pitch class is preserved, and for `.named` pitches **spelling survives** — a `B♭` maps to a `B♭`, never an enharmonic `A♯` (unlike the scalar `Double`/`Int` `mapIntoRange`, which only knows MIDI numbers). There is no `modulo:` parameter: the fold is octave-only by design, which is exactly what keeps the pitch class and spelling intact.
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 5)) // .named(.c, 5)
Pitch.named(.bFlat, 2).mapIntoRange(low: .named(.c, 4), high: .named(.c, 5)) // .named(.bFlat, 4)
```
When the range is wider than an octave the fewest-octaves rule returns the first representative reached from `self`:
```swift
Pitch.named(.c, 3).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 5) — folds up
Pitch.named(.c, 7).mapIntoRange(low: .named(.a, 4), high: .named(.a, 6)) // .named(.c, 6) — folds down
```
When no octave lands inside the range (the bounds span less than an octave and this pitch class has no member there), or when an endpoint / the pitch is a rest or out-of-MIDI-range, **the original pitch is returned unchanged**. `.midi` / `.freq` pitches fold numerically and keep their case (`.freq` keeps sub-semitone cents).
---
## Scales and modes
Factories build a scale from a tonic + interval pattern. Seven-note diatonic modes use seven distinct letters, so spelling is guaranteed.
```swift
let dMajor = try Scale.major(.d)
dMajor.degrees // [D, E, F♯, G, A, B, C♯] ← one letter per degree
try Scale.dorian(.eFlat).degrees // [E♭, F, G♭, A♭, B♭, C, D♭]
try Scale.harmonicMinor(.a).degrees // [A, B, C, D, E, F, G♯]
```
Symmetric scales have more notes than letters; each factory fixes a canonical spelling:
```swift
try Scale.wholeTone(.c).degrees // [C, D, E, F♯, G♯, A♯]
try Scale.octatonicHalfWhole(.c).degrees // [C, D♭, E♭, E, F♯, G, A, B♭]
try Scale.majorPentatonic(.c).degrees // [C, D, E, G, A]
try Scale.blues(.c).degrees // [C, E♭, F, G♭, G, B♭]
```
Available: `major`/`ionian`, `dorian`, `phrygian`, `lydian`, `mixolydian`, `aeolian`/`naturalMinor`, `locrian`, `harmonicMinor`, `melodicMinor`, `wholeTone`, `chromatic`, `octatonicHalfWhole`, `octatonicWholeHalf`, `augmentedScale`, `majorPentatonic`, `minorPentatonic`, `blues`. Or build from explicit degrees / intervals / named pitches:
```swift
let custom = try Scale(tonic: .c, intervals: [.unison, .majorSecond, .minorThird])
let set = try Scale(tonic: .c, pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
```
### Queries
```swift
let cMajor = try Scale.major(.c)
cMajor.contains(.fSharp) // false (pitch-class membership)
cMajor.degree(of: .g) // ScaleDegree(index: 4, alteration: 0)
cMajor.degree(of: .fSharp) // ScaleDegree(index: 3, alteration: +1) ← raised 4th
cMajor.noteName(atDegree: 9) // E (wraps mod 7)
cMajor.pitch(atDegree: 2, octave: 4) // .named(.e, 4)
```
`degree(of:)` resolves exact spelling → enharmonic pitch-class → same letter → nearest pitch-class, carrying any chromatic `alteration` so non-scale pitches survive the round trip.
---
## Pitch collections
Order matters — a `PitchCollection` is a melodic cell, an atonal set, or a 12-tone row.
```swift
let cell = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
cell.retrograde.pitches // G E C
try cell.transposedChromatic(by: .majorThird).pitches // E G♯ B (every pitch +M3)
try cell.inverted(around: .named(.c, 4)).pitches // C A♭3 F3 (mirror, spelled)
cell.octaveReduced.pitches // fold to one octave
```
### 12-tone rows
When a collection is twelve named pitches across all twelve pitch-classes, the row's own spelling defines a pitch-class → note-name map, so **every derived form stays spelling-consistent** with the prime row.
```swift
let row = PitchCollection(pitches: [
.named(.c, 4), .named(.dFlat, 4), .named(.d, 4), .named(.eFlat, 4),
.named(.e, 4), .named(.f, 4), .named(.gFlat, 4), .named(.g, 4),
.named(.aFlat, 4), .named(.a, 4), .named(.bFlat, 4), .named(.b, 4),
])
row.isToneRow // true
try row.toneRowInversion() // I0
try row.toneRowRetrograde() // R0
try row.toneRowTransposed(3) // T3 (pc + 3, spelled via the row's map → G♭ stays G♭)
try row.toneRowTransposedInversion(5) // T5I
let matrix = try row.toneRowMatrix() // [[NoteName]] 12×12 (top = prime, left = inversion)
```
---
## Diatonic vs. chromatic transposition
This is the distinction the toolkit exists to get right.
- **Chromatic** — `PitchCollection.transposedChromatic(by:_:)` moves every pitch by the *same spelled interval*.
- **Diatonic (modal)** — `Scale.transposeDiatonic(_:byDegrees:)` moves every pitch by the *same number of scale steps*, staying in the scale.
```swift
let cMajor = try Scale.major(.c)
let line = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.e, 4)])
try cMajor.transposeDiatonic(line, byDegrees: 2).pitches // E F G (in-scale thirds)
try line.transposedChromatic(by: .majorThird).pitches // E F♯ G♯ (three equal M3s)
```
### Scale-to-scale mapping
`PitchCollection.mapped(from:to:)` re-assigns each pitch by degree from one scale to another, carrying alteration and octave register.
```swift
let triad = PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.d)).pitches // D F♯ A
try triad.mapped(from: try Scale.major(.c), to: try Scale.major(.eFlat)).pitches // E♭ G B♭
try triad.mapped(from: try Scale.major(.c), to: try Scale.aeolian(.c)).pitches // C E♭ G (major→minor triad)
```
Degree-count mismatch (e.g. pentatonic → heptatonic) maps by index with wrap.
---
## Notation — feeding the Score / MusicXML pipeline
Theory output is `NoteName` / `Pitch`, which the **Score DSL** consumes directly. Build a transposed phrase, then export to MusicXML — the spellings survive the round trip (sharps stay sharp, `B♯` does not collapse to `C`).
```swift
// A phrase, transposed up a major third with correct spelling.
let phrase = PitchCollection(pitches: [.named(.c, 4), .named(.d, 4), .named(.a, 4)])
let up = try phrase.transposedChromatic(by: .majorThird) // E F♯ C♯
let score = Score(bpm: 120) {
Part("theory") {
for pitch in up.pitches {
Note(pitch, dur: .quarter) // Note(_ pitch: Pitch, dur:) takes .named directly
}
}
}
let xml = score.toMusicXMLString()
// E → <step>E</step>, F♯ → <step>F</step><alter>1</alter>, C♯ → <step>C</step><alter>1</alter>
// Round-trips losslessly:
let decoded = try Score.fromMusicXML(data: Data(xml.utf8))
```
Build a whole scale or a chord the same way:
```swift
let scale = try Scale.dorian(.d)
let part = Part("dorian") {
for i in 0..<scale.count {
Note(scale.pitch(atDegree: i, octave: 4), dur: .eighth)
}
}
let chordTriad = try Scale.major(.eFlat)
Chord([ // Chord(_ pitches: [Pitch], dur:)
chordTriad.pitch(atDegree: 0, octave: 4),
chordTriad.pitch(atDegree: 2, octave: 4),
chordTriad.pitch(atDegree: 4, octave: 4),
], dur: .half)
```
See `ScoreSystem` for the full notation DSL, and `docs/stdlib/` neighbours for generators.
---
## Synthesis — Hz and seconds from theory values
For audio, convert `Pitch` to frequency and `NoteDuration` to seconds, then feed Generator parameters.
**Pitch → frequency.** `Pitch.frequency` returns Hz (`Double?`, `nil` for rests / out-of-range). Quarter-tones and `.freq` pitches resolve to real Hz.
```swift
Pitch.named(.a, 4).frequency // 440.0
Pitch.named(.cQuarterSharp, 4).frequency // ≈ 269.29 Hz (C4 × 2^(0.5/12))
Pitch.midi(60).frequency // 261.63 Hz
// Map a whole scale to oscillator frequencies:
let freqs = try Scale.major(.a)
.degrees.enumerated()
.compactMap { Pitch.named($0.element, 4).frequency }
```
(`midiToHz(_:)` / `hzToMidi(_:)` in `LyrebirdMusicMath` cover the raw numeric conversions.)
**Duration → seconds.** `NoteDuration.beats` is in quarter-note beats (quarter = 1). Multiply by the seconds-per-beat for your tempo:
```swift
let bpm = 120.0
let secondsPerBeat = 60.0 / bpm
let eighthSeconds = NoteDuration.eighth.beats * secondsPerBeat // 0.5 × 0.5 = 0.25 s
let dottedQuarter = NoteDuration.quarter.dotted.beats * secondsPerBeat // 0.75 s
```
**Drive a Synthesizer.** Pass the frequency into a Generator graph:
```swift
final class Tone: SynthesizerBase {
let freq: Double
let amp: Double
init(freq: Double, amp: Double = 0.2) {
self.freq = freq
self.amp = amp
super.init()
}
override func build() {
let env = EnvelopeGen.Control(
envelope: Envelope(levels: [0, 1, 0], durations: [0.01, 0.4], curves: [2, -3]),
doneAction: .freeNode // engine removes this synth when the envelope ends
)
let sig = OscSin.Audio(freq: freq) * env * amp
output(bus: 0, source: Pan2(input: sig, pan: 0))
}
}
let gSharp4 = try Pitch.named(.e, 4).transposed(by: .majorThird) // .named(.gSharp, 4)
if let hz = gSharp4.frequency {
try engine.add(Tone(freq: hz)) // G♯4 ≈ 415.30 Hz
}
```
**Sequence a collection over time** with a routine — convert each pitch to Hz, hold each for a duration:
```swift
let cell = try PitchCollection(pitches: [.named(.c, 4), .named(.e, 4), .named(.g, 4)])
.transposedChromatic(by: .perfectFifth) // G B D
let routine = LyrebirdRoutine { ctx in
ctx.tempo = 120.0
for pitch in cell.pitches {
guard let hz = pitch.frequency else { continue }
ctx.add(Tone(freq: hz))
try ctx.wait(beats: NoteDuration.quarter.beats) // 0.5 s at 120 BPM
}
}
routine.start(engine: engine)
```
Because the toolkit preserves spelling end-to-end, the **same theory objects** drive both the engraved score (correct accidentals in MusicXML) and the sounding synthesis (exact Hz) — no separate pitch model for notation vs. audio.
---
## Error handling
Operations throw rather than silently mis-spell:
| Error | When |
|---|---|
| `IntervalError.qualityNumberMismatch` | `.major` on a 5th, `.perfect` on a 3rd, etc. |
| `IntervalError.unrepresentableSpelling` | correct spelling needs an accidental beyond 𝄫 / 𝄪. |
| `IntervalError.quarterToneUnsupported` | transposing across a quarter-tone accidental (intervals are 12-TET). |
| `ScaleError.tonicMismatch` / `.nonNamedPitch` | bad `Scale` construction; diatonic / mapping on a `.midi` / `.freq` pitch. |
| `ToneRowError.notTwelveToneRow` | row operation on a collection that is not 12 distinct named pitch-classes. |