sim-lib-music-transform 0.1.4

Pitch, time, pattern, and diagnostic transforms over canonical SIM music objects.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
//! Exact identity-preserving staff transforms and their audit reports.

mod additive;
mod composition;
mod leading;
mod progression;
mod register;

use std::collections::BTreeSet;

use sim_lib_music_core::{
    Articulation, Channel, ObjectId, Pitch, Staff, StaffNote, StaffVoice, Time,
};

use crate::TransformError;

pub use additive::*;
pub use composition::*;
pub use leading::*;
pub use progression::*;
pub use register::*;

/// One reversible or explicitly destructive change made by an exact transform.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum MusicTransformChange {
    /// A note onset changed.
    Onset {
        /// Affected event.
        event_id: ObjectId,
        /// Exact prior onset.
        before: Time,
        /// Exact new onset.
        after: Time,
    },
    /// A note duration changed.
    Duration {
        /// Affected event.
        event_id: ObjectId,
        /// Exact prior duration.
        before: Time,
        /// Exact new duration.
        after: Time,
    },
    /// A note articulation changed.
    Articulation {
        /// Affected event.
        event_id: ObjectId,
        /// Prior articulation.
        before: Articulation,
        /// New articulation.
        after: Articulation,
    },
    /// A note pitch changed while its pitch class stayed fixed.
    Pitch {
        /// Affected event.
        event_id: ObjectId,
        /// Prior pitch.
        before: Pitch,
        /// New pitch.
        after: Pitch,
    },
    /// A note moved to another voice.
    Voice {
        /// Affected event.
        event_id: ObjectId,
        /// Prior voice identity.
        before: ObjectId,
        /// New voice identity.
        after: ObjectId,
    },
    /// Voice separation allocated a new voice identity.
    CreatedVoice {
        /// New identity.
        voice_id: ObjectId,
        /// Original voice from which it was split.
        source_voice_id: ObjectId,
    },
    /// Repetition derived fresh note/event identities for a later occurrence.
    RepeatedIdentity {
        /// Original logical note identity.
        source_note_id: ObjectId,
        /// Original event identity.
        source_event_id: ObjectId,
        /// Derived logical note identity.
        repeated_note_id: ObjectId,
        /// Derived event identity.
        repeated_event_id: ObjectId,
        /// Zero-based occurrence index, always greater than zero.
        occurrence: usize,
    },
    /// A rhythm mask or slice removed an event.
    Removed {
        /// Removed logical note identity.
        note_id: ObjectId,
        /// Removed event identity.
        event_id: ObjectId,
        /// Stable reason for removal.
        reason: &'static str,
    },
    /// An additive transform introduced a new independent voice.
    AddedVoice {
        /// New voice identity.
        voice_id: ObjectId,
    },
    /// An additive transform introduced a note without changing source notes.
    AddedNote {
        /// Containing voice.
        voice_id: ObjectId,
        /// New logical note identity.
        note_id: ObjectId,
        /// New event identity.
        event_id: ObjectId,
    },
    /// Reversing an additive transform removed its introduced voice.
    RemovedVoice {
        /// Removed voice identity.
        voice_id: ObjectId,
    },
}

/// Exact transform value paired with identity and change evidence.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct MusicTransform<T> {
    /// Transformed value.
    pub value: T,
    /// Identities still present after the transform.
    pub preserved: Vec<ObjectId>,
    /// Complete ordered edits performed by the transform.
    pub changes: Vec<MusicTransformChange>,
}

impl<T> MusicTransform<T> {
    /// Returns `true` when the transform left its input unchanged.
    pub fn is_unchanged(&self) -> bool {
        self.changes.is_empty()
    }
}

/// Exact half-open sustain-pedal interval.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub struct SustainSpan {
    /// Pedal-down time.
    pub start: Time,
    /// Pedal-up time.
    pub end: Time,
    /// Optional channel restriction.
    pub channel: Option<Channel>,
}

impl SustainSpan {
    /// Builds a sustain span; validity is checked when applying it.
    pub fn new(start: Time, end: Time, channel: Option<Channel>) -> Self {
        Self {
            start,
            end,
            channel,
        }
    }
}

/// Ordering used for simultaneous notes during delayed-note voice separation.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum DelayedNoteOrder {
    /// Stable pitch/event identity order.
    Stable,
    /// Higher pitches receive earlier voice slots.
    HighestFirst,
    /// Lower pitches receive earlier voice slots.
    LowestFirst,
}

/// Periodic exact-onset rhythm mask.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RhythmMask {
    step: Time,
    pattern: Vec<bool>,
}

impl RhythmMask {
    /// Builds a non-empty mask with a positive exact step.
    pub fn new(step: Time, pattern: Vec<bool>) -> Result<Self, TransformError> {
        if step <= Time::from_integer(0) {
            return Err(TransformError::InvalidFactor);
        }
        if pattern.is_empty() {
            return Err(TransformError::InvalidTransformOutput {
                transform: "rhythm-mask",
                reason: "pattern must not be empty",
            });
        }
        Ok(Self { step, pattern })
    }

    /// Returns the exact duration of one mask slot.
    pub fn step(&self) -> Time {
        self.step
    }

    /// Returns the periodic keep/drop pattern.
    pub fn pattern(&self) -> &[bool] {
        &self.pattern
    }

    fn keeps(&self, onset: Time) -> bool {
        let slots = onset / self.step;
        let slot = slots.numer().div_euclid(*slots.denom());
        self.pattern[slot.rem_euclid(self.pattern.len() as i64) as usize]
    }
}

/// Extends note releases that occur while one of `spans` is active.
///
/// Onsets, pitches, identities, and exact rational time are retained. A note
/// released inside overlapping sustain spans is extended through the furthest
/// applicable pedal-up boundary. Transitive extension is independent of the
/// order in which spans are supplied.
pub fn sustain_staff(
    staff: &Staff,
    spans: &[SustainSpan],
) -> Result<MusicTransform<Staff>, TransformError> {
    validate_spans(spans)?;
    transform_notes(staff, |mut note, changes| {
        let before = note.note.duration;
        let mut end = note.end();
        loop {
            let prior_end = end;
            for span in spans {
                if span
                    .channel
                    .is_none_or(|channel| channel == note.note.channel)
                    && end >= span.start
                    && end < span.end
                    && note.onset < span.end
                {
                    end = span.end;
                }
            }
            if end == prior_end {
                break;
            }
        }
        note.note.duration = end - note.onset;
        if note.note.duration != before {
            changes.push(MusicTransformChange::Duration {
                event_id: note.event_id.clone(),
                before,
                after: note.note.duration,
            });
        }
        note
    })
}

/// Connects each note in a voice to its next onset and marks it legato.
///
/// Existing overlaps are not shortened. The final note of each voice is left
/// unchanged because there is no following articulation target.
pub fn slur_staff(staff: &Staff) -> Result<MusicTransform<Staff>, TransformError> {
    let mut voices = staff.voices.clone();
    let mut changes = Vec::new();
    for voice in &mut voices {
        voice.notes.sort_by(note_order);
        for index in 0..voice.notes.len().saturating_sub(1) {
            let next_onset = voice.notes[index + 1].onset;
            let note = &mut voice.notes[index];
            if note.end() < next_onset {
                let before = note.note.duration;
                note.note.duration = next_onset - note.onset;
                changes.push(MusicTransformChange::Duration {
                    event_id: note.event_id.clone(),
                    before,
                    after: note.note.duration,
                });
            }
            if note.note.articulation != Articulation::Legato {
                let before = note.note.articulation;
                note.note.articulation = Articulation::Legato;
                changes.push(MusicTransformChange::Articulation {
                    event_id: note.event_id.clone(),
                    before,
                    after: Articulation::Legato,
                });
            }
        }
    }
    finish(voices, changes)
}

/// Expands every onset, note duration, and voice span by a positive exact factor.
pub fn expand_staff(staff: &Staff, factor: Time) -> Result<MusicTransform<Staff>, TransformError> {
    if factor <= Time::from_integer(0) {
        return Err(TransformError::InvalidFactor);
    }
    let mut voices = staff.voices.clone();
    let mut changes = Vec::new();
    for voice in &mut voices {
        voice.duration *= factor;
        for note in &mut voice.notes {
            let onset = note.onset;
            let duration = note.note.duration;
            note.onset *= factor;
            note.note.duration *= factor;
            if note.onset != onset {
                changes.push(MusicTransformChange::Onset {
                    event_id: note.event_id.clone(),
                    before: onset,
                    after: note.onset,
                });
            }
            if note.note.duration != duration {
                changes.push(MusicTransformChange::Duration {
                    event_id: note.event_id.clone(),
                    before: duration,
                    after: note.note.duration,
                });
            }
        }
    }
    finish(voices, changes)
}

/// Splits delayed overlapping notes into monophonic voices without moving them.
///
/// Exact abutment (`previous.end == next.onset`) remains in one voice. The first
/// output retains the original voice id; additional lines receive deterministic
/// derived ids, while every note/event identity is preserved.
pub fn separate_delayed_notes(
    staff: &Staff,
    order: DelayedNoteOrder,
) -> Result<MusicTransform<Staff>, TransformError> {
    let mut output = Vec::new();
    let mut changes = Vec::new();
    for voice in &staff.voices {
        let mut notes = voice.notes.clone();
        notes.sort_by(|left, right| delayed_order(left, right, order));
        let mut lines = Vec::<StaffVoice>::new();
        for mut note in notes {
            let slot = lines.iter().position(|line| {
                line.notes
                    .last()
                    .is_none_or(|last| last.end() <= note.onset)
            });
            let index = slot.unwrap_or(lines.len());
            if index == lines.len() {
                let id = if index == 0 {
                    voice.id.clone()
                } else {
                    ObjectId::new(format!("{}/delayed-{index}", voice.id))
                        .expect("derived voice identity is non-empty")
                };
                if index > 0 {
                    changes.push(MusicTransformChange::CreatedVoice {
                        voice_id: id.clone(),
                        source_voice_id: voice.id.clone(),
                    });
                }
                lines.push(StaffVoice {
                    id,
                    name: if index == 0 {
                        voice.name.clone()
                    } else {
                        format!("{} delayed {}", voice.name, index + 1)
                    },
                    duration: voice.duration,
                    notes: Vec::new(),
                });
            }
            let destination = lines[index].id.clone();
            if note.voice_id != destination {
                changes.push(MusicTransformChange::Voice {
                    event_id: note.event_id.clone(),
                    before: note.voice_id.clone(),
                    after: destination.clone(),
                });
                note.voice_id = destination;
            }
            lines[index].notes.push(note);
        }
        if lines.is_empty() {
            lines.push(voice.clone());
        }
        output.extend(lines);
    }
    finish(output, changes)
}

fn transform_notes(
    staff: &Staff,
    mut f: impl FnMut(StaffNote, &mut Vec<MusicTransformChange>) -> StaffNote,
) -> Result<MusicTransform<Staff>, TransformError> {
    let mut voices = staff.voices.clone();
    let mut changes = Vec::new();
    for voice in &mut voices {
        voice.notes = voice
            .notes
            .drain(..)
            .map(|note| f(note, &mut changes))
            .collect();
        if let Some(end) = voice.notes.iter().map(StaffNote::end).max() {
            voice.duration = voice.duration.max(end);
        }
    }
    finish(voices, changes)
}

fn finish(
    voices: Vec<StaffVoice>,
    changes: Vec<MusicTransformChange>,
) -> Result<MusicTransform<Staff>, TransformError> {
    let staff = Staff::new(voices).map_err(TransformError::InvalidStaff)?;
    let mut created = BTreeSet::new();
    for change in &changes {
        match change {
            MusicTransformChange::CreatedVoice { voice_id, .. } => {
                created.insert(voice_id);
            }
            MusicTransformChange::RepeatedIdentity {
                repeated_note_id,
                repeated_event_id,
                ..
            } => {
                created.insert(repeated_note_id);
                created.insert(repeated_event_id);
            }
            MusicTransformChange::AddedVoice { voice_id } => {
                created.insert(voice_id);
            }
            MusicTransformChange::AddedNote {
                note_id, event_id, ..
            } => {
                created.insert(note_id);
                created.insert(event_id);
            }
            _ => {}
        }
    }
    Ok(MusicTransform {
        preserved: staff
            .object_ids()
            .into_iter()
            .filter(|id| !created.contains(id))
            .collect(),
        value: staff,
        changes,
    })
}

fn validate_spans(spans: &[SustainSpan]) -> Result<(), TransformError> {
    if spans
        .iter()
        .any(|span| span.start < Time::from_integer(0) || span.end < span.start)
    {
        return Err(TransformError::InvalidTransformOutput {
            transform: "sustain",
            reason: "sustain spans must satisfy 0 <= start <= end",
        });
    }
    Ok(())
}

fn note_order(left: &StaffNote, right: &StaffNote) -> std::cmp::Ordering {
    left.onset
        .cmp(&right.onset)
        .then_with(|| left.note.pitch.cmp(&right.note.pitch))
        .then_with(|| left.event_id.cmp(&right.event_id))
}

fn delayed_order(
    left: &StaffNote,
    right: &StaffNote,
    order: DelayedNoteOrder,
) -> std::cmp::Ordering {
    left.onset.cmp(&right.onset).then_with(|| {
        let pitch = left.note.pitch.cmp(&right.note.pitch);
        let pitch = match order {
            DelayedNoteOrder::Stable | DelayedNoteOrder::LowestFirst => pitch,
            DelayedNoteOrder::HighestFirst => pitch.reverse(),
        };
        pitch.then_with(|| left.event_id.cmp(&right.event_id))
    })
}