weirdnet-audio-record 0.3.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
//! Mixing and offset estimation.

/// Sum equal-shaped interleaved buffers with a linear gain each. The result is as long as the
/// longest input.
pub fn mix(sources: &[(&[f32], f32)]) -> Vec<f32> {
    let len = sources.iter().map(|(s, _)| s.len()).max().unwrap_or(0);
    let mut out = vec![0.0f32; len];
    for (s, g) in sources {
        for (o, x) in out.iter_mut().zip(s.iter()) {
            *o += x * g;
        }
    }
    out
}

/// The lag, in frames from `-max_lag` to `max_lag`, at which mono `signal` best matches mono
/// `reference` (a positive lag: the signal is late). Uses plain cross-correlation, so give it a
/// test signal with a clear shape (a click or noise burst), not a steady tone.
pub fn estimate_offset(reference: &[f32], signal: &[f32], max_lag: usize) -> i64 {
    let mut best = (f64::MIN, 0i64);
    let max_lag = max_lag as i64;
    for lag in -max_lag..=max_lag {
        let mut sum = 0.0f64;
        for (i, r) in reference.iter().enumerate() {
            let j = i as i64 + lag;
            if j >= 0
                && let Some(s) = signal.get(j as usize)
            {
                sum += f64::from(*r) * f64::from(*s);
            }
        }
        if sum > best.0 {
            best = (sum, lag);
        }
    }
    best.1
}