weirdnet-media 0.2.0

Weirdnet media processing for clients and nodes: WAV probing and PCM in pure Rust, 16 kHz resampling, silence-aware chunking, long-audio transcription plans, long-text speech plans, SRT/VTT, video frame planning, and a hardened ffmpeg runner with a test fake.
Documentation
//! Silence-aware cut points: where to split a long clip so each piece fits a window, cutting at
//! the quietest moment near the end of each window rather than in the middle of a word.

use crate::pcm::Pcm;

/// How cuts are searched for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct CutConfig {
    /// RMS frame length (default 30 ms).
    pub frame_ms: u64,
    /// The share of each window, at its end, searched for the quietest frame, in percent (default
    /// 20, the last fifth).
    pub search_percent: u8,
}

impl Default for CutConfig {
    fn default() -> Self {
        CutConfig { frame_ms: 30, search_percent: 20 }
    }
}

impl CutConfig {
    /// Sets the frame length.
    pub fn with_frame_ms(mut self, ms: u64) -> Self {
        self.frame_ms = ms.max(1);
        self
    }

    /// Sets the searched share of each window.
    pub fn with_search_percent(mut self, percent: u8) -> Self {
        self.search_percent = percent.clamp(1, 100);
        self
    }
}

/// RMS (0..=1, channels mixed) of each `frame_ms` frame; the last partial frame counts.
pub fn frame_rms(pcm: &Pcm, frame_ms: u64) -> Vec<f64> {
    let per = ((u64::from(pcm.sample_rate) * frame_ms.max(1)) / 1000).max(1) as usize;
    let n = pcm.frames();
    (0..n.div_ceil(per)).map(|i| pcm.rms(i * per, ((i + 1) * per).min(n))).collect()
}

/// The cut points (milliseconds, increasing, never 0 or the end) that split `pcm` into pieces no
/// longer than `max_ms`, each cut at the quietest 30 ms frame in the last fifth of its window.
/// Empty when the clip already fits. No overlap between pieces.
pub fn silence_cuts(pcm: &Pcm, max_ms: u64) -> Vec<u64> {
    silence_cuts_with(pcm, max_ms, CutConfig::default())
}

/// [`silence_cuts`] with a [`CutConfig`].
pub fn silence_cuts_with(pcm: &Pcm, max_ms: u64, config: CutConfig) -> Vec<u64> {
    let frame_ms = config.frame_ms.max(1);
    cuts_from_rms(&frame_rms(pcm, frame_ms), frame_ms, pcm.duration_ms(), max_ms, config.search_percent)
}

/// The cut search over precomputed frame energies (`rms[i]` covers `[i * frame_ms, (i + 1) *
/// frame_ms)`), for callers that measure energy elsewhere.
pub fn cuts_from_rms(rms: &[f64], frame_ms: u64, duration_ms: u64, max_ms: u64, search_percent: u8) -> Vec<u64> {
    let frame_ms = frame_ms.max(1);
    let max_ms = max_ms.max(frame_ms * 2);
    let mut cuts = Vec::new();
    let mut pos = 0u64;
    while duration_ms.saturating_sub(pos) > max_ms {
        let end = pos + max_ms;
        let search = (max_ms * u64::from(search_percent.clamp(1, 100)) / 100).max(frame_ms);
        let lo = end.saturating_sub(search).max(pos + frame_ms);
        // Frames that lie wholly inside [lo, end).
        let first = lo.div_ceil(frame_ms) as usize;
        let last = (end / frame_ms) as usize; // exclusive
        let mut best: Option<(usize, f64)> = None;
        for (i, &e) in rms.iter().enumerate().take(last).skip(first) {
            // `<=`: among equally quiet frames the latest wins, keeping pieces long.
            if best.is_none_or(|(_, b)| e <= b) {
                best = Some((i, e));
            }
        }
        let cut = match best {
            Some((i, _)) => i as u64 * frame_ms + frame_ms / 2,
            None => end,
        };
        let cut = cut.clamp(pos + 1, end);
        cuts.push(cut);
        pos = cut;
    }
    cuts
}