Skip to main content

alpha2_model/
time_offset.rs

1//! What time offset nodes may read, and what they draw again.
2
3use crate::{
4    ClipId, Composition, CompositionId, CompositionNode, CompositionReads, NodeId, NodeOp, Project,
5};
6use alpha2_media::SourceId;
7use std::collections::{HashMap, HashSet};
8use std::fmt;
9
10/// Why a [`crate::ModelError::InvalidTimeOffset`] refuses a time offset node.
11#[derive(Clone, Debug, Eq, PartialEq)]
12pub enum TimeOffsetProblem {
13    /// Its input reaches a group input: an image handed in, which has no other time.
14    GroupInput,
15    /// Its input reaches the clip node of a composition an adjustment clip shows: the scene
16    /// beneath the clip, which has no other time.
17    AdjustmentBackdrop {
18        /// The adjustment clip.
19        clip: ClipId,
20    },
21    /// Its input reaches the clip node of a composition that a clip of a composition source
22    /// shows.
23    CompositionSource {
24        /// The clip.
25        clip: ClipId,
26    },
27}
28
29impl fmt::Display for TimeOffsetProblem {
30    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
31        match self {
32            Self::GroupInput => formatter.write_str("shifts a group input"),
33            Self::AdjustmentBackdrop { clip } => {
34                write!(formatter, "shifts the scene beneath adjustment clip {clip}")
35            }
36            Self::CompositionSource { clip } => {
37                write!(formatter, "shifts the composition source of clip {clip}")
38            }
39        }
40    }
41}
42
43pub(crate) fn has_offsets(composition: &Composition) -> bool {
44    composition.nodes.iter().any(is_offset)
45}
46
47const fn is_offset(node: &CompositionNode) -> bool {
48    matches!(node.op, NodeOp::TimeOffset { .. })
49}
50
51struct Graph<'a> {
52    nodes: &'a [CompositionNode],
53    positions: HashMap<&'a NodeId, usize>,
54    inputs: Vec<Vec<usize>>,
55    order: Vec<usize>,
56}
57
58impl<'a> Graph<'a> {
59    fn new(composition: &'a Composition) -> Self {
60        let nodes = composition.nodes.as_slice();
61        let positions: HashMap<&NodeId, usize> = nodes
62            .iter()
63            .enumerate()
64            .map(|(position, node)| (&node.id, position))
65            .collect();
66        let inputs: Vec<Vec<usize>> = nodes
67            .iter()
68            .map(|node| {
69                node.op
70                    .inputs()
71                    .into_iter()
72                    .filter_map(|input| positions.get(input.node()?).copied())
73                    .collect()
74            })
75            .collect();
76        let mut order = Vec::with_capacity(nodes.len());
77        let mut entered = vec![false; nodes.len()];
78        for root in 0..nodes.len() {
79            if entered[root] {
80                continue;
81            }
82            entered[root] = true;
83            let mut stack = vec![(root, 0_usize)];
84            while let Some((current, next)) = stack.last_mut() {
85                let Some(&input) = inputs[*current].get(*next) else {
86                    order.push(*current);
87                    stack.pop();
88                    continue;
89                };
90                *next += 1;
91                if !entered[input] {
92                    entered[input] = true;
93                    stack.push((input, 0));
94                }
95            }
96        }
97        Self {
98            nodes,
99            positions,
100            inputs,
101            order,
102        }
103    }
104
105    fn reaching(&self, found: impl Fn(&CompositionNode) -> bool) -> Vec<bool> {
106        let mut reaches = vec![false; self.nodes.len()];
107        for &position in &self.order {
108            reaches[position] = found(&self.nodes[position])
109                || self.inputs[position].iter().any(|&input| reaches[input]);
110        }
111        reaches
112    }
113
114    fn shifts(&self, position: usize) -> bool {
115        !self.nodes[position].bypass && is_offset(&self.nodes[position])
116    }
117
118    fn drawn_from(&self, needed: &[Vec<usize>], from: &[usize]) -> Vec<usize> {
119        let mut reached = vec![false; self.nodes.len()];
120        let mut region = Vec::new();
121        let mut pending = from.to_vec();
122        while let Some(position) = pending.pop() {
123            if std::mem::replace(&mut reached[position], true) {
124                continue;
125            }
126            region.push(position);
127            if !self.shifts(position) {
128                pending.extend(&needed[position]);
129            }
130        }
131        region
132    }
133
134    fn scopes(&self, composition: &Composition, reads: &CompositionReads<'_>) -> Vec<Scopes> {
135        let needed: Vec<Vec<usize>> = self
136            .nodes
137            .iter()
138            .map(|node| {
139                reads
140                    .needed_inputs(node)
141                    .into_iter()
142                    .filter_map(|input| self.positions.get(input.node()?).copied())
143                    .collect()
144            })
145            .collect();
146        let mut scopes = vec![Scopes::default(); self.nodes.len()];
147        let output = composition
148            .output
149            .as_ref()
150            .and_then(|output| self.positions.get(output));
151        for position in self.drawn_from(&needed, &output.copied().into_iter().collect::<Vec<_>>()) {
152            scopes[position].unshifted = 1;
153        }
154        for &position in self.order.iter().rev() {
155            let drawn = scopes[position].total();
156            if drawn == 0 || !self.shifts(position) {
157                continue;
158            }
159            for read in self.drawn_from(&needed, &needed[position]) {
160                scopes[read].shifted = scopes[read].shifted.saturating_add(drawn);
161            }
162        }
163        scopes
164    }
165
166    fn first_offset_reading(&self, reaches: &[bool]) -> Option<&'a NodeId> {
167        self.nodes
168            .iter()
169            .enumerate()
170            .find(|&(position, node)| {
171                is_offset(node) && self.inputs[position].iter().any(|&input| reaches[input])
172            })
173            .map(|(_, node)| &node.id)
174    }
175}
176
177#[derive(Clone, Copy, Default)]
178struct Scopes {
179    unshifted: u64,
180    shifted: u64,
181}
182
183impl Scopes {
184    const fn total(self) -> u64 {
185        self.unshifted.saturating_add(self.shifted)
186    }
187}
188
189fn dependencies_first<'a>(
190    compositions: &'a [Composition],
191    drawn: impl Fn(&'a CompositionNode) -> Option<&'a Composition>,
192) -> Vec<&'a Composition> {
193    let mut ordered = Vec::with_capacity(compositions.len());
194    let mut done = HashSet::new();
195    let mut walking = HashSet::new();
196    for root in compositions {
197        let mut stack = vec![(root, false)];
198        while let Some((composition, expanded)) = stack.pop() {
199            if done.contains(&composition.id) {
200                continue;
201            }
202            if expanded {
203                done.insert(&composition.id);
204                ordered.push(composition);
205                continue;
206            }
207            if !walking.insert(&composition.id) {
208                continue;
209            }
210            stack.push((composition, true));
211            stack.extend(
212                composition
213                    .nodes
214                    .iter()
215                    .filter_map(&drawn)
216                    .filter(|inner| !done.contains(&inner.id))
217                    .map(|inner| (inner, false)),
218            );
219        }
220    }
221    ordered
222}
223
224pub(crate) fn shift_spans(composition: &Composition) -> Option<Vec<(i64, i64)>> {
225    if !has_offsets(composition) {
226        return None;
227    }
228    let graph = Graph::new(composition);
229    let mut spans = vec![(0_i64, 0_i64); graph.nodes.len()];
230    for &position in graph.order.iter().rev() {
231        let (mut low, mut high) = spans[position];
232        if let (true, NodeOp::TimeOffset { offset, .. }) =
233            (graph.shifts(position), &graph.nodes[position].op)
234        {
235            low = low.saturating_add(offset.ticks());
236            high = high.saturating_add(offset.ticks());
237        }
238        for &input in &graph.inputs[position] {
239            spans[input] = (spans[input].0.min(low), spans[input].1.max(high));
240        }
241    }
242    Some(spans)
243}
244
245#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
246pub(crate) enum Read<'a> {
247    Clip,
248    Source(&'a SourceId),
249}
250
251#[derive(Default)]
252struct ReadCounts<'a> {
253    unshifted: HashMap<Read<'a>, u64>,
254    shifted: HashMap<Read<'a>, u64>,
255}
256
257impl<'a> ReadCounts<'a> {
258    fn add(&mut self, read: Read<'a>, scopes: Scopes) {
259        for (counts, drawn) in [
260            (&mut self.unshifted, scopes.unshifted),
261            (&mut self.shifted, scopes.shifted),
262        ] {
263            if drawn > 0 {
264                let count = counts.entry(read).or_default();
265                *count = count.saturating_add(drawn);
266            }
267        }
268    }
269
270    fn add_drawn(&mut self, inner: &Self, scopes: Scopes, shows_clip: bool) {
271        let kept = |read: &Read<'a>| shows_clip || *read != Read::Clip;
272        for (&read, &count) in inner.unshifted.iter().filter(|(read, _)| kept(read)) {
273            self.add(
274                read,
275                Scopes {
276                    unshifted: scopes.unshifted.saturating_mul(count),
277                    shifted: scopes.shifted.saturating_mul(count),
278                },
279            );
280        }
281        for (&read, &count) in inner.shifted.iter().filter(|(read, _)| kept(read)) {
282            self.add(
283                read,
284                Scopes {
285                    unshifted: 0,
286                    shifted: scopes.total().saturating_mul(count),
287                },
288            );
289        }
290    }
291}
292
293fn drawn_composition<'a>(
294    node: &'a CompositionNode,
295    source_compositions: &HashMap<&SourceId, &'a CompositionId>,
296) -> Option<&'a CompositionId> {
297    match &node.op {
298        NodeOp::Group { composition, .. } => Some(composition),
299        NodeOp::Media { source_id, .. } => source_compositions.get(source_id).copied(),
300        _ => None,
301    }
302}
303
304pub(crate) type ShiftedReads<'a> = HashMap<&'a CompositionId, HashMap<Read<'a>, u64>>;
305
306pub(crate) fn shifted_reads(project: &Project) -> ShiftedReads<'_> {
307    if !project.compositions.iter().any(has_offsets) {
308        return HashMap::new();
309    }
310    let by_id: HashMap<&CompositionId, &Composition> = project
311        .compositions
312        .iter()
313        .map(|composition| (&composition.id, composition))
314        .collect();
315    let reads = CompositionReads::new(&by_id);
316    let source_compositions: HashMap<&SourceId, &CompositionId> = project
317        .sources
318        .iter()
319        .filter_map(|source| Some((&source.id, source.composition.as_ref()?)))
320        .collect();
321    let drawn = |node| drawn_composition(node, &source_compositions);
322    let mut counts: HashMap<&CompositionId, ReadCounts<'_>> = HashMap::new();
323    let ordered = dependencies_first(&project.compositions, |node| {
324        by_id.get(drawn(node)?).copied()
325    });
326    for composition in ordered {
327        let graph = Graph::new(composition);
328        let scopes = graph.scopes(composition, &reads);
329        let mut own = ReadCounts::default();
330        for (node, scopes) in composition.nodes.iter().zip(scopes) {
331            if node.bypass || scopes.total() == 0 {
332                continue;
333            }
334            match (&node.op, drawn(node).and_then(|id| counts.get(id))) {
335                (NodeOp::Clip {}, _) => own.add(Read::Clip, scopes),
336                (NodeOp::Group { .. }, Some(inner)) => own.add_drawn(inner, scopes, true),
337                (NodeOp::Media { .. }, Some(inner)) => own.add_drawn(inner, scopes, false),
338                (NodeOp::Media { source_id, .. }, None) => {
339                    own.add(Read::Source(source_id), scopes);
340                }
341                _ => {}
342            }
343        }
344        counts.insert(&composition.id, own);
345    }
346    counts
347        .into_iter()
348        .map(|(id, counts)| (id, counts.shifted))
349        .collect()
350}
351
352pub(crate) fn ensure_no_group_input_is_shifted(
353    composition: &Composition,
354) -> Result<(), crate::ModelError> {
355    if !has_offsets(composition) {
356        return Ok(());
357    }
358    let graph = Graph::new(composition);
359    let reaches = graph.reaching(|node| matches!(node.op, NodeOp::GroupInput { .. }));
360    match graph.first_offset_reading(&reaches) {
361        Some(node) => Err(crate::ModelError::InvalidTimeOffset {
362            composition: composition.id.clone(),
363            node: node.clone(),
364            problem: TimeOffsetProblem::GroupInput,
365        }),
366        None => Ok(()),
367    }
368}
369
370pub(crate) type ShiftedClipReads<'a> = HashMap<&'a CompositionId, (&'a CompositionId, &'a NodeId)>;
371
372pub(crate) fn ensure_clip_can_be_shifted(
373    clip: &crate::Clip,
374    source: &crate::MediaSource,
375    composition: &CompositionId,
376    shifted: &ShiftedClipReads<'_>,
377) -> Result<(), crate::ModelError> {
378    let problem = match source.kind {
379        crate::MediaKind::Adjustment => TimeOffsetProblem::AdjustmentBackdrop {
380            clip: clip.id.clone(),
381        },
382        crate::MediaKind::Composition => TimeOffsetProblem::CompositionSource {
383            clip: clip.id.clone(),
384        },
385        _ => return Ok(()),
386    };
387    match shifted.get(composition) {
388        Some(&(composition, node)) => Err(crate::ModelError::InvalidTimeOffset {
389            composition: composition.clone(),
390            node: node.clone(),
391            problem,
392        }),
393        None => Ok(()),
394    }
395}
396
397pub(crate) fn depth_and_inlined_nodes<'a>(
398    composition: &'a Composition,
399    drawn: impl Fn(&'a CompositionNode) -> (usize, u64),
400) -> (usize, u64) {
401    let graph = Graph::new(composition);
402    let over = crate::MAX_INLINED_NODES as u64 + 1;
403    let mut cost = vec![0_u64; graph.nodes.len()];
404    let mut nesting = vec![0_usize; graph.nodes.len()];
405    let mut walked_for = vec![usize::MAX; graph.nodes.len()];
406    let mut total = 0_u64;
407    for &position in &graph.order {
408        let node = &graph.nodes[position];
409        let (inner, own) = drawn(node);
410        let below = graph.inputs[position]
411            .iter()
412            .map(|&input| nesting[input])
413            .max()
414            .unwrap_or(0);
415        if is_offset(node) {
416            nesting[position] = below.saturating_add(1);
417            let mut again = 0_u64;
418            let mut pending = graph.inputs[position].clone();
419            while let Some(read) = pending.pop().filter(|_| total.saturating_add(again) < over) {
420                if std::mem::replace(&mut walked_for[read], position) == position {
421                    continue;
422                }
423                again = again.saturating_add(cost[read]);
424                if !is_offset(&graph.nodes[read]) {
425                    pending.extend(&graph.inputs[read]);
426                }
427            }
428            cost[position] = own.saturating_add(again);
429        } else {
430            nesting[position] = below.max(inner);
431            cost[position] = own;
432        }
433        total = total.saturating_add(cost[position]).min(over);
434    }
435    let depth = nesting.iter().copied().max().unwrap_or(0).saturating_add(1);
436    (depth, total)
437}
438
439pub(crate) fn shifted_clip_reads(compositions: &[Composition]) -> ShiftedClipReads<'_> {
440    let mut shifted = HashMap::new();
441    if !compositions.iter().any(has_offsets) {
442        return shifted;
443    }
444    let by_id: HashMap<&CompositionId, &Composition> = compositions
445        .iter()
446        .map(|composition| (&composition.id, composition))
447        .collect();
448    let group = |node: &CompositionNode| match &node.op {
449        NodeOp::Group { composition, .. } => by_id.get(composition).copied(),
450        _ => None,
451    };
452    let mut draws_clip: HashMap<&CompositionId, bool> = HashMap::new();
453    for composition in dependencies_first(compositions, group) {
454        let graph = Graph::new(composition);
455        let reaches = graph.reaching(|node| match &node.op {
456            NodeOp::Clip {} => true,
457            NodeOp::Group { composition, .. } => {
458                draws_clip.get(composition).copied().unwrap_or(false)
459            }
460            _ => false,
461        });
462        let output = composition
463            .output
464            .as_ref()
465            .and_then(|output| graph.positions.get(output))
466            .is_some_and(|&output| reaches[output]);
467        draws_clip.insert(&composition.id, output);
468        let read = composition
469            .nodes
470            .iter()
471            .enumerate()
472            .find_map(|(position, node)| match &node.op {
473                NodeOp::TimeOffset { .. } => graph.inputs[position]
474                    .iter()
475                    .any(|&input| reaches[input])
476                    .then_some((&composition.id, &node.id)),
477                NodeOp::Group { composition, .. } => shifted.get(composition).copied(),
478                _ => None,
479            });
480        if let Some(read) = read {
481            shifted.insert(&composition.id, read);
482        }
483    }
484    shifted
485}
486
487#[cfg(test)]
488#[path = "time_offset_tests.rs"]
489mod tests;