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),
}
impl Placement {
pub(crate) fn validate(self) -> Result<(), ConfigError> {
if let Self::Ratio(r) = self {
if !(0.0..=1.0).contains(&r) {
return Err(ConfigError::InvalidRatio);
}
}
Ok(())
}
}
#[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,
}
}
}
impl Weights {
pub(crate) fn validate(&self) -> Result<(), ConfigError> {
let w = self;
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);
}
Ok(())
}
}
#[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> {
placement.validate()?;
self.placement = placement;
Ok(self)
}
pub fn weights(mut self, weights: Weights) -> Result<Self, ConfigError> {
weights.validate()?;
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 previous_end: u64,
pub next_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
}