1use crate::time_curve::Motion;
8use alpha2_model::{
9 Clip, ClipId, DataAnchor, DataBinding, DataInterpolation, DataKind, DataSamples, DataSet,
10 DataSetId, DataSpace, DataValues, DataVia, NodeId, Project, TimeMap, Vec2,
11};
12use alpha2_time::MediaTime;
13use std::collections::HashMap;
14use std::sync::OnceLock;
15
16#[derive(Clone, Debug, Default)]
18pub struct DataIndex {
19 sets: HashMap<DataSetId, usize>,
20 clips: HashMap<ClipId, (usize, usize)>,
21 curve_cuts: HashMap<ClipId, OnceLock<Vec<i64>>>,
22 picture_sizes: Vec<Option<(u32, u32)>>,
24}
25
26impl DataIndex {
27 #[must_use]
29 pub fn new(project: &Project) -> Self {
30 if project.data.is_empty() {
31 return Self::default();
32 }
33 let sources = project
34 .sources
35 .iter()
36 .map(|source| (&source.id, source))
37 .collect::<HashMap<_, _>>();
38 let video_size = |fingerprint: Option<&alpha2_model::MediaFingerprint>| {
39 fingerprint
40 .and_then(|fingerprint| fingerprint.streams.as_ref())
41 .and_then(|streams| streams.video.as_ref())
42 .filter(|video| video.width > 0 && video.height > 0)
43 .map(|video| (video.width, video.height))
44 };
45 Self {
46 sets: project
47 .data
48 .iter()
49 .enumerate()
50 .map(|(index, set)| (set.id.clone(), index))
51 .collect(),
52 clips: project
53 .timeline
54 .tracks
55 .iter()
56 .enumerate()
57 .flat_map(|(track, entry)| {
58 entry
59 .clips
60 .iter()
61 .enumerate()
62 .map(move |(clip, value)| (value.id.clone(), (track, clip)))
63 })
64 .collect(),
65 curve_cuts: project
66 .timeline
67 .tracks
68 .iter()
69 .flat_map(|track| &track.clips)
70 .filter(|clip| matches!(clip.time_map, TimeMap::Curve { .. }))
71 .map(|clip| (clip.id.clone(), OnceLock::new()))
72 .collect(),
73 picture_sizes: project
74 .data
75 .iter()
76 .map(|set| {
77 video_size(set.made_from.as_ref()).or_else(|| {
78 set.anchor
79 .source()
80 .and_then(|source| sources.get(source))
81 .and_then(|source| video_size(source.fingerprint.as_ref()))
82 })
83 })
84 .collect(),
85 }
86 }
87
88 fn set<'p>(&self, project: &'p Project, id: &DataSetId) -> Option<(&'p DataSet, usize)> {
89 let index = *self.sets.get(id)?;
90 project.data.get(index).map(|set| (set, index))
91 }
92
93 fn clip<'p>(&self, project: &'p Project, id: &ClipId) -> Option<&'p Clip> {
94 let (track, clip) = *self.clips.get(id)?;
95 project.timeline.tracks.get(track)?.clips.get(clip)
96 }
97
98 fn curve_cuts(&self, clip: &Clip) -> &[i64] {
99 let Some(cuts) = self.curve_cuts.get(&clip.id) else {
100 return &[];
101 };
102 cuts.get_or_init(|| {
103 let (start, end) = (
104 clip.timeline_range.start().ticks(),
105 clip.timeline_range.end().ticks(),
106 );
107 crate::TimeCurve::of(&clip.time_map)
108 .and_then(|curve| curve.cuts(start, end, crate::retime::MAX_STRETCHES))
109 .unwrap_or_default()
110 })
111 }
112}
113
114#[derive(Clone, Copy)]
116pub struct SampleContext<'a> {
117 scope: Option<Scope<'a>>,
118}
119
120#[derive(Clone, Copy)]
121struct Scope<'a> {
122 project: &'a Project,
123 index: &'a DataIndex,
124 nodes: Option<Nodes<'a>>,
125}
126
127#[derive(Clone, Copy)]
129enum Nodes<'a> {
130 Step(&'a crate::CompositionPlan, usize),
132 Composition(&'a alpha2_model::Composition),
134}
135
136impl Nodes<'_> {
137 fn media_start(&self, via: &NodeId) -> Option<MediaTime> {
138 match self {
139 Self::Step(plan, step) => plan.media_start(*step, via),
140 Self::Composition(composition) => {
141 composition.nodes.iter().find_map(|node| match &node.op {
142 alpha2_model::NodeOp::Media { start, .. } if &node.id == via => Some(*start),
143 _ => None,
144 })
145 }
146 }
147 }
148
149 fn same(&self, other: &Self) -> bool {
150 match (self, other) {
151 (Self::Step(a, i), Self::Step(b, j)) => std::ptr::eq(*a, *b) && i == j,
152 (Self::Composition(a), Self::Composition(b)) => std::ptr::eq(*a, *b),
153 _ => false,
154 }
155 }
156}
157
158impl PartialEq for SampleContext<'_> {
160 fn eq(&self, other: &Self) -> bool {
161 match (&self.scope, &other.scope) {
162 (None, None) => true,
163 (Some(left), Some(right)) => {
164 std::ptr::eq(left.project, right.project)
165 && std::ptr::eq(left.index, right.index)
166 && match (left.nodes, right.nodes) {
167 (None, None) => true,
168 (Some(a), Some(b)) => a.same(&b),
169 _ => false,
170 }
171 }
172 _ => false,
173 }
174 }
175}
176
177impl std::fmt::Debug for SampleContext<'_> {
178 fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179 formatter
180 .debug_struct("SampleContext")
181 .field("data", &self.scope.is_some())
182 .finish()
183 }
184}
185
186impl<'a> SampleContext<'a> {
187 pub const NONE: SampleContext<'static> = SampleContext { scope: None };
189
190 #[must_use]
192 pub const fn timeline(project: &'a Project, index: &'a DataIndex) -> Self {
193 Self {
194 scope: Some(Scope {
195 project,
196 index,
197 nodes: None,
198 }),
199 }
200 }
201
202 #[must_use]
204 pub const fn composition(
205 project: &'a Project,
206 index: &'a DataIndex,
207 composition: &'a alpha2_model::Composition,
208 ) -> Self {
209 Self {
210 scope: Some(Scope {
211 project,
212 index,
213 nodes: Some(Nodes::Composition(composition)),
214 }),
215 }
216 }
217
218 #[must_use]
221 pub fn for_step(&self, plan: &'a crate::CompositionPlan, step: usize) -> Self {
222 Self {
223 scope: self.scope.map(|scope| Scope {
224 nodes: Some(Nodes::Step(plan, step)),
225 ..scope
226 }),
227 }
228 }
229
230 #[must_use]
232 pub fn for_timeline(&self) -> Self {
233 Self {
234 scope: self.scope.map(|scope| Scope {
235 nodes: None,
236 ..scope
237 }),
238 }
239 }
240
241 fn canvas_aspect(&self) -> f64 {
243 self.scope.map_or(1.0, |scope| {
244 f64::from(scope.project.settings.width) / f64::from(scope.project.settings.height)
245 })
246 }
247}
248
249#[derive(Copy, Clone, Debug, PartialEq)]
251pub struct Correction {
252 pub translate: Vec2,
254 pub rotation_degrees: f32,
256 pub scale: f32,
258 pub picture: Vec2,
260}
261
262impl Correction {
263 #[must_use]
266 pub fn apply(&self, point: Vec2, aspect: f64) -> Vec2 {
267 let (sin, cos) = libm::sincos(f64::from(self.rotation_degrees).to_radians());
268 let scale = f64::from(self.scale);
269 let x = (f64::from(point.x) - 0.5) * aspect;
270 let y = f64::from(point.y) - 0.5;
271 let turned_x = scale * (cos * x - sin * y);
272 let turned_y = scale * (sin * x + cos * y);
273 Vec2::new(
274 finite(
275 0.5 + turned_x / aspect + f64::from(self.translate.x) * f64::from(self.picture.x),
276 ),
277 finite(0.5 + turned_y + f64::from(self.translate.y) * f64::from(self.picture.y)),
278 )
279 }
280}
281
282#[allow(clippy::cast_possible_truncation)]
283fn finite(value: f64) -> f32 {
284 if value.is_finite() {
285 value.clamp(f64::from(f32::MIN), f64::from(f32::MAX)) as f32
286 } else {
287 0.0
288 }
289}
290
291#[must_use]
294pub fn contained_picture(picture: (u32, u32), canvas_aspect: f64) -> Vec2 {
295 let picture_aspect = f64::from(picture.0) / f64::from(picture.1);
296 if picture_aspect >= canvas_aspect {
297 Vec2::new(1.0, finite(canvas_aspect / picture_aspect))
298 } else {
299 Vec2::new(finite(picture_aspect / canvas_aspect), 1.0)
300 }
301}
302
303fn picture_to_layer(point: Vec2, picture: Vec2) -> Vec2 {
306 Vec2::new(
307 finite(0.5 + (f64::from(point.x) - 0.5) * f64::from(picture.x)),
308 finite(0.5 + (f64::from(point.y) - 0.5) * f64::from(picture.y)),
309 )
310}
311
312#[must_use]
317pub fn sample_channel(
318 samples: &DataSamples,
319 channel: usize,
320 arity: usize,
321 time: MediaTime,
322) -> Option<Vec<f32>> {
323 let width = samples.channels.len().max(1) * arity;
324 let at = |sample: usize| -> Option<&[Option<f32>]> {
325 let start = sample * width + channel * arity;
326 samples.values.get(start..start + arity)
327 };
328 let known = |sample: usize| at(sample).filter(|values| values[0].is_some());
329 let collect =
330 |values: &[Option<f32>]| values.iter().map(|value| value.unwrap_or(0.0)).collect();
331 let next = samples.times.partition_point(|sample| *sample <= time);
332 let Some(current) = next.checked_sub(1) else {
333 return (0..samples.times.len()).find_map(known).map(collect);
335 };
336 if let Some(left) = known(current) {
337 if samples.interpolation == DataInterpolation::Linear
338 && samples.times[current] < time
339 && let Some(right) = known(next)
340 {
341 let amount = crate::animation::interpolation_amount(
343 samples.times[current],
344 samples.times[next],
345 time,
346 );
347 return Some(
348 left.iter()
349 .zip(right)
350 .map(|(from, to)| {
351 crate::animation::interpolate_f32(
352 from.unwrap_or(0.0),
353 to.unwrap_or(0.0),
354 amount,
355 )
356 })
357 .collect(),
358 );
359 }
360 return Some(collect(left));
361 }
362 (0..current)
364 .rev()
365 .find_map(known)
366 .or_else(|| (next..samples.times.len()).find_map(known))
367 .map(collect)
368}
369
370fn anchor_time(
372 scope: &Scope<'_>,
373 set: &DataSet,
374 binding: &DataBinding,
375 time: MediaTime,
376) -> Option<MediaTime> {
377 match (&set.anchor, &binding.via) {
378 (DataAnchor::Timeline, _) => Some(time),
379 (DataAnchor::Source { .. }, Some(DataVia::Clip(clip))) => {
380 let clip = scope.index.clip(scope.project, clip)?;
381 crate::picture_source_time(
382 clip.timeline_range,
383 clip.source_range,
384 &clip.time_map,
385 scope.project.settings.frame_rate,
386 time,
387 )
388 }
389 (DataAnchor::Source { .. }, Some(DataVia::Node(node))) => {
390 let start = scope.nodes?.media_start(node)?;
391 Some(MediaTime(start.ticks().saturating_add(time.ticks())))
392 }
393 (DataAnchor::Source { .. }, None) => None,
394 }
395}
396
397#[must_use]
399pub fn bound_kind(binding: &DataBinding, context: &SampleContext<'_>) -> Option<DataKind> {
400 let scope = context.scope?;
401 scope
402 .index
403 .set(scope.project, &binding.data)
404 .map(|(set, _)| set.kind())
405}
406
407#[must_use]
409pub fn bound_scalar(
410 binding: &DataBinding,
411 time: MediaTime,
412 context: &SampleContext<'_>,
413) -> Option<f32> {
414 let scope = context.scope?;
415 let (set, _) = scope.index.set(scope.project, &binding.data)?;
416 let DataValues::Scalars(samples) = &set.values else {
417 return None;
418 };
419 let at = anchor_time(&scope, set, binding, time)?;
420 let value = *sample_channel(samples, samples.channel(&binding.channel)?, 1, at)?.first()?;
421 Some(binding.remap.map_or(value, |remap| remap.apply(value)))
422}
423
424#[must_use]
427pub fn bound_vec2(
428 binding: &DataBinding,
429 time: MediaTime,
430 context: &SampleContext<'_>,
431) -> Option<Vec2> {
432 let scope = context.scope?;
433 let (set, index) = scope.index.set(scope.project, &binding.data)?;
434 match &set.values {
435 DataValues::Scalars(_) => {
436 bound_scalar(binding, time, context).map(|value| Vec2::new(value, value))
437 }
438 DataValues::Points(samples) => {
439 let at = anchor_time(&scope, set, binding, time)?;
440 let values = sample_channel(samples, samples.channel(&binding.channel)?, 2, at)?;
441 let point = Vec2::new(values[0], values[1]);
442 let placed = match (&set.anchor, binding.space) {
443 (DataAnchor::Timeline, _) | (_, None) => point,
444 (DataAnchor::Source { .. }, Some(space)) => {
445 let aspect = context.canvas_aspect();
446 let picture = scope.index.picture_sizes[index]
447 .map_or(Vec2::new(1.0, 1.0), |size| contained_picture(size, aspect));
448 let layer = picture_to_layer(point, picture);
449 match (space, &binding.via) {
450 (DataSpace::Canvas, Some(DataVia::Clip(clip))) => {
451 let clip = scope.index.clip(scope.project, clip)?;
452 layer_to_canvas(clip, layer, time, context)
453 }
454 _ => layer,
455 }
456 }
457 };
458 let [x, y] = binding.offset.unwrap_or_default();
459 Some(Vec2::new(placed.x + x, placed.y + y))
460 }
461 DataValues::Similarity(_) | DataValues::Words(_) | DataValues::Intervals(_) => None,
462 }
463}
464
465fn layer_to_canvas(clip: &Clip, layer: Vec2, time: MediaTime, context: &SampleContext<'_>) -> Vec2 {
468 let aspect = context.canvas_aspect();
469 let corrected = correction_at(clip, time, context)
470 .map_or(layer, |correction| correction.apply(layer, aspect));
471 let visual = crate::sample_visual(&clip.visual, time, aspect, context);
472 let (sin, cos) = libm::sincos(f64::from(visual.rotation_degrees).to_radians());
473 let x =
474 (f64::from(corrected.x) - f64::from(visual.anchor.x)) * f64::from(visual.scale.x) * aspect;
475 let y = (f64::from(corrected.y) - f64::from(visual.anchor.y)) * f64::from(visual.scale.y);
476 Vec2::new(
477 finite(f64::from(visual.position.x) + (cos * x - sin * y) / aspect),
478 finite(f64::from(visual.position.y) + sin * x + cos * y),
479 )
480}
481
482#[must_use]
484pub fn correction_at(
485 clip: &Clip,
486 time: MediaTime,
487 context: &SampleContext<'_>,
488) -> Option<Correction> {
489 clip_correction(
490 &clip.visual,
491 (clip.timeline_range, clip.source_range, &clip.time_map),
492 time,
493 context,
494 )
495}
496
497pub(crate) fn clip_correction(
500 visual: &alpha2_model::VisualProperties,
501 placement: (
502 alpha2_time::TimeRange,
503 alpha2_time::TimeRange,
504 &alpha2_model::TimeMap,
505 ),
506 time: MediaTime,
507 context: &SampleContext<'_>,
508) -> Option<Correction> {
509 let reference = visual.correction.as_ref()?;
510 let scope = context.scope?;
511 let (set, index) = scope.index.set(scope.project, &reference.data)?;
512 let DataValues::Similarity(samples) = &set.values else {
513 return None;
514 };
515 let (timeline_range, source_range, time_map) = placement;
516 let at = crate::picture_source_time(
517 timeline_range,
518 source_range,
519 time_map,
520 scope.project.settings.frame_rate,
521 time,
522 )?;
523 let values = sample_channel(samples, 0, DataKind::Similarity.arity().unwrap_or(4), at)?;
524 let picture = scope.index.picture_sizes[index].map_or(Vec2::new(1.0, 1.0), |size| {
525 contained_picture(size, context.canvas_aspect())
526 });
527 Some(Correction {
528 translate: Vec2::new(values[0], values[1]),
529 rotation_degrees: values[2],
530 scale: values[3],
531 picture,
532 })
533}
534
535pub(crate) fn next_data_knot(
536 binding: &DataBinding,
537 after: MediaTime,
538 context: &SampleContext<'_>,
539) -> Option<MediaTime> {
540 let change = next_data_change(binding, after, context);
541 let follows_a_bend = || {
542 let scope = context.scope?;
543 let (set, _) = scope.index.set(scope.project, &binding.data)?;
544 let linear = set.values.samples()?.interpolation == DataInterpolation::Linear;
545 let (DataAnchor::Source { .. }, Some(DataVia::Clip(clip))) = (&set.anchor, &binding.via)
546 else {
547 return None;
548 };
549 let clip = scope.index.clip(scope.project, clip)?;
550 let next = MediaTime(after.ticks().checked_add(1)?);
551 let inside = clip.timeline_range.contains(after) && clip.timeline_range.contains(next);
552 let bends = crate::TimeCurve::of(&clip.time_map)?.motion_at(after.ticks()) == Motion::Bend;
553 (linear && inside && bends).then_some(next)
554 };
555 follows_a_bend().or(change)
556}
557
558#[must_use]
565pub fn next_data_change(
566 binding: &DataBinding,
567 after: MediaTime,
568 context: &SampleContext<'_>,
569) -> Option<MediaTime> {
570 let scope = context.scope?;
571 let (set, _) = scope.index.set(scope.project, &binding.data)?;
572 let samples = set.values.samples()?;
573 let times = &samples.times;
574 match (&set.anchor, &binding.via) {
575 (DataAnchor::Timeline, _) => times
576 .get(times.partition_point(|time| *time <= after))
577 .copied(),
578 (DataAnchor::Source { .. }, Some(DataVia::Clip(clip))) => {
579 let clip = scope.index.clip(scope.project, clip)?;
580 let rate = scope.project.settings.frame_rate;
581 let (start, end) = (
582 clip.timeline_range.start().ticks(),
583 clip.timeline_range.end().ticks(),
584 );
585 if after.ticks() >= end {
586 return None;
587 }
588 if after.ticks() < start {
589 return Some(clip.timeline_range.start());
590 }
591 let shown = |tick: i64| {
592 crate::picture_source_time(
593 clip.timeline_range,
594 clip.source_range,
595 &clip.time_map,
596 rate,
597 MediaTime(tick),
598 )
599 .map_or(i64::MIN, MediaTime::ticks)
600 };
601 let index_at = |tick: i64| times.partition_point(|time| time.ticks() <= shown(tick));
602 let held = samples.interpolation == DataInterpolation::Hold;
603 let on_stairs = !held
604 && crate::TimeCurve::of(&clip.time_map)
605 .is_some_and(|curve| curve.motion_at(after.ticks()) == Motion::Stairs);
606 let (current, now) = (index_at(after.ticks()), shown(after.ticks()));
607 let changed = |tick: i64| {
608 if on_stairs {
609 shown(tick) != now
610 } else {
611 index_at(tick) != current
612 }
613 };
614 let cuts = scope.index.curve_cuts(clip);
615 let run_end = |tick: i64| match &clip.time_map {
616 TimeMap::Loop { .. } => clip.source_range.duration().map_or(end, |length| {
617 let passed = (tick - start) / length.ticks().max(1) + 1;
618 start.saturating_add(passed.saturating_mul(length.ticks()))
619 }),
620 TimeMap::Curve { .. } => cuts
621 .get(cuts.partition_point(|cut| *cut <= tick))
622 .copied()
623 .unwrap_or(end),
624 TimeMap::Forward | TimeMap::Reverse | TimeMap::Freeze { .. } => end,
625 };
626 let passes_run_ends = held && matches!(clip.time_map, TimeMap::Curve { .. });
627 let mut low = after.ticks() + 1;
628 loop {
629 let high = run_end(low - 1).min(end);
630 if changed(high - 1) {
631 return Some(MediaTime(crate::retime::first_reached(low, high, changed)));
632 }
633 if high >= end {
634 return None;
635 }
636 if !passes_run_ends || changed(high) {
637 return Some(MediaTime(high));
638 }
639 low = high + 1;
640 }
641 }
642 (DataAnchor::Source { .. }, _) => None,
643 }
644}