Skip to main content

silence_split/
adjust.rs

1//! Adjust caller-supplied cut points while preserving their correspondence to the result.
2
3use alloc::vec::Vec;
4use core::time::Duration;
5
6use crate::analyze::Analysis;
7use crate::candidates::{Candidate, Context, Grid};
8use crate::errors::ConfigError;
9use crate::plan::{Cut, Gap, Placement, Plan, Weights};
10use crate::segment::SegmentConfig;
11
12/// Search window and cut preferences for [`adjust`].
13#[derive(Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub struct AdjustConfig {
16    window: Duration,
17    weights: Weights,
18    placement: Placement,
19}
20
21impl AdjustConfig {
22    /// Searches within `window` of each point, using default weights and the quietest placement.
23    /// A zero window snaps each point to the nearest frame boundary when no candidate is exact.
24    #[must_use]
25    pub fn new(window: Duration) -> Self {
26        Self {
27            window,
28            weights: Weights::default(),
29            placement: Placement::Quietest,
30        }
31    }
32
33    /// Sets the cut cost weights. Length weights are unused; distance from the point always has
34    /// weight one. The fixed per-cut cost is identical for all choices of one point.
35    ///
36    /// # Errors
37    ///
38    /// [`ConfigError::InvalidWeights`] for invalid weights, as with [`crate::PlanConfig::weights`].
39    pub fn weights(mut self, weights: Weights) -> Result<Self, ConfigError> {
40        weights.validate()?;
41        self.weights = weights;
42        Ok(self)
43    }
44
45    /// Sets the representative cut position inside each silence.
46    ///
47    /// # Errors
48    ///
49    /// [`ConfigError::InvalidRatio`] if a ratio is outside `0.0..=1.0`.
50    pub fn placement(mut self, placement: Placement) -> Result<Self, ConfigError> {
51        placement.validate()?;
52        self.placement = placement;
53        Ok(self)
54    }
55}
56
57/// The adjusted plan and the result for every original input point, in the caller's order.
58#[derive(Clone, Debug, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct AdjustResult {
61    /// Pieces in timeline order, keeping all audio. Piece length flags are always false.
62    pub plan: Plan,
63    /// One entry per input point. `None` means the point was skipped: it was at or beyond an
64    /// endpoint, duplicated an earlier input point, or adjusted onto an endpoint or an already
65    /// chosen boundary. For duplicate input positions, the first input owns the result.
66    pub point_cuts: Vec<Option<Cut>>,
67}
68
69/// Moves cut points to nearby candidates, keeping all audio and returning each point's result.
70///
71/// Points are processed in sorted, deduplicated order. Each point picks a candidate within the
72/// configured window and before the midpoints to its neighbours, minimizing cut cost plus
73/// `|cut - point| / window`. If no candidate exists, it snaps to the nearest frame boundary as a
74/// [`crate::CutReason::Forced`] cut. The distance weight is always one. Min/max lengths do not
75/// apply. [`AdjustResult::point_cuts`] preserves the original order, including skipped points.
76#[must_use]
77pub fn adjust(
78    analysis: &Analysis,
79    segment: &SegmentConfig,
80    points: &[u64],
81    config: &AdjustConfig,
82) -> AdjustResult {
83    let mut result = AdjustResult {
84        plan: Plan::default(),
85        point_cuts: alloc::vec![None; points.len()],
86    };
87    let ctx = Context::new(analysis, segment, &config.weights, usize::MAX);
88    let n = analysis.frames();
89    if n == 0 {
90        return result;
91    }
92    let window = config.window;
93    let grid = Grid {
94        block: analysis
95            .frames_floor(window.min(Duration::from_secs(1)))
96            .max(1),
97        edge_limit: Some(0),
98    };
99    let candidates = ctx.candidates(Gap::Keep, config.placement, &grid, 0, n);
100    let inner = &candidates[1..candidates.len() - 1];
101    let positions: Vec<u64> = inner.iter().map(|c| analysis.position(c.left)).collect();
102    let len = analysis.sample_count();
103    let mut points: Vec<(usize, u64)> = points
104        .iter()
105        .copied()
106        .enumerate()
107        .filter(|(_, p)| *p > 0 && *p < len)
108        .collect();
109    points.sort_unstable_by_key(|&(index, point)| (point, index));
110    points.dedup_by_key(|entry| entry.1);
111
112    let reach = analysis.samples_in(window);
113    let mut chosen: Vec<Candidate> = Vec::with_capacity(points.len() + 2);
114    let mut accepted = Vec::with_capacity(points.len());
115    chosen.push(Candidate::node(0));
116    for (k, &(index, p)) in points.iter().enumerate() {
117        let lo = k.checked_sub(1).map_or(0, |i| points[i].1.midpoint(p));
118        let hi = points.get(k + 1).map_or(len, |next| p.midpoint(next.1));
119        let from = positions.partition_point(|x| (*x as f64) < p as f64 - reach || *x < lo);
120        let to = positions.partition_point(|x| *x < hi && *x as f64 <= p as f64 + reach);
121        let best = (from..to.max(from))
122            .map(|i| {
123                let distance = positions[i].abs_diff(p) as f64;
124                let pull = if reach > 0.0 { distance / reach } else { 0.0 };
125                (inner[i].cost + pull, &inner[i])
126            })
127            .fold(None, |best: Option<(f64, &Candidate)>, (v, c)| match best {
128                Some((b, _)) if b <= v => best,
129                _ => Some((v, c)),
130            });
131        let pick = match best {
132            Some((_, c)) => c.clone(),
133            None => ctx.forced_at(p),
134        };
135        let after_previous = chosen.last().is_some_and(|c| c.left < pick.left);
136        if pick.left < n && after_previous {
137            chosen.push(pick);
138            accepted.push(index);
139        }
140    }
141    chosen.push(Candidate::node(n));
142    let path: Vec<usize> = (0..chosen.len()).collect();
143    result.plan = ctx.to_plan(&chosen, &path, 0.0, u64::MAX);
144    for (index, cut) in accepted.into_iter().zip(&result.plan.cuts) {
145        result.point_cuts[index] = Some(*cut);
146    }
147    result
148}