forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

hevc_dpb.rs299 lines, 10.6 KiBHistoryRawDownload
1//! HEVC picture management over any surface type: picture order count (8.3.1),
2//! reference picture sets and marking (8.3.2), and output bumping (C.5.2).
3//!
4//! The VA-API and Vulkan Video decoders both build on this. A stored picture
5//! is only its surface, POC, timestamp, marking and output state; the driver
6//! sees the reference picture set as DPB indices into [`Dpb::pictures`].
7
8use ec_core::color::Tags;
9use ec_h265_syntax::{NalUnitType, SliceHeader, Sps};
10
11use crate::error::{Error, Result};
12
13/// PCI vendor ID of AMD.
14pub(crate) const AMD_VENDOR_ID: u32 = 0x1002;
15
16/// AMD's VCN returns wrong chroma for HEVC with 16x16 coding tree blocks, in the
17/// firmware, so ffmpeg's VA-API and Vulkan decoders get the same wrong picture. Such
18/// streams go to software. `amd` is only asked when the CTB size is 16.
19pub(crate) fn hevc_ctb16_broken(sps: &Sps, amd: impl FnOnce() -> bool) -> bool {
20 sps.ctb_size() == 16 && amd()
21}
22
23/// Reference marking of a stored picture (8.3.2).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub(crate) enum Mark {
26 Unused,
27 ShortTerm,
28 LongTerm,
29}
30
31/// One stored picture: its surface, POC, marking and whether it is still to be output.
32pub(crate) struct StoredPicture<S> {
33 pub(crate) surface: S,
34 pub(crate) poc: i32,
35 #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
36 pub(crate) timestamp: i64,
37 pub(crate) mark: Mark,
38 /// Still to be handed to the caller.
39 pub(crate) output: bool,
40}
41
42impl<S> StoredPicture<S> {
43 pub(crate) fn stored(&self) -> bool {
44 self.output || self.mark != Mark::Unused
45 }
46}
47
48/// The reference picture set of the picture being decoded, as DPB indices.
49#[derive(Debug, Default, Clone)]
50pub(crate) struct Rps {
51 pub(crate) st_curr_before: Vec<usize>,
52 pub(crate) st_curr_after: Vec<usize>,
53 pub(crate) lt_curr: Vec<usize>,
54}
55
56/// The decoded picture buffer and the cross-picture state of 8.3.1 and C.5.2.
57pub(crate) struct Dpb<S> {
58 pub(crate) pictures: Vec<StoredPicture<S>>,
59 /// `prevTid0Pic`'s picture order count, for the MSB derivation of 8.3.1.
60 pub(crate) prev_tid0_poc: i32,
61 /// Set once a picture has been decoded since the last reset.
62 pub(crate) started: bool,
63 pub(crate) max_reorder: usize,
64 pub(crate) max_dec_pic_buffering: usize,
65}
66
67impl<S> Dpb<S> {
68 pub(crate) fn new() -> Dpb<S> {
69 Dpb {
70 pictures: Vec::new(),
71 prev_tid0_poc: 0,
72 started: false,
73 max_reorder: 1,
74 max_dec_pic_buffering: 6,
75 }
76 }
77
78 /// `PicOrderCntVal` (8.3.1).
79 pub(crate) fn picture_order_count(
80 &self,
81 sps: &Sps,
82 sh: &SliceHeader,
83 nal_type: NalUnitType,
84 ) -> i32 {
85 if nal_type.is_idr() {
86 return 0;
87 }
88 let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
89 let lsb = sh.poc_lsb as i32;
90 let (prev_msb, prev_lsb) = if !self.started {
91 (0, 0)
92 } else {
93 (
94 self.prev_tid0_poc - (self.prev_tid0_poc.rem_euclid(max_lsb)),
95 self.prev_tid0_poc.rem_euclid(max_lsb),
96 )
97 };
98 // An IRAP that starts a new coded video sequence has no predecessor.
99 if nal_type.is_irap() && !self.started {
100 return lsb;
101 }
102 let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
103 prev_msb + max_lsb
104 } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
105 prev_msb - max_lsb
106 } else {
107 prev_msb
108 };
109 msb + lsb
110 }
111
112 /// Reference picture set derivation and marking (8.3.2).
113 pub(crate) fn apply_rps(
114 &mut self,
115 sps: &Sps,
116 sh: &SliceHeader,
117 nal_type: NalUnitType,
118 poc: i32,
119 ) -> Result<Rps> {
120 if nal_type.is_irap() && (nal_type.is_idr() || !self.started) {
121 for pic in &mut self.pictures {
122 pic.mark = Mark::Unused;
123 }
124 self.pictures.retain(|p| p.stored());
125 return Ok(Rps::default());
126 }
127
128 let set = &sh.short_term_ref_pic_set;
129 let max_lsb = 1i32 << (sps.log2_max_poc_lsb_minus4 + 4);
130 let mut wanted: Vec<(i32, bool, bool)> = Vec::new(); // (poc, used, long term)
131 for i in 0..set.num_negative as usize {
132 wanted.push((poc + set.delta_poc_s0[i], set.used_s0[i], false));
133 }
134 for i in 0..set.num_positive as usize {
135 wanted.push((poc + set.delta_poc_s1[i], set.used_s1[i], false));
136 }
137 for lt in &sh.long_term {
138 // 8.3.2: a long-term entry without an MSB cycle is matched on its
139 // POC low bits alone, which is how a stream survives an MSB wrap.
140 let target = if lt.delta_poc_msb_present {
141 poc - (lt.delta_poc_msb_cycle as i32) * max_lsb - poc.rem_euclid(max_lsb)
142 + lt.poc_lsb_lt as i32
143 } else {
144 lt.poc_lsb_lt as i32
145 };
146 wanted.push((target, lt.used_by_curr, !lt.delta_poc_msb_present));
147 }
148
149 let mut rps = Rps::default();
150 let mut keep = vec![false; self.pictures.len()];
151 let mut missing_used = false;
152 for (target, used, lsb_only) in wanted {
153 let found = self.pictures.iter().position(|p| {
154 if lsb_only {
155 p.poc.rem_euclid(max_lsb) == target.rem_euclid(max_lsb)
156 } else {
157 p.poc == target
158 }
159 });
160 let Some(idx) = found else {
161 // 8.3.2: a picture the current one predicts from must be in the
162 // buffer. One that is not is a broken GOP, and a reference list
163 // built without it would name a surface that was never decoded.
164 missing_used |= used;
165 continue;
166 };
167 keep[idx] = true;
168 if !used {
169 continue;
170 }
171 // The three "current" lists are what the reference lists are built
172 // from, in POC order relative to the current picture.
173 if self.pictures[idx].mark == Mark::LongTerm || lsb_only {
174 rps.lt_curr.push(idx);
175 } else if self.pictures[idx].poc < poc {
176 rps.st_curr_before.push(idx);
177 } else {
178 rps.st_curr_after.push(idx);
179 }
180 }
181 rps.st_curr_before
182 .sort_by_key(|&i| std::cmp::Reverse(self.pictures[i].poc));
183 rps.st_curr_after.sort_by_key(|&i| self.pictures[i].poc);
184
185 for (i, pic) in self.pictures.iter_mut().enumerate() {
186 if !keep[i] {
187 pic.mark = Mark::Unused;
188 }
189 }
190 // Dropping unreferenced, already-output pictures here is what returns
191 // their surfaces to the pool; the indices in `rps` are recomputed after.
192 let mut remap = vec![usize::MAX; self.pictures.len()];
193 let mut next = 0usize;
194 for (i, pic) in self.pictures.iter().enumerate() {
195 if pic.stored() {
196 remap[i] = next;
197 next += 1;
198 }
199 }
200 self.pictures.retain(|p| p.stored());
201 if missing_used {
202 return Err(Error::Stream(ec_core::Error::corrupt(
203 "HEVC reference picture set names a picture used for prediction that was never decoded",
204 )));
205 }
206 for list in [
207 &mut rps.st_curr_before,
208 &mut rps.st_curr_after,
209 &mut rps.lt_curr,
210 ] {
211 list.retain(|&i| remap[i] != usize::MAX);
212 for entry in list.iter_mut() {
213 *entry = remap[*entry];
214 }
215 }
216 Ok(rps)
217 }
218 /// The next picture to output (C.5.2.4), while the buffer holds more than
219 /// its reordering or storage limit allows; `flush` outputs every one.
220 pub(crate) fn next_output(&self, flush: bool) -> Option<usize> {
221 let pending = self.pictures.iter().filter(|p| p.output).count();
222 let stored = self.pictures.iter().filter(|p| p.stored()).count();
223 if !flush && pending <= self.max_reorder && stored <= self.max_dec_pic_buffering {
224 return None;
225 }
226 self.pictures
227 .iter()
228 .enumerate()
229 .filter(|(_, p)| p.output)
230 .min_by_key(|(_, p)| p.poc)
231 .map(|(i, _)| i)
232 }
233
234 /// Marks the picture at `idx` as output and drops it once it is not stored.
235 pub(crate) fn released(&mut self, idx: usize) {
236 self.pictures[idx].output = false;
237 self.pictures.retain(|p| p.stored());
238 }
239}
240
241/// True unless the NAL type says sub-layer non-reference (`_N`, an even type
242/// below 16).
243pub(crate) fn is_reference_picture(nal_type: NalUnitType) -> bool {
244 let code = nal_type.code();
245 code >= 16 || code % 2 == 1
246}
247
248/// RADL (6, 7) and RASL (8, 9): the leading pictures of an IRAP, which 8.3.1
249/// excludes from the picture order count prediction.
250pub(crate) fn is_leading_picture(nal_type: NalUnitType) -> bool {
251 (6..=9).contains(&nal_type.code())
252}
253
254/// An SPS's VUI `colour_description` and range flag, as [`Tags`] for
255/// [`ColorDescription::resolve`]. [`Tags::default()`] when the VUI has no
256/// `video_signal_type` at all.
257#[cfg_attr(not(target_os = "linux"), allow(dead_code))]
258pub(crate) fn vui_colour_tags(sps: &Sps) -> Tags {
259 let Some(vst) = sps.vui.as_ref().and_then(|vui| vui.video_signal_type) else {
260 return Tags::default();
261 };
262 let (_primaries, transfer, matrix) = vst
263 .colour_description
264 .map(|cd| {
265 (
266 cd.colour_primaries,
267 cd.transfer_characteristics,
268 cd.matrix_coeffs,
269 )
270 })
271 .unwrap_or((0, 0, 0));
272 Tags::from_codes(
273 u64::from(matrix),
274 u64::from(transfer),
275 if vst.video_full_range_flag { 2 } else { 1 },
276 )
277}
278
279/// RASL_N and RASL_R (8, 9): leading pictures dropped whole when their IRAP's
280/// `NoRaslOutputFlag` is 1 (8.1.3).
281pub(crate) fn is_rasl_picture(nal_type: NalUnitType) -> bool {
282 matches!(nal_type.code(), 8 | 9)
283}
284
285/// BLA_W_LP, BLA_W_RADL and BLA_N_LP (16..=18): always `NoRaslOutputFlag` 1
286/// (8.1.3), a broken-link splice point that never has a decodable RASL.
287pub(crate) fn is_bla_picture(nal_type: NalUnitType) -> bool {
288 (16..=18).contains(&nal_type.code())
289}
290
291/// `slice_pic_parameter_set_id`, readable without any parameter set.
292pub(crate) fn peek_pps_id(rbsp: &[u8], nal_type: NalUnitType) -> Result<u32> {
293 let mut r = ec_core::BitReader::new(rbsp);
294 r.read_bit()?; // first_slice_segment_in_pic_flag
295 if nal_type.is_irap() {
296 r.read_bit()?; // no_output_of_prior_pics_flag
297 }
298 Ok(r.read_ue()?)
299}