Skip to main content

alpha2_host_core/
cursor.rs

1//! Which frames an export cursor reads next, and when a decoder keeps decoding instead of seeking.
2//!
3//! A cursor is one reader of one source: a clip, or a composition step inside it, so two clips of
4//! one file decode independently.
5
6use std::collections::HashMap;
7
8use alpha2_engine::ExportFrameNeeds;
9use alpha2_eval::FrameNeed;
10use alpha2_media::SourceId;
11use alpha2_model::{ClipId, NodeId};
12use alpha2_time::{MediaTime, TimeRange};
13
14#[derive(Debug, Eq, PartialEq)]
15/// The times a cursor asks for while its source time does not increase.
16pub struct BackwardRun {
17    /// Distinct, non-increasing, in the order the cursor asks for them.
18    pub times: Vec<MediaTime>,
19    /// The last export frame index of the run.
20    pub until: u64,
21}
22
23/// Times while they do not increase and every frame asks for the cursor.
24#[must_use]
25pub fn backward_run(
26    frames: &[ExportFrameNeeds],
27    start: u64,
28    cursor: &DecodeCursorKey,
29) -> BackwardRun {
30    let mut times = Vec::<MediaTime>::new();
31    let mut until = start;
32    for frame in frames.iter().skip_while(|frame| frame.index < start) {
33        let Some(time) = cursor_time(frame, cursor) else {
34            break;
35        };
36        match times.last() {
37            Some(last) if time > *last => break,
38            Some(last) if time == *last => {}
39            _ => times.push(time),
40        }
41        until = frame.index;
42    }
43    BackwardRun { times, until }
44}
45
46/// The source time `frame` asks `cursor` for, if it reads it.
47#[must_use]
48pub fn cursor_time(frame: &ExportFrameNeeds, cursor: &DecodeCursorKey) -> Option<MediaTime> {
49    frame
50        .needs
51        .iter()
52        .find(|need| decode_cursor_key(need) == *cursor)
53        .map(|need| need.media_time)
54}
55
56/// Two seconds, as the browser's video adapters use. Further ahead, a seek from the preceding
57/// keyframe decodes less than every frame between.
58pub const MAX_SEQUENTIAL_DECODE_GAP: MediaTime =
59    MediaTime::from_ticks(2 * alpha2_time::TICKS_PER_SECOND);
60
61/// Not backward, and at most [`MAX_SEQUENTIAL_DECODE_GAP`] ahead. Either way the frame presented at
62/// `requested` is the one answered.
63#[must_use]
64pub fn decodes_on(previous: MediaTime, requested: MediaTime) -> bool {
65    requested >= previous
66        && requested.ticks().saturating_sub(previous.ticks()) <= MAX_SEQUENTIAL_DECODE_GAP.ticks()
67}
68
69/// The source, the clip, and the composition step reading it (none for the clip's own source).
70pub type DecodeCursorKey = (SourceId, ClipId, Option<NodeId>);
71
72/// The cursor a need reads through.
73#[must_use]
74pub fn decode_cursor_key(need: &FrameNeed) -> DecodeCursorKey {
75    (
76        need.source_id.clone(),
77        need.clip_id.clone(),
78        need.reader.clone(),
79    )
80}
81
82/// What an export reads at once over its range, from one [`alpha2_eval::ActiveIndex`].
83#[derive(Debug)]
84pub struct VisualDecodeReads {
85    /// Peak decoder cursors reading at once, at least 1. Provider sources and stills open none.
86    pub decoder_peak: usize,
87    /// Peak cursors of `video` sources reading at once, providers included; at least `decoder_peak`.
88    pub frame_peak: usize,
89    /// Peak cursors of `video` provider sources reading at once; may be 0.
90    pub provider_peak: usize,
91    /// Peak cursors of image sequences reading at once; may be 0.
92    pub sequence_peak: usize,
93    /// When each decoder cursor reads.
94    pub reads: CursorReads,
95}
96
97/// [`VisualDecodeReads`] over `export_range`.
98#[must_use]
99pub fn visual_decode_reads(
100    project: &alpha2_model::Project,
101    export_range: TimeRange,
102) -> VisualDecodeReads {
103    let frame_by_frame = |provider: Option<bool>| {
104        project
105            .sources
106            .iter()
107            .filter(|source| {
108                source.kind == alpha2_model::MediaKind::Video
109                    && provider.is_none_or(|provider| source.provider.is_some() == provider)
110            })
111            .map(|source| &source.id)
112            .collect::<std::collections::HashSet<_>>()
113    };
114    let decoded = frame_by_frame(Some(false));
115    let provided = frame_by_frame(Some(true));
116    let framed = frame_by_frame(None);
117    let sequences = project
118        .sources
119        .iter()
120        .filter(|source| {
121            matches!(
122                source.provider,
123                Some(alpha2_model::ProviderSource::ImageSequence { .. })
124            )
125        })
126        .map(|source| &source.id)
127        .collect::<std::collections::HashSet<_>>();
128    // An export validated the project already; an index it cannot build reads nothing.
129    let Ok(index) = alpha2_eval::ActiveIndex::build(project) else {
130        return VisualDecodeReads {
131            decoder_peak: 1,
132            frame_peak: 1,
133            provider_peak: 0,
134            sequence_peak: 0,
135            reads: CursorReads::default(),
136        };
137    };
138    let decoder_peak = index
139        .peak_source_reads(export_range, |source| decoded.contains(source))
140        .max(1);
141    VisualDecodeReads {
142        decoder_peak,
143        frame_peak: index
144            .peak_source_reads(export_range, |source| framed.contains(source))
145            .max(decoder_peak),
146        provider_peak: index.peak_source_reads(export_range, |source| provided.contains(source)),
147        sequence_peak: index.peak_source_reads(export_range, |source| sequences.contains(source)),
148        reads: CursorReads::new(
149            index.source_reads(export_range, |source| decoded.contains(source)),
150        ),
151    }
152}
153
154/// Where each cursor may read ([`alpha2_eval::ActiveIndex::source_reads`]), which tells a shard
155/// which session it can close and which one is read last. An unknown cursor is taken to be read
156/// now, so it is never closed early and is evicted only by recency.
157#[derive(Debug, Default)]
158pub struct CursorReads {
159    /// By start.
160    spans: HashMap<DecodeCursorKey, Vec<TimeRange>>,
161}
162
163impl CursorReads {
164    /// The spans every cursor reads, from the active index.
165    #[must_use]
166    pub fn new(reads: Vec<alpha2_eval::SourceRead>) -> Self {
167        let mut spans = HashMap::<DecodeCursorKey, Vec<TimeRange>>::new();
168        for read in reads {
169            spans
170                .entry((read.source_id, read.clip_id, read.reader))
171                .or_default()
172                .push(read.span);
173        }
174        for cursor_spans in spans.values_mut() {
175            cursor_spans.sort_unstable_by_key(|span| span.start());
176        }
177        Self { spans }
178    }
179
180    /// Whether `cursor` has spans.
181    #[must_use]
182    pub fn knows(&self, cursor: &DecodeCursorKey) -> bool {
183        self.spans.contains_key(cursor)
184    }
185
186    /// `time` itself inside a span, else the next span's start; `None` when nothing is read from
187    /// `time` on or the cursor is unknown.
188    #[must_use]
189    pub fn next_read(&self, cursor: &DecodeCursorKey, time: MediaTime) -> Option<MediaTime> {
190        self.spans
191            .get(cursor)?
192            .iter()
193            .find(|span| span.end() > time)
194            .map(|span| span.start().max(time))
195    }
196
197    /// Whether `cursor` reads nothing from `time` on.
198    #[must_use]
199    pub fn finished(&self, cursor: &DecodeCursorKey, time: MediaTime) -> bool {
200        self.knows(cursor) && self.next_read(cursor, time).is_none()
201    }
202}
203
204#[cfg(test)]
205mod tests {
206    use super::*;
207
208    fn range(start: i64, end: i64) -> TimeRange {
209        TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end)).expect("range")
210    }
211
212    #[test]
213    fn decode_parallelism_counts_what_compositions_read() {
214        use serde_json::json;
215        let span = |start, end| json!({"start": start, "end": end});
216        let video = |id: &str| json!({"id": id, "kind": "video", "locator": format!("{id}.mp4")});
217        let media = |id: &str| json!({"id": id, "op": {"type": "media", "source_id": id}});
218        let quad = json!({"id": "quad", "nodes": [
219            media("a"), media("b"), media("c"), media("d"),
220            {"id": "mix", "op": {"type": "merge", "layers": [
221                {"input": "a"}, {"input": "b"}, {"input": "c"}, {"input": "d"}
222            ]}}
223        ], "output": "mix"});
224        let project = |clip: serde_json::Value| {
225            alpha2_model::Project::from_json(
226                &json!({
227                    "schema_version": 1, "id": "p", "name": "p",
228                    "settings": {"width": 64, "height": 36, "frame_rate": {"num": 30, "den": 1}, "sample_rate": 48_000},
229                    "sources": [video("a"), video("b"), video("c"), video("d"),
230                        {"id": "split", "kind": "composition", "composition": "quad"}],
231                    "compositions": [quad],
232                    "timeline": {"tracks": [{"id": "t", "name": "V", "kind": "video", "clips": [clip]}]}
233                })
234                .to_string(),
235            )
236            .expect("valid")
237        };
238        let composed = project(json!({
239            "id": "c", "source_id": "a", "composition": {"id": "quad"},
240            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
241        }));
242        assert_eq!(
243            visual_decode_reads(&composed, range(0, 120_000)).decoder_peak,
244            4
245        );
246        let source = project(json!({
247            "id": "c", "source_id": "split",
248            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
249        }));
250        assert_eq!(
251            visual_decode_reads(&source, range(0, 120_000)).decoder_peak,
252            4
253        );
254    }
255
256    #[test]
257    fn peaks_count_the_provider_sources_that_play_frame_by_frame() {
258        use serde_json::json;
259        let span = |start, end| json!({"start": start, "end": end});
260        let sequence = |id: &str| {
261            json!({"id": id, "kind": "video", "locator": format!("sequence://{id}"),
262                "provider": {"format": "image_sequence", "frames": ["f1", "f2"],
263                    "frame_rate": {"num": 10, "den": 1}, "start_number": 1}})
264        };
265        let clip = |id: &str, source: &str, start: i64, end: i64| {
266            json!({"id": id, "source_id": source,
267                "timeline_range": span(start, end), "source_range": span(0, end - start)})
268        };
269        let track = |id: &str, clips: Vec<serde_json::Value>| json!({"id": id, "name": id, "kind": "video", "clips": clips});
270        let project = |tracks: Vec<serde_json::Value>| {
271            alpha2_model::Project::from_json(
272                &json!({
273                    "schema_version": 1, "id": "p", "name": "p",
274                    "settings": {"width": 64, "height": 36, "frame_rate": {"num": 30, "den": 1}, "sample_rate": 48_000},
275                    "sources": [
276                        {"id": "video", "kind": "video", "locator": "video.mp4"},
277                        sequence("s1"), sequence("s2"), sequence("s3"), sequence("s4"),
278                        {"id": "anim", "kind": "video", "locator": "asset://anim",
279                            "provider": {"format": "animated_image"}},
280                        {"id": "logo", "kind": "image", "locator": "asset://logo",
281                            "provider": {"format": "svg"}},
282                        {"id": "layered", "kind": "composition", "composition": "over"}
283                    ],
284                    "compositions": [{"id": "over", "nodes": [
285                        {"id": "m", "op": {"type": "media", "source_id": "s4"}}
286                    ], "output": "m"}],
287                    "timeline": {"tracks": tracks}
288                })
289                .to_string(),
290            )
291            .expect("valid")
292        };
293        let overlapping = project(vec![
294            track("v", vec![clip("a", "video", 0, 120_000)]),
295            track("s1", vec![clip("b", "s1", 0, 120_000)]),
296            track("s2", vec![clip("c", "s2", 0, 120_000)]),
297            track("s3", vec![clip("d", "s3", 0, 120_000)]),
298            track("svg", vec![clip("e", "logo", 0, 120_000)]),
299        ]);
300        let reads = visual_decode_reads(&overlapping, range(0, 120_000));
301        assert_eq!(
302            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
303            (1, 4, 3)
304        );
305        assert_eq!(reads.sequence_peak, 3);
306        let composed = project(vec![
307            track("v", vec![clip("a", "video", 0, 120_000)]),
308            track("c", vec![clip("b", "layered", 0, 120_000)]),
309        ]);
310        let reads = visual_decode_reads(&composed, range(0, 120_000));
311        assert_eq!(
312            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
313            (1, 2, 1)
314        );
315        assert_eq!(reads.sequence_peak, 1);
316        let following = project(vec![track(
317            "s",
318            vec![
319                clip("a", "s1", 0, 40_000),
320                clip("b", "s2", 40_000, 80_000),
321                clip("c", "s3", 80_000, 120_000),
322            ],
323        )]);
324        let reads = visual_decode_reads(&following, range(0, 120_000));
325        assert_eq!(
326            (reads.decoder_peak, reads.frame_peak, reads.provider_peak),
327            (1, 1, 1)
328        );
329        assert_eq!(reads.sequence_peak, 1);
330        let beside_an_animation = project(vec![
331            track("s", vec![clip("a", "s1", 0, 120_000)]),
332            track("g", vec![clip("b", "anim", 0, 120_000)]),
333        ]);
334        let reads = visual_decode_reads(&beside_an_animation, range(0, 120_000));
335        assert_eq!((reads.provider_peak, reads.sequence_peak), (2, 1));
336        let none = project(vec![track("v", vec![clip("a", "video", 0, 120_000)])]);
337        assert_eq!(
338            visual_decode_reads(&none, range(0, 120_000)).sequence_peak,
339            0
340        );
341    }
342}