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/// The peak number of decoder cursors reading at once
83/// ([`alpha2_eval::ActiveIndex::peak_source_reads`]) over `export_range`, at least 1, and when each
84/// reads. Provider sources and stills open no decoder.
85#[must_use]
86pub fn visual_decode_reads(
87    project: &alpha2_model::Project,
88    export_range: TimeRange,
89) -> (usize, CursorReads) {
90    let decoded = project
91        .sources
92        .iter()
93        .filter(|source| source.kind == alpha2_model::MediaKind::Video && source.provider.is_none())
94        .map(|source| &source.id)
95        .collect::<std::collections::HashSet<_>>();
96    // An export validated the project already; an index it cannot build reads nothing.
97    let Ok(index) = alpha2_eval::ActiveIndex::build(project) else {
98        return (1, CursorReads::default());
99    };
100    let counted = |source: &SourceId| decoded.contains(source);
101    (
102        index.peak_source_reads(export_range, counted).max(1),
103        CursorReads::new(index.source_reads(export_range, counted)),
104    )
105}
106
107/// Where each cursor may read ([`alpha2_eval::ActiveIndex::source_reads`]), which tells a shard
108/// which session it can close and which one is read last. An unknown cursor is taken to be read
109/// now, so it is never closed early and is evicted only by recency.
110#[derive(Debug, Default)]
111pub struct CursorReads {
112    /// By start.
113    spans: HashMap<DecodeCursorKey, Vec<TimeRange>>,
114}
115
116impl CursorReads {
117    /// The spans every cursor reads, from the active index.
118    #[must_use]
119    pub fn new(reads: Vec<alpha2_eval::SourceRead>) -> Self {
120        let mut spans = HashMap::<DecodeCursorKey, Vec<TimeRange>>::new();
121        for read in reads {
122            spans
123                .entry((read.source_id, read.clip_id, read.reader))
124                .or_default()
125                .push(read.span);
126        }
127        for cursor_spans in spans.values_mut() {
128            cursor_spans.sort_unstable_by_key(|span| span.start());
129        }
130        Self { spans }
131    }
132
133    /// Whether `cursor` has spans.
134    #[must_use]
135    pub fn knows(&self, cursor: &DecodeCursorKey) -> bool {
136        self.spans.contains_key(cursor)
137    }
138
139    /// `time` itself inside a span, else the next span's start; `None` when nothing is read from
140    /// `time` on or the cursor is unknown.
141    #[must_use]
142    pub fn next_read(&self, cursor: &DecodeCursorKey, time: MediaTime) -> Option<MediaTime> {
143        self.spans
144            .get(cursor)?
145            .iter()
146            .find(|span| span.end() > time)
147            .map(|span| span.start().max(time))
148    }
149
150    /// Whether `cursor` reads nothing from `time` on.
151    #[must_use]
152    pub fn finished(&self, cursor: &DecodeCursorKey, time: MediaTime) -> bool {
153        self.knows(cursor) && self.next_read(cursor, time).is_none()
154    }
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    fn range(start: i64, end: i64) -> TimeRange {
162        TimeRange::new(MediaTime::from_ticks(start), MediaTime::from_ticks(end)).expect("range")
163    }
164
165    #[test]
166    fn decode_parallelism_counts_what_compositions_read() {
167        use serde_json::json;
168        let span = |start, end| json!({"start": start, "end": end});
169        let video = |id: &str| json!({"id": id, "kind": "video", "locator": format!("{id}.mp4")});
170        let media = |id: &str| json!({"id": id, "op": {"type": "media", "source_id": id}});
171        let quad = json!({"id": "quad", "nodes": [
172            media("a"), media("b"), media("c"), media("d"),
173            {"id": "mix", "op": {"type": "merge", "layers": [
174                {"input": "a"}, {"input": "b"}, {"input": "c"}, {"input": "d"}
175            ]}}
176        ], "output": "mix"});
177        let project = |clip: serde_json::Value| {
178            alpha2_model::Project::from_json(
179                &json!({
180                    "schema_version": 1, "id": "p", "name": "p",
181                    "settings": {"width": 64, "height": 36, "frame_rate": {"num": 30, "den": 1}, "sample_rate": 48_000},
182                    "sources": [video("a"), video("b"), video("c"), video("d"),
183                        {"id": "split", "kind": "composition", "composition": "quad"}],
184                    "compositions": [quad],
185                    "timeline": {"tracks": [{"id": "t", "name": "V", "kind": "video", "clips": [clip]}]}
186                })
187                .to_string(),
188            )
189            .expect("valid")
190        };
191        let composed = project(json!({
192            "id": "c", "source_id": "a", "composition": {"id": "quad"},
193            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
194        }));
195        assert_eq!(visual_decode_reads(&composed, range(0, 120_000)).0, 4);
196        let source = project(json!({
197            "id": "c", "source_id": "split",
198            "timeline_range": span(0, 120_000), "source_range": span(0, 120_000)
199        }));
200        assert_eq!(visual_decode_reads(&source, range(0, 120_000)).0, 4);
201    }
202}