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, AudioEffect, AudioProperties, BusId, Clip, ClipId, ClipTransition,
6    DataBinding, DataVia, Extrapolation, Project, ShapeGeometry, ShapeMask, TimeMap, TrackId,
7    VisualProperties,
8};
9use alpha2_time::{MediaTime, TimeRange};
10
11/// What holds a timeline-keyed value or a clip reference; `track` indexes `timeline.tracks`.
12#[derive(Copy, Clone, Debug, PartialEq, Eq)]
13pub enum TimelineOwner<'a> {
14    /// A clip's visual, masks, audio or matte.
15    Clip {
16        /// Its track.
17        track: usize,
18        /// Its id.
19        id: &'a ClipId,
20        /// Its timeline range.
21        range: TimeRange,
22    },
23    /// A transition's clips or effect parameters.
24    Transition {
25        /// Its track.
26        track: usize,
27        /// Its position in the track's `transitions`.
28        index: usize,
29        /// Its timeline range.
30        range: TimeRange,
31    },
32    /// A track's bus.
33    Track {
34        /// Its track.
35        track: usize,
36        /// Its id.
37        id: &'a TrackId,
38    },
39    /// The master bus.
40    Master,
41    /// A bus.
42    Bus {
43        /// Its position in `audio.buses`.
44        bus: usize,
45        /// Its id.
46        id: &'a BusId,
47    },
48}
49
50/// What a reference to a clip is.
51#[derive(Copy, Clone, Debug, PartialEq, Eq)]
52pub enum ClipReference {
53    /// A clip's `matte.source`.
54    Matte,
55    /// A transition's `from_clip`.
56    TransitionFrom,
57    /// A transition's `to_clip`.
58    TransitionTo,
59    /// A data binding's `via: { clip }`.
60    Via,
61}
62
63/// A value whose keyframes are in timeline time.
64pub trait TimelineValue {
65    /// Moves every keyframe by `delta` ticks.
66    fn shift(&mut self, delta: i64);
67    /// Keeps the keyframes that decide values inside `window` (ticks, end exclusive): those
68    /// inside it and the nearest one on each side, or all of them when the window reaches past
69    /// an end the value does not hold at.
70    fn keep_window(&mut self, window: (i64, i64));
71    /// Calls `visit` with each clip a data binding of the value reads through: the value's own
72    /// binding, or those of its `split` channels.
73    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId));
74    /// [`Self::via_clips`], to point them at other clips.
75    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId));
76}
77
78/// The positions of the keyframes that decide values inside `window`, as `first..last`.
79fn decisive<K>(keys: &[K], time: impl Fn(&K) -> MediaTime, window: (i64, i64)) -> (usize, usize) {
80    let first = keys
81        .partition_point(|key| time(key).ticks() <= window.0)
82        .saturating_sub(1);
83    let last = (keys.partition_point(|key| time(key).ticks() < window.1) + 1).min(keys.len());
84    (first, last.max(first))
85}
86
87fn reaches_past_its_keys<K>(
88    keys: &[K],
89    time: impl Fn(&K) -> MediaTime,
90    window: (i64, i64),
91    before: Extrapolation,
92    after: Extrapolation,
93) -> bool {
94    let (Some(first), Some(last)) = (keys.first(), keys.last()) else {
95        return false;
96    };
97    (!before.is_hold() && window.0 < time(first).ticks())
98        || (!after.is_hold() && window.1 > time(last).ticks())
99}
100
101const fn via_of(binding: &DataBinding) -> Option<&ClipId> {
102    match &binding.via {
103        Some(DataVia::Clip(clip)) => Some(clip),
104        _ => None,
105    }
106}
107
108const fn via_of_mut(binding: &mut DataBinding) -> Option<&mut ClipId> {
109    match &mut binding.via {
110        Some(DataVia::Clip(clip)) => Some(clip),
111        _ => None,
112    }
113}
114
115impl<T> TimelineValue for Animated<T> {
116    fn shift(&mut self, delta: i64) {
117        match self {
118            Self::Keyframes { keyframes, .. } => {
119                for key in keyframes {
120                    key.time = MediaTime(key.time.ticks() + delta);
121                }
122            }
123            Self::Split { channels } => shift_channels(channels, delta),
124            Self::Constant { .. } | Self::Data(_) => {}
125        }
126    }
127
128    fn keep_window(&mut self, window: (i64, i64)) {
129        match self {
130            Self::Keyframes {
131                keyframes,
132                before,
133                after,
134            } => {
135                if !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after) {
136                    let (first, last) = decisive(keyframes, |key| key.time, window);
137                    keyframes.truncate(last);
138                    keyframes.drain(..first);
139                }
140            }
141            Self::Split { channels } => keep_channel_windows(channels, window),
142            Self::Constant { .. } | Self::Data(_) => {}
143        }
144    }
145
146    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId)) {
147        match self {
148            Self::Data(binding) => via_of(binding).into_iter().for_each(visit),
149            Self::Split { channels } => via_channels(channels, visit),
150            Self::Constant { .. } | Self::Keyframes { .. } => {}
151        }
152    }
153
154    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId)) {
155        match self {
156            Self::Data(binding) => via_of_mut(binding).into_iter().for_each(visit),
157            Self::Split { channels } => via_channels_mut(channels, visit),
158            Self::Constant { .. } | Self::Keyframes { .. } => {}
159        }
160    }
161}
162
163fn shift_channels(channels: &mut [Animated<f32>], delta: i64) {
164    for channel in channels {
165        channel.shift(delta);
166    }
167}
168
169fn keep_channel_windows(channels: &mut [Animated<f32>], window: (i64, i64)) {
170    for channel in channels {
171        channel.keep_window(window);
172    }
173}
174
175fn via_channels(channels: &[Animated<f32>], visit: &mut dyn FnMut(&ClipId)) {
176    for channel in channels {
177        channel.via_clips(visit);
178    }
179}
180
181fn via_channels_mut(channels: &mut [Animated<f32>], visit: &mut dyn FnMut(&mut ClipId)) {
182    for channel in channels {
183        channel.via_clips_mut(visit);
184    }
185}
186
187impl TimelineValue for AnimatedPoint {
188    fn shift(&mut self, delta: i64) {
189        match self {
190            Self::Keyframes { keyframes, .. } => {
191                for key in keyframes {
192                    key.time = MediaTime(key.time.ticks() + delta);
193                }
194            }
195            Self::Split { channels } => shift_channels(channels, delta),
196            Self::Path(motion) => motion.distance.shift(delta),
197            Self::Constant { .. } | Self::Data(_) => {}
198        }
199    }
200
201    fn keep_window(&mut self, window: (i64, i64)) {
202        match self {
203            Self::Keyframes {
204                keyframes,
205                before,
206                after,
207            } => {
208                if !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after) {
209                    let (first, last) = decisive(keyframes, |key| key.time, window);
210                    keyframes.truncate(last);
211                    keyframes.drain(..first);
212                }
213            }
214            Self::Split { channels } => keep_channel_windows(channels, window),
215            Self::Path(motion) => motion.distance.keep_window(window),
216            Self::Constant { .. } | Self::Data(_) => {}
217        }
218    }
219
220    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId)) {
221        match self {
222            Self::Data(binding) => via_of(binding).into_iter().for_each(visit),
223            Self::Split { channels } => via_channels(channels, visit),
224            Self::Path(motion) => motion.distance.via_clips(visit),
225            Self::Constant { .. } | Self::Keyframes { .. } => {}
226        }
227    }
228
229    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId)) {
230        match self {
231            Self::Data(binding) => via_of_mut(binding).into_iter().for_each(visit),
232            Self::Split { channels } => via_channels_mut(channels, visit),
233            Self::Path(motion) => motion.distance.via_clips_mut(visit),
234            Self::Constant { .. } | Self::Keyframes { .. } => {}
235        }
236    }
237}
238
239impl TimelineValue for TimeMap {
240    fn shift(&mut self, delta: i64) {
241        if let Self::Curve { keyframes, .. } = self {
242            for key in keyframes {
243                key.time = MediaTime(key.time.ticks() + delta);
244            }
245        }
246    }
247
248    fn keep_window(&mut self, window: (i64, i64)) {
249        if let Self::Curve {
250            keyframes,
251            before,
252            after,
253        } = self
254            && !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after)
255        {
256            let (first, last) = decisive(keyframes, |key| key.time, window);
257            let last = last.max(first + 2).min(keyframes.len());
258            keyframes.truncate(last);
259            keyframes.drain(..first.min(last.saturating_sub(2)));
260        }
261    }
262
263    fn via_clips(&self, _: &mut dyn FnMut(&ClipId)) {}
264
265    fn via_clips_mut(&mut self, _: &mut dyn FnMut(&mut ClipId)) {}
266}
267
268/// A visitor of timeline-clock values, given each value's place as `Type.field` (`Type[tag]`
269/// for an enum variant), the names of the model's JSON schema.
270pub type TimelineVisit<'v> = dyn FnMut(&'static str, &mut dyn TimelineValue) + 'v;
271
272fn clip_values(
273    visual: &mut VisualProperties,
274    masks: &mut [ShapeMask],
275    audio: &mut AudioProperties,
276    time_map: &mut TimeMap,
277    visit: &mut TimelineVisit<'_>,
278) {
279    visit("VisualProperties.position", &mut visual.position);
280    visit("VisualProperties.scale", &mut visual.scale);
281    visit(
282        "VisualProperties.rotation_degrees",
283        &mut visual.rotation_degrees,
284    );
285    visit("VisualProperties.opacity", &mut visual.opacity);
286    for mask in masks {
287        visit("ShapeMask.feather", &mut mask.feather);
288        geometry_values(&mut mask.shape, visit);
289    }
290    visit("AudioProperties.gain", &mut audio.gain);
291    visit("AudioProperties.pan", &mut audio.pan);
292    effect_values(&mut audio.effects, &mut |at, value| visit(at, value));
293    visit("Clip.time_map", time_map);
294}
295
296fn effect_values(
297    effects: &mut [AudioEffect],
298    visit: &mut dyn FnMut(&'static str, &mut Animated<f32>),
299) {
300    for effect in effects {
301        effect.for_each_param_mut(&mut |param| visit(param.place, param.value));
302    }
303}
304
305fn geometry_values(geometry: &mut ShapeGeometry, visit: &mut TimelineVisit<'_>) {
306    match geometry {
307        ShapeGeometry::Rectangle(shape) => {
308            visit("ShapeGeometry[rectangle].center", &mut shape.center);
309            visit("ShapeGeometry[rectangle].size", &mut shape.size);
310            visit(
311                "ShapeGeometry[rectangle].corner_radius",
312                &mut shape.corner_radius,
313            );
314            visit(
315                "ShapeGeometry[rectangle].rotation_degrees",
316                &mut shape.rotation_degrees,
317            );
318        }
319        ShapeGeometry::Ellipse(shape) => {
320            visit("ShapeGeometry[ellipse].center", &mut shape.center);
321            visit("ShapeGeometry[ellipse].size", &mut shape.size);
322            visit(
323                "ShapeGeometry[ellipse].rotation_degrees",
324                &mut shape.rotation_degrees,
325            );
326        }
327        ShapeGeometry::Polystar(shape) => {
328            visit("ShapeGeometry[polystar].center", &mut shape.center);
329            visit("ShapeGeometry[polystar].points", &mut shape.points);
330            visit(
331                "ShapeGeometry[polystar].outer_radius",
332                &mut shape.outer_radius,
333            );
334            visit(
335                "ShapeGeometry[polystar].inner_radius",
336                &mut shape.inner_radius,
337            );
338            visit(
339                "ShapeGeometry[polystar].outer_roundness",
340                &mut shape.outer_roundness,
341            );
342            visit(
343                "ShapeGeometry[polystar].inner_roundness",
344                &mut shape.inner_roundness,
345            );
346            visit(
347                "ShapeGeometry[polystar].rotation_degrees",
348                &mut shape.rotation_degrees,
349            );
350        }
351        ShapeGeometry::Path(shape) => visit("ShapeGeometry[path].path", &mut shape.path),
352    }
353}
354
355impl Clip {
356    /// Calls `visit` with each of the clip's values keyed in timeline time.
357    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
358        clip_values(
359            &mut self.visual,
360            &mut self.masks,
361            &mut self.audio,
362            &mut self.time_map,
363            visit,
364        );
365    }
366}
367
368impl ClipTransition {
369    /// Calls `visit` with each of the transition's values keyed in timeline time.
370    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
371        for value in self.effect.params.values_mut() {
372            visit("ClipEffect.params", value);
373        }
374    }
375}
376
377impl Project {
378    /// Calls `visit` with every value keyed in timeline time and its owner: the clip values and
379    /// transition parameters of each track in order, then [`Self::for_each_bus_value_mut`].
380    pub fn for_each_timeline_value_mut(
381        &mut self,
382        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut dyn TimelineValue),
383    ) {
384        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
385            for clip in &mut track.clips {
386                let owner = TimelineOwner::Clip {
387                    track: position,
388                    id: &clip.id,
389                    range: clip.timeline_range,
390                };
391                clip_values(
392                    &mut clip.visual,
393                    &mut clip.masks,
394                    &mut clip.audio,
395                    &mut clip.time_map,
396                    &mut |at, value| visit(owner, at, value),
397                );
398            }
399            for (index, transition) in track.transitions.iter_mut().enumerate() {
400                let owner = TimelineOwner::Transition {
401                    track: position,
402                    index,
403                    range: transition.timeline_range,
404                };
405                transition.for_each_timeline_value_mut(&mut |at, value| visit(owner, at, value));
406            }
407        }
408        self.for_each_bus_value_mut(&mut |owner, at, value| visit(owner, at, value));
409    }
410
411    /// Calls `visit` with each bus value keyed in timeline time: the gain, pan, send gains and
412    /// effect parameters of each track in order, then the master gain and effect parameters,
413    /// then the same of each bus in order.
414    pub fn for_each_bus_value_mut(
415        &mut self,
416        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut Animated<f32>),
417    ) {
418        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
419            let owner = TimelineOwner::Track {
420                track: position,
421                id: &track.id,
422            };
423            visit(owner, "TrackAudio.gain", &mut track.audio.gain);
424            visit(owner, "TrackAudio.pan", &mut track.audio.pan);
425            for send in &mut track.audio.sends {
426                visit(owner, "AudioSend.gain", &mut send.gain);
427            }
428            effect_values(&mut track.audio.effects, &mut |at, value| {
429                visit(owner, at, value);
430            });
431        }
432        visit(
433            TimelineOwner::Master,
434            "MasterAudio.gain",
435            &mut self.audio.gain,
436        );
437        effect_values(&mut self.audio.effects, &mut |at, value| {
438            visit(TimelineOwner::Master, at, value);
439        });
440        for (position, bus) in self.audio.buses.iter_mut().enumerate() {
441            let owner = TimelineOwner::Bus {
442                bus: position,
443                id: &bus.id,
444            };
445            visit(owner, "AudioBus.gain", &mut bus.gain);
446            visit(owner, "AudioBus.pan", &mut bus.pan);
447            for send in &mut bus.sends {
448                visit(owner, "AudioSend.gain", &mut send.gain);
449            }
450            effect_values(&mut bus.effects, &mut |at, value| visit(owner, at, value));
451        }
452    }
453
454    /// Calls `visit` with every reference from one part of the timeline to a clip: mattes,
455    /// transition clips and `via: { clip }` bindings, in the order of
456    /// [`Self::for_each_timeline_value_mut`].
457    pub fn for_each_clip_reference_mut(
458        &mut self,
459        visit: &mut dyn FnMut(TimelineOwner<'_>, ClipReference, &mut ClipId),
460    ) {
461        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
462            for clip in &mut track.clips {
463                let owner = TimelineOwner::Clip {
464                    track: position,
465                    id: &clip.id,
466                    range: clip.timeline_range,
467                };
468                if let Some(matte) = &mut clip.matte {
469                    visit(owner, ClipReference::Matte, &mut matte.source);
470                }
471                clip_values(
472                    &mut clip.visual,
473                    &mut clip.masks,
474                    &mut clip.audio,
475                    &mut clip.time_map,
476                    &mut |_, value| {
477                        value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
478                    },
479                );
480            }
481            for (index, transition) in track.transitions.iter_mut().enumerate() {
482                let owner = TimelineOwner::Transition {
483                    track: position,
484                    index,
485                    range: transition.timeline_range,
486                };
487                visit(
488                    owner,
489                    ClipReference::TransitionFrom,
490                    &mut transition.from_clip,
491                );
492                visit(owner, ClipReference::TransitionTo, &mut transition.to_clip);
493                transition.for_each_timeline_value_mut(&mut |_, value| {
494                    value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
495                });
496            }
497        }
498        self.for_each_bus_value_mut(&mut |owner, _, value| {
499            value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
500        });
501    }
502}