1pub mod sequence;
17pub mod tools;
18
19pub use sequence::{MeterTerminal, OffsetAlign};
20
21use crate::defaults::{FloatType, UnsignedIntegerType};
22use crate::duration::Duration;
23use crate::duration::DurationType;
24use crate::error::{Error, Result};
25use crate::notation::{BeamType, Beams};
26
27#[must_use]
31pub fn partition_name(count: usize) -> String {
32 BEAT_COUNT_NAMES
33 .get(count)
34 .map_or_else(|| format!("{count}-uple"), |name| (*name).to_string())
35}
36
37const BEAT_COUNT_NAMES: [&str; 9] = [
41 "Empty",
42 "Single",
43 "Duple",
44 "Triple",
45 "Quadruple",
46 "Quintuple",
47 "Sextuple",
48 "Septuple",
49 "Octuple",
50];
51
52#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
56#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
57pub enum BeatDivision {
58 Other,
61 Simple,
63 Compound,
65}
66
67impl BeatDivision {
68 pub fn music21_name(&self) -> &'static str {
70 match self {
71 Self::Other => "Other",
72 Self::Simple => "Simple",
73 Self::Compound => "Compound",
74 }
75 }
76
77 pub fn count(&self) -> UnsignedIntegerType {
82 match self {
83 Self::Other => 1,
84 Self::Simple => 2,
85 Self::Compound => 3,
86 }
87 }
88}
89
90#[derive(Clone, Debug, PartialEq)]
104#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
105#[must_use]
106pub struct TimeSignature {
107 numerator: UnsignedIntegerType,
108 denominator: UnsignedIntegerType,
109 favor_compound: bool,
110 display_sequence: MeterTerminal,
111 beat_sequence: MeterTerminal,
112 beam_sequence: MeterTerminal,
113 accent_sequence: MeterTerminal,
114 #[cfg_attr(feature = "serde", serde(default))]
116 symbol: Option<String>,
117 #[cfg_attr(feature = "serde", serde(default))]
118 symbolize_denominator: bool,
119 #[cfg_attr(feature = "serde", serde(default))]
120 color: crate::display::Color,
121 #[cfg_attr(feature = "serde", serde(default))]
123 restated: crate::display::Drawn<bool>,
124 #[cfg_attr(feature = "serde", serde(default))]
125 hidden: crate::display::Drawn<bool>,
126 #[cfg_attr(feature = "serde", serde(default))]
129 overridden_bar_duration: Option<Duration>,
130}
131
132impl Default for TimeSignature {
133 fn default() -> Self {
135 Self::common()
136 }
137}
138
139pub const MAX_NUMERATOR: UnsignedIntegerType = 10_000;
143
144impl TimeSignature {
145 pub fn new(numerator: UnsignedIntegerType, denominator: UnsignedIntegerType) -> Result<Self> {
151 if numerator == 0 {
152 return Err(Error::Meter(
153 "time signature numerator must be non-zero".to_string(),
154 ));
155 }
156 if denominator == 0 {
157 return Err(Error::Meter(
158 "time signature denominator must be non-zero".to_string(),
159 ));
160 }
161 if numerator > MAX_NUMERATOR {
162 return Err(Error::Meter(format!(
163 "time signature numerator {numerator} is more than {MAX_NUMERATOR}"
164 )));
165 }
166 let mut signature = Self {
167 numerator,
168 denominator,
169 favor_compound: favor_compound(numerator, denominator, None),
170 display_sequence: whole_bar(numerator, denominator)?,
171 beat_sequence: whole_bar(numerator, denominator)?,
172 beam_sequence: whole_bar(numerator, denominator)?,
173 accent_sequence: whole_bar(numerator, denominator)?,
174 symbol: None,
175 symbolize_denominator: false,
176 color: crate::display::Drawn(None),
177 restated: crate::display::Drawn(false),
178 hidden: crate::display::Drawn(false),
179 overridden_bar_duration: None,
180 };
181 signature.set_default_partitions()?;
182 Ok(signature)
183 }
184
185 pub fn symbol(&self) -> Option<&str> {
189 self.symbol.as_deref()
190 }
191
192 pub fn set_symbol(&mut self, symbol: Option<String>) {
194 self.symbol = symbol.filter(|symbol| !symbol.is_empty());
195 }
196
197 pub fn is_restated(&self) -> bool {
207 self.restated.0
208 }
209
210 pub fn set_restated(&mut self, restated: bool) {
212 self.restated.0 = restated;
213 }
214
215 pub fn symbolize_denominator(&self) -> bool {
218 self.symbolize_denominator
219 }
220
221 pub fn set_symbolize_denominator(&mut self, symbolize: bool) {
223 self.symbolize_denominator = symbolize;
224 }
225
226 pub fn color(&self) -> Option<&str> {
229 self.color.0.as_deref()
230 }
231
232 pub fn set_color(&mut self, color: Option<String>) {
234 self.color.0 = color;
235 }
236
237 pub fn is_hidden(&self) -> bool {
241 self.hidden.0
242 }
243
244 pub fn set_hidden(&mut self, hidden: bool) {
246 self.hidden.0 = hidden;
247 }
248
249 #[must_use]
254 pub fn display_sequence(&self) -> &MeterTerminal {
255 &self.display_sequence
256 }
257
258 #[must_use]
261 pub fn beat_sequence(&self) -> &MeterTerminal {
262 &self.beat_sequence
263 }
264
265 #[must_use]
268 pub fn beam_sequence(&self) -> &MeterTerminal {
269 &self.beam_sequence
270 }
271
272 #[must_use]
276 pub fn accent_sequence(&self) -> &MeterTerminal {
277 &self.accent_sequence
278 }
279
280 #[must_use]
283 pub fn favors_compound(&self) -> bool {
284 self.favor_compound
285 }
286
287 pub fn set_beat_sequence(&mut self, sequence: MeterTerminal) {
290 self.beat_sequence = sequence;
291 }
292
293 pub fn set_beam_sequence(&mut self, sequence: MeterTerminal) {
296 self.beam_sequence = sequence;
297 }
298
299 pub fn set_accent_sequence(&mut self, sequence: MeterTerminal) {
302 self.accent_sequence = sequence;
303 }
304
305 pub fn set_display_sequence(&mut self, sequence: MeterTerminal) {
308 self.display_sequence = sequence;
309 }
310
311 pub fn set_display(&mut self, value: &str) -> Result<()> {
319 let parts = Self::parts(value)?;
320 let denominator = parts
321 .iter()
322 .map(|(_, part)| *part)
323 .max()
324 .unwrap_or(self.denominator);
325 let numerator = parts
326 .iter()
327 .fold(0, |sum: UnsignedIntegerType, (count, part)| {
328 sum.saturating_add(count.saturating_mul(denominator / part))
329 });
330 let display = whole_bar(numerator, denominator)?;
331 if (display.quarter_length() - self.bar_quarter_length()).abs() > OFFSET_TOLERANCE {
332 return Err(Error::Meter(format!(
333 "cannot write a {} bar as {value:?}: that is {} quarter lengths, not {}",
334 self.ratio_string(),
335 display.quarter_length(),
336 self.bar_quarter_length()
337 )));
338 }
339 if parts.len() > 1 {
340 let written: Vec<String> = parts
341 .iter()
342 .map(|(count, part)| format!("{count}/{part}"))
343 .collect();
344 let borrowed: Vec<&str> = written.iter().map(String::as_str).collect();
345 self.display_sequence = display.partitioned_by_parts(&borrowed)?;
346 return Ok(());
347 }
348 self.display_sequence = display;
349 Ok(())
350 }
351
352 pub fn divide_beats(&mut self, count: UnsignedIntegerType) -> Result<()> {
359 if count == 0 {
360 return Err(Error::Meter(
361 "a bar cannot be divided into no parts".to_string(),
362 ));
363 }
364 let divided = whole_bar(self.numerator, self.denominator)?
365 .partitioned_by_count(count as usize, false)?;
366 self.beat_sequence = divided.clone();
369 self.accent_sequence = divided.clone();
370 self.beam_sequence = divided;
371 Ok(())
372 }
373
374 pub fn set_beat_count(&mut self, count: UnsignedIntegerType) -> Result<()> {
381 if count == 0 {
382 return Err(Error::Meter(
383 "a bar cannot be counted in no beats".to_string(),
384 ));
385 }
386 let mut beats = MeterTerminal::new(self.numerator, self.denominator)?
387 .partitioned_by_count(count as usize, false)?;
388 if beats.len() > 1 {
389 beats = beats.subdivided_partitions_equal(None)?;
390 }
391 self.beat_sequence = beats;
392 Ok(())
393 }
394
395 fn set_default_partitions(&mut self) -> Result<()> {
399 self.set_default_beam_partitions()?;
400 self.set_default_beat_partitions()?;
401 self.set_default_accent_weights();
402 Ok(())
403 }
404
405 fn set_default_beam_partitions(&mut self) -> Result<()> {
414 let numerator = self.numerator;
415 let denominator = self.denominator;
416 if self.beam_sequence.summed_numerator() {
417 return Ok(());
418 }
419 if (denominator == 8 && matches!(numerator, 1..=3))
420 || (denominator == 16 && matches!(numerator, 1..=5))
421 || (denominator == 32 && matches!(numerator, 1..=11))
422 {
423 return Ok(());
424 }
425 let beams = &self.beam_sequence;
426 self.beam_sequence = match numerator {
427 2..=4 => {
428 let mut beams = beams.partitioned_by_count(numerator as usize, false)?;
429 if denominator == 4 {
430 for index in 0..beams.len() {
431 let divided = beams.parts()[index].subdivide_by_count(2)?;
432 beams = beams.set_index(index, divided)?;
433 }
434 }
435 beams
436 }
437 5 => {
438 let mut beams = beams.partitioned_by_list(&[2, 3])?;
439 if denominator == 4 {
440 for (index, count) in [2, 3].into_iter().enumerate() {
441 let divided = beams.parts()[index].subdivide_by_count(count)?;
442 beams = beams.set_index(index, divided)?;
443 }
444 }
445 beams
446 }
447 7 => beams.partitioned_by_count(3, false)?,
448 other if other >= 6 && other.is_multiple_of(3) => {
450 beams.partitioned_by_list(&vec![3; (other / 3) as usize])?
451 }
452 _ => return Ok(()),
453 };
454 Ok(())
455 }
456
457 fn set_default_beat_partitions(&mut self) -> Result<()> {
464 let numerator = self.numerator;
465 let compound = self.favor_compound;
466 let beats = &self.beat_sequence;
467 self.beat_sequence = if self.display_sequence.len() == 1 {
468 match numerator {
469 2 => beats.partitioned_by_count(2, false)?,
470 6 if compound => beats.partitioned_by_count(2, false)?,
471 3 if compound => beats.partitioned_by_count(1, false)?,
472 3 => beats.partitioned_by_list(&[1, 1, 1])?,
473 9 if compound => beats.partitioned_by_list(&[3, 3, 3])?,
474 4 => beats.partitioned_by_count(4, false)?,
475 12 if compound => beats.partitioned_by_count(4, false)?,
476 other if other >= 15 && other.is_multiple_of(3) && compound => {
477 beats.partitioned_by_list(&vec![3; (other / 3) as usize])?
478 }
479 other => beats.partitioned_by_count(other as usize, false)?,
480 }
481 } else {
482 let written: Vec<String> = self
483 .display_sequence
484 .parts()
485 .iter()
486 .map(|part| format!("{}/{}", part.numerator(), part.denominator()))
487 .collect();
488 let borrowed: Vec<&str> = written.iter().map(String::as_str).collect();
489 beats.partitioned_by_parts(&borrowed)?
490 };
491 if self.beat_sequence.len() > 1 {
492 match self.beat_sequence.subdivided_partitions_equal(None) {
495 Ok(divided) => self.beat_sequence = divided,
496 Err(error) if self.denominator >= 128 => {
497 let _ = error;
498 }
499 Err(error) => return Err(error),
500 }
501 }
502 Ok(())
503 }
504
505 fn set_default_accent_weights(&mut self) {
509 let weights = self.default_accent_weights();
510 let ones = vec![1; weights.len()];
511 let Ok(partitioned) = self.accent_sequence.partitioned_by_list(&ones) else {
512 return;
513 };
514 let weighed: Vec<MeterTerminal> = partitioned
515 .parts()
516 .iter()
517 .zip(weights)
518 .map(|(part, weight)| part.with_weight(weight))
519 .collect();
520 if let Ok(sequence) =
521 MeterTerminal::sequence(partitioned.numerator(), partitioned.denominator(), weighed)
522 {
523 self.accent_sequence = sequence.with_summed_numerator(partitioned.summed_numerator());
524 }
525 }
526
527 pub fn from_ratio_string(ratio: &str) -> Result<Self> {
536 let parts = Self::parts(ratio)?;
537 if parts.iter().any(|(_, part)| *part == 0) {
538 return Err(Error::Meter(format!(
539 "time signature denominator must be non-zero: {ratio}"
540 )));
541 }
542 let word = division_word(ratio);
543 let summed = ratio.split('+').any(|part| !part.contains('/'));
544 let denominator = parts[0].1;
545 if parts.iter().all(|(_, part)| *part == denominator) {
546 let numerator = parts
547 .iter()
548 .fold(0, |sum: UnsignedIntegerType, (count, _)| {
549 sum.saturating_add(*count)
550 });
551 let mut signature = Self::new(numerator, denominator)?;
552 signature.write_as(&parts, word, summed)?;
553 return Ok(signature);
554 }
555 let denominator = parts
558 .iter()
559 .map(|(_, part)| *part)
560 .max()
561 .unwrap_or(denominator);
562 let numerator = parts
563 .iter()
564 .fold(0, |sum: UnsignedIntegerType, (count, part)| {
565 sum.saturating_add(count.saturating_mul(denominator / part))
566 });
567 let mut signature = Self::new(numerator, denominator)?;
568 signature.write_as(&parts, word, summed)?;
569 Ok(signature)
570 }
571
572 fn write_as(
576 &mut self,
577 parts: &[(UnsignedIntegerType, UnsignedIntegerType)],
578 word: Option<&str>,
579 summed: bool,
580 ) -> Result<()> {
581 self.favor_compound = favor_compound(self.numerator, self.denominator, word);
582 self.beat_sequence = whole_bar(self.numerator, self.denominator)?;
583 self.beam_sequence = whole_bar(self.numerator, self.denominator)?;
584 self.accent_sequence = whole_bar(self.numerator, self.denominator)?;
585 if parts.len() > 1 {
586 let written = parts
593 .iter()
594 .map(|(count, part)| format!("{count}/{part}"))
595 .collect::<Vec<_>>()
596 .join("+");
597 let loaded = MeterTerminal::from_partition_string(&written)?;
598 self.display_sequence = loaded.clone();
599 self.beat_sequence = loaded.clone();
600 self.beam_sequence = loaded;
601 }
602 for sequence in [
605 &mut self.display_sequence,
606 &mut self.beat_sequence,
607 &mut self.beam_sequence,
608 &mut self.accent_sequence,
609 ] {
610 *sequence = sequence.with_summed_numerator(summed);
611 }
612 self.set_default_partitions()
613 }
614
615 #[must_use]
619 pub fn summed_numerator(&self) -> bool {
620 self.display_sequence.summed_numerator()
621 }
622
623 pub fn set_summed_numerator(&mut self, summed: bool) {
626 self.display_sequence = self.display_sequence.with_summed_numerator(summed);
627 }
628
629 pub fn parts(ratio: &str) -> Result<Vec<(UnsignedIntegerType, UnsignedIntegerType)>> {
638 let unworded = without_division_word(ratio);
639 let written = unworded.trim();
640 if written.is_empty() {
641 return Err(Error::Meter("a time signature says nothing".to_string()));
642 }
643 let mut pre: Vec<(UnsignedIntegerType, Option<UnsignedIntegerType>)> = Vec::new();
644 for part in written.split('+') {
645 let part = part.trim();
646 match part.split_once('/') {
647 Some((numerator, denominator)) => pre.push((
648 Self::count(numerator, "numerator", written)?,
649 Some(Self::count(denominator, "denominator", written)?),
650 )),
651 None => pre.push((Self::count(part, "numerator", written)?, None)),
652 }
653 }
654 let mut out = Vec::with_capacity(pre.len());
655 for (index, (numerator, denominator)) in pre.iter().enumerate() {
656 let denominator = match denominator {
657 Some(denominator) => *denominator,
658 None => pre[index + 1..]
659 .iter()
660 .find_map(|(_, later)| *later)
661 .ok_or_else(|| {
662 Error::Meter(format!(
663 "cannot match a denominator to every numerator in {written:?}"
664 ))
665 })?,
666 };
667 out.push((*numerator, denominator));
668 }
669 Ok(out)
670 }
671
672 fn count(part: &str, label: &str, ratio: &str) -> Result<UnsignedIntegerType> {
675 let digits = part
676 .trim()
677 .rsplit(|character: char| character.is_whitespace())
678 .next()
679 .unwrap_or("")
680 .trim();
681 digits
682 .parse::<UnsignedIntegerType>()
683 .map_err(|_| Error::Meter(format!("cannot read a {label} from {part:?} in {ratio:?}")))
684 }
685
686 pub fn common() -> Self {
688 Self::new(4, 4).expect("4/4 is a meter")
689 }
690
691 pub fn cut() -> Self {
693 Self::new(2, 2).expect("2/2 is a meter")
694 }
695
696 pub fn numerator(&self) -> UnsignedIntegerType {
698 self.numerator
699 }
700
701 pub fn denominator(&self) -> UnsignedIntegerType {
703 self.denominator
704 }
705
706 pub fn ratio_string(&self) -> String {
708 if self.display_sequence.len() > 1 {
713 return self.display_sequence.partition_display();
714 }
715 format!("{}/{}", self.numerator, self.denominator)
716 }
717
718 pub fn bar_quarter_length(&self) -> FloatType {
720 FloatType::from(self.numerator) * 4.0 / FloatType::from(self.denominator)
721 }
722
723 pub fn bar_duration(&self) -> Duration {
727 if let Some(written) = &self.overridden_bar_duration {
728 return written.clone();
729 }
730 Duration::new(self.bar_quarter_length())
731 .expect("a non-zero numerator and denominator give a positive finite bar length")
732 }
733
734 pub fn set_bar_duration(&mut self, written: Option<Duration>) {
747 self.overridden_bar_duration = written;
748 }
749
750 pub fn written_bar_duration(&self) -> Option<&Duration> {
753 self.overridden_bar_duration.as_ref()
754 }
755
756 pub fn offset_in_bar(&self, element_offset: FloatType, meter_offset: FloatType) -> FloatType {
770 let bar = self.bar_duration().quarter_length();
773
774 let op_frac = crate::makenotation::op_frac;
779 if op_frac(element_offset + meter_offset) < bar {
780 return element_offset;
781 }
782 op_frac(op_frac(element_offset - meter_offset).rem_euclid(bar))
783 }
784
785 pub fn beat_count(&self) -> UnsignedIntegerType {
791 self.beat_sequence.len() as UnsignedIntegerType
792 }
793
794 pub fn beat_count_name(&self) -> String {
798 partition_name(self.beat_count() as usize)
799 }
800
801 pub fn beat_quarter_length(&self) -> FloatType {
805 let (start, end) = self.beat_spans()[0];
806 end - start
807 }
808
809 pub fn beat_duration(&self) -> Duration {
811 Duration::new(self.beat_quarter_length())
812 .expect("a beat of a meter is a positive finite length")
813 }
814
815 pub fn beat_division(&self) -> BeatDivision {
817 let parts = self.beat_sequence.parts();
818 if parts.len() <= 1 {
819 return BeatDivision::Other;
820 }
821 let mut counts = parts.iter().map(MeterTerminal::len);
822 let Some(first) = counts.next() else {
823 return BeatDivision::Other;
824 };
825 if first == 0 || !counts.all(|count| count == first) {
826 return BeatDivision::Other;
829 }
830 match first {
831 2 => BeatDivision::Simple,
832 3 => BeatDivision::Compound,
833 _ => BeatDivision::Other,
834 }
835 }
836
837 pub fn beat_division_count(&self) -> UnsignedIntegerType {
839 self.beat_division().count()
840 }
841
842 pub fn is_compound(&self) -> bool {
844 self.beat_division() == BeatDivision::Compound
845 }
846
847 pub fn classification(&self) -> String {
849 format!(
850 "{} {}",
851 self.beat_division().music21_name(),
852 self.beat_count_name()
853 )
854 }
855
856 pub fn beat_division_count_name(&self) -> &'static str {
859 self.beat_division().music21_name()
860 }
861
862 pub fn ratio_equal(&self, other: &TimeSignature) -> bool {
865 self.numerator == other.numerator && self.denominator == other.denominator
866 }
867
868 pub fn beat_length_to_quarter_length_ratio(&self) -> FloatType {
871 4.0 / FloatType::from(self.denominator)
872 }
873
874 pub fn quarter_length_to_beat_length_ratio(&self) -> FloatType {
877 FloatType::from(self.denominator) / 4.0
878 }
879
880 pub fn beat_division_quarter_lengths(&self) -> Result<Vec<FloatType>> {
893 let beat_sequence = self.beat_sequence();
894 let beats = match beat_sequence.parts() {
895 [] => std::slice::from_ref(beat_sequence),
896 beats => beats,
897 };
898
899 let divisions = |beat: &MeterTerminal| -> Vec<FloatType> {
902 match beat.parts() {
903 [] => vec![beat.quarter_length()],
904 parts => parts.iter().map(MeterTerminal::quarter_length).collect(),
905 }
906 };
907
908 let every: Vec<FloatType> = beats.iter().flat_map(divisions).collect();
909 if every.windows(2).any(|pair| pair[0] != pair[1]) {
910 return Err(Error::Meter(format!(
911 "non uniform beat division: {every:?}"
912 )));
913 }
914 Ok(beats.first().map(divisions).unwrap_or_default())
915 }
916
917 pub fn beat_division_durations(&self) -> Result<Vec<Duration>> {
920 self.beat_division_quarter_lengths()?
921 .into_iter()
922 .map(Duration::new)
923 .collect()
924 }
925
926 pub fn beat_sub_division_durations(&self) -> Result<Vec<Duration>> {
929 let mut out = Vec::new();
930 for quarter_length in self.beat_division_quarter_lengths()? {
931 let half = Duration::new(quarter_length / 2.0)?;
932 out.push(half.clone());
933 out.push(half);
934 }
935 Ok(out)
936 }
937
938 pub fn offset_from_beat(&self, beat: FloatType) -> Result<FloatType> {
942 let whole = beat.floor();
943 if !beat.is_finite() || whole < 1.0 || whole > FloatType::from(self.beat_count()) {
944 return Err(Error::Meter(format!(
945 "requested beat value ({beat}) not found in the {} beats of {}",
946 self.beat_count(),
947 self.ratio_string()
948 )));
949 }
950 let (start, end) = self.beat_spans()[whole as usize - 1];
951 let fraction = snapped_fraction(beat - whole);
952 Ok(start + fraction * (end - start))
953 }
954
955 pub fn beat_progress(&self, offset: FloatType) -> Result<(UnsignedIntegerType, FloatType)> {
958 let index = self.beat_index(offset)?;
959 let (start, _) = self.beat_spans()[index];
960 Ok((
962 index as UnsignedIntegerType + 1,
963 crate::makenotation::op_frac(offset - start),
964 ))
965 }
966
967 pub fn beat_proportion(&self, offset: FloatType) -> Result<FloatType> {
971 let (beat, progress) = self.beat_progress(offset)?;
972 let (start, end) = self.beat_spans()[beat as usize - 1];
973 Ok(crate::makenotation::op_frac(
974 FloatType::from(beat) + progress / (end - start),
975 ))
976 }
977
978 pub fn beat_proportion_string(&self, offset: FloatType) -> Result<String> {
983 let (beat, progress) = self.beat_progress(offset)?;
984 let (start, end) = self.beat_spans()[beat as usize - 1];
985 let proportion = progress / (end - start);
986 if proportion == 0.0 {
987 return Ok(beat.to_string());
988 }
989 let (numerator, denominator) = closest_fraction(proportion, 16);
990 Ok(format!("{beat} {numerator}/{denominator}"))
991 }
992
993 fn beat_spans(&self) -> Vec<(FloatType, FloatType)> {
997 let mut spans = Vec::new();
998 let mut position = 0.0;
999 for part in self.beat_sequence.parts() {
1000 let end = position + part.quarter_length();
1001 spans.push((position, end));
1002 position = end;
1003 }
1004 if spans.is_empty() {
1005 spans.push((0.0, self.bar_quarter_length()));
1006 }
1007 spans
1008 }
1009
1010 pub fn beat_duration_at(&self, offset: FloatType) -> Result<Duration> {
1016 let index = self.beat_index(offset)?;
1017 let (start, end) = self.beat_spans()[index];
1018 Duration::new(end - start)
1019 }
1020
1021 fn beat_index(&self, offset: FloatType) -> Result<usize> {
1023 if !offset.is_finite() || offset < 0.0 || offset >= self.bar_quarter_length() {
1024 return Err(Error::Meter(format!(
1025 "offset {offset} is outside a {} bar of {} quarter lengths",
1026 self.ratio_string(),
1027 self.bar_quarter_length()
1028 )));
1029 }
1030 let spans = self.beat_spans();
1031 for (index, (start, end)) in spans.iter().enumerate() {
1032 let _ = start;
1033 if offset < end - OFFSET_TOLERANCE {
1034 return Ok(index);
1035 }
1036 }
1037 Ok(spans.len() - 1)
1038 }
1039
1040 pub fn beat_offsets(&self) -> Vec<FloatType> {
1042 self.beat_spans()
1043 .into_iter()
1044 .map(|(start, _)| start)
1045 .collect()
1046 }
1047
1048 pub fn beat_at_offset(&self, offset: FloatType) -> Result<UnsignedIntegerType> {
1053 if !offset.is_finite() || offset < 0.0 || offset >= self.bar_quarter_length() {
1054 return Err(Error::Meter(format!(
1055 "offset {offset} is outside a {} bar of {} quarter lengths",
1056 self.ratio_string(),
1057 self.bar_quarter_length()
1058 )));
1059 }
1060 Ok(self.beat_index(offset)? as UnsignedIntegerType + 1)
1061 }
1062}
1063
1064fn closest_fraction(value: FloatType, max_denominator: u32) -> (u32, u32) {
1068 let mut best = (value.round() as u32, 1);
1069 let mut best_error = (value - value.round()).abs();
1070 for denominator in 2..=max_denominator {
1071 let numerator = (value * FloatType::from(denominator)).round();
1072 let error = (value - numerator / FloatType::from(denominator)).abs();
1073 if error < best_error {
1074 best = (numerator as u32, denominator);
1075 best_error = error;
1076 }
1077 }
1078 best
1079}
1080
1081impl std::fmt::Display for TimeSignature {
1082 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1083 f.write_str(&self.ratio_string())
1084 }
1085}
1086
1087const OFFSET_TOLERANCE: FloatType = 1e-9;
1090
1091const SHORTEST_PARTITION: FloatType = 4.0 / 128.0;
1093
1094const LONGEST_PARTITION: FloatType = 4.0;
1096
1097impl TimeSignature {
1098 fn accent_hierarchy(
1110 &self,
1111 ) -> (
1112 UnsignedIntegerType,
1113 UnsignedIntegerType,
1114 UnsignedIntegerType,
1115 ) {
1116 let beats = self.beat_count();
1117 let first = if beats > 1 { beats } else { self.numerator };
1118 let top = match first {
1119 1 | 2 | 4 | 8 | 16 | 32 => 2,
1120 3 => 3,
1121 other => other,
1122 };
1123 let Some((span, unit)) = split_span(self.numerator, self.denominator, top) else {
1126 return (1, 1, 1);
1127 };
1128 let second = default_division(span, unit);
1129 let Some((span, unit)) = split_span(span, unit, second) else {
1130 return (1, 1, 1);
1131 };
1132 let third = default_division(span, unit);
1133 let partition = self.bar_quarter_length() / FloatType::from(top * second * third);
1138 if !(SHORTEST_PARTITION..=LONGEST_PARTITION).contains(&partition) {
1139 return (1, 1, 1);
1140 }
1141 (top, second, third)
1142 }
1143
1144 pub fn accent_partition_quarter_length(&self) -> FloatType {
1147 let parts = self.accent_sequence.parts();
1148 if parts.len() > 1 {
1149 return parts[0].quarter_length();
1150 }
1151 let (top, second, third) = self.accent_hierarchy();
1152 self.bar_quarter_length() / FloatType::from(top * second * third)
1153 }
1154
1155 pub fn accent_weights(&self) -> Vec<FloatType> {
1160 let carried: Vec<FloatType> = self
1161 .accent_sequence
1162 .parts()
1163 .iter()
1164 .map(MeterTerminal::weight)
1165 .collect();
1166 if carried.len() > 1 {
1167 return carried;
1168 }
1169 self.default_accent_weights()
1170 }
1171
1172 fn default_accent_weights(&self) -> Vec<FloatType> {
1177 if !self.beat_sequence.is_uniform_partition(0)
1178 && let Some(weights) = self.accent_weights_from_the_beats()
1179 {
1180 return weights;
1181 }
1182 let (top, second, third) = self.accent_hierarchy();
1183 let count = top * second * third;
1184 (0..count)
1185 .map(|index| {
1186 let depth = 1
1187 + UnsignedIntegerType::from(index.is_multiple_of(third))
1188 + UnsignedIntegerType::from(index.is_multiple_of(second * third))
1189 + UnsignedIntegerType::from(index == 0);
1190 FloatType::from(2u32.pow(depth - 1)) / 8.0
1191 })
1192 .collect()
1193 }
1194
1195 fn accent_weights_from_the_beats(&self) -> Option<Vec<FloatType>> {
1205 let nested = MeterTerminal::new(self.numerator, self.denominator)
1206 .ok()?
1207 .subdivided_nested_hierarchy_by(3, &self.beat_sequence, true)
1208 .ok()?;
1209 let levels = nested.depth();
1210 if levels == 0 {
1211 return None;
1212 }
1213 let starts: Vec<Vec<FloatType>> = (0..levels)
1214 .map(|level| {
1215 nested
1216 .level_span(level)
1217 .into_iter()
1218 .map(|(start, _)| start)
1219 .collect()
1220 })
1221 .collect();
1222 let depths: Vec<usize> = starts[levels - 1]
1225 .iter()
1226 .map(|start| {
1227 starts
1228 .iter()
1229 .filter(|level| {
1230 level
1231 .iter()
1232 .any(|other| (other - start).abs() < OFFSET_TOLERANCE)
1233 })
1234 .count()
1235 })
1236 .collect();
1237 let deepest = depths.iter().copied().max()?;
1238 Some(
1239 depths
1240 .into_iter()
1241 .map(|depth| {
1242 FloatType::from(2u32.pow(depth as u32 - 1))
1243 / FloatType::from(2u32.pow(deepest as u32 - 1))
1244 })
1245 .collect(),
1246 )
1247 }
1248
1249 pub fn accent(&self, offset: FloatType) -> bool {
1253 let parts = match self.accent_sequence.parts() {
1254 [] => std::slice::from_ref(&self.accent_sequence),
1255 parts => parts,
1256 };
1257 let mut position = 0.0;
1258 for part in parts {
1259 if (position - offset).abs() < OFFSET_TOLERANCE {
1260 return true;
1261 }
1262 position += part.quarter_length();
1263 }
1264 false
1265 }
1266
1267 pub fn accent_weight(&self, offset: FloatType) -> Result<FloatType> {
1271 self.accent_weight_with(offset, false, false)
1272 }
1273
1274 pub fn accent_weight_at_level(
1277 &self,
1278 offset: FloatType,
1279 level: usize,
1280 force_position_match: bool,
1281 permit_meter_modulus: bool,
1282 ) -> Result<FloatType> {
1283 let bar = self.bar_quarter_length();
1284 let offset = if permit_meter_modulus {
1285 offset.rem_euclid(bar)
1286 } else {
1287 offset
1288 };
1289 let offset = offset_within(offset, bar)?;
1290 let terminals = self.accent_sequence.level_list(level, true);
1291 if terminals.len() <= 1 {
1292 return self.accent_weight_with(offset, force_position_match, permit_meter_modulus);
1293 }
1294 let spans = self.accent_sequence.level_span(level);
1295 let smallest = terminals
1296 .iter()
1297 .map(MeterTerminal::weight)
1298 .fold(FloatType::INFINITY, FloatType::min);
1299 for (index, (start, end)) in spans.iter().enumerate() {
1300 if offset < end - OFFSET_TOLERANCE {
1301 if force_position_match && (offset - start).abs() >= OFFSET_TOLERANCE {
1302 return Ok(smallest * 0.5);
1303 }
1304 return Ok(terminals[index].weight());
1305 }
1306 }
1307 Ok(terminals[terminals.len() - 1].weight())
1308 }
1309
1310 pub fn set_accent_weight(&mut self, weights: &[FloatType], level: usize) -> Result<()> {
1313 self.accent_sequence = self.accent_sequence.with_level_weight(level, weights)?;
1314 Ok(())
1315 }
1316
1317 pub fn accent_weight_with(
1322 &self,
1323 offset: FloatType,
1324 force_position_match: bool,
1325 permit_meter_modulus: bool,
1326 ) -> Result<FloatType> {
1327 let bar = self.bar_quarter_length();
1328 let offset = if permit_meter_modulus {
1329 offset.rem_euclid(bar)
1330 } else {
1331 offset
1332 };
1333 let offset = offset_within(offset, bar)?;
1334 let weights = self.accent_weights();
1335 let partition = self.accent_partition_quarter_length();
1336 let index = ((offset + OFFSET_TOLERANCE) / partition).floor() as usize;
1337 let index = index.min(weights.len() - 1);
1338 if force_position_match
1339 && (offset - index as FloatType * partition).abs() >= OFFSET_TOLERANCE
1340 {
1341 let smallest = weights
1342 .iter()
1343 .copied()
1344 .fold(FloatType::INFINITY, FloatType::min);
1345 return Ok(smallest * 0.5);
1346 }
1347 Ok(weights[index])
1348 }
1349
1350 pub fn average_beat_strength(&self, stream: &crate::Stream, notes_only: bool) -> FloatType {
1357 let bar = self.bar_quarter_length();
1358 let offsets: Vec<FloatType> = stream
1359 .events()
1360 .iter()
1361 .filter(|event| !notes_only || crate::makenotation::is_not_rest(event.element()))
1362 .map(crate::stream::StreamEvent::offset)
1363 .collect();
1364 if offsets.is_empty() {
1365 return 0.0;
1366 }
1367 let total: FloatType = offsets
1368 .iter()
1369 .map(|offset| {
1370 self.accent_weight_with(offset.rem_euclid(bar), true, false)
1371 .unwrap_or(0.0)
1372 })
1373 .sum();
1374 total / offsets.len() as FloatType
1375 }
1376
1377 pub fn beat_depth(&self, offset: FloatType) -> Result<u8> {
1383 let bar = self.bar_quarter_length();
1384 if offset.is_nan() || offset < 0.0 || offset >= bar {
1385 return Err(Error::Meter(format!(
1386 "cannot access from qLenPos {}",
1387 offset_repr(offset)
1388 )));
1389 }
1390 let depth = self
1391 .beat_sequence
1392 .offset_to_depth(offset, crate::meter::OffsetAlign::Quantize)?;
1393 Ok(depth as u8)
1394 }
1395}
1396
1397#[must_use]
1404pub fn snapped_fraction(value: FloatType) -> FloatType {
1405 const GRAIN: FloatType = 1e-2;
1406 let thirds = [1.0 / 3.0, 2.0 / 3.0, 1.0 / 6.0, 5.0 / 6.0];
1407 for candidate in thirds {
1408 if (value - candidate).abs() <= GRAIN {
1409 return candidate;
1410 }
1411 }
1412 value
1413}
1414
1415#[derive(Clone, Copy, Debug, PartialEq)]
1422pub struct BeamedNote {
1423 pub offset: FloatType,
1425 pub quarter_length: FloatType,
1427 pub duration_type: DurationType,
1429 pub sounds: bool,
1431}
1432
1433impl TimeSignature {
1434 pub fn beams_for(
1445 &self,
1446 notes: &[BeamedNote],
1447 measure_start_offset: FloatType,
1448 measure_padding: Option<FloatType>,
1449 ) -> Result<Vec<Option<Beams>>> {
1450 if notes.len() <= 1 {
1451 return Ok(notes.iter().map(|_| None).collect());
1452 }
1453
1454 let mut beamed: Vec<Option<Beams>> = notes
1457 .iter()
1458 .map(|note| Beams::naive(Some(note.duration_type), note.sounds))
1459 .collect();
1460 crate::notation::remove_sandwiched_unbeamables(&mut beamed);
1461
1462 for depth in 0..Beams::LEVELS {
1463 for index in 0..notes.len() {
1464 self.fix_one_beam(
1465 &mut beamed,
1466 notes,
1467 index,
1468 depth,
1469 measure_start_offset,
1470 measure_padding,
1471 )?;
1472 }
1473 }
1474
1475 crate::notation::sanitize_partial_beams(&mut beamed);
1476 crate::notation::merge_connecting_partial_beams(&mut beamed);
1477 Ok(beamed)
1478 }
1479
1480 fn fix_one_beam(
1483 &self,
1484 beamed: &mut [Option<Beams>],
1485 notes: &[BeamedNote],
1486 index: usize,
1487 depth: usize,
1488 measure_start_offset: FloatType,
1489 measure_padding: Option<FloatType>,
1490 ) -> Result<()> {
1491 let beam_number = depth as u32 + 1;
1492 let carries = |beams: Option<&Beams>| {
1493 beams.is_some_and(|beams| {
1494 beams
1495 .numbers()
1496 .into_iter()
1497 .flatten()
1498 .any(|n| n == beam_number)
1499 })
1500 };
1501 if !carries(beamed[index].as_ref()) {
1502 return Ok(());
1503 }
1504
1505 let note = notes[index];
1506 let start = note.offset + measure_start_offset;
1507 let end = start + note.quarter_length;
1508 let start_next = end;
1509
1510 let is_first = index == 0;
1511 let is_last = index + 1 == notes.len();
1512
1513 let previous_is_none = is_first || beamed[index - 1].is_none();
1516 let next_is_none = is_last || beamed[index + 1].is_none();
1517 let previous_carries = !is_first && carries(beamed[index - 1].as_ref());
1518 let next_carries = !is_last && carries(beamed[index + 1].as_ref());
1519 let previous_broke = !is_first
1520 && beamed[index - 1].as_ref().is_some_and(|beams| {
1521 beams.by_number(beam_number).is_some_and(|beam| {
1522 matches!(beam.beam_type(), Some(BeamType::Stop))
1523 || (matches!(beam.beam_type(), Some(BeamType::PartialBeam))
1524 && beam.direction() == Some(crate::notation::BeamDirection::Left))
1525 })
1526 });
1527
1528 let archetype = self.beam_sequence.level(depth, true)?;
1529 let (span_start, span_end) = archetype.offset_to_span(start, false)?;
1530 let span_next_start = if next_is_none {
1531 0.0
1532 } else {
1533 archetype.offset_to_span(start_next, false)?.0
1534 };
1535
1536 let same = |a: FloatType, b: FloatType| (a - b).abs() < OFFSET_TOLERANCE;
1537
1538 if same(end, span_end)
1540 && (same(start, span_start) || (previous_is_none && beam_number == 1))
1541 {
1542 beamed[index] = None;
1543 return Ok(());
1544 }
1545
1546 let ends_the_measure = is_last && measure_padding.is_none_or(|padding| padding == 0.0);
1547
1548 let (beam_type, direction) = if is_first && measure_start_offset == 0.0 {
1549 if next_is_none || !next_carries {
1550 (
1551 BeamType::PartialBeam,
1552 Some(crate::notation::BeamDirection::Right),
1553 )
1554 } else {
1555 (BeamType::Start, None)
1556 }
1557 } else if ends_the_measure {
1558 if previous_is_none || !previous_carries {
1559 (
1560 BeamType::PartialBeam,
1561 Some(crate::notation::BeamDirection::Left),
1562 )
1563 } else {
1564 (BeamType::Stop, None)
1565 }
1566 } else if previous_is_none || !previous_carries {
1567 if beam_number == 1 && next_is_none {
1569 beamed[index] = None;
1570 return Ok(());
1571 } else if (next_is_none && beam_number > 1) || start_next >= span_end - OFFSET_TOLERANCE
1572 {
1573 (
1577 BeamType::PartialBeam,
1578 Some(crate::notation::BeamDirection::Left),
1579 )
1580 } else if next_is_none || !next_carries {
1581 (
1582 BeamType::PartialBeam,
1583 Some(crate::notation::BeamDirection::Right),
1584 )
1585 } else {
1586 (BeamType::Start, None)
1587 }
1588 } else if previous_broke {
1589 if next_is_none {
1590 (
1591 BeamType::PartialBeam,
1592 Some(crate::notation::BeamDirection::Left),
1593 )
1594 } else if next_carries {
1595 (BeamType::Start, None)
1596 } else {
1597 (
1598 BeamType::PartialBeam,
1599 Some(crate::notation::BeamDirection::Right),
1600 )
1601 }
1602 } else if next_is_none || !next_carries {
1603 (BeamType::Stop, None)
1604 } else if start_next < span_end - OFFSET_TOLERANCE {
1605 (BeamType::Continue, None)
1606 } else if start_next >= span_next_start - OFFSET_TOLERANCE {
1607 (BeamType::Stop, None)
1608 } else {
1609 return Err(Error::Meter("cannot match beamType".to_string()));
1610 };
1611
1612 if let Some(beams) = beamed[index].as_mut() {
1613 beams.set_by_number(beam_number, beam_type, direction)?;
1614 }
1615 Ok(())
1616 }
1617}
1618
1619fn whole_bar(
1623 numerator: UnsignedIntegerType,
1624 denominator: UnsignedIntegerType,
1625) -> Result<MeterTerminal> {
1626 let whole = format!("{numerator}/{denominator}");
1627 MeterTerminal::new(numerator, denominator)?.partitioned_by_parts(&[whole.as_str()])
1628}
1629
1630fn division_word(ratio: &str) -> Option<&'static str> {
1634 let lower = ratio.to_ascii_lowercase();
1635 if lower.contains("slow") {
1636 Some("slow")
1637 } else if lower.contains("fast") {
1638 Some("fast")
1639 } else {
1640 None
1641 }
1642}
1643
1644fn without_division_word(ratio: &str) -> String {
1646 let mut out = ratio.to_string();
1647 for word in ["slow", "fast"] {
1648 while let Some(at) = out.to_ascii_lowercase().find(word) {
1649 out.replace_range(at..at + word.len(), " ");
1650 }
1651 }
1652 out
1653}
1654
1655fn favor_compound(
1661 numerator: UnsignedIntegerType,
1662 denominator: UnsignedIntegerType,
1663 word: Option<&str>,
1664) -> bool {
1665 match word {
1666 Some("slow") => false,
1667 Some("fast") => true,
1668 _ => !(numerator == 3 && denominator < 8),
1669 }
1670}
1671
1672pub fn best_time_signature(measure: &crate::Stream) -> Result<TimeSignature> {
1684 let elements = measure.recurse();
1685 let sum = elements
1686 .iter()
1687 .filter(|(_, element)| element.as_stream().is_none())
1688 .map(|(offset, element)| offset + element.quarter_length())
1689 .fold(0.0, FloatType::max);
1690
1691 let mut min_dur = 4.0;
1693 let mut min_dots = 0;
1694 for (_, element) in &elements {
1695 let sounds =
1696 element.is_note_or_chord() || matches!(element, crate::stream::StreamElement::Rest(_));
1697 let quarter_length = element.quarter_length();
1698 if sounds && quarter_length != 0.0 && quarter_length < min_dur && is_binary(quarter_length)
1699 {
1700 min_dur = quarter_length;
1701 min_dots = element.duration().map_or(0, Duration::dots);
1702 }
1703 }
1704
1705 let (numerator, denominator) = if is_binary(sum) {
1706 binary_signature(sum, min_dur, min_dots)?
1707 } else {
1708 let (numerator, denominator) = crate::duration::limited_fraction(sum, 65535)
1709 .ok_or_else(|| Error::Meter("Cannot find a good match for this measure".to_string()))?;
1710 (
1711 numerator as UnsignedIntegerType,
1712 denominator as UnsignedIntegerType,
1713 )
1714 };
1715 let (numerator, denominator) = simplified_signature(numerator, denominator)
1716 .ok_or_else(|| Error::Meter("Cannot find a good match for this measure".to_string()))?;
1717
1718 let strength =
1719 |ratio: (UnsignedIntegerType, UnsignedIntegerType)| -> Result<(TimeSignature, FloatType)> {
1720 let signature = TimeSignature::new(ratio.0, ratio.1)?;
1721 let strength = signature.average_beat_strength(measure, true);
1722 Ok((signature, strength))
1723 };
1724 match (numerator, denominator) {
1725 (3, 4) => {
1727 let (three_four, simple) = strength((3, 4))?;
1728 let (six_eight, compound) = strength((6, 8))?;
1729 Ok(if simple <= compound {
1730 six_eight
1731 } else {
1732 three_four
1733 })
1734 }
1735 (6, 4) => {
1737 let (six_four, first) = strength((6, 4))?;
1738 let (twelve_eight, second) = strength((12, 8))?;
1739 let (three_two, third) = strength((3, 2))?;
1740 let most = first.max(second).max(third);
1741 Ok(if most == first {
1742 six_four
1743 } else if most == third {
1744 three_two
1745 } else {
1746 twelve_eight
1747 })
1748 }
1749 _ => TimeSignature::new(numerator, denominator),
1750 }
1751}
1752
1753fn binary_signature(
1758 sum: FloatType,
1759 min_dur: FloatType,
1760 min_dots: u32,
1761) -> Result<(UnsignedIntegerType, UnsignedIntegerType)> {
1762 let no_match = || Error::Meter("Cannot find a good match for this measure".to_string());
1763 let smallest_type = crate::duration::DurationType::from_music21_name("128th")
1764 .expect("music21 names the 128th note");
1765 let limit = smallest_type.quarter_length();
1766 let dot_multiplier =
1767 FloatType::from(2u32.pow(min_dots + 1) - 1) / FloatType::from(2u32.pow(min_dots));
1768
1769 let mut min_test = min_dur;
1770 let mut remaining = 10;
1771 while remaining > 0 {
1772 let parts = sum / min_test;
1773 if parts.floor() == parts || min_test <= limit {
1774 break;
1775 }
1776 min_test /= 2.0 * dot_multiplier;
1777 remaining -= 1;
1778 }
1779 let mut remaining = 10;
1780 while remaining > 0 {
1781 if min_test < limit {
1782 min_test = limit;
1783 break;
1784 }
1785 let (duration_type, matched) =
1786 crate::duration::quarter_length_to_closest_type(min_test).map_err(|_| no_match())?;
1787 if matched || duration_type == smallest_type {
1788 break;
1789 }
1790 min_test /= 2.0 * dot_multiplier;
1791 remaining -= 1;
1792 }
1793 let (duration_type, matched) =
1794 crate::duration::quarter_length_to_closest_type(min_test).map_err(|_| no_match())?;
1795 if !matched {
1796 return Err(Error::Meter(format!(
1797 "cannot find a type for denominator {min_test}"
1798 )));
1799 }
1800 let mut float_denominator = duration_type.type_number().unwrap_or(1.0);
1801 let mut multiplier = 1.0;
1802 let mut numerator_float = 0.0;
1803 while remaining > 0 {
1804 numerator_float = multiplier * sum / min_test;
1805 if numerator_float == numerator_float.floor() {
1806 break;
1807 }
1808 multiplier *= 2.0;
1809 remaining -= 1;
1810 }
1811 float_denominator *= multiplier;
1812 let numerator = numerator_float as UnsignedIntegerType;
1813 let denominator = float_denominator as UnsignedIntegerType;
1814 let divisor = num::integer::gcd(numerator, denominator).max(1);
1815 Ok((numerator / divisor, denominator / divisor))
1816}
1817
1818fn simplified_signature(
1822 numerator: UnsignedIntegerType,
1823 denominator: UnsignedIntegerType,
1824) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
1825 if numerator == denominator && !matches!(numerator, 2 | 4) {
1826 Some((4, 4))
1827 } else if numerator != denominator && denominator == 1 {
1828 Some((numerator.checked_mul(4)?, 4))
1829 } else if numerator != denominator && denominator == 2 {
1830 Some((numerator.checked_mul(2)?, 4))
1831 } else {
1832 Some((numerator, denominator))
1833 }
1834}
1835
1836fn is_binary(quarter_length: FloatType) -> bool {
1840 (quarter_length * 32768.0).fract() == 0.0
1841}
1842
1843fn split_span(
1847 count: UnsignedIntegerType,
1848 unit: UnsignedIntegerType,
1849 parts: UnsignedIntegerType,
1850) -> Option<(UnsignedIntegerType, UnsignedIntegerType)> {
1851 if count.is_multiple_of(parts) {
1852 Some((count / parts, unit))
1853 } else {
1854 Some((count, unit.checked_mul(parts)?))
1855 }
1856}
1857
1858fn default_division(count: UnsignedIntegerType, unit: UnsignedIntegerType) -> UnsignedIntegerType {
1862 let _ = unit;
1863 if count > 3 && count.is_multiple_of(3) {
1864 count / 3
1865 } else if count == 1 || count.is_multiple_of(2) {
1866 2
1867 } else {
1868 count
1869 }
1870}
1871
1872pub(crate) fn offset_repr(offset: FloatType) -> String {
1875 if offset.fract() == 0.0 {
1876 format!("{offset:.1}")
1877 } else {
1878 offset.to_string()
1879 }
1880}
1881
1882fn offset_within(offset: FloatType, length: FloatType) -> Result<FloatType> {
1885 if offset.is_nan() || offset < 0.0 || offset >= length {
1886 return Err(Error::Meter(format!(
1887 "cannot access from qLenPos {} where total duration is {}",
1888 offset_repr(offset),
1889 offset_repr(length)
1890 )));
1891 }
1892 Ok(offset)
1893}
1894
1895#[cfg(test)]
1896mod tests {
1897
1898 #[test]
1899 fn a_meter_counting_more_beats_than_the_limit_is_refused() {
1900 use super::{MAX_NUMERATOR, TimeSignature};
1901
1902 assert!(TimeSignature::new(MAX_NUMERATOR, 4).is_ok());
1903 assert!(TimeSignature::new(MAX_NUMERATOR + 1, 4).is_err());
1904 assert!(TimeSignature::from_ratio_string("99999999/1").is_err());
1905 assert!(TimeSignature::from_ratio_string("6000/4+6000/4").is_err());
1906 assert!(TimeSignature::from_ratio_string("4000000000/4+4000000000/4").is_err());
1907 assert!(TimeSignature::from_ratio_string("4000000000/4+1/8").is_err());
1908 }
1909
1910 #[test]
1911 fn a_meter_with_a_part_over_nought_is_refused() {
1912 use super::TimeSignature;
1913
1914 assert!(TimeSignature::from_ratio_string("3/8+2/0").is_err());
1915 assert!(TimeSignature::from_ratio_string("3/0+2/8").is_err());
1916 }
1917
1918 #[test]
1919 fn a_meter_of_the_shortest_units_is_one_accent() {
1920 use super::TimeSignature;
1921
1922 let signature = TimeSignature::new(1, 1 << 31).unwrap();
1923 assert_eq!(signature.accent_weights(), [1.0]);
1924 }
1925
1926 #[test]
1927 fn an_offset_past_the_bar_wraps_from_where_the_meter_stands() {
1928 let three = TimeSignature::from_ratio_string("3/4").unwrap();
1930 assert_eq!(three.offset_in_bar(2.0, 0.0), 2.0);
1931 assert_eq!(three.offset_in_bar(4.0, 0.0), 1.0);
1932 let five = TimeSignature::from_ratio_string("5/4").unwrap();
1933 assert_eq!(five.offset_in_bar(3.0, 0.0), 3.0);
1934 assert_eq!(five.offset_in_bar(5.0, 0.0), 0.0);
1935
1936 assert_eq!(three.offset_in_bar(1.5, 1.0), 1.5);
1938 assert_eq!(three.offset_in_bar(2.5, 1.0), 1.5);
1939 }
1940
1941 #[test]
1942 fn beat_divisions_are_read_off_the_beats_as_music21_reads_them() {
1943 let cases: [(&str, &[FloatType], &[FloatType]); 9] = [
1946 ("2+3/8", &[0.5, 0.5], &[0.25; 4]),
1947 ("3+3+2/8", &[0.5; 3], &[0.25; 6]),
1948 ("5/8", &[0.25, 0.25], &[0.125; 4]),
1949 ("7/8", &[0.25, 0.25], &[0.125; 4]),
1950 ("4/4", &[0.5, 0.5], &[0.25; 4]),
1951 ("6/8", &[0.5; 3], &[0.25; 6]),
1952 ("5/4", &[0.5, 0.5], &[0.25; 4]),
1953 ("9/8", &[0.5; 3], &[0.25; 6]),
1954 ("3/2", &[1.0, 1.0], &[0.5; 4]),
1955 ];
1956 for (ratio, divisions, subdivisions) in cases {
1957 let meter = TimeSignature::from_ratio_string(ratio).unwrap();
1958 let lengths = |durations: Vec<Duration>| -> Vec<FloatType> {
1959 durations.iter().map(Duration::quarter_length).collect()
1960 };
1961 assert_eq!(
1962 lengths(meter.beat_division_durations().unwrap()),
1963 divisions,
1964 "{ratio}"
1965 );
1966 assert_eq!(
1967 lengths(meter.beat_sub_division_durations().unwrap()),
1968 subdivisions,
1969 "{ratio}"
1970 );
1971 }
1972
1973 for ratio in ["3/4+3/8", "2/4+3/8", "1/4+1/8"] {
1975 let meter = TimeSignature::from_ratio_string(ratio).unwrap();
1976 assert!(meter.beat_division_durations().is_err(), "{ratio}");
1977 }
1978 }
1979 #[test]
1983 fn a_meter_is_read_as_music21_writes_it() {
1984 use crate::meter::TimeSignature;
1985
1986 let plain = TimeSignature::from_ratio_string("6/8").unwrap();
1990 let slow = TimeSignature::from_ratio_string("slow 6/8").unwrap();
1991 assert_eq!(TimeSignature::from_ratio_string("fast 6/8").unwrap(), plain);
1992 assert_ne!(slow, plain);
1993 assert_eq!(
1994 (slow.numerator(), slow.denominator()),
1995 (plain.numerator(), plain.denominator())
1996 );
1997 assert_eq!(plain.beat_sequence().len(), 2);
1998 assert_eq!(slow.beat_sequence().len(), 6);
1999
2000 let additive = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2001 assert_eq!((additive.numerator(), additive.denominator()), (5, 8));
2002 assert_eq!(
2003 TimeSignature::parts("3/8+2/8").unwrap(),
2004 vec![(3, 8), (2, 8)]
2005 );
2006 assert_eq!(TimeSignature::parts("3+2/8").unwrap(), vec![(3, 8), (2, 8)]);
2008 assert_eq!(
2009 TimeSignature::parts("3+2+5/8+3/4").unwrap(),
2010 vec![(3, 8), (2, 8), (5, 8), (3, 4)]
2011 );
2012 let mixed = TimeSignature::from_ratio_string("3/8+1/4").unwrap();
2014 assert_eq!((mixed.numerator(), mixed.denominator()), (5, 8));
2015
2016 assert!(TimeSignature::parts("3+2+5").is_err());
2017 assert!(TimeSignature::from_ratio_string("").is_err());
2018 assert!(TimeSignature::from_ratio_string("3.0/4.0").is_err());
2019 }
2020
2021 #[test]
2022 fn a_summed_numerator_is_beamed_as_it_was_written() {
2023 use crate::meter::TimeSignature;
2024
2025 let expected = [
2030 ("3+2/8", true, "{3/8+2/8}"),
2031 ("3/8+2/8", false, "{2/8+3/8}"),
2032 ("2+3/8", true, "{2/8+3/8}"),
2033 ("3+2+2/8", true, "{3/8+2/8+2/8}"),
2034 ("3/8+2/8+2/8", false, "{2/8+2/8+3/8}"),
2035 ("2+2+3/16", true, "{2/16+2/16+3/16}"),
2036 ("3/16+2/16", false, "{3/16+2/16}"),
2037 ("6/8", false, "{3/8+3/8}"),
2038 ];
2039 for (written, summed, beams) in expected {
2040 let signature = TimeSignature::from_ratio_string(written).unwrap();
2041 assert_eq!(signature.summed_numerator(), summed, "{written}");
2042 assert_eq!(signature.beam_sequence().to_string(), beams, "{written}");
2043 }
2044
2045 let mut signature = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2046 signature.set_summed_numerator(true);
2047 assert!(signature.summed_numerator());
2048 assert!(signature.display_sequence().summed_numerator());
2049 }
2050
2051 #[test]
2052 fn the_sequences_are_partitioned_as_music21_partitions_them() {
2053 use crate::meter::TimeSignature;
2054
2055 let expected = [
2058 ("1/4", "{1/4}", "{1/4}"),
2059 ("2/4", "{{1/8+1/8}+{1/8+1/8}}", "{{1/8+1/8}+{1/8+1/8}}"),
2060 (
2061 "3/4",
2062 "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2063 "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2064 ),
2065 (
2066 "4/4",
2067 "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2068 "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2069 ),
2070 (
2071 "5/4",
2072 "{{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}+{1/8+1/8}}",
2073 "{{1/4+1/4}+{1/4+1/4+1/4}}",
2074 ),
2075 ("6/4", "{{1/4+1/4+1/4}+{1/4+1/4+1/4}}", "{3/4+3/4}"),
2076 ("2/2", "{{1/4+1/4}+{1/4+1/4}}", "{1/2+1/2}"),
2077 ("3/2", "{{1/4+1/4}+{1/4+1/4}+{1/4+1/4}}", "{1/2+1/2+1/2}"),
2078 ("3/8", "{3/8}", "{3/8}"),
2079 (
2080 "5/8",
2081 "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2082 "{2/8+3/8}",
2083 ),
2084 ("6/8", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2085 (
2086 "9/8",
2087 "{{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}}",
2088 "{3/8+3/8+3/8}",
2089 ),
2090 (
2091 "12/8",
2092 "{{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}+{1/8+1/8+1/8}}",
2093 "{3/8+3/8+3/8+3/8}",
2094 ),
2095 (
2096 "5/16",
2097 "{{1/32+1/32}+{1/32+1/32}+{1/32+1/32}+{1/32+1/32}+{1/32+1/32}}",
2098 "{5/16}",
2099 ),
2100 (
2101 "slow 6/8",
2102 "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2103 "{3/8+3/8}",
2104 ),
2105 ("fast 6/8", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2106 ("6/8 fast", "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}", "{3/8+3/8}"),
2107 (
2108 "6/8 Slow",
2109 "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2110 "{3/8+3/8}",
2111 ),
2112 ("3/8+2/8", "{{1/8+1/8+1/8}+{1/8+1/8}}", "{2/8+3/8}"),
2113 ("2/4+3/8", "{{1/4+1/4}+{1/8+1/8+1/8}}", "{2/8+2/8+3/8}"),
2114 ];
2115 for (ratio, beats, beams) in expected {
2116 let signature = TimeSignature::from_ratio_string(ratio).unwrap();
2117 assert_eq!(
2118 signature.beat_sequence().to_string(),
2119 beats,
2120 "beats of {ratio}"
2121 );
2122 assert_eq!(
2123 signature.beam_sequence().to_string(),
2124 beams,
2125 "beams of {ratio}"
2126 );
2127 }
2128 }
2129
2130 #[test]
2132 fn accent_weights_and_beat_depths_follow_the_default_hierarchy() {
2133 let weights = |ratio: &str| {
2134 TimeSignature::from_ratio_string(ratio)
2135 .unwrap()
2136 .accent_weights()
2137 };
2138 assert_eq!(
2139 weights("4/4"),
2140 [1.0, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125]
2141 );
2142 assert_eq!(
2143 weights("6/8"),
2144 [
2145 1.0, 0.125, 0.25, 0.125, 0.25, 0.125, 0.5, 0.125, 0.25, 0.125, 0.25, 0.125
2146 ]
2147 );
2148 assert_eq!(
2149 weights("12/8"),
2150 [
2151 1.0, 0.125, 0.125, 0.25, 0.125, 0.125, 0.5, 0.125, 0.125, 0.25, 0.125, 0.125
2152 ]
2153 );
2154 assert_eq!(weights("3/4").len(), 12);
2155 assert_eq!(weights("24/8").len(), 24);
2156 assert_eq!(
2157 TimeSignature::new(1, 4)
2158 .unwrap()
2159 .accent_partition_quarter_length(),
2160 0.125
2161 );
2162
2163 let three_four = TimeSignature::new(3, 4).unwrap();
2164 let read: Vec<FloatType> = (0..3)
2165 .map(|beat| three_four.accent_weight(FloatType::from(beat)).unwrap())
2166 .collect();
2167 assert_eq!(read, [1.0, 0.5, 0.5]);
2168 let beyond = three_four.accent_weight(3.0).unwrap_err().to_string();
2169 assert!(beyond.ends_with("cannot access from qLenPos 3.0 where total duration is 3.0"));
2170 assert_eq!(weights("16/1"), [1.0]);
2173 assert_eq!(weights("1/32"), [1.0]);
2174 assert_eq!(
2175 TimeSignature::new(24, 4)
2176 .unwrap()
2177 .accent_partition_quarter_length(),
2178 1.0
2179 );
2180 assert_eq!(
2181 three_four.accent_weight_with(4.0, false, true).unwrap(),
2182 0.5
2183 );
2184 assert_eq!(
2185 three_four.accent_weight_with(0.1, true, false).unwrap(),
2186 0.0625
2187 );
2188 assert_eq!(
2189 three_four.accent_weight_with(0.1, false, false).unwrap(),
2190 1.0
2191 );
2192 assert!(three_four.accent(2.0));
2193 assert!(!three_four.accent(0.1));
2194 assert!(!three_four.accent(3.0));
2195
2196 assert_eq!(three_four.beat_depth(0.0).unwrap(), 2);
2197 assert_eq!(three_four.beat_depth(0.25).unwrap(), 2);
2198 assert_eq!(three_four.beat_depth(0.5).unwrap(), 1);
2199 assert_eq!(three_four.beat_depth(1.0).unwrap(), 2);
2200 assert!(three_four.beat_depth(3.0).is_err());
2201 assert_eq!(
2202 TimeSignature::new(3, 8).unwrap().beat_depth(0.5).unwrap(),
2203 1
2204 );
2205 assert_eq!(
2206 TimeSignature::new(6, 8).unwrap().beat_depth(1.0).unwrap(),
2207 1
2208 );
2209 assert_eq!(
2210 TimeSignature::new(6, 8).unwrap().beat_depth(1.5).unwrap(),
2211 2
2212 );
2213 }
2214
2215 #[test]
2217 fn the_best_time_signature_fits_what_the_measure_holds() {
2218 use crate::{Note, Pitch, Stream};
2219
2220 let measure = |lengths: &[FloatType]| {
2221 let mut stream = Stream::new();
2222 for length in lengths {
2223 let mut note = Note::from_pitch(Pitch::from_name("C4").unwrap());
2224 note.set_duration(Duration::new(*length).unwrap());
2225 stream.push(note);
2226 }
2227 stream
2228 };
2229 let best = |lengths: &[FloatType]| {
2230 best_time_signature(&measure(lengths))
2231 .unwrap()
2232 .ratio_string()
2233 };
2234 assert_eq!(best(&[1.0, 1.0, 0.5, 0.5]), "3/4");
2235 assert_eq!(best(&[0.75, 0.25, 0.5, 0.75, 0.25, 0.5]), "6/8");
2236 assert_eq!(best(&[2.0, 2.0, 2.0]), "3/2");
2237 assert_eq!(best(&[0.75, 0.25, 0.5, 0.75, 0.25, 0.5, 1.5, 1.5]), "12/8");
2238 assert_eq!(best(&[1.0, 2.0, 1.0, 2.0]), "6/4");
2239 assert_eq!(best(&[1.0, 0.375]), "11/32");
2240 assert_eq!(best(&[3.5, 5.5]), "9/4");
2241 assert_eq!(best(&[1.0, 1.0, 1.0, 1.0]), "4/4");
2242 assert_eq!(best(&[4.0]), "4/4");
2243 assert_eq!(best(&[1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 1.0]), "2/4");
2245 }
2246
2247 #[test]
2248 fn a_measure_too_long_for_any_signature_has_none() {
2249 use crate::{Note, Pitch, Stream};
2250
2251 let mut note = Note::from_pitch(Pitch::from_name("C4").unwrap());
2252 note.set_duration(Duration::new(4_294_967_296.0).unwrap());
2253 let mut measure = Stream::new();
2254 measure.push(note);
2255 assert!(best_time_signature(&measure).is_err());
2256 }
2257
2258 #[test]
2261 fn beat_strength_is_averaged_over_a_stream() {
2262 use crate::{Note, Pitch, Stream};
2263
2264 let mut stream = Stream::new();
2265 for (name, length) in [("C4", 1.0), ("D4", 1.0), ("E4", 0.5), ("F4", 0.5)] {
2266 let mut note = Note::from_pitch(Pitch::from_name(name).unwrap());
2267 note.set_duration(Duration::new(length).unwrap());
2268 stream.push(note);
2269 }
2270 assert_eq!(
2271 TimeSignature::new(6, 8)
2272 .unwrap()
2273 .average_beat_strength(&stream, true),
2274 0.4375
2275 );
2276 assert_eq!(
2277 TimeSignature::new(3, 4)
2278 .unwrap()
2279 .average_beat_strength(&stream, true),
2280 0.5625
2281 );
2282 stream.insert(0.0, TimeSignature::new(3, 4).unwrap());
2283 stream.insert(0.0, TimeSignature::new(6, 8).unwrap());
2284 assert_eq!(
2285 TimeSignature::new(6, 8)
2286 .unwrap()
2287 .average_beat_strength(&stream, false),
2288 0.625
2289 );
2290 assert_eq!(
2291 TimeSignature::new(4, 4)
2292 .unwrap()
2293 .average_beat_strength(&Stream::new(), true),
2294 0.0
2295 );
2296 }
2297
2298 #[test]
2303 fn a_measure_weighs_its_own_notes_and_not_its_voices() {
2304 use crate::stream::StreamKind;
2305 use crate::{Note, Pitch, Stream};
2306
2307 let mut voice = Stream::with_kind(StreamKind::Voice);
2308 for (name, length) in [("C5", 2.0), ("B4", 1.0)] {
2309 let mut note = Note::from_pitch(Pitch::from_name(name).unwrap());
2310 note.set_duration(Duration::new(length).unwrap());
2311 voice.push(note);
2312 }
2313 let mut plain = voice.clone();
2314 plain.set_kind(StreamKind::Measure);
2315 let mut voiced = Stream::with_kind(StreamKind::Measure);
2316 voiced.insert(0.0, voice);
2317
2318 let three_four = TimeSignature::new(3, 4).unwrap();
2319 assert_eq!(three_four.average_beat_strength(&voiced, true), 0.0);
2320 assert_eq!(best_time_signature(&plain).unwrap().ratio_string(), "3/4");
2321 assert_eq!(best_time_signature(&voiced).unwrap().ratio_string(), "6/8");
2322 }
2323
2324 #[test]
2325 fn a_signature_reports_its_two_numbers_and_its_bar() {
2326 let six_eight = TimeSignature::new(6, 8).unwrap();
2327 assert_eq!((six_eight.numerator(), six_eight.denominator()), (6, 8));
2328 assert_eq!(six_eight.bar_duration().quarter_length(), 3.0);
2329 }
2330
2331 #[test]
2334 fn beat_progress_is_read_through_op_frac() {
2335 let six_eight = TimeSignature::new(6, 8).unwrap();
2336 let (beat, progress) = six_eight.beat_progress(5.0 / 3.0).unwrap();
2337 assert_eq!(beat, 2);
2338 assert_eq!(progress, crate::makenotation::op_frac(1.0 / 6.0));
2339 }
2340
2341 #[test]
2342 fn a_written_bar_length_stands_over_the_meters_own() {
2343 let mut three_eight = TimeSignature::new(3, 8).unwrap();
2344 three_eight.set_bar_duration(Some(Duration::new(1.75).unwrap()));
2345 assert_eq!(three_eight.bar_duration().quarter_length(), 1.75);
2346 assert_eq!(three_eight.bar_quarter_length(), 1.5);
2348
2349 three_eight.set_bar_duration(None);
2350 assert_eq!(three_eight.bar_duration().quarter_length(), 1.5);
2351 }
2352
2353 #[test]
2354 fn division_helpers_match_music21() {
2355 let quarter_lengths = |durations: Vec<Duration>| -> Vec<FloatType> {
2356 durations.into_iter().map(|d| d.quarter_length()).collect()
2357 };
2358 let cases: [(&str, FloatType, &str, &[FloatType], usize); 7] = [
2359 ("4/4", 1.0, "Simple", &[0.5, 0.5], 4),
2360 ("6/8", 0.5, "Compound", &[0.5, 0.5, 0.5], 6),
2361 ("2/2", 2.0, "Simple", &[1.0, 1.0], 4),
2362 ("3/8", 0.5, "Other", &[1.5], 2),
2363 ("7/8", 0.5, "Simple", &[0.25, 0.25], 4),
2364 ("12/16", 0.25, "Compound", &[0.25, 0.25, 0.25], 6),
2365 ("1/4", 1.0, "Other", &[1.0], 2),
2366 ];
2367 for (ratio, beat_to_quarter, division_name, divisions, sub_divisions) in cases {
2368 let ts = ts(ratio);
2369 assert_eq!(
2370 ts.beat_length_to_quarter_length_ratio(),
2371 beat_to_quarter,
2372 "{ratio}"
2373 );
2374 assert_eq!(
2375 ts.quarter_length_to_beat_length_ratio(),
2376 1.0 / beat_to_quarter,
2377 "{ratio}"
2378 );
2379 assert_eq!(ts.beat_division_count_name(), division_name, "{ratio}");
2380 assert_eq!(
2381 quarter_lengths(ts.beat_division_durations().unwrap()),
2382 divisions,
2383 "{ratio}"
2384 );
2385 let subs = quarter_lengths(ts.beat_sub_division_durations().unwrap());
2386 assert_eq!(subs.len(), sub_divisions, "{ratio}");
2387 assert!(subs.iter().all(|ql| *ql == divisions[0] / 2.0), "{ratio}");
2388 }
2389 assert!(ts("4/4").ratio_equal(&ts("4/4")));
2390 assert!(!ts("4/4").ratio_equal(&ts("2/2")));
2391 }
2392
2393 #[test]
2394 fn beat_positions_match_music21() {
2395 let common = ts("4/4");
2396 let cases: [(FloatType, UnsignedIntegerType, FloatType, FloatType, &str); 7] = [
2397 (0.0, 1, 0.0, 1.0, "1"),
2398 (0.5, 1, 0.5, 1.5, "1 1/2"),
2399 (1.25, 2, 0.25, 2.25, "2 1/4"),
2400 (2.75, 3, 0.75, 3.75, "3 3/4"),
2401 (3.0, 4, 0.0, 4.0, "4"),
2402 (3.75, 4, 0.75, 4.75, "4 3/4"),
2403 (3.9, 4, 0.9, 4.9, "4 9/10"),
2404 ];
2405 for (offset, beat, progress, proportion, text) in cases {
2406 let (actual_beat, actual_progress) = common.beat_progress(offset).unwrap();
2407 assert_eq!(actual_beat, beat, "{offset}");
2408 assert!((actual_progress - progress).abs() < 1e-9, "{offset}");
2409 assert!(
2410 (common.beat_proportion(offset).unwrap() - proportion).abs() < 1e-9,
2411 "{offset}"
2412 );
2413 assert_eq!(
2414 common.beat_proportion_string(offset).unwrap(),
2415 text,
2416 "{offset}"
2417 );
2418 }
2419
2420 let compound = ts("6/8");
2421 assert_eq!(compound.beat_proportion_string(0.5).unwrap(), "1 1/3");
2422 assert_eq!(compound.beat_proportion_string(1.0).unwrap(), "1 2/3");
2423 assert_eq!(compound.beat_proportion_string(2.5).unwrap(), "2 2/3");
2424 assert!((compound.beat_proportion(2.0).unwrap() - 7.0 / 3.0).abs() < 1e-9);
2425 assert_eq!(ts("3/8").beat_proportion_string(1.0).unwrap(), "1 2/3");
2426 assert!(common.beat_progress(4.0).is_err());
2427 }
2428
2429 #[test]
2430 fn offset_from_beat_matches_music21() {
2431 let common = ts("4/4");
2432 for (beat, offset) in [
2433 (1.0, 0.0),
2434 (1.5, 0.5),
2435 (2.5, 1.5),
2436 (3.25, 2.25),
2437 (4.75, 3.75),
2438 ] {
2439 assert_eq!(common.offset_from_beat(beat).unwrap(), offset, "{beat}");
2440 }
2441 assert!(common.offset_from_beat(5.0).is_err());
2442 assert!(common.offset_from_beat(0.5).is_err());
2443 let compound = ts("6/8");
2444 assert_eq!(compound.offset_from_beat(1.5).unwrap(), 0.75);
2445 assert_eq!(compound.offset_from_beat(2.5).unwrap(), 2.25);
2446 assert!((compound.offset_from_beat(2.999).unwrap() - 2.9985).abs() < 1e-9);
2447 assert_eq!(ts("3/8").offset_from_beat(1.5).unwrap(), 0.75);
2448 }
2449
2450 #[test]
2451 fn closest_fraction_limits_the_denominator_like_python() {
2452 assert_eq!(closest_fraction(0.5, 16), (1, 2));
2453 assert_eq!(closest_fraction(1.0 / 3.0, 16), (1, 3));
2454 assert_eq!(closest_fraction(0.9, 16), (9, 10));
2455 assert_eq!(closest_fraction(0.75, 16), (3, 4));
2456 assert_eq!(closest_fraction(0.1234, 16), (1, 8));
2457 }
2458 use super::*;
2459
2460 fn ts(ratio: &str) -> TimeSignature {
2461 TimeSignature::from_ratio_string(ratio).expect("valid time signature")
2462 }
2463
2464 #[test]
2465 fn common_and_cut_time_match_their_ratios() {
2466 assert_eq!(TimeSignature::common().ratio_string(), "4/4");
2467 assert_eq!(TimeSignature::cut().ratio_string(), "2/2");
2468 assert_eq!(TimeSignature::default(), TimeSignature::common());
2469 }
2470
2471 #[test]
2472 fn bar_and_beat_lengths_follow_the_ratio() {
2473 assert_eq!(ts("4/4").bar_quarter_length(), 4.0);
2474 assert_eq!(ts("5/16").bar_quarter_length(), 1.25);
2475 assert_eq!(ts("3/8").bar_quarter_length(), 1.5);
2476 assert_eq!(ts("6/8").beat_quarter_length(), 1.5);
2477 assert_eq!(ts("4/4").beat_quarter_length(), 1.0);
2478 assert_eq!(ts("2/2").beat_duration().quarter_length(), 2.0);
2479 }
2480
2481 #[test]
2482 fn compound_meters_beat_in_threes() {
2483 for (ratio, beats, division) in [
2484 ("6/8", 2, BeatDivision::Compound),
2485 ("9/8", 3, BeatDivision::Compound),
2486 ("12/8", 4, BeatDivision::Compound),
2487 ("15/8", 5, BeatDivision::Compound),
2488 ("18/8", 6, BeatDivision::Compound),
2489 ("24/8", 8, BeatDivision::Compound),
2490 ] {
2491 assert_eq!(ts(ratio).beat_count(), beats, "{ratio}");
2492 assert_eq!(ts(ratio).beat_division(), division, "{ratio}");
2493 assert!(ts(ratio).is_compound(), "{ratio}");
2494 }
2495 }
2496
2497 #[test]
2498 fn three_is_the_one_denominator_sensitive_numerator() {
2499 assert_eq!(ts("3/2").beat_count(), 3);
2501 assert_eq!(ts("3/4").beat_count(), 3);
2502 assert_eq!(ts("3/8").beat_count(), 1);
2503 assert_eq!(ts("3/16").beat_count(), 1);
2504 assert_eq!(ts("3/32").beat_count(), 1);
2505 assert_eq!(ts("3/3").beat_count(), 3);
2508 assert_eq!(ts("3/6").beat_count(), 3);
2509 assert_eq!(ts("3/12").beat_count(), 1);
2510 for denominator in [2, 4, 8, 16] {
2512 assert_eq!(TimeSignature::new(6, denominator).unwrap().beat_count(), 2);
2513 assert_eq!(TimeSignature::new(5, denominator).unwrap().beat_count(), 5);
2514 }
2515 }
2516
2517 #[test]
2518 fn a_bar_written_in_unequal_parts_is_counted_along_its_own_beats() {
2519 use crate::meter::TimeSignature;
2520
2521 let mixed = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2524 assert_eq!(mixed.bar_quarter_length(), 3.5);
2525 assert_eq!(mixed.beat_count(), 2);
2526 assert_eq!(mixed.beat_offsets(), vec![0.0, 2.0]);
2527 assert_eq!(mixed.beat_at_offset(2.5).unwrap(), 2);
2528 assert_eq!(mixed.beat_duration_at(0.0).unwrap().quarter_length(), 2.0);
2529 assert_eq!(mixed.beat_duration_at(2.5).unwrap().quarter_length(), 1.5);
2530 assert_eq!(mixed.offset_from_beat(2.0).unwrap(), 2.0);
2531 assert_eq!(mixed.offset_from_beat(1.5).unwrap(), 1.0);
2534 assert_eq!(mixed.beat_proportion_string(2.5).unwrap(), "2 1/3");
2535 assert_eq!(mixed.beat_depth(0.0).unwrap(), 2);
2536
2537 let other = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2538 assert_eq!(other.beat_offsets(), vec![0.0, 1.5]);
2539 assert_eq!(other.offset_from_beat(2.0).unwrap(), 1.5);
2540 assert_eq!(other.offset_from_beat(1.5).unwrap(), 0.75);
2541 assert!(other.beat_proportion_string(2.5).is_err());
2543
2544 let common = TimeSignature::common();
2546 assert_eq!(common.beat_offsets(), vec![0.0, 1.0, 2.0, 3.0]);
2547 assert_eq!(common.offset_from_beat(2.0).unwrap(), 1.0);
2548 assert_eq!(common.offset_from_beat(1.5).unwrap(), 0.5);
2549 assert_eq!(common.beat_proportion_string(2.5).unwrap(), "3 1/2");
2550 }
2551
2552 #[test]
2553 fn a_bar_whose_beats_differ_answers_its_first_beat_length() {
2554 use crate::meter::TimeSignature;
2555
2556 let mixed = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2559 assert_eq!(mixed.beat_quarter_length(), 2.0);
2560 assert_eq!(mixed.beat_duration().quarter_length(), 2.0);
2561 assert!(mixed.beat_division_durations().is_err());
2562 assert_eq!(mixed.beat_division_count(), 1);
2563 assert_eq!(mixed.beat_division_count_name(), "Other");
2564 assert_eq!(mixed.classification(), "Other Duple");
2565
2566 let other = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2567 assert_eq!(other.beat_quarter_length(), 1.5);
2568 assert_eq!(other.beat_division_count(), 1);
2569 assert_eq!(other.classification(), "Other Duple");
2570
2571 assert_eq!(TimeSignature::common().beat_quarter_length(), 1.0);
2573 assert_eq!(
2574 TimeSignature::from_ratio_string("6/8")
2575 .unwrap()
2576 .beat_quarter_length(),
2577 1.5
2578 );
2579 }
2580
2581 #[test]
2582 fn weights_a_caller_sets_are_the_weights_read_back() {
2583 use crate::meter::TimeSignature;
2584
2585 let mut common = TimeSignature::common();
2586 let default = common.accent_weights();
2587 assert_eq!(default[0], 1.0);
2588
2589 common.set_accent_weight(&[0.8, 0.2], 0).unwrap();
2591 let set = common.accent_weights();
2592 assert_eq!(set.len(), default.len());
2593 assert!((set[0] - 0.8).abs() < 1e-9);
2594 assert!((set[1] - 0.2).abs() < 1e-9);
2595 assert!((set[2] - 0.8).abs() < 1e-9);
2596
2597 assert!((common.accent_weight(0.0).unwrap() - 0.8).abs() < 1e-9);
2599
2600 assert_eq!(TimeSignature::common().accent_weights()[0], 1.0);
2602 }
2603
2604 #[test]
2605 fn a_bar_can_be_counted_in_a_different_number_of_beats() {
2606 use crate::meter::TimeSignature;
2607
2608 for (ratio, count, partitioned) in [
2610 (
2611 "6/8",
2612 6,
2613 "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2614 ),
2615 ("6/8", 2, "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}"),
2616 ("4/4", 2, "{{1/4+1/4}+{1/4+1/4}}"),
2617 ("3/4", 1, "{3/4}"),
2618 (
2619 "2/4",
2620 4,
2621 "{{1/16+1/16}+{1/16+1/16}+{1/16+1/16}+{1/16+1/16}}",
2622 ),
2623 ] {
2624 let mut signature = TimeSignature::from_ratio_string(ratio).unwrap();
2625 signature.set_beat_count(count).unwrap();
2626 assert_eq!(
2627 signature.beat_sequence().to_string(),
2628 partitioned,
2629 "{ratio} in {count}"
2630 );
2631 assert_eq!(signature.beat_count(), count, "{ratio} in {count}");
2632 }
2633 }
2634
2635 #[test]
2636 fn a_bar_can_be_written_a_different_way_than_it_is_counted() {
2637 use crate::meter::TimeSignature;
2638
2639 let mut signature = TimeSignature::from_ratio_string("3/4").unwrap();
2642 let counted = signature.beat_sequence().to_string();
2643 signature.set_display("2/8+2/8+2/8").unwrap();
2644 assert_eq!(signature.display_sequence().to_string(), "{2/8+2/8+2/8}");
2645 assert_eq!(
2646 signature.display_sequence().partition_display(),
2647 "2/8+2/8+2/8"
2648 );
2649 assert_eq!(signature.beat_sequence().to_string(), counted);
2651 assert_eq!(signature.beat_count(), 3);
2652 assert!(signature.set_display("2/4").is_err());
2658
2659 let mut common = TimeSignature::common();
2661 common.set_beat_sequence(
2662 common
2663 .beat_sequence()
2664 .partitioned_by_count(2, true)
2665 .unwrap(),
2666 );
2667 assert_eq!(common.beat_count(), 2);
2668 }
2669
2670 #[test]
2671 fn the_divisions_a_meter_is_built_with_partition_its_beats() {
2672 use crate::meter::TimeSignature;
2673
2674 for (ratio, divisions, partitioned) in [
2676 ("3/4", 1, "{3/4}"),
2677 ("6/8", 2, "{3/8+3/8}"),
2678 ("4/4", 2, "{1/2+1/2}"),
2679 ("3/4", 3, "{1/4+1/4+1/4}"),
2680 ] {
2681 let mut signature = TimeSignature::from_ratio_string(ratio).unwrap();
2682 signature.divide_beats(divisions).unwrap();
2683 assert_eq!(
2684 signature.beat_sequence().to_string(),
2685 partitioned,
2686 "{ratio} in {divisions}"
2687 );
2688 }
2689
2690 let mut counted = TimeSignature::from_ratio_string("6/8").unwrap();
2692 counted.set_beat_count(2).unwrap();
2693 assert_eq!(
2694 counted.beat_sequence().to_string(),
2695 "{{1/8+1/8+1/8}+{1/8+1/8+1/8}}"
2696 );
2697 }
2698
2699 #[test]
2700 fn a_fractional_beat_is_read_as_the_fraction_it_suggests() {
2701 use crate::meter::TimeSignature;
2702
2703 let compound = TimeSignature::from_ratio_string("6/8").unwrap();
2708 assert!((compound.offset_from_beat(2.33).unwrap() - 2.0).abs() < 1e-9);
2709 assert!((compound.offset_from_beat(2.66).unwrap() - 2.5).abs() < 1e-9);
2710 assert!((compound.offset_from_beat(1.66).unwrap() - 1.0).abs() < 1e-9);
2711
2712 let simple = TimeSignature::common();
2715 let third = 1.0 / 3.0;
2716 assert!((simple.offset_from_beat(2.33).unwrap() - (1.0 + third)).abs() < 1e-9);
2717 assert!((simple.offset_from_beat(2.66).unwrap() - (1.0 + 2.0 * third)).abs() < 1e-9);
2718 assert!((simple.offset_from_beat(1.66).unwrap() - (2.0 * third)).abs() < 1e-9);
2719
2720 let mut divided = TimeSignature::common();
2722 divided.divide_beats(4).unwrap();
2723 assert_eq!(divided.beat_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2724 assert_eq!(divided.accent_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2725 assert_eq!(divided.beam_sequence().to_string(), "{1/4+1/4+1/4+1/4}");
2726 assert_eq!(divided.display_sequence().to_string(), "{4/4}");
2727
2728 divided.set_accent_weight(&[0.8, 0.2], 0).unwrap();
2730 let weights = divided.accent_weights();
2731 assert_eq!(weights.len(), 4);
2732 assert!((weights[0] - 0.8).abs() < 1e-9);
2733 assert!((weights[1] - 0.2).abs() < 1e-9);
2734 }
2735
2736 #[test]
2737 fn classification_joins_division_and_count() {
2738 assert_eq!(ts("4/4").classification(), "Simple Quadruple");
2739 assert_eq!(ts("6/8").classification(), "Compound Duple");
2740 assert_eq!(ts("3/8").classification(), "Other Single");
2741 assert_eq!(ts("5/4").classification(), "Simple Quintuple");
2742 assert_eq!(ts("13/8").classification(), "Simple 13-uple");
2743 assert_eq!(ts("21/16").classification(), "Compound Septuple");
2744 }
2745
2746 #[test]
2747 fn beat_offsets_partition_the_bar() {
2748 assert_eq!(ts("4/4").beat_offsets(), [0.0, 1.0, 2.0, 3.0]);
2749 assert_eq!(ts("6/8").beat_offsets(), [0.0, 1.5]);
2750 assert_eq!(ts("5/8").beat_offsets(), [0.0, 0.5, 1.0, 1.5, 2.0]);
2751 }
2752
2753 #[test]
2754 fn beat_at_offset_is_one_based_and_bounded() {
2755 assert_eq!(ts("4/4").beat_at_offset(1.5).unwrap(), 2);
2756 assert_eq!(ts("6/8").beat_at_offset(1.5).unwrap(), 2);
2757 assert_eq!(ts("5/8").beat_at_offset(1.5).unwrap(), 4);
2758 assert_eq!(ts("4/4").beat_at_offset(0.0).unwrap(), 1);
2759 assert!(ts("4/4").beat_at_offset(4.0).is_err());
2760 assert!(ts("4/4").beat_at_offset(-0.5).is_err());
2761 assert!(ts("4/4").beat_at_offset(FloatType::NAN).is_err());
2762 }
2763
2764 #[test]
2765 fn irrational_denominators_are_accepted_as_music21_accepts_them() {
2766 let four_three = ts("4/3");
2767 assert!((four_three.bar_quarter_length() - 16.0 / 3.0).abs() < 1e-12);
2768 assert_eq!(four_three.beat_count(), 4);
2769 }
2770
2771 #[test]
2772 fn malformed_ratios_error_instead_of_panicking() {
2773 for ratio in [
2774 "", "4", "4/", "/4", "4/4/4", "x/4", "4/x", "0/4", "4/0", "-1/4",
2775 ] {
2776 assert!(
2777 TimeSignature::from_ratio_string(ratio).is_err(),
2778 "{ratio:?} should not parse"
2779 );
2780 }
2781 }
2782
2783 #[test]
2784 fn display_is_the_ratio_string() {
2785 assert_eq!(ts("7/8").to_string(), "7/8");
2786 }
2787
2788 #[test]
2789 fn a_meter_says_how_it_was_written() {
2790 use crate::meter::TimeSignature;
2791
2792 let written = TimeSignature::from_ratio_string("2/4+3/8").unwrap();
2794 assert_eq!(written.ratio_string(), "2/4+3/8");
2795 assert_eq!(written.to_string(), "2/4+3/8");
2796 assert_eq!((written.numerator(), written.denominator()), (7, 8));
2798
2799 let two_three = TimeSignature::from_ratio_string("2/8+3/8").unwrap();
2802 let three_two = TimeSignature::from_ratio_string("3/8+2/8").unwrap();
2803 assert_eq!(two_three.ratio_string(), "2/8+3/8");
2804 assert_eq!(three_two.ratio_string(), "3/8+2/8");
2805 assert_ne!(two_three, three_two);
2806 assert!(two_three.ratio_equal(&three_two));
2809
2810 let again = TimeSignature::from_ratio_string(&written.ratio_string()).unwrap();
2812 assert_eq!(again.ratio_string(), written.ratio_string());
2813
2814 let slow = TimeSignature::from_ratio_string("slow 6/8").unwrap();
2817 let fast = TimeSignature::from_ratio_string("6/8").unwrap();
2818 assert_eq!(slow.ratio_string(), "6/8");
2819 assert_eq!(fast.ratio_string(), "6/8");
2820 assert_ne!(slow, fast);
2821
2822 assert_eq!(TimeSignature::common().ratio_string(), "4/4");
2824 }
2825}