crates/format/audio/src/pcm.rs 2.9 KiB 89 lines Raw
1 //! The sample block that every audio path shares.2 //!3 //! Samples are i16 and interleaved because that is the body of a wav and the4 //! shape that a model's front end reads. The rate and the channel count travel5 //! with the samples so no caller has to carry them beside the block.6 7 use crate::AudioError;8 9 /// The lowest rate that a microphone or a model front end uses.10 pub(crate) const MIN_RATE: u32 = 8_000;11 12 /// The highest rate that a device in this tree accepts.13 pub(crate) const MAX_RATE: u32 = 192_000;14 15 /// One channel is the mean of the block.16 const CHANNELS_MONO: u8 = 1;17 18 /// Two channels are interleaved left then right.19 const CHANNELS_STEREO: u8 = 2;20 21 /// Milliseconds in a second, for the duration that a caller reads.22 const MILLIS_PER_SECOND: u64 = 1_000;23 24 /// A block of samples: i16, interleaved, at one rate.25 #[derive(Clone, PartialEq, Eq, Debug)]26 pub struct Pcm {27     /// The rate in samples per second.28     pub rate: u32,29     /// 1 for mono, 2 for stereo.30     pub channels: u8,31     /// Interleaved samples. The length is a multiple of `channels`.32     pub samples: Vec<i16>,33 }34 35 impl Pcm {36     /// A block that a wav or a model can carry. The rate and the channel count37     /// are bounded because a device and a front end only accept those shapes.38     pub fn new(rate: u32, channels: u8, samples: Vec<i16>) -> Result<Pcm, AudioError> {39         if samples.is_empty() {40             return Err(AudioError::Empty);41         }42         if !(MIN_RATE..=MAX_RATE).contains(&rate) {43             return Err(AudioError::Rate);44         }45         if channels != CHANNELS_MONO && channels != CHANNELS_STEREO {46             return Err(AudioError::Channels);47         }48         if !samples.len().is_multiple_of(usize::from(channels)) {49             return Err(AudioError::Shape);50         }51         Ok(Pcm {52             rate,53             channels,54             samples,55         })56     }57 58     /// One frame is one sample on every channel.59     pub fn frames(&self) -> usize {60         self.samples.len() / usize::from(self.channels)61     }62 63     /// The duration in whole milliseconds. A caller uses it to bound a job.64     pub fn duration_ms(&self) -> u64 {65         let frames = self.frames() as u64;66         frames.saturating_mul(MILLIS_PER_SECOND) / u64::from(self.rate)67     }68 69     /// A mono mixdown: the mean of the channels, rounded toward zero.70     pub fn mono(&self) -> Pcm {71         let samples = if self.channels == CHANNELS_STEREO {72             self.samples73                 .chunks_exact(usize::from(CHANNELS_STEREO))74                 .map(|pair| {75                     // Integer division in Rust truncates toward zero.76                     let sum = i32::from(pair[0]) + i32::from(pair[1]);77                     (sum / i32::from(CHANNELS_STEREO)) as i1678                 })79                 .collect()80         } else {81             self.samples.clone()82         };83         Pcm {84             rate: self.rate,85             channels: CHANNELS_MONO,86             samples,87         }88     }89 }