crates/format/audio/src/resample.rs 2.4 KiB 63 lines Raw
1 //! The rate change that a model asks for.2 //!3 //! A model names a rate and a device produced another. The two rates in a job4 //! are almost always related by a small integer, so an average or a linear5 //! interpolation is enough. A ratio that is not exact is refused because it6 //! would need a filter whose length this crate does not own.7 8 use crate::AudioError;9 use crate::pcm::MAX_RATE;10 use crate::pcm::MIN_RATE;11 use crate::pcm::Pcm;12 13 /// The rate change that a model asks for: integer downsample by an average, or14 /// integer upsample by linear interpolation. Anything else is refused.15 pub fn resample(pcm: &Pcm, rate: u32) -> Result<Pcm, AudioError> {16     if !(MIN_RATE..=MAX_RATE).contains(&rate) {17         return Err(AudioError::Rate);18     }19     if rate == pcm.rate {20         return Ok(pcm.clone());21     }22 23     let channels = usize::from(pcm.channels);24     let frames = pcm.frames();25 26     if pcm.rate.is_multiple_of(rate) {27         let factor = (pcm.rate / rate) as usize;28         let out_frames = frames / factor;29         let mut samples = Vec::with_capacity(out_frames * channels);30         for frame in 0..out_frames {31             let base = frame * factor * channels;32             for channel in 0..channels {33                 let sum: i32 = (0..factor)34                     .map(|k| i32::from(pcm.samples[base + k * channels + channel]))35                     .sum();36                 samples.push((sum / factor as i32) as i16);37             }38         }39         return Pcm::new(rate, pcm.channels, samples);40     }41 42     if rate.is_multiple_of(pcm.rate) {43         let factor = (rate / pcm.rate) as usize;44         let out_frames = frames * factor;45         let mut samples = Vec::with_capacity(out_frames * channels);46         for frame in 0..out_frames {47             let source = frame / factor;48             let step = frame % factor;49             // The last source frame holds, so the final output frames keep its50             // value instead of extrapolating past the block.51             let next = (source + 1).min(frames.saturating_sub(1));52             for channel in 0..channels {53                 let left = i64::from(pcm.samples[source * channels + channel]);54                 let right = i64::from(pcm.samples[next * channels + channel]);55                 let value = left + (right - left) * step as i64 / factor as i64;56                 samples.push(value as i16);57             }58         }59         return Pcm::new(rate, pcm.channels, samples);60     }61 62     Err(AudioError::Ratio)63 }