Skip to main content

music21/
dynamics.rs

1//! Dynamic marks, ported from music21's `dynamics` module.
2//!
3//! A [`Dynamic`] is a mark such as `mf` and the loudness it stands for, a
4//! scalar between nought and one. Placed in a [`Stream`](crate::Stream) it is
5//! in force until the next one, which is what
6//! [`realize_volume`](crate::volume::realize_volume) reads.
7
8use std::fmt;
9
10use crate::{
11    defaults::FloatType,
12    display::Drawn,
13    error::{Error, Result},
14    notation::Placement,
15    style::{StyleValue, TextStyle},
16};
17
18/// The marks music21 lists, softest first: its `shortNames`.
19pub const SHORT_NAMES: [&str; 16] = [
20    "pppppp", "ppppp", "pppp", "ppp", "pp", "p", "mp", "mf", "f", "fp", "sf", "ff", "fff", "ffff",
21    "fffff", "ffffff",
22];
23
24/// The Italian word for a mark, where music21 gives one: its `longNames`.
25const LONG_NAMES: [(&str, &str); 10] = [
26    ("ppp", "pianississimo"),
27    ("pp", "pianissimo"),
28    ("p", "piano"),
29    ("mp", "mezzopiano"),
30    ("mf", "mezzoforte"),
31    ("f", "forte"),
32    ("fp", "fortepiano"),
33    ("sf", "sforzando"),
34    ("ff", "fortissimo"),
35    ("fff", "fortississimo"),
36];
37
38/// What a mark means in English, where music21 says: its `englishNames`.
39const ENGLISH_NAMES: [(&str, &str); 8] = [
40    ("ppp", "extremely soft"),
41    ("pp", "very soft"),
42    ("p", "soft"),
43    ("mp", "moderately soft"),
44    ("mf", "moderately loud"),
45    ("f", "loud"),
46    ("ff", "very loud"),
47    ("fff", "extremely loud"),
48];
49
50/// The loudness each mark stands for: music21's `dynamicStrToScalar`.
51const SCALARS: [(&str, FloatType); 13] = [
52    ("n", 0.0),
53    ("pppp", 0.1),
54    ("ppp", 0.15),
55    ("pp", 0.25),
56    ("p", 0.35),
57    ("mp", 0.45),
58    ("mf", 0.55),
59    ("f", 0.7),
60    ("fp", 0.75),
61    ("sf", 0.85),
62    ("ff", 0.85),
63    ("fff", 0.9),
64    ("ffff", 0.95),
65];
66
67/// The loudness of a mark music21 has no scalar for.
68const DEFAULT_SCALAR: FloatType = 0.5;
69
70fn looked_up<T: Copy>(table: &[(&str, T)], mark: &str) -> Option<T> {
71    table
72        .iter()
73        .find(|(name, _)| *name == mark)
74        .map(|(_, value)| *value)
75}
76
77/// The mark a loudness between nought and one falls under: music21's
78/// `dynamicStrFromDecimal`. Nought is `n`, niente, and `pppp` and `fff` are
79/// the ends of what it answers.
80pub fn dynamic_str_from_decimal(value: FloatType) -> &'static str {
81    match value {
82        value if value <= 0.0 => "n",
83        value if value < 0.11 => "pppp",
84        value if value < 0.16 => "ppp",
85        value if value < 0.26 => "pp",
86        value if value < 0.36 => "p",
87        value if value < 0.5 => "mp",
88        value if value < 0.65 => "mf",
89        value if value < 0.8 => "f",
90        value if value < 0.9 => "ff",
91        _ => "fff",
92    }
93}
94
95/// A dynamic mark and the loudness it stands for.
96///
97/// ```
98/// use music21::Dynamic;
99///
100/// let forte = Dynamic::new("f");
101/// assert_eq!(forte.volume_scalar(), 0.7);
102/// assert_eq!(forte.long_name(), Some("forte"));
103///
104/// // A mark with no loudness of its own is read without its `s` and `z`.
105/// assert_eq!(Dynamic::new("sfz").volume_scalar(), 0.7);
106///
107/// // A loudness names the mark it falls under and keeps its own value.
108/// let soft = Dynamic::from_scalar(0.4)?;
109/// assert_eq!(soft.value(), "mp");
110/// assert_eq!(soft.volume_scalar(), 0.4);
111/// # Ok::<(), music21::Error>(())
112/// ```
113#[derive(Clone, Debug, PartialEq)]
114#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
115#[must_use]
116pub struct Dynamic {
117    value: String,
118    /// A loudness a caller gave, which wins over the mark's own.
119    #[cfg_attr(feature = "serde", serde(default))]
120    volume_scalar: Option<FloatType>,
121    #[cfg_attr(feature = "serde", serde(default))]
122    placement: Drawn<Option<Placement>>,
123    /// Where it is drawn, as music21's `style` says.
124    /// Boxed, as a dynamic is held by value in enums that are mostly small.
125    #[cfg_attr(feature = "serde", serde(default = "default_style"))]
126    style: Box<TextStyle>,
127}
128
129/// Where music21 starts every dynamic off: 36 tenths left of its note and
130/// 80 below the top line, which lines it up under a sixteenth.
131fn default_style() -> Box<TextStyle> {
132    let mut style = TextStyle::default();
133    style.absolute_x = Some(StyleValue::Whole(-36));
134    style.absolute_y = Some(StyleValue::Whole(-80));
135    Box::new(style)
136}
137
138impl Dynamic {
139    /// A dynamic from its mark. Any text is a mark, as it is upstream; one
140    /// music21 has no loudness for sounds at the middle of the range.
141    pub fn new(value: impl Into<String>) -> Self {
142        Self {
143            value: value.into(),
144            volume_scalar: None,
145            placement: Drawn(None),
146            style: default_style(),
147        }
148    }
149
150    /// Where it is drawn: music21's `style`, which starts at 36 tenths to
151    /// the left and 80 down.
152    pub fn style(&self) -> &TextStyle {
153        &self.style
154    }
155
156    /// Says where it is drawn.
157    pub fn set_style(&mut self, style: TextStyle) {
158        *self.style = style;
159    }
160
161    /// Which side of the staff it is written on, where the score says.
162    pub fn placement(&self) -> Option<Placement> {
163        self.placement.0
164    }
165
166    /// Says which side of the staff it is written on.
167    pub fn set_placement(&mut self, placement: Option<Placement>) {
168        self.placement.0 = placement;
169    }
170
171    /// A dynamic from a loudness between nought and one, named as the mark
172    /// that loudness falls under and keeping the loudness itself.
173    pub fn from_scalar(scalar: FloatType) -> Result<Self> {
174        let mut dynamic = Self::new(dynamic_str_from_decimal(scalar));
175        dynamic.set_volume_scalar(scalar)?;
176        Ok(dynamic)
177    }
178
179    /// The mark as written, `mf`.
180    pub fn value(&self) -> &str {
181        &self.value
182    }
183
184    /// Writes another mark. A loudness a caller gave is kept.
185    pub fn set_value(&mut self, value: impl Into<String>) {
186        self.value = value.into();
187    }
188
189    /// The Italian word for the mark, `mezzoforte`, where music21 has one.
190    pub fn long_name(&self) -> Option<&'static str> {
191        looked_up(&LONG_NAMES, &self.value)
192    }
193
194    /// What the mark means in English, where music21 says.
195    pub fn english_name(&self) -> Option<&'static str> {
196        looked_up(&ENGLISH_NAMES, &self.value)
197    }
198
199    /// The loudness the dynamic stands for, between nought and one:
200    /// music21's `volumeScalar`.
201    ///
202    /// The one a caller gave, else the mark's own. A mark with none of its
203    /// own is tried again without a leading letter where it has an `s` in
204    /// it and without a closing `z`, so `sfz` is as loud as `f`; failing
205    /// that it is the middle of the range.
206    pub fn volume_scalar(&self) -> FloatType {
207        if let Some(scalar) = self.volume_scalar {
208            return scalar;
209        }
210        if let Some(scalar) = looked_up(&SCALARS, &self.value) {
211            return scalar;
212        }
213        // music21 drops the first character wherever the mark has an `s`
214        // anywhere in it, which is what is reproduced.
215        let mut mark = self.value.as_str();
216        if mark.contains('s') {
217            let mut characters = mark.chars();
218            characters.next();
219            mark = characters.as_str();
220        }
221        let mark = mark.strip_suffix('z').unwrap_or(mark);
222        looked_up(&SCALARS, mark).unwrap_or(DEFAULT_SCALAR)
223    }
224
225    /// Gives the dynamic a loudness of its own, overriding its mark's.
226    pub fn set_volume_scalar(&mut self, scalar: FloatType) -> Result<()> {
227        if !(0.0..=1.0).contains(&scalar) {
228            return Err(Error::Volume(format!(
229                "cannot set as volume scalar to: {scalar}"
230            )));
231        }
232        self.volume_scalar = Some(scalar);
233        Ok(())
234    }
235}
236
237impl fmt::Display for Dynamic {
238    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
239        write!(f, "{}", self.value)
240    }
241}
242
243#[cfg(test)]
244mod tests {
245    use super::*;
246
247    /// Read off music21; the tables themselves are held to it by
248    /// `table_parity`.
249    #[test]
250    fn a_mark_sounds_as_loud_as_music21_says() {
251        for (mark, scalar) in [
252            ("sf", 0.85),
253            ("sfz", 0.7),
254            ("fp", 0.75),
255            ("rfz", 0.5),
256            ("sffz", 0.85),
257            ("ppppp", 0.5),
258            ("n", 0.0),
259        ] {
260            assert_eq!(Dynamic::new(mark).volume_scalar(), scalar, "{mark}");
261        }
262        assert_eq!(Dynamic::new("sf").long_name(), Some("sforzando"));
263        assert_eq!(Dynamic::new("sf").english_name(), None);
264        assert_eq!(Dynamic::new("mf").english_name(), Some("moderately loud"));
265        assert!(Dynamic::from_scalar(1.5).is_err());
266        assert_eq!(dynamic_str_from_decimal(0.0), "n");
267        assert_eq!(dynamic_str_from_decimal(0.95), "fff");
268    }
269}