use alloc::vec::Vec;
use core::num::NonZeroUsize;
use core::time::Duration;
use crate::analyze::Analysis;
use crate::candidates::{Candidate, Context, Grid};
use crate::dp;
use crate::errors::ConfigError;
use crate::segment::SegmentConfig;
#[derive(Clone, Copy, Debug, PartialEq)]
#[non_exhaustive]
pub enum Placement {
Quietest,
Center,
Ratio(f32),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Gap {
Keep,
Drop,
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct Weights {
pub cut: f64,
pub level: f64,
pub pause: f64,
pub pause_ref: Duration,
pub target: f64,
pub short: f64,
}
impl Default for Weights {
fn default() -> Self {
Self {
cut: 0.1,
level: 1.0,
pause: 1.0,
pause_ref: Duration::from_millis(500),
target: 1.0,
short: 4.0,
}
}
}
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub struct PlanConfig {
pub(crate) min: Duration,
pub(crate) target: Duration,
pub(crate) max: Duration,
pub(crate) count: Option<NonZeroUsize>,
pub(crate) gap: Gap,
pub(crate) placement: Placement,
pub(crate) weights: Weights,
}
impl PlanConfig {
pub fn new(min: Duration, target: Duration, max: Duration) -> Result<Self, ConfigError> {
if target.is_zero() || min > target || target > max {
return Err(ConfigError::InvalidLengths);
}
Ok(Self {
min,
target,
max,
count: None,
gap: Gap::Keep,
placement: Placement::Quietest,
weights: Weights::default(),
})
}
#[must_use]
pub fn count(mut self, count: NonZeroUsize) -> Self {
self.count = Some(count);
self
}
#[must_use]
pub fn gap(mut self, gap: Gap) -> Self {
self.gap = gap;
self
}
pub fn placement(mut self, placement: Placement) -> Result<Self, ConfigError> {
if let Placement::Ratio(r) = placement {
if !(0.0..=1.0).contains(&r) {
return Err(ConfigError::InvalidRatio);
}
}
self.placement = placement;
Ok(self)
}
pub fn weights(mut self, weights: Weights) -> Result<Self, ConfigError> {
let w = &weights;
let valid = [w.level, w.pause, w.target, w.short]
.iter()
.all(|v| v.is_finite() && *v >= 0.0)
&& w.cut.is_finite()
&& w.cut > 0.0
&& !w.pause_ref.is_zero();
if !valid {
return Err(ConfigError::InvalidWeights);
}
self.weights = weights;
Ok(self)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Cut {
pub end: u64,
pub start: u64,
pub reason: CutReason,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub enum CutReason {
Silence,
Quiet,
Forced,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Piece {
pub start: u64,
pub end: u64,
pub too_short: bool,
pub too_long: bool,
}
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[non_exhaustive]
pub struct Plan {
pub pieces: Vec<Piece>,
pub cuts: Vec<Cut>,
}
#[must_use]
pub fn plan(analysis: &Analysis, segment: &SegmentConfig, config: &PlanConfig) -> Plan {
let max = analysis.samples_floor(config.max);
let block_time = (config.max.saturating_sub(config.min) / 2)
.max(config.max / 8)
.min(Duration::from_secs(1));
let block = analysis.frames_floor(block_time).max(1);
let block_samples = analysis.position(block.min(analysis.frames()));
let padding_cap = analysis.frames_floor(config.max).saturating_sub(2 * block);
let ctx = Context::new(analysis, segment, &config.weights, padding_cap);
let Some((first, last)) = ctx.ends(config.gap) else {
return Plan::default();
};
let span = analysis.position(last) - analysis.position(first);
let grid = Grid {
block,
edge_limit: Some(max.saturating_sub(2 * block_samples)),
};
let mut nodes = ctx.candidates(config.gap, config.placement, &grid, first, last);
let target = match config.count {
Some(n) => span as f64 / n.get() as f64,
None => {
ctx.complete_max(&mut nodes, max);
analysis.samples_in(config.target)
}
};
let solve = |nodes: &[Candidate], reach: u64| -> Plan {
let lengths = dp::Lengths {
min: analysis.samples_in(config.min),
target,
max: reach,
weights: &config.weights,
};
let left: Vec<u64> = nodes.iter().map(|c| analysis.position(c.left)).collect();
let right: Vec<u64> = nodes.iter().map(|c| analysis.position(c.right)).collect();
let cost: Vec<f64> = nodes.iter().map(|c| c.cost).collect();
let path = match config.count {
Some(n) => dp::solve_count(&left, &right, &cost, &lengths, n.get()),
None => dp::solve(&left, &right, &cost, &lengths),
};
ctx.to_plan(nodes, &path, lengths.min, max)
};
let result = solve(&nodes, max);
if let Some(n) = config.count {
if result.pieces.len() < n.get() || result.pieces.iter().any(|p| p.too_long) {
let reach = ctx.complete_count(&mut nodes, max, n.get());
return solve(&nodes, reach);
}
}
result
}
#[must_use]
pub fn adjust(
analysis: &Analysis,
segment: &SegmentConfig,
points: &[u64],
window: Duration,
) -> Plan {
let weights = Weights::default();
let ctx = Context::new(analysis, segment, &weights, usize::MAX);
let n = analysis.frames();
if n == 0 {
return Plan::default();
}
let grid = Grid {
block: analysis
.frames_floor(window.min(Duration::from_secs(1)))
.max(1),
edge_limit: Some(0),
};
let candidates = ctx.candidates(Gap::Keep, Placement::Quietest, &grid, 0, n);
let inner = &candidates[1..candidates.len() - 1];
let positions: Vec<u64> = inner.iter().map(|c| analysis.position(c.left)).collect();
let len = analysis.sample_count();
let mut points: Vec<u64> = points
.iter()
.copied()
.filter(|p| *p > 0 && *p < len)
.collect();
points.sort_unstable();
points.dedup();
let reach = analysis.samples_in(window);
let mut chosen: Vec<Candidate> = Vec::with_capacity(points.len() + 2);
chosen.push(Candidate::node(0));
for (k, &p) in points.iter().enumerate() {
let lo = k.checked_sub(1).map_or(0, |i| points[i].midpoint(p));
let hi = points.get(k + 1).map_or(len, |next| p.midpoint(*next));
let from = positions.partition_point(|x| (*x as f64) < p as f64 - reach || *x < lo);
let to = positions.partition_point(|x| *x < hi && *x as f64 <= p as f64 + reach);
let best = (from..to.max(from))
.map(|i| {
let distance = positions[i].abs_diff(p) as f64;
let pull = if reach > 0.0 { distance / reach } else { 0.0 };
(inner[i].cost + pull, &inner[i])
})
.fold(None, |best: Option<(f64, &Candidate)>, (v, c)| match best {
Some((b, _)) if b <= v => best,
_ => Some((v, c)),
});
let pick = match best {
Some((_, c)) => c.clone(),
None => ctx.forced_at(p),
};
let after_previous = chosen.last().is_some_and(|c| c.left < pick.left);
if pick.left < n && after_previous {
chosen.push(pick);
}
}
chosen.push(Candidate::node(n));
let path: Vec<usize> = (0..chosen.len()).collect();
ctx.to_plan(&chosen, &path, 0.0, u64::MAX)
}