- 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.
81 KiB
Score System
@Metadata { @PageKind(article) }
Author musical scores in Swift. Notes, rests, chords, dynamics, articulations, and tuplets — all expressed in a result-builder DSL with exact rational tuplet math.
Overview
Lyrebird's score system gives you a language-side musical-event representation distinct from MIDI files: you write Swift, you get a flat list of ScoreEvent instances with absolute beat positions. Tuplet ratios compose under nesting via Fraction arithmetic; only the final ScoreEvent.beat and ScoreEvent.duration are emitted as Double. No floating-point drift across nested Tuplet(3, inTimeOf: 2) layers.
ScoreEvent.duration is the notated duration (pre-articulation). To get the sounding (performed) duration — i.e. the actual note length for audio synthesis, MIDI note-off, or SMF — call event.performedDuration, which applies articulation.durationScale. Engraving and MusicXML use duration; audio and MIDI use performedDuration.
The score itself is purely declarative. ScorePlayer walks the flat event list against a LyrebirdClock on a LyrebirdRoutine thread (mirroring MIDIFilePlayer), and SMF / MusicXML bridges let you round-trip between formats.
Authoring
let score = Score(bpm: 120) {
Part("lead") {
Note(.c, 4, dur: .quarter, dyn: .mf)
Note(.e, 4, dur: .eighth, dyn: .mf, art: .staccato)
Rest(dur: .eighth)
Tuplet(3, inTimeOf: 2) {
Note(.g, 4, dur: .quarter)
Note(.a, 4, dur: .quarter)
Note(.b, 4, dur: .quarter)
}
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half, dyn: .f)
}
// Explicit bass clef; default .auto would also infer .bass from these pitches.
Part("bass", channel: 1, clef: .bass) {
Note(.c, 2, dur: .whole, dyn: .mp)
}
}
let leadEvents = score.parts[0].flatten()
for event in leadEvents {
print("[\(event.beat)] \(event.pitch) dur=\(event.duration) vel=\(event.velocity)")
}
Algorithmic generation
The builder supports native Swift control flow directly — for loops collect via
the builder's buildArray, if/else via buildOptional/buildEither.
.forEach will not work: its closure body produces Void, so the notes are
discarded. Reach for a for loop:
Part("lead") {
for pitch in [Pitch.named(.c, 5), .named(.e, 5), .named(.g, 5)] {
Note(pitch, dur: .quarter, art: .staccato)
}
}
Two helpers go further when the run is reusable, index-driven, or fed by a
Pattern. Both return [ScoreElement] that drops straight into a
Part/Tuplet/Voice body:
Generate(_:_:)maps each index0 ..< countthrough a builder closure. The body is a full builder block, so an index may emit zero, one, or many elements (loops,if, chords, nestedTuplet/Voice).PatternNotes(count:pitches:dur:durations:dyn:dynamics:art:)and itsmidi:overload pull pitches — and optionally per-note rhythm and dynamic — fromPatternvalue sources. The pitch pattern drives length: if it exhausts beforecount, generation stops early. Aux patterns fall back to the scalardur/dynwhen omitted or exhausted. Themidi:overload rounds and clamps eachDoubleto MIDI[0, 127].
Part("texture") {
// 1000 sixteenths walking a whole-tone fragment by index.
Generate(1000) { i in
Note(midi: 48 + (i % 12), dur: .sixteenth, dyn: .mp)
}
// A seeded Brownian MIDI walk with a repeating rhythm cell.
PatternNotes(
count: 12,
midi: Pattern.brownian(low: 60, high: 84, step: 4, length: 12, seed: 42),
durations: Pattern.sequence([.eighth, .eighth, .quarter]),
dyn: .p
)
}
For one-off generation, a plain function returning [ScoreElement] (or a bare
for loop) is just as valid — these helpers are sugar over that pattern, not a
new builder type.
Core types
| Type | Role |
|---|---|
Score |
Top-level container with bpm, timeSignature, parts |
ScorePart |
One named timeline of elements; supports per-part MIDI channel hint and Clef |
ScoreElement |
Unflattened tree node — note / rest / chord / tuplet / voice |
ScoreEvent |
Flat output of ScorePart/flatten() — absolute beat + duration + velocity |
Pitch |
.midi(Int) / .freq(Double) / .named(NoteName, Int) / .rest |
Letter |
Diatonic letter C, D, E, F, G, A, B (determines octave of containing pitch) |
Accidental |
Nine-step microtonal grid: doubleFlat, threeQuarterFlat, flat, quarterFlat, natural, quarterSharp, sharp, threeQuarterSharp, doubleSharp |
NoteName |
(Letter, Accidental) struct preserving spelling. C♭ and B produce the same MIDI but are distinct values |
NoteDuration |
.fraction(Fraction) (preferred) or .beats(Double); named conveniences from .doubleWhole (breve, 8 beats) down through .whole, .half, .quarter, .eighth, … .sixtyFourth. British names are aliases for the same values: .breve, .semibreve, .minim, .crotchet, .quaver, .semiquaver, .demisemiquaver, .hemidemisemiquaver. Dot it with the .dotted / .doubleDotted properties — .quarter.dotted (×3/2), .half.doubleDotted (×7/4) — or the .dotted(_:) / .doubleDotted(_:) static funcs |
Dynamic |
.ppp–.fff and .raw(Double); .velocity returns normalized [0, 1] |
Articulation |
.normal, .staccato, .staccatissimo, .legato, .tenuto, .accent, .marcato — the single art: value; affects played duration and velocity and emits its glyph |
NotationMark |
Notation-only marks: list on a note/chord — extra articulation glyphs, string/technique symbols (.leftHandPizzicato, .snapPizzicato, .upBow, .downBow, .harmonic, .openString), and .fermata(`` ``FermataShape`` ``). Emits <technical> / <articulations> / <fermata>; does not affect playback. Emit-only (not parsed back) |
FermataShape |
.normal, .angled, .square (long), .doubleSquare (very long / longa), .doubleAngled, .doubleDot, .halfCurve, .curlew |
Fraction |
Reduced Int64 rational; backbone of exact tuplet arithmetic |
Clef |
Per-part MusicXML clef: .treble, .bass, .alto, .tenor, .treble8vb, .percussion, .auto |
KeySignature |
Score-level key signature: fifths (circle-of-fifths integer) + KeySignature/Mode (.major / .minor). Also available as a per-part override on ScorePart |
Transpose |
Per-part transposing-instrument spec: chromatic + diatonic + octaveChange (written→sounding). Notation-only; named conveniences .bFlat, .a, .eFlat, .fHorn |
RepeatStructure |
Score-level repeat barline and volta-ending description (measure-indexed, notation-only) |
Ending |
One volta bracket: number (1, 2, …), startMeasure, stopMeasure (1-based, inclusive) |
TempoChange |
Mid-piece tempo change: measure (1-based) + bpm (> 0); notation-only |
Tempo Changes
TempoChange describes where a new tempo takes effect in the score. It is a score-level, measure-indexed, notation-only annotation:
- Score-level: one
[TempoChange]array applies to all parts uniformly. Every part receives the same tempo<direction>element at the matching measure. - Measure-indexed: each change is anchored to a 1-based measure number.
- Notation-only:
ScorePart/flatten()is unaffected.ScorePlayerand NRT rendering use the single baseScore/bpmthroughout. Segmented beat-to-seconds tempo-map playback is planned for a future phase.
let score = Score(
bpm: 120,
tempoChanges: [
TempoChange(measure: 5, bpm: 160), // allegro at bar 5
TempoChange(measure: 9, bpm: 72) // adagio at bar 9
]
) {
Part("melody") { Note(.c, 4, dur: .quarter) }
}
The tempoChanges: parameter defaults to [] so existing call sites are unchanged.
Measure-1 rule
Score/bpm always supplies the measure-1 tempo. A TempoChange targeting measure 1 is superseded by bpm during encoding (the encoder writes bpm for measure 1 and ignores any TempoChange at that measure). Use tempoChanges for measures ≥ 2.
Deduplication
When two TempoChange values target the same measure, first-in-array order wins during encoding. The parser applies the same rule (first-in-document wins per measure).
TempoChange properties
| Property | Type | Description |
|---|---|---|
measure |
Int |
1-based measure number where the new tempo takes effect. Must be ≥ 1. |
bpm |
Double |
New tempo in quarter-note beats per minute. Must be > 0. |
MusicXML encoding
Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:) emits a tempo <direction placement="above"> block at the start of each matching measure, in every part. The format is identical to the measure-1 base-tempo direction:
<direction placement="above">
<direction-type>
<metronome>
<beat-unit>quarter</beat-unit>
<per-minute>160</per-minute>
</metronome>
</direction-type>
<sound tempo="160"/>
</direction>
When tempoChanges is empty, zero extra tempo directions are emitted — output is byte-identical to a score without any tempo changes.
MusicXML parsing
Score/fromMusicXML(data:) reads tempo directions from the first part (all parts share identical tempo directions). A <direction> block in measure 1 sets Score/bpm; blocks in measures ≥ 2 produce TempoChange entries in Score/tempoChanges. <per-minute> is preferred over <sound tempo="X"/> when both appear in the same block. The result is sorted ascending by measure number and deduplicated (first-in-document wins per measure).
Notation-only limitation
Playback does not realize tempo changes. ScorePlayer fires note-on events at beat times computed from the single base Score/bpm. Implementing a tempo map (segmented beat-to-seconds conversion respecting each TempoChange interval) is planned for a future phase.
Repeats and Endings
RepeatStructure describes where forward/backward repeat barlines and volta ending brackets (1st ending, 2nd ending, …) appear in the score. It is a score-level, measure-indexed, notation-only annotation:
- Score-level: one
RepeatStructureapplies to all parts uniformly. Every part receives the same<barline>elements at the same measure numbers in MusicXML. - Measure-indexed: forward repeats, backward repeats, and ending brackets are specified by 1-based measure number.
- Notation-only:
ScorePart/flatten()is unaffected. Playback does not unfold repeats and does not duplicate events in theScoreEventlist — that is future work.
let score = Score(
bpm: 120,
timeSignature: TimeSignature(4, 4),
repeats: RepeatStructure(
forwardRepeatMeasures: [1], // |: at the left edge of bar 1
backwardRepeatMeasures: [4], // :| at the right edge of bar 4
endings: [
Ending(number: 1, startMeasure: 3, stopMeasure: 3), // 1st ending
Ending(number: 2, startMeasure: 4, stopMeasure: 4) // 2nd ending
]
)
) {
Part("melody") { Note(.c, 4, dur: .quarter) }
}
The repeats: parameter defaults to RepeatStructure/none (empty — zero <barline> elements) so existing call sites that omit it are unchanged.
RepeatStructure properties
| Property | Type | Description |
|---|---|---|
forwardRepeatMeasures |
Set<Int> |
1-based measure numbers whose left barline is a forward repeat (` |
backwardRepeatMeasures |
Set<Int> |
1-based measure numbers whose right barline is a backward repeat (`: |
endings |
[Ending] |
Volta brackets |
isEmpty |
Bool |
true when all sets/arrays are empty (the .none default) |
Ending properties
| Property | Type | Description |
|---|---|---|
number |
Int |
Volta number (1 = 1st ending, 2 = 2nd ending, …). Must be ≥ 1. |
startMeasure |
Int |
1-based measure number where the bracket begins (inclusive). Must be ≥ 1. |
stopMeasure |
Int |
1-based measure number where the bracket ends (inclusive). Must be ≥ startMeasure. |
MusicXML barline encoding
Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:) emits <barline> elements inside each matching <measure> block, in every part. Child element order follows the MusicXML 4.0 DTD (<bar-style>, <ending>, <repeat>):
Left barline (forward repeat and/or ending start) — emitted after <attributes> and the tempo direction, before the first note/rest:
<barline location="left">
<bar-style>heavy-light</bar-style> <!-- only when forward repeat -->
<ending number="1" type="start"/> <!-- only when an ending starts here -->
<repeat direction="forward"/> <!-- only when forward repeat -->
</barline>
An ending-only left barline (no forward repeat) omits <bar-style> and <repeat>. A forward-repeat-only left barline omits <ending>.
Right barline (backward repeat and/or ending stop) — emitted immediately before </measure>:
<barline location="right">
<bar-style>light-heavy</bar-style> <!-- only when backward repeat -->
<ending number="1" type="stop"/> <!-- only when an ending stops here -->
<repeat direction="backward"/> <!-- only when backward repeat -->
</barline>
When repeats.isEmpty is true, zero <barline> elements are emitted — output is byte-identical to a score without any repeat structure.
Multi-voice parts: the left barline is emitted once at the very start of the measure (before voice 1), the right barline once at the very end (after the last voice). Barlines are NOT duplicated per voice.
MusicXML barline parsing
Score/fromMusicXML(data:) reads <barline> elements from the first part (all parts share identical barlines). Accumulation:
<repeat direction="forward"/>inside a<barline location="left">→ adds the containing measure number toforwardRepeatMeasures.<repeat direction="backward"/>inside a<barline location="right">→ adds tobackwardRepeatMeasures.<ending number="N" type="start"/>→ records the pending start measure for volta N.<ending number="N" type="stop|discontinue"/>→ pairs with the pending start to form anEndingand appends it toendings.
Documents without <barline> elements produce Score/repeats == RepeatStructure/none.
Notation-only limitation
Playback does not unfold repeats. ScorePart/flatten() returns events in document order without duplicating the repeated sections. Implementing playback unfolding (expanding the flat event list for repeated passages) is planned for a future phase.
Meter and time signatures
A TimeSignature is a numerator/denominator plus an explicit beat grouping —
a partition of the numerator into felt beats, in denominator-note units. Simple,
compound, and complex/additive meters are all just groupings, so there is no
special-casing:
- Simple
4/4→[1, 1, 1, 1](four quarter beats). - Compound
6/8→[3, 3](two dotted-quarter beats). Auto-inferred when the denominator is8/16, the numerator is a multiple of three, and> 3. - Slow
6/8felt as six eighths →TimeSignature(6, 8, grouping: [1, 1, 1, 1, 1, 1]). - Additive
3+3+2over eighths →TimeSignature(8, 8, grouping: [3, 3, 2]).
beat everywhere in the meter / positioning layer means the felt (conducted)
beat defined by the grouping — consistent across meters (beat 1 is always the
downbeat). The finer denominator-note unit is the division. (This is distinct
from the absolute-timeline "beat" in ScoreEvent/beat / bpm, which is always
one quarter note — the machine unit that musical positions resolve down to.)
A MeterMap is a segmented map of (startBar, TimeSignature) plus an optional
MeterMap/anacrusis (pickup length in quarter beats). It governs barlines for a
whole score (Score/meterMap) or, polymetrically, a single part
(ScorePart/meterMap).
let score = Score(
meterMap: MeterMap(segments: [
MeterMap.Segment(startBar: 1, .fourFour),
MeterMap.Segment(startBar: 5, .threeFour), // mid-piece change at bar 5
], anacrusis: Fraction(1, 1)) // one-quarter pickup
) {
Part("lead") { Note(.c, 4, dur: .quarter) }
}
The MusicXML encoder emits a fresh <time> wherever the signature changes, uses
per-measure capacity for barline splitting, and renders an anacrusis as
<measure number="0" implicit="yes"> (full bars stay 1-based). Constant-meter,
no-anacrusis output is unchanged. The parser reads every <time> and the implicit
pickup back into a MeterMap on round-trip — with one caveat: standard MusicXML
<time> carries no beat grouping, so a re-parsed signature keeps its
numerator/denominator but re-infers the default grouping (an authored slow-6/8
[1,1,1,1,1,1] returns as compound [3, 3]).
Polymeter
Give a ScorePart its own ScorePart/meterMap to run it in a different meter
from the rest of the score. Each part is encoded independently in score-partwise,
so parts can have different bar groupings — and different bar counts — at the same
time. A Part(_:meterMap:) override is all-or-nothing: a part either inherits
the score map (nil, the default) or supplies a complete replacement.
let score = Score {
Part("piano") { // inherits score 4/4
for _ in 0..<12 { Note(.c, 5, dur: .quarter) } // 3 bars
}
Part("perc", meterMap: MeterMap(.threeFour)) { // its own 3/4
for _ in 0..<12 { Note(.c, 4, dur: .quarter) } // 4 bars, same total length
}
}
Caveats:
- Score-level
Score/repeats,Score/tempoChanges, andScore/keySignatureare measure-indexed, so they align by measure number across parts, not by absolute beat. Under polymeter, "measure 5" is a different absolute beat in each part — use score-level measure-numbered annotations with care when bar lengths differ. - Round-trip reads meter score-globally (from the first part), so per-part
meter maps do not survive
Score/fromMusicXML(data:). Polymeter is export-faithful but not round-trip-faithful.
Beat timelines
To place notes at explicit beat positions and auto-fill the rests, use
ScoreTimeline with absolute quarter beats or musician-friendly BeatPosition
values (.quarters, .beat, .bar(_:beat:), .bar(_:division:)) resolved
against a MeterMap. Overlaps .trap (throw) or .truncatePrevious; multiple
voices come from fillVoices (explicit) or fillAutoVoiced (automatic
distribution). See ScoreTimeline for the full surface.
Key Signature
KeySignature expresses a Western tonal key as a circle-of-fifths position and mode. It is a score-level property: all parts share the same key signature in the measure-1 <attributes> block.
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4), keySignature: .gMajor) {
Part("melody") { Note(.g, 4, dur: .quarter) }
Part("bass", channel: 1, clef: .bass) { Note(.g, 2, dur: .whole) }
}
The keySignature: parameter defaults to KeySignature/cMajor (C major, fifths = 0) so existing call sites that omit it are unchanged.
fifths convention
fifths |
Major key | Minor key |
|---|---|---|
| 0 | C major | A minor |
| +1 | G major | E minor |
| +2 | D major | B minor |
| +3 | A major | F♯ minor |
| +4 | E major | C♯ minor |
| +5 | B major | G♯ minor |
| +6 | F♯ major | D♯ minor |
| +7 | C♯ major | A♯ minor |
| -1 | F major | D minor |
| -2 | B♭ major | G minor |
| -3 | E♭ major | C minor |
| -4 | A♭ major | F minor |
| -5 | D♭ major | B♭ minor |
| -6 | G♭ major | E♭ minor |
| -7 | C♭ major | A♭ minor |
Named static-let constants cover every key in the table:
.cMajor, .gMajor, .dMajor, .aMajor, .eMajor, .bMajor, .fSharpMajor,
.cSharpMajor, .fMajor, .bFlatMajor, .eFlatMajor, .aFlatMajor, .dFlatMajor,
.gFlatMajor, .cFlatMajor; and .aMinor, .eMinor, .bMinor, .fSharpMinor,
.cSharpMinor, .gSharpMinor, .dSharpMinor, .aSharpMinor, .dMinor, .gMinor,
.cMinor, .fMinor, .bFlatMinor, .eFlatMinor, .aFlatMinor.
MusicXML round-trip
Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:) emits <key> inside <attributes> after <divisions> and before <time>, in every part's measure 1:
<attributes>
<divisions>480</divisions>
<key>
<fifths>1</fifths>
<mode>major</mode>
</key>
<time>
<beats>4</beats>
<beat-type>4</beat-type>
</time>
<clef>…</clef>
</attributes>
Score/fromMusicXML(data:) reads <fifths> and <mode> from each part's first <key> element. The first part's key becomes Score/keySignature; subsequent parts whose key differs from the first part's key get a per-part ScorePart/keySignature override (see Transposing Instruments below). Documents without a <key> element default to KeySignature/cMajor.
Transposing Instruments
Transposing instruments (B♭ clarinet, F horn, E♭ alto sax, etc.) need two things in MusicXML:
- A per-part key signature override — the instrument's written key, which differs from the concert key by the transposition interval.
- A
<transpose>element — metadata that tells notation software how to convert written pitch to sounding pitch.
Both are notation-only. ScorePart/flatten() returns events at the written pitch. Concert-pitch playback (applying the transpose interval to produce sounding pitches) is planned for a future phase.
Transpose type
Transpose describes the written→sounding pitch interval:
public struct Transpose: Sendable, Hashable {
public let chromatic: Int // semitone shift (negative = sounds below written)
public let diatonic: Int // diatonic step shift
public let octaveChange: Int // additional octave shift (0 when omitted)
}
Named conveniences for common instruments:
| Convenience | Instrument | Written→Sounding | chromatic |
diatonic |
|---|---|---|---|---|
.bFlat |
B♭ clarinet, B♭ trumpet | Major 2nd down | -2 |
-1 |
.a |
Clarinet in A | Minor 3rd down | -3 |
-2 |
.eFlat |
Alto saxophone in E♭ | Major 6th down | -9 |
-5 |
.fHorn |
Horn in F | Perfect 5th down | -7 |
-4 |
Per-part key override
Pass keySignature: to the Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:) DSL constructor:
// Concert key G major. B♭ clarinet: written key A major (a major 2nd up).
let score = Score(bpm: 120, keySignature: .gMajor) {
Part("strings") {
Note(.g, 4, dur: .quarter)
}
Part("clarinet", clef: .treble, keySignature: .aMajor, transpose: .bFlat) {
// Written pitches — a major 2nd above concert pitch.
Note(.a, 5, dur: .quarter)
Note(.b, 5, dur: .quarter)
}
}
MusicXML encoding
Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:) emits each part's effective key in its <key> block:
- Parts with a
keySignatureoverride → emit the override's fifths/mode. - Parts with
keySignature == nil→ emit the score-level key (unchanged behaviour).
When transpose != nil, a <transpose> block is emitted after <clef> (MusicXML 4.0 attributes order: divisions, key, time, clef, transpose):
<!-- B♭ clarinet part -->
<attributes>
<divisions>480</divisions>
<key>
<fifths>3</fifths> <!-- A major, the written key -->
<mode>major</mode>
</key>
<time>…</time>
<clef>…</clef>
<transpose>
<diatonic>-1</diatonic>
<chromatic>-2</chromatic>
<!-- <octave-change> omitted when 0 -->
</transpose>
</attributes>
A part with no key override and no transpose emits exactly the score key and no <transpose> element — output is byte-identical to the non-transposing behaviour.
MusicXML parsing
Score/fromMusicXML(data:) now reads each part's <key> independently (first-key-per-part wins). It also reads <transpose> from the first <attributes> block in each part.
Resolution rules:
- Score key = the first part's parsed key (first-wins document-wide).
- Per-part override: when a part's key DIFFERS from the first part's key →
ScorePart.keySignatureis set to that part's key; when they MATCH →ScorePart.keySignaturestaysnilso non-transposing scores round-trip without spurious overrides. ScorePart.transpose: set from<diatonic>,<chromatic>,<octave-change>when present;nilotherwise.
Notation-only limitation
ScorePart/flatten() returns events at the written pitch. The transpose interval is not applied to produce sounding pitches. A transposing part's playback sounds at the written pitch until concert-pitch playback (applying the transpose to flatten) is implemented in a future phase.
Clef
Each ScorePart carries a Clef used when encoding to MusicXML. Set it via the
clef: parameter of the Part(_:channel:clef:keySignature:transpose:meterMap:offset:id:elements:) DSL constructor:
let violin: ScorePart = Part("Violin", clef: .treble) { Note(.c, 4, dur: .quarter) }
let viola: ScorePart = Part("Viola", clef: .alto) { Note(.c, 4, dur: .quarter) }
let cello: ScorePart = Part("Cello", clef: .bass) { Note(.c, 3, dur: .quarter) }
let guitar: ScorePart = Part("Guitar", clef: .treble8vb) { Note(.c, 4, dur: .quarter) } // sounds an octave lower
let drums: ScorePart = Part("Drums", clef: .percussion) { Note(.c, 4, dur: .quarter) }
The default is Clef/auto, which infers the clef at encode time from the
median MIDI pitch of the part's non-rest events:
- Median < 57 (A3) →
Clef/bass - Median ≥ 57 →
Clef/treble - No pitched notes →
Clef/treble
The threshold Clef.autoBassThresholdMidi = 57 (A3) sits between the typical
bass-part and treble-part pitch centres. Override with an explicit clef when
a part starts in an unusual register.
Clef round-trips through MusicXML: Score/fromMusicXML(data:) reads the first
<clef> element in each <part> and restores the correct Clef case on the
decoded ScorePart. The mapping covers all five supported clefs:
MusicXML <sign> / <line> |
Clef case |
|---|---|
| G / 2 | .treble |
G / 2 + <clef-octave-change>-1</clef-octave-change> |
.treble8vb |
| F / 4 | .bass |
| C / 3 | .alto |
| C / 4 | .tenor |
| percussion | .percussion |
Mid-voice clef changes
The clef: parameter sets the part's initial clef. To switch clef partway
through a part, place a ClefChange(_:) element inline, immediately before the
first note that should appear under the new clef:
Part("cello", clef: .bass) {
Note(.named(.c, 2), dur: .half)
ClefChange(.tenor) // switch to tenor for the high passage
Note(.named(.c, 4), dur: .half)
ClefChange(.bass) // switch back
Note(.named(.g, 2), dur: .half)
}
A clef change is notation-only, exactly like a grace note: ScorePart/flatten()
skips it, so it emits no ScoreEvent and does not advance the beat cursor.
MusicXML pitches are absolute — the clef changes only how following notes are
drawn (staff line + ledger lines), never their sounding pitch. The flattened
event list is identical with or without clef changes.
In MusicXML it encodes as a mid-measure attributes block (valid anywhere inside a
<measure> per MusicXML 4.0):
<attributes>
<clef><sign>C</sign><line>4</line></clef>
</attributes>
It round-trips: Score/fromMusicXML(data:) keeps the first <clef> as the
part-level ScorePart/clef and restores every subsequent <clef> as an inline
ScoreElement/clefChange(_:) element at the same position.
Clef/auto is rejected by ClefChange(_:) (precondition trap): .auto
infers a clef from a part's median pitch and has no meaning at a single point.
Pass an explicit clef. A clef change with no following note in the part is dropped
on round-trip (consistent with other trailing notational marks).
Tuplets
Tuplets are wrappers that scale every child duration by normal / actual:
Tuplet(3, inTimeOf: 2)— three notes performed in the time of two (the canonical triplet).Tuplet(5, inTimeOf: 4)— quintuplet.Tuplet(7, inTimeOf: 4)— septuplet.Tuplet(7, inTimeOf: 8)— for the rare "stretched" cases where 7 notes fill more than their nominal span.
Nesting is supported and exact:
Tuplet(5, inTimeOf: 4) {
Note(.c, 4, dur: .eighth) // duration: 1/2 × 4/5 = 2/5 beat
Tuplet(3, inTimeOf: 2) {
Note(.d, 5, dur: .sixteenth) // duration: 1/4 × 4/5 × 2/3 = 2/15 beat
Note(.e, 5, dur: .sixteenth)
Note(.f, 5, dur: .sixteenth)
}
Note(.g, 4, dur: .eighth)
Note(.a, 4, dur: .eighth)
Note(.b, 4, dur: .eighth)
}
The flattened total span is exactly 2 beats (5 outer eighth slots × 2/5 each), and the cursor lands on a clean Double after the tuplet — no accumulated FP error from 1/3 + 1/3 + 1/3 sums.
MusicXML bracket engraving for nested tuplets
When you export nested tuplets via Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:), each
bracket level receives the correct displayed number. The encoder applies a
per-part rule:
- Parts with NO nesting (only single-level tuplets): bracket starts use the
bare self-closing form
<tuplet type="start" number="1"/>. - Parts WITH any nesting (at least one bracket at level 2 or higher): ALL
bracket starts in that part use the full explicit form with
<tuplet-actual>,<tuplet-normal>, and<tuplet-type>children. This prevents engravers (Dorico, MuseScore) from misreading ambiguous bare brackets spanning notes with mixed cumulative ratios (e.g. 5:4 outer notes and 15:8 inner notes in the same outer bracket).
<time-modification> on every note always carries the cumulative ratio (e.g.
15/8 for a note inside a 5:4 ⊃ 3:2 group). STOP brackets are always bare.
Full form for a 5:4 outer bracket in a nested part:
<tuplet type="start" number="1">
<tuplet-actual>
<tuplet-number>5</tuplet-number>
<tuplet-type>quarter</tuplet-type>
</tuplet-actual>
<tuplet-normal>
<tuplet-number>4</tuplet-number>
<tuplet-type>quarter</tuplet-type>
</tuplet-normal>
</tuplet>
Full form for the inner 3:2 bracket (number=2):
<tuplet type="start" number="2">
<tuplet-actual>
<tuplet-number>3</tuplet-number>
<tuplet-type>quarter</tuplet-type>
</tuplet-actual>
<tuplet-normal>
<tuplet-number>2</tuplet-number>
<tuplet-type>quarter</tuplet-type>
</tuplet-normal>
</tuplet>
<tuplet-type> is derived from the note's printed type name (e.g. "quarter",
"eighth") — the same name the encoder uses for <type>.
Remaining limitations: tuplet crossing a barline still drops brackets; very deep
nesting (3+ levels where one note opens two inner levels simultaneously) is only
partially bracketed; mixed-note-type inner tuplets use the first note's type for
<tuplet-type> (adequate for homogeneous inner groups).
Multi-voice polyphony
Use Voice(n) { … } blocks at the top level of a Part to write two or more
independent rhythmic streams that overlay the same beat space:
Part("piano", clef: .treble) {
Voice(1) {
Note(.e, 5, dur: .half) // upper voice: starts at beat 0
Note(.d, 5, dur: .half) // continues at beat 2
}
Voice(2) {
Note(.c, 4, dur: .whole) // lower voice: also starts at beat 0
}
}
Each Voice(n) block starts its own cursor at beat zero and does NOT advance
the outer part cursor — so multiple Voice blocks always overlay from the
start of the part. ScorePart/lastBeat() returns the maximum sounding end
beat across all voices.
Voice numbers are 1-based and must be ≥ 1. The number becomes the
MusicXML <voice> field. After flattening, ScoreEvent.voice holds the voice
number so callers can route different voices to different synthesizers.
Single-voice invariant
Parts that contain no Voice(n) wrapper — i.e. the common single-voice case —
behave exactly as in the legacy single-voice path: no <backup> elements appear in the
encoded MusicXML and flatten() returns events in sequential cursor order.
The multi-voice encoder path is only activated when the part's top-level
element list contains at least one .voice(_, _) case.
MusicXML encoding with <backup>
When encoding a multi-voice part, each <measure> emits voice 1's content
first, then a <backup><duration>CAP</duration></backup> element (where CAP
is the measure capacity in ticks), then voice 2's content with
<voice>2</voice> on each note, and so on for additional voices.
Redundant dynamics in multi-voice parts
Because each voice emits its own dynamic <direction>, several voices that open
on the same beat with the same dynamic produce a stack of identical markings
(e.g. three mps under a grand-staff chord). By default the encoder collapses
these: each dynamic is emitted once per staff per metric onset, so identical
dynamics sharing an onset on the same staff merge into one direction, while each
staff of a grand staff keeps its own dynamic line and genuinely different voice
dynamics (one voice f, another p) are always preserved.
This is controlled by the collapseRedundantDynamics parameter on
Score/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:) (and
Score/toMusicXMLData(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)), which defaults
to true. Pass false to restore the raw one-direction-per-voice output:
let score = Score(bpm: 120) {
Part("melody") { Note(.c, 4, dur: .quarter) }
}
let clean: String = score.toMusicXMLString() // collapsed (default)
let raw: String = score.toMusicXMLString(collapseRedundantDynamics: false) // one per voice
MusicXML parsing of <backup> / <forward>
Score.fromMusicXML(data:) now handles <backup> and <forward> elements:
<backup>: rewinds the absolute cursor by the specified number of divisions.<forward>: inserts a rest of the corresponding duration to advance the cursor (preserving beat positions for subsequent notes).
When a parsed part contains notes from multiple <voice> numbers (i.e. the
source document used <backup>), the parser groups events by voice number,
sorts each voice's events by absolute beat, and wraps each voice in a
.voice(n, […]) block. Single-voice parts (no <backup> in source) return
the unchanged flat element list — the round-trip is structurally identical.
Round-trip
A 2-voice score encodes to MusicXML with <backup> and parses back to the
same .voice(1, […]) / .voice(2, […]) structure with matching flattened
events (same beats, pitches, and durations within floating-point tolerance).
Hairpins (wedge markings)
Use Crescendo { … } and Diminuendo { … } to annotate a span of notes with a
hairpin wedge (< / >) in MusicXML. Both constructs are purely notational:
they do not change timing, velocity, or the flattened ScoreEvent list. The
children of a wedge block are flattened identically to the same notes written
without the wrapper.
WedgeKind
WedgeKind is a two-case enum:
| Case | MusicXML type |
Visual |
|---|---|---|
.crescendo |
"crescendo" |
Opening wedge < |
.diminuendo |
"diminuendo" |
Closing wedge > |
DSL
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)
}
Diminuendo {
Note(.f, 5, dur: .quarter, dyn: .f)
Note(.e, 5, dur: .quarter)
Note(.d, 5, dur: .quarter, dyn: .p)
}
Transparent flatten semantics
ScorePart.flatten() on a wedge element recurses into the children with the
same cursor and voiceFallback — exactly as if the children were written directly
in the enclosing context. A wedge wrapper therefore produces no extra events,
no timing differences, and no velocity changes.
MusicXML encoding
The encoder marks the first child atom of a wedge span with a
<wedge type="crescendo|diminuendo"/> direction, and the last child atom
with a <wedge type="stop"/> direction:
<direction placement="below">
<direction-type><wedge type="crescendo"/></direction-type>
</direction>
<note>…first note…</note>
…
<note>…last note…</note>
<direction placement="below">
<direction-type><wedge type="stop"/></direction-type>
</direction>
Wedge directions coexist with dynamic <direction> elements — both are emitted
before/after the same note without conflict. Wedges may span barlines: the start
direction appears before the first note in measure N and the stop direction
appears after the last note in measure M (M ≥ N). Tied barline-continuation
pieces do NOT re-emit wedge directions.
Wedge directions also work inside Voice(n) { … } blocks; the wedge annotation
is scoped to the voice that contains it.
MusicXML parsing and round-trip
Score.fromMusicXML(data:) parses <wedge> elements from <direction> blocks
and reconstructs .wedge(kind, [...]) wrappers around the corresponding note
spans. The flattened event list (beats, pitches, velocities) is always identical
to what the same notes without a wedge wrapper would produce — the wedge is
event-transparent.
Nesting with other DSL elements
Crescendo / Diminuendo compose freely with other DSL elements:
Part("lead") {
Crescendo {
Tuplet(3, inTimeOf: 2) {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
}
Note(.f, 5, dur: .half, dyn: .f)
}
}
A wedge inside a Tuplet marks the first and last atoms within the tuplet group.
A wedge wrapping a Tuplet marks the first and last atoms of the entire span.
Both are supported; the tuplet <time-modification> and bracket annotations are
preserved on the child atoms.
Slurs and Spanners
Lyrebird provides two authoring paths for slur and hairpin boundaries. Both are
purely notational — they do not affect ScorePart/flatten() output (the
ScoreEvent list is identical whether or not spans are present).
Slur { } block — clean non-overlapping spans
The Slur { } DSL function wraps a sequence of children in a ScoreElement/slur(_:)
block. 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 one note.
Slur {
Note(.c, 5, dur: .quarter)
Note(.d, 5, dur: .quarter)
Note(.e, 5, dur: .quarter)
Note(.f, 5, dur: .quarter)
}
Slur { } is the preferred form for clean, non-overlapping spans. The block
composes freely with Crescendo, Diminuendo, Tuplet, and Voice wrappers.
Per-note spanners: — overlapping and shared-boundary spans
When a note must simultaneously carry boundaries from different overlapping
spans — for example, a slur that starts on the same note where a crescendo ends
— use the spanners: parameter on Note or Chord:
Part("lead") {
Crescendo {
Note(.c, 5, dur: .quarter, dyn: .p)
Note(.d, 5, dur: .quarter)
// This note: crescendo opens AND a slur starts here (shared boundary).
Note(.e, 5, dur: .quarter, spanners: [.beginSlur, .beginCrescendo])
}
// Slur ends here; separate crescendo continues further.
Note(.f, 5, dur: .quarter, spanners: [.endSlur])
Note(.g, 5, dur: .quarter, dyn: .f, spanners: [.endHairpin])
}
When spanners: is non-empty the note is wrapped in a ScoreElement/spanned(_:_:)
element; when the array is empty the plain note is returned unchanged — existing
output is byte-identical.
The Spanner cases:
| Case | Effect |
|---|---|
.beginSlur |
<slur number="1" type="start"/> on the note |
.endSlur |
<slur number="1" type="stop"/> on the note |
.beginCrescendo |
<wedge type="crescendo"/> before the note |
.beginDiminuendo |
<wedge type="diminuendo"/> before the note |
.endHairpin |
<wedge type="stop"/> after the note |
.beginGlissando(Glissando(...)) |
<glissando type="start" …/> (or <slide …/>) on the note |
.endGlissando |
<glissando type="stop" …/> (or <slide …/>) on the note |
Note that .endHairpin is type-agnostic: MusicXML <wedge type="stop"/> closes
any open hairpin regardless of whether it was opened as crescendo or diminuendo.
Slur, wedge, and glissando annotations are independent fields on an atom — any combination of span boundaries on the same note compose without conflict.
Conflict policy: lenient + diagnostic
At encode time the encoder performs a per-voice balance check over the produced
atom stream. On detecting an imbalance — a double-open, an end with no matching
open, or an open still active at the end of the part — the offending boundary
annotation is dropped (so the score still renders) and a warning is posted to
LyrebirdMessageCenter/shared. Inspect LyrebirdMessageCenter.shared.messages
to see any spanner diagnostics after encoding.
Glissandos and Slides
A glissando connects two notes with a visual pitch sweep — a two-note span exactly
like a slur. Use Spanner/beginGlissando(_:) on the START note and
Spanner/endGlissando on the STOP note via the spanners: parameter:
// Default wavy glissando (unmeasured):
Note(.g, 5, dur: .quarter, spanners: [.beginGlissando(Glissando())])
Note(.c, 6, dur: .quarter, spanners: [.endGlissando])
// Measured slide with solid line:
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(kind: .slide, lineType: .solid))])
Note(.e, 5, dur: .quarter, spanners: [.endGlissando])
// With a text label on the start:
Note(.d, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando(text: "gliss."))])
Note(.f, 5, dur: .quarter, spanners: [.endGlissando])
Glissando descriptor
| Property | Type | Default | Description |
|---|---|---|---|
kind |
GlissandoKind |
.glissando |
Whether to emit <glissando> or <slide> |
lineType |
GlissandoLineType |
.wavy |
Visual line style (solid, dashed, dotted, wavy) |
text |
String? |
nil |
Optional label on the start element (e.g. "gliss.") |
GlissandoKind
| Case | MusicXML element | Meaning |
|---|---|---|
.glissando |
<glissando> |
Wavy or curved, unmeasured pitch sweep |
.slide |
<slide> |
Straight line, measured portamento |
GlissandoLineType
| Case | line-type attribute |
|---|---|
.solid |
"solid" |
.dashed |
"dashed" |
.dotted |
"dotted" |
.wavy |
"wavy" (conventional for unmeasured glissandos) |
MusicXML output
On the START note, inside <notations>:
<!-- Self-closing when text is nil: -->
<glissando type="start" line-type="wavy" number="1"/>
<!-- Non-self-closing when text is present: -->
<glissando type="start" line-type="wavy" number="1">gliss.</glissando>
<!-- Slide kind uses <slide> element name: -->
<slide type="start" line-type="solid" number="1"/>
On the STOP note, inside <notations>:
<glissando type="stop" number="1"/>
<!-- or for a slide: -->
<slide type="stop" number="1"/>
The stop element name always matches the start kind — the encoder propagates the
GlissandoKind from the opener to the stop atom during balance validation.
Composition with other spans
Glissandos compose with slurs and hairpins on the same note without conflict:
Note(.c, 5, dur: .quarter,
spanners: [.beginGlissando(Glissando()), .beginSlur])
Note(.e, 5, dur: .quarter,
spanners: [.endGlissando, .endSlur])
Both <slur …> and <glissando …> appear inside the <notations> block.
Currently NOT parsed on decode
<glissando> and <slide> elements in an imported MusicXML file are not
currently round-tripped back to Spanner/beginGlissando(_:) / Spanner/endGlissando
values. Glissando is an emit-only feature in the current encoder.
Grace Notes
Grace notes are ornamental noteheads with no beat-grid duration. They are
notation-only: ScorePart/flatten() skips them entirely, emits no
ScoreEvent, and does NOT advance the beat cursor. The flattened event list
is identical whether or not grace notes are present.
DSL
// Acciaccatura (slashed grace — default): a quick, crushed ornament.
Grace(.fSharp, 5) // slashed: true is the default
Note(.g, 5, dur: .quarter, dyn: .mf) // main note the grace ornaments
// Appoggiatura (unslashed grace): a leaning ornament with more weight.
Grace(.d, 5, slashed: false)
Note(.e, 5, dur: .quarter, dyn: .mf)
// Convenience: Grace(_ pitch: Pitch) or Grace(_ name: NoteName, _ octave: Int).
Grace(Pitch.named(.fSharp, 5))
Grace(.fSharp, 5, slashed: true) // equivalent
Placement: author a Grace element immediately before the main note it
ornaments. A run of consecutive Grace elements before a note forms a grace-note
group — multiple small noteheads appear before the main note.
Flatten semantics: skipped
ScorePart/flatten() on a .grace element does nothing — no event is
appended and the cursor does not move. This means:
- A score WITH grace notes and the SAME score WITHOUT grace notes produce an
identical
ScoreEventlist (same event count, same beats, same durations). - Grace notes never push content across a barline or alter measure layout in
flatten().
acciaccatura vs appoggiatura
slashed |
Type | Convention |
|---|---|---|
true (default) |
Acciaccatura | Tiny note with a slash through the stem; performed very quickly, crushed against the main note |
false |
Appoggiatura | Tiny note WITHOUT a slash; performed with more weight and steals time from the main note |
MusicXML encoding
A grace note is emitted as a <note> with a <grace> child as its first
element, followed by <pitch>, <voice>, and <type>. There is no
<duration> element on a grace note (MusicXML convention):
<!-- Acciaccatura (slashed): -->
<note>
<grace slash="yes"/>
<pitch>
<step>F</step>
<alter>1</alter>
<octave>5</octave>
</pitch>
<voice>1</voice>
<type>eighth</type>
</note>
<!-- Appoggiatura (unslashed): -->
<note>
<grace/>
<pitch>…</pitch>
<voice>1</voice>
<type>eighth</type>
</note>
Grace atoms have soundingDuration = 0 and are emitted inline in the
measure-emission loop immediately before the following note. They contribute
zero to measure-fill accounting — grace notes never push content across a
barline. measureCount is not inflated by grace notes: a full measure of quarter
notes plus a leading grace still yields exactly the correct number of measures.
A grace note that is the last element in a part (degenerate — no following main note to ornament) is still emitted in the current measure at the current cursor position.
MusicXML parsing and round-trip
Score/fromMusicXML(data:) recognises a <note> containing a <grace> child
as a grace note. Grace notes have no <duration> — the parser's duration-driven
cursor is not advanced. The grace note is committed as a .grace(pitch, slashed:)
element immediately before the following note.
Round-trip: Grace(.fSharp, 5) → encode <grace slash="yes"/> note → parse
→ .grace(Pitch.named(.fSharp, 5), slashed: true) is recovered. The event
round-trip (flatten) is identical whether the grace is present or not.
Playback limitation
Grace notes are currently notation-only. ScorePlayer and audio rendering
do not realize them as sound events — no note-on is fired for a grace note.
Implemented grace playback (stealing a small duration from the preceding or
following main note and firing a note-on for the grace pitch at the stolen time)
is planned for a future phase.
Note display overrides
NoteDisplay lets a single note or chord override its notation appearance in
MusicXML output without affecting its sounding ScoreEvent representation.
ScorePart/flatten() is transparent to NoteDisplay — the event list is
identical whether or not a display override is present.
The four properties
| Property | MusicXML emitted | Default (no override) |
|---|---|---|
notehead: Notehead? |
<notehead>VALUE</notehead> |
omitted |
size: NoteSize? |
size="cue|large" on <type> |
no attribute |
hideStem: Bool |
<stem>none</stem> |
omitted |
hideBeam: Bool |
note excluded from beam grouping | beamed normally |
An all-defaults NoteDisplay() value has hasOverrides == false and produces
byte-identical MusicXML output to the same note without a display wrapper.
Notehead shapes (Notehead)
| Case | MusicXML value | Typical use |
|---|---|---|
.normal |
"normal" |
Standard filled notehead (default) |
.x |
"x" |
Percussion, spoken voice |
.diamond |
"diamond" |
Harmonics, col legno, Bartók pizzicato |
.triangle |
"triangle" |
Bell-like or muted percussion |
.slash |
"slash" |
Rhythmic/jazz comping notation |
.cross |
"cross" |
Plus-sign shape |
.circleX |
"circle-x" |
Choked cymbal |
.square |
"square" |
Square notehead |
.hidden |
"none" |
Hidden notehead — note present but invisible |
.other(String) |
raw string | Any MusicXML notehead value not listed above |
Note: the hidden notehead is
.hidden(mapping to MusicXML"none"), not.none— a bare.nonein theNotehead?argument would read asOptional.none(no override) rather than a hidden head.
Note-type size scaling (NoteSize)
NoteSize maps to the size= attribute on the MusicXML <type> element.
It scales the whole note (head + stem + flag/beam + ledger lines) —
MusicXML has no per-notehead percentage scaling.
// Cue note: smaller than normal.
Note(.e, 5, dur: .eighth, display: NoteDisplay(size: .cue))
// → <type size="cue">eighth</type>
// Large note (e.g. solo passage marking).
Note(.e, 5, dur: .quarter, display: NoteDisplay(size: .large))
// → <type size="large">quarter</type>
NoteSize.normal and nil both suppress the size= attribute (byte-identical
output) and count as no override for hasOverrides.
Hiding the stem
hideStem: true emits <stem>none</stem> immediately after
<time-modification> and before <notehead> / <staff>, per MusicXML 4.0
child-element order. Ignored for rests (which have no stem).
Note(.c, 5, dur: .quarter, display: NoteDisplay(hideStem: true))
// Produces: <stem>none</stem> inside the <note> block.
Breaking beam groups (hideBeam)
hideBeam: true excludes the note from the beam-annotation pass: any beam run
that would include this note is split at it, and no <beam> element is emitted
for the note itself. The surrounding notes that ARE beamable remain beamed in
their own sub-runs.
// Second note breaks the beam group.
Note(.c, 5, dur: .eighth)
Note(.d, 5, dur: .eighth, display: NoteDisplay(hideBeam: true))
Note(.e, 5, dur: .eighth)
Note(.f, 5, dur: .eighth)
// Result: [begin|end] [no beam] [begin|end] instead of [begin|continue|continue|end]
DSL usage
Pass display: as the last parameter of Note(...) or Chord(...):
// X notehead, cue size, hidden stem.
Note(.c, 5, dur: .quarter, display: NoteDisplay(
notehead: .x,
size: .cue,
hideStem: true
))
// Diamond notehead on a chord.
Chord([(.c, 5), (.e, 5), (.g, 5)], dur: .half, display: NoteDisplay(notehead: .diamond))
// Compose with spanners: both the notehead and the slur are emitted.
Note(.d, 5, dur: .quarter, spanners: [.beginSlur], display: NoteDisplay(hideStem: true))
When display: is non-nil and hasOverrides is true, the DSL function
wraps the produced element in a ScoreElement/displayed(_:_:) wrapper.
When hasOverrides is false (all-defaults or nil), the wrapper is
omitted and output is byte-identical to a note without any display: argument.
Emit-only — not parsed on decode
Note: Currently NOT parsed.
Score/fromMusicXML(data:)does not parse<notehead>,<stem>, or thesize=attribute on<type>back intoNoteDisplay. A score encoded with notehead/stem/size overrides will round-trip correctly as sound events (pitch, beat, duration, velocity are fully preserved), but the visual overrides are not reconstructed on decode. This is intentional —NoteDisplayis an authoring-side annotation.
Composing display with spanners and structure
display: and spanners: can be combined on the same note. The DSL applies
spanners first (wrapping in .spanned([…], .note(…))), then display (wrapping
in .displayed(…, .spanned(…, .note(…)))):
// Slur AND diamond notehead on the same note.
Note(.c, 5, dur: .quarter, spanners: [.beginSlur], display: NoteDisplay(notehead: .diamond))
// Internal structure: .displayed(display, .spanned([.beginSlur], .note(...)))
Nesting two display: wrappers uses outer-wins semantics: the outermost
.displayed overwrites any inner display set on the same atoms.
Authored ties
A tie connects two consecutive noteheads of the same pitch into one sustained
sounding event. In Lyrebird, ties are authored by setting tie: true on the first
of the two Note(...) elements — the pair is then notated as two tied noteheads
in MusicXML but sounds as a single note of the summed duration.
DSL
// Quarter tied to an eighth → sounds as one dotted-quarter (1.5 beats)
// notated as two tied noteheads.
Note(.g, 4, dur: .quarter, tie: true)
Note(.g, 4, dur: .eighth)
The tie: parameter defaults to false, so existing call sites are unchanged.
Flatten semantics: sounds as one note
ScorePart/flatten() merges a tie == true note with the immediately-following
same-pitch, same-voice note into one ScoreEvent whose:
durationis the sum of both notated durationsbeat,velocity,articulation,pitch, andvoicecome from the first note
Tie chains work: if A.tie == true, B.tie == true, and C follows, all three
collapse into one event of duration A.dur + B.dur + C.dur. A tie == true note
whose immediately-following element is not a same-pitch, same-voice note is treated
as untied — two separate events are emitted and no tie annotation appears in
MusicXML.
Both single notes and chords support tie: true.
MusicXML encoding: two tied noteheads
The MusicXML encoder walks the unflattened element tree, so it sees both note elements. The first note emits:
<note>
<pitch>…</pitch>
<duration>480</duration> <!-- quarter -->
<tie type="start"/>
<voice>1</voice>
<type>quarter</type>
<notations>
<tied type="start"/>
</notations>
</note>
The second note emits:
<note>
<pitch>…</pitch>
<duration>240</duration> <!-- eighth -->
<tie type="stop"/>
<voice>1</voice>
<type>eighth</type>
<notations>
<tied type="stop"/>
</notations>
</note>
Both <tie> (sounding) and <tied> (notation) elements are emitted per MusicXML
4.0 conventions. The authored-tie mechanism composes with barline-split ties: a
note can simultaneously be an authored-tie-start and get split across a barline —
both sets of <tie> elements are emitted correctly.
MusicXML round-trip
An authored tie round-trips as a single merged note (event-preserving,
structure-collapsing). The parser already merges <tie type="stop"/> noteheads
back into the preceding note (the same mechanism used for barline-split ties), so:
Note(.c, 4, dur: .quarter, tie: true)+Note(.c, 4, dur: .eighth)→ encode → parse →Note(.c, 4, dur: .fraction(3/2), tie: false)(one element, 1.5 beats)flatten()on the round-tripped score produces the sameScoreEventlist (1 event at beat 0, duration 1.5 beats, pitch C4)
The structural two-notehead annotation is not preserved on the way back — only the sounding event is. This is consistent with how barline-split ties already round-trip, and how tuplets do not structurally round-trip.
Chord ties
A chord tie connects two consecutive chord stacks of the same pitch set (order-insensitive) and the same voice into one sustained sounding chord whose duration is the sum of both notated durations.
DSL
// C major chord tied across two bars — all three pitches sustain.
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .whole, tie: true)
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .whole)
// → flatten() yields 3 events, each 8.0 beats (2 whole notes summed), beat 0.
The tie: parameter on Chord(...) defaults to false, so all existing call
sites are unchanged.
Flatten semantics: same-pitch-set match
ScorePart/flatten() merges a tie == true chord with the immediately-following
chord that has the same pitch set (order-insensitive) and the same voice. The
merged result has one ScoreEvent per pitch, each with:
duration= sum of both notated chord durationsbeat,velocity,articulation,voice, andchannelfrom the first chord
Tie chains work: A.tie→B.tie→C all collapse into pitch-count events with the
summed duration. A tie==true chord whose immediately-following element is not a
same-pitch-set, same-voice chord is treated as untied — all pitches from both
chords are emitted separately and no tie annotation appears in MusicXML.
MusicXML encoding: per-notehead tie elements
Every notehead in a tied chord emits <tie type="start"/> and
<tied type="start"/>. Every notehead in the following (stop) chord emits
<tie type="stop"/> and <tied type="stop"/>. For a 3-pitch chord, this produces
3 tie-start elements and 3 tie-stop elements total.
<!-- first chord notehead (lead) -->
<note>
<pitch><step>C</step><octave>4</octave></pitch>
<duration>1920</duration>
<tie type="start"/>
<voice>2</voice>
<type>whole</type>
<notations><tied type="start"/></notations>
</note>
<!-- second chord notehead (chord-mate E4) -->
<note>
<chord/>
<pitch><step>E</step><octave>4</octave></pitch>
<duration>1920</duration>
<tie type="start"/>
<voice>2</voice>
<type>whole</type>
<notations><tied type="start"/></notations>
</note>
<!-- … third chord-mate G4 likewise … -->
Composition with barline-split: a tied chord that is also split across a barline emits the authored-tie start on the LAST barline-split piece and the authored-tie stop on the FIRST piece of the follower chord — mirroring the authored-tie note fix.
MusicXML round-trip
An authored chord tie round-trips as a single merged chord (event-preserving,
structure-collapsing). The parser merges <tie type="stop"/> noteheads of each
pitch back into the preceding chord element (same mechanism as note ties and
barline-split ties), so:
Chord([(.c,4),(.e,4),(.g,4)], dur: .quarter, tie: true)+Chord([(.c,4),(.e,4),(.g,4)], dur: .eighth)→ encode → parse → one merged chord element of duration 3/2 quarters, 3 events on flattenflatten()on the round-tripped score produces the same event list (3 events at beat 0, duration 1.5 beats, pitches C4/E4/G4)
The two-chord structural annotation is not preserved on the way back — only the sounding events are. This is consistent with how note ties and barline-split ties already round-trip.
Articulation effects
Articulation modifies the performed (sounding) duration relative to the notated duration,
and may bump velocity:
| Case | Duration scale | Velocity bonus |
|---|---|---|
.normal |
1.0 | 0.0 |
.staccato |
0.5 | 0.0 |
.staccatissimo |
0.25 | 0.0 |
.legato |
1.05 | 0.0 |
.tenuto |
1.0 | 0.0 |
.accent |
1.0 | +0.15 |
.marcato |
0.85 | +0.25 |
Velocity is clamped to [0, 1] after the bonus is added.
ScoreEvent.duration always holds the notated beat value from the score — articulation duration-scaling is not baked in at flatten time. Call event.performedDuration (a computed property: duration × articulation.durationScale) when you need the actual sounding length for audio scheduling, MIDI note-off timing, or SMF output. MusicXML encoding uses duration directly so <duration> values stay on-grid regardless of articulation.
Dynamic mapping
Dynamic cases map to normalized velocity:
| Case | Velocity |
|---|---|
.ppp |
0.10 |
.pp |
0.20 |
.p |
0.35 |
.mp |
0.50 |
.mf |
0.60 |
.f |
0.75 |
.ff |
0.85 |
.fff |
1.00 |
.raw(Double) |
clamped to [0, 1] |
Dynamic.midiVelocity returns [0, 127] for direct MIDI integration.
Pitch conventions
Pitch.midi(60)is middle C.Pitch.named(.c, 4)is also middle C — octave 4 contains middle C.Pitch.freq(440.0)is A4. Microtonal pitches can use.freqdirectly OR a quarter-toneAccidentalon.named.Pitch.restis the sentinel for rests;pitch.isRestis the predicate.
Spelling preservation
NoteName is a (Letter, Accidental) pair so the original spelling round-trips through formats that care (MusicXML, MIDI key signatures, display). Octave is determined by the letter, NOT the sounding pitch:
Pitch.named(.cFlat, 4).midiNote // 59 — letter C in octave 4, sounds at B3
Pitch.named(.bSharp, 3).midiNote // 60 — letter B in octave 3, sounds at C4
Pitch.named(.cSharp, 4) != Pitch.named(.dFlat, 4) // distinct values, same MIDI
Every standard spelling has a static-let factory — .c, .cSharp, .dFlat, .cFlat, .bSharp, .eSharp, .fFlat, .cDoubleSharp, .dDoubleFlat, plus quarter-tone variants .cQuarterSharp, .dThreeQuarterFlat, etc. — for every letter.
Quarter tones
The Accidental enum spans doubleFlat to doubleSharp in 50-cent steps, so 24-TET pitches express directly:
Pitch.named(.cQuarterSharp, 4).midiNoteFractional // 60.5
Pitch.named(.cQuarterSharp, 4).frequency // C4 × 2^(0.5/12) ≈ 268.31 Hz
midiNoteFractional returns the exact MIDI position (Double) without rounding. midiNote rounds to the nearest integer; quarter-tone accidentals snap up or down at the boundary.
Playback
ScorePlayer walks the merged event stream against a LyrebirdClock
on a LyrebirdRoutine thread. Two modes:
// Your own note renderer and sampler — anything that consumes a ScoreEvent / MIDIMessage.
struct NoteRenderer: Sendable { func handle(_ event: ScoreEvent) {} }
struct DrumSampler: Sendable { func handle(_ message: MIDIMessage) {} }
let mySynth: NoteRenderer = NoteRenderer()
let mySampler: DrumSampler = DrumSampler()
let score = Score(bpm: 120) {
Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.g, 4, dur: .half)
}
}
let clock: LyrebirdClock = LyrebirdClock(engine: engine, bpm: 120)
let player: ScorePlayer = ScorePlayer(score: score, engine: engine, clock: clock)
// Mode 1: emit one ScoreEvent per notated event. Caller drives note-off /
// sustain via event.performedDuration (sounding length) as needed.
player.play { event in
mySynth.handle(event)
}
// Mode 2: emit paired noteOn / noteOff MIDIMessages. Note-offs land at
// event.beat + event.performedDuration, ordered before any noteOn at the
// same beat to avoid stuck-key behaviour.
player.playMIDI { msg in
mySampler.handle(msg)
}
// later …
player.stop() // signal stop
player.reset() // synchronously join the routine thread
By default ScorePlayer/play(applyScoreTempo:handler:) writes Score/bpm into
LyrebirdClock bpm at start. Pass applyScoreTempo: false to
re-pace the score at the clock's existing tempo.
Score.allEvents is the merged + stable-sorted event stream used by the
player; ties at the same beat are broken by ScoreEvent/channel so
inter-part ordering is deterministic.
SMF bridge
Bidirectional Standard MIDI File ↔ Score conversion. Pure language-side, no external dependency.
Score → SMF bytes
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("lead", channel: 0) {
Note(.c, 4, dur: .quarter)
Note(.e, 4, dur: .quarter)
Note(.g, 4, dur: .half)
}
Part("bass", channel: 1) {
Note(.c, 2, dur: .whole)
}
}
let data: Data = score.toMIDIFileBytes(ticksPerQuarter: 480)
try data.write(to: URL(fileURLWithPath: "/tmp/score.mid"))
The output is SMF format 1: track 0 carries tempo + time-signature
meta events; tracks 1..N each correspond to one ScorePart with a
track-name meta and paired noteOn / noteOff at event.beat × ppq
ticks. Note-offs at the same tick as another noteOn sort first, so
back-to-back notes never produce stuck-key behaviour. Velocity 0 is
clamped to MIDI velocity 1 on the way out (so dyn: .raw(0.0) still
emits as a noteOn rather than aliasing to noteOff).
SMF → Score
let file = try MIDIFile.read(filePath: "/path/to/song.mid")
let score = file.toScore()
print("Score: \(score.bpm) BPM, \(score.parts.count) parts")
Each SMF track becomes a ScorePart. NoteOn / noteOff events are
paired into ScoreEvents with duration = offBeat - onBeat; LIFO
matching on (channel, note) handles overlapping repeats on the same
pitch. The first tempo meta event sets Score/bpm; the first time
signature sets Score/timeSignature. Track names become part names.
Channel-less tracks (e.g. the conductor track) are dropped by default —
pass skipChannelLessTracks: false to keep them as empty parts.
Pitches lose spelling: SMF carries no <step> / <alter> info, so
every pitch is reconstructed as Pitch/midi(_:). To preserve
spelling, drive from MusicXML instead.
The element tree produced for each part is monophonic-shaped (.note +
.rest). Polyphonic / overlapping-note tracks preserve every event in
the flat ScorePart/flatten() output but the unflattened element
tree linearises them — the MusicXML bridge is the lossless polyphony
path.
MusicXML bridge
Score ↔ MusicXML 4.0 (score-partwise) bidirectional conversion.
Pure language-side, uses Foundation XMLParser for read; raw string
emission for write. Pitch spelling round-trips exactly via
NoteName/letter + NoteName/accidental ↔ <step> / <alter> /
<octave>. Quarter-tones via fractional <alter> (0.5, -1.5,
etc.) — a key reason MusicXML was chosen as the lossless interchange
format.
Score → MusicXML
import Foundation
let score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
Part("Melody") {
Note(.cFlat, 4, dur: .quarter) // distinct from B3
Note(.bSharp, 3, dur: .quarter) // distinct from C4
Note(.cQuarterSharp, 4, dur: .eighth) // 24-TET
Chord([(.c, 4), (.e, 4), (.g, 4)], dur: .half)
}
}
let xml: String = score.toMusicXMLString() // String
let data: Data = score.toMusicXMLData() // UTF-8 Data
try data.write(to: URL(fileURLWithPath: "/tmp/score.musicxml"))
Output structure: score-partwise root, one <part-list> with one
<score-part> per ScorePart, one <part> per part containing a
single <measure number="1"> with attributes (divisions, time, clef),
tempo direction, and the part's notes / rests / chords.
MusicXML → Score
let score = try Score.fromMusicXML(filePath: "/path/to/song.musicxml")
print("\(score.bpm) BPM, \(score.parts.count) parts")
Parses <part-list> for part names + IDs, walks each <part> <measure>
collecting <note> blocks. <pitch> (<step>, <alter>, <octave>)
maps directly back to Pitch/named(_:_:) preserving spelling.
<chord/> flag groups simultaneous notes into ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:).
<rest/> advances cursor without emitting a note.
First <sound tempo="..."> or <metronome><per-minute> becomes
Score/bpm. First <time> becomes Score/timeSignature.
Articulations (<staccato/>, <accent/>, <strong-accent/>,
<tenuto/>, <staccatissimo/>) map to Articulation.
What round-trips losslessly
- Pitch spelling (Letter + Accidental, including double accidentals and the four quarter-tone steps).
- Octave (letter-based, so
C♭4stays in octave 4 even though it sounds at MIDI 59). - Beat positions and durations (via configurable
<divisions>, default 480). - Chord groupings (consecutive
<note>elements with<chord/>↔ScoreElement/chord(_:duration:dynamic:articulation:voice:tie:)). - Tempo + time signature.
- Track / part names.
- Voice numbers.
- Articulations.
Current limitations
- No tuplet wrappers — durations are emitted verbatim as divisions;
Tuplet-authored events come through with their already-scaled durations
and re-flatten to the correct beats, but the emitted XML has no
<time-modification>markers (though existing<time-modification>in imported documents is silently accepted — durations are exact rationals). <dynamics>directions are fully supported: named dynamics (<ppp/>…<fff/>) and<other-dynamics>forDynamic/raw(_:)are emitted on encode (change-only per voice,placement="below") and parsed on decode (sticky — applies to all subsequent notes until the next direction).<sound dynamics>is intentionally NOT emitted; velocity is the Lyrebird-side playback path (ScoreEvent.velocity).- No
<key>/<lyric>/ ornaments. Slurs (<slur>), beams (<beam>), clef (<clef>), and dynamics (<dynamics>) are fully emitted on encode and parsed on decode. score-timewisedocuments are rejected (MusicXMLError.unsupportedTimewiseDocument).<backup>and<forward>are now fully handled.
Out of scope (Phases A + B + C + D)
- No notation engraving (beams, stems, slurs, lyrics).
- No mid-piece time-signature changes within a single
Score. - No tempo map within a single
Score— tempo is a single value. - No multi-measure splitting + ties on MusicXML emit.
- No tuplet markers on MusicXML emit (Tuplet authoring works in the DSL; the resulting events round-trip via beats, just without the tuplet wrapper on output).
Sections
Large scores are easier to author when the material is divided into named blocks — intro, verse, chorus, bridge. ScoreSection provides that authoring layer on top of the existing flat Score.
Concept
A ScoreSection is a self-contained block of music with its own:
- Local bar numbering — bar 1 inside a section is always the first bar of that section, regardless of where the section sits in the assembled score.
- Rehearsal mark — a label rendered at the section's first global measure in MusicXML output. Prefer single letters (
"A","B","C"): rehearsal marks are system objects that editors render as an auto-advanced letter sequence, so single letters round-trip reliably; custom words ("Intro","Chorus") are emitted faithfully but many editors (e.g. Dorico) re-sequence them and hide the authored text. - Local meter map — the time signature(s) governing that section. When omitted, the section inherits the score-level
timeSignature(which defaults to 4/4 unless set at theScorelevel). - Local tempo changes — measure-indexed within the section; offset to global measure numbers on assembly.
- Local repeat structure — repeat barlines within the section; offset on assembly.
- Parts — only the instruments that play in this section. All present parts are rest-padded to the section's measure span (the longest part rounded up to whole bars), so they bar-align; instruments absent from a section receive whole-measure rest fill (TACET). See Part padding below.
DSL usage
let score = Score(bpm: 120) {
Section("A") {
Part("lead") { Note(.c, 5, dur: .whole) }
Part("bass") { Note(.c, 2, dur: .whole) }
}
Section("B", meterMap: MeterMap(TimeSignature(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)) }
}
Section("C", tempoChanges: [TempoChange(measure: 1, bpm: 160)]) {
Part("lead") {
Note(.g, 5, dur: .whole)
}
// "bass" is TACET — receives a whole rest automatically.
}
}
After assembly: score.parts contains the full flat element list for each instrument across all sections; score.rehearsalMarks maps each section's first global measure to its label.
Local vs global measure numbering
Every TempoChange, RepeatStructure, and Ending value inside a ScoreSection uses local measure numbers (bar 1 = the first bar of that section). During assembly these are shifted by the running measure offset so they land at the correct global bar numbers in the assembled Score.
For example, a section starting at global bar 5 with a local TempoChange(measure: 2, bpm: 140) becomes a global TempoChange(measure: 6, bpm: 140).
Instrument identity (id)
Parts are matched across sections by ScorePart/id, not by ScorePart/name. This lets a section rename an instrument (e.g. "Solo Lead" in one section, "Rhythm Lead" in another) while still stitching their content together into the same flat part:
let a: ScoreSection = Section("A") {
Part("Solo Lead", id: "lead") { Note(.c, 4, dur: .quarter) }
}
let b: ScoreSection = Section("B") {
Part("Rhythm Lead", id: "lead") { Note(.e, 4, dur: .quarter) } // same flat part as "Solo Lead"
}
When id: is omitted it defaults to name, so Part("lead") and Part("lead") in different sections share the same identity automatically — no changes needed for the common case.
Rehearsal marks
Each section contributes a Score/rehearsalMarks entry at its first global measure. The MusicXML encoder emits a <direction placement="above"><direction-type><rehearsal>LABEL</rehearsal></direction-type></direction> block at that measure — only in the first part (rehearsal marks are system objects, like tempo directions). Being a system object placed above the top staff, the mark is tied to the section, not an instrument line, and avoids colliding with staff notation.
Important: Use single-letter labels (
"A","B","C"). Editors render rehearsal marks as an auto-advanced letter sequence and commonly re-sequence imported marks, hiding any custom text — so a label like"Intro"may display as"A". The encoder also offersScore/toMusicXMLString(divisions:collapseRedundantDynamics:rehearsalMarksAsStaffText:)withrehearsalMarksAsStaffText: true, which emits the labels as boxed<words>staff text (rendered verbatim), but that attaches to a staff and can collide with notation — prefer letters and the default<rehearsal>.
Rehearsal marks are emit-only in v1: Score/fromMusicXML(data:) does not reconstruct them. The decoded Score/rehearsalMarks is always empty after a round-trip.
Part padding (all parts bar-align to the section)
A section's measure span is the longest part rounded up to whole bars under the section's effective meter. Every part in the section is rest-padded to that span automatically, so all parts share the same bar count and the section's last barline is aligned across the score:
- A present part shorter than the section span is padded with rests from its last note to the section's final barline (e.g. a 1-bar part in a section whose longest part is 3 bars is padded to 3 bars).
- A part absent from the section is TACET: it receives one whole-measure rest per bar of the section.
No authoring action is required — this happens during section lowering. The fill is bar-aligned to the section's effective meter.
v1 constraints
-
Cross-section repeats — a repeat structure on a section is shifted into the global map, but a repeat that SPANS two sections (e.g. a forward repeat at the last bar of one section and a backward repeat at the first bar of the next) is not supported. The two repeat barlines will appear in the MusicXML as separate, adjacent barlines, not as a unified spanning repeat.
-
Anacrusis — only the FIRST section's
meterMap.anacrusisis honored in the assembled score. A later section's anacrusis is silently set to.zeroduring lowering. Pickup bars inside a non-first section require manual rest padding to align with the section's beat span. -
Per-part meterMap inside a section — a
ScorePartwith its ownmeterMapoverride inside aScoreSectionis accepted, but the section's beat-span calculation uses only the section-level meter (not the per-part meter). The per-part override is preserved on the final flat part and affects MusicXML encoding for that part, but TACET fill lengths for other instruments are derived from the section-level map. -
Decode —
ScoreSectionvalues are not reconstructed from MusicXML. The section boundaries and rehearsal-mark labels are emit-only; the decodedScore/rehearsalMarksmap is always empty.
Page layout
PageLayout lets a Score carry page-size, orientation, margin, and scaling information for MusicXML export. When the score's Score/pageLayout property is non-nil, the encoder emits a <defaults> block immediately after <score-partwise version="4.0"> and before <part-list>. When it is nil (the default) no <defaults> block is emitted and the output is byte-identical to scores built without this property.
Usage
// Simple: letter paper, portrait, default margins and scaling.
let letterScore = Score(bpm: 120, pageLayout: PageLayout()) {
Part("Piano") { Note(.c, 4, dur: .quarter) }
}
// A4 landscape with custom margins.
let a4Score = Score(
bpm: 120,
pageLayout: PageLayout(
size: .a4,
orientation: .landscape,
margins: PageLayout.Margins(uniformMillimeters: 20.0)
)
) {
Part("Piano") { Note(.c, 4, dur: .quarter) }
}
// Section-based score with page layout.
let sectionScore = Score(bpm: 120, pageLayout: PageLayout(size: .a4)) {
Section("Intro") { Part("lead") { Note(.c, 4, dur: .quarter) } }
}
Tenths model
MusicXML page dimensions are expressed in tenths of a staff-space — a unit that scales with notation size. PageLayout/Scaling declares the mapping: millimeters physical mm correspond to tenths staff-space tenths. The conversion factor is tenths / millimeters tenths-per-mm.
Default scaling: 7.0 mm = 40.0 tenths (≈ 5.714 tenths/mm). This is a common notation default where one staff space — the distance between adjacent staff lines — is 1.75 mm, so the four staff spaces of a five-line staff span 7 mm.
All values stored in PageLayout are in physical millimeters; the encoder converts them to tenths automatically.
Orientation encoding
MusicXML has no explicit landscape flag. Orientation is encoded by swapping the physical width and height values in <page-width> / <page-height>:
- Portrait:
<page-width>= portrait width,<page-height>= portrait height. - Landscape:
<page-width>= portrait height,<page-height>= portrait width.
All PageLayout/PageSize portrait dimensions follow the convention width ≤ height.
Standard page sizes
PageLayout/PageSize |
Portrait width (mm) | Portrait height (mm) |
|---|---|---|
.letter |
215.9 | 279.4 |
.legal |
215.9 | 355.6 |
.tabloid |
279.4 | 431.8 |
.a4 |
210 | 297 |
.a3 |
297 | 420 |
.custom(widthMillimeters:heightMillimeters:) |
caller-supplied | caller-supplied |
Margins
Margins are stored in millimeters as PageLayout/Margins and converted to tenths during encoding.
When PageLayout/oddMargins and PageLayout/evenMargins are equal (the symmetric-init case), the encoder emits a single <page-margins type="both"> block. When they differ, it emits two blocks: <page-margins type="odd"> and <page-margins type="even">.
Default margin: 15 mm all sides.
Emitted XML
<score-partwise version="4.0">
<defaults>
<scaling>
<millimeters>7</millimeters>
<tenths>40</tenths>
</scaling>
<page-layout>
<page-height>1696.457</page-height> <!-- A4 portrait, default scaling -->
<page-width>1200</page-width>
<page-margins type="both">
<left-margin>85.714</left-margin>
<right-margin>85.714</right-margin>
<top-margin>85.714</top-margin>
<bottom-margin>85.714</bottom-margin>
</page-margins>
</page-layout>
</defaults>
<part-list>
…
</part-list>
…
Decode limitation
<defaults> / <page-layout> is not parsed on decode — this is emit-only in v1. Score/fromMusicXML(data:) silently skips the <defaults> block; Score/pageLayout is always nil after a round-trip.
See Also
ScoreScorePartScoreSectionScoreSectionBuilderScoreElementScoreEventScorePlayerScoreBuilderScorePartBuilderPitchLetterAccidentalNoteNameNoteDurationDynamicArticulationFractionClefKeySignatureRepeatStructureEndingMusicXMLErrorMIDIFileLyrebirdClockLyrebirdRoutine- doc:ExternalIntegrations
- doc:RoutineTask