forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

dpb.rs320 lines, 10.5 KiBHistoryRawDownload
1//! The decoded picture buffer and output order (C.5.2): storage, marking, the
2//! bumping process, and the frames handed to the caller.
3
4use std::collections::VecDeque;
5use std::sync::Arc;
6
7use super::meta::PictureMeta;
8use super::shared::SharedPic;
9use crate::decode::DecodedPicture;
10use ec_core::error::Result;
11use ec_h265_syntax::sei::{ContentLightLevel, MasteringDisplay, PictureHash};
12use ec_h265_syntax::{ColourDescription, ConformanceWindow, Sps};
13
14/// Reference marking of a buffered picture (8.3.2).
15#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16pub enum Marking {
17 /// Not used for reference: it can only wait for output.
18 Unused,
19 /// Used for short-term reference.
20 ShortTerm,
21 /// Used for long-term reference.
22 LongTerm,
23}
24
25/// One picture in the decoded picture buffer.
26#[derive(Debug, Clone)]
27pub struct DpbPicture {
28 /// Identity within this decoder; stable for the picture's whole life.
29 pub id: u32,
30 /// `PicOrderCntVal`.
31 pub poc: i32,
32 /// Reference marking.
33 pub marking: Marking,
34 /// `PicOutputFlag` still owed: the picture waits for the bumping process.
35 pub needed_for_output: bool,
36 /// `PicLatencyCount` (C.5.2.3).
37 pub latency: u32,
38 /// Decode-order index of the access unit this picture came from. Generated
39 /// (8.3.3) pictures carry `u32::MAX`.
40 pub au_index: u32,
41 /// Cropping of the SPS the picture was decoded under.
42 pub window: ConformanceWindow,
43 /// The samples and the collocated motion (8.5.3.2.8). Empty samples when the decoder
44 /// runs without pixel decode. The samples may still be being decoded.
45 pub picture: Arc<SharedPic>,
46 /// HDR, colour and hash metadata of the picture.
47 pub meta: Arc<PictureMeta>,
48}
49
50/// A frame waiting for output. Its samples may still be being decoded; [`PendingFrame::resolve`]
51/// waits for them.
52#[derive(Debug, Clone)]
53pub struct PendingFrame {
54 /// See [`Frame::poc`].
55 pub poc: i32,
56 /// See [`Frame::au_index`].
57 pub au_index: u32,
58 /// See [`Frame::window`].
59 pub window: ConformanceWindow,
60 /// The picture, complete once [`PendingFrame::resolve`] returns.
61 pub picture: Arc<SharedPic>,
62 /// See [`Frame::meta`].
63 pub meta: Arc<PictureMeta>,
64}
65
66impl PendingFrame {
67 /// Wait for the picture to be complete and return it as a [`Frame`].
68 pub fn resolve(self) -> Result<Frame> {
69 let picture = self.picture.snapshot()?;
70 Ok(Frame {
71 poc: self.poc,
72 au_index: self.au_index,
73 window: self.window,
74 picture,
75 meta: self.meta,
76 })
77 }
78}
79
80/// A picture the decoder hands out, in output order.
81#[derive(Debug, Clone)]
82pub struct Frame {
83 /// `PicOrderCntVal` of the picture.
84 pub poc: i32,
85 /// Decode-order index of the access unit (0 for the first picture start).
86 pub au_index: u32,
87 /// Cropping to apply for display.
88 pub window: ConformanceWindow,
89 /// The samples, at the coded size.
90 pub picture: Arc<DecodedPicture>,
91 /// HDR, colour and hash metadata of the picture.
92 pub meta: Arc<PictureMeta>,
93}
94
95impl Frame {
96 /// The picture cropped to the conformance window, at the display size.
97 pub fn cropped(&self) -> DecodedPicture {
98 let p = &self.picture;
99 let (sx, sy) = crate::decode::chroma_shifts(p.chroma_format_idc);
100 let (left, top) = ((self.window.left << sx) as usize, (self.window.top << sy) as usize);
101 let width = p.width - left - ((self.window.right << sx) as usize);
102 let height = p.height - top - ((self.window.bottom << sy) as usize);
103 let crop = |plane: &[u16], stride: usize, x: usize, y: usize, w: usize, h: usize| {
104 (y..y + h)
105 .flat_map(|r| plane[r * stride + x..r * stride + x + w].iter().copied())
106 .collect::<Vec<u16>>()
107 };
108 let cw = p.width >> sx;
109 let chroma = |plane: &[u16]| match plane.is_empty() {
110 true => Vec::new(),
111 false => crop(plane, cw, left >> sx, top >> sy, width >> sx, height >> sy),
112 };
113 DecodedPicture {
114 width,
115 height,
116 bit_depth: p.bit_depth,
117 bit_depth_c: p.bit_depth_c,
118 chroma_format_idc: p.chroma_format_idc,
119 y: crop(&p.y, p.width, left, top, width, height),
120 cb: chroma(&p.cb),
121 cr: chroma(&p.cr),
122 }
123 }
124
125 /// The mastering display colour volume in force for this frame (SEI 137).
126 pub fn mastering_display(&self) -> Option<&MasteringDisplay> {
127 self.meta.mastering_display.as_ref()
128 }
129
130 /// The content light level of this frame: MaxCLL and MaxFALL (SEI 144).
131 pub fn content_light_level(&self) -> Option<&ContentLightLevel> {
132 self.meta.content_light.as_ref()
133 }
134
135 /// `preferred_transfer_characteristics` of the alternative transfer SEI (147).
136 pub fn alternative_transfer_characteristics(&self) -> Option<u8> {
137 self.meta.alternative_transfer
138 }
139
140 /// The VUI colour description of the SPS this frame was decoded under.
141 pub fn colour_description(&self) -> Option<ColourDescription> {
142 self.meta.colour_description
143 }
144
145 /// The VUI `video_full_range_flag` of the SPS this frame was decoded under.
146 pub fn video_full_range_flag(&self) -> Option<bool> {
147 self.meta.video_full_range_flag
148 }
149
150 /// The `decoded_picture_hash` of this frame, when its suffix SEI came.
151 pub fn picture_hash(&self) -> Option<&PictureHash> {
152 self.meta.picture_hash.as_ref()
153 }
154}
155
156/// The buffer sizes and reordering limits of the active SPS at HighestTid.
157#[derive(Debug, Clone, Copy, PartialEq, Eq)]
158pub struct DpbLimits {
159 /// `sps_max_dec_pic_buffering_minus1[HighestTid] + 1`.
160 pub max_dec_pic_buffering: usize,
161 /// `sps_max_num_reorder_pics[HighestTid]`.
162 pub max_num_reorder: usize,
163 /// `sps_max_latency_increase_plus1[HighestTid]`.
164 pub max_latency_plus1: u32,
165}
166
167impl DpbLimits {
168 /// The limits an SPS declares.
169 pub fn from_sps(sps: &Sps) -> DpbLimits {
170 DpbLimits {
171 max_dec_pic_buffering: sps.max_dec_pic_buffering_minus1 as usize + 1,
172 max_num_reorder: sps.max_num_reorder_pics as usize,
173 max_latency_plus1: sps.max_latency_increase_plus1,
174 }
175 }
176
177 /// `SpsMaxLatencyPictures` (C.5.2.1). Meaningful only when `max_latency_plus1` is set.
178 pub fn max_latency_pictures(&self) -> u64 {
179 self.max_num_reorder as u64 + u64::from(self.max_latency_plus1).saturating_sub(1)
180 }
181}
182
183/// The decoded picture buffer. Pictures are addressed by [`DpbPicture::id`].
184#[derive(Debug, Default)]
185pub struct Dpb {
186 pics: Vec<DpbPicture>,
187 next_id: u32,
188}
189
190impl Dpb {
191 /// An empty buffer.
192 pub fn new() -> Dpb {
193 Dpb::default()
194 }
195
196 /// Every buffered picture, in storage order.
197 pub fn pictures(&self) -> &[DpbPicture] {
198 &self.pics
199 }
200
201 /// Mutable access for the picture-level bookkeeping in the decoder.
202 pub fn pictures_mut(&mut self) -> &mut [DpbPicture] {
203 &mut self.pics
204 }
205
206 /// Number of buffered pictures.
207 pub fn len(&self) -> usize {
208 self.pics.len()
209 }
210
211 /// True when nothing is buffered.
212 pub fn is_empty(&self) -> bool {
213 self.pics.is_empty()
214 }
215
216 /// The picture with this id, if still buffered.
217 pub fn get(&self, id: u32) -> Option<&DpbPicture> {
218 self.pics.iter().find(|p| p.id == id)
219 }
220
221 /// Store a picture and return its id.
222 pub fn insert(
223 &mut self,
224 poc: i32,
225 marking: Marking,
226 needed_for_output: bool,
227 picture: Arc<SharedPic>,
228 window: ConformanceWindow,
229 au_index: u32,
230 ) -> u32 {
231 let id = self.next_id;
232 self.next_id = self.next_id.wrapping_add(1);
233 self.pics.push(DpbPicture {
234 id,
235 poc,
236 marking,
237 needed_for_output,
238 latency: 0,
239 au_index,
240 window,
241 picture,
242 meta: Arc::new(PictureMeta::default()),
243 });
244 id
245 }
246
247 /// Attach metadata to a buffered picture by id.
248 pub fn set_meta(&mut self, id: u32, meta: PictureMeta) {
249 if let Some(p) = self.pics.iter_mut().find(|p| p.id == id) {
250 p.meta = Arc::new(meta);
251 }
252 }
253
254 /// Drop every picture, without output.
255 pub fn clear(&mut self) {
256 self.pics.clear();
257 }
258
259 /// Drop pictures that are neither waiting for output nor used for reference (C.5.2.2).
260 pub fn remove_unneeded(&mut self) {
261 self.pics
262 .retain(|p| p.needed_for_output || p.marking != Marking::Unused);
263 }
264
265 /// True when the bumping process must run (C.5.2.2 and C.5.2.3): too many
266 /// pictures waiting for output, a picture past its latency limit, or, when
267 /// `check_fullness` is set, a full buffer.
268 pub fn needs_bumping(&self, limits: &DpbLimits, check_fullness: bool) -> bool {
269 let waiting = self.pics.iter().filter(|p| p.needed_for_output).count();
270 if waiting > limits.max_num_reorder {
271 return true;
272 }
273 if limits.max_latency_plus1 != 0 {
274 let max = limits.max_latency_pictures();
275 if self
276 .pics
277 .iter()
278 .any(|p| p.needed_for_output && u64::from(p.latency) >= max)
279 {
280 return true;
281 }
282 }
283 check_fullness && self.pics.len() >= limits.max_dec_pic_buffering
284 }
285
286 /// One step of the bumping process (C.5.2.4): output the picture with the
287 /// smallest POC among those waiting, and drop it if it is no longer used for
288 /// reference. Returns false when nothing waits for output.
289 pub fn bump(&mut self, out: &mut VecDeque<PendingFrame>) -> bool {
290 let next = self
291 .pics
292 .iter()
293 .enumerate()
294 .filter(|(_, p)| p.needed_for_output)
295 .min_by_key(|(_, p)| p.poc)
296 .map(|(i, _)| i);
297 let Some(idx) = next else {
298 return false;
299 };
300 let pic = &mut self.pics[idx];
301 pic.needed_for_output = false;
302 out.push_back(PendingFrame {
303 poc: pic.poc,
304 au_index: pic.au_index,
305 window: pic.window,
306 picture: Arc::clone(&pic.picture),
307 meta: Arc::clone(&pic.meta),
308 });
309 if pic.marking == Marking::Unused {
310 self.pics.remove(idx);
311 }
312 true
313 }
314
315 /// Output every waiting picture in POC order, then empty the buffer.
316 pub fn drain(&mut self, out: &mut VecDeque<PendingFrame>) {
317 while self.bump(out) {}
318 self.clear();
319 }
320}