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
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Every value keyed in timeline time and every reference to a clip, for operations that cut or
//! move timeline time.

use crate::{
    Animated, AnimatedPoint, AudioEffect, AudioProperties, BusId, Clip, ClipId, ClipTransition,
    DataBinding, DataVia, Extrapolation, Project, ShapeGeometry, ShapeMask, TimeMap, TrackId,
    VisualProperties,
};
use alpha2_time::{MediaTime, TimeRange};

/// What holds a timeline-keyed value or a clip reference; `track` indexes `timeline.tracks`.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum TimelineOwner<'a> {
    /// A clip's visual, masks, audio or matte.
    Clip {
        /// Its track.
        track: usize,
        /// Its id.
        id: &'a ClipId,
        /// Its timeline range.
        range: TimeRange,
    },
    /// A transition's clips or effect parameters.
    Transition {
        /// Its track.
        track: usize,
        /// Its position in the track's `transitions`.
        index: usize,
        /// Its timeline range.
        range: TimeRange,
    },
    /// A track's bus.
    Track {
        /// Its track.
        track: usize,
        /// Its id.
        id: &'a TrackId,
    },
    /// The master bus.
    Master,
    /// A bus.
    Bus {
        /// Its position in `audio.buses`.
        bus: usize,
        /// Its id.
        id: &'a BusId,
    },
}

/// What a reference to a clip is.
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum ClipReference {
    /// A clip's `matte.source`.
    Matte,
    /// A transition's `from_clip`.
    TransitionFrom,
    /// A transition's `to_clip`.
    TransitionTo,
    /// A data binding's `via: { clip }`.
    Via,
}

/// A value whose keyframes are in timeline time.
pub trait TimelineValue {
    /// Moves every keyframe by `delta` ticks.
    fn shift(&mut self, delta: i64);
    /// Keeps the keyframes that decide values inside `window` (ticks, end exclusive): those
    /// inside it and the nearest one on each side, or all of them when the window reaches past
    /// an end the value does not hold at.
    fn keep_window(&mut self, window: (i64, i64));
    /// Calls `visit` with each clip a data binding of the value reads through: the value's own
    /// binding, or those of its `split` channels.
    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId));
    /// [`Self::via_clips`], to point them at other clips.
    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId));
}

/// The positions of the keyframes that decide values inside `window`, as `first..last`.
fn decisive<K>(keys: &[K], time: impl Fn(&K) -> MediaTime, window: (i64, i64)) -> (usize, usize) {
    let first = keys
        .partition_point(|key| time(key).ticks() <= window.0)
        .saturating_sub(1);
    let last = (keys.partition_point(|key| time(key).ticks() < window.1) + 1).min(keys.len());
    (first, last.max(first))
}

fn reaches_past_its_keys<K>(
    keys: &[K],
    time: impl Fn(&K) -> MediaTime,
    window: (i64, i64),
    before: Extrapolation,
    after: Extrapolation,
) -> bool {
    let (Some(first), Some(last)) = (keys.first(), keys.last()) else {
        return false;
    };
    (!before.is_hold() && window.0 < time(first).ticks())
        || (!after.is_hold() && window.1 > time(last).ticks())
}

const fn via_of(binding: &DataBinding) -> Option<&ClipId> {
    match &binding.via {
        Some(DataVia::Clip(clip)) => Some(clip),
        _ => None,
    }
}

const fn via_of_mut(binding: &mut DataBinding) -> Option<&mut ClipId> {
    match &mut binding.via {
        Some(DataVia::Clip(clip)) => Some(clip),
        _ => None,
    }
}

impl<T> TimelineValue for Animated<T> {
    fn shift(&mut self, delta: i64) {
        match self {
            Self::Keyframes { keyframes, .. } => {
                for key in keyframes {
                    key.time = MediaTime(key.time.ticks() + delta);
                }
            }
            Self::Split { channels } => shift_channels(channels, delta),
            Self::Constant { .. } | Self::Data(_) => {}
        }
    }

    fn keep_window(&mut self, window: (i64, i64)) {
        match self {
            Self::Keyframes {
                keyframes,
                before,
                after,
            } => {
                if !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after) {
                    let (first, last) = decisive(keyframes, |key| key.time, window);
                    keyframes.truncate(last);
                    keyframes.drain(..first);
                }
            }
            Self::Split { channels } => keep_channel_windows(channels, window),
            Self::Constant { .. } | Self::Data(_) => {}
        }
    }

    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId)) {
        match self {
            Self::Data(binding) => via_of(binding).into_iter().for_each(visit),
            Self::Split { channels } => via_channels(channels, visit),
            Self::Constant { .. } | Self::Keyframes { .. } => {}
        }
    }

    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId)) {
        match self {
            Self::Data(binding) => via_of_mut(binding).into_iter().for_each(visit),
            Self::Split { channels } => via_channels_mut(channels, visit),
            Self::Constant { .. } | Self::Keyframes { .. } => {}
        }
    }
}

fn shift_channels(channels: &mut [Animated<f32>], delta: i64) {
    for channel in channels {
        channel.shift(delta);
    }
}

fn keep_channel_windows(channels: &mut [Animated<f32>], window: (i64, i64)) {
    for channel in channels {
        channel.keep_window(window);
    }
}

fn via_channels(channels: &[Animated<f32>], visit: &mut dyn FnMut(&ClipId)) {
    for channel in channels {
        channel.via_clips(visit);
    }
}

fn via_channels_mut(channels: &mut [Animated<f32>], visit: &mut dyn FnMut(&mut ClipId)) {
    for channel in channels {
        channel.via_clips_mut(visit);
    }
}

impl TimelineValue for AnimatedPoint {
    fn shift(&mut self, delta: i64) {
        match self {
            Self::Keyframes { keyframes, .. } => {
                for key in keyframes {
                    key.time = MediaTime(key.time.ticks() + delta);
                }
            }
            Self::Split { channels } => shift_channels(channels, delta),
            Self::Path(motion) => motion.distance.shift(delta),
            Self::Constant { .. } | Self::Data(_) => {}
        }
    }

    fn keep_window(&mut self, window: (i64, i64)) {
        match self {
            Self::Keyframes {
                keyframes,
                before,
                after,
            } => {
                if !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after) {
                    let (first, last) = decisive(keyframes, |key| key.time, window);
                    keyframes.truncate(last);
                    keyframes.drain(..first);
                }
            }
            Self::Split { channels } => keep_channel_windows(channels, window),
            Self::Path(motion) => motion.distance.keep_window(window),
            Self::Constant { .. } | Self::Data(_) => {}
        }
    }

    fn via_clips(&self, visit: &mut dyn FnMut(&ClipId)) {
        match self {
            Self::Data(binding) => via_of(binding).into_iter().for_each(visit),
            Self::Split { channels } => via_channels(channels, visit),
            Self::Path(motion) => motion.distance.via_clips(visit),
            Self::Constant { .. } | Self::Keyframes { .. } => {}
        }
    }

    fn via_clips_mut(&mut self, visit: &mut dyn FnMut(&mut ClipId)) {
        match self {
            Self::Data(binding) => via_of_mut(binding).into_iter().for_each(visit),
            Self::Split { channels } => via_channels_mut(channels, visit),
            Self::Path(motion) => motion.distance.via_clips_mut(visit),
            Self::Constant { .. } | Self::Keyframes { .. } => {}
        }
    }
}

impl TimelineValue for TimeMap {
    fn shift(&mut self, delta: i64) {
        if let Self::Curve { keyframes, .. } = self {
            for key in keyframes {
                key.time = MediaTime(key.time.ticks() + delta);
            }
        }
    }

    fn keep_window(&mut self, window: (i64, i64)) {
        if let Self::Curve {
            keyframes,
            before,
            after,
        } = self
            && !reaches_past_its_keys(keyframes, |key| key.time, window, *before, *after)
        {
            let (first, last) = decisive(keyframes, |key| key.time, window);
            let last = last.max(first + 2).min(keyframes.len());
            keyframes.truncate(last);
            keyframes.drain(..first.min(last.saturating_sub(2)));
        }
    }

    fn via_clips(&self, _: &mut dyn FnMut(&ClipId)) {}

    fn via_clips_mut(&mut self, _: &mut dyn FnMut(&mut ClipId)) {}
}

/// A visitor of timeline-clock values, given each value's place as `Type.field` (`Type[tag]`
/// for an enum variant), the names of the model's JSON schema.
pub type TimelineVisit<'v> = dyn FnMut(&'static str, &mut dyn TimelineValue) + 'v;

fn clip_values(
    visual: &mut VisualProperties,
    masks: &mut [ShapeMask],
    audio: &mut AudioProperties,
    time_map: &mut TimeMap,
    visit: &mut TimelineVisit<'_>,
) {
    visit("VisualProperties.position", &mut visual.position);
    visit("VisualProperties.scale", &mut visual.scale);
    visit(
        "VisualProperties.rotation_degrees",
        &mut visual.rotation_degrees,
    );
    visit("VisualProperties.opacity", &mut visual.opacity);
    for mask in masks {
        visit("ShapeMask.feather", &mut mask.feather);
        geometry_values(&mut mask.shape, visit);
    }
    visit("AudioProperties.gain", &mut audio.gain);
    visit("AudioProperties.pan", &mut audio.pan);
    effect_values(&mut audio.effects, &mut |at, value| visit(at, value));
    visit("Clip.time_map", time_map);
}

fn effect_values(
    effects: &mut [AudioEffect],
    visit: &mut dyn FnMut(&'static str, &mut Animated<f32>),
) {
    for effect in effects {
        effect.for_each_param_mut(&mut |param| visit(param.place, param.value));
    }
}

fn geometry_values(geometry: &mut ShapeGeometry, visit: &mut TimelineVisit<'_>) {
    match geometry {
        ShapeGeometry::Rectangle(shape) => {
            visit("ShapeGeometry[rectangle].center", &mut shape.center);
            visit("ShapeGeometry[rectangle].size", &mut shape.size);
            visit(
                "ShapeGeometry[rectangle].corner_radius",
                &mut shape.corner_radius,
            );
            visit(
                "ShapeGeometry[rectangle].rotation_degrees",
                &mut shape.rotation_degrees,
            );
        }
        ShapeGeometry::Ellipse(shape) => {
            visit("ShapeGeometry[ellipse].center", &mut shape.center);
            visit("ShapeGeometry[ellipse].size", &mut shape.size);
            visit(
                "ShapeGeometry[ellipse].rotation_degrees",
                &mut shape.rotation_degrees,
            );
        }
        ShapeGeometry::Polystar(shape) => {
            visit("ShapeGeometry[polystar].center", &mut shape.center);
            visit("ShapeGeometry[polystar].points", &mut shape.points);
            visit(
                "ShapeGeometry[polystar].outer_radius",
                &mut shape.outer_radius,
            );
            visit(
                "ShapeGeometry[polystar].inner_radius",
                &mut shape.inner_radius,
            );
            visit(
                "ShapeGeometry[polystar].outer_roundness",
                &mut shape.outer_roundness,
            );
            visit(
                "ShapeGeometry[polystar].inner_roundness",
                &mut shape.inner_roundness,
            );
            visit(
                "ShapeGeometry[polystar].rotation_degrees",
                &mut shape.rotation_degrees,
            );
        }
        ShapeGeometry::Path(shape) => visit("ShapeGeometry[path].path", &mut shape.path),
    }
}

impl Clip {
    /// Calls `visit` with each of the clip's values keyed in timeline time.
    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
        clip_values(
            &mut self.visual,
            &mut self.masks,
            &mut self.audio,
            &mut self.time_map,
            visit,
        );
    }
}

impl ClipTransition {
    /// Calls `visit` with each of the transition's values keyed in timeline time.
    pub fn for_each_timeline_value_mut(&mut self, visit: &mut TimelineVisit<'_>) {
        for value in self.effect.params.values_mut() {
            visit("ClipEffect.params", value);
        }
    }
}

impl Project {
    /// Calls `visit` with every value keyed in timeline time and its owner: the clip values and
    /// transition parameters of each track in order, then [`Self::for_each_bus_value_mut`].
    pub fn for_each_timeline_value_mut(
        &mut self,
        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut dyn TimelineValue),
    ) {
        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
            for clip in &mut track.clips {
                let owner = TimelineOwner::Clip {
                    track: position,
                    id: &clip.id,
                    range: clip.timeline_range,
                };
                clip_values(
                    &mut clip.visual,
                    &mut clip.masks,
                    &mut clip.audio,
                    &mut clip.time_map,
                    &mut |at, value| visit(owner, at, value),
                );
            }
            for (index, transition) in track.transitions.iter_mut().enumerate() {
                let owner = TimelineOwner::Transition {
                    track: position,
                    index,
                    range: transition.timeline_range,
                };
                transition.for_each_timeline_value_mut(&mut |at, value| visit(owner, at, value));
            }
        }
        self.for_each_bus_value_mut(&mut |owner, at, value| visit(owner, at, value));
    }

    /// Calls `visit` with each bus value keyed in timeline time: the gain, pan, send gains and
    /// effect parameters of each track in order, then the master gain and effect parameters,
    /// then the same of each bus in order.
    pub fn for_each_bus_value_mut(
        &mut self,
        visit: &mut dyn FnMut(TimelineOwner<'_>, &'static str, &mut Animated<f32>),
    ) {
        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
            let owner = TimelineOwner::Track {
                track: position,
                id: &track.id,
            };
            visit(owner, "TrackAudio.gain", &mut track.audio.gain);
            visit(owner, "TrackAudio.pan", &mut track.audio.pan);
            for send in &mut track.audio.sends {
                visit(owner, "AudioSend.gain", &mut send.gain);
            }
            effect_values(&mut track.audio.effects, &mut |at, value| {
                visit(owner, at, value);
            });
        }
        visit(
            TimelineOwner::Master,
            "MasterAudio.gain",
            &mut self.audio.gain,
        );
        effect_values(&mut self.audio.effects, &mut |at, value| {
            visit(TimelineOwner::Master, at, value);
        });
        for (position, bus) in self.audio.buses.iter_mut().enumerate() {
            let owner = TimelineOwner::Bus {
                bus: position,
                id: &bus.id,
            };
            visit(owner, "AudioBus.gain", &mut bus.gain);
            visit(owner, "AudioBus.pan", &mut bus.pan);
            for send in &mut bus.sends {
                visit(owner, "AudioSend.gain", &mut send.gain);
            }
            effect_values(&mut bus.effects, &mut |at, value| visit(owner, at, value));
        }
    }

    /// Calls `visit` with every reference from one part of the timeline to a clip: mattes,
    /// transition clips and `via: { clip }` bindings, in the order of
    /// [`Self::for_each_timeline_value_mut`].
    pub fn for_each_clip_reference_mut(
        &mut self,
        visit: &mut dyn FnMut(TimelineOwner<'_>, ClipReference, &mut ClipId),
    ) {
        for (position, track) in self.timeline.tracks.iter_mut().enumerate() {
            for clip in &mut track.clips {
                let owner = TimelineOwner::Clip {
                    track: position,
                    id: &clip.id,
                    range: clip.timeline_range,
                };
                if let Some(matte) = &mut clip.matte {
                    visit(owner, ClipReference::Matte, &mut matte.source);
                }
                clip_values(
                    &mut clip.visual,
                    &mut clip.masks,
                    &mut clip.audio,
                    &mut clip.time_map,
                    &mut |_, value| {
                        value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
                    },
                );
            }
            for (index, transition) in track.transitions.iter_mut().enumerate() {
                let owner = TimelineOwner::Transition {
                    track: position,
                    index,
                    range: transition.timeline_range,
                };
                visit(
                    owner,
                    ClipReference::TransitionFrom,
                    &mut transition.from_clip,
                );
                visit(owner, ClipReference::TransitionTo, &mut transition.to_clip);
                transition.for_each_timeline_value_mut(&mut |_, value| {
                    value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
                });
            }
        }
        self.for_each_bus_value_mut(&mut |owner, _, value| {
            value.via_clips_mut(&mut |via| visit(owner, ClipReference::Via, via));
        });
    }
}