Music XML updates and optimizations
This commit is contained in:
@@ -134,6 +134,37 @@ struct BinaryOpGeneratorTests {
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 7.0 })
|
||||
}
|
||||
|
||||
// Order-sensitive operands: a flipped vDSP subtract/divide argument order
|
||||
// would produce the reciprocal/negated value, so these lock the orientation.
|
||||
|
||||
@Test func scalarMinusGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (1.0 as Double) - ConstantAudioGen(0.25)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.75 })
|
||||
}
|
||||
|
||||
@Test func scalarDividedByGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = (1.0 as Double) / ConstantAudioGen(4.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 0.25 })
|
||||
}
|
||||
|
||||
@Test func generatorMinusGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(3.0) - ConstantAudioGen(2.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 1.0 })
|
||||
}
|
||||
|
||||
@Test func generatorDividedByGenerator() {
|
||||
let count: Int = 8
|
||||
let gen: BinaryOpGenerator = ConstantAudioGen(8.0) / ConstantAudioGen(2.0)
|
||||
let samples: [[Double]] = gen.calculatedSamples(graph: graph, count: count)
|
||||
#expect(samples[0].prefix(count).allSatisfy { $0 == 4.0 })
|
||||
}
|
||||
}
|
||||
|
||||
// MARK: - Multi-channel broadcast
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// MusicXMLBarlineExactFillTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
/// Regression coverage for two MusicXML-export defects exposed by sectioned
|
||||
/// scores with rest-padded short parts.
|
||||
///
|
||||
/// 1. **Barline-exact-fill rounding.** In the single-voice encoder, when a
|
||||
/// note/rest that crosses a barline has its FINAL piece land exactly on the
|
||||
/// next barline (`leftover` and the measure's `remaining` capacity reach zero
|
||||
/// together), the measure was left open with `remaining == 0`. The next
|
||||
/// sounding atom could then neither fit nor split cleanly: the split loop
|
||||
/// emitted a spurious `max(1, …)` one-division piece before the bar finally
|
||||
/// closed, tying it forward and shifting every later note by one division
|
||||
/// (visually turning constant 4/4 bars into 5/4).
|
||||
/// 2. **Non-bar-aligned rest padding.** Section auto-padding decomposed the
|
||||
/// whole gap greedily into the largest representable rests (a 21-beat gap
|
||||
/// became three double-dotted-whole rests) with no bar alignment, so the
|
||||
/// encoder split them into metrically-wrong fragments (a quarter + dotted-half
|
||||
/// rest crossing the mid-bar strong beat) instead of clean whole-measure rests.
|
||||
@MainActor
|
||||
@Suite("MusicXML — barline-exact-fill rounding")
|
||||
struct MusicXMLBarlineExactFillTests {
|
||||
|
||||
/// Split a part's body into `(measureNumber, measureBody)` pairs using the
|
||||
/// codebase's string-splitting idiom (no regex).
|
||||
private func measureBlocks(_ xml: String, part pid: String) -> [(number: String, body: String)] {
|
||||
guard let partStart: Range<String.Index> = xml.range(of: "<part id=\"\(pid)\">"),
|
||||
let partEnd: Range<String.Index> = xml.range(
|
||||
of: "</part>",
|
||||
range: partStart.upperBound..<xml.endIndex
|
||||
) else {
|
||||
return []
|
||||
}
|
||||
let partBody: String = String(xml[partStart.upperBound..<partEnd.lowerBound])
|
||||
var blocks: [(number: String, body: String)] = []
|
||||
let chunks: [String] = partBody.components(separatedBy: "<measure number=\"")
|
||||
for chunk: String in chunks.dropFirst() {
|
||||
guard let quote: Range<String.Index> = chunk.range(of: "\"") else { continue }
|
||||
let number: String = String(chunk[chunk.startIndex..<quote.lowerBound])
|
||||
blocks.append((number: number, body: chunk))
|
||||
}
|
||||
return blocks
|
||||
}
|
||||
|
||||
/// Sum the `<duration>` of every non-chord `<note>` in a measure body.
|
||||
private func durationSum(_ measureBody: String) -> Int {
|
||||
var total: Int = 0
|
||||
let notes: [String] = measureBody.components(separatedBy: "<note>")
|
||||
for note: String in notes.dropFirst() {
|
||||
if note.contains("<chord/>") { continue }
|
||||
guard let open: Range<String.Index> = note.range(of: "<duration>"),
|
||||
let close: Range<String.Index> = note.range(
|
||||
of: "</duration>",
|
||||
range: open.upperBound..<note.endIndex
|
||||
),
|
||||
let value: Int = Int(note[open.upperBound..<close.lowerBound]) else {
|
||||
continue
|
||||
}
|
||||
total += value
|
||||
}
|
||||
return total
|
||||
}
|
||||
|
||||
/// A breve (8 beats) in 4/4 exactly fills two bars; the following whole note
|
||||
/// must land cleanly on bar 3, NOT be split into a 1-division sliver in bar 2.
|
||||
@Test func breveThenWholeNoteNoSliver() {
|
||||
let divisions: Int = 480
|
||||
let score: Score = Score(bpm: 120, timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead") {
|
||||
Note(.c, 4, dur: .doubleWhole) // fills bars 1-2 exactly (8 beats)
|
||||
Note(.d, 4, dur: .whole) // must be bar 3, all 4 beats
|
||||
Note(.e, 4, dur: .whole) // bar 4
|
||||
}
|
||||
}
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: "P1") {
|
||||
#expect(
|
||||
durationSum(block.body) == 4 * divisions,
|
||||
"measure \(block.number) holds \(durationSum(block.body)) divisions, expected \(4 * divisions)"
|
||||
)
|
||||
}
|
||||
// No one-division phantom note anywhere.
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
|
||||
/// The sectioned-score path that originally surfaced the bug: a part with a
|
||||
/// long rest-pad tail that ends exactly on a barline, immediately followed by
|
||||
/// a new section whose note enters on the downbeat. Models the
|
||||
/// melody-section-then-chord-section boundary.
|
||||
@Test func sectionPadTailThenDownbeatNoteNoSliver() {
|
||||
let divisions: Int = 480
|
||||
let melody: ScoreSection = Section(
|
||||
"A",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
// Short part: 23 beats of content, padded to the section's 44-beat
|
||||
// span (max part length) with rests whose tail ends on a barline.
|
||||
Part("lead") {
|
||||
for _: Int in 0..<23 { Note(.c, 4, dur: .quarter) }
|
||||
}
|
||||
// Long part forces the section span to 11 bars (44 beats).
|
||||
Part("bass") {
|
||||
for _: Int in 0..<44 { Note(.c, 2, dur: .quarter) }
|
||||
}
|
||||
}
|
||||
let chords: ScoreSection = Section(
|
||||
"B",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
Part("lead") { Note(.f, 5, dur: .whole) }
|
||||
Part("bass") { Note(.f, 2, dur: .whole) }
|
||||
}
|
||||
let score: Score = Score(sections: [melody, chords], bpm: 120)
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
for pid: String in ["P1", "P2"] {
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: pid) {
|
||||
#expect(
|
||||
durationSum(block.body) == 4 * divisions,
|
||||
"\(pid) measure \(block.number) holds \(durationSum(block.body)) divisions, expected \(4 * divisions)"
|
||||
)
|
||||
}
|
||||
}
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
|
||||
/// A short part padded to its section's beat span must fill whole empty bars
|
||||
/// with single whole-measure rests, not greedy largest-value rests that
|
||||
/// straddle barlines and fragment into metrically-wrong groupings (a quarter
|
||||
/// + dotted-half rest crossing the mid-bar strong beat reads as malformed).
|
||||
@Test func sectionPadFillsWholeBarsAsMeasureRests() {
|
||||
let divisions: Int = 480
|
||||
// 23 quarter-beats of content → ends mid-bar (bar 6, beat 3). The 44-beat
|
||||
// section span (set by the long part) leaves a 21-beat pad spanning the
|
||||
// rest of bar 6 plus full bars 7-11.
|
||||
let section: ScoreSection = Section(
|
||||
"A",
|
||||
meterMap: MeterMap(TimeSignature(4, 4))
|
||||
) {
|
||||
Part("lead") { for _: Int in 0..<23 { Note(.c, 4, dur: .quarter) } }
|
||||
Part("bass") { for _: Int in 0..<44 { Note(.c, 2, dur: .quarter) } }
|
||||
}
|
||||
let score: Score = Score(sections: [section], bpm: 120)
|
||||
let xml: String = score.toMusicXMLString(divisions: divisions)
|
||||
|
||||
// The lead part's empty bars 7-11 must each be a whole-measure rest.
|
||||
var measureRestBars: Set<String> = []
|
||||
for block: (number: String, body: String) in measureBlocks(xml, part: "P1") {
|
||||
if block.body.contains("<rest measure=\"yes\"") {
|
||||
measureRestBars.insert(block.number)
|
||||
}
|
||||
}
|
||||
for bar: String in ["7", "8", "9", "10", "11"] {
|
||||
#expect(
|
||||
measureRestBars.contains(bar),
|
||||
"bar \(bar) should be a single whole-measure rest"
|
||||
)
|
||||
}
|
||||
// No fragmented one-division phantom anywhere.
|
||||
#expect(!xml.contains("<duration>1</duration>"))
|
||||
}
|
||||
}
|
||||
@@ -429,6 +429,29 @@ struct SVFTests {
|
||||
#expect(!allSame, "SVF.Audio with LFO-driven freq must produce non-constant output")
|
||||
}
|
||||
|
||||
// MARK: 18b. Generator-driven freq above the sample rate stays stable (no divergence)
|
||||
|
||||
@Test func freqAboveSampleRateStaysFinite() {
|
||||
// A generator cutoff swept well past the sample rate drives sin(π·freq/sr)
|
||||
// negative; the coefficient must clamp to 0 rather than produce a negative
|
||||
// f that diverges the Chamberlin recurrence.
|
||||
let hugeFreq: Double = 2.0 * sampleRate
|
||||
let lfo: OscSin.Audio = OscSin.Audio(freq: 0.5, mul: hugeFreq, add: hugeFreq)
|
||||
let input: OscSin.Audio = OscSin.Audio(freq: 100.0, mul: 0.5)
|
||||
let svf: SVF.Audio = SVF.Audio(input: input, freq: lfo, q: svfButterworthQ)
|
||||
|
||||
var allFinite: Bool = true
|
||||
for _ in 0..<8 {
|
||||
let g: SynthGraph = makeSynthGraph(engine: engine)
|
||||
let result: [[Double]] = svf.calculatedSamples(graph: g, count: blockSize)
|
||||
for ch: Int in 0..<result.count {
|
||||
for s: Double in result[ch].prefix(blockSize) where !s.isFinite { allFinite = false }
|
||||
}
|
||||
advanceBlock(engine)
|
||||
}
|
||||
#expect(allFinite, "SVF.Audio with above-Nyquist generator freq must not diverge")
|
||||
}
|
||||
|
||||
// MARK: 19. Q driven by audio generator (per-sample q path)
|
||||
|
||||
@Test func qDrivenByAudioGenerator() {
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
// ScorePartOffsetTests.swift
|
||||
// Lyrebird
|
||||
//
|
||||
// Copyright (c) 2026 Joshua Parmenter / realizedsound
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
import Testing
|
||||
import Foundation
|
||||
@testable @_spi(LyrebirdExtensions) import LyrebirdSynth
|
||||
|
||||
// MARK: - ScorePartOffsetTests
|
||||
|
||||
@MainActor
|
||||
@Suite("ScorePart entrance offset")
|
||||
struct ScorePartOffsetTests {
|
||||
|
||||
// MARK: - Flat-score offset (no sections)
|
||||
|
||||
@Test func measuresOffsetDelaysEntranceWholeBars() {
|
||||
// 2 bars of 4/4 lead = 8 quarter beats before the first note.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .measures(2)) {
|
||||
Note(.c, 5, dur: .whole)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 8.0)
|
||||
}
|
||||
|
||||
@Test func beatsOffsetDelaysEntranceMidBar() {
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .beats(2.5)) {
|
||||
Note(.c, 5, dur: .quarter)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 2.5)
|
||||
}
|
||||
|
||||
@Test func fractionOffsetIsExact() {
|
||||
let score: Score = Score {
|
||||
Part("lead", offset: .fraction(Fraction(3, 2))) {
|
||||
Note(.c, 5, dur: .quarter)
|
||||
}
|
||||
}
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 1.5)
|
||||
}
|
||||
|
||||
@Test func nonPositiveOffsetIsNoOp() {
|
||||
// Every case's documented "negative or zero → no offset" contract.
|
||||
let zeroMeasures: Score = Score {
|
||||
Part("a", offset: .measures(0)) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let negBeats: Score = Score {
|
||||
Part("b", offset: .beats(-3)) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let zeroFraction: Score = Score {
|
||||
Part("c", offset: .fraction(Fraction(0, 1))) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
let negFraction: Score = Score {
|
||||
Part("d", offset: .fraction(Fraction(-1, 2))) { Note(.c, 5, dur: .quarter) }
|
||||
}
|
||||
#expect(zeroMeasures.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(negBeats.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(zeroFraction.parts[0].flatten()[0].beat == 0.0)
|
||||
#expect(negFraction.parts[0].flatten()[0].beat == 0.0)
|
||||
}
|
||||
|
||||
// MARK: - Consumed-into-rests invariant
|
||||
|
||||
@Test func offsetIsConsumedNilOnAssembledScore() {
|
||||
let score: Score = Score {
|
||||
Part("lead", offset: .measures(2)) { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
#expect(score.parts[0].offset == nil)
|
||||
}
|
||||
|
||||
@Test func noOffsetByteIdenticalToExplicitNil() {
|
||||
let withNil: Score = Score {
|
||||
Part("lead") { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
let explicitNil: Score = Score {
|
||||
Part("lead", offset: nil) { Note(.c, 5, dur: .whole) }
|
||||
}
|
||||
#expect(withNil.toMusicXMLString() == explicitNil.toMusicXMLString())
|
||||
}
|
||||
|
||||
// MARK: - Section offset
|
||||
|
||||
@Test func sectionOffsetDelaysEntranceWithinSection() {
|
||||
// Single-section score: section start == beat 0, so the offset part's
|
||||
// first event lands at the offset (2 bars = beat 8).
|
||||
let score: Score = Score {
|
||||
Section("A") {
|
||||
Part("violin") {
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
Note(.g, 5, dur: .whole)
|
||||
}
|
||||
Part("cello", offset: .measures(2)) {
|
||||
Note(.c, 3, dur: .whole)
|
||||
}
|
||||
}
|
||||
}
|
||||
let violin: [ScoreEvent] = score.parts[0].flatten()
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(violin[0].beat == 0.0)
|
||||
#expect(cello[0].beat == 8.0)
|
||||
}
|
||||
|
||||
@Test func offsetCountsTowardSectionSpan() {
|
||||
// Cello: 3-bar offset + 1 whole note = 4 bars; violin only 1 bar.
|
||||
// The section must size to the longest = 4 bars (16 quarter beats).
|
||||
let score: Score = Score {
|
||||
Section("A") {
|
||||
Part("violin") { Note(.g, 5, dur: .whole) }
|
||||
Part("cello", offset: .measures(3)) { Note(.c, 3, dur: .whole) }
|
||||
}
|
||||
}
|
||||
// Both parts pad to the same section span. Violin's last (padded) beat
|
||||
// and the cello's entrance prove the span grew to 4 bars.
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(cello[0].beat == 12.0)
|
||||
// Violin part sounding end = its single whole note (4 beats).
|
||||
#expect(score.parts[0].lastBeat() == 4.0)
|
||||
// The encoded score has 4 measures for both parts.
|
||||
let xml: String = score.toMusicXMLString()
|
||||
let violinMeasures: Int = xml.components(separatedBy: "<measure number=\"4\"").count - 1
|
||||
#expect(violinMeasures >= 1)
|
||||
}
|
||||
|
||||
@Test func polymetricPartOffsetUsesOwnMeter() {
|
||||
// Cello in 3/4 with a 2-bar offset = 6 quarter beats before entrance.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Section("A") {
|
||||
Part("violin") { Note(.g, 5, dur: .whole) }
|
||||
Part("cello", meterMap: MeterMap(TimeSignature(3, 4)), offset: .measures(2)) {
|
||||
Note(.c, 3, dur: .quarter)
|
||||
}
|
||||
}
|
||||
}
|
||||
let cello: [ScoreEvent] = score.parts[1].flatten()
|
||||
#expect(cello[0].beat == 6.0)
|
||||
}
|
||||
|
||||
@Test func offsetThenFillMeasureFillsFromDelayedEntrance() {
|
||||
// Offset 1 bar (4 beats), then a half note, then FillMeasure → the fill
|
||||
// should complete bar 2 (the entrance bar), i.e. 2 more beats of rest.
|
||||
let score: Score = Score(timeSignature: TimeSignature(4, 4)) {
|
||||
Part("lead", offset: .measures(1)) {
|
||||
Note(.c, 5, dur: .half)
|
||||
FillMeasure()
|
||||
}
|
||||
}
|
||||
// First (and only) note at beat 4; total part span fills to end of bar 2
|
||||
// = 8 beats. lastBeat = note end (4 + 0.5*2? half note = 2 beats) = 6.
|
||||
let events: [ScoreEvent] = score.parts[0].flatten()
|
||||
#expect(events.count == 1)
|
||||
#expect(events[0].beat == 4.0)
|
||||
#expect(events[0].beat + events[0].duration == 6.0)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user