Skip to main content

alpha2_model/
timeline_values.rs

1//! Every value keyed in timeline time and every reference to a clip, for operations that cut or
2//! move timeline time.
3
4use crate::{
5    Animated, AnimatedPoint, AudioProperties, Clip, ClipId, ClipTransition, DataBinding, DataVia,
6    Project, ShapeGeometry, ShapeMask, TrackId, VisualProperties,
7};
8use alpha2_time::{MediaTime, TimeRange};
9
10/// What holds a timeline-keyed value or a clip reference; `track` indexes `timeline.tracks`.
11#[derive(Copy, Clone, Debug, PartialEq, Eq)]
12pub enum TimelineOwner<'a> {
13    /// A clip's visual, masks, audio or matte.
14    Clip {
15        /// Its track.
16        track: usize,
17        /// Its id.
18        id: &'a ClipId,
19        /// Its timeline range.
20        range: TimeRange,
21    },
22    /// A transition's clips or effect parameters.
23    Transition {
24        /// Its track.
25        track: usize,
26        /// Its position in the track's `transitions`.
27        index: usize,
28        /// Its timeline range.
29        range: TimeRange,
30    },
31    /// A track's bus.
32    Track {
33        /// Its track.
34        track: usize,
35        /// Its id.
36        id: &'a TrackId,
37    },
38    /// The master bus.
39    Master,
40}
41
42/// What a reference to a clip is.
43#[derive(Copy, Clone, Debug, PartialEq, Eq)]
44pub enum ClipReference {
45    /// A clip's `matte.source`.
46    Matte,
47    /// A transition's `from_clip`.
48    TransitionFrom,
49    /// A transition's `to_clip`.
50    TransitionTo,
51    /// A data binding's `via: { clip }`.
52    Via,
53}
54
55/// A value whose keyframes are in timeline time.
56pub trait TimelineValue {
57    /// Moves every keyframe by `delta` ticks.
58    fn shift(&mut self, delta: i64);
59    /// Keeps the keyframes that decide values inside `window` (ticks, end exclusive): those
60    /// inside it and the nearest one on each side.
61    fn keep_window(&mut self, window: (i64, i64));
62    /// The clip a data binding reads through, if any.
63    fn via_clip(&self) -> Option<&ClipId>;
64    /// [`Self::via_clip`], to point it at another clip.
65    fn via_clip_mut(&mut self) -> Option<&mut ClipId>;
66}
67
68/// The positions of the keyframes that decide values inside `window`, as `first..last`.
69fn decisive<K>(keys: &[K], time: impl Fn(&K) -> MediaTime, window: (i64, i64)) -> (usize, usize) {
70    let first = keys
71        .partition_point(|key| time(key).ticks() <= window.0)
72        .saturating_sub(1);
73    let last = (keys.partition_point(|key| time(key).ticks() < window.1) + 1).min(keys.len());
74    (first, last.max(first))
75}
76
77const fn via_of(binding: &DataBinding) -> Option<&ClipId> {
78    match &binding.via {
79        Some(DataVia::Clip(clip)) => Some(clip),
80        _ => None,
81    }
82}
83
84const fn via_of_mut(binding: &mut DataBinding) -> Option<&mut ClipId> {
85    match &mut binding.via {
86        Some(DataVia::Clip(clip)) => Some(clip),
87        _ => None,
88    }
89}
90
91impl<T> TimelineValue for Animated<T> {
92    fn shift(&mut self, delta: i64) {
93        if let Self::Keyframes { keyframes } = self {
94            for key in keyframes {
95                key.time = MediaTime(key.time.ticks() + delta);
96            }
97        }
98    }
99
100    fn keep_window(&mut self, window: (i64, i64)) {
101        if let Self::Keyframes { keyframes } = self {
102            let (first, last) = decisive(keyframes, |key| key.time, window);
103            keyframes.truncate(last);
104            keyframes.drain(..first);
105        }
106    }
107
108    fn via_clip(&self) -> Option<&ClipId> {
109        self.data().and_then(via_of)
110    }
111
112    fn via_clip_mut(&mut self) -> Option<&mut ClipId> {
113        match self {
114            Self::Data(binding) => via_of_mut(binding),
115            _ => None,
116        }
117    }
118}
119
120impl TimelineValue for AnimatedPoint {
121    fn shift(&mut self, delta: i64) {
122        if let Self::Keyframes { keyframes } = self {
123            for key in keyframes {
124                key.time = MediaTime(key.time.ticks() + delta);
125            }
126        }
127    }
128
129    fn keep_window(&mut self, window: (i64, i64)) {
130        if let Self::Keyframes { keyframes } = self {
131            let (first, last) = decisive(keyframes, |key| key.time, window);
132            keyframes.truncate(last);
133            keyframes.drain(..first);
134        }
135    }
136
137    fn via_clip(&self) -> Option<&ClipId> {
138        self.data().and_then(via_of)
139    }
140
141    fn via_clip_mut(&mut self) -> Option<&mut ClipId> {
142        match self {
143            Self::Data(binding) => via_of_mut(binding),
144            _ => None,
145        }
146    }
147}
148
149/// A visitor of timeline-clock values, given each value's place as `Type.field` (`Type[tag]`
150/// for an enum variant), the names of the model's JSON schema.
151pub type TimelineVisit<'v> = dyn FnMut(&'static str, &mut dyn TimelineValue) + 'v;
152
153fn clip_values(
154    visual: &mut VisualProperties,
155    masks: &mut [ShapeMask],
156    audio: &mut AudioProperties,
157    visit: &mut TimelineVisit<'_>,
158) {
159    visit("VisualProperties.position", &mut visual.position);
160    visit("VisualProperties.scale", &mut visual.scale);
161    visit(
162        "VisualProperties.rotation_degrees",
163        &mut visual.rotation_degrees,
164    );
165    visit("VisualProperties.opacity", &mut visual.opacity);
166    for mask in masks {
167        visit("ShapeMask.feather", &mut mask.feather);
168        geometry_values(&mut mask.shape, visit);
169    }
170    visit("AudioProperties.gain", &mut audio.gain);
171    visit("AudioProperties.pan", &mut audio.pan);
172}
173
174fn geometry_values(geometry: &mut ShapeGeometry, visit: &mut TimelineVisit<'_>) {
175    match geometry {
176        ShapeGeometry::Rectangle(shape) => {
177            visit("ShapeGeometry[rectangle].center", &mut shape.center);
178            visit("ShapeGeometry[rectangle].size", &mut shape.size);
179            visit(
180                "ShapeGeometry[rectangle].corner_radius",
181                &mut shape.corner_radius,
182            );
183            visit(
184                "ShapeGeometry[rectangle].rotation_degrees",
185                &mut shape.rotation_degrees,
186            );
187        }
188        ShapeGeometry::Ellipse(shape) => {
189            visit("ShapeGeometry[ellipse].center", &mut shape.center);
190            visit("ShapeGeometry[ellipse].size", &mut shape.size);
191            visit(
192                "ShapeGeometry[ellipse].rotation_degrees",
193                &mut shape.rotation_degrees,
194            );
195        }
196        ShapeGeometry::Polystar(shape) => {
197            visit("ShapeGeometry[polystar].center", &mut shape.center);
198            visit("ShapeGeometry[polystar].points", &mut shape.points);
199            visit(
200                "ShapeGeometry[polystar].outer_radius",
201                &mut shape.outer_radius,
202            );
203            visit(
204                "ShapeGeometry[polystar].inner_radius",
205                &mut shape.inner_radius,
206            );
207            visit(
208                "ShapeGeometry[polystar].outer_roundness",
209                &mut shape.outer_roundness,
210            );
211            visit(
212                "ShapeGeometry[polystar].inner_roundness",
213                &mut shape.inner_roundness,
214            );
215            visit(
216                "ShapeGeometry[polystar].rotation_degrees",
217                &mut shape.rotation_degrees,
218            );
219        }
220        ShapeGeometry::Path(shape) => visit("ShapeGeometry[path].path", &mut shape.path),
221    }
222}
223
224impl Clip {
225    /// Calls `visit` with each of the clip's values keyed in timeline time.
226    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
227        clip_values(&mut self.visual, &mut self.masks, &mut self.audio, visit);
228    }
229}
230
231impl ClipTransition {
232    /// Calls `visit` with each of the transition's values keyed in timeline time.
233    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
234        for value in self.effect.params.values_mut() {
235            visit("ClipEffect.params", value);
236        }
237    }
238}
239
240impl Project {
241    /// Calls `visit` with every value keyed in timeline time and its owner: the clip values and
242    /// transition parameters of each track in order, then [`Self::for_each_bus_value_mut`].
243    pub fn for_each_timeline_value_mut(
244        &mut self,
245        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut dyn TimelineValue),
246    ) {
247        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
248            for clip in &mut track.clips {
249                let owner = TimelineOwner::Clip {
250                    track: position,
251                    id: &clip.id,
252                    range: clip.timeline_range,
253                };
254                clip_values(
255                    &mut clip.visual,
256                    &mut clip.masks,
257                    &mut clip.audio,
258                    &mut |at, value| visit(owner, at, value),
259                );
260            }
261            for (index, transition) in track.transitions.iter_mut().enumerate() {
262                let owner = TimelineOwner::Transition {
263                    track: position,
264                    index,
265                    range: transition.timeline_range,
266                };
267                transition.for_each_timeline_value_mut(&mut |at, value| visit(owner, at, value));
268            }
269        }
270        self.for_each_bus_value_mut(&mut |owner, at, value| visit(owner, at, value));
271    }
272
273    /// Calls `visit` with each bus value keyed in timeline time: the gain and pan of each track
274    /// in order, then the master gain.
275    pub fn for_each_bus_value_mut(
276        &mut self,
277        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut Animated<f32>),
278    ) {
279        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
280            let owner = TimelineOwner::Track {
281                track: position,
282                id: &track.id,
283            };
284            visit(owner, "TrackAudio.gain", &mut track.audio.gain);
285            visit(owner, "TrackAudio.pan", &mut track.audio.pan);
286        }
287        visit(
288            TimelineOwner::Master,
289            "MasterAudio.gain",
290            &mut self.audio.gain,
291        );
292    }
293
294    /// Calls `visit` with every reference from one part of the timeline to a clip: mattes,
295    /// transition clips and `via: { clip }` bindings, in the order of
296    /// [`Self::for_each_timeline_value_mut`].
297    pub fn for_each_clip_reference_mut(
298        &mut self,
299        visit: &mut dyn FnMut(TimelineOwner<'_>, ClipReference, &mut ClipId),
300    ) {
301        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
302            for clip in &mut track.clips {
303                let owner = TimelineOwner::Clip {
304                    track: position,
305                    id: &clip.id,
306                    range: clip.timeline_range,
307                };
308                if let Some(matte) = &mut clip.matte {
309                    visit(owner, ClipReference::Matte, &mut matte.source);
310                }
311                clip_values(
312                    &mut clip.visual,
313                    &mut clip.masks,
314                    &mut clip.audio,
315                    &mut |_, value| {
316                        if let Some(via) = value.via_clip_mut() {
317                            visit(owner, ClipReference::Via, via);
318                        }
319                    },
320                );
321            }
322            for (index, transition) in track.transitions.iter_mut().enumerate() {
323                let owner = TimelineOwner::Transition {
324                    track: position,
325                    index,
326                    range: transition.timeline_range,
327                };
328                visit(
329                    owner,
330                    ClipReference::TransitionFrom,
331                    &mut transition.from_clip,
332                );
333                visit(owner, ClipReference::TransitionTo, &mut transition.to_clip);
334                transition.for_each_timeline_value_mut(&mut |_, value| {
335                    if let Some(via) = value.via_clip_mut() {
336                        visit(owner, ClipReference::Via, via);
337                    }
338                });
339            }
340        }
341        self.for_each_bus_value_mut(&mut |owner, _, value| {
342            if let Some(via) = value.via_clip_mut() {
343                visit(owner, ClipReference::Via, via);
344            }
345        });
346    }
347}