Skip to main content

music21/mei/
step.rs

1//! The steps of music21's `mei.base` that decide what an attribute's value
2//! stands for, one value at a time.
3//!
4//! music21 reads MEI element by element, and its callers call those steps
5//! one by one: `_accidentalFromAttr`, `_qlDurationFromAttr`,
6//! `_sharpsFromAttr`, `_getOctaveShift` and the rest. Each table and rule
7//! here is one of them; [`from_mei`](super::from_mei) reads a whole
8//! document through them, and the wheel's `music21.mei.base` hands its
9//! callers each one.
10
11use crate::defaults::{FloatType, IntegerType};
12use crate::error::{Error, Result};
13use crate::notation::{Syllabic, TieType};
14
15/// music21's `_ACCID_ATTR_DICT`: a written `accid` and the accidental it
16/// names.
17pub const WRITTEN_ACCIDENTALS: [(&str, &str); 17] = [
18    ("s", "#"),
19    ("f", "-"),
20    ("ss", "##"),
21    ("x", "##"),
22    ("ff", "--"),
23    ("xs", "###"),
24    ("ts", "###"),
25    ("tf", "---"),
26    ("n", "n"),
27    ("nf", "-"),
28    ("ns", "#"),
29    ("su", "#~"),
30    ("sd", "~"),
31    ("fu", "`"),
32    ("fd", "-`"),
33    ("nu", "~"),
34    ("nd", "`"),
35];
36
37/// music21's `_ACCID_GES_ATTR_DICT`: a sounding `accid.ges` and the
38/// accidental it names.
39pub const GESTURAL_ACCIDENTALS: [(&str, &str); 9] = [
40    ("s", "#"),
41    ("f", "-"),
42    ("ss", "##"),
43    ("ff", "--"),
44    ("n", "n"),
45    ("su", "#~"),
46    ("sd", "~"),
47    ("fu", "`"),
48    ("fd", "-`"),
49];
50
51/// music21's `_DUR_ATTR_DICT`: a `dur` and its quarter length.
52pub const DURATIONS: [(&str, FloatType); 14] = [
53    ("long", 16.0),
54    ("breve", 8.0),
55    ("1", 4.0),
56    ("2", 2.0),
57    ("4", 1.0),
58    ("8", 0.5),
59    ("16", 0.25),
60    ("32", 0.125),
61    ("64", 0.0625),
62    ("128", 0.03125),
63    ("256", 0.015625),
64    ("512", 0.0078125),
65    ("1024", 0.00390625),
66    ("2048", 0.001953125),
67];
68
69/// The quarter length music21 gives an element with no `dur`, small enough
70/// to be told apart: an `<mRest>` is given its measure's length later.
71pub const NO_DURATION: FloatType = 0.00390625;
72
73/// The class music21 makes for a mark it has none of its own for.
74pub const PLAIN_ARTICULATION: &str = "Articulation";
75
76/// music21's `_ARTIC_ATTR_DICT`: an `artic` and the name of music21's
77/// class for it.
78pub const ARTICULATIONS: [(&str, &str); 30] = [
79    ("acc", "Accent"),
80    ("stacc", "Staccato"),
81    ("ten", "Tenuto"),
82    ("stacciss", "Staccatissimo"),
83    ("marc", "StrongAccent"),
84    ("spicc", "Spiccato"),
85    ("doit", "Doit"),
86    ("plop", "Plop"),
87    ("fall", "Falloff"),
88    ("dnbow", "DownBow"),
89    ("upbow", "UpBow"),
90    ("harm", "Harmonic"),
91    ("snap", "SnapPizzicato"),
92    ("stop", "Stopped"),
93    ("open", "OpenString"),
94    ("dbltongue", "DoubleTongue"),
95    ("toe", "OrganToe"),
96    ("trpltongue", "TripleTongue"),
97    ("heel", "OrganHeel"),
98    ("tap", PLAIN_ARTICULATION),
99    ("lhpizz", PLAIN_ARTICULATION),
100    ("dot", PLAIN_ARTICULATION),
101    ("stroke", PLAIN_ARTICULATION),
102    ("rip", PLAIN_ARTICULATION),
103    ("bend", PLAIN_ARTICULATION),
104    ("flip", PLAIN_ARTICULATION),
105    ("smear", PLAIN_ARTICULATION),
106    ("fingernail", PLAIN_ARTICULATION),
107    ("damp", PLAIN_ARTICULATION),
108    ("dampall", PLAIN_ARTICULATION),
109];
110
111/// The `artic` values that are two marks, which music21 makes apart from
112/// its table.
113pub const COMPOUND_ARTICULATIONS: [(&str, [&str; 2]); 2] = [
114    ("marc-stacc", ["StrongAccent", "Staccato"]),
115    ("ten-stacc", ["Tenuto", "Staccato"]),
116];
117
118/// music21's `_BAR_ATTR_DICT`: a `right` or `rend` and the barline style
119/// it names. Repeats, which start with `rpt`, are made apart.
120pub const BARLINES: [(&str, &str); 6] = [
121    ("dashed", "dashed"),
122    ("dotted", "dotted"),
123    ("dbl", "double"),
124    ("end", "final"),
125    ("invis", "none"),
126    ("single", "regular"),
127];
128
129/// What a repeat's `right` starts with.
130pub const REPEAT_PREFIX: &str = "rpt";
131
132/// music21's `_MEI_UNITDUR_TO_TREMOLO_MARKS`: a `<bTrem>`'s `unitdur` and
133/// the marks its tremolo is drawn with.
134pub const TREMOLO_MARKS: [(&str, IntegerType); 8] = [
135    ("8", 1),
136    ("16", 2),
137    ("32", 3),
138    ("64", 4),
139    ("128", 5),
140    ("256", 6),
141    ("512", 7),
142    ("1024", 8),
143];
144
145/// The octaves a clef's `dis` moves it by.
146const DISPLACEMENTS: [(&str, IntegerType); 3] = [("8", 1), ("15", 2), ("22", 3)];
147
148/// The `dis.place` that moves a clef down.
149const BELOW: &str = "below";
150
151/// The steps of an octave, and the semitones.
152const STEPS_PER_OCTAVE: i64 = 7;
153const SEMITONES_PER_OCTAVE: i64 = 12;
154
155/// The semitones one octave of a transposition may stray from its steps
156/// before music21 decides the steps left an octave out.
157const STRAY_PER_OCTAVE: i64 = 5;
158
159/// A `<syl>`'s `wordpos` and the place in its word it names.
160const WORD_POSITIONS: [(&str, Syllabic); 3] = [
161    ("i", Syllabic::Begin),
162    ("m", Syllabic::Middle),
163    ("t", Syllabic::End),
164];
165
166/// A `<syl>`'s `con` and what joins it to the next syllable.
167const CONNECTORS: [(&str, &str); 4] = [("s", " "), ("d", "-"), ("t", "~"), ("u", "_")];
168
169/// What joins syllables that name no `con`.
170const DEFAULT_CONNECTOR: &str = "-";
171
172/// An MEI document music21 refuses, with its message.
173pub(crate) fn mei_error(message: impl Into<String>) -> Error {
174    Error::mei(message.into())
175}
176
177/// music21's `_UNEXPECTED_ATTR_VALUE`: what music21 says of an attribute
178/// value it has no meaning for.
179pub fn unexpected(name: &str, value: &str) -> String {
180    format!("Unexpected value for \"{name}\" attribute: {value}")
181}
182
183/// music21's `_attrTranslator`: what `attribute` stands for in `table`,
184/// refused by the name of the attribute it was the value of.
185///
186/// ```
187/// use music21::mei::step::{translate, WRITTEN_ACCIDENTALS};
188///
189/// assert_eq!(translate(&WRITTEN_ACCIDENTALS, "s", "accid").unwrap(), "#");
190/// assert!(translate(&WRITTEN_ACCIDENTALS, "q", "accid").is_err());
191/// ```
192pub fn translate<T: Copy>(table: &[(&str, T)], attribute: &str, name: &str) -> Result<T> {
193    table
194        .iter()
195        .find(|(key, _)| *key == attribute)
196        .map(|(_, value)| *value)
197        .ok_or_else(|| mei_error(unexpected(name, attribute)))
198}
199
200/// music21's `_accidentalFromAttr`: the accidental a written `accid`
201/// names, none where there is no `accid`.
202pub fn written_accidental(attribute: Option<&str>) -> Result<Option<&'static str>> {
203    attribute
204        .map(|attribute| translate(&WRITTEN_ACCIDENTALS, attribute, "accid"))
205        .transpose()
206}
207
208/// music21's `_accidGesFromAttr`: the accidental an `accid.ges` names.
209pub fn gestural_accidental(attribute: &str) -> Result<&'static str> {
210    translate(&GESTURAL_ACCIDENTALS, attribute, "accid.ges")
211}
212
213/// music21's `_qlDurationFromAttr`: the quarter length of a `dur`,
214/// [`NO_DURATION`] where there is none.
215pub fn quarter_length(attribute: Option<&str>) -> Result<FloatType> {
216    match attribute {
217        None => Ok(NO_DURATION),
218        Some(attribute) => translate(&DURATIONS, attribute, "dur"),
219    }
220}
221
222/// music21's `_articulationFromAttr`: the names of music21's classes for
223/// the marks one `artic` value names.
224pub fn articulation_classes(attribute: &str) -> Result<Vec<&'static str>> {
225    if let Some((_, pair)) = COMPOUND_ARTICULATIONS
226        .iter()
227        .find(|(name, _)| *name == attribute)
228    {
229        return Ok(pair.to_vec());
230    }
231    Ok(vec![translate(&ARTICULATIONS, attribute, "artic")?])
232}
233
234/// music21's `_sharpsFromAttr`: the sharps a `key.sig` counts, flats
235/// negative.
236///
237/// ```
238/// use music21::mei::step::sharps_of;
239///
240/// assert_eq!(sharps_of("3s").unwrap(), 3);
241/// assert_eq!(sharps_of("3f").unwrap(), -3);
242/// assert_eq!(sharps_of("0").unwrap(), 0);
243/// ```
244pub fn sharps_of(signature: &str) -> Result<IntegerType> {
245    if signature.starts_with('0') {
246        return Ok(0);
247    }
248    let count: IntegerType = signature
249        .get(..1)
250        .unwrap_or_default()
251        .parse()
252        .map_err(|_| mei_error(format!("the key signature {signature:?} has no number")))?;
253    if signature.ends_with('s') {
254        return Ok(count);
255    }
256    Ok(-count)
257}
258
259/// music21's `_getOctaveShift`: the octaves a clef's `dis` and `dis.place`
260/// move it by, down negative.
261pub fn octave_shift(displaced: Option<&str>, place: Option<&str>) -> Result<IntegerType> {
262    let octaves = match displaced {
263        None => 0,
264        Some(displaced) => translate(&DISPLACEMENTS, displaced, "dis")?,
265    };
266    if place == Some(BELOW) {
267        return Ok(-octaves);
268    }
269    Ok(octaves)
270}
271
272/// music21's `_transpositionFromAttrs` before it makes the interval: the
273/// generic interval and the semitones of a `trans.diat` and `trans.semi`.
274///
275/// MEI counts steps from a unison of 0, music21 from 1; a transposition
276/// past an octave written with its steps inside one has the octaves put
277/// back.
278pub fn transposition_steps(diatonic: i64, semitones: i64) -> Result<(IntegerType, IntegerType)> {
279    let mut diatonic = diatonic;
280    let octaves = semitones.abs() / SEMITONES_PER_OCTAVE;
281    if (semitones - diatonic).abs() > STRAY_PER_OCTAVE * (octaves + 1) {
282        diatonic += STEPS_PER_OCTAVE * octaves * semitones.signum();
283    }
284    diatonic += diatonic.signum();
285    let too_far = || mei_error(format!("a transposition of {diatonic} steps is too far"));
286    let generic = IntegerType::try_from(diatonic).map_err(|_| too_far())?;
287    let chromatic = IntegerType::try_from(semitones).map_err(|_| too_far())?;
288    Ok((generic, chromatic))
289}
290
291/// music21's `_tieFromAttr`: the part of a tie a `tie` names.
292pub fn tie_type(attribute: &str) -> TieType {
293    let has = |mark: char| attribute.contains(mark);
294    if has('m') || (has('t') && has('i')) {
295        return TieType::Continue;
296    }
297    if has('i') {
298        return TieType::Start;
299    }
300    TieType::Stop
301}
302
303/// music21's `sylFromElement` before it makes the lyric: a syllable's text
304/// with what joins it to its neighbours, and its place in its word, none
305/// where it names no `wordpos`.
306pub fn syllable(
307    text: &str,
308    word_position: Option<&str>,
309    connector: Option<&str>,
310) -> Result<(String, Option<Syllabic>)> {
311    let Some(word_position) = word_position else {
312        return Ok((text.to_owned(), None));
313    };
314    let joiner = match connector {
315        None => DEFAULT_CONNECTOR,
316        Some(connector) => translate(&CONNECTORS, connector, "con")?,
317    };
318    let syllabic = translate(&WORD_POSITIONS, word_position, "wordpos")?;
319    let joined = match syllabic {
320        Syllabic::Begin => format!("{text}{joiner}"),
321        Syllabic::Middle => format!("{joiner}{text}{joiner}"),
322        _ => format!("{joiner}{text}"),
323    };
324    Ok((joined, Some(syllabic)))
325}
326
327/// The tremolo marks a `<bTrem>`'s `unitdur` names, none for a value
328/// music21 has none for.
329pub fn tremolo_marks(unit: &str) -> Option<IntegerType> {
330    translate(&TREMOLO_MARKS, unit, "unitdur").ok()
331}
332
333/// A random version-4 UUID, as music21 names a slur written apart from its
334/// notes with `uuid4()`; `count` keeps two in one read apart.
335pub fn fresh_uuid(count: usize) -> String {
336    use std::hash::{BuildHasher, Hasher};
337
338    // std seeds each `RandomState` afresh, which is all the randomness
339    // a name needs.
340    let random = std::collections::hash_map::RandomState::new();
341    let mut halves = [0_u64; 2];
342    for (half, made) in halves.iter_mut().enumerate() {
343        let mut hasher = random.build_hasher();
344        hasher.write_usize(count);
345        hasher.write_usize(half);
346        *made = hasher.finish();
347    }
348    let high = (halves[0] & !0xF000) | 0x4000;
349    let low = (halves[1] & 0x3FFF_FFFF_FFFF_FFFF) | 0x8000_0000_0000_0000;
350    format!(
351        "{:08x}-{:04x}-{:04x}-{:04x}-{:012x}",
352        high >> 32,
353        (high >> 16) & 0xFFFF,
354        high & 0xFFFF,
355        low >> 48,
356        low & 0xFFFF_FFFF_FFFF
357    )
358}
359
360/// music21's `removeOctothorpe`: an `xml:id` reference without its `#`.
361///
362/// ```
363/// use music21::mei::step::without_hash;
364///
365/// assert_eq!(without_hash("#e46c"), "e46c");
366/// assert_eq!(without_hash("e46c"), "e46c");
367/// ```
368pub fn without_hash(id: &str) -> &str {
369    id.strip_prefix('#').unwrap_or(id)
370}
371
372#[cfg(test)]
373mod tests {
374    use super::*;
375
376    #[test]
377    fn a_transposition_past_an_octave_has_its_octaves_put_back() {
378        assert_eq!(transposition_steps(-2, -3).unwrap(), (-3, -3));
379        assert_eq!(transposition_steps(4, 7).unwrap(), (5, 7));
380        assert_eq!(transposition_steps(11, 19).unwrap(), (12, 19));
381        assert_eq!(transposition_steps(0, 12).unwrap(), (8, 12));
382        assert_eq!(transposition_steps(-4, -19).unwrap(), (-12, -19));
383        assert_eq!(transposition_steps(1, 26).unwrap(), (16, 26));
384    }
385
386    #[test]
387    fn a_clef_moves_by_its_octaves() {
388        assert_eq!(octave_shift(Some("15"), Some("above")).unwrap(), 2);
389        assert_eq!(octave_shift(Some("22"), Some("below")).unwrap(), -3);
390        assert_eq!(octave_shift(Some("8"), None).unwrap(), 1);
391        assert_eq!(octave_shift(None, None).unwrap(), 0);
392        assert!(octave_shift(Some("9"), None).is_err());
393    }
394
395    #[test]
396    fn a_tie_names_its_part() {
397        assert_eq!(tie_type("i"), TieType::Start);
398        assert_eq!(tie_type("ti"), TieType::Continue);
399        assert_eq!(tie_type("m"), TieType::Continue);
400        assert_eq!(tie_type("t"), TieType::Stop);
401    }
402
403    #[test]
404    fn a_syllable_is_joined_by_its_place() {
405        let (text, place) = syllable("Chri", Some("i"), Some("s")).unwrap();
406        assert_eq!((text.as_str(), place), ("Chri ", Some(Syllabic::Begin)));
407        let (text, place) = syllable("sto", Some("m"), Some("t")).unwrap();
408        assert_eq!((text.as_str(), place), ("~sto~", Some(Syllabic::Middle)));
409        let (text, place) = syllable("pher", Some("t"), None).unwrap();
410        assert_eq!((text.as_str(), place), ("-pher", Some(Syllabic::End)));
411        assert_eq!(syllable("shoe", None, None).unwrap(), ("shoe".into(), None));
412    }
413
414    #[test]
415    fn an_unknown_value_names_its_attribute() {
416        let refused = translate(&DURATIONS, "9", "dur").unwrap_err();
417        assert!(refused.to_string().contains(&unexpected("dur", "9")));
418        assert_eq!(
419            articulation_classes("marc-stacc").unwrap(),
420            ["StrongAccent", "Staccato"]
421        );
422        assert_eq!(tremolo_marks("16"), Some(2));
423        assert_eq!(tremolo_marks("4"), None);
424    }
425}