Repository Public
1//! ORIX Sonata2//! File: crates/sonata-interop/src/score.rs3//! Description: Notation model derived from a Program: measures, voices, rests, ties across bar4//! lines, dotted values, simple tuplets and pitch spelling. Shared by the MusicXML writer and the5//! Score space of the app. This is a faithful transcription, not professional engraving.6//!7//! Author: Simon-Pierre Boucher8//! Contact: contact@spboucher.ai910use serde::{Deserialize, Serialize};11use sonata_ir::{Articulation, Key, Mode, Program, Rational, Span, Track, TrackKind};1213fn r(n: i64, d: i64) -> Rational {14 Rational::new(n, d).unwrap_or(Rational::ZERO)15}16fn add(a: Rational, b: Rational) -> Rational {17 a.checked_add(b).unwrap_or(a)18}19fn sub(a: Rational, b: Rational) -> Rational {20 a.checked_sub(b).unwrap_or(Rational::ZERO)21}22fn mul(a: Rational, b: Rational) -> Rational {23 a.checked_mul(b).unwrap_or(a)24}2526/// Note values from the whole note (0) down to the 128th (7).27#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]28#[serde(rename_all = "snake_case")]29pub enum NoteType {30 Whole,31 Half,32 Quarter,33 Eighth,34 Sixteenth,35 ThirtySecond,36 SixtyFourth,37 OneTwentyEighth,38}3940impl NoteType {41 pub const ALL: [NoteType; 8] = [42 NoteType::Whole,43 NoteType::Half,44 NoteType::Quarter,45 NoteType::Eighth,46 NoteType::Sixteenth,47 NoteType::ThirtySecond,48 NoteType::SixtyFourth,49 NoteType::OneTwentyEighth,50 ];51 /// Length in whole notes.52 pub fn length(self) -> Rational {53 r(1, 1 << (self as u32))54 }55 /// MusicXML `<type>` text.56 pub fn xml_name(self) -> &'static str {57 ["whole", "half", "quarter", "eighth", "16th", "32nd", "64th", "128th"][self as usize]58 }59 /// Number of flags or beams of the value.60 pub fn flags(self) -> u8 {61 (self as u8).saturating_sub(2)62 }63}6465#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]66pub struct SpelledPitch {67 /// 0 = C, 1 = D, ... 6 = B.68 pub step: u8,69 /// Semitones of alteration; fractional for microtones.70 pub alter: f64,71 pub octave: i8,72 /// Written MIDI pitch (transposition applied).73 pub midi: f64,74 /// Identifier of the source note.75 pub note_id: u64,76 pub tie_start: bool,77 pub tie_stop: bool,78 /// The accidental must be printed: the alteration differs from what the key signature and79 /// the earlier notes of the measure on the same line imply. Set by [`engrave`].80 #[serde(default)]81 pub show_accidental: bool,82}8384/// Role of an element in a beam group.85#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]86#[serde(rename_all = "snake_case")]87pub enum Beam {88 #[default]89 None,90 Begin,91 Continue,92 End,93}9495#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]96pub struct Tuplet {97 pub actual: u8,98 pub normal: u8,99}100101#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]102pub struct Element {103 /// Offset from the start of the measure, whole notes.104 pub offset: Rational,105 /// Sounding (actual) length in whole notes, tuplet ratio applied.106 pub duration: Rational,107 pub note_type: NoteType,108 pub dots: u8,109 pub tuplet: Option<Tuplet>,110 /// Empty for a rest; several pitches for a chord, ascending.111 pub pitches: Vec<SpelledPitch>,112 pub articulation: Articulation,113 pub span: Span,114 /// Beam grouping within the beat (eighths and shorter). Set by [`engrave`].115 #[serde(default)]116 pub beam: Beam,117 /// Stem direction. Set by [`engrave`]; meaningless for rests and whole notes.118 #[serde(default)]119 pub stem_up: bool,120}121122impl Element {123 pub fn is_rest(&self) -> bool {124 self.pitches.is_empty()125 }126}127128#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]129#[serde(rename_all = "snake_case")]130pub enum Clef {131 Treble,132 Bass,133 Alto,134 Percussion,135}136137#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]138pub struct MeasureInfo {139 /// 1-based number.140 pub number: u32,141 pub start: Rational,142 pub length: Rational,143 pub numerator: u32,144 pub denominator: u32,145 /// True when the time signature differs from the previous measure (always true for the first).146 pub signature_change: bool,147 /// Tempo marks whose position falls inside this measure: (bpm, beat unit).148 pub tempos: Vec<(f64, Rational)>,149}150151#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]152pub struct PartMeasure {153 /// Up to four voices; each is a gap-free sequence covering the whole measure (rests included).154 pub voices: Vec<Vec<Element>>,155}156157#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]158pub struct Part {159 pub id: String,160 pub name: String,161 pub track: u32,162 pub clef: Clef,163 /// Written pitch = sounding pitch + this many semitones.164 pub transposition: i32,165 pub measures: Vec<PartMeasure>,166}167168#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]169pub struct Score {170 pub title: String,171 /// Key signature: number of sharps (positive) or flats (negative).172 pub fifths: i8,173 pub minor: bool,174 pub measures: Vec<MeasureInfo>,175 pub parts: Vec<Part>,176 /// What had to be approximated; shown to the user, never hidden.177 pub warnings: Vec<String>,178}179180/// Key signature (fifths) of a key; modes use the signature of their relative major.181pub fn key_fifths(key: &Key) -> (i8, bool) {182 let offset = match key.mode {183 Mode::Major | Mode::PentatonicMajor | Mode::WholeTone | Mode::Chromatic => 0,184 Mode::Dorian => 2,185 Mode::Phrygian => 4,186 Mode::Lydian => 5,187 Mode::Mixolydian => 7,188 Mode::Minor | Mode::HarmonicMinor | Mode::MelodicMinor | Mode::PentatonicMinor | Mode::Blues => 9,189 Mode::Locrian => 11,190 };191 let pc = (key.tonic as i32 + 12 - offset).rem_euclid(12);192 // Fifths of the major key on each pitch class, sharp spelling then flat spelling.193 const SHARP: [i8; 12] = [0, 7, 2, 9, 4, 11, 6, 1, 8, 3, 10, 5];194 let s = SHARP[pc as usize];195 let flat = s - 12;196 let prefer_flat = key.tonic_accidental < 0 || (key.tonic_accidental == 0 && s > 6);197 let fifths = if s <= 6 && !prefer_flat {198 s199 } else if flat >= -7 && (prefer_flat || s > 7) {200 flat201 } else {202 s203 };204 let minor = matches!(key.mode, Mode::Minor | Mode::HarmonicMinor | Mode::MelodicMinor | Mode::PentatonicMinor | Mode::Blues);205 (fifths.clamp(-7, 7), minor)206}207208/// Spells a MIDI pitch for a key signature: flats in flat keys, sharps otherwise. Notes of the209/// key's scale get their diatonic spelling. Microtones keep the nearest semitone's letter and210/// carry the remainder in `alter`.211pub fn spell(midi: f64, fifths: i8) -> (u8, f64, i8) {212 let nearest = midi.round();213 let micro = midi - nearest;214 let pc = (nearest as i64).rem_euclid(12) as usize;215 let octave = ((nearest as i64).div_euclid(12) - 1) as i8;216 // (step, alter) for each pitch class with sharps and with flats.217 const SHARPS: [(u8, i8); 12] = [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (3, 0), (3, 1), (4, 0), (4, 1), (5, 0), (5, 1), (6, 0)];218 const FLATS: [(u8, i8); 12] = [(0, 0), (1, -1), (1, 0), (2, -1), (2, 0), (3, 0), (4, -1), (4, 0), (5, -1), (5, 0), (6, -1), (6, 0)];219 let (mut step, mut alter) = if fifths < 0 { FLATS[pc] } else { SHARPS[pc] };220 let mut oct = octave;221 // Signatures with 6 or 7 accidentals use E#/B# or Cb/Fb.222 if fifths >= 6 && pc == 5 {223 (step, alter) = (2, 1);224 }225 if fifths >= 7 && pc == 0 {226 (step, alter) = (6, 1);227 oct -= 1;228 }229 if fifths <= -6 && pc == 11 {230 (step, alter) = (0, -1);231 oct += 1;232 }233 if fifths <= -7 && pc == 4 {234 (step, alter) = (3, -1);235 }236 (step, alter as f64 + micro, oct)237}238239/// Like [`spell`], and in a minor key the raised seventh and sixth degrees (the leading tone and240/// the melodic-minor sixth) keep their scale-degree letter: C sharp in D minor, not D flat.241pub fn spell_in_key(midi: f64, fifths: i8, minor: bool) -> (u8, f64, i8) {242 let plain = spell(midi, fifths);243 if !minor {244 return plain;245 }246 let nearest = midi.round() as i64;247 let pc = nearest.rem_euclid(12);248 // Tonic of the minor key with this signature, and its letter.249 let tonic_pc = ((fifths as i64 * 7).rem_euclid(12) + 9) % 12;250 let (tonic_step, _, _) = spell(tonic_pc as f64 + 60.0, fifths);251 const NATURAL: [i64; 7] = [0, 2, 4, 5, 7, 9, 11];252 for (degree_pc, letters_below) in [((tonic_pc + 11) % 12, 1u8), ((tonic_pc + 9) % 12, 2u8)] {253 if pc != degree_pc {254 continue;255 }256 let step = (tonic_step + 7 - letters_below) % 7;257 // Alteration that brings the natural letter to this pitch class, in -2..=2.258 let mut alter = (pc - NATURAL[step as usize]).rem_euclid(12);259 if alter > 6 {260 alter -= 12;261 }262 if alter.abs() > 1 {263 return plain; // would need a double accidental: keep the simple spelling264 }265 // The octave is that of the natural letter: B sharp belongs to the octave below its C.266 let octave = ((nearest - alter).div_euclid(12) - 1) as i8;267 return (step, alter as f64 + (midi - midi.round()), octave);268 }269 plain270}271272struct Piece {273 len: Rational,274 note_type: NoteType,275 dots: u8,276 tuplet: Option<Tuplet>,277}278279fn is_pow2(n: i64) -> bool {280 n > 0 && n & (n - 1) == 0281}282283/// Splits a power-of-two-denominator length into dotted values, largest first.284/// Returns the pieces and the remainder that is shorter than a 128th.285fn split_binary(mut rem: Rational, out: &mut Vec<(Rational, NoteType, u8)>) -> Rational {286 let smallest = NoteType::OneTwentyEighth.length();287 while rem >= smallest {288 let mut chosen = None;289 for t in NoteType::ALL {290 let l = t.length();291 if l <= rem {292 let dd = mul(l, r(7, 4));293 let d = mul(l, r(3, 2));294 let can_dot = (t as u8) < 7;295 let can_ddot = (t as u8) < 6;296 chosen = Some(if can_ddot && dd <= rem && dd == rem {297 (dd, t, 2)298 } else if can_dot && d <= rem {299 (d, t, 1)300 } else {301 (l, t, 0)302 });303 break;304 }305 }306 let Some((len, t, dots)) = chosen else { break };307 out.push((len, t, dots));308 rem = sub(rem, len);309 }310 rem311}312313/// Splits a length into notatable pieces. Returns the unnotatable remainder.314fn split_notatable(dur: Rational, out: &mut Vec<Piece>) -> Rational {315 if dur <= Rational::ZERO {316 return Rational::ZERO;317 }318 if is_pow2(dur.den()) {319 let mut bin = Vec::new();320 let rem = split_binary(dur, &mut bin);321 out.extend(bin.into_iter().map(|(len, note_type, dots)| Piece { len, note_type, dots, tuplet: None }));322 return rem;323 }324 for (actual, normal) in [(3u8, 2u8), (5, 4), (7, 4)] {325 let a = actual as i64;326 if dur.den() % a == 0 && is_pow2(dur.den() / a) {327 // notated = actual length x actual/normal has a binary denominator.328 let ratio = r(actual as i64, normal as i64);329 let notated = mul(dur, ratio);330 if is_pow2(notated.den()) {331 let mut bin = Vec::new();332 let rem = split_binary(notated, &mut bin);333 let back = r(normal as i64, actual as i64);334 out.extend(bin.into_iter().map(|(len, note_type, dots)| Piece {335 len: mul(len, back),336 note_type,337 dots,338 tuplet: Some(Tuplet { actual, normal }),339 }));340 return mul(rem, back);341 }342 }343 }344 // Not a simple tuplet: quantise to the 128th grid (reported by the caller).345 let grid = 128;346 let q = (dur.to_f64() * grid as f64).floor() as i64;347 let quant = r(q, grid);348 let mut bin = Vec::new();349 split_binary(quant, &mut bin);350 out.extend(bin.into_iter().map(|(len, note_type, dots)| Piece { len, note_type, dots, tuplet: None }));351 sub(dur, quant)352}353354struct ChordEvent {355 start: Rational,356 duration: Rational,357 pitches: Vec<(f64, u64)>,358 articulation: Articulation,359 span: Span,360}361362fn measures_of(program: &Program) -> Vec<MeasureInfo> {363 let mut out = Vec::new();364 let mut pos = Rational::ZERO;365 let mut sig_i = 0usize;366 let sigs = &program.signatures;367 let end =368 program.tracks.iter().flat_map(|t| t.notes.iter()).map(|n| add(n.notated_start, n.notated_duration)).max().unwrap_or(Rational::ZERO).max(program.end);369 let mut prev: Option<(u32, u32)> = None;370 loop {371 while sig_i + 1 < sigs.len() && sigs[sig_i + 1].at <= pos {372 sig_i += 1;373 }374 let (num, den) = sigs.get(sig_i).map(|s| (s.numerator.max(1), s.denominator.max(1))).unwrap_or((4, 4));375 let mut length = r(num as i64, den as i64);376 // A signature change that is not on this grid's bar line shortens the bar (pickup-like).377 if let Some(next) = sigs.get(sig_i + 1) {378 if next.at > pos && next.at < add(pos, length) {379 length = sub(next.at, pos);380 }381 }382 let bar_end = add(pos, length);383 let tempos = program.tempo_map.points.iter().filter(|p| p.at >= pos && p.at < bar_end).map(|p| (p.bpm, p.beat_unit)).collect();384 out.push(MeasureInfo {385 number: out.len() as u32 + 1,386 start: pos,387 length,388 numerator: num,389 denominator: den,390 signature_change: prev != Some((num, den)),391 tempos,392 });393 prev = Some((num, den));394 pos = bar_end;395 if pos >= end || out.len() >= 100_000 {396 break;397 }398 }399 out400}401402fn clef_for(track: &Track, transposition: i32) -> Clef {403 if let Some(i) = &track.instrument {404 if matches!(i.model.as_str(), "kick" | "snare" | "hihat") {405 return Clef::Percussion;406 }407 }408 if track.notes.is_empty() {409 return Clef::Treble;410 }411 // Violas read the alto clef by convention, whatever their register.412 let named_viola =413 track.name.to_ascii_lowercase().contains("viola") || track.instrument.as_ref().is_some_and(|i| i.name.to_ascii_lowercase().contains("viola"));414 if named_viola {415 return Clef::Alto;416 }417 // Otherwise by the mean written pitch: below G3 (55) the bass clef needs fewer ledger lines.418 let mean = track.notes.iter().map(|n| n.pitch).sum::<f64>() / track.notes.len() as f64 + transposition as f64;419 if mean < 55.0 {420 Clef::Bass421 } else {422 Clef::Treble423 }424}425426/// Builds the notation model of a program.427pub fn build_score(program: &Program) -> Score {428 let (fifths, minor) = program.key.as_ref().map(key_fifths).unwrap_or((0, false));429 let measures = measures_of(program);430 let mut warnings = Vec::new();431 let mut parts = Vec::new();432 for track in program.tracks.iter().filter(|t| t.kind == TrackKind::Instrument) {433 let transposition = track.score_transposition;434 // 1. Chords: notes of the same source voice with identical notated start and length.435 let mut notes: Vec<&sonata_ir::NoteEvent> = track.notes.iter().filter(|n| n.notated_duration > Rational::ZERO).collect();436 notes.sort_by(|a, b| {437 a.voice438 .cmp(&b.voice)439 .then(a.notated_start.cmp(&b.notated_start))440 .then(a.notated_duration.cmp(&b.notated_duration))441 .then(a.pitch.total_cmp(&b.pitch))442 });443 let mut by_voice: Vec<(u32, Vec<ChordEvent>)> = Vec::new();444 for n in notes {445 if by_voice.last().map(|v| v.0) != Some(n.voice) {446 by_voice.push((n.voice, Vec::new()));447 }448 let chords = &mut by_voice.last_mut().unwrap().1;449 match chords.last_mut() {450 Some(c) if c.start == n.notated_start && c.duration == n.notated_duration => c.pitches.push((n.pitch, n.id)),451 _ => chords.push(ChordEvent {452 start: n.notated_start,453 duration: n.notated_duration,454 pitches: vec![(n.pitch, n.id)],455 articulation: n.articulation,456 span: n.span,457 }),458 }459 }460 // 2. Monophonic notation voices: overlapping chords move to the next voice.461 let mut voices: Vec<Vec<ChordEvent>> = Vec::new();462 let mut dropped = 0usize;463 for (_, chords) in by_voice {464 let base = voices.len();465 for c in chords {466 let slot =467 voices.iter().enumerate().skip(base).find(|(_, v)| v.last().map(|l| add(l.start, l.duration) <= c.start).unwrap_or(true)).map(|(i, _)| i);468 match slot {469 Some(i) => voices[i].push(c),470 None if voices.len() < 4 => voices.push(vec![c]),471 None => dropped += 1,472 }473 }474 }475 if dropped > 0 {476 warnings.push(format!("{}: {dropped} chord(s) omitted from the score (more than four simultaneous voices)", track.name));477 }478 if voices.is_empty() {479 voices.push(Vec::new());480 }481 // 3. Lay each voice out measure by measure.482 let mut part_measures: Vec<PartMeasure> = measures.iter().map(|_| PartMeasure { voices: Vec::new() }).collect();483 let mut residue = Rational::ZERO;484 for voice in &voices {485 let mut ci = 0usize;486 // Portion of a chord carried over the bar line: (chord index, remaining length).487 let mut carry: Option<(usize, Rational)> = None;488 for (mi, m) in measures.iter().enumerate() {489 let mut elems: Vec<Element> = Vec::new();490 let mut cursor = Rational::ZERO;491 let push =492 |elems: &mut Vec<Element>, cursor: &mut Rational, len: Rational, chord: Option<(&ChordEvent, bool, bool)>, residue: &mut Rational| {493 let mut pieces = Vec::new();494 let rem = split_notatable(len, &mut pieces);495 if rem > Rational::ZERO {496 *residue = add(*residue, rem);497 }498 let count = pieces.len();499 for (pi, p) in pieces.into_iter().enumerate() {500 let pitches = match chord {501 None => Vec::new(),502 Some((c, tied_in, tied_out)) => {503 let mut ps: Vec<SpelledPitch> = c504 .pitches505 .iter()506 .map(|(pitch, id)| {507 let written = pitch + transposition as f64;508 let (step, alter, octave) = spell_in_key(written, fifths, minor);509 SpelledPitch {510 step,511 alter,512 octave,513 midi: written,514 note_id: *id,515 tie_stop: tied_in || pi > 0,516 tie_start: tied_out || pi + 1 < count,517 show_accidental: false,518 }519 })520 .collect();521 ps.sort_by(|a, b| a.midi.total_cmp(&b.midi));522 ps523 }524 };525 elems.push(Element {526 offset: *cursor,527 duration: p.len,528 note_type: p.note_type,529 dots: p.dots,530 tuplet: p.tuplet,531 pitches,532 articulation: chord.map(|c| c.0.articulation).unwrap_or(Articulation::Normal),533 span: chord.map(|c| c.0.span).unwrap_or_default(),534 beam: Beam::None,535 stem_up: true,536 });537 *cursor = add(*cursor, p.len);538 }539 // Whatever could not be notated is skipped in time so later notes stay aligned.540 if rem > Rational::ZERO {541 *cursor = add(*cursor, rem);542 }543 };544 if let Some((idx, left)) = carry.take() {545 let take = left.min(m.length);546 let more = left > take;547 push(&mut elems, &mut cursor, take, Some((&voice[idx], true, more)), &mut residue);548 if more {549 carry = Some((idx, sub(left, take)));550 }551 }552 while carry.is_none() && ci < voice.len() {553 let c = &voice[ci];554 let rel = sub(c.start, m.start);555 if c.start >= add(m.start, m.length) {556 break;557 }558 if c.start < m.start {559 // Starts before this measure (can only happen after an omitted overlap).560 ci += 1;561 continue;562 }563 if rel > cursor {564 let gap = sub(rel, cursor);565 push(&mut elems, &mut cursor, gap, None, &mut residue);566 }567 let room = sub(m.length, rel);568 let take = c.duration.min(room);569 let more = c.duration > take;570 cursor = rel;571 push(&mut elems, &mut cursor, take, Some((c, false, more)), &mut residue);572 if more {573 carry = Some((ci, sub(c.duration, take)));574 }575 ci += 1;576 }577 if cursor < m.length {578 let gap = sub(m.length, cursor);579 if elems.is_empty() && gap == m.length {580 // Whole-measure rest.581 elems.push(Element {582 offset: Rational::ZERO,583 duration: m.length,584 note_type: NoteType::Whole,585 dots: 0,586 tuplet: None,587 pitches: Vec::new(),588 articulation: Articulation::Normal,589 span: Span::default(),590 beam: Beam::None,591 stem_up: true,592 });593 } else {594 push(&mut elems, &mut cursor, gap, None, &mut residue);595 }596 }597 part_measures[mi].voices.push(elems);598 }599 }600 if residue > Rational::ZERO {601 warnings.push(format!("{}: durations finer than a 128th or irregular tuplets were quantised (total {} of a whole note)", track.name, residue));602 }603 if track.notes.iter().any(|n| (n.pitch - n.pitch.round()).abs() > 1e-9) {604 warnings.push(format!("{}: microtonal pitches are written as fractional alterations", track.name));605 }606 parts.push(Part {607 id: format!("P{}", parts.len() + 1),608 name: track.name.clone(),609 track: track.id,610 clef: clef_for(track, transposition),611 transposition,612 measures: part_measures,613 });614 }615 let mut score = Score { title: program.title.clone(), fifths, minor, measures, parts, warnings };616 engrave(&mut score);617 score618}619620/// Length of the group of beats that beams and rests respect: one beat, or three eighths in621/// compound metres (6/8, 9/8, 12/8).622pub fn beat_group(numerator: u32, denominator: u32) -> Rational {623 if denominator == 8 && numerator.is_multiple_of(3) && numerator >= 6 {624 r(3, 8)625 } else {626 r(1, denominator.max(1) as i64)627 }628}629630/// Alteration (in semitones) the key signature gives to a step (0 = C ... 6 = B).631pub fn key_alter(step: u8, fifths: i8) -> i8 {632 const SHARPS: [u8; 7] = [3, 0, 4, 1, 5, 2, 6];633 const FLATS: [u8; 7] = [6, 2, 5, 1, 4, 0, 3];634 if fifths > 0 && SHARPS[..(fifths as usize).min(7)].contains(&step) {635 1636 } else if fifths < 0 && FLATS[..(fifths.unsigned_abs() as usize).min(7)].contains(&step) {637 -1638 } else {639 0640 }641}642643/// Diatonic position of the middle staff line of a clef (`octave * 7 + step`).644pub fn middle_line(clef: Clef) -> i32 {645 match clef {646 Clef::Treble | Clef::Percussion => 4 * 7 + 6, // B4647 Clef::Bass => 3 * 7 + 1, // D3648 Clef::Alto => 4 * 7, // C4649 }650}651652/// Engraving decisions shared by every renderer, so the app, the PDF and MusicXML agree:653/// 1. rests that start off the beat are split at the next beat boundary;654/// 2. accidentals: printed when the alteration differs from the key signature or from an655/// earlier note of the same measure on the same line (all voices of the part together);656/// a note continuing a tie repeats nothing;657/// 3. beams: consecutive notes shorter than a quarter inside one beat group;658/// 4. stems: with several sounding voices in a measure, odd voices up and even voices down;659/// otherwise by the note farthest from the middle line (up when below it), one direction660/// per beam group.661pub fn engrave(score: &mut Score) {662 let fifths = score.fifths;663 for part in &mut score.parts {664 let middle = middle_line(part.clef);665 for (mi, pm) in part.measures.iter_mut().enumerate() {666 let Some(info) = score.measures.get(mi) else { continue };667 let group = beat_group(info.numerator, info.denominator);668 // 1. Rests.669 for voice in &mut pm.voices {670 let mut out: Vec<Element> = Vec::with_capacity(voice.len());671 for e in voice.drain(..) {672 let whole_measure = e.is_rest() && e.offset.is_zero() && e.duration == info.length;673 let phase = e.offset.checked_div(group).map(|q| q.den() != 1).unwrap_or(false);674 if e.is_rest() && !whole_measure && e.tuplet.is_none() && phase {675 // Next multiple of the beat group after the rest's start.676 let k = (e.offset.to_f64() / group.to_f64()).floor() as i64 + 1;677 let boundary = mul(group, Rational::from_int(k));678 let end = add(e.offset, e.duration);679 if boundary < end {680 let mut cursor = e.offset;681 for len in [sub(boundary, e.offset), sub(end, boundary)] {682 let mut pieces = Vec::new();683 split_notatable(len, &mut pieces);684 for p in pieces {685 out.push(Element { offset: cursor, duration: p.len, note_type: p.note_type, dots: p.dots, tuplet: p.tuplet, ..e.clone() });686 cursor = add(cursor, p.len);687 }688 }689 continue;690 }691 }692 out.push(e);693 }694 *voice = out;695 }696 // 2. Accidentals, in time order across the voices of the part.697 let mut order: Vec<(Rational, usize, usize)> = Vec::new();698 for (vi, voice) in pm.voices.iter().enumerate() {699 for (ei, e) in voice.iter().enumerate() {700 if !e.is_rest() {701 order.push((e.offset, vi, ei));702 }703 }704 }705 order.sort();706 let mut state: std::collections::BTreeMap<(i8, u8), i32> = std::collections::BTreeMap::new();707 for (_, vi, ei) in order {708 for p in &mut pm.voices[vi][ei].pitches {709 let alter = p.alter.round() as i32;710 let current = *state.get(&(p.octave, p.step)).unwrap_or(&(key_alter(p.step, fifths) as i32));711 if p.tie_stop {712 p.show_accidental = false;713 continue;714 }715 p.show_accidental = alter != current;716 state.insert((p.octave, p.step), alter);717 }718 }719 // 3. Beams.720 let sounding = pm.voices.iter().filter(|v| v.iter().any(|e| !e.is_rest())).count();721 for (vi, voice) in pm.voices.iter_mut().enumerate() {722 let key = |e: &Element| (e.offset.to_f64() / group.to_f64() + 1e-9).floor() as i64;723 let beamable = |e: &Element| !e.is_rest() && e.note_type.flags() > 0;724 let mut i = 0;725 while i < voice.len() {726 voice[i].beam = Beam::None;727 if !beamable(&voice[i]) {728 i += 1;729 continue;730 }731 let mut j = i + 1;732 while j < voice.len() && beamable(&voice[j]) && key(&voice[j]) == key(&voice[i]) {733 j += 1;734 }735 if j - i >= 2 {736 for (k, e) in voice[i..j].iter_mut().enumerate() {737 e.beam = if k == 0 {738 Beam::Begin739 } else if k == j - i - 1 {740 Beam::End741 } else {742 Beam::Continue743 };744 }745 }746 // 4. Stems for this group (or single note).747 let up = if sounding > 1 {748 vi % 2 == 0749 } else {750 let far = voice[i..j]751 .iter()752 .flat_map(|e| e.pitches.iter())753 .map(|p| p.octave as i32 * 7 + p.step as i32 - middle)754 .max_by_key(|d| d.abs())755 .unwrap_or(0);756 far < 0757 };758 for e in &mut voice[i..j] {759 e.stem_up = up;760 }761 i = j;762 }763 // Notes that cannot be beamed (quarters and longer).764 for e in voice.iter_mut().filter(|e| !e.is_rest() && e.note_type.flags() == 0) {765 e.stem_up = if sounding > 1 {766 vi % 2 == 0767 } else {768 e.pitches.iter().map(|p| p.octave as i32 * 7 + p.step as i32 - middle).max_by_key(|d| d.abs()).unwrap_or(0) < 0769 };770 }771 }772 }773 }774}775776#[cfg(test)]777pub(crate) mod tests {778 use super::*;779 use sonata_ir::{InstrumentSpec, NoteEvent, Output, Params};780781 pub fn note(id: u64, start: Rational, dur: Rational, pitch: f64, voice: u32) -> NoteEvent {782 NoteEvent {783 id,784 start,785 duration: dur,786 notated_start: start,787 notated_duration: dur,788 start_sec: start.to_f64() * 2.0,789 end_sec: (start.to_f64() + dur.to_f64()) * 2.0,790 pitch,791 velocity: 0.8,792 voice,793 articulation: Articulation::Normal,794 tied_from_previous: false,795 bend: Vec::new(),796 span: Span::default(),797 }798 }799800 pub fn program(notes: Vec<NoteEvent>) -> Program {801 let mut p = Program::empty("Test");802 p.tracks.push(Track {803 id: 0,804 name: "piano".into(),805 kind: TrackKind::Instrument,806 instrument: Some(InstrumentSpec { name: "GrandPiano".into(), model: "piano".into(), params: Params::new(), patch: None }),807 gain_db: 0.0,808 pan: 0.0,809 mute: false,810 solo: false,811 effects: vec![],812 sends: vec![],813 output: Output::Master,814 notes,815 clips: vec![],816 automation: vec![],817 score_transposition: 0,818 span: Span::default(),819 });820 p.refresh_stats();821 p822 }823824 fn total(voice: &[Element]) -> Rational {825 voice.iter().fold(Rational::ZERO, |a, e| add(a, e.duration))826 }827828 #[test]829 fn every_voice_fills_every_measure() {830 let notes = vec![831 note(0, r(0, 1), r(1, 4), 62.0, 0),832 note(1, r(0, 1), r(1, 4), 65.0, 0),833 note(2, r(3, 8), r(3, 8), 69.0, 0),834 note(3, r(7, 8), r(1, 2), 72.0, 0), // crosses the bar line: tie835 note(4, r(3, 2), r(1, 12), 60.0, 0), // triplet eighths836 note(5, r(19, 12), r(1, 12), 62.0, 0),837 note(6, r(20, 12), r(1, 12), 64.0, 0),838 note(7, r(0, 1), r(1, 1), 48.0, 1), // second voice839 ];840 let s = build_score(&program(notes));841 assert_eq!(s.parts.len(), 1);842 assert_eq!(s.measures.len(), 2);843 assert!(s.warnings.is_empty(), "{:?}", s.warnings);844 for (mi, pm) in s.parts[0].measures.iter().enumerate() {845 assert_eq!(pm.voices.len(), 2);846 for v in &pm.voices {847 assert_eq!(total(v), s.measures[mi].length, "measure {mi}");848 }849 }850 let m1 = &s.parts[0].measures[0].voices[0];851 assert_eq!(m1[0].pitches.len(), 2, "chord");852 assert!(m1[1].is_rest() && m1[1].note_type == NoteType::Eighth);853 assert_eq!((m1[2].note_type, m1[2].dots), (NoteType::Quarter, 1));854 let last = m1.last().unwrap();855 assert!(last.pitches[0].tie_start && !last.pitches[0].tie_stop);856 let m2 = &s.parts[0].measures[1].voices[0];857 assert!(m2[0].pitches[0].tie_stop);858 let trip: Vec<_> = m2.iter().filter(|e| e.tuplet.is_some()).collect();859 assert_eq!(trip.len(), 3);860 assert_eq!(trip[0].tuplet, Some(Tuplet { actual: 3, normal: 2 }));861 assert_eq!(trip[0].note_type, NoteType::Eighth);862 }863864 #[test]865 fn engraving_rules() {866 // D minor (one flat). Bb is in the key; B natural and C# need accidentals once per measure.867 let mut p = program(vec![868 note(0, r(0, 1), r(1, 8), 70.0, 0), // Bb4: in the key signature869 note(1, r(1, 8), r(1, 8), 71.0, 0), // B4 natural: shown870 note(2, r(1, 4), r(1, 8), 71.0, 0), // B4 again: not shown871 note(3, r(3, 8), r(1, 8), 70.0, 0), // back to Bb: shown872 note(4, r(1, 2), r(1, 4), 61.0, 0), // C#4 below the middle line873 note(5, r(7, 8), r(1, 8), 84.0, 0), // after a rest that starts off the beat874 note(6, r(1, 1), r(1, 8), 71.0, 0), // new measure: B natural shown again875 ]);876 p.key = Some(Key { tonic: 2, tonic_accidental: 0, tonic_letter: 1, mode: Mode::Minor });877 let s = build_score(&p);878 assert_eq!(s.fifths, -1);879 let v = &s.parts[0].measures[0].voices[0];880 let shown: Vec<bool> = v.iter().filter(|e| !e.is_rest()).map(|e| e.pitches[0].show_accidental).collect();881 assert_eq!(shown, vec![false, true, false, true, true, false]);882 assert!(s.parts[0].measures[1].voices[0][0].pitches[0].show_accidental);883 // Beams: two groups of two eighths (beats 1 and 2); the quarter and the lone eighth are not beamed.884 let beams: Vec<Beam> = v.iter().filter(|e| !e.is_rest()).map(|e| e.beam).collect();885 assert_eq!(beams, vec![Beam::Begin, Beam::End, Beam::Begin, Beam::End, Beam::None, Beam::None]);886 // Stems: B4 is the middle line of the treble clef (down by convention), C#4 is below it (up), C6 above (down).887 let notes: Vec<&Element> = v.iter().filter(|e| !e.is_rest()).collect();888 assert!(notes[4].stem_up && !notes[5].stem_up && !notes[0].stem_up);889 // The rest between 3/4 and 7/8 starts on the beat: a single eighth rest.890 let rests: Vec<&Element> = v.iter().filter(|e| e.is_rest()).collect();891 assert_eq!(rests.len(), 1);892 assert_eq!(rests[0].note_type, NoteType::Eighth);893894 // A rest starting off the beat is split at the beat: 1/8 note, then rests 1/8 + 1/2 + 1/4...895 let s = build_score(&program(vec![note(0, r(0, 1), r(1, 8), 60.0, 0)]));896 let v = &s.parts[0].measures[0].voices[0];897 assert_eq!(v[1].offset, r(1, 8));898 assert_eq!(v[1].duration, r(1, 8), "rest up to the next beat first");899 assert_eq!(v.iter().fold(Rational::ZERO, |a, e| add(a, e.duration)), r(1, 1));900901 // Two sounding voices: first up, second down.902 let s = build_score(&program(vec![note(0, r(0, 1), r(1, 4), 72.0, 0), note(1, r(0, 1), r(1, 2), 48.0, 1)]));903 let m = &s.parts[0].measures[0];904 assert!(m.voices[0][0].stem_up && !m.voices[1][0].stem_up);905 // Clef choice: bass for a low part, alto for a viola, treble otherwise.906 let mut low = program(vec![note(0, r(0, 1), r(1, 4), 40.0, 0)]);907 assert_eq!(build_score(&low).parts[0].clef, Clef::Bass);908 low.tracks[0].name = "Viola 1".into();909 assert_eq!(build_score(&low).parts[0].clef, Clef::Alto);910 assert_eq!(build_score(&program(vec![note(0, r(0, 1), r(1, 4), 67.0, 0)])).parts[0].clef, Clef::Treble);911 assert_eq!(key_alter(3, 2), 1);912 assert_eq!(key_alter(6, -1), -1);913 assert_eq!(beat_group(6, 8), r(3, 8));914 }915916 #[test]917 fn spelling_follows_the_key() {918 assert_eq!(spell(61.0, 2), (0, 1.0, 4)); // C#4 in D major919 assert_eq!(spell(61.0, -3), (1, -1.0, 4)); // Db4 in Eb major920 assert_eq!(spell(60.0, 0), (0, 0.0, 4));921 // Minor keys keep the letter of the raised degrees.922 assert_eq!(spell_in_key(61.0, -1, true), (0, 1.0, 4), "C#4 in D minor");923 assert_eq!(spell_in_key(59.0, -1, true), (6, 0.0, 3), "B natural in D minor");924 assert_eq!(spell_in_key(68.0, 0, true), (4, 1.0, 4), "G#4 in A minor");925 assert_eq!(spell_in_key(71.0, -3, true), (6, 0.0, 4), "B natural in C minor");926 assert_eq!(spell_in_key(72.0, 4, true), (6, 1.0, 4), "B#4 in C# minor sits in octave 4");927 assert_eq!(spell_in_key(61.0, -1, false), (1, -1.0, 4), "Db in F major");928 let (step, alter, _) = spell(69.5, 0);929 assert_eq!(step, 5);930 assert!((alter - -0.5).abs() < 1e-9 || (alter - 0.5).abs() < 1e-9);931 let d_minor = Key { tonic: 2, tonic_accidental: 0, tonic_letter: 1, mode: Mode::Minor };932 assert_eq!(key_fifths(&d_minor), (-1, true));933 let fs_major = Key { tonic: 6, tonic_accidental: 1, tonic_letter: 3, mode: Mode::Major };934 assert_eq!(key_fifths(&fs_major), (6, false));935 let gb_major = Key { tonic: 6, tonic_accidental: -1, tonic_letter: 4, mode: Mode::Major };936 assert_eq!(key_fifths(&gb_major), (-6, false));937 let e_dorian = Key { tonic: 4, tonic_accidental: 0, tonic_letter: 2, mode: Mode::Dorian };938 assert_eq!(key_fifths(&e_dorian), (2, false));939 }940941 #[test]942 fn irregular_durations_are_reported() {943 let s = build_score(&program(vec![note(0, r(0, 1), r(1, 11), 60.0, 0)]));944 assert!(s.warnings.iter().any(|w| w.contains("quantised")));945 for v in &s.parts[0].measures[0].voices {946 assert!(total(v) <= s.measures[0].length);947 }948 }949}950