1use 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#[derive(Clone, Debug, PartialEq)]
14#[non_exhaustive]
15pub struct AdjustConfig {
16 window: Duration,
17 weights: Weights,
18 placement: Placement,
19}
20
21impl AdjustConfig {
22 #[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 pub fn weights(mut self, weights: Weights) -> Result<Self, ConfigError> {
40 weights.validate()?;
41 self.weights = weights;
42 Ok(self)
43 }
44
45 pub fn placement(mut self, placement: Placement) -> Result<Self, ConfigError> {
51 placement.validate()?;
52 self.placement = placement;
53 Ok(self)
54 }
55}
56
57#[derive(Clone, Debug, Default, PartialEq, Eq)]
59#[non_exhaustive]
60pub struct AdjustResult {
61 pub plan: Plan,
63 pub point_cuts: Vec<Option<Cut>>,
67}
68
69#[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}