forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBc327308Tahinli25 days ago1014 commits

reverse.rs144 lines, 5.5 KiBHistoryRawDownload
1//! Walking a clip's frames backwards without holding the clip in memory.
2//!
3//! A video codec only decodes forwards: a picture needs the ones before it, back to
4//! the last sync frame. So a reversed clip is served a *block* at a time -- decode a
5//! stretch of the window forwards, hand it out last to first, then the stretch
6//! before it -- and memory is bounded by the block, not the clip. The blocks are cut
7//! on sync frames where the container says where they are (one GOP is then decoded
8//! once, not once per picture), and capped at [`BLOCK_BUDGET`] bytes of decoded
9//! pictures: a GOP longer than the cap is decoded again from its sync frame for each
10//! of its blocks, which is slower but never larger.
11//!
12//! This module is only the plan -- which blocks, in which order. The decoding and
13//! the pictures' type belong to the caller (playback walks BGRA canvases, export
14//! I420 planes), so both serve a reversed clip by the one rule.
15
16use std::path::Path;
17
18/// What one block of decoded pictures may weigh. A 1080p BGRA canvas is 8 MB, so
19/// this is thirty-odd of them; 4K takes eight.
20pub(crate) const BLOCK_BUDGET: usize = 256 << 20;
21
22/// The most pictures one block may hold when each is `bytes` big: never fewer than
23/// two, so a block always makes progress, and never more than a hundred and twenty.
24pub(crate) fn block_cap(bytes: usize) -> u32 {
25 (BLOCK_BUDGET / bytes.max(1)).clamp(2, 120) as u32
26}
27
28/// Every frame of `path`'s picture a decoder may be started on, when that is cheap
29/// to ask: an mp4 answers off its sync table, while a Matroska file costs a walk of
30/// its clusters (seconds on a big film), so it answers nothing and its blocks are
31/// cut without. Empty is always a legal answer; the plan is merely less tidy.
32pub(crate) fn sync_frames(path: &Path) -> Vec<u32> {
33 if crate::demux::is_matroska(path) {
34 return Vec::new();
35 }
36 crate::demux::sync_points(path)
37}
38
39/// The walk down a window of source frames: [`Walk::next`] hands out the blocks
40/// `[start, end)` from the window's last frame to its first.
41pub(crate) struct Walk {
42 sync: Vec<u32>,
43 lo: u32,
44 end: u32,
45 cap: u32,
46}
47
48impl Walk {
49 /// The blocks of the half-open window `lo..hi`, at most `cap` pictures each,
50 /// cut on the frames of `sync` (sorted) where they can be.
51 pub(crate) fn new(sync: Vec<u32>, lo: u32, hi: u32, cap: u32) -> Self {
52 Self { sync, lo, end: hi.max(lo), cap: cap.max(1) }
53 }
54
55 /// Changes the cap for the blocks still to come: the first picture says how big
56 /// the pictures really are.
57 pub(crate) fn set_cap(&mut self, cap: u32) {
58 self.cap = cap.max(1);
59 }
60
61 /// The next block `(start, end)`, below the one before it; `None` at the window's
62 /// first frame. A block starts on the earliest sync frame that keeps it within the
63 /// cap, so a GOP is whole in one block whenever it fits; with none that does, it
64 /// is the `cap` frames below `end`, and the decoder runs up to them from the sync
65 /// frame before.
66 pub(crate) fn next(&mut self) -> Option<(u32, u32)> {
67 if self.end <= self.lo {
68 return None;
69 }
70 let end = self.end;
71 let floor = self.lo.max(end.saturating_sub(self.cap));
72 let at = self.sync.partition_point(|&s| s < floor);
73 let start = match self.sync.get(at) {
74 Some(&s) if s < end => s,
75 _ => floor,
76 };
77 self.end = start;
78 Some((start, end))
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use super::*;
85
86 fn blocks(sync: &[u32], lo: u32, hi: u32, cap: u32) -> Vec<(u32, u32)> {
87 let mut walk = Walk::new(sync.to_vec(), lo, hi, cap);
88 std::iter::from_fn(|| walk.next()).collect()
89 }
90
91 #[test]
92 fn blocks_tile_the_window_from_the_top_down() {
93 let sync: Vec<u32> = (0..100).step_by(10).collect();
94 let got = blocks(&sync, 3, 95, 25);
95 // Contiguous, descending, covering exactly 3..95.
96 assert_eq!(got.first().map(|b| b.1), Some(95));
97 assert_eq!(got.last().map(|b| b.0), Some(3));
98 for pair in got.windows(2) {
99 assert_eq!(pair[1].1, pair[0].0, "no gap and no overlap between {pair:?}");
100 }
101 assert!(got.iter().all(|&(s, e)| e > s && e - s <= 25), "{got:?}");
102 }
103
104 #[test]
105 fn a_block_starts_on_a_sync_frame_when_one_fits() {
106 let sync = [0, 10, 20, 30, 40];
107 // end 50, cap 25: the earliest sync frame in 25..50 is 30.
108 assert_eq!(blocks(&sync, 0, 50, 25)[0], (30, 50));
109 // Then 5..30 holds 10 and 20; the earliest in range is 10.
110 assert_eq!(blocks(&sync, 0, 50, 25)[1], (10, 30));
111 }
112
113 #[test]
114 fn a_gop_longer_than_the_cap_is_cut_by_the_cap() {
115 let got = blocks(&[0, 100], 0, 100, 30);
116 assert_eq!(got, vec![(70, 100), (40, 70), (10, 40), (0, 10)]);
117 }
118
119 #[test]
120 fn no_sync_table_still_walks_in_capped_blocks() {
121 assert_eq!(blocks(&[], 5, 20, 8), vec![(12, 20), (5, 12)]);
122 }
123
124 #[test]
125 fn an_all_intra_file_does_not_make_blocks_of_one() {
126 let sync: Vec<u32> = (0..64).collect();
127 let got = blocks(&sync, 0, 64, 16);
128 assert_eq!(got.len(), 4, "{got:?}");
129 }
130
131 #[test]
132 fn empty_and_single_frame_windows() {
133 assert!(blocks(&[], 7, 7, 4).is_empty());
134 assert_eq!(blocks(&[], 7, 8, 4), vec![(7, 8)]);
135 }
136
137 #[test]
138 fn the_cap_follows_the_picture_size() {
139 assert_eq!(block_cap(1920 * 1080 * 4), 32);
140 assert_eq!(block_cap(3840 * 2160 * 4), 8);
141 assert_eq!(block_cap(usize::MAX), 2);
142 assert_eq!(block_cap(1), 120);
143 }
144}