1use 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)]
15pub struct BackwardRun {
17 pub times: Vec<MediaTime>,
19 pub until: u64,
21}
22
23#[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#[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
56pub const MAX_SEQUENTIAL_DECODE_GAP: MediaTime =
59 MediaTime::from_ticks(2 * alpha2_time::TICKS_PER_SECOND);
60
61#[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
69pub type DecodeCursorKey = (SourceId, ClipId, Option<NodeId>);
71
72#[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#[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 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#[derive(Debug, Default)]
111pub struct CursorReads {
112 spans: HashMap<DecodeCursorKey, Vec<TimeRange>>,
114}
115
116impl CursorReads {
117 #[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 #[must_use]
135 pub fn knows(&self, cursor: &DecodeCursorKey) -> bool {
136 self.spans.contains_key(cursor)
137 }
138
139 #[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 #[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}