1use crate::defaults::{FloatType, IntegerType};
21use crate::duration::Duration;
22use crate::error::{Error, Result};
23use crate::metadata::Metadata;
24use crate::note::Note;
25use crate::pitch::Pitch;
26use crate::rest::Rest;
27use crate::scale::{Scale, ScaleType};
28use crate::stream::{Stream, StreamElement, StreamKind};
29
30pub const AUDIO_CHUNK_LENGTH: usize = 1024;
33
34pub const RECORD_SAMPLE_RATE: FloatType = 44100.0;
37
38pub const RECORD_CHANNELS: usize = 1;
41
42pub const REST_FREQUENCY: FloatType = 10.0;
44
45fn audio_error(message: impl Into<String>) -> Error {
46 Error::Analysis(message.into())
47}
48
49fn default_scale(scale: Option<&Scale>) -> Result<Scale> {
50 match scale {
51 Some(scale) => Ok(scale.clone()),
52 None => Ok(Scale::new(ScaleType::Major, Pitch::from_name("C4")?)),
53 }
54}
55
56pub fn histogram(data: &[FloatType], bins: usize) -> Result<(Vec<usize>, Vec<FloatType>)> {
73 let most = data
74 .iter()
75 .copied()
76 .reduce(FloatType::max)
77 .ok_or_else(|| audio_error("no values to count"))?;
78 let least = data.iter().copied().fold(most, FloatType::min);
79 let width = (most - least) / bins as FloatType;
80 let mut counts = vec![0; bins];
81 for value in data {
82 let mut count = 1;
83 while *value > least + count as FloatType * width {
84 count += 1;
85 }
86 *counts
87 .get_mut(count - 1)
88 .ok_or_else(|| audio_error(format!("{value} falls past the last bin")))? += 1;
89 }
90 let edges = (0..=bins)
91 .map(|index| least + index as FloatType * width)
92 .collect();
93 Ok((counts, edges))
94}
95
96pub fn interpolation(correlation: &[FloatType], peak: usize) -> FloatType {
100 if peak == 0 || peak + 1 == correlation.len() {
101 return peak as FloatType;
102 }
103 let (before, at, after) = (
104 correlation[peak - 1],
105 correlation[peak],
106 correlation[peak + 1],
107 );
108 (before - after) / (before - 2.0 * at + after) * 0.5 + peak as FloatType
109}
110
111pub fn autocorrelation_frequency(
139 signal: &[FloatType],
140 sample_rate: FloatType,
141) -> Result<FloatType> {
142 if signal.is_empty() {
143 return Err(audio_error("v cannot be empty"));
144 }
145 let length = signal.len();
146 let correlation: Vec<FloatType> = (0..length)
147 .map(|lag| {
148 signal[..length - lag]
149 .iter()
150 .zip(&signal[lag..])
151 .map(|(a, b)| a * b)
152 .sum()
153 })
154 .collect();
155 let Some(beginning) = correlation
156 .windows(2)
157 .position(|pair| pair[1] - pair[0] > 0.0)
158 else {
159 return Ok(REST_FREQUENCY);
160 };
161 let peak = correlation[beginning..]
163 .iter()
164 .enumerate()
165 .fold((0, FloatType::NEG_INFINITY), |best, (index, value)| {
166 if *value > best.1 {
167 (index, *value)
168 } else {
169 best
170 }
171 })
172 .0
173 + beginning;
174 Ok(sample_rate / interpolation(&correlation, peak))
175}
176
177pub fn prepare_thresholds(scale: Option<&Scale>) -> Result<(Vec<FloatType>, Vec<Pitch>)> {
185 let scale = match scale {
186 Some(scale) => scale.clone(),
187 None => Scale::new(ScaleType::Chromatic, Pitch::from_name("C4")?),
188 };
189 let pitches = scale.pitches()?;
190 let mut remainders: Vec<FloatType> = pitches
191 .iter()
192 .map(|pitch| pitch.frequency_hz().log2().fract())
193 .collect();
194 if let Some(last) = remainders.last_mut() {
195 *last += 1.0;
196 }
197 let thresholds = remainders
198 .windows(2)
199 .map(|pair| (pair[0] + pair[1]) / 2.0)
200 .collect();
201 Ok((thresholds, pitches))
202}
203
204pub fn normalize_input_frequency(
213 frequency: FloatType,
214 thresholds: &[FloatType],
215 pitches: &[Pitch],
216) -> Result<(FloatType, Pitch)> {
217 let log = frequency.log2();
218 if !log.is_finite() {
219 return Err(audio_error(format!(
220 "cannot place a frequency of {frequency}"
221 )));
222 }
223 let (remainder, octave) = (log.fract(), log.trunc() as IntegerType);
224 let (index, shift) = match thresholds
225 .iter()
226 .position(|threshold| remainder < *threshold)
227 {
228 Some(index) => (index, 4),
229 None => (pitches.len().wrapping_sub(1), 3),
230 };
231 let scale_pitch = pitches
232 .get(index)
233 .ok_or_else(|| audio_error("the scale has no pitches"))?;
234 let mut placed = scale_pitch.clone();
235 placed.set_octave(Some(octave - shift));
236 Ok((scale_pitch.frequency_hz(), placed))
237}
238
239pub fn detect_pitch_frequencies(
247 frequencies: &[FloatType],
248 scale: Option<&Scale>,
249) -> Result<Vec<FloatType>> {
250 let (thresholds, pitches) = prepare_thresholds(Some(&default_scale(scale)?))?;
251 frequencies
252 .iter()
253 .map(|frequency| {
254 Ok(
255 normalize_input_frequency(*frequency, &thresholds, &pitches)?
256 .1
257 .frequency_hz(),
258 )
259 })
260 .collect()
261}
262
263pub fn smooth_frequencies(frequencies: &[FloatType], smooth_levels: usize) -> Result<Vec<i64>> {
282 if smooth_levels < 1 {
286 return Err(Error::Value("smoothLevels must be >= 1".to_string()));
287 }
288 let count = frequencies.len();
289 if smooth_levels > count {
290 return Err(Error::Value(format!(
291 "There cannot be more smoothLevels ({smooth_levels}) than inputPitches ({count})"
292 )));
293 }
294 let mut smoothed = frequencies.to_vec();
295 let levels = smooth_levels as FloatType;
296 let beginning = smoothed[..smooth_levels].iter().sum::<FloatType>() / levels;
297 let ends = (0..smooth_levels)
298 .map(|i| smoothed[count - 1 - i])
299 .sum::<FloatType>()
300 / levels;
301 let half_down = smooth_levels / 2;
302 let half_up = smooth_levels.div_ceil(2);
303 for i in 0..count {
304 smoothed[i] = if i < half_down {
305 beginning.trunc()
306 } else if (i as i64) > count as i64 - half_up as i64 - 1 {
307 ends.trunc()
308 } else {
309 (0..smooth_levels)
310 .map(|j| smoothed[i + j - half_down])
311 .sum::<FloatType>()
312 / levels
313 };
314 }
315 Ok(smoothed
316 .into_iter()
317 .map(|value| value.round_ties_even() as i64)
318 .collect())
319}
320
321pub fn pitch_frequencies_to_objects(
334 frequencies: &[FloatType],
335 scale: Option<&Scale>,
336) -> Result<(Vec<Pitch>, Vec<FloatType>)> {
337 let (thresholds, pitches) = prepare_thresholds(Some(&default_scale(scale)?))?;
338 let mut placed: Vec<Pitch> = frequencies
339 .iter()
340 .map(|frequency| Ok(normalize_input_frequency(*frequency, &thresholds, &pitches)?.1))
341 .collect::<Result<_>>()?;
342 let count = placed.len();
343 let mut plotted = Vec::new();
344 let mut i = 0;
345 while i + 1 < count {
346 let name = placed[i].name();
347 let hold = i;
348 let mut total: IntegerType = 0;
349 while i + 1 < count && placed[i].name() == name {
350 total += placed[i].octave().unwrap_or(4);
351 i += 1;
352 }
353 let octave =
354 (total as FloatType / (i - hold) as FloatType).round_ties_even() as IntegerType;
355 for j in 0..i - hold {
356 let index = (hold + j + count - 1) % count;
358 placed[index].set_octave(Some(octave));
359 plotted.push(placed[index].frequency_hz());
360 }
361 }
362 Ok((placed, plotted))
363}
364
365fn pitch_at_frequency(hertz: FloatType) -> Result<Pitch> {
367 let space = 12.0 * ((hertz / 440.0).ln() / (2.0 as FloatType).ln()) + 69.0;
368 Pitch::from_pitch_space((space * 1e6).round_ties_even() / 1e6)
369}
370
371#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
375pub struct JoinedNote {
376 pub pitch: Option<usize>,
378 pub length: usize,
380}
381
382pub fn joined_pitches(pitches: &[Pitch]) -> Result<Vec<JoinedNote>> {
393 let mut read = pitches.to_vec();
394 let first = read
395 .first_mut()
396 .ok_or_else(|| audio_error("no pitches to join"))?;
397 *first = pitch_at_frequency(REST_FREQUENCY)?;
398 let mut joined = Vec::new();
399 let (mut good, mut bad) = (0, 0);
400 let mut j = 0;
401 while j < read.len() {
402 let frequency = read[j].frequency_hz();
403 let mut valid = false;
404 while j < read.len() && read[j].frequency_hz() == frequency {
405 good += 1;
406 if good >= 6 {
407 valid = true;
408 if bad >= 15 {
409 joined.push(JoinedNote {
410 pitch: None,
411 length: bad,
412 });
413 }
414 bad = 0;
415 }
416 j += 1;
417 }
418 if valid {
419 joined.push(JoinedNote {
420 pitch: Some(j - 1),
421 length: good,
422 });
423 } else {
424 bad += good;
425 }
426 good = 0;
427 j += 1;
428 }
429 Ok(joined)
430}
431
432pub fn join_consecutive_identical_pitches(
442 mut pitches: Vec<Pitch>,
443) -> Result<(Vec<StreamElement>, Vec<usize>)> {
444 let first = pitches
445 .first_mut()
446 .ok_or_else(|| audio_error("no pitches to join"))?;
447 *first = pitch_at_frequency(REST_FREQUENCY)?;
448 let mut notes: Vec<StreamElement> = Vec::new();
449 let mut lengths = Vec::new();
450 for one in joined_pitches(&pitches)? {
451 lengths.push(one.length);
452 notes.push(match one.pitch {
453 Some(place) => Note::from_pitch(pitches[place].clone()).into(),
454 None => Rest::new(Duration::quarter()).into(),
455 });
456 }
457 Ok((notes, lengths))
458}
459
460pub fn quantize_duration(length: FloatType) -> FloatType {
463 let length = length * 100.0;
464 let typical = [25.0, 50.0, 100.0, 150.0, 200.0, 400.0];
465 let mut chosen = typical[0];
466 for (index, pair) in typical.windows(2).enumerate() {
467 if length > (pair[0] + pair[1]) / 2.0 {
468 chosen = typical[index + 1];
469 }
470 }
471 chosen / 100.0
472}
473
474pub fn quarter_length_estimation(
484 lengths: &[usize],
485 most_repeated_quarter_length: FloatType,
486) -> Result<FloatType> {
487 let mut data: Vec<FloatType> = lengths.iter().map(|length| *length as FloatType).collect();
488 data.push(0.0);
489 let (counts, edges) = histogram(&data, 8)?;
490 let fullest = counts.iter().copied().max().unwrap_or(0);
491 let index = counts
492 .iter()
493 .rposition(|count| *count == fullest)
494 .unwrap_or(0);
495 let estimate = (edges[index] + edges[index + 1]) / 2.0;
496 let most_repeated = if most_repeated_quarter_length == 0.0 {
497 1.0
498 } else {
499 most_repeated_quarter_length
500 };
501 Ok(estimate * (2.0 as FloatType).powf(0.0 - most_repeated.log2()))
502}
503
504#[derive(Clone, Copy, Debug, PartialEq)]
507#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
508pub struct TranscribedNote {
509 pub note: usize,
511 pub quarter_length: FloatType,
513 pub kept: bool,
516}
517
518pub fn transcribed_notes(
530 notes: &[StreamElement],
531 lengths: &[usize],
532 score_notes: Option<&Stream>,
533 remove_rests_at_beginning: bool,
534) -> Result<(Vec<TranscribedNote>, FloatType)> {
535 let most_common = match score_notes {
536 Some(score) => crate::features::vector_by_id(score, "QL2")?
537 .and_then(|vector| vector.first().map(|value| value.as_float()))
538 .unwrap_or(1.0),
539 None => 1.0,
540 };
541 let estimate = quarter_length_estimation(lengths, most_common)?;
542 let mut out = Vec::with_capacity(lengths.len());
543 let mut skipping = remove_rests_at_beginning;
544 for (index, length) in lengths.iter().enumerate() {
545 let element = notes
546 .get(index)
547 .ok_or_else(|| audio_error("more lengths than notes"))?;
548 let quarter_length = quantize_duration(*length as FloatType / estimate);
549 let kept = !(skipping && matches!(element, StreamElement::Rest(_)));
550 if kept {
551 skipping = false;
552 }
553 out.push(TranscribedNote {
554 note: index,
555 quarter_length,
556 kept,
557 });
558 }
559 Ok((out, estimate))
560}
561
562pub fn notes_and_durations_to_stream(
574 notes: &[StreamElement],
575 lengths: &[usize],
576 score_notes: Option<&Stream>,
577 remove_rests_at_beginning: bool,
578) -> Result<(Stream, FloatType)> {
579 let (given, estimate) =
580 transcribed_notes(notes, lengths, score_notes, remove_rests_at_beginning)?;
581 let mut part = Stream::with_kind(StreamKind::Part);
582 for one in &given {
583 let mut element = notes
584 .get(one.note)
585 .cloned()
586 .ok_or_else(|| audio_error("more lengths than notes"))?;
587 let duration = Duration::new(one.quarter_length)?;
588 match &mut element {
589 StreamElement::Note(note) => note.set_duration(duration),
590 StreamElement::Rest(rest) => rest.set_duration(duration),
591 _ => {}
592 }
593 if one.kept {
594 part.push(element);
595 }
596 }
597 let mut score = Stream::with_kind(StreamKind::Score);
598 let mut metadata = Metadata::default();
599 metadata.add_text("title", "Automatic Music21 Transcription");
600 score.set_metadata(Some(metadata));
601 score.insert(0.0, part);
602 Ok((score, estimate))
603}
604
605pub fn decision_process(
619 parts: &[(usize, FloatType)],
620 note_prediction: FloatType,
621 beginning_data: &[FloatType],
622 last_note_position: FloatType,
623 countdown: usize,
624 page: Option<(FloatType, FloatType)>,
625) -> Result<(usize, usize)> {
626 let begins = |part: usize| -> Result<FloatType> {
627 let id = parts
628 .get(part)
629 .ok_or_else(|| audio_error(format!("no part {part}")))?
630 .0;
631 beginning_data
632 .get(id)
633 .copied()
634 .ok_or_else(|| audio_error(format!("no beginning recorded for part {part}")))
635 };
636 let mut position = 0;
637 let mut i = 0;
638 while i < parts.len() && begins(i)? < note_prediction {
639 i += 1;
640 position = i;
641 }
642 if parts.len() == 1 {
643 position = 0;
644 }
645 let first = beginning_data
646 .first()
647 .copied()
648 .ok_or_else(|| audio_error("no beginnings recorded"))?;
649 let mut distance = (first - note_prediction).abs();
650 let best = parts.first().ok_or_else(|| audio_error("no parts"))?.1;
651 for (index, (_, probability)) in parts.iter().enumerate() {
652 let start = begins(index)?;
653 if *probability >= 0.9 * best
654 && start > last_note_position
655 && (start - note_prediction).abs() < distance
656 {
657 distance = (start - note_prediction).abs();
658 position = index;
659 }
660 }
661 let start = begins(position)?;
662 let probability = parts[position].1;
663 let doubtful = probability < 0.6
664 || parts.len() == 1
665 || (distance > 20.0 && countdown == 0)
666 || (distance > 30.0 && countdown == 1)
667 || page.is_some_and(|(first, last)| (start < first || start > last) && countdown < 2);
668 Ok((position, if doubtful { countdown + 1 } else { 0 }))
669}
670
671fn wav_samples(bytes: &[u8]) -> Result<(Vec<u8>, usize, usize)> {
674 let word = |at: usize| -> Result<u32> {
675 bytes
676 .get(at..at + 4)
677 .map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
678 .ok_or_else(|| audio_error("file does not start with RIFF id"))
679 };
680 if bytes.get(..4) != Some(b"RIFF") || bytes.get(8..12) != Some(b"WAVE") {
681 return Err(audio_error("file does not start with RIFF id"));
682 }
683 let mut at = 12;
684 let mut frame_size = None;
685 while at + 8 <= bytes.len() {
686 let id = &bytes[at..at + 4];
687 let size = word(at + 4)? as usize;
688 let body = at + 8;
689 let end = (body + size).min(bytes.len());
690 match id {
691 b"fmt " => {
692 let field = |offset: usize| -> Result<u16> {
693 bytes
694 .get(body + offset..body + offset + 2)
695 .map(|b| u16::from_le_bytes([b[0], b[1]]))
696 .ok_or_else(|| audio_error("fmt chunk too short"))
697 };
698 let format = field(0)?;
699 if format != 1 && format != 0xFFFE {
700 return Err(audio_error(format!("unknown format: {format}")));
701 }
702 let channels = usize::from(field(2)?);
703 let width = usize::from(field(14)?).div_ceil(8);
704 if channels == 0 || width == 0 {
705 return Err(audio_error("bad # of channels or sample width"));
706 }
707 frame_size = Some(channels * width);
708 }
709 b"data" => {
710 let frame_size =
711 frame_size.ok_or_else(|| audio_error("data chunk before fmt chunk"))?;
712 let data = bytes[body..end].to_vec();
713 let frames = size / frame_size;
714 return Ok((data, frames, frame_size));
715 }
716 _ => {}
717 }
718 at = body + size + (size & 1);
719 }
720 Err(audio_error("fmt chunk and/or data chunk missing"))
721}
722
723pub fn frequencies_from_wav(bytes: &[u8]) -> Result<Vec<FloatType>> {
733 let (data, frames, frame_size) = wav_samples(bytes)?;
734 let chunk_bytes = AUDIO_CHUNK_LENGTH * frame_size;
735 (0..frames / AUDIO_CHUNK_LENGTH)
736 .map(|chunk| {
737 let samples: Vec<FloatType> = data[chunk * chunk_bytes..(chunk + 1) * chunk_bytes]
738 .as_chunks::<2>()
739 .0
740 .iter()
741 .map(|pair| FloatType::from(i16::from_le_bytes(*pair)))
742 .collect();
743 autocorrelation_frequency(&samples, RECORD_SAMPLE_RATE)
744 })
745 .collect()
746}
747
748pub fn monophonic_stream_from_wav(bytes: &[u8], scale: Option<&Scale>) -> Result<Stream> {
761 let frequencies = frequencies_from_wav(bytes)?;
762 let detected = detect_pitch_frequencies(&frequencies, scale)?;
763 let smoothed: Vec<FloatType> = smooth_frequencies(&detected, 7)?
764 .into_iter()
765 .map(|value| value as FloatType)
766 .collect();
767 let (pitches, _) = pitch_frequencies_to_objects(&smoothed, scale)?;
768 let (notes, lengths) = join_consecutive_identical_pitches(pitches)?;
769 let (score, _) = notes_and_durations_to_stream(¬es, &lengths, None, true)?;
770 score
771 .parts()
772 .first()
773 .map(|part| (*part).clone())
774 .ok_or_else(|| audio_error("no part"))
775}