1use crate::{EvalError, IndexedCaptions, IndexedClip, IndexedTransition, IntervalNode, build_tree};
7use alpha2_media::SourceId;
8use alpha2_model::{CompositionId, Project, ProjectId};
9use alpha2_time::TimeRange;
10
11#[derive(Clone, Debug)]
13pub struct ActiveIndex {
14 pub(crate) project_id: ProjectId,
15 pub(crate) nodes: Vec<IntervalNode>,
16 pub(crate) root: Option<usize>,
17 pub(crate) transitions: Vec<IndexedTransition>,
18 pub(crate) captions: Vec<IndexedCaptions>,
20 pub(crate) max_active: usize,
22 pub(crate) data: crate::DataIndex,
24 pub(crate) plans_too_large: bool,
26}
27
28impl ActiveIndex {
29 #[must_use]
32 pub fn sample_context<'a>(
33 &'a self,
34 project: &'a alpha2_model::Project,
35 ) -> crate::SampleContext<'a> {
36 crate::SampleContext::timeline(project, &self.data)
37 }
38
39 #[must_use]
41 pub const fn data(&self) -> &crate::DataIndex {
42 &self.data
43 }
44
45 #[allow(clippy::too_many_lines)]
51 pub fn build(project: &Project) -> Result<Self, EvalError> {
52 project.validate().map_err(EvalError::InvalidProject)?;
53 let mut entries = Vec::new();
54 let mut transitions = Vec::new();
55 let matte_sources = project.timeline.matte_sources();
56 let lookup = crate::composition::Lookup::new(
57 &project.compositions,
58 &project.sources,
59 (project.settings.width, project.settings.height),
60 );
61 let (plans, source_plans, plans_too_large) = compile_plans(project, &lookup);
62 let sources = project
63 .sources
64 .iter()
65 .map(|source| (&source.id, source))
66 .collect::<std::collections::HashMap<_, _>>();
67 let generators = generator_plans(project);
68 for (track_order, track) in project.timeline.tracks.iter().enumerate() {
69 for (clip_order, clip) in track.clips.iter().enumerate() {
70 let source = sources.get(&clip.source_id).copied();
72 let source_is_audible = source.is_some_and(alpha2_model::MediaSource::is_audible);
73 let generator = source.and_then(|source| source.generator.clone());
74 let drawn = clip
76 .composition
77 .as_ref()
78 .is_none_or(|reference| lookup.reads().draws_clip(&reference.id));
79 let source_composition = source
80 .filter(|_| drawn)
81 .and_then(|source| source_composition_of(source, &source_plans));
82 entries.push(IndexedClip {
83 clip_id: clip.id.clone(),
84 source_id: clip.source_id.clone(),
85 track_id: track.id.clone(),
86 track_kind: track.kind,
87 timeline_range: clip.timeline_range,
88 source_range: clip.source_range,
89 time_map: clip.time_map,
90 visual: clip.visual.clone(),
91 composition: clip.composition.as_ref().and_then(|reference| {
93 plans
94 .get(&reference.id)
95 .map(|plan| crate::IndexedComposition {
96 plan: std::sync::Arc::clone(plan),
97 reference: reference.clone(),
98 })
99 }),
100 blend_mode: clip.blend_mode,
101 cache: clip.cache,
102 masks: clip.masks.clone(),
103 matte: clip.matte.clone(),
104 is_matte: matte_sources.contains(&clip.id),
105 adjustment: source
106 .is_some_and(|source| source.kind == alpha2_model::MediaKind::Adjustment),
107 audio: clip.audio.clone(),
108 source_is_audible,
109 generator,
110 plan: generators.get(&clip.source_id).cloned(),
111 source_composition,
112 track_order,
113 clip_order,
114 });
115 }
116 transitions.extend(track.transitions.iter().enumerate().map(
117 |(list_order, transition)| IndexedTransition {
118 from_clip: transition.from_clip.clone(),
119 to_clip: transition.to_clip.clone(),
120 timeline_range: transition.timeline_range,
121 easing: transition.easing,
122 effect: transition.effect.clone(),
123 track_order,
124 list_order,
125 },
126 ));
127 }
128 let captions = project
129 .timeline
130 .tracks
131 .iter()
132 .enumerate()
133 .filter_map(|(track_order, track)| {
134 track.captions.as_ref().map(|captions| {
135 let mut shown = captions.clone();
136 if shown.from_words.is_some() {
137 shown.cues = crate::caption_cues(project, &track.id, captions)
138 .map_err(EvalError::InvalidProject)?;
139 }
140 Ok(IndexedCaptions::new(track.id.clone(), track_order, shown))
141 })
142 })
143 .collect::<Result<_, EvalError>>()?;
144 entries.sort_unstable_by_key(|entry| {
145 (
146 entry.timeline_range.start(),
147 entry.track_order,
148 entry.clip_order,
149 )
150 });
151 let max_active = deepest_overlap(&entries);
152 let (nodes, root) = build_tree(entries);
153 transitions.sort_unstable_by_key(|transition| {
154 (
155 transition.timeline_range.start(),
156 transition.track_order,
157 transition.list_order,
158 )
159 });
160 Ok(Self {
161 project_id: project.id.clone(),
162 nodes,
163 root,
164 transitions,
165 captions,
166 max_active,
167 data: crate::DataIndex::new(project),
168 plans_too_large,
169 })
170 }
171
172 #[must_use]
178 pub fn plan_errors(&self, range: TimeRange) -> Vec<EvalError> {
179 let mut found = Vec::new();
180 for entry in self.nodes.iter().map(IntervalNode::entry) {
181 if entry.track_kind != alpha2_model::TrackKind::Video
182 || entry.timeline_range.intersection(range).is_none()
183 {
184 continue;
185 }
186 let own = entry
187 .composition
188 .as_ref()
189 .map(|indexed| (&indexed.reference.id, &indexed.plan));
190 let shown = entry
191 .source_composition
192 .as_ref()
193 .map(|(id, plan)| (id, plan));
194 if let Some((composition, Err(reason))) = own
195 .into_iter()
196 .chain(shown)
197 .map(|(id, plan)| (id, plan.as_ref().as_ref()))
198 .find(|(_, plan)| plan.is_err())
199 {
200 found.push((
201 entry.timeline_range.start(),
202 entry.track_order,
203 EvalError::IncompleteComposition {
204 clip: entry.clip_id.clone(),
205 composition: composition.clone(),
206 reason: reason.clone(),
207 },
208 ));
209 }
210 }
211 found.sort_by_key(|(start, track, _)| (*start, *track));
212 if self.plans_too_large {
213 found.truncate(1);
214 }
215 found.into_iter().map(|(_, _, error)| error).collect()
216 }
217
218 #[must_use]
220 pub const fn plans_too_large(&self) -> bool {
221 self.plans_too_large
222 }
223
224 #[must_use]
226 pub fn project_id(&self) -> &ProjectId {
227 &self.project_id
228 }
229
230 #[must_use]
232 pub fn len(&self) -> usize {
233 self.nodes.len()
234 }
235
236 #[must_use]
238 pub fn is_empty(&self) -> bool {
239 self.nodes.is_empty()
240 }
241
242 pub fn effects(&self) -> impl Iterator<Item = &alpha2_model::ClipEffect> {
245 let mut seen = std::collections::HashSet::new();
246 let plans = self
247 .nodes
248 .iter()
249 .flat_map(|node| clip_plans(node.entry()))
250 .flatten()
251 .filter(|slot| seen.insert(std::sync::Arc::as_ptr(slot)))
252 .filter_map(|slot| slot.as_ref().as_ref().ok())
253 .collect::<Vec<_>>();
254 plans
255 .into_iter()
256 .flat_map(crate::CompositionPlan::effects)
257 .chain(self.transitions.iter().map(|transition| &transition.effect))
258 }
259
260 #[must_use]
266 pub fn peak_source_reads(
267 &self,
268 range: TimeRange,
269 mut counted: impl FnMut(&SourceId) -> bool,
270 ) -> usize {
271 let mut plan_reads = std::collections::HashMap::new();
273 let mut events = Vec::new();
274 for entry in self.nodes.iter().map(IntervalNode::entry) {
275 let Some(span) = entry.timeline_range.intersection(range) else {
276 continue;
277 };
278 let [composition, source_composition] = clip_plans(entry);
279 let mut reads = usize::from(draws_own_source(entry) && counted(&entry.source_id));
280 for slot in [composition, source_composition].into_iter().flatten() {
281 reads += *plan_reads
282 .entry(std::sync::Arc::as_ptr(slot))
283 .or_insert_with(|| {
284 slot.as_ref().as_ref().map_or(0, |plan| {
285 plan.steps
286 .iter()
287 .filter(|step| match &step.op {
288 crate::StepOp::Media { source_id, .. } => counted(source_id),
289 _ => false,
290 })
291 .count()
292 })
293 });
294 }
295 if reads > 0 {
296 let delta = isize::try_from(reads).unwrap_or(isize::MAX);
297 events.extend([(span.start(), delta), (span.end(), -delta)]);
298 }
299 }
300 events.sort_unstable_by_key(|&(time, delta)| (time, delta.signum()));
302 let mut active = 0_usize;
303 let mut peak = 0;
304 for (_, delta) in events {
305 active = active.saturating_add_signed(delta);
306 peak = peak.max(active);
307 }
308 peak
309 }
310
311 #[must_use]
317 pub fn source_reads(
318 &self,
319 range: TimeRange,
320 mut counted: impl FnMut(&SourceId) -> bool,
321 ) -> Vec<SourceRead> {
322 let mut reads = Vec::new();
323 for entry in self.nodes.iter().map(IntervalNode::entry) {
324 let Some(span) = entry.timeline_range.intersection(range) else {
325 continue;
326 };
327 let read = |source_id: &SourceId, reader| SourceRead {
328 source_id: source_id.clone(),
329 clip_id: entry.clip_id.clone(),
330 reader,
331 span,
332 };
333 if draws_own_source(entry) && counted(&entry.source_id) {
334 reads.push(read(&entry.source_id, None));
335 }
336 let [composition, source_composition] = clip_plans(entry);
337 for (slot, of_source) in [(composition, false), (source_composition, true)] {
338 let Some(Ok(plan)) = slot.map(|slot| slot.as_ref().as_ref()) else {
339 continue;
340 };
341 for step in &plan.steps {
342 let crate::StepOp::Media { source_id, .. } = &step.op else {
343 continue;
344 };
345 if !counted(source_id) {
346 continue;
347 }
348 let reader = if of_source {
349 alpha2_model::NodeId::new(format!("/{}", step.node)).ok()
350 } else {
351 Some(step.node.clone())
352 };
353 reads.push(read(source_id, reader));
354 }
355 }
356 }
357 reads
358 }
359}
360
361#[derive(Clone, Debug, Eq, PartialEq)]
363pub struct SourceRead {
364 pub source_id: SourceId,
366 pub clip_id: alpha2_model::ClipId,
368 pub reader: Option<alpha2_model::NodeId>,
370 pub span: TimeRange,
372}
373
374fn draws_own_source(entry: &IndexedClip) -> bool {
375 let [composition, source_composition] = clip_plans(entry);
376 entry.generator.is_none()
377 && source_composition.is_none()
378 && composition.is_none_or(|slot| {
379 slot.as_ref()
380 .as_ref()
381 .is_ok_and(crate::CompositionPlan::uses_clip)
382 })
383}
384
385fn clip_plans(entry: &IndexedClip) -> [Option<&PlanSlot>; 2] {
387 [
388 entry
389 .composition
390 .as_ref()
391 .map(|composition| &composition.plan),
392 entry.source_composition.as_ref().map(|(_, plan)| plan),
393 ]
394}
395
396type Plans<'a> = std::collections::HashMap<&'a CompositionId, PlanSlot>;
397
398fn compile_plans<'a>(
401 project: &'a Project,
402 lookup: &crate::composition::Lookup<'a>,
403) -> (Plans<'a>, Plans<'a>, bool) {
404 let shown = project
405 .timeline
406 .tracks
407 .iter()
408 .flat_map(|track| &track.clips)
409 .filter_map(|clip| clip.composition.as_ref().map(|reference| &reference.id))
410 .collect::<std::collections::HashSet<_>>();
411 let sourced = project
413 .sources
414 .iter()
415 .filter_map(|source| source.composition.as_ref())
416 .collect::<std::collections::HashSet<_>>();
417 let mut budget = crate::composition::PlanBudget::new(crate::MAX_PLAN_BYTES);
418 let mut plans = Plans::new();
419 let mut source_plans = Plans::new();
420 let refused = std::sync::Arc::new(Err(crate::PlanError::TooLarge));
421 for composition in &project.compositions {
422 if budget.exceeded() {
424 if shown.contains(&composition.id) {
425 plans.insert(&composition.id, std::sync::Arc::clone(&refused));
426 }
427 if sourced.contains(&composition.id) {
428 source_plans.insert(&composition.id, std::sync::Arc::clone(&refused));
429 }
430 continue;
431 }
432 if shown.contains(&composition.id) {
433 let plan =
434 crate::composition::plan_composition_within(composition, lookup, &mut budget);
435 plans.insert(&composition.id, std::sync::Arc::new(plan));
436 }
437 if sourced.contains(&composition.id) {
438 let plan = crate::composition::plan_source_composition_within(
439 composition,
440 lookup,
441 &mut budget,
442 );
443 source_plans.insert(&composition.id, std::sync::Arc::new(plan));
444 }
445 }
446 if budget.exceeded() {
447 for plan in plans.values_mut().chain(source_plans.values_mut()) {
448 *plan = std::sync::Arc::clone(&refused);
449 }
450 }
451 (plans, source_plans, budget.exceeded())
452}
453
454fn source_composition_of(
455 source: &alpha2_model::MediaSource,
456 plans: &Plans<'_>,
457) -> Option<(CompositionId, PlanSlot)> {
458 let id = source.composition.as_ref()?;
459 Some((id.clone(), std::sync::Arc::clone(plans.get(id)?)))
460}
461
462pub(crate) type PlanSlot = std::sync::Arc<Result<crate::CompositionPlan, crate::PlanError>>;
464
465fn deepest_overlap(entries: &[IndexedClip]) -> usize {
466 let mut edges: Vec<_> = entries
468 .iter()
469 .flat_map(|entry| {
470 [
471 (entry.timeline_range.start(), 1_i8),
472 (entry.timeline_range.end(), -1),
473 ]
474 })
475 .collect();
476 edges.sort_unstable();
477 let mut depth = 0_usize;
478 let mut deepest = 0;
479 for (_, step) in edges {
480 depth = depth.saturating_add_signed(isize::from(step));
481 deepest = deepest.max(depth);
482 }
483 deepest
484}
485
486fn generator_plans(
488 project: &Project,
489) -> std::collections::HashMap<&SourceId, std::sync::Arc<crate::GeneratorPlan>> {
490 project
491 .sources
492 .iter()
493 .filter_map(|source| {
494 let plan = crate::GeneratorPlan::new(
495 source.generator.as_ref()?,
496 (project.settings.width, project.settings.height),
497 )?;
498 Some((&source.id, std::sync::Arc::new(plan)))
499 })
500 .collect()
501}