forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

inter.rs234 lines, 8.5 KiBHistoryRawDownload
1//! Inter prediction of the coding units of a P or B slice (8.5.3.3).
2//!
3//! [`InterRefs`] holds what a slice's prediction units read: the final (in-loop
4//! filtered) samples of every picture in `RefPicList0` and `RefPicList1`, in list
5//! order, and the explicit weights when the PPS turns weighted prediction on.
6//! [`super::cu_syntax`] calls [`super::mc::predict_pu`] for each prediction unit,
7//! right after its motion is derived, then adds the coding unit's residual.
8
9use super::cu_syntax::{Motion, ResidualBlock};
10use super::mc::{self, Block, McScratch, PlaneMut, PlaneRef, RefPicture};
11use super::pic::PicState;
12use super::shared::SharedPic;
13use super::weighted::ExplicitWeights;
14use crate::decode::DecodedPicture;
15use ec_core::error::Result;
16use ec_h265_syntax::Sps;
17use ec_h265_syntax::slice::SliceHeader;
18use std::sync::{Arc, RwLockReadGuard};
19
20/// The reference pictures and weights of one P or B slice.
21pub struct InterRefs {
22 /// `pics[list][ref_idx]`: the reference pictures, in list order. A picture may still be
23 /// being decoded; a prediction waits for the rows it reads (see [`InterRefs::predict`]).
24 pub pics: [Vec<Arc<SharedPic>>; 2],
25 /// Explicit weights (`pred_weight_table()` of the slice), when weighted prediction applies.
26 pub weights: Option<ExplicitWeights>,
27 /// The log2 chroma subsampling `(sub_x, sub_y)` of the sequence.
28 pub sub: (u32, u32),
29}
30
31impl InterRefs {
32 /// The reference set of a slice: the pictures of its lists, and its explicit weights.
33 pub fn new(
34 pics: [Vec<Arc<SharedPic>>; 2],
35 header: &SliceHeader,
36 sps: &Sps,
37 ) -> Result<InterRefs> {
38 let weights = match header.pred_weight_table.as_ref() {
39 Some(table) => Some(ExplicitWeights::from_table(
40 table,
41 sps.bit_depth_luma_minus8 + 8,
42 sps.bit_depth_chroma_minus8 + 8,
43 sps.range.high_precision_offsets_enabled,
44 )?),
45 None => None,
46 };
47 Ok(InterRefs {
48 pics,
49 weights,
50 sub: crate::decode::chroma_shifts(sps.chroma_format_idc),
51 })
52 }
53
54 /// Predict one prediction unit into `out` (8.5.3.3). Before the samples are read,
55 /// the unit waits until each reference has its rows final: the block, the filter
56 /// taps below it (four rows) and the vertical motion. The read lock on a reference
57 /// is held only for this call, so a writer never waits on a reader that waits on it.
58 pub fn predict(
59 &self,
60 motion: &Motion,
61 pu: Block,
62 out: &mut [PlaneMut<'_>; 3],
63 scratch: &mut McScratch,
64 ) -> Result<()> {
65 for list in 0..2 {
66 if let Some(pic) = self.picture(motion, list) {
67 // The luma taps reach 4 rows below the block, the chroma taps 2 chroma
68 // rows; a vector far above the picture clamps its reads to row 0, so at
69 // least one row is always waited for.
70 let bottom = (pu.y + pu.height) as i64 + (i64::from(motion.mv[list][1]) >> 2) + 16;
71 pic.wait_rows(bottom.clamp(1, pic.height as i64) as usize)?;
72 }
73 }
74 let pics = [self.picture(motion, 0), self.picture(motion, 1)];
75 let guards = lock_ref_planes(pics, || {});
76 // A list that names the picture of the other list reads through that lock.
77 let same = matches!(pics, [Some(a), Some(b)] if std::ptr::eq(a, b));
78 let planes = [
79 guards[0].as_deref(),
80 if same {
81 guards[0].as_deref()
82 } else {
83 guards[1].as_deref()
84 },
85 ];
86 // `predict_pu` indexes a list by `ref_idx`, so each used list is a slice whose
87 // entries up to that index all name the one picture.
88 let mut lists: [Vec<RefPicture<'_>>; 2] = [Vec::new(), Vec::new()];
89 for list in 0..2 {
90 if let (Some(pic), Some(idx)) = (planes[list], self.index(motion, list)) {
91 lists[list] = vec![ref_picture(pic); idx + 1];
92 }
93 }
94 mc::predict_pu_fmt(
95 [lists[0].as_slice(), lists[1].as_slice()],
96 motion,
97 self.weights.as_ref(),
98 pu,
99 self.sub,
100 out,
101 scratch,
102 )
103 }
104
105 /// The reference index of `list` when the list is used and names a picture.
106 fn index(&self, motion: &Motion, list: usize) -> Option<usize> {
107 if !motion.pred_flags[list] {
108 return None;
109 }
110 usize::try_from(motion.ref_idx[list])
111 .ok()
112 .filter(|&i| i < self.pics[list].len())
113 }
114
115 /// The picture a used list of `motion` names.
116 fn picture(&self, motion: &Motion, list: usize) -> Option<&SharedPic> {
117 self.index(motion, list).map(|i| &*self.pics[list][i])
118 }
119}
120
121/// Read-lock the planes of the pictures `pics` names, each distinct picture once. Both
122/// lists of a B slice often name one picture; a second read lock taken by the same thread
123/// deadlocks as soon as the picture's worker queues a write in between. `between` runs
124/// after the first lock is taken (the tests use it to queue that write).
125fn lock_ref_planes<'a>(
126 pics: [Option<&'a SharedPic>; 2],
127 between: impl FnOnce(),
128) -> [Option<RwLockReadGuard<'a, DecodedPicture>>; 2] {
129 let same = matches!(pics, [Some(a), Some(b)] if std::ptr::eq(a, b));
130 let first = pics[0].map(|p| p.read_planes());
131 between();
132 let second = match pics[1] {
133 Some(p) if !same => Some(p.read_planes()),
134 _ => None,
135 };
136 [first, second]
137}
138
139/// The three planes of a decoded picture, for motion compensation.
140fn ref_picture(pic: &DecodedPicture) -> RefPicture<'_> {
141 let (sx, sy) = pic.chroma_shifts();
142 let (cw, ch) = (pic.width.div_ceil(1 << sx), pic.height.div_ceil(1 << sy));
143 [
144 PlaneRef {
145 samples: &pic.y,
146 stride: pic.width,
147 width: pic.width,
148 height: pic.height,
149 bit_depth: pic.bit_depth,
150 },
151 PlaneRef {
152 samples: &pic.cb,
153 stride: cw,
154 width: cw,
155 height: ch,
156 bit_depth: pic.bit_depth_c,
157 },
158 PlaneRef {
159 samples: &pic.cr,
160 stride: cw,
161 width: cw,
162 height: ch,
163 bit_depth: pic.bit_depth_c,
164 },
165 ]
166}
167
168/// Add the residual blocks of an inter coding unit to the samples its prediction
169/// units already wrote.
170pub fn add_residuals(pic: &mut PicState, residuals: &[ResidualBlock]) {
171 if !pic.has_pixels() {
172 return;
173 }
174 for block in residuals {
175 pic.add_residual(
176 block.component,
177 block.x,
178 block.y,
179 block.size,
180 &block.samples,
181 );
182 }
183}
184
185#[cfg(test)]
186mod tests {
187 use super::*;
188 use std::sync::mpsc;
189 use std::time::Duration;
190
191 /// Both lists of a B slice naming one picture: the picture is read-locked once, so a
192 /// writer that queues up while the prediction holds the lock does not deadlock it.
193 /// The watchdog turns a deadlock into a failure.
194 #[test]
195 fn shared_reference_in_both_lists_locks_once() {
196 let (tx, rx) = mpsc::channel();
197 std::thread::spawn(move || {
198 let (w, h) = (64usize, 64usize);
199 let pic = Arc::new(SharedPic::new(0, w, h, (8, 8), true, 1));
200 let src = DecodedPicture {
201 width: w,
202 height: h,
203 bit_depth: 8,
204 bit_depth_c: 8,
205 chroma_format_idc: 1,
206 y: vec![0; w * h],
207 cb: vec![0; (w / 2) * (h / 2)],
208 cr: vec![0; (w / 2) * (h / 2)],
209 };
210 let writer = {
211 let pic = Arc::clone(&pic);
212 let src = src.clone();
213 move || {
214 for to in 1..=h {
215 pic.publish_rows(&src, to);
216 }
217 }
218 };
219 let mut writer_thread = None;
220 let guards = lock_ref_planes([Some(&*pic), Some(&*pic)], || {
221 // The picture's worker publishes rows now and queues behind the read lock.
222 writer_thread = Some(std::thread::spawn(writer.clone()));
223 std::thread::sleep(Duration::from_millis(100));
224 });
225 drop(guards);
226 if let Some(t) = writer_thread {
227 t.join().expect("writer");
228 }
229 let _ = tx.send(());
230 });
231 rx.recv_timeout(Duration::from_secs(20))
232 .expect("prediction deadlocked: a reference picture was read-locked twice");
233 }
234}