use alpha2_model::{LoopMode, TimeMap};
use alpha2_time::{FrameRate, MediaTime, TICKS_PER_SECOND, TimeRange};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(crate) struct Mirror {
ticks: i128,
per: i128,
}
impl Mirror {
pub(crate) const TICK: Self = Self { ticks: 1, per: 1 };
pub(crate) fn frame(rate: FrameRate) -> Self {
Self {
ticks: i128::from(TICKS_PER_SECOND) * i128::from(rate.denominator()),
per: i128::from(rate.numerator()),
}
}
fn start_of(self, frame: i128) -> Option<i128> {
Some(frame.checked_mul(self.ticks)?.div_euclid(self.per))
}
fn frame_of(self, tick: i128) -> Option<i128> {
Some(
tick.checked_add(1)?
.checked_mul(self.per)?
.checked_sub(1)?
.div_euclid(self.ticks),
)
}
fn offset(self, start: i128, length: i128, elapsed: i128, scale: i128) -> Option<i128> {
let first = self.frame_of(start.checked_sub(1)?)?.checked_add(1)?;
let last = self.frame_of(start.checked_add(length)?.checked_sub(1)?)?;
if first > last {
return Some(0);
}
let tick = start.checked_add(elapsed)?;
let frame = self.frame_of(tick)?;
let (frame, into) = if frame < first {
(first, 0)
} else {
(frame, tick.checked_sub(self.start_of(frame)?)?)
};
let mirrored = self
.start_of(first.checked_add(last)?.checked_sub(frame)?)?
.checked_sub(into)?
.checked_sub(start)?;
if mirrored <= 0 {
return Some(0);
}
Some(mirrored.checked_mul(scale)?.div_euclid(length))
}
}
pub(crate) fn map_source_time(
timeline: TimeRange,
source: TimeRange,
time_map: &TimeMap,
mirror: Mirror,
time: MediaTime,
) -> Option<MediaTime> {
let timeline_duration = i128::from(timeline.duration()?.ticks());
let source_duration = i128::from(source.duration()?.ticks());
if timeline_duration == 0 || source_duration == 0 {
return None;
}
let elapsed = i128::from(time.ticks()) - i128::from(timeline.start().ticks());
let offset = match time_map {
TimeMap::Forward => elapsed
.checked_mul(source_duration)?
.div_euclid(timeline_duration),
TimeMap::Reverse => mirror.offset(
i128::from(timeline.start().ticks()),
timeline_duration,
elapsed,
source_duration,
)?,
TimeMap::Freeze { source_time } => return Some(*source_time),
TimeMap::Curve { .. } => {
let shown = crate::TimeCurve::of(time_map)?.shown(time.ticks())?;
let (first, last) = (source.start().ticks(), source.end().ticks() - 1);
return Some(MediaTime(shown.clamp(first, last)));
}
TimeMap::Loop { mode } => {
let within = elapsed.rem_euclid(source_duration);
let pass = elapsed.div_euclid(source_duration);
match mode {
LoopMode::PingPong if pass.rem_euclid(2) == 1 => mirror.offset(
i128::from(timeline.start().ticks())
.checked_add(pass.checked_mul(source_duration)?)?,
source_duration,
within,
source_duration,
)?,
LoopMode::Repeat | LoopMode::PingPong => within,
}
}
};
let mapped = i128::from(source.start().ticks()).checked_add(offset)?;
i64::try_from(mapped).ok().map(MediaTime::from_ticks)
}
#[must_use]
pub fn picture_source_time(
timeline: TimeRange,
source: TimeRange,
time_map: &TimeMap,
frame_rate: FrameRate,
time: MediaTime,
) -> Option<MediaTime> {
map_source_time(timeline, source, time_map, Mirror::frame(frame_rate), time)
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum Direction {
Rising,
Falling,
Still,
}
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct Stretch {
pub from: i64,
pub to: i64,
pub direction: Direction,
pub low: i64,
pub high: i64,
}
#[derive(Clone, Debug)]
pub struct ClipTimes<'a> {
timeline: TimeRange,
source: TimeRange,
time_map: &'a TimeMap,
frame_rate: FrameRate,
stretches: Vec<Stretch>,
shown: (i64, i64),
}
pub(crate) const MAX_STRETCHES: usize = 1 << 22;
impl<'a> ClipTimes<'a> {
#[must_use]
pub fn new(
timeline: TimeRange,
source: TimeRange,
time_map: &'a TimeMap,
frame_rate: FrameRate,
) -> Option<Self> {
let mut times = Self {
timeline,
source,
time_map,
frame_rate,
stretches: Vec::new(),
shown: (i64::MAX, i64::MIN),
};
times.stretches = times.work_out()?;
times.shown = times
.stretches
.iter()
.fold(times.shown, |(low, high), stretch| {
(low.min(stretch.low), high.max(stretch.high))
});
Some(times)
}
#[must_use]
pub fn stretches(&self) -> &[Stretch] {
&self.stretches
}
fn shown(&self, tick: i64) -> i64 {
picture_source_time(
self.timeline,
self.source,
self.time_map,
self.frame_rate,
MediaTime(tick),
)
.map_or(i64::MIN, MediaTime::ticks)
}
fn stretch(&self, from: i64, to: i64, direction: Option<Direction>) -> Stretch {
let (first, last) = (self.shown(from), self.shown(to - 1));
Stretch {
from,
to,
direction: direction.unwrap_or(match last.cmp(&first) {
std::cmp::Ordering::Greater => Direction::Rising,
std::cmp::Ordering::Less => Direction::Falling,
std::cmp::Ordering::Equal => Direction::Still,
}),
low: first.min(last),
high: first.max(last),
}
}
fn work_out(&self) -> Option<Vec<Stretch>> {
let (start, end) = (self.timeline.start().ticks(), self.timeline.end().ticks());
let source_length = self.source.duration()?.ticks();
if start >= end || source_length <= 0 {
return Some(Vec::new());
}
match self.time_map {
TimeMap::Forward => Some(vec![self.stretch(start, end, Some(Direction::Rising))]),
TimeMap::Reverse => Some(vec![self.stretch(start, end, Some(Direction::Falling))]),
TimeMap::Freeze { .. } => Some(vec![self.stretch(start, end, Some(Direction::Still))]),
TimeMap::Loop { mode } => {
let passes = (i128::from(end) - i128::from(start) - 1) / i128::from(source_length);
let last_end = i128::from(start) + (passes + 1) * i128::from(source_length);
i64::try_from(last_end).ok()?;
let passes = usize::try_from(passes + 1)
.ok()
.filter(|passes| *passes <= MAX_STRETCHES)?;
let mut stretches = Vec::with_capacity(passes);
let mut from = start;
for pass in 0..passes {
let to = from.saturating_add(source_length).min(end);
let direction = if *mode == LoopMode::PingPong && pass % 2 == 1 {
Direction::Falling
} else {
Direction::Rising
};
stretches.push(self.stretch(from, to, Some(direction)));
from = to;
}
Some(stretches)
}
TimeMap::Curve { .. } => {
let cuts = crate::TimeCurve::of(self.time_map)?.cuts(start, end, MAX_STRETCHES)?;
let mut stretches: Vec<Stretch> = Vec::with_capacity(cuts.len());
let ends = cuts.iter().skip(1).copied().chain([end]);
for (from, to) in cuts.iter().copied().zip(ends) {
let leg = self.stretch(from, to, None);
match stretches.last_mut() {
Some(previous) if continues(previous, &leg) => {
if previous.direction == Direction::Still {
previous.direction = leg.direction;
}
previous.to = leg.to;
previous.low = previous.low.min(leg.low);
previous.high = previous.high.max(leg.high);
}
_ => stretches.push(leg),
}
}
Some(stretches)
}
}
}
pub(crate) fn line_breaks(&self) -> Vec<i64> {
let mut breaks = Vec::new();
for stretch in &self.stretches {
let (from, to) = (stretch.from, stretch.to);
breaks.extend([from, to - 1]);
if stretch.direction == Direction::Falling {
let (top, bottom) = (stretch.high, stretch.low);
breaks.push(first_reached(from, to, |tick| self.shown(tick) < top) - 1);
breaks.push(first_reached(from, to, |tick| self.shown(tick) <= bottom));
}
}
breaks.sort_unstable();
breaks.dedup();
breaks
}
#[must_use]
pub fn timeline_ranges(
&self,
range_start: MediaTime,
range_end: MediaTime,
) -> Option<Vec<TimeRange>> {
if range_start >= range_end {
return Some(Vec::new());
}
let (low, high) = (range_start.ticks(), range_end.ticks());
if covers_source(self.time_map, self.source, range_start, range_end) {
return Some(if self.stretches.is_empty() {
Vec::new()
} else {
vec![self.timeline]
});
}
let mut ranges: Vec<TimeRange> = Vec::new();
if self.shown.1 < low || self.shown.0 >= high {
return Some(ranges);
}
for stretch in &self.stretches {
if stretch.high < low || stretch.low >= high {
continue;
}
let (from, to) = (stretch.from, stretch.to);
let (first, last) = match stretch.direction {
Direction::Rising => (
first_reached(from, to, |tick| self.shown(tick) >= low),
first_reached(from, to, |tick| self.shown(tick) >= high),
),
Direction::Falling => (
first_reached(from, to, |tick| self.shown(tick) < high),
first_reached(from, to, |tick| self.shown(tick) < low),
),
Direction::Still => (from, to),
};
if first < last {
let range = TimeRange::new(MediaTime(first), MediaTime(last)).ok()?;
match ranges.last_mut() {
Some(previous) if previous.end() == range.start() => {
*previous = TimeRange::new(previous.start(), range.end()).ok()?;
}
_ => ranges.push(range),
}
}
}
Some(ranges)
}
#[must_use]
pub fn timeline_times(&self, instant: MediaTime) -> Vec<MediaTime> {
let at = instant.ticks();
let mut times = Vec::new();
if self.shown.1 < at || self.shown.0 > at {
return times;
}
for stretch in &self.stretches {
if stretch.high < at || stretch.low > at {
continue;
}
let (from, to) = (stretch.from, stretch.to);
let found = match stretch.direction {
Direction::Rising => first_reached(from, to, |tick| self.shown(tick) >= at),
Direction::Falling => first_reached(from, to, |tick| self.shown(tick) <= at),
Direction::Still => to,
};
if found < to {
times.push(MediaTime(found));
}
}
times
}
}
fn continues(previous: &Stretch, leg: &Stretch) -> bool {
use Direction::{Falling, Rising, Still};
match (previous.direction, leg.direction) {
(Rising, Rising) => previous.high <= leg.low,
(Falling, Falling) => previous.low >= leg.high,
(Still | Rising, Still) | (Still, Rising) => previous.high == leg.low,
(Falling, Still) | (Still, Falling) => previous.low == leg.high,
(Rising, Falling) | (Falling, Rising) => false,
}
}
pub(crate) fn picture_line_breaks(
timeline: TimeRange,
source: TimeRange,
time_map: &TimeMap,
frame_rate: FrameRate,
) -> Option<Vec<i64>> {
Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.line_breaks())
}
pub(crate) fn first_reached(from: i64, to: i64, reached: impl Fn(i64) -> bool) -> i64 {
let (mut low, mut high) = (from, to);
while low < high {
let middle = low + (high - low) / 2;
if reached(middle) {
high = middle;
} else {
low = middle + 1;
}
}
low
}
#[must_use]
pub fn source_range_to_timeline(
timeline: TimeRange,
source: TimeRange,
time_map: &TimeMap,
frame_rate: FrameRate,
range_start: MediaTime,
range_end: MediaTime,
) -> Option<Vec<TimeRange>> {
if range_start >= range_end {
return Some(Vec::new());
}
if covers_source(time_map, source, range_start, range_end) {
return Some(if timeline.is_empty() || source.is_empty() {
Vec::new()
} else {
vec![timeline]
});
}
ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_ranges(range_start, range_end)
}
fn covers_source(time_map: &TimeMap, source: TimeRange, start: MediaTime, end: MediaTime) -> bool {
!matches!(time_map, TimeMap::Freeze { .. }) && start <= source.start() && end >= source.end()
}
#[must_use]
pub fn source_instant_to_timeline(
timeline: TimeRange,
source: TimeRange,
time_map: &TimeMap,
frame_rate: FrameRate,
instant: MediaTime,
) -> Option<Vec<MediaTime>> {
Some(ClipTimes::new(timeline, source, time_map, frame_rate)?.timeline_times(instant))
}