Skip to main content

music21/
tempo.rs

1//! Metronome marks, a port of the stream-free part of music21's `tempo`.
2
3use crate::{
4    defaults::FloatType,
5    display::Drawn,
6    duration::Duration,
7    error::{Error, Result},
8    notation::Placement,
9    stream::Stream,
10};
11
12/// The tempo words music21 knows and the beats per minute each implies,
13/// in music21's order.
14pub const DEFAULT_TEMPO_VALUES: [(&str, FloatType); 30] = [
15    ("larghissimo", 16.0),
16    ("largamente", 32.0),
17    ("grave", 40.0),
18    ("molto adagio", 40.0),
19    ("largo", 46.0),
20    ("lento", 52.0),
21    ("adagio", 56.0),
22    ("slow", 56.0),
23    ("langsam", 56.0),
24    ("larghetto", 60.0),
25    ("adagietto", 66.0),
26    ("andante", 72.0),
27    ("andantino", 80.0),
28    ("andante moderato", 83.0),
29    ("maestoso", 88.0),
30    ("moderato", 92.0),
31    ("moderate", 92.0),
32    ("allegretto", 108.0),
33    ("animato", 120.0),
34    ("allegro moderato", 128.0),
35    ("allegro", 132.0),
36    ("fast", 132.0),
37    ("schnell", 132.0),
38    ("allegrissimo", 140.0),
39    ("molto allegro", 144.0),
40    ("très vite", 144.0),
41    ("vivace", 160.0),
42    ("vivacissimo", 168.0),
43    ("presto", 184.0),
44    ("prestissimo", 208.0),
45];
46
47/// Converts a tempo counted in one note value into the same tempo counted in
48/// another, both given in quarter lengths.
49///
50/// Sixty half notes a minute is a hundred and twenty quarters.
51pub fn convert_tempo_by_referent(
52    number: FloatType,
53    source_quarter_length: FloatType,
54    destination_quarter_length: FloatType,
55) -> FloatType {
56    let seconds_per_source_beat = 60.0 / number;
57    let seconds_per_quarter = seconds_per_source_beat / source_quarter_length;
58    60.0 / (seconds_per_quarter * destination_quarter_length)
59}
60
61/// A number within a millionth of a whole one as that whole number, which is
62/// what music21's `numToIntOrFloat` makes of every number a mark is given:
63/// a tempo counted in another note value comes back a hair off, and the mark
64/// keeps `165`, not `165.00000000000003`.
65fn whole_where_nearly(number: FloatType) -> FloatType {
66    let rounded = number.round_ties_even();
67    if (rounded - number).abs() < 1e-6 {
68        rounded
69    } else {
70        number
71    }
72}
73
74/// Returns the tempo word music21 pairs with a beats-per-minute value, when
75/// one lies within two beats of it. Ties go to the lower value, then the
76/// alphabetically earlier word, as music21 sorts them.
77pub fn default_text_for_number(number: FloatType) -> Option<&'static str> {
78    let mut sorted = DEFAULT_TEMPO_VALUES;
79    sorted.sort_by(|left, right| {
80        left.1
81            .partial_cmp(&right.1)
82            .unwrap_or(std::cmp::Ordering::Equal)
83            .then_with(|| left.0.cmp(right.0))
84    });
85    sorted
86        .iter()
87        .find(|(_, value)| (value - 2.0..=value + 2.0).contains(&number))
88        .map(|(text, _)| *text)
89}
90
91/// Returns the beats per minute music21 pairs with a tempo word, matching the
92/// whole text case-insensitively first and any single word of it second.
93pub fn default_number_for_text(text: &str) -> Option<FloatType> {
94    let lowered = text.to_lowercase();
95    let lookup = |candidate: &str| {
96        DEFAULT_TEMPO_VALUES
97            .iter()
98            .find(|(name, _)| *name == candidate)
99            .map(|(_, value)| *value)
100    };
101    lookup(&lowered).or_else(|| lookup(text)).or_else(|| {
102        text.split(' ')
103            .filter_map(|word| lookup(&word.to_lowercase()))
104            .next_back()
105    })
106}
107
108/// A metronome marking: a beats-per-minute number, a tempo word, and the
109/// note value the number counts.
110///
111/// Either half may be implied from the other: a number alone picks up the
112/// nearest tempo word, and a word alone picks up its conventional number.
113#[derive(Clone, Debug, PartialEq)]
114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
115#[must_use]
116pub struct MetronomeMark {
117    number: Option<FloatType>,
118    text: Option<String>,
119    referent: Duration,
120    number_implicit: bool,
121    text_implicit: bool,
122    /// What the mark is played at, where that is not what it says.
123    #[cfg_attr(feature = "serde", serde(default))]
124    number_sounding: Option<FloatType>,
125    #[cfg_attr(feature = "serde", serde(default))]
126    parentheses: Drawn<bool>,
127    #[cfg_attr(feature = "serde", serde(default))]
128    placement: Drawn<Option<Placement>>,
129    /// Whether it is left off the page: music21's
130    /// `style.hideObjectOnPrint`.
131    #[cfg_attr(feature = "serde", serde(default))]
132    hidden: Drawn<bool>,
133}
134
135impl Default for MetronomeMark {
136    /// A mark that says nothing yet: no number, no word, counting quarters.
137    /// music21 builds one of these and fills it in.
138    fn default() -> Self {
139        Self::build(None, None, Duration::quarter())
140    }
141}
142
143impl MetronomeMark {
144    /// A mark of `number` beats per minute, counting quarter notes, with the
145    /// tempo word implied from the number when one is close enough.
146    pub fn new(number: FloatType) -> Self {
147        Self::build(Some(number), None, Duration::quarter())
148    }
149
150    /// A mark from a tempo word alone, with the number implied from the word
151    /// when music21 knows it.
152    pub fn from_text(text: impl Into<String>) -> Self {
153        Self::build(None, Some(text.into()), Duration::quarter())
154    }
155
156    /// A mark carrying both an explicit number and an explicit word.
157    pub fn with_number_and_text(number: FloatType, text: impl Into<String>) -> Self {
158        Self::build(Some(number), Some(text.into()), Duration::quarter())
159    }
160
161    /// Changes the note value the number counts, so `Duration::half()` makes
162    /// the number a count of half notes.
163    pub fn with_referent(mut self, referent: Duration) -> Self {
164        self.referent = referent;
165        self
166    }
167
168    fn build(number: Option<FloatType>, text: Option<String>, referent: Duration) -> Self {
169        let number = number.map(whole_where_nearly);
170        let number_implicit = number.is_none();
171        let text_implicit = text.is_none();
172        let number = number.or_else(|| text.as_deref().and_then(default_number_for_text));
173        let text = text.or_else(|| number.and_then(default_text_for_number).map(String::from));
174        Self {
175            number_implicit: number_implicit && number.is_some(),
176            text_implicit: text_implicit && text.is_some(),
177            number,
178            text,
179            referent,
180            number_sounding: None,
181            parentheses: Drawn(false),
182            placement: Drawn(None),
183            hidden: Drawn(false),
184        }
185    }
186
187    /// Whether the mark is left off the page: music21's
188    /// `style.hideObjectOnPrint`.
189    pub fn hidden(&self) -> bool {
190        self.hidden.0
191    }
192
193    /// Leaves the mark off the page, or puts it back.
194    pub fn set_hidden(&mut self, hidden: bool) {
195        self.hidden.0 = hidden;
196    }
197
198    /// Whether the mark is written in parentheses: music21's
199    /// `parentheses`.
200    pub fn parentheses(&self) -> bool {
201        self.parentheses.0
202    }
203
204    /// Says whether the mark is written in parentheses.
205    pub fn set_parentheses(&mut self, parentheses: bool) {
206        self.parentheses.0 = parentheses;
207    }
208
209    /// Which side of the staff it is written on, where the score says.
210    pub fn placement(&self) -> Option<Placement> {
211        self.placement.0
212    }
213
214    /// Says which side of the staff it is written on.
215    pub fn set_placement(&mut self, placement: Option<Placement>) {
216        self.placement.0 = placement;
217    }
218
219    /// The same tempo counted in a different note value: music21's
220    /// `getEquivalentByReferent`, so quarter = 60 becomes eighth = 120. The
221    /// tempo word is carried over unchanged, implied or not.
222    pub fn equivalent_by_referent(&self, referent: Duration) -> MetronomeMark {
223        let number = self.number.map(|number| {
224            convert_tempo_by_referent(
225                number,
226                self.referent.quarter_length(),
227                referent.quarter_length(),
228            )
229        });
230        Self::build(number, self.text.clone(), referent)
231    }
232
233    /// The same number counted in a different note value, so the tempo
234    /// itself changes: music21's `getMaintainedNumberWithReferent`.
235    pub fn maintained_number_with_referent(&self, referent: Duration) -> MetronomeMark {
236        Self::build(self.number, self.text.clone(), referent)
237    }
238
239    /// The beats per minute, if known.
240    pub fn number(&self) -> Option<FloatType> {
241        self.number
242    }
243
244    /// Sets the beats per minute, which is then no longer implied. A mark
245    /// with no word of its own picks one up, as music21 does.
246    pub fn set_number(&mut self, number: Option<FloatType>) {
247        let number = number.map(whole_where_nearly);
248        self.number = number;
249        self.number_implicit = false;
250        if self.text.is_none()
251            && let Some(number) = number
252            && let Some(text) = default_text_for_number(number)
253        {
254            self.text = Some(text.to_string());
255            self.text_implicit = true;
256        }
257    }
258
259    /// Sets the tempo word, which is then no longer implied. A mark with no
260    /// number of its own picks one up.
261    pub fn set_text(&mut self, text: impl Into<String>) {
262        let text = text.into();
263        self.text_implicit = false;
264        if self.number.is_none()
265            && let Some(number) = default_number_for_text(&text)
266        {
267            self.number = Some(number);
268            self.number_implicit = true;
269        }
270        self.text = Some(text);
271    }
272
273    /// Sets the note value the number counts, leaving the number alone — so
274    /// the tempo itself changes.
275    pub fn set_referent(&mut self, referent: Duration) {
276        self.referent = referent;
277    }
278
279    /// The tempo word, if any.
280    pub fn text(&self) -> Option<&str> {
281        self.text.as_deref()
282    }
283
284    /// The mark as music21's `repr` writes it: the word, the referent and
285    /// the number, or the sounding number marked as playback only where
286    /// none is written.
287    ///
288    /// ```
289    /// use music21::tempo::MetronomeMark;
290    ///
291    /// let mut mark = MetronomeMark::new(40.0);
292    /// mark.set_text("slow");
293    /// assert_eq!(mark.music21_repr(), "<music21.tempo.MetronomeMark slow Quarter=40>");
294    /// ```
295    pub fn music21_repr(&self) -> String {
296        let mut sounding = "";
297        let mut number = self.number();
298        if number.is_none() && self.number_sounding().is_some() {
299            sounding = " (playback only)";
300            number = self.number_sounding();
301        }
302        let number = number.map_or_else(|| "None".to_string(), python_number);
303        let referent = self.referent().full_name();
304        match self.text() {
305            Some(text) => {
306                format!("<music21.tempo.MetronomeMark {text} {referent}={number}{sounding}>")
307            }
308            None => format!("<music21.tempo.MetronomeMark {referent}={number}{sounding}>"),
309        }
310    }
311
312    /// The tempo word as something a score would carry: music21's
313    /// `getTextExpression`. A word only implied from the number is not
314    /// answered unless `return_implicit` asks for it.
315    pub fn text_expression(&self, return_implicit: bool) -> Option<&str> {
316        if self.text_implicit && !return_implicit {
317            return None;
318        }
319        self.text.as_deref()
320    }
321
322    /// The note value the number counts.
323    pub fn referent(&self) -> &Duration {
324        &self.referent
325    }
326
327    /// Whether the number was implied from the tempo word.
328    pub fn number_implicit(&self) -> bool {
329        self.number_implicit
330    }
331
332    /// Says so, or unsays it. music21 lets a caller write this: its MIDI
333    /// reader copies a mark onto every staff and marks the copies implicit,
334    /// which is how the parts after the first hide the number.
335    pub fn set_number_implicit(&mut self, implicit: bool) {
336        self.number_implicit = implicit;
337    }
338
339    /// Whether the tempo word was implied from the number.
340    pub fn text_implicit(&self) -> bool {
341        self.text_implicit
342    }
343
344    /// music21's `numberSounding`: how fast the mark is actually played,
345    /// where that is not the number written over the staff.
346    ///
347    /// A score may say *Allegro* and be played at a hundred and forty-four,
348    /// and a MusicXML `<sound tempo=...>` with no metronome mark beside it
349    /// is a tempo that sounds and is never written. Nothing here is
350    /// answered from it unless it is asked for: [`Self::quarter_bpm`] reads
351    /// the written number, and [`Self::sounding_quarter_bpm`] reads this.
352    pub fn number_sounding(&self) -> Option<FloatType> {
353        self.number_sounding
354    }
355
356    /// Sets how fast the mark is played, apart from what it says.
357    pub fn set_number_sounding(&mut self, number: Option<FloatType>) {
358        self.number_sounding = number;
359    }
360
361    /// A mark built to be played at this speed.
362    ///
363    /// It does not become the mark's number: a mark that says nothing and
364    /// sounds at a hundred and sixty-eight still says nothing, which is how
365    /// music21 carries a tempo that is played and never written.
366    pub fn with_number_sounding(mut self, number: FloatType) -> Self {
367        self.number_sounding = Some(number);
368        self
369    }
370
371    /// The tempo as quarter notes per minute, whatever the referent.
372    pub fn quarter_bpm(&self) -> Option<FloatType> {
373        self.number
374            .map(|number| convert_tempo_by_referent(number, self.referent.quarter_length(), 1.0))
375    }
376
377    /// The same, at the speed the mark is played rather than the one it
378    /// says: music21's `getQuarterBPM(useNumberSounding=True)`.
379    pub fn sounding_quarter_bpm(&self) -> Option<FloatType> {
380        match self.number_sounding {
381            Some(number) => Some(convert_tempo_by_referent(
382                number,
383                self.referent.quarter_length(),
384                1.0,
385            )),
386            None => self.quarter_bpm(),
387        }
388    }
389
390    /// Seconds each quarter note lasts.
391    ///
392    /// A mark of nought beats a minute is refused rather than answered with
393    /// an infinity, which is what dividing by it gives and what every
394    /// arithmetic downstream of it would then carry.
395    pub fn seconds_per_quarter(&self) -> Result<FloatType> {
396        // music21 reads the speed the mark is played at, its
397        // getQuarterBPM() taking useNumberSounding=True by default, so a
398        // mark that says no number but carries a sounding one -- what a
399        // MusicXML <sound tempo="..."> reads as -- still answers.
400        let quarter_bpm = self.sounding_quarter_bpm().ok_or_else(|| {
401            Error::Tempo("cannot derive seconds as getQuarterBPM() returns None".to_string())
402        })?;
403        if quarter_bpm == 0.0 {
404            return Err(Error::Tempo(
405                "a tempo of no beats a minute lasts no seconds a beat".to_string(),
406            ));
407        }
408        Ok(60.0 / quarter_bpm)
409    }
410
411    /// Seconds a span of the given quarter length lasts at this tempo.
412    pub fn quarter_length_to_seconds(&self, quarter_length: FloatType) -> Result<FloatType> {
413        Ok(self.seconds_per_quarter()? * quarter_length)
414    }
415
416    /// Seconds a duration lasts at this tempo.
417    pub fn duration_to_seconds(&self, duration: &Duration) -> Result<FloatType> {
418        self.quarter_length_to_seconds(duration.quarter_length())
419    }
420
421    /// The duration that lasts the given number of seconds at this tempo.
422    pub fn seconds_to_duration(&self, seconds: FloatType) -> Result<Duration> {
423        if seconds.is_nan() || seconds <= 0.0 {
424            return Err(Error::Tempo(
425                "seconds must be a number greater than zero".to_string(),
426            ));
427        }
428        Duration::new(seconds / self.seconds_per_quarter()?)
429    }
430}
431
432/// Carries what lies between two points of one stream into another, keeping
433/// each thing's place between them: music21's `interpolateElements`.
434///
435/// `start` and `end` each say where one point stands in the source and where
436/// it stands in the destination -- a downbeat at offset 10 of a score and
437/// 20.5 of a recording, the next at 14 and at 25. Everything strictly
438/// between them in the source is inserted into the destination at the same
439/// proportion of the way across, so a note at 11 lands at 21.625.
440///
441/// music21 finds the two points by asking one object for its offset in each
442/// stream. A stream here owns what it holds, so there is no such object to
443/// ask and the offsets are given instead; and for the same reason this is
444/// always music21's `autoAdd`, since nothing can already be in both.
445pub fn interpolate_elements(
446    source: &Stream,
447    destination: &mut Stream,
448    start: (FloatType, FloatType),
449    end: (FloatType, FloatType),
450) -> Result<()> {
451    let (start_source, end_source) = (start.0, end.0);
452    // Checked before the walk, so two points at one offset are refused even
453    // with nothing between them.
454    interpolated_offset(start_source, start, end)?;
455    for event in source.events() {
456        if event.offset() > start_source && event.offset() < end_source {
457            destination.insert(
458                interpolated_offset(event.offset(), start, end)?,
459                event.element().clone(),
460            );
461        }
462    }
463    Ok(())
464}
465
466/// Where a thing standing at `offset` in the source lands in the destination,
467/// the same proportion of the way between the two points: the arithmetic of
468/// [`interpolate_elements`], for a caller that moves things of its own.
469///
470/// `start` and `end` are each a point's offset in the source and in the
471/// destination. It is an error for the two to stand at one offset in the
472/// source, since then nothing lies between them to scale.
473///
474/// ```
475/// use music21::tempo::interpolated_offset;
476///
477/// assert_eq!(interpolated_offset(11.0, (10.0, 20.5), (14.0, 25.0))?, 21.625);
478/// # Ok::<(), music21::Error>(())
479/// ```
480pub fn interpolated_offset(
481    offset: FloatType,
482    start: (FloatType, FloatType),
483    end: (FloatType, FloatType),
484) -> Result<FloatType> {
485    let ((start_source, start_destination), (end_source, end_destination)) = (start, end);
486    if end_source == start_source {
487        return Err(Error::Tempo(
488            "the two points stand at the same offset in the source, so nothing lies between them"
489                .to_string(),
490        ));
491    }
492    let scale = (end_destination - start_destination) / (end_source - start_source);
493    Ok(scale * (offset - start_source) + start_destination)
494}
495
496/// Which side of a [`MetricModulation`] something is on: the mark in force
497/// before it, or the mark after. music21 calls them `'left'` and `'right'`.
498#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
499#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
500pub enum ModulationSide {
501    /// The mark in force before the modulation: music21's `'left'`.
502    Old,
503    /// The mark in force after it: music21's `'right'`.
504    New,
505}
506
507/// A tempo said in words and not in numbers: music21's `TempoText`.
508///
509/// ```
510/// use music21::tempo::TempoText;
511///
512/// let slow = TempoText::new("slow");
513/// assert_eq!(slow.metronome_mark().number(), Some(56.0));
514/// assert!(TempoText::new("Largo e piano").is_common_tempo_text());
515/// assert!(!TempoText::new("undulating").is_common_tempo_text());
516/// ```
517#[derive(Clone, Debug, PartialEq)]
518#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
519#[must_use]
520pub struct TempoText {
521    text: String,
522    #[cfg_attr(feature = "serde", serde(default))]
523    placement: Drawn<Option<Placement>>,
524}
525
526impl TempoText {
527    /// A tempo said as `text`.
528    pub fn new(text: impl Into<String>) -> Self {
529        Self {
530            text: text.into(),
531            placement: Drawn(None),
532        }
533    }
534
535    /// Which side of the staff it is written on, where the score says.
536    pub fn placement(&self) -> Option<Placement> {
537        self.placement.0
538    }
539
540    /// Says which side of the staff it is written on.
541    pub fn set_placement(&mut self, placement: Option<Placement>) {
542        self.placement.0 = placement;
543    }
544
545    /// The text as music21's `repr` writes it.
546    ///
547    /// ```
548    /// use music21::tempo::TempoText;
549    ///
550    /// assert_eq!(TempoText::new("Allegro").music21_repr(), "<music21.tempo.TempoText 'Allegro'>");
551    /// ```
552    pub fn music21_repr(&self) -> String {
553        format!(
554            "<music21.tempo.TempoText {}>",
555            crate::common::stringtools::python_str_repr(self.text())
556        )
557    }
558
559    /// The words the tempo is said in.
560    pub fn text(&self) -> &str {
561        &self.text
562    }
563
564    /// Says the tempo in other words.
565    pub fn set_text(&mut self, text: impl Into<String>) {
566        self.text = text.into();
567    }
568
569    /// The metronome mark the words imply: music21's `getMetronomeMark`.
570    pub fn metronome_mark(&self) -> MetronomeMark {
571        MetronomeMark::from_text(self.text.clone())
572    }
573
574    /// Whether the words read as a tempo: music21's `isCommonTempoText`,
575    /// which looks for one of its tempo words inside them, or them inside
576    /// one, ignoring case, spaces and full stops.
577    pub fn is_common_tempo_text(&self) -> bool {
578        is_common_tempo_text(&self.text)
579    }
580}
581
582/// Whether `text` reads as a tempo, as [`TempoText::is_common_tempo_text`]
583/// asks it.
584pub fn is_common_tempo_text(text: &str) -> bool {
585    let stripped = |value: &str| {
586        value
587            .trim()
588            .chars()
589            .filter(|character| *character != ' ' && *character != '.')
590            .collect::<String>()
591            .to_lowercase()
592    };
593    let text = stripped(text);
594    DEFAULT_TEMPO_VALUES.iter().any(|(candidate, _)| {
595        let candidate = stripped(candidate);
596        text.contains(&candidate) || candidate.contains(&text)
597    })
598}
599
600/// A change of tempo written as an equation between two metronome marks:
601/// music21's `MetricModulation`.
602///
603/// The usual one keeps a number and moves it to another note value --
604/// quarter = 60 becoming dotted quarter = 60 -- so the old mark and the new
605/// are what the equation is written with. Either side may be given by its
606/// note value alone and take its number from the other, and the old side may
607/// take it from the mark in force before the modulation, which a score knows
608/// and this type is handed ([`MetricModulation::update_from`]).
609///
610/// ```
611/// use music21::{tempo::{MetricModulation, MetronomeMark}, Duration};
612///
613/// let mut modulation = MetricModulation::new();
614/// modulation.set_old_metronome(Some(MetronomeMark::new(60.0)));
615/// modulation.set_new_referent(Duration::half());
616/// assert_eq!(modulation.number(), Some(60.0));
617/// assert_eq!(modulation.new_metronome().unwrap().quarter_bpm(), Some(120.0));
618/// ```
619#[derive(Clone, Debug, PartialEq)]
620#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
621#[must_use]
622pub struct MetricModulation {
623    old: Option<MetronomeMark>,
624    new: Option<MetronomeMark>,
625    classical_style: bool,
626    maintain_beat: bool,
627    transition_symbol: String,
628    arrow_direction: Option<String>,
629    parentheses: bool,
630    #[cfg_attr(feature = "serde", serde(default))]
631    placement: Drawn<Option<Placement>>,
632}
633
634impl Default for MetricModulation {
635    fn default() -> Self {
636        Self::new()
637    }
638}
639
640impl MetricModulation {
641    /// A modulation between two marks not yet given, written with `=`.
642    pub fn new() -> Self {
643        Self {
644            old: None,
645            new: None,
646            classical_style: false,
647            maintain_beat: false,
648            transition_symbol: "=".to_string(),
649            arrow_direction: None,
650            parentheses: false,
651            placement: Drawn(None),
652        }
653    }
654
655    /// Which side of the staff the modulation is written on, where the
656    /// score says.
657    pub fn placement(&self) -> Option<Placement> {
658        self.placement.0
659    }
660
661    /// Says which side of the staff the modulation is written on.
662    pub fn set_placement(&mut self, placement: Option<Placement>) {
663        self.placement.0 = placement;
664    }
665
666    /// The mark in force before the modulation, if one is given.
667    pub fn old_metronome(&self) -> Option<&MetronomeMark> {
668        self.old.as_ref()
669    }
670
671    /// The mark in force after it, if one is given.
672    pub fn new_metronome(&self) -> Option<&MetronomeMark> {
673        self.new.as_ref()
674    }
675
676    /// Sets the mark in force before the modulation, or takes it away.
677    pub fn set_old_metronome(&mut self, mark: Option<MetronomeMark>) {
678        self.old = mark;
679    }
680
681    /// Sets the mark in force after the modulation, or takes it away.
682    pub fn set_new_metronome(&mut self, mark: Option<MetronomeMark>) {
683        self.new = mark;
684    }
685
686    /// The note value the old mark counts.
687    pub fn old_referent(&self) -> Option<&Duration> {
688        self.old.as_ref().map(MetronomeMark::referent)
689    }
690
691    /// The note value the new mark counts.
692    pub fn new_referent(&self) -> Option<&Duration> {
693        self.new.as_ref().map(MetronomeMark::referent)
694    }
695
696    /// Counts the old side in `referent`: the old mark's own tempo counted
697    /// that way, or where there is none the tempo of `previous` -- the mark
698    /// in force before the modulation -- counted that way, or failing both a
699    /// mark with no number yet. music21's `oldReferent` setter.
700    pub fn set_old_referent(&mut self, referent: Duration, previous: Option<&MetronomeMark>) {
701        self.old = Some(match (&self.old, previous) {
702            (Some(old), _) => old.equivalent_by_referent(referent),
703            (None, Some(previous)) => previous.equivalent_by_referent(referent),
704            (None, None) => MetronomeMark::default().with_referent(referent),
705        });
706    }
707
708    /// Counts the new side in `referent`: the new mark's own tempo counted
709    /// that way, or where there is none the old mark's *number* moved to
710    /// that note value -- the modulation proper -- or failing both a mark
711    /// with no number yet. music21's `newReferent` setter.
712    pub fn set_new_referent(&mut self, referent: Duration) {
713        self.new = Some(match (&self.new, &self.old) {
714            (Some(new), _) => new.equivalent_by_referent(referent),
715            (None, Some(old)) => old.maintained_number_with_referent(referent),
716            (None, None) => MetronomeMark::default().with_referent(referent),
717        });
718    }
719
720    /// The number of the new mark, which is what the modulation sets.
721    pub fn number(&self) -> Option<FloatType> {
722        self.new.as_ref().and_then(MetronomeMark::number)
723    }
724
725    /// Fills in what the marks leave unsaid from `previous`, the mark in
726    /// force before the modulation: music21's `updateByContext`, with the
727    /// context search done by whoever knows the score.
728    ///
729    /// The old side becomes `previous` counted in the old side's note value,
730    /// or `previous` itself where there is no old side; and a new side with
731    /// a note value takes the old side's number, since the number is what a
732    /// modulation keeps.
733    pub fn update_from(&mut self, previous: Option<&MetronomeMark>) {
734        if let Some(previous) = previous {
735            self.old = Some(match &self.old {
736                Some(old) => previous.equivalent_by_referent(old.referent().clone()),
737                None => previous.maintained_number_with_referent(previous.referent().clone()),
738            });
739        }
740        let number = self.old.as_ref().and_then(MetronomeMark::number);
741        if let (Some(new), Some(number)) = (self.new.as_mut(), number) {
742            new.set_number(Some(number));
743        }
744    }
745
746    /// Sets one side to the same tempo as the other counted in `referent`:
747    /// music21's `setEqualityByReferent`. With no side named, the side not
748    /// yet given is the one set; it is an error when both are given or when
749    /// the other side is missing.
750    pub fn set_equality_by_referent(
751        &mut self,
752        side: Option<ModulationSide>,
753        referent: Duration,
754    ) -> Result<()> {
755        self.set_from_other(side, |other| other.equivalent_by_referent(referent))
756    }
757
758    /// Sets one side to the other's number counted in `referent`, which is a
759    /// different tempo: music21's `setOtherByReferent`. The side is chosen
760    /// as [`MetricModulation::set_equality_by_referent`] chooses it.
761    pub fn set_other_by_referent(
762        &mut self,
763        side: Option<ModulationSide>,
764        referent: Duration,
765    ) -> Result<()> {
766        self.set_from_other(side, |other| {
767            other.maintained_number_with_referent(referent)
768        })
769    }
770
771    fn side_to_set(&self, side: Option<ModulationSide>) -> Result<ModulationSide> {
772        side.or(match (&self.old, &self.new) {
773            (None, _) => Some(ModulationSide::Old),
774            (_, None) => Some(ModulationSide::New),
775            _ => None,
776        })
777        .ok_or_else(|| Error::Tempo("cannot set equality for a side of None".to_string()))
778    }
779
780    fn no_other_side() -> Error {
781        Error::Tempo("there is no mark on the other side to take the tempo from".to_string())
782    }
783
784    /// Sets the side `side_to_set` chooses to a mark derived from the other.
785    fn set_from_other(
786        &mut self,
787        side: Option<ModulationSide>,
788        derive: impl FnOnce(&MetronomeMark) -> MetronomeMark,
789    ) -> Result<()> {
790        let (target, other) = match self.side_to_set(side)? {
791            ModulationSide::New => (&mut self.new, &self.old),
792            ModulationSide::Old => (&mut self.old, &self.new),
793        };
794        let other = other.as_ref().ok_or_else(Self::no_other_side)?;
795        *target = Some(derive(other));
796        Ok(())
797    }
798
799    /// Whether the first mark written is the new tempo rather than the old,
800    /// the reverse of the usual order: music21's `classicalStyle`.
801    pub fn classical_style(&self) -> bool {
802        self.classical_style
803    }
804
805    /// Sets whether the first mark written is the new tempo.
806    pub fn set_classical_style(&mut self, classical: bool) {
807        self.classical_style = classical;
808    }
809
810    /// Whether the beat is kept after the equation, as it is going from 3/4
811    /// to 6/8: music21's `maintainBeat`.
812    pub fn maintain_beat(&self) -> bool {
813        self.maintain_beat
814    }
815
816    /// Sets whether the beat is kept after the equation.
817    pub fn set_maintain_beat(&mut self, maintain: bool) {
818        self.maintain_beat = maintain;
819    }
820
821    /// What the equation is written with, `=` unless an edition says
822    /// otherwise.
823    pub fn transition_symbol(&self) -> &str {
824        &self.transition_symbol
825    }
826
827    /// Sets what the equation is written with.
828    pub fn set_transition_symbol(&mut self, symbol: impl Into<String>) {
829        self.transition_symbol = symbol.into();
830    }
831
832    /// Which way an arrow drawn for the equation points, where older
833    /// editions draw one: `"left"`, `"right"`, or none.
834    pub fn arrow_direction(&self) -> Option<&str> {
835        self.arrow_direction.as_deref()
836    }
837
838    /// Sets which way the arrow points, or takes it away.
839    pub fn set_arrow_direction(&mut self, direction: Option<String>) {
840        self.arrow_direction = direction;
841    }
842
843    /// Whether the equation is written in parentheses.
844    pub fn parentheses(&self) -> bool {
845        self.parentheses
846    }
847
848    /// Sets whether the equation is written in parentheses.
849    pub fn set_parentheses(&mut self, parentheses: bool) {
850        self.parentheses = parentheses;
851    }
852}
853
854/// A number as music21 keeps it, a whole one as an integer.
855fn python_number(number: FloatType) -> String {
856    if number.fract() == 0.0 {
857        format!("{}", number as i64)
858    } else {
859        crate::statistics::python_repr(number)
860    }
861}
862
863#[cfg(test)]
864mod tests {
865    #[test]
866    fn a_number_a_hair_off_a_whole_one_is_that_whole_number() {
867        // Read off music21: dotted quarter = 110 counted in quarters is 165,
868        // and a dotted quarter at 165 is 247.5 quarters a minute.
869        let mark = super::MetronomeMark::new(110.0)
870            .with_referent(super::Duration::from_type_with_dots(
871                crate::duration::DurationType::Quarter,
872                1,
873            ))
874            .equivalent_by_referent(super::Duration::quarter());
875        assert_eq!(mark.number(), Some(165.0));
876        let dotted = mark.maintained_number_with_referent(super::Duration::from_type_with_dots(
877            crate::duration::DurationType::Quarter,
878            1,
879        ));
880        assert_eq!(dotted.quarter_bpm(), Some(247.5));
881    }
882
883    use super::*;
884
885    #[test]
886    fn a_mark_can_be_rewritten_one_half_at_a_time() {
887        let mut mark = MetronomeMark::from_text("adagio");
888        assert!(mark.number_implicit());
889        mark.set_number(Some(60.0));
890        assert!(!mark.number_implicit());
891        assert_eq!(mark.number(), Some(60.0));
892        mark.set_number_implicit(true);
893        assert!(mark.number_implicit());
894        mark.set_referent(Duration::half());
895        assert_eq!(mark.referent().quarter_length(), 2.0);
896        assert_eq!(mark.quarter_bpm(), Some(120.0));
897
898        let mut numbered = MetronomeMark::new(90.0);
899        assert!(numbered.text_implicit());
900        numbered.set_text("largo");
901        assert!(!numbered.text_implicit());
902        assert_eq!(numbered.text(), Some("largo"));
903        assert_eq!(numbered.number(), Some(90.0));
904        let mut wordless = MetronomeMark::default();
905        wordless.set_number(Some(184.0));
906        assert_eq!(wordless.text(), Some("presto"));
907        assert!(wordless.text_implicit());
908        wordless.set_number(None);
909        assert_eq!(wordless.number(), None);
910    }
911
912    /// music21's own `getTextExpression` examples.
913    #[test]
914    fn an_implied_word_is_only_answered_when_asked_for() {
915        let presto = MetronomeMark::from_text("presto");
916        assert_eq!(presto.number(), Some(184.0));
917        assert_eq!(presto.text_expression(false), Some("presto"));
918
919        let ninety = MetronomeMark::new(90.0);
920        assert!(ninety.text_implicit());
921        assert_eq!(ninety.text_expression(false), None);
922        assert_eq!(ninety.text_expression(true), Some("maestoso"));
923    }
924
925    #[test]
926    fn a_mark_may_be_played_faster_than_it_is_written() {
927        // music21's own example: a tempo that sounds and is never written.
928        let playback = MetronomeMark::default().with_number_sounding(168.0);
929        assert_eq!(playback.number_sounding(), Some(168.0));
930        // It says nothing: the tempo is played and never written.
931        assert_eq!(playback.number(), None);
932        assert_eq!(playback.text(), None);
933        assert_eq!(playback.quarter_bpm(), None);
934        assert_eq!(playback.sounding_quarter_bpm(), Some(168.0));
935
936        // A mark that says a number keeps it, and only the sounding tempo
937        // reads the other.
938        let mut written = MetronomeMark::new(60.0).with_referent(Duration::half());
939        assert_eq!(written.quarter_bpm(), Some(120.0));
940        assert_eq!(written.sounding_quarter_bpm(), Some(120.0));
941        written.set_number_sounding(Some(90.0));
942        assert_eq!(written.number(), Some(60.0));
943        assert_eq!(written.quarter_bpm(), Some(120.0));
944        assert_eq!(written.sounding_quarter_bpm(), Some(180.0));
945    }
946
947    #[test]
948    fn referent_changes_match_music21() {
949        let quarter_sixty = MetronomeMark::new(60.0);
950        let eighths = quarter_sixty.equivalent_by_referent(Duration::eighth());
951        assert_eq!(eighths.number(), Some(120.0));
952        assert_eq!(eighths.referent().quarter_length(), 0.5);
953        assert_eq!(eighths.text(), Some("larghetto"));
954        let halves = quarter_sixty.equivalent_by_referent(Duration::half());
955        assert_eq!(halves.number(), Some(30.0));
956
957        let andante = MetronomeMark::with_number_and_text(72.0, "andante")
958            .with_referent(Duration::new(1.5).unwrap());
959        let quarters = andante.equivalent_by_referent(Duration::quarter());
960        assert_eq!(quarters.number(), Some(108.0));
961        assert_eq!(quarters.text(), Some("andante"));
962        assert_eq!(
963            andante.equivalent_by_referent(Duration::half()).number(),
964            Some(54.0)
965        );
966
967        let kept = andante.maintained_number_with_referent(Duration::eighth());
968        assert_eq!(kept.number(), Some(72.0));
969        assert_eq!(kept.referent().quarter_length(), 0.5);
970        assert_eq!(kept.text(), Some("andante"));
971    }
972
973    #[test]
974    fn numbers_imply_the_tempo_words_music21_picks() {
975        let cases = [
976            (120.0, Some("animato")),
977            (60.0, Some("larghetto")),
978            (61.0, Some("larghetto")),
979            (62.0, Some("larghetto")),
980            (63.0, None),
981            (90.0, Some("maestoso")),
982            (92.0, Some("moderate")),
983            (100.0, None),
984            (118.0, Some("animato")),
985            (122.0, Some("animato")),
986            (123.0, None),
987            (16.0, Some("larghissimo")),
988            (12.0, None),
989            (56.5, Some("adagio")),
990            (300.0, None),
991        ];
992        for (number, text) in cases {
993            let mark = MetronomeMark::new(number);
994            assert_eq!(mark.text(), text, "{number}");
995            assert_eq!(mark.text_implicit(), text.is_some(), "{number}");
996            assert!(!mark.number_implicit());
997        }
998    }
999
1000    #[test]
1001    fn words_imply_their_conventional_numbers() {
1002        let cases = [
1003            ("allegro", Some(132.0)),
1004            ("Allegro", Some(132.0)),
1005            ("ALLEGRO ", Some(132.0)),
1006            ("très vite", Some(144.0)),
1007            ("andante moderato", Some(83.0)),
1008            ("unknown words", None),
1009        ];
1010        for (text, number) in cases {
1011            let mark = MetronomeMark::from_text(text);
1012            assert_eq!(mark.number(), number, "{text}");
1013            assert_eq!(mark.number_implicit(), number.is_some(), "{text}");
1014            assert_eq!(mark.text(), Some(text));
1015            assert!(!mark.text_implicit());
1016        }
1017        let both = MetronomeMark::with_number_and_text(120.0, "fast");
1018        assert_eq!(both.number(), Some(120.0));
1019        assert_eq!(both.text(), Some("fast"));
1020        assert!(!both.number_implicit() && !both.text_implicit());
1021    }
1022
1023    #[test]
1024    fn referents_convert_to_quarter_bpm_and_seconds() {
1025        let quarter = MetronomeMark::new(120.0);
1026        assert_eq!(quarter.quarter_bpm(), Some(120.0));
1027        assert_eq!(quarter.quarter_length_to_seconds(1.0).unwrap(), 0.5);
1028        assert_eq!(
1029            quarter.seconds_to_duration(0.75).unwrap().quarter_length(),
1030            1.5
1031        );
1032
1033        let half = MetronomeMark::new(60.0).with_referent(Duration::half());
1034        assert_eq!(half.quarter_bpm(), Some(120.0));
1035        assert_eq!(half.text(), Some("larghetto"));
1036        assert_eq!(half.quarter_length_to_seconds(1.0).unwrap(), 0.5);
1037        assert_eq!(
1038            half.duration_to_seconds(&Duration::new(3.0).unwrap())
1039                .unwrap(),
1040            1.5
1041        );
1042        assert_eq!(half.seconds_to_duration(1.0).unwrap().quarter_length(), 2.0);
1043
1044        let eighth = MetronomeMark::new(120.0).with_referent(Duration::eighth());
1045        assert_eq!(eighth.quarter_bpm(), Some(60.0));
1046        assert_eq!(eighth.seconds_per_quarter().unwrap(), 1.0);
1047
1048        let dotted = MetronomeMark::new(56.5).with_referent(Duration::half());
1049        assert!((dotted.quarter_bpm().unwrap() - 113.0).abs() < 1e-9);
1050
1051        assert_eq!(convert_tempo_by_referent(60.0, 1.0, 2.0), 30.0);
1052        assert_eq!(convert_tempo_by_referent(60.0, 2.0, 1.0), 120.0);
1053
1054        let unknown = MetronomeMark::from_text("unknown words");
1055        assert_eq!(unknown.quarter_bpm(), None);
1056        assert!(unknown.seconds_per_quarter().is_err());
1057
1058        // A mark that says no number but sounds one -- what a MusicXML
1059        // <sound tempo="96"> reads as -- is counted at the one it sounds,
1060        // as music21's getQuarterBPM() takes useNumberSounding=True.
1061        let mut playback = MetronomeMark::from_text("unknown words");
1062        playback.set_number_sounding(Some(96.0));
1063        assert_eq!(playback.number(), None);
1064        assert_eq!(playback.sounding_quarter_bpm(), Some(96.0));
1065        assert!((playback.seconds_per_quarter().expect("seconds") - 0.625).abs() < 1e-12);
1066        assert!(quarter.seconds_to_duration(0.0).is_err());
1067
1068        let motionless = MetronomeMark::new(0.0);
1069        assert_eq!(motionless.quarter_bpm(), Some(0.0));
1070        assert!(motionless.seconds_per_quarter().is_err());
1071        assert!(
1072            motionless
1073                .duration_to_seconds(&Duration::quarter())
1074                .is_err()
1075        );
1076        assert!(motionless.quarter_length_to_seconds(1.0).is_err());
1077    }
1078
1079    /// music21's own example: a bar of a score laid against a recording.
1080    #[test]
1081    fn what_lies_between_two_points_keeps_its_place_between_them() {
1082        use crate::{Note, Stream};
1083
1084        let mut source = Stream::new();
1085        for (offset, name) in [
1086            (10.0, "C4"),
1087            (11.0, "D4"),
1088            (12.0, "E4"),
1089            (13.0, "F4"),
1090            (14.0, "G4"),
1091        ] {
1092            source.insert(offset, Note::from_name(name).unwrap());
1093        }
1094        let offsets = |stream: &Stream| -> Vec<FloatType> {
1095            stream.events().iter().map(|event| event.offset()).collect()
1096        };
1097
1098        let mut recording = Stream::new();
1099        interpolate_elements(&source, &mut recording, (10.0, 20.5), (14.0, 25.0)).unwrap();
1100        assert_eq!(offsets(&recording), [21.625, 22.75, 23.875]);
1101
1102        let mut slower = Stream::new();
1103        interpolate_elements(&source, &mut slower, (10.0, 10.1), (14.0, 50.5)).unwrap();
1104        for (found, expected) in offsets(&slower).iter().zip([20.2, 30.3, 40.4]) {
1105            assert!((found - expected).abs() < 1e-9);
1106        }
1107
1108        assert!(interpolate_elements(&source, &mut slower, (10.0, 0.0), (10.0, 4.0)).is_err());
1109    }
1110
1111    #[test]
1112    fn a_metric_modulation_moves_a_number_to_another_note_value() {
1113        // Each answer read off music21 11.0.0b9's MetricModulation.
1114        use super::{MetricModulation, MetronomeMark, ModulationSide};
1115        use crate::Duration;
1116
1117        // Setting both referents first leaves both numbers unsaid.
1118        let mut modulation = MetricModulation::new();
1119        modulation.set_old_referent(Duration::half(), None);
1120        modulation.set_new_referent(Duration::new(0.25).unwrap());
1121        assert_eq!(modulation.number(), None);
1122
1123        // Then an old mark with a number: the new side takes the number.
1124        let mut modulation = MetricModulation::new();
1125        modulation.set_old_referent(Duration::quarter(), None);
1126        modulation.set_new_referent(Duration::eighth());
1127        modulation.set_old_metronome(Some(MetronomeMark::new(60.0)));
1128        modulation.update_from(None);
1129        assert_eq!(modulation.number(), Some(60.0));
1130        assert_eq!(
1131            modulation.new_metronome().unwrap().text(),
1132            Some("larghetto")
1133        );
1134
1135        // Equality keeps the tempo and recounts it: half = 30 is quarter = 60.
1136        let mut modulation = MetricModulation::new();
1137        modulation.set_new_metronome(Some(MetronomeMark::new(60.0)));
1138        modulation
1139            .set_equality_by_referent(None, Duration::half())
1140            .unwrap();
1141        assert_eq!(modulation.old_metronome().unwrap().number(), Some(30.0));
1142
1143        // The other translation keeps the number and changes the tempo.
1144        let mut modulation = MetricModulation::new();
1145        modulation.set_old_metronome(Some(MetronomeMark::new(60.0)));
1146        modulation
1147            .set_other_by_referent(Some(ModulationSide::New), Duration::half())
1148            .unwrap();
1149        assert_eq!(modulation.number(), Some(60.0));
1150        assert_eq!(
1151            modulation.new_metronome().unwrap().quarter_bpm(),
1152            Some(120.0)
1153        );
1154
1155        // With both sides given there is no side to choose.
1156        assert!(
1157            modulation
1158                .set_equality_by_referent(None, Duration::quarter())
1159                .is_err()
1160        );
1161
1162        // The mark in force before fills in an old side counted in eighths.
1163        let mut modulation = MetricModulation::new();
1164        modulation.set_old_referent(Duration::eighth(), None);
1165        modulation.update_from(Some(&MetronomeMark::new(90.0)));
1166        assert_eq!(modulation.old_metronome().unwrap().number(), Some(180.0));
1167    }
1168}