amm_sdk 0.4.0

Abstract Music Manipulation (AMM) Rust SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
use crate::context::{Key, Tempo, TimeSignature};
use crate::note::Note;
use crate::structure::{Chord, MultiVoice, Part, Phrase, Section, Staff};
use crate::temporal::{place_and_merge_part_timeslice, PartTimeslice};
use amm_internal::amm_prelude::*;
use amm_macros::{JsonDeserialize, JsonSerialize};

#[derive(Debug, Default, Eq, PartialEq, JsonDeserialize, JsonSerialize)]
pub struct Composition {
  title: String,
  copyright: Option<String>,
  publisher: Option<String>,
  composers: Vec<String>,
  lyricists: Vec<String>,
  arrangers: Vec<String>,
  metadata: BTreeMap<String, String>,
  parts: Vec<Part>,
  tempo: Tempo,
  starting_key: Key,
  starting_time_signature: TimeSignature,
}

impl Composition {
  #[must_use]
  pub fn new(title: &str, tempo: Option<Tempo>, key: Option<Key>, time_signature: Option<TimeSignature>) -> Self {
    Self {
      title: String::from(title),
      copyright: None,
      publisher: None,
      composers: Vec::new(),
      lyricists: Vec::new(),
      arrangers: Vec::new(),
      metadata: BTreeMap::new(),
      parts: Vec::new(),
      tempo: tempo.unwrap_or_default(),
      starting_key: key.unwrap_or_default(),
      starting_time_signature: time_signature.unwrap_or_default(),
    }
  }

  #[must_use]
  pub fn flatten(&self) -> Self {
    // Combines simultaneously played parts (i.e., multivoices) into single phrases
    // and returns a new Composition that is guaranteed to have no multivoices
    Self {
      title: self.title.clone(),
      copyright: self.copyright.clone(),
      publisher: self.publisher.clone(),
      composers: self.composers.clone(),
      lyricists: self.lyricists.clone(),
      arrangers: self.arrangers.clone(),
      metadata: self.metadata.clone(),
      parts: self.parts.iter().map(Part::flatten).collect(),
      tempo: self.tempo,
      starting_key: self.starting_key,
      starting_time_signature: self.starting_time_signature,
    }
  }

  #[must_use]
  pub fn restructure_staves_as_parts(&self) -> Self {
    // Converts each staff in a part into a new part, ensuring that each part
    // contains only a single staff
    Self {
      title: self.title.clone(),
      copyright: self.copyright.clone(),
      publisher: self.publisher.clone(),
      composers: self.composers.clone(),
      lyricists: self.lyricists.clone(),
      arrangers: self.arrangers.clone(),
      metadata: self.metadata.clone(),
      parts: self.parts.iter().flat_map(Part::extract_staves_as_parts).collect(),
      tempo: self.tempo,
      starting_key: self.starting_key,
      starting_time_signature: self.starting_time_signature,
    }
  }

  pub fn set_title(&mut self, title: &str) -> &mut Self {
    self.title = String::from(title);
    self
  }

  pub fn set_copyright(&mut self, copyright: &str) -> &mut Self {
    self.copyright = Some(String::from(copyright));
    self
  }

  pub fn set_publisher(&mut self, publisher: &str) -> &mut Self {
    self.publisher = Some(String::from(publisher));
    self
  }

  pub fn set_tempo(&mut self, tempo: Tempo) -> &mut Self {
    self.tempo = tempo;
    self
  }

  pub fn set_starting_key(&mut self, key: Key) -> &mut Self {
    self.starting_key = key;
    self
  }

  pub fn set_starting_time_signature(&mut self, time_signature: TimeSignature) -> &mut Self {
    self.starting_time_signature = time_signature;
    self
  }

  pub fn add_composer(&mut self, name: &str) -> &mut Self {
    self.composers.push(String::from(name));
    self
  }

  pub fn add_lyricist(&mut self, name: &str) -> &mut Self {
    self.lyricists.push(String::from(name));
    self
  }

  pub fn add_arranger(&mut self, name: &str) -> &mut Self {
    self.arrangers.push(String::from(name));
    self
  }

  pub fn add_metadata(&mut self, key: &str, value: &str) -> &mut Self {
    self.metadata.insert(String::from(key), String::from(value));
    self
  }

  pub fn add_part(&mut self, name: &str) -> &mut Part {
    self.remove_part_by_name(name).parts.push(Part::new(name));
    unsafe { self.parts.last_mut().unwrap_unchecked() }
  }

  #[must_use]
  pub fn get_title(&self) -> &str {
    &self.title
  }

  #[must_use]
  pub fn get_copyright(&self) -> &Option<String> {
    &self.copyright
  }

  #[must_use]
  pub fn get_publisher(&self) -> &Option<String> {
    &self.publisher
  }

  #[must_use]
  pub fn get_tempo(&self) -> &Tempo {
    &self.tempo
  }

  #[must_use]
  pub fn get_starting_key(&self) -> &Key {
    &self.starting_key
  }

  #[must_use]
  pub fn get_starting_time_signature(&self) -> &TimeSignature {
    &self.starting_time_signature
  }

  #[must_use]
  pub fn get_composers(&self) -> &[String] {
    &self.composers
  }

  #[must_use]
  pub fn get_lyricists(&self) -> &[String] {
    &self.lyricists
  }

  #[must_use]
  pub fn get_arrangers(&self) -> &[String] {
    &self.arrangers
  }

  #[must_use]
  pub fn get_metadata(&self) -> &BTreeMap<String, String> {
    &self.metadata
  }

  #[must_use]
  pub fn get_part_names(&self) -> Vec<String> {
    self.parts.iter().map(|part| String::from(part.get_name())).collect()
  }

  #[must_use]
  pub fn get_part_by_name(&self, name: &str) -> Option<&Part> {
    self.parts.iter().find(|part| part.get_name() == name)
  }

  #[must_use]
  pub fn get_part_mut_by_name(&mut self, name: &str) -> Option<&mut Part> {
    self.parts.iter_mut().find(|part| part.get_name() == name)
  }

  #[must_use]
  pub fn get_part(&self, id: usize) -> Option<&Part> {
    self.parts.iter().find(|part| part.get_id() == id)
  }

  #[must_use]
  pub fn get_part_mut(&mut self, id: usize) -> Option<&mut Part> {
    self.parts.iter_mut().find(|part| part.get_id() == id)
  }

  #[must_use]
  pub fn get_chord(&self, id: usize) -> Option<&Chord> {
    self.parts.iter().find_map(|part| part.get_chord(id))
  }

  #[must_use]
  pub fn get_chord_mut(&mut self, id: usize) -> Option<&mut Chord> {
    self.parts.iter_mut().find_map(|part| part.get_chord_mut(id))
  }

  #[must_use]
  pub fn get_multivoice(&self, id: usize) -> Option<&MultiVoice> {
    self.parts.iter().find_map(|part| part.get_multivoice(id))
  }

  #[must_use]
  pub fn get_multivoice_mut(&mut self, id: usize) -> Option<&mut MultiVoice> {
    self.parts.iter_mut().find_map(|part| part.get_multivoice_mut(id))
  }

  #[must_use]
  pub fn get_note(&self, id: usize) -> Option<&Note> {
    self.parts.iter().find_map(|part| part.get_note(id))
  }

  #[must_use]
  pub fn get_note_mut(&mut self, id: usize) -> Option<&mut Note> {
    self.parts.iter_mut().find_map(|part| part.get_note_mut(id))
  }

  #[must_use]
  pub fn get_phrase(&self, id: usize) -> Option<&Phrase> {
    self.parts.iter().find_map(|part| part.get_phrase(id))
  }

  #[must_use]
  pub fn get_phrase_mut(&mut self, id: usize) -> Option<&mut Phrase> {
    self.parts.iter_mut().find_map(|part| part.get_phrase_mut(id))
  }

  #[must_use]
  pub fn get_section(&self, id: usize) -> Option<&Section> {
    self.parts.iter().find_map(|part| part.get_section(id))
  }

  #[must_use]
  pub fn get_section_mut(&mut self, id: usize) -> Option<&mut Section> {
    self.parts.iter_mut().find_map(|part| part.get_section_mut(id))
  }

  #[must_use]
  pub fn get_staff(&self, id: usize) -> Option<&Staff> {
    self.parts.iter().find_map(|part| part.get_staff(id))
  }

  #[must_use]
  pub fn get_staff_mut(&mut self, id: usize) -> Option<&mut Staff> {
    self.parts.iter_mut().find_map(|part| part.get_staff_mut(id))
  }

  #[must_use]
  pub fn get_beats(&self) -> f64 {
    self
      .parts
      .iter()
      .map(|part| part.get_beats(&self.tempo.base_note))
      .reduce(f64::max)
      .unwrap_or_default()
  }

  #[must_use]
  pub fn get_duration(&self) -> f64 {
    // Note: Does not take into account fermatas or gradual tempo changes like accelerandos as these are style-dependent
    self.get_beats() * 60.0 / f64::from(self.tempo.beats_per_minute)
  }

  pub fn remove_copyright(&mut self) -> &mut Self {
    self.copyright = None;
    self
  }

  pub fn remove_publisher(&mut self) -> &mut Self {
    self.publisher = None;
    self
  }

  pub fn remove_composer(&mut self, name: &str) -> &mut Self {
    self.composers.retain(|composer| composer != name);
    self
  }

  pub fn remove_lyricist(&mut self, name: &str) -> &mut Self {
    self.lyricists.retain(|lyricist| lyricist != name);
    self
  }

  pub fn remove_arranger(&mut self, name: &str) -> &mut Self {
    self.arrangers.retain(|arranger| arranger != name);
    self
  }

  pub fn remove_metadata(&mut self, key: &str) -> &mut Self {
    self.metadata.remove(key);
    self
  }

  pub fn remove_part_by_name(&mut self, name: &str) -> &mut Self {
    self.parts.retain(|part| part.get_name() != name);
    self
  }

  pub fn remove_item(&mut self, id: usize) -> &mut Self {
    self.parts.retain(|part| part.get_id() != id);
    self.parts.iter_mut().for_each(|part| {
      part.remove_item(id);
    });
    self
  }

  pub fn remove_modification(&mut self, id: usize) -> &mut Self {
    self.iter_mut().for_each(|part| {
      part.remove_modification(id);
    });
    self
  }

  #[must_use]
  pub fn num_timeslices(&self) -> usize {
    self.parts.iter().map(Part::num_timeslices).max().unwrap_or_default()
  }

  pub fn iter(&self) -> core::slice::Iter<'_, Part> {
    self.parts.iter()
  }

  pub fn iter_mut(&mut self) -> core::slice::IterMut<'_, Part> {
    self.parts.iter_mut()
  }

  #[must_use]
  pub fn iter_timeslices(&self) -> impl core::iter::FusedIterator<Item = PartTimeslice> {
    // Return PartTimeslices where each slice contains a map of parts and their current timeslice
    // Note: If you want timeslices for a single part, call `iter_timeslices()` on the part directly
    let mut timeslices: Vec<(f64, PartTimeslice)> = Vec::new();
    for part in &self.parts {
      let part_name = part.get_name();
      let (mut index, mut curr_time) = (0, 0.0);
      for slice in part.iter_timeslices() {
        (index, curr_time) = place_and_merge_part_timeslice(part_name, &mut timeslices, slice, index, curr_time);
      }
    }
    timeslices.into_iter().map(|(_, slice)| slice)
  }
}

impl IntoIterator for Composition {
  type Item = Part;
  type IntoIter = alloc::vec::IntoIter<Self::Item>;
  fn into_iter(self) -> Self::IntoIter {
    self.parts.into_iter()
  }
}

impl<'a> IntoIterator for &'a Composition {
  type Item = &'a Part;
  type IntoIter = core::slice::Iter<'a, Part>;
  fn into_iter(self) -> Self::IntoIter {
    self.iter()
  }
}

impl<'a> IntoIterator for &'a mut Composition {
  type Item = &'a mut Part;
  type IntoIter = core::slice::IterMut<'a, Part>;
  fn into_iter(self) -> Self::IntoIter {
    self.iter_mut()
  }
}

#[cfg(feature = "print")]
impl core::fmt::Display for Composition {
  #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
  fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
    let duration = self.get_duration();
    write!(f, "Composition:\n  Title: {}\n  First Composer: {}\n  First Lyricist: {}\n  First Arranger: {}\n  Publisher: {}\n  Copyright: {}\n  Tempo: {}\n  Key: {}\n  Time Signature: {}\n  Num Parts: {}\n  Length: {:02}:{:02}",
      self.title,
      self.composers.first().unwrap_or(&String::from("Unknown")),
      self.lyricists.first().unwrap_or(&String::from("Unknown")),
      self.arrangers.first().unwrap_or(&String::from("Unknown")),
      self.publisher.as_deref().unwrap_or("Unknown"),
      self.copyright.as_deref().unwrap_or("None"),
      self.tempo,
      self.starting_key,
      self.starting_time_signature,
      self.parts.len(),
      duration as u32 / 60,
      duration as u32 % 60
    )
  }
}