tellers-timeline-core 0.1.0

An OpenTimelineIO timeline engine with policy-driven editing, sync, sanitization, and effect conventions.
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
use crate::{IdMetadataExt, InsertPolicy, OverlapPolicy, Seconds, Stack, TrackKind};

impl Stack {
    /// Move an item identified by `item_id` to `dest_time` on the track with `dest_track_id`.
    ///
    /// When the selected clip belongs to a Tellers group, every sub-unit of the
    /// group (each sync column, and each standalone clip) shifts by the same time
    /// delta as the selected clip. Only the selected clip changes track; the other
    /// members stay on their own tracks. Otherwise the move falls through to the
    /// regular single-item path.
    ///
    /// Returns true if the item was successfully moved.
    pub fn move_item_at_time(
        &mut self,
        item_id: &str,
        dest_track_id: &str,
        dest_time: Seconds,
        replace_with_gap: bool,
        insert_policy: InsertPolicy,
        overlap_policy: OverlapPolicy,
    ) -> bool {
        if let Some(plan) = self.tellers_group_move_plan(item_id, dest_track_id, dest_time) {
            let backup = self.clone();
            if !self.move_group_plan(
                &backup,
                item_id,
                plan,
                replace_with_gap,
                insert_policy,
                overlap_policy,
            ) {
                *self = backup;
                return false;
            }
            return true;
        }

        self.move_item_at_time_single(
            item_id,
            dest_track_id,
            dest_time,
            replace_with_gap,
            insert_policy,
            overlap_policy,
        )
    }

    /// Lift the entire selection before placing any member. Ripple deletion must
    /// not shift a group member that has already reached its destination.
    fn move_group_plan(
        &mut self,
        snapshot: &Stack,
        selected_id: &str,
        plan: Vec<(String, String, Seconds)>,
        replace_with_gap: bool,
        insert_policy: InsertPolicy,
        overlap_policy: OverlapPolicy,
    ) -> bool {
        let mut columns = Vec::new();
        let mut targets = Vec::new();
        for (id, track_id, time) in plan {
            if !time.is_finite() || time < 0.0 {
                return false;
            }
            let Some((ti, ii, item)) = snapshot.get_item(&id) else {
                return false;
            };
            let Some((_, destination)) = snapshot.get_track_by_id(&track_id) else {
                return false;
            };
            if snapshot.children[ti].kind != destination.kind {
                return false;
            }
            let members = snapshot.synced_move_items(&id).unwrap_or_else(|| {
                vec![super::SyncedMoveItem {
                    track_index: ti,
                    item_index: ii,
                    track_kind: snapshot.children[ti].kind.clone(),
                    item: item.clone(),
                    is_selected: true,
                }]
            });
            targets.extend(members.iter().map(|m| (m.track_index, m.item_index)));
            columns.push((track_id, time, members));
        }
        self.delete_clips_at_indices(targets, replace_with_gap);
        // Snap the selected anchor once, never each group member independently.
        let Some((track_id, requested, _)) = columns.iter().find(|(_, _, members)| {
            members
                .iter()
                .any(|m| m.is_selected && m.item.get_id().as_deref() == Some(selected_id))
        }) else {
            return false;
        };
        let Some((_, track)) = self.get_track_by_id(track_id) else {
            return false;
        };
        let Some(resolved) =
            super::insertion_start_or_end_for_policy(track, *requested, insert_policy)
        else {
            return false;
        };
        let adjustment = resolved - requested;
        for (_, time, _) in &mut columns {
            *time += adjustment;
            if *time < 0.0 {
                return false;
            }
        }
        // All sources are lifted: place earliest first so later Push inserts
        // cannot ripple a member that is already at its planned position.
        columns.sort_by(|a, b| a.1.total_cmp(&b.1));
        let mut expected = Vec::new();
        for (track_id, time, members) in columns {
            let Some((dest, _)) = self.get_track_by_id(&track_id) else {
                return false;
            };
            let Some(selected) = members.iter().find(|m| m.is_selected) else {
                return false;
            };
            // Partners in slot order (nearest the owner first), as the
            // single-column move does: insertion assigns slots in list order,
            // so stack order would reverse the channels.
            let member_tracks: Vec<usize> = members.iter().map(|m| m.track_index).collect();
            let owner = snapshot
                .column_owner_track_index(&member_tracks)
                .unwrap_or(selected.track_index);
            let mut audio_partners = Vec::new();
            let mut video = None;
            let mut video_track = None;
            let mut source_tracks = Vec::new();
            for member in &members {
                let Some(source_id) = snapshot.children[member.track_index].get_id() else {
                    return false;
                };
                let Some((source, _)) = self.get_track_by_id(&source_id) else {
                    return false;
                };
                source_tracks.push(source);
                if let Some(id) = member.item.get_id() {
                    expected.push((
                        id,
                        time,
                        member.item.duration(),
                        crate::item_link_group_id(&member.item),
                    ));
                }
                if member.is_selected {
                    continue;
                }
                match member.track_kind {
                    TrackKind::Audio => {
                        let slot = snapshot.partner_slot_order(owner, member.track_index);
                        audio_partners.push((slot, member.item.clone(), source));
                    }
                    TrackKind::Video => {
                        if video.is_some() {
                            return false;
                        }
                        video = Some(member.item.clone());
                        if snapshot.children[selected.track_index].get_id().as_deref()
                            == Some(&track_id)
                        {
                            video_track = Some(source_id);
                        }
                    }
                    TrackKind::Other => return false,
                }
            }
            audio_partners.sort_by_key(|(slot, _, _)| *slot);
            let (audio, audio_tracks): (Vec<_>, Vec<_>) = audio_partners
                .into_iter()
                .map(|(_, item, source)| (item, source))
                .unzip();
            let old_start =
                snapshot.children[selected.track_index].start_time_of_item(selected.item_index);
            if self
                .insert_synced_item_at_time(
                    dest,
                    time,
                    None,
                    selected.item.clone(),
                    Self::effective_move_overlap_policy(
                        overlap_policy,
                        Some(old_start),
                        time,
                        // Every member is already lifted off the stack.
                        self.move_landing_is_free(dest, time, selected.item.duration(), &[]),
                    ),
                    InsertPolicy::SplitAndInsert,
                    (!audio.is_empty()).then_some(audio),
                    video,
                    false,
                    video_track.as_deref(),
                    Some(&audio_tracks),
                    Some(&source_tracks),
                )
                .is_none()
            {
                return false;
            }
        }
        // Never report success with clipped, lost, or independently rippled members.
        if expected.iter().any(|(id, time, duration, _)| {
            self.get_item(id).is_none_or(|(ti, ii, item)| {
                (self.children[ti].start_time_of_item(ii) - time).abs() > super::EPS
                    || (item.duration() - duration).abs() > super::EPS
            })
        }) {
            return false;
        }
        // Reinsertions sanitize intermediate singletons. Restore the original
        // links only after every member is present, including offset partners.
        // Any new split columns that reused a temporarily vacant link ID must
        // receive another ID before the original relationship is restored.
        let moved_ids: std::collections::HashSet<_> =
            expected.iter().map(|e| e.0.as_str()).collect();
        let original_links: std::collections::BTreeSet<_> =
            expected.iter().filter_map(|e| e.3).collect();
        let mut next_link = self.next_sync_clips_id().max(snapshot.next_sync_clips_id());
        for link in original_links {
            let mut reassigned = false;
            for track in &mut self.children {
                for item in &mut track.items {
                    if crate::item_link_group_id(item) == Some(link)
                        && !item
                            .get_id()
                            .as_deref()
                            .is_some_and(|id| moved_ids.contains(id))
                    {
                        Self::set_item_sync_clips(item, Some(next_link));
                        reassigned = true;
                    }
                }
            }
            if reassigned {
                next_link += 1;
            }
        }
        for (id, _, _, link) in &expected {
            if let Some((ti, ii, _)) = self.get_item(id) {
                Self::set_item_sync_clips(&mut self.children[ti].items[ii], *link);
            }
        }
        self.sanitize();
        true
    }

    /// Move a single sub-unit: a sync column (aligned video/audio partners) moves
    /// as a unit; all other clips, including link groups and unsynced items, share
    /// the same delete + insert path with cluster propagation. This is the
    /// group-unaware move used as a building block by `move_item_at_time`.
    fn move_item_at_time_single(
        &mut self,
        item_id: &str,
        dest_track_id: &str,
        dest_time: Seconds,
        replace_with_gap: bool,
        insert_policy: InsertPolicy,
        overlap_policy: OverlapPolicy,
    ) -> bool {
        if !self.move_keeps_track_kind(item_id, dest_track_id) {
            return false;
        }
        // A ripple move (Push, no gap left behind) only changes the order of
        // clips. Dropping a clip at a time inside its own slot on its own track
        // keeps the order, so nothing moves; placing it would leave the lifted
        // slot's gap behind.
        if overlap_policy == OverlapPolicy::Push && !replace_with_gap {
            if let Some((track_index, item_index, item)) = self.get_item(item_id) {
                let start = self.children[track_index].start_time_of_item(item_index);
                if self.children[track_index].get_id().as_deref() == Some(dest_track_id)
                    && dest_time > start - super::EPS
                    && dest_time < start + item.duration() - super::EPS
                {
                    return true;
                }
            }
        }
        if let Some(items_to_move) = self.synced_move_items(item_id) {
            let dest_track_index = match self.get_track_by_id(dest_track_id) {
                Some((index, _)) => index,
                None => return false,
            };
            return self.move_synced_items_at_time_via_insert(
                items_to_move,
                dest_track_index,
                dest_time,
                replace_with_gap,
                insert_policy,
                overlap_policy,
            );
        }

        self.move_linked_items_at_time(
            item_id,
            dest_track_id,
            dest_time,
            replace_with_gap,
            insert_policy,
            overlap_policy,
        )
    }

    /// A clip only ever moves onto a track of its own kind (video to video,
    /// audio to audio), whether or not it is synced.
    fn move_keeps_track_kind(&self, item_id: &str, dest_track_id: &str) -> bool {
        let (Some((source, _, _)), Some((_, dest))) =
            (self.get_item(item_id), self.get_track_by_id(dest_track_id))
        else {
            return false;
        };
        self.children[source].kind == dest.kind
    }

    /// Move an item identified by `item_id` to `dest_index` on the track with `dest_track_id`.
    /// Returns true if the item was successfully moved.
    pub fn move_item_at_index(
        &mut self,
        item_id: &str,
        dest_track_id: &str,
        dest_index: usize,
        replace_with_gap: bool,
        overlap_policy: OverlapPolicy,
    ) -> bool {
        if !self.move_keeps_track_kind(item_id, dest_track_id) {
            return false;
        }
        if let Some((_, track)) = self.get_track_by_id(dest_track_id) {
            let time = track.start_time_of_item(dest_index);
            if self
                .tellers_group_move_plan(item_id, dest_track_id, time)
                .is_some()
            {
                return self.move_item_at_time(
                    item_id,
                    dest_track_id,
                    time,
                    replace_with_gap,
                    InsertPolicy::InsertBefore,
                    overlap_policy,
                );
            }
        }
        let item_to_move = match self.get_item(item_id) {
            Some((_ti, _ii, it)) => it.clone(),
            None => return false,
        };

        let backup = self.clone();
        let dest_track_index = match self.get_track_by_id(dest_track_id) {
            Some((i, _)) => i,
            None => return false,
        };
        if let Some(items_to_move) = self.synced_move_items(item_id) {
            return self.move_synced_items(
                items_to_move,
                dest_track_index,
                replace_with_gap,
                overlap_policy,
                dest_index,
            );
        }

        // `dest_index` refers to the track as it is now. Lifting the item from
        // earlier on the same track shifts the indices after it (its slot goes,
        // or its gap merges with a neighbour), so anchor the destination on the
        // start time `items[dest_index]` has once the item is lifted: the same,
        // or earlier by the item's duration when no gap is left behind. Then
        // find that boundary again, splitting a merged gap if needed.
        let source = self.get_item(item_id).map(|(ti, ii, _)| (ti, ii));
        let anchor_time = match source {
            Some((ti, ii)) if ti == dest_track_index && ii < dest_index => {
                let lifted = if replace_with_gap {
                    0.0
                } else {
                    item_to_move.duration()
                };
                Some(self.children[ti].start_time_of_item(dest_index) - lifted)
            }
            _ => None,
        };

        if self.delete_one_item(item_id, replace_with_gap).is_none() {
            return false;
        }

        let dest_index = match anchor_time {
            Some(time) => {
                let track = &mut self.children[dest_track_index];
                track.split_at_time(time);
                (0..=track.items.len())
                    .find(|&index| track.start_time_of_item(index) >= time - super::EPS)
                    .unwrap_or(track.items.len())
            }
            None => dest_index,
        };

        if self
            .insert_item_at_index(
                dest_track_id,
                dest_index,
                item_to_move,
                overlap_policy,
                None,
                None,
            )
            .is_some()
        {
            self.sanitize();
            true
        } else {
            *self = backup;
            false
        }
    }
}