Skip to main content

music21/
audiosearch.rs

1//! Finding the notes in a recording: music21's `audioSearch`.
2//!
3//! A recording is cut into chunks of [`AUDIO_CHUNK_LENGTH`] frames; each
4//! chunk's frequency is found by autocorrelation
5//! ([`autocorrelation_frequency`]) and snapped to the nearest pitch of a
6//! scale ([`detect_pitch_frequencies`]). The frequencies are smoothed
7//! ([`smooth_frequencies`]), turned into pitches whose octaves are evened
8//! out ([`pitch_frequencies_to_objects`]), and runs of one pitch long
9//! enough to be a note become notes and rests
10//! ([`join_consecutive_identical_pitches`]), whose lengths are quantized
11//! against the most common length ([`notes_and_durations_to_stream`]).
12//! [`monophonic_stream_from_wav`] does all of it, as music21's
13//! `transcriber.monophonicStreamFromFile` does.
14//!
15//! As music21 does, every recording is taken to be sampled at
16//! [`RECORD_SAMPLE_RATE`], whatever its file says, and its samples are read
17//! as 16-bit numbers. music21's recording from a microphone and its score
18//! follower are not here.
19
20use 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
30/// How many frames of a recording each frequency is found from: music21's
31/// `audioChunkLength`.
32pub const AUDIO_CHUNK_LENGTH: usize = 1024;
33
34/// The sample rate every recording is taken to have: music21's
35/// `recordSampleRate`.
36pub const RECORD_SAMPLE_RATE: FloatType = 44100.0;
37
38/// How many channels music21 records from a microphone:
39/// `recording.default_recordChannels`.
40pub const RECORD_CHANNELS: usize = 1;
41
42/// The frequency standing for a rest.
43pub 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
56/// How many of `data` fall in each of `bins` equal bins from its least to
57/// its greatest, and the bins' edges: music21's `histogram`. A value on an
58/// edge counts in the bin below it.
59///
60/// ```
61/// use music21::audiosearch::histogram;
62///
63/// let (counts, edges) = histogram(&[1.0, 2.0, 2.0, 3.0, 5.0], 4)?;
64/// assert_eq!(counts, [3, 1, 0, 1]);
65/// assert_eq!(edges, [1.0, 2.0, 3.0, 4.0, 5.0]);
66/// # Ok::<(), music21::Error>(())
67/// ```
68///
69/// # Errors
70///
71/// No data, or no bins.
72pub 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
96/// Where between three points about a peak the top of the parabola
97/// through them lies: music21's `interpolation`. A peak at either end
98/// is taken as it is.
99pub 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
111/// The frequency a signal sounds, found by autocorrelation: music21's
112/// `autocorrelationFunction`. The signal's correlation with itself at
113/// each lag is taken; past the first lag where it starts to rise, its
114/// highest point, placed between samples by [`interpolation`], is the
115/// period. A signal whose correlation never rises is a rest, frequency
116/// ten.
117///
118/// music21 correlates with scipy's FFT convolution, which rounds; the
119/// crate sums the products exactly, so the two can differ in the last
120/// bits.
121///
122/// ```
123/// use music21::audiosearch::autocorrelation_frequency;
124///
125/// let rate = 44100.0;
126/// let signal: Vec<f64> = (0..1024)
127///     .map(|i| (2.0 * std::f64::consts::PI * 441.0 * i as f64 / rate).sin() * 10000.0)
128///     .collect();
129/// let frequency = autocorrelation_frequency(&signal, rate)?;
130/// // music21 finds 442.2033...: the interpolated peak sits a little early.
131/// assert!((frequency - 442.2033).abs() < 1e-3);
132/// # Ok::<(), music21::Error>(())
133/// ```
134///
135/// # Errors
136///
137/// An empty signal.
138pub 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    // numpy's argmax: the first of equal highs.
162    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
177/// The thresholds between a scale's pitches, as fractions of an octave
178/// above the octave's C, and the pitches: music21's `prepareThresholds`.
179/// The scale is the chromatic scale on C4 where none is given.
180///
181/// # Errors
182///
183/// A scale whose pitches cannot be worked out.
184pub 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
204/// The scale pitch a frequency falls nearest, put in the octave it sounds
205/// in, and the frequency of that pitch as the scale has it: music21's
206/// `normalizeInputFrequency`, with thresholds and pitches from
207/// [`prepare_thresholds`].
208///
209/// # Errors
210///
211/// A frequency that is not a finite number above nought, or no pitches.
212pub 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
239/// Each frequency's nearest pitch of `scale` (C major on C4 where none is
240/// given), and the frequency of that pitch in the octave it sounds:
241/// music21's `detectPitchFrequencies`.
242///
243/// # Errors
244///
245/// As [`normalize_input_frequency`].
246pub 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
263/// Each frequency averaged with its neighbours, `smooth_levels` at a time,
264/// and rounded to a whole number: music21's `smoothFrequencies`. As in
265/// music21, each average takes in those already made before it, and the
266/// first and last few frequencies are the truncated average of the first
267/// and last `smooth_levels`.
268///
269/// ```
270/// use music21::audiosearch::smooth_frequencies;
271///
272/// let smoothed = smooth_frequencies(&[100.0, 100.0, 400.0, 100.0, 100.0], 3)?;
273/// // Each average takes in the ones made before it.
274/// assert_eq!(smoothed, [200, 233, 244, 200, 200]);
275/// # Ok::<(), music21::Error>(())
276/// ```
277///
278/// # Errors
279///
280/// No levels, or more levels than frequencies.
281pub fn smooth_frequencies(frequencies: &[FloatType], smooth_levels: usize) -> Result<Vec<i64>> {
282    // music21 raises a `ValueError` for both of these rather than its own
283    // class: they are arguments that were never values, not music that
284    // cannot be read.
285    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
321/// The pitches of a list of frequencies, each the nearest pitch of `scale`
322/// (C major on C4 where none is given), with each run of one name put in
323/// the run's average octave, and the frequencies so placed: music21's
324/// `pitchFrequenciesToObjects`.
325///
326/// As in music21, a run's octave goes to the pitches from the one before
327/// it to the one before its last, the very first run's to the last pitch,
328/// and the last pitch is never counted in a run.
329///
330/// # Errors
331///
332/// As [`normalize_input_frequency`].
333pub 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            // Python's index one before, the last for the first.
357            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
365/// The pitch music21 makes by setting a pitch's frequency.
366fn 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/// One note or rest a run of pitches makes: the by-position twin of
372/// [`join_consecutive_identical_pitches`].
373#[derive(Clone, Copy, Debug, PartialEq, Eq)]
374#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
375pub struct JoinedNote {
376    /// Which of the pitches it sounds, or none where it is a rest.
377    pub pitch: Option<usize>,
378    /// How many pitches it stands for.
379    pub length: usize,
380}
381
382/// What each run of one pitch makes, as the places of the pitches rather
383/// than as notes: the by-position twin of
384/// [`join_consecutive_identical_pitches`].
385///
386/// music21 hands the note it makes the very `Pitch` object of the run's
387/// last pitch, so a caller holding those objects wants to know which.
388///
389/// # Errors
390///
391/// No pitches.
392pub 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
432/// Notes and rests from runs of one pitch, and how many pitches each
433/// lasted: music21's `joinConsecutiveIdenticalPitches`. A run of six or
434/// more is a note of its last pitch; fifteen or more pitches in shorter
435/// runs before a note make a rest. The first pitch is taken as a rest's,
436/// and as in music21 the first pitch after each run is passed over.
437///
438/// # Errors
439///
440/// No pitches.
441pub 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
460/// A length, in quarters, snapped to a sixteenth, eighth, quarter, dotted
461/// quarter, half or whole: music21's `quantizeDuration`.
462pub 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
474/// How many pitches a quarter note lasts, from how many each note lasted:
475/// the middle of the last of the fullest bins of an eight-bin
476/// [`histogram`] of the lengths and nought, taken as
477/// `most_repeated_quarter_length` (a quarter where nought): music21's
478/// `quarterLengthEstimation`.
479///
480/// # Errors
481///
482/// As [`histogram`].
483pub 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/// What one note of a transcription is given: the by-position twin of
505/// [`notes_and_durations_to_stream`].
506#[derive(Clone, Copy, Debug, PartialEq)]
507#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
508pub struct TranscribedNote {
509    /// Which of the notes given it is.
510    pub note: usize,
511    /// How long it is to last, in quarters.
512    pub quarter_length: FloatType,
513    /// Whether it goes into the part: a rest before the first note is
514    /// left out where the caller asked for that.
515    pub kept: bool,
516}
517
518/// How long each note of a transcription is to last and which of them go
519/// into the part, and the quarter length estimated: the by-position twin
520/// of [`notes_and_durations_to_stream`].
521///
522/// music21 writes the length onto *every* note it is given, the rests it
523/// then leaves out included, which is why each note is answered for
524/// whether it is kept or not.
525///
526/// # Errors
527///
528/// Fewer notes than lengths, or no lengths.
529pub 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
562/// A score of one part holding `notes`, each as long as its length in
563/// [`quantize_duration`]d quarters of the estimated quarter length, and that
564/// estimate: music21's `notesAndDurationsToStream`. The estimate is
565/// [`quarter_length_estimation`] against the most common note length of
566/// `score_notes` where given, or against a quarter. With
567/// `remove_rests_at_beginning`, rests before the first note are left out.
568/// The score is titled `Automatic Music21 Transcription`.
569///
570/// # Errors
571///
572/// Fewer notes than lengths, or no lengths.
573pub 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
605/// Which of the parts a score follower is weighing to take as where the
606/// player is, and the count of doubtful guesses so far: music21's
607/// `decisionProcess`. Each part is its index into `beginning_data`, where
608/// it begins, and how well it matched; parts are in order of how well they
609/// matched. Of the parts matching within nine tenths of the best and
610/// beginning after `last_note_position`, the one beginning nearest
611/// `note_prediction` is taken; the countdown grows when the guess is
612/// doubtful and is otherwise reset.
613///
614/// # Errors
615///
616/// No parts, a part beginning where `beginning_data` has nothing, or every
617/// part beginning before the prediction with none taken instead.
618pub 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
671/// The 16-bit samples of a WAV file and how many frames it holds, read as
672/// Python's `wave` module reads an uncompressed one.
673fn 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
723/// The frequency of each whole chunk of [`AUDIO_CHUNK_LENGTH`] frames of a
724/// WAV file, found by [`autocorrelation_frequency`]: music21's
725/// `getFrequenciesFromAudioFile`. Each chunk's bytes are read as 16-bit
726/// samples, every channel's in turn, and taken to be sampled at
727/// [`RECORD_SAMPLE_RATE`]; frames after the last whole chunk are left out.
728///
729/// # Errors
730///
731/// A file that is not an uncompressed WAV file.
732pub 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
748/// The notes of a recording of one line, as a part: music21's
749/// `transcriber.monophonicStreamFromFile`, which runs
750/// [`frequencies_from_wav`], [`detect_pitch_frequencies`],
751/// [`smooth_frequencies`] by seven, [`pitch_frequencies_to_objects`],
752/// [`join_consecutive_identical_pitches`] and
753/// [`notes_and_durations_to_stream`], rests at the beginning left out.
754/// Pitches are taken from `scale`, C major on C4 where none is given.
755///
756/// # Errors
757///
758/// A file that is not an uncompressed WAV file, or one too short to
759/// smooth or to hold a note.
760pub 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(&notes, &lengths, None, true)?;
770    score
771        .parts()
772        .first()
773        .map(|part| (*part).clone())
774        .ok_or_else(|| audio_error("no part"))
775}