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#[derive(Debug)]
84pub struct VisualDecodeReads {
85 pub decoder_peak: usize,
87 pub frame_peak: usize,
89 pub provider_peak: usize,
91 pub sequence_peak: usize,
93 pub reads: CursorReads,
95}
96
97#[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 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#[derive(Debug, Default)]
158pub struct CursorReads {
159 spans: HashMap<DecodeCursorKey, Vec<TimeRange>>,
161}
162
163impl CursorReads {
164 #[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 #[must_use]
182 pub fn knows(&self, cursor: &DecodeCursorKey) -> bool {
183 self.spans.contains_key(cursor)
184 }
185
186 #[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 #[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}