use crate::{
ClipId, Composition, CompositionId, CompositionNode, CompositionReads, NodeId, NodeOp, Project,
};
use alpha2_media::SourceId;
use std::collections::{HashMap, HashSet};
use std::fmt;
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TimeOffsetProblem {
GroupInput,
AdjustmentBackdrop {
clip: ClipId,
},
CompositionSource {
clip: ClipId,
},
}
impl fmt::Display for TimeOffsetProblem {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::GroupInput => formatter.write_str("shifts a group input"),
Self::AdjustmentBackdrop { clip } => {
write!(formatter, "shifts the scene beneath adjustment clip {clip}")
}
Self::CompositionSource { clip } => {
write!(formatter, "shifts the composition source of clip {clip}")
}
}
}
}
pub(crate) fn has_offsets(composition: &Composition) -> bool {
composition.nodes.iter().any(is_offset)
}
const fn is_offset(node: &CompositionNode) -> bool {
matches!(node.op, NodeOp::TimeOffset { .. })
}
struct Graph<'a> {
nodes: &'a [CompositionNode],
positions: HashMap<&'a NodeId, usize>,
inputs: Vec<Vec<usize>>,
order: Vec<usize>,
}
impl<'a> Graph<'a> {
fn new(composition: &'a Composition) -> Self {
let nodes = composition.nodes.as_slice();
let positions: HashMap<&NodeId, usize> = nodes
.iter()
.enumerate()
.map(|(position, node)| (&node.id, position))
.collect();
let inputs: Vec<Vec<usize>> = nodes
.iter()
.map(|node| {
node.op
.inputs()
.into_iter()
.filter_map(|input| positions.get(input.node()?).copied())
.collect()
})
.collect();
let mut order = Vec::with_capacity(nodes.len());
let mut entered = vec![false; nodes.len()];
for root in 0..nodes.len() {
if entered[root] {
continue;
}
entered[root] = true;
let mut stack = vec![(root, 0_usize)];
while let Some((current, next)) = stack.last_mut() {
let Some(&input) = inputs[*current].get(*next) else {
order.push(*current);
stack.pop();
continue;
};
*next += 1;
if !entered[input] {
entered[input] = true;
stack.push((input, 0));
}
}
}
Self {
nodes,
positions,
inputs,
order,
}
}
fn reaching(&self, found: impl Fn(&CompositionNode) -> bool) -> Vec<bool> {
let mut reaches = vec![false; self.nodes.len()];
for &position in &self.order {
reaches[position] = found(&self.nodes[position])
|| self.inputs[position].iter().any(|&input| reaches[input]);
}
reaches
}
fn shifts(&self, position: usize) -> bool {
!self.nodes[position].bypass && is_offset(&self.nodes[position])
}
fn drawn_from(&self, needed: &[Vec<usize>], from: &[usize]) -> Vec<usize> {
let mut reached = vec![false; self.nodes.len()];
let mut region = Vec::new();
let mut pending = from.to_vec();
while let Some(position) = pending.pop() {
if std::mem::replace(&mut reached[position], true) {
continue;
}
region.push(position);
if !self.shifts(position) {
pending.extend(&needed[position]);
}
}
region
}
fn scopes(&self, composition: &Composition, reads: &CompositionReads<'_>) -> Vec<Scopes> {
let needed: Vec<Vec<usize>> = self
.nodes
.iter()
.map(|node| {
reads
.needed_inputs(node)
.into_iter()
.filter_map(|input| self.positions.get(input.node()?).copied())
.collect()
})
.collect();
let mut scopes = vec![Scopes::default(); self.nodes.len()];
let output = composition
.output
.as_ref()
.and_then(|output| self.positions.get(output));
for position in self.drawn_from(&needed, &output.copied().into_iter().collect::<Vec<_>>()) {
scopes[position].unshifted = 1;
}
for &position in self.order.iter().rev() {
let drawn = scopes[position].total();
if drawn == 0 || !self.shifts(position) {
continue;
}
for read in self.drawn_from(&needed, &needed[position]) {
scopes[read].shifted = scopes[read].shifted.saturating_add(drawn);
}
}
scopes
}
fn first_offset_reading(&self, reaches: &[bool]) -> Option<&'a NodeId> {
self.nodes
.iter()
.enumerate()
.find(|&(position, node)| {
is_offset(node) && self.inputs[position].iter().any(|&input| reaches[input])
})
.map(|(_, node)| &node.id)
}
}
#[derive(Clone, Copy, Default)]
struct Scopes {
unshifted: u64,
shifted: u64,
}
impl Scopes {
const fn total(self) -> u64 {
self.unshifted.saturating_add(self.shifted)
}
}
fn dependencies_first<'a>(
compositions: &'a [Composition],
drawn: impl Fn(&'a CompositionNode) -> Option<&'a Composition>,
) -> Vec<&'a Composition> {
let mut ordered = Vec::with_capacity(compositions.len());
let mut done = HashSet::new();
let mut walking = HashSet::new();
for root in compositions {
let mut stack = vec![(root, false)];
while let Some((composition, expanded)) = stack.pop() {
if done.contains(&composition.id) {
continue;
}
if expanded {
done.insert(&composition.id);
ordered.push(composition);
continue;
}
if !walking.insert(&composition.id) {
continue;
}
stack.push((composition, true));
stack.extend(
composition
.nodes
.iter()
.filter_map(&drawn)
.filter(|inner| !done.contains(&inner.id))
.map(|inner| (inner, false)),
);
}
}
ordered
}
pub(crate) fn shift_spans(composition: &Composition) -> Option<Vec<(i64, i64)>> {
if !has_offsets(composition) {
return None;
}
let graph = Graph::new(composition);
let mut spans = vec![(0_i64, 0_i64); graph.nodes.len()];
for &position in graph.order.iter().rev() {
let (mut low, mut high) = spans[position];
if let (true, NodeOp::TimeOffset { offset, .. }) =
(graph.shifts(position), &graph.nodes[position].op)
{
low = low.saturating_add(offset.ticks());
high = high.saturating_add(offset.ticks());
}
for &input in &graph.inputs[position] {
spans[input] = (spans[input].0.min(low), spans[input].1.max(high));
}
}
Some(spans)
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub(crate) enum Read<'a> {
Clip,
Source(&'a SourceId),
}
#[derive(Default)]
struct ReadCounts<'a> {
unshifted: HashMap<Read<'a>, u64>,
shifted: HashMap<Read<'a>, u64>,
}
impl<'a> ReadCounts<'a> {
fn add(&mut self, read: Read<'a>, scopes: Scopes) {
for (counts, drawn) in [
(&mut self.unshifted, scopes.unshifted),
(&mut self.shifted, scopes.shifted),
] {
if drawn > 0 {
let count = counts.entry(read).or_default();
*count = count.saturating_add(drawn);
}
}
}
fn add_drawn(&mut self, inner: &Self, scopes: Scopes, shows_clip: bool) {
let kept = |read: &Read<'a>| shows_clip || *read != Read::Clip;
for (&read, &count) in inner.unshifted.iter().filter(|(read, _)| kept(read)) {
self.add(
read,
Scopes {
unshifted: scopes.unshifted.saturating_mul(count),
shifted: scopes.shifted.saturating_mul(count),
},
);
}
for (&read, &count) in inner.shifted.iter().filter(|(read, _)| kept(read)) {
self.add(
read,
Scopes {
unshifted: 0,
shifted: scopes.total().saturating_mul(count),
},
);
}
}
}
fn drawn_composition<'a>(
node: &'a CompositionNode,
source_compositions: &HashMap<&SourceId, &'a CompositionId>,
) -> Option<&'a CompositionId> {
match &node.op {
NodeOp::Group { composition, .. } => Some(composition),
NodeOp::Media { source_id, .. } => source_compositions.get(source_id).copied(),
_ => None,
}
}
pub(crate) type ShiftedReads<'a> = HashMap<&'a CompositionId, HashMap<Read<'a>, u64>>;
pub(crate) fn shifted_reads(project: &Project) -> ShiftedReads<'_> {
if !project.compositions.iter().any(has_offsets) {
return HashMap::new();
}
let by_id: HashMap<&CompositionId, &Composition> = project
.compositions
.iter()
.map(|composition| (&composition.id, composition))
.collect();
let reads = CompositionReads::new(&by_id);
let source_compositions: HashMap<&SourceId, &CompositionId> = project
.sources
.iter()
.filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
.collect();
let drawn = |node| drawn_composition(node, &source_compositions);
let mut counts: HashMap<&CompositionId, ReadCounts<'_>> = HashMap::new();
let ordered = dependencies_first(&project.compositions, |node| {
by_id.get(drawn(node)?).copied()
});
for composition in ordered {
let graph = Graph::new(composition);
let scopes = graph.scopes(composition, &reads);
let mut own = ReadCounts::default();
for (node, scopes) in composition.nodes.iter().zip(scopes) {
if node.bypass || scopes.total() == 0 {
continue;
}
match (&node.op, drawn(node).and_then(|id| counts.get(id))) {
(NodeOp::Clip {}, _) => own.add(Read::Clip, scopes),
(NodeOp::Group { .. }, Some(inner)) => own.add_drawn(inner, scopes, true),
(NodeOp::Media { .. }, Some(inner)) => own.add_drawn(inner, scopes, false),
(NodeOp::Media { source_id, .. }, None) => {
own.add(Read::Source(source_id), scopes);
}
_ => {}
}
}
counts.insert(&composition.id, own);
}
counts
.into_iter()
.map(|(id, counts)| (id, counts.shifted))
.collect()
}
pub(crate) fn ensure_no_group_input_is_shifted(
composition: &Composition,
) -> Result<(), crate::ModelError> {
if !has_offsets(composition) {
return Ok(());
}
let graph = Graph::new(composition);
let reaches = graph.reaching(|node| matches!(node.op, NodeOp::GroupInput { .. }));
match graph.first_offset_reading(&reaches) {
Some(node) => Err(crate::ModelError::InvalidTimeOffset {
composition: composition.id.clone(),
node: node.clone(),
problem: TimeOffsetProblem::GroupInput,
}),
None => Ok(()),
}
}
pub(crate) type ShiftedClipReads<'a> = HashMap<&'a CompositionId, (&'a CompositionId, &'a NodeId)>;
pub(crate) fn ensure_clip_can_be_shifted(
clip: &crate::Clip,
source: &crate::MediaSource,
composition: &CompositionId,
shifted: &ShiftedClipReads<'_>,
) -> Result<(), crate::ModelError> {
let problem = match source.kind {
crate::MediaKind::Adjustment => TimeOffsetProblem::AdjustmentBackdrop {
clip: clip.id.clone(),
},
crate::MediaKind::Composition => TimeOffsetProblem::CompositionSource {
clip: clip.id.clone(),
},
_ => return Ok(()),
};
match shifted.get(composition) {
Some(&(composition, node)) => Err(crate::ModelError::InvalidTimeOffset {
composition: composition.clone(),
node: node.clone(),
problem,
}),
None => Ok(()),
}
}
pub(crate) fn depth_and_inlined_nodes<'a>(
composition: &'a Composition,
drawn: impl Fn(&'a CompositionNode) -> (usize, u64),
) -> (usize, u64) {
let graph = Graph::new(composition);
let over = crate::MAX_INLINED_NODES as u64 + 1;
let mut cost = vec![0_u64; graph.nodes.len()];
let mut nesting = vec![0_usize; graph.nodes.len()];
let mut walked_for = vec![usize::MAX; graph.nodes.len()];
let mut total = 0_u64;
for &position in &graph.order {
let node = &graph.nodes[position];
let (inner, own) = drawn(node);
let below = graph.inputs[position]
.iter()
.map(|&input| nesting[input])
.max()
.unwrap_or(0);
if is_offset(node) {
nesting[position] = below.saturating_add(1);
let mut again = 0_u64;
let mut pending = graph.inputs[position].clone();
while let Some(read) = pending.pop().filter(|_| total.saturating_add(again) < over) {
if std::mem::replace(&mut walked_for[read], position) == position {
continue;
}
again = again.saturating_add(cost[read]);
if !is_offset(&graph.nodes[read]) {
pending.extend(&graph.inputs[read]);
}
}
cost[position] = own.saturating_add(again);
} else {
nesting[position] = below.max(inner);
cost[position] = own;
}
total = total.saturating_add(cost[position]).min(over);
}
let depth = nesting.iter().copied().max().unwrap_or(0).saturating_add(1);
(depth, total)
}
pub(crate) fn shifted_clip_reads(compositions: &[Composition]) -> ShiftedClipReads<'_> {
let mut shifted = HashMap::new();
if !compositions.iter().any(has_offsets) {
return shifted;
}
let by_id: HashMap<&CompositionId, &Composition> = compositions
.iter()
.map(|composition| (&composition.id, composition))
.collect();
let group = |node: &CompositionNode| match &node.op {
NodeOp::Group { composition, .. } => by_id.get(composition).copied(),
_ => None,
};
let mut draws_clip: HashMap<&CompositionId, bool> = HashMap::new();
for composition in dependencies_first(compositions, group) {
let graph = Graph::new(composition);
let reaches = graph.reaching(|node| match &node.op {
NodeOp::Clip {} => true,
NodeOp::Group { composition, .. } => {
draws_clip.get(composition).copied().unwrap_or(false)
}
_ => false,
});
let output = composition
.output
.as_ref()
.and_then(|output| graph.positions.get(output))
.is_some_and(|&output| reaches[output]);
draws_clip.insert(&composition.id, output);
let read = composition
.nodes
.iter()
.enumerate()
.find_map(|(position, node)| match &node.op {
NodeOp::TimeOffset { .. } => graph.inputs[position]
.iter()
.any(|&input| reaches[input])
.then_some((&composition.id, &node.id)),
NodeOp::Group { composition, .. } => shifted.get(composition).copied(),
_ => None,
});
if let Some(read) = read {
shifted.insert(&composition.id, read);
}
}
shifted
}
#[cfg(test)]
#[path = "time_offset_tests.rs"]
mod tests;