alpha2-model 0.9.0

Versioned project and timeline model for alpha2.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
//! What time offset nodes may read, and what they draw again.

use crate::{
    ClipId, Composition, CompositionId, CompositionNode, CompositionReads, NodeId, NodeOp, Project,
};
use alpha2_media::SourceId;
use std::collections::{HashMap, HashSet};
use std::fmt;

/// Why a [`crate::ModelError::InvalidTimeOffset`] refuses a time offset node.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum TimeOffsetProblem {
    /// Its input reaches a group input: an image handed in, which has no other time.
    GroupInput,
    /// Its input reaches the clip node of a composition an adjustment clip shows: the scene
    /// beneath the clip, which has no other time.
    AdjustmentBackdrop {
        /// The adjustment clip.
        clip: ClipId,
    },
    /// Its input reaches the clip node of a composition that a clip of a composition source
    /// shows.
    CompositionSource {
        /// The clip.
        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;