silence_split/plan.rs
1//! Cut planning: where to split the audio.
2
3use alloc::vec::Vec;
4use core::num::NonZeroUsize;
5use core::time::Duration;
6
7use crate::analyze::Analysis;
8use crate::candidates::{Candidate, Context, Grid};
9use crate::dp;
10use crate::errors::ConfigError;
11use crate::segment::SegmentConfig;
12
13/// Where to cut inside a silence that is longer than its padding.
14#[derive(Clone, Copy, Debug, PartialEq)]
15#[non_exhaustive]
16pub enum Placement {
17 /// At the lowest smoothed level.
18 Quietest,
19 /// In the middle.
20 Center,
21 /// At this fraction of the way through, from `0.0` (start) to `1.0` (end).
22 Ratio(f32),
23}
24
25impl Placement {
26 pub(crate) fn validate(self) -> Result<(), ConfigError> {
27 if let Self::Ratio(r) = self {
28 if !(0.0..=1.0).contains(&r) {
29 return Err(ConfigError::InvalidRatio);
30 }
31 }
32 Ok(())
33 }
34}
35
36/// What happens to the silence at a cut.
37#[derive(Clone, Copy, Debug, PartialEq, Eq)]
38#[non_exhaustive]
39pub enum Gap {
40 /// Nothing is dropped; the pieces joined in order are the original audio.
41 Keep,
42 /// The middle of a silence chosen for a cut is dropped, keeping the padding on both sides.
43 /// Leading and trailing silence beyond the padding is dropped too.
44 Drop,
45}
46
47/// Cost weights of the planner.
48///
49/// A cut at `x` costs `cut + level · norm(x) + pause · (1 − min(1, q(x) / pause_ref))`, where
50/// `norm` is the level smoothed over 150 ms and scaled between the noise floor and the reference
51/// (at least 20 dB apart), and `q` is the
52/// length of the quiet stretch around `x`. A piece of length `ℓ` costs
53/// `target · ((ℓ − target_len) / target_len)² + short · (min − ℓ) / min` when `ℓ < min`.
54/// [`crate::adjust()`] adds `|x − p| / window` for the distance from the requested point.
55///
56/// The defaults are starting values that have not been tuned on a corpus.
57#[derive(Clone, Debug, PartialEq)]
58#[non_exhaustive]
59pub struct Weights {
60 /// Fixed cost of every cut. Keeps free cuts in digital silence from multiplying.
61 pub cut: f64,
62 /// Weight of the level at the cut.
63 pub level: f64,
64 /// Weight of cutting outside a long pause.
65 pub pause: f64,
66 /// Pause length that earns the full pause credit.
67 pub pause_ref: Duration,
68 /// Weight of the squared relative distance from the target length. Zero cuts only to stay
69 /// within the maximum.
70 pub target: f64,
71 /// Weight of pieces shorter than the minimum.
72 pub short: f64,
73}
74
75impl Default for Weights {
76 fn default() -> Self {
77 Self {
78 cut: 0.1,
79 level: 1.0,
80 pause: 1.0,
81 pause_ref: Duration::from_millis(500),
82 target: 1.0,
83 short: 4.0,
84 }
85 }
86}
87
88impl Weights {
89 pub(crate) fn validate(&self) -> Result<(), ConfigError> {
90 let w = self;
91 let valid = [w.level, w.pause, w.target, w.short]
92 .iter()
93 .all(|v| v.is_finite() && *v >= 0.0)
94 && w.cut.is_finite()
95 && w.cut > 0.0
96 && !w.pause_ref.is_zero();
97 if !valid {
98 return Err(ConfigError::InvalidWeights);
99 }
100 Ok(())
101 }
102}
103
104/// Piece length limits and cut preferences for [`plan`].
105#[derive(Clone, Debug, PartialEq)]
106#[non_exhaustive]
107pub struct PlanConfig {
108 pub(crate) min: Duration,
109 pub(crate) target: Duration,
110 pub(crate) max: Duration,
111 pub(crate) count: Option<NonZeroUsize>,
112 pub(crate) gap: Gap,
113 pub(crate) placement: Placement,
114 pub(crate) weights: Weights,
115}
116
117impl PlanConfig {
118 /// Pieces never longer than `max`, preferably `target` long and not shorter than `min`.
119 ///
120 /// `max` is a hard limit that includes padding. `min` is soft: a shorter piece is penalized
121 /// ([`Weights::short`]) and flagged [`Piece::too_short`]. Silence is kept ([`Gap::Keep`]) and cuts inside
122 /// silence go to the quietest point ([`Placement::Quietest`]).
123 ///
124 /// # Errors
125 ///
126 /// [`ConfigError::InvalidLengths`] unless `min <= target <= max` and `target` is non-zero.
127 pub fn new(min: Duration, target: Duration, max: Duration) -> Result<Self, ConfigError> {
128 if target.is_zero() || min > target || target > max {
129 return Err(ConfigError::InvalidLengths);
130 }
131 Ok(Self {
132 min,
133 target,
134 max,
135 count: None,
136 gap: Gap::Keep,
137 placement: Placement::Quietest,
138 weights: Weights::default(),
139 })
140 }
141
142 /// Asks for exactly `count` pieces, each targeting an equal share of the audio. `min` and
143 /// `max` still apply; fewer pieces are returned only when there are not enough cut positions.
144 #[must_use]
145 pub fn count(mut self, count: NonZeroUsize) -> Self {
146 self.count = Some(count);
147 self
148 }
149
150 /// Sets what happens to the silence at a cut.
151 #[must_use]
152 pub fn gap(mut self, gap: Gap) -> Self {
153 self.gap = gap;
154 self
155 }
156
157 /// Sets where a cut goes inside a long silence when silence is kept.
158 ///
159 /// # Errors
160 ///
161 /// [`ConfigError::InvalidRatio`] if a [`Placement::Ratio`] is outside `0.0..=1.0`.
162 pub fn placement(mut self, placement: Placement) -> Result<Self, ConfigError> {
163 placement.validate()?;
164 self.placement = placement;
165 Ok(self)
166 }
167
168 /// Sets the cost weights.
169 ///
170 /// # Errors
171 ///
172 /// [`ConfigError::InvalidWeights`] if a weight is negative or not finite, the per-cut cost is
173 /// zero, or `pause_ref` is zero.
174 pub fn weights(mut self, weights: Weights) -> Result<Self, ConfigError> {
175 weights.validate()?;
176 self.weights = weights;
177 Ok(self)
178 }
179}
180
181/// A boundary between two consecutive pieces.
182///
183/// The earlier piece ends at `previous_end` and the later one starts at `next_start`. With
184/// [`Gap::Keep`] they are equal; with [`Gap::Drop`] the samples `[previous_end, next_start)` are
185/// dropped.
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
187#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
188#[non_exhaustive]
189pub struct Cut {
190 /// End of the earlier piece.
191 pub previous_end: u64,
192 /// Start of the later piece.
193 pub next_start: u64,
194 /// What the cut is in.
195 pub reason: CutReason,
196}
197
198/// What a cut falls in.
199#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
200#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
201#[non_exhaustive]
202pub enum CutReason {
203 /// A silence candidate, or a point in silence outside the planner's effective padding.
204 /// Padding may be shortened for the maximum, so this can differ from padded segments.
205 Silence,
206 /// Not silence, but within the quietest quarter of the level range.
207 Quiet,
208 /// Anywhere else: the length limits left no quiet choice.
209 Forced,
210}
211
212/// A piece of the original audio, `[start, end)` in samples.
213#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
214#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
215#[non_exhaustive]
216pub struct Piece {
217 /// First sample.
218 pub start: u64,
219 /// One past the last sample.
220 pub end: u64,
221 /// Shorter than the minimum length.
222 pub too_short: bool,
223 /// Longer than the maximum length. Only when the limits cannot be met on the analysis frame
224 /// grid, such as a maximum shorter than a frame or a count too small for the maximum.
225 pub too_long: bool,
226}
227
228/// Pieces in order and the cuts between them: `cuts[i]` separates `pieces[i]` and
229/// `pieces[i + 1]`.
230///
231/// Samples before the first piece and after the last are dropped leading and trailing silence
232/// ([`Gap::Drop`] only).
233#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
234#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
235#[non_exhaustive]
236pub struct Plan {
237 /// The pieces.
238 pub pieces: Vec<Piece>,
239 /// The cuts between pieces.
240 pub cuts: Vec<Cut>,
241}
242
243/// Chooses cuts over the whole audio that keep every piece within `max`, minimizing the total
244/// cost of all cuts and piece lengths (see [`Weights`]).
245///
246/// Candidates are the silence spans and the quietest point of every block of
247/// `min(1 s, max((max − min) / 2, max / 8))` outside them. Additional frame boundaries are inserted
248/// when needed to satisfy the maximum or the piece count, including within padding. Padding that
249/// would leave less than two blocks of the maximum is shortened to fit. Silence wins over quiet
250/// sound through the cut cost. Cuts fall on analysis frame boundaries. The result is deterministic.
251///
252/// With [`PlanConfig::count`], feasibility includes the removable silence ranges. Only when no
253/// frame-grid plan can meet both limits is the maximum relaxed to the smallest attainable longest
254/// piece; pieces exceeding the requested maximum are flagged [`Piece::too_long`].
255#[must_use]
256pub fn plan(analysis: &Analysis, segment: &SegmentConfig, config: &PlanConfig) -> Plan {
257 let max = analysis.samples_floor(config.max);
258 // Blocks follow max − min, but not below max / 8: a tight soft minimum must not shrink the
259 // grid to every frame.
260 let block_time = (config.max.saturating_sub(config.min) / 2)
261 .max(config.max / 8)
262 .min(Duration::from_secs(1));
263 let block = analysis.frames_floor(block_time).max(1);
264 let block_samples = analysis.position(block.min(analysis.frames()));
265 // A piece must hold the padding plus a block to reach the next grid candidate.
266 let padding_cap = analysis.frames_floor(config.max).saturating_sub(2 * block);
267 let ctx = Context::new(analysis, segment, &config.weights, padding_cap);
268 let Some((first, last)) = ctx.ends(config.gap) else {
269 return Plan::default();
270 };
271 let span = analysis.position(last) - analysis.position(first);
272 // The nearest grid candidates outside a silence may be a block or two from it, so a silence
273 // longer than the maximum less two blocks gets grid candidates of its own.
274 let grid = Grid {
275 block,
276 edge_limit: Some(max.saturating_sub(2 * block_samples)),
277 };
278 let mut nodes = ctx.candidates(config.gap, config.placement, &grid, first, last);
279 let target = match config.count {
280 Some(n) => span as f64 / n.get() as f64,
281 None => {
282 ctx.complete_max(&mut nodes, max);
283 analysis.samples_in(config.target)
284 }
285 };
286 let solve = |nodes: &[Candidate], reach: u64| -> Plan {
287 let lengths = dp::Lengths {
288 min: analysis.samples_in(config.min),
289 target,
290 max: reach,
291 weights: &config.weights,
292 };
293 let left: Vec<u64> = nodes.iter().map(|c| analysis.position(c.left)).collect();
294 let right: Vec<u64> = nodes.iter().map(|c| analysis.position(c.right)).collect();
295 let cost: Vec<f64> = nodes.iter().map(|c| c.cost).collect();
296 let path = match config.count {
297 Some(n) => dp::solve_count(&left, &right, &cost, &lengths, n.get()),
298 None => dp::solve(&left, &right, &cost, &lengths),
299 };
300 ctx.to_plan(nodes, &path, lengths.min, max)
301 };
302 let result = solve(&nodes, max);
303 if let Some(n) = config.count {
304 if result.pieces.len() < n.get() || result.pieces.iter().any(|p| p.too_long) {
305 let reach = ctx.complete_count(&mut nodes, max, n.get());
306 return solve(&nodes, reach);
307 }
308 }
309 result
310}