forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

rps.rs320 lines, 10.9 KiBHistoryRawDownload
1//! Reference picture sets, marking and reference picture lists (8.3.2 to 8.3.4).
2
3use super::dpb::{Dpb, Marking};
4use super::shared::SharedPic;
5use crate::decode::DecodedPicture;
6use ec_core::error::{Error, Result};
7use ec_h265_syntax::slice::{LongTermRef, SliceHeader, SliceType};
8use ec_h265_syntax::{ConformanceWindow, ShortTermRefPicSet};
9use std::sync::Arc;
10
11/// What clause 8.3.2 needs from the current picture and its slice header.
12#[derive(Debug, Clone, Copy)]
13pub struct RpsInput<'a> {
14 /// `PicOrderCntVal` of the current picture.
15 pub poc: i32,
16 /// `log2_max_pic_order_cnt_lsb`.
17 pub log2_max_poc_lsb: u32,
18 /// The slice's short-term reference picture set (empty for an IDR picture).
19 pub st: &'a ShortTermRefPicSet,
20 /// The slice's long-term entries (empty for an IDR picture).
21 pub lt: &'a [LongTermRef],
22 /// The current picture is an IRAP with NoRaslOutputFlag: every reference
23 /// picture in the buffer is marked unused first.
24 pub irap_no_rasl: bool,
25 /// Luma width of the picture, for generated pictures.
26 pub width: usize,
27 /// Luma height of the picture, for generated pictures.
28 pub height: usize,
29 /// Bit depths (luma, chroma) of a generated (8.3.3) picture, whose samples are
30 /// grey. `None` generates a picture without samples, for a decoder that does
31 /// not decode pixels.
32 pub fill: Option<(u32, u32)>,
33 /// `chroma_format_idc` of the generated picture.
34 pub chroma_format_idc: u32,
35}
36
37/// One entry of a reference picture set or list.
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39pub struct RefEntry {
40 /// The picture's id in the decoded picture buffer.
41 pub id: u32,
42 /// Its `PicOrderCntVal`.
43 pub poc: i32,
44 /// Whether it is a long-term reference.
45 pub long_term: bool,
46}
47
48/// The five reference picture subsets of 8.3.2, as buffer ids. Missing
49/// `Curr` entries are generated (8.3.3); missing `Foll` entries are left out.
50#[derive(Debug, Clone, Default, PartialEq, Eq)]
51pub struct RefPicSet {
52 /// `RefPicSetStCurrBefore`.
53 pub st_curr_before: Vec<RefEntry>,
54 /// `RefPicSetStCurrAfter`.
55 pub st_curr_after: Vec<RefEntry>,
56 /// `RefPicSetStFoll`.
57 pub st_foll: Vec<RefEntry>,
58 /// `RefPicSetLtCurr`.
59 pub lt_curr: Vec<RefEntry>,
60 /// `RefPicSetLtFoll`.
61 pub lt_foll: Vec<RefEntry>,
62}
63
64/// `RefPicList0` and `RefPicList1` of one slice (8.3.4).
65#[derive(Debug, Clone, Default, PartialEq, Eq)]
66pub struct RefPicLists {
67 /// `RefPicList0`.
68 pub l0: Vec<RefEntry>,
69 /// `RefPicList1`; empty unless the slice is a B slice.
70 pub l1: Vec<RefEntry>,
71}
72
73/// A long-term or short-term candidate: found in the buffer, or missing.
74#[derive(Debug, Clone, Copy)]
75enum Slot {
76 Found(RefEntry),
77 Missing(i32),
78}
79
80impl Dpb {
81 /// Derive the reference picture set of the current picture and apply its
82 /// marking to the buffer (8.3.2), generating any missing `Curr` picture
83 /// (8.3.3) so that inter prediction always has something to read.
84 pub fn apply_rps(&mut self, input: &RpsInput<'_>) -> RefPicSet {
85 let max_lsb = 1i64 << input.log2_max_poc_lsb;
86 let poc = i64::from(input.poc);
87 if input.irap_no_rasl {
88 for p in self.pictures_mut() {
89 p.marking = Marking::Unused;
90 }
91 }
92
93 // Long-term entries (8-5): a picture named here becomes long-term. The
94 // candidates are reference pictures of either marking.
95 let mut lt_slots: Vec<(Slot, bool)> = Vec::new();
96 for e in input.lt {
97 let msb_present = e.delta_poc_msb_present;
98 let mut target = i64::from(e.poc_lsb_lt);
99 if msb_present {
100 target += poc - i64::from(e.delta_poc_msb_cycle) * max_lsb - (poc & (max_lsb - 1));
101 }
102 let found = self.pictures().iter().find(|p| {
103 if p.marking == Marking::Unused {
104 return false;
105 }
106 let p_poc = i64::from(p.poc);
107 if msb_present {
108 p_poc == target
109 } else {
110 (p_poc & (max_lsb - 1)) == target
111 }
112 });
113 let slot = match found {
114 Some(p) => Slot::Found(RefEntry {
115 id: p.id,
116 poc: p.poc,
117 long_term: true,
118 }),
119 None => Slot::Missing(target as i32),
120 };
121 lt_slots.push((slot, e.used_by_curr));
122 }
123 for (slot, _) in &lt_slots {
124 if let Slot::Found(entry) = slot {
125 self.mark(entry.id, Marking::LongTerm);
126 }
127 }
128
129 // Short-term entries (8-6 to 8-8): short-term pictures only, after the
130 // long-term conversion above.
131 let mut st_before: Vec<(Slot, bool)> = Vec::new();
132 let mut st_after: Vec<(Slot, bool)> = Vec::new();
133 let st = input.st;
134 for i in 0..st.num_negative as usize {
135 let target = poc + i64::from(st.delta_poc_s0[i]);
136 st_before.push((self.find_short(target), st.used_s0[i]));
137 }
138 for i in 0..st.num_positive as usize {
139 let target = poc + i64::from(st.delta_poc_s1[i]);
140 st_after.push((self.find_short(target), st.used_s1[i]));
141 }
142
143 // Everything not named by one of the five lists is no longer a reference.
144 let named: Vec<u32> = lt_slots
145 .iter()
146 .chain(st_before.iter())
147 .chain(st_after.iter())
148 .filter_map(|(slot, _)| match slot {
149 Slot::Found(e) => Some(e.id),
150 Slot::Missing(_) => None,
151 })
152 .collect();
153 for p in self.pictures_mut() {
154 if p.marking != Marking::Unused && !named.contains(&p.id) {
155 p.marking = Marking::Unused;
156 }
157 }
158
159 let mut set = RefPicSet::default();
160 for (slot, used) in lt_slots {
161 if let Some(entry) = self.resolve(slot, used, true, input) {
162 if used {
163 set.lt_curr.push(entry);
164 } else {
165 set.lt_foll.push(entry);
166 }
167 }
168 }
169 for (slot, used) in st_before {
170 if let Some(entry) = self.resolve(slot, used, false, input) {
171 if used {
172 set.st_curr_before.push(entry);
173 } else {
174 set.st_foll.push(entry);
175 }
176 }
177 }
178 for (slot, used) in st_after {
179 if let Some(entry) = self.resolve(slot, used, false, input) {
180 if used {
181 set.st_curr_after.push(entry);
182 } else {
183 set.st_foll.push(entry);
184 }
185 }
186 }
187 set
188 }
189
190 fn find_short(&self, target: i64) -> Slot {
191 match self
192 .pictures()
193 .iter()
194 .find(|p| p.marking == Marking::ShortTerm && i64::from(p.poc) == target)
195 {
196 Some(p) => Slot::Found(RefEntry {
197 id: p.id,
198 poc: p.poc,
199 long_term: false,
200 }),
201 None => Slot::Missing(target as i32),
202 }
203 }
204
205 fn mark(&mut self, id: u32, marking: Marking) {
206 for p in self.pictures_mut() {
207 if p.id == id {
208 p.marking = marking;
209 }
210 }
211 }
212
213 /// Turn a candidate into an entry. A missing `Curr` entry is generated; a
214 /// missing `Foll` entry is dropped.
215 fn resolve(
216 &mut self,
217 slot: Slot,
218 used: bool,
219 long_term: bool,
220 input: &RpsInput<'_>,
221 ) -> Option<RefEntry> {
222 match slot {
223 Slot::Found(entry) => Some(entry),
224 Slot::Missing(poc) if used => {
225 let marking = if long_term {
226 Marking::LongTerm
227 } else {
228 Marking::ShortTerm
229 };
230 let id = self.generate(poc, marking, input);
231 Some(RefEntry { id, poc, long_term })
232 }
233 Slot::Missing(_) => None,
234 }
235 }
236
237 /// Generate a missing reference picture (8.3.3.2): grey samples, no output.
238 fn generate(&mut self, poc: i32, marking: Marking, input: &RpsInput<'_>) -> u32 {
239 let picture = match input.fill {
240 Some((bit_depth, bit_depth_c)) => DecodedPicture::grey_planes_fmt(
241 input.width,
242 input.height,
243 bit_depth,
244 bit_depth_c,
245 input.chroma_format_idc,
246 ),
247 None => DecodedPicture {
248 width: input.width,
249 height: input.height,
250 bit_depth: 8,
251 bit_depth_c: 8,
252 chroma_format_idc: input.chroma_format_idc,
253 y: Vec::new(),
254 cb: Vec::new(),
255 cr: Vec::new(),
256 },
257 };
258 self.insert(
259 poc,
260 marking,
261 false,
262 Arc::new(SharedPic::from_planes(poc, picture)),
263 ConformanceWindow::default(),
264 u32::MAX,
265 )
266 }
267}
268
269/// Build `RefPicList0` and `RefPicList1` for a slice (8.3.4). Entries cycle
270/// through the `Curr` subsets until the list is as long as the active count;
271/// `ref_pic_list_modification` picks entries out of that cycle.
272pub fn build_ref_lists(set: &RefPicSet, header: &SliceHeader) -> Result<RefPicLists> {
273 let mut lists = RefPicLists::default();
274 if header.slice_type == SliceType::I {
275 return Ok(lists);
276 }
277 let total = set.st_curr_before.len() + set.st_curr_after.len() + set.lt_curr.len();
278 if total == 0 {
279 return Err(Error::corrupt(
280 "HEVC slice: inter slice whose RPS has no reference picture".to_string(),
281 ));
282 }
283 let num0 = header.num_ref_idx_l0_active_minus1 as usize + 1;
284 let temp0 = cycle(
285 &[&set.st_curr_before, &set.st_curr_after, &set.lt_curr],
286 num0.max(total),
287 );
288 lists.l0 = pick(&temp0, &header.list_entry[0], num0)?;
289 if header.slice_type == SliceType::B {
290 let num1 = header.num_ref_idx_l1_active_minus1 as usize + 1;
291 let temp1 = cycle(
292 &[&set.st_curr_after, &set.st_curr_before, &set.lt_curr],
293 num1.max(total),
294 );
295 lists.l1 = pick(&temp1, &header.list_entry[1], num1)?;
296 }
297 Ok(lists)
298}
299
300fn cycle(parts: &[&Vec<RefEntry>], len: usize) -> Vec<RefEntry> {
301 let base: Vec<RefEntry> = parts.iter().flat_map(|p| p.iter().copied()).collect();
302 if base.is_empty() {
303 return Vec::new();
304 }
305 (0..len).map(|i| base[i % base.len()]).collect()
306}
307
308fn pick(temp: &[RefEntry], entries: &[u32], n: usize) -> Result<Vec<RefEntry>> {
309 (0..n)
310 .map(|i| {
311 let idx = entries.get(i).map_or(i, |&e| e as usize);
312 temp.get(idx).copied().ok_or_else(|| {
313 Error::corrupt(format!(
314 "HEVC slice: list entry {idx} is past the {} candidates",
315 temp.len()
316 ))
317 })
318 })
319 .collect()
320}