use std::f64::consts::PI;
use crate::error::{MediaError, Result};
use crate::probe::{SampleFormat, wav_header};
pub const TRANSCRIBE_RATE: u32 = 16_000;
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Pcm {
pub sample_rate: u32,
pub channels: u16,
pub samples: Vec<i16>,
}
impl Pcm {
pub fn new(sample_rate: u32, channels: u16, samples: Vec<i16>) -> Self {
Pcm { sample_rate, channels, samples }
}
pub fn silence(sample_rate: u32, channels: u16, ms: u64) -> Self {
let frames = frames_for(sample_rate, ms);
Pcm::new(sample_rate, channels, vec![0; frames * usize::from(channels)])
}
pub fn frames(&self) -> usize {
self.samples.len() / usize::from(self.channels.max(1))
}
pub fn duration_ms(&self) -> u64 {
if self.sample_rate == 0 {
return 0;
}
self.frames() as u64 * 1000 / u64::from(self.sample_rate)
}
pub fn same_format(&self, other: &Pcm) -> bool {
self.sample_rate == other.sample_rate && self.channels == other.channels
}
pub fn slice_ms(&self, start_ms: u64, end_ms: u64) -> Pcm {
let ch = usize::from(self.channels.max(1));
let a = frames_for(self.sample_rate, start_ms).min(self.frames());
let b = frames_for(self.sample_rate, end_ms).clamp(a, self.frames());
Pcm::new(self.sample_rate, self.channels, self.samples[a * ch..b * ch].to_vec())
}
pub fn to_mono(&self) -> Pcm {
let ch = usize::from(self.channels.max(1));
if ch == 1 {
return self.clone();
}
let samples = self.samples.chunks_exact(ch).map(|f| (f.iter().map(|s| i32::from(*s)).sum::<i32>() / ch as i32) as i16).collect();
Pcm::new(self.sample_rate, 1, samples)
}
pub fn resample(&self, rate: u32) -> Pcm {
if rate == self.sample_rate || self.sample_rate == 0 || rate == 0 {
return Pcm::new(if rate == 0 { self.sample_rate } else { rate }, self.channels, self.samples.clone());
}
let ch = usize::from(self.channels.max(1));
let n_in = self.frames();
let n_out = ((n_in as u128 * u128::from(rate) + u128::from(self.sample_rate) / 2) / u128::from(self.sample_rate)) as usize;
let ratio = f64::from(rate) / f64::from(self.sample_rate);
let cutoff = ratio.min(1.0) * 0.95;
let half = (8.0 / cutoff).ceil() as i64;
const RES: f64 = 256.0;
let table: Vec<f64> = (0..=(2 * half as usize * RES as usize))
.map(|k| {
let d = k as f64 / RES - half as f64;
let x = d * cutoff;
let sinc = if x.abs() < 1e-12 { 1.0 } else { (PI * x).sin() / (PI * x) };
sinc * (0.5 + 0.5 * (PI * d / (half as f64 + 1.0)).cos())
})
.collect();
let mut out = vec![0i16; n_out * ch];
let mut acc = vec![0.0f64; ch];
for i in 0..n_out {
let center = i as f64 / ratio;
let first = (center.floor() as i64 - half + 1).max(0);
let last = (center.floor() as i64 + half).min(n_in as i64 - 1);
acc.iter_mut().for_each(|a| *a = 0.0);
let mut norm = 0.0f64;
for j in first..=last {
let idx = ((j as f64 - center + half as f64) * RES).round() as usize;
let k = table[idx.min(table.len() - 1)];
norm += k;
let base = j as usize * ch;
for (c, a) in acc.iter_mut().enumerate() {
*a += k * f64::from(self.samples[base + c]);
}
}
for (c, a) in acc.iter().enumerate() {
let v = if norm.abs() > 1e-9 { a / norm } else { 0.0 };
out[i * ch + c] = v.round().clamp(-32768.0, 32767.0) as i16;
}
}
Pcm::new(rate, self.channels, out)
}
pub fn to_transcribe(&self) -> Pcm {
self.to_mono().resample(TRANSCRIBE_RATE)
}
pub fn rms(&self, start: usize, end: usize) -> f64 {
let ch = usize::from(self.channels.max(1));
let (start, end) = (start.min(self.frames()), end.min(self.frames()));
if end <= start {
return 0.0;
}
let mut sum = 0.0f64;
for f in start..end {
let s: f64 = self.samples[f * ch..f * ch + ch].iter().map(|s| f64::from(*s)).sum::<f64>() / ch as f64;
sum += s * s;
}
(sum / (end - start) as f64).sqrt() / 32768.0
}
}
fn frames_for(rate: u32, ms: u64) -> usize {
(u128::from(rate) * u128::from(ms) / 1000) as usize
}
pub fn decode_wav(bytes: &[u8]) -> Result<Pcm> {
let info = wav_header(bytes, None)?;
let start = info.data_offset as usize;
let len = (info.data_len as usize).min(bytes.len().saturating_sub(start));
let align = usize::from(info.block_align);
let data = &bytes[start..start + len - len % align];
let width = usize::from(info.bits_per_sample / 8);
let samples: Vec<i16> = match (info.format, info.bits_per_sample) {
(SampleFormat::Int, 8) => data.iter().map(|b| (i16::from(*b) - 128) << 8).collect(),
(SampleFormat::Int, 16) => data.as_chunks::<2>().0.iter().map(|c| i16::from_le_bytes(*c)).collect(),
(SampleFormat::Int, 24) => data.as_chunks::<3>().0.iter().map(|c| i16::from_le_bytes([c[1], c[2]])).collect(),
(SampleFormat::Int, 32) => data.as_chunks::<4>().0.iter().map(|c| i16::from_le_bytes([c[2], c[3]])).collect(),
(SampleFormat::Float, 32) => data.as_chunks::<4>().0.iter().map(|c| float_to_i16(f64::from(f32::from_le_bytes(*c)))).collect(),
(SampleFormat::Float, 64) => data.as_chunks::<8>().0.iter().map(|c| float_to_i16(f64::from_le_bytes(*c))).collect(),
(f, b) => return Err(MediaError::invalid(format!("WAV {f:?} {b}-bit is not supported"))),
};
debug_assert_eq!(samples.len(), data.len() / width);
Ok(Pcm::new(info.sample_rate, info.channels, samples))
}
fn float_to_i16(x: f64) -> i16 {
if !x.is_finite() {
return 0;
}
(x.clamp(-1.0, 1.0) * 32767.0).round() as i16
}
pub fn encode_wav(pcm: &Pcm) -> Vec<u8> {
let data_len = (pcm.samples.len() * 2) as u32;
let ch = pcm.channels.max(1);
let mut out = Vec::with_capacity(44 + data_len as usize);
out.extend_from_slice(b"RIFF");
out.extend_from_slice(&(36 + data_len).to_le_bytes());
out.extend_from_slice(b"WAVEfmt ");
out.extend_from_slice(&16u32.to_le_bytes());
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&ch.to_le_bytes());
out.extend_from_slice(&pcm.sample_rate.to_le_bytes());
out.extend_from_slice(&(pcm.sample_rate * u32::from(ch) * 2).to_le_bytes());
out.extend_from_slice(&(ch * 2).to_le_bytes());
out.extend_from_slice(&16u16.to_le_bytes());
out.extend_from_slice(b"data");
out.extend_from_slice(&data_len.to_le_bytes());
for s in &pcm.samples {
out.extend_from_slice(&s.to_le_bytes());
}
out
}
pub fn normalize_wav(bytes: &[u8]) -> Result<Vec<u8>> {
Ok(encode_wav(&decode_wav(bytes)?.to_transcribe()))
}
pub fn wav_bytes(rate: u32, channels: u16, ms: u64) -> u64 {
44 + frames_for(rate, ms) as u64 * u64::from(channels) * 2
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Join {
Cut,
Crossfade { ms: u64 },
Pause { ms: u64 },
}
pub fn crossfade(a: &Pcm, b: &Pcm, ms: u64) -> Result<Pcm> {
if !a.same_format(b) {
return Err(MediaError::invalid("crossfaded pieces differ in sample rate or channels"));
}
let ch = usize::from(a.channels.max(1));
let n = frames_for(a.sample_rate, ms).min(a.frames()).min(b.frames());
let keep = a.frames() - n;
let mut out = Vec::with_capacity(a.samples.len() + b.samples.len() - n * ch);
out.extend_from_slice(&a.samples[..keep * ch]);
for i in 0..n {
let t = (i as f64 + 0.5) / n as f64;
let (ga, gb) = ((t * PI / 2.0).cos(), (t * PI / 2.0).sin());
for c in 0..ch {
let v = f64::from(a.samples[(keep + i) * ch + c]) * ga + f64::from(b.samples[i * ch + c]) * gb;
out.push(v.round().clamp(-32768.0, 32767.0) as i16);
}
}
out.extend_from_slice(&b.samples[n * ch..]);
Ok(Pcm::new(a.sample_rate, a.channels, out))
}
pub fn concat(pieces: &[Pcm], joins: &[Join]) -> Result<Pcm> {
let Some(first) = pieces.first() else {
return Ok(Pcm::default());
};
if let Some(bad) = pieces.iter().position(|p| !p.same_format(first)) {
return Err(MediaError::invalid(format!(
"piece {} is {} Hz x{}, the first is {} Hz x{}",
bad + 1,
pieces[bad].sample_rate,
pieces[bad].channels,
first.sample_rate,
first.channels
)));
}
let mut out = first.clone();
for (i, p) in pieces.iter().enumerate().skip(1) {
match joins.get(i - 1).copied().unwrap_or(Join::Cut) {
Join::Cut => out.samples.extend_from_slice(&p.samples),
Join::Crossfade { ms } => out = crossfade(&out, p, ms)?,
Join::Pause { ms } => {
out.samples.extend(Pcm::silence(first.sample_rate, first.channels, ms).samples);
out.samples.extend_from_slice(&p.samples);
}
}
}
Ok(out)
}
pub fn tone(sample_rate: u32, hz: f64, ms: u64, amplitude: f64) -> Pcm {
let frames = frames_for(sample_rate, ms);
let samples = (0..frames)
.map(|i| (amplitude.clamp(0.0, 1.0) * 32767.0 * (2.0 * PI * hz * i as f64 / f64::from(sample_rate)).sin()).round() as i16)
.collect();
Pcm::new(sample_rate, 1, samples)
}