weirdnet-audio-record 0.2.0

Recording for Weirdnet audio: stems, device outputs and a mix from streams, latency records, take manifests with per-source offsets, gap handling, alignment and re-alignment on export.
Documentation
//! 32-bit float WAV files.
use std::io::{self, Read, Write};
use std::path::Path;

fn bad(what: &str) -> io::Error {
    io::Error::new(io::ErrorKind::InvalidData, what.to_string())
}

/// Write interleaved samples as a 32-bit float WAV.
pub fn write_f32<W: Write>(mut w: W, sample_rate: u32, channels: u16, samples: &[f32]) -> io::Result<()> {
    let data_len = (samples.len() * 4) as u32;
    let frames = (samples.len() / channels.max(1) as usize) as u32;
    w.write_all(b"RIFF")?;
    w.write_all(&(4 + (8 + 18) + (8 + 4) + (8 + data_len)).to_le_bytes())?;
    w.write_all(b"WAVEfmt ")?;
    w.write_all(&18u32.to_le_bytes())?;
    w.write_all(&3u16.to_le_bytes())?; // IEEE float
    w.write_all(&channels.to_le_bytes())?;
    w.write_all(&sample_rate.to_le_bytes())?;
    w.write_all(&(sample_rate * u32::from(channels) * 4).to_le_bytes())?;
    w.write_all(&(channels * 4).to_le_bytes())?;
    w.write_all(&32u16.to_le_bytes())?;
    w.write_all(&0u16.to_le_bytes())?;
    w.write_all(b"fact")?;
    w.write_all(&4u32.to_le_bytes())?;
    w.write_all(&frames.to_le_bytes())?;
    w.write_all(b"data")?;
    w.write_all(&data_len.to_le_bytes())?;
    let mut buf = Vec::with_capacity(samples.len() * 4);
    for s in samples {
        buf.extend_from_slice(&s.to_le_bytes());
    }
    w.write_all(&buf)
}

/// Read a WAV (32-bit float or 16-bit PCM): sample rate, channels and interleaved samples.
pub fn read_f32<R: Read>(mut r: R) -> io::Result<(u32, u16, Vec<f32>)> {
    let mut b = Vec::new();
    r.read_to_end(&mut b)?;
    if b.len() < 12 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" {
        return Err(bad("not a WAV file"));
    }
    let mut pos = 12;
    let mut fmt: Option<(u16, u16, u32, u16)> = None;
    while pos + 8 <= b.len() {
        let id = &b[pos..pos + 4];
        let len = u32::from_le_bytes(b[pos + 4..pos + 8].try_into().expect("4 bytes")) as usize;
        let body = b.get(pos + 8..pos + 8 + len).ok_or_else(|| bad("truncated chunk"))?;
        if id == b"fmt " {
            if len < 16 {
                return Err(bad("short fmt chunk"));
            }
            let tag = u16::from_le_bytes([body[0], body[1]]);
            let ch = u16::from_le_bytes([body[2], body[3]]);
            let rate = u32::from_le_bytes(body[4..8].try_into().expect("4 bytes"));
            let bits = u16::from_le_bytes([body[14], body[15]]);
            fmt = Some((tag, ch, rate, bits));
        } else if id == b"data" {
            let (tag, ch, rate, bits) = fmt.ok_or_else(|| bad("data before fmt"))?;
            let samples = match (tag, bits) {
                (3, 32) => body.as_chunks::<4>().0.iter().map(|c| f32::from_le_bytes(*c)).collect(),
                (1, 16) => body.as_chunks::<2>().0.iter().map(|c| f32::from(i16::from_le_bytes(*c)) / 32768.0).collect(),
                _ => return Err(bad("only 32-bit float and 16-bit PCM are read")),
            };
            return Ok((rate, ch, samples));
        }
        pos += 8 + len + (len & 1);
    }
    Err(bad("no data chunk"))
}

/// [`write_f32`] to a file.
pub fn save(path: &Path, sample_rate: u32, channels: u16, samples: &[f32]) -> io::Result<()> {
    let f = std::fs::File::create(path)?;
    let mut w = io::BufWriter::new(f);
    write_f32(&mut w, sample_rate, channels, samples)?;
    w.flush()
}

/// [`read_f32`] from a file.
pub fn load(path: &Path) -> io::Result<(u32, u16, Vec<f32>)> {
    read_f32(std::fs::File::open(path)?)
}