edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·cbbd6e2·Tahinli·2 months ago·2369 commits
| 1 | //! Decoded picture buffer (spec clause 8.2): picture storage, picture order |
| 2 | //! count, reference marking, reference list construction and output order. |
| 3 | //! |
| 4 | //! The buffer owns every decoded picture, including the one being decoded — the |
| 5 | //! decoder holds that one *out* of the pool while a picture is open, which is |
| 6 | //! what lets motion compensation borrow reference planes immutably while |
| 7 | //! writing the current planes mutably. |
| 8 | //! |
| 9 | //! Pictures are pooled, never freed: a picture that is neither referenced nor |
| 10 | //! awaiting output goes back on the free list with its plane and motion |
| 11 | //! allocations intact, so a steady-state decode loop reuses the same buffers |
| 12 | //! forever and allocates nothing. |
| 13 | //! |
| 14 | //! Output order is display order. Every picture leaves through the bumping |
| 15 | //! process of clause C.4.5.3 — smallest picture order count first, released |
| 16 | //! when the buffer is over its reordering or storage limit — so a stream with |
| 17 | //! B pictures comes out in the order a player has to present it, not the order |
| 18 | //! it was coded in. |
| 19 | |
| 20 | use ec_core::error::{Error, Result}; |
| 21 | use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps}; |
| 22 | |
| 23 | /// Luma plane padding on every side, sized for inter-prediction filter |
| 24 | /// overreach: a 16-wide partition plus the two/three sample reach of the 6-tap |
| 25 | /// filter, rounded up. |
| 26 | pub(crate) const PAD_Y: usize = 32; |
| 27 | /// Chroma plane padding on every side (8-wide block plus one bilinear tap). |
| 28 | pub(crate) const PAD_C: usize = 16; |
| 29 | /// `mb_slice` value for a not-yet-decoded macroblock. |
| 30 | pub(crate) const NO_SLICE: u16 = u16::MAX; |
| 31 | /// Hard cap on stored pictures: 16 reference frames (Annex A) plus the current. |
| 32 | const MAX_STORED: usize = 17; |
| 33 | |
| 34 | /// Per-4x4-block flags recorded for inter neighbour derivation. |
| 35 | /// The block belongs to an intra macroblock. |
| 36 | pub(crate) const BLK_INTRA: u8 = 1; |
| 37 | /// The block belongs to a P_Skip or B_Skip macroblock. |
| 38 | pub(crate) const BLK_SKIP: u8 = 2; |
| 39 | /// The block is predicted in direct mode (B_Skip, B_Direct_16x16 or a |
| 40 | /// B_Direct_8x8 sub-macroblock). |
| 41 | pub(crate) const BLK_DIRECT: u8 = 4; |
| 42 | |
| 43 | /// Reference marking of a stored picture (clause 8.2.5). |
| 44 | #[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] |
| 45 | pub(crate) enum Mark { |
| 46 | /// "unused for reference". |
| 47 | #[default] |
| 48 | Unused, |
| 49 | /// "used for short-term reference". |
| 50 | Short, |
| 51 | /// "used for long-term reference". |
| 52 | Long, |
| 53 | } |
| 54 | |
| 55 | /// A padded 8-bit plane. |
| 56 | #[derive(Debug, Default)] |
| 57 | pub(crate) struct Plane8 { |
| 58 | pub data: Vec<u8>, |
| 59 | pub stride: usize, |
| 60 | /// Index of sample (0, 0) of the picture. |
| 61 | pub origin: usize, |
| 62 | pub width: usize, |
| 63 | pub height: usize, |
| 64 | pub pad: usize, |
| 65 | } |
| 66 | |
| 67 | impl Plane8 { |
| 68 | fn resize(&mut self, width: usize, height: usize, pad: usize) { |
| 69 | self.stride = width + 2 * pad; |
| 70 | self.origin = pad * self.stride + pad; |
| 71 | self.width = width; |
| 72 | self.height = height; |
| 73 | self.pad = pad; |
| 74 | self.data.clear(); |
| 75 | self.data.resize(self.stride * (height + 2 * pad), 0); |
| 76 | } |
| 77 | |
| 78 | #[inline] |
| 79 | pub(crate) fn at(&self, x: usize, y: usize) -> usize { |
| 80 | self.origin + y * self.stride + x |
| 81 | } |
| 82 | |
| 83 | /// Replicate the edge samples into the padding, which turns the per-sample |
| 84 | /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see |
| 85 | /// [`crate::inter`]). |
| 86 | fn extend_borders(&mut self) { |
| 87 | let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride); |
| 88 | for y in 0..h { |
| 89 | let row = self.origin + y * stride; |
| 90 | let (left, right) = (self.data[row], self.data[row + w - 1]); |
| 91 | self.data[row - pad..row].fill(left); |
| 92 | self.data[row + w..row + w + pad].fill(right); |
| 93 | } |
| 94 | let full = self.origin - pad; |
| 95 | for y in 0..pad { |
| 96 | let (src, dst) = (full, full - (y + 1) * stride); |
| 97 | self.data.copy_within(src..src + stride, dst); |
| 98 | let src = full + (h - 1) * stride; |
| 99 | self.data |
| 100 | .copy_within(src..src + stride, src + (y + 1) * stride); |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | /// Per-slice values the deblocking filter needs after slice decode ends. |
| 106 | #[derive(Debug, Clone, Copy)] |
| 107 | pub(crate) struct SliceParams { |
| 108 | pub disable_deblock_idc: u8, |
| 109 | pub alpha_offset: i32, |
| 110 | pub beta_offset: i32, |
| 111 | pub cb_qp_offset: i32, |
| 112 | pub cr_qp_offset: i32, |
| 113 | } |
| 114 | |
| 115 | /// Flat per-picture decode context. |
| 116 | /// |
| 117 | /// All per-macroblock and per-4x4-block state lives in struct-of-arrays keyed |
| 118 | /// by macroblock address or 4x4-block coordinate: no per-macroblock heap |
| 119 | /// objects anywhere, and the whole picture is one reusable allocation set. |
| 120 | #[derive(Debug, Default)] |
| 121 | pub(crate) struct Picture { |
| 122 | pub sps_id: u8, |
| 123 | pub mb_w: usize, |
| 124 | pub mb_h: usize, |
| 125 | pub y: Plane8, |
| 126 | pub cb: Plane8, |
| 127 | pub cr: Plane8, |
| 128 | /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. |
| 129 | pub nz_y: Vec<u8>, |
| 130 | /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. |
| 131 | pub nz_c: [Vec<u8>; 2], |
| 132 | /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). |
| 133 | pub i4_modes: Vec<u8>, |
| 134 | /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). |
| 135 | pub mb_qp: Vec<u8>, |
| 136 | /// `FLAG_*` bits per macroblock. |
| 137 | pub mb_flags: Vec<u8>, |
| 138 | /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock. |
| 139 | pub mb_cbp: Vec<u8>, |
| 140 | /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb, 2 Cr. |
| 141 | pub mb_dc_cbf: Vec<u8>, |
| 142 | /// Owning slice index per macroblock, `NO_SLICE` when undecoded. |
| 143 | pub mb_slice: Vec<u16>, |
| 144 | /// `MvLX[..][..]` per luma 4x4 block, `[list][component]`, quarter samples. |
| 145 | pub mv: Vec<[[i16; 2]; 2]>, |
| 146 | /// `RefIdxLX` per luma 4x4 block, -1 when the list is not used. |
| 147 | pub ref_idx: Vec<[i8; 2]>, |
| 148 | /// Identity ([`Picture::id`]) of the referenced picture per list, -1 when |
| 149 | /// unused. Reference *indices* are per slice, so only the picture identity |
| 150 | /// answers "same reference picture?" for boundary strength (8.7.2.1) and |
| 151 | /// `MapColToList0` (8.4.1.2.3). |
| 152 | pub ref_id: Vec<[i32; 2]>, |
| 153 | /// `Abs( mvd_lX[..][..][comp] )` per block, `[l0x, l0y, l1x, l1y]`, |
| 154 | /// saturated (the thresholds of 9.3.3.1.1.7 are 2 and 32). |
| 155 | pub mvd_abs: Vec<[u8; 4]>, |
| 156 | /// `BLK_*` flags per luma 4x4 block. |
| 157 | pub blk: Vec<u8>, |
| 158 | pub slices: Vec<SliceParams>, |
| 159 | pub decoded_mbs: usize, |
| 160 | pub complete: bool, |
| 161 | |
| 162 | // ---- clause 8.2 picture state ---- |
| 163 | /// Stream-unique identity, assigned when the picture is started. |
| 164 | pub id: i32, |
| 165 | /// `PicOrderCnt( )` of the frame. |
| 166 | pub poc: i32, |
| 167 | pub frame_num: u32, |
| 168 | /// `FrameNumWrap` (8-27), recomputed for every decoded picture. |
| 169 | pub frame_num_wrap: i32, |
| 170 | /// `PicNum` (8-28) for short-term, `LongTermPicNum` (8-29) for long-term. |
| 171 | pub pic_num: i32, |
| 172 | pub long_term_frame_idx: u32, |
| 173 | pub mark: Mark, |
| 174 | /// The picture has not been output yet. |
| 175 | pub output: bool, |
| 176 | /// Inferred by the frame_num gap process of 8.2.5.2 rather than decoded. |
| 177 | pub non_existing: bool, |
| 178 | /// `FrameNumOffset` (8-6 / 8-11), carried to the next picture. |
| 179 | pub frame_num_offset: i32, |
| 180 | /// `PicOrderCntMsb` (8-3), carried to the next picture for POC type 0. |
| 181 | pub poc_msb: i32, |
| 182 | /// `pic_order_cnt_lsb` as coded, carried alongside `poc_msb`. |
| 183 | pub poc_lsb: i32, |
| 184 | /// Presentation timestamp of the access unit this picture came from. It |
| 185 | /// travels with the picture rather than with the packet, because display |
| 186 | /// order reorders the two apart. |
| 187 | pub pts: Option<ec_core::timebase::Timestamp>, |
| 188 | /// Cropped output size and the crop origin, in luma samples. A stored |
| 189 | /// picture describes its own output geometry so that emitting it needs no |
| 190 | /// lookup back into the parameter sets — which a later sequence may have |
| 191 | /// replaced by then. |
| 192 | pub out_size: (u32, u32), |
| 193 | pub crop: (u32, u32), |
| 194 | /// Colour description carried from the VUI. |
| 195 | pub color: ec_core::frame::ColorInfo, |
| 196 | } |
| 197 | |
| 198 | impl Picture { |
| 199 | /// Reset for a new picture of `sps`'s geometry, reallocating only when the |
| 200 | /// geometry actually changed. |
| 201 | pub(crate) fn start(&mut self, sps: &Sps) { |
| 202 | let mb_w = sps.mb_width as usize; |
| 203 | let mb_h = sps.mb_height as usize; |
| 204 | if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { |
| 205 | self.mb_w = mb_w; |
| 206 | self.mb_h = mb_h; |
| 207 | self.sps_id = sps.id; |
| 208 | self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); |
| 209 | self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); |
| 210 | self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); |
| 211 | let blocks = mb_w * mb_h * 16; |
| 212 | self.nz_y.resize(blocks, 0); |
| 213 | for c in &mut self.nz_c { |
| 214 | c.resize(mb_w * mb_h * 4, 0); |
| 215 | } |
| 216 | self.i4_modes.resize(blocks, 2); |
| 217 | self.mb_qp.resize(mb_w * mb_h, 0); |
| 218 | self.mb_flags.resize(mb_w * mb_h, 0); |
| 219 | self.mb_cbp.resize(mb_w * mb_h, 0); |
| 220 | self.mb_dc_cbf.resize(mb_w * mb_h, 0); |
| 221 | self.mb_slice.resize(mb_w * mb_h, NO_SLICE); |
| 222 | self.mv.resize(blocks, [[0; 2]; 2]); |
| 223 | self.ref_idx.resize(blocks, [-1; 2]); |
| 224 | self.ref_id.resize(blocks, [-1; 2]); |
| 225 | self.mvd_abs.resize(blocks, [0; 4]); |
| 226 | self.blk.resize(blocks, 0); |
| 227 | } |
| 228 | // Per-MB metadata is rewritten by each decoded macroblock; only the |
| 229 | // "who is decoded" state must be wiped between pictures. |
| 230 | self.mb_slice.fill(NO_SLICE); |
| 231 | self.mb_flags.fill(0); |
| 232 | self.slices.clear(); |
| 233 | self.decoded_mbs = 0; |
| 234 | self.complete = false; |
| 235 | self.mark = Mark::Unused; |
| 236 | self.output = false; |
| 237 | self.non_existing = false; |
| 238 | self.long_term_frame_idx = 0; |
| 239 | self.frame_num_wrap = 0; |
| 240 | self.pic_num = 0; |
| 241 | self.out_size = (sps.width, sps.height); |
| 242 | self.crop = (sps.crop.0, sps.crop.2); |
| 243 | self.color = ec_core::frame::ColorInfo::default(); |
| 244 | if let Some(vui) = &sps.vui { |
| 245 | self.color.full_range = vui.video_full_range; |
| 246 | if let Some((p, t, m)) = vui.colour_description { |
| 247 | self.color.primaries = p; |
| 248 | self.color.transfer = t; |
| 249 | self.color.matrix = m; |
| 250 | } |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | /// Replicate every plane's borders once the picture is fully reconstructed. |
| 255 | pub(crate) fn extend_borders(&mut self) { |
| 256 | self.y.extend_borders(); |
| 257 | self.cb.extend_borders(); |
| 258 | self.cr.extend_borders(); |
| 259 | } |
| 260 | |
| 261 | /// Fill the picture with mid-grey, for a frame the stream never sent. |
| 262 | fn fill_grey(&mut self) { |
| 263 | self.y.data.fill(128); |
| 264 | self.cb.data.fill(128); |
| 265 | self.cr.data.fill(128); |
| 266 | } |
| 267 | |
| 268 | fn copy_samples_from(&mut self, src: &Picture) { |
| 269 | self.y.data.copy_from_slice(&src.y.data); |
| 270 | self.cb.data.copy_from_slice(&src.cb.data); |
| 271 | self.cr.data.copy_from_slice(&src.cr.data); |
| 272 | } |
| 273 | |
| 274 | /// True while the picture occupies a decoded picture buffer slot. |
| 275 | fn stored(&self) -> bool { |
| 276 | self.mark != Mark::Unused || self.output |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | /// One reference picture list (`RefPicList0` / `RefPicList1`). |
| 281 | /// |
| 282 | /// Entries are indices into [`Dpb::frames`]; the list is a fixed array because |
| 283 | /// Annex A caps it at 32 entries, so building it allocates nothing. |
| 284 | #[derive(Clone, Copy, Debug)] |
| 285 | pub(crate) struct RefList { |
| 286 | entries: [u8; 33], |
| 287 | len: usize, |
| 288 | } |
| 289 | |
| 290 | impl Default for RefList { |
| 291 | fn default() -> RefList { |
| 292 | RefList { |
| 293 | entries: [0; 33], |
| 294 | len: 0, |
| 295 | } |
| 296 | } |
| 297 | } |
| 298 | |
| 299 | impl RefList { |
| 300 | pub(crate) fn len(&self) -> usize { |
| 301 | self.len |
| 302 | } |
| 303 | |
| 304 | /// The DPB index of `RefPicListX[idx]`, `None` past the end. |
| 305 | #[inline] |
| 306 | pub(crate) fn get(&self, idx: usize) -> Option<usize> { |
| 307 | (idx < self.len).then(|| usize::from(self.entries[idx])) |
| 308 | } |
| 309 | |
| 310 | fn push(&mut self, idx: usize) { |
| 311 | if self.len < self.entries.len() { |
| 312 | self.entries[self.len] = idx as u8; |
| 313 | self.len += 1; |
| 314 | } |
| 315 | } |
| 316 | } |
| 317 | |
| 318 | /// The decoded picture buffer and the clause 8.2 state that spans pictures. |
| 319 | pub(crate) struct Dpb { |
| 320 | /// Stored pictures, in no particular order. |
| 321 | pub frames: Vec<Picture>, |
| 322 | /// Recycled picture buffers. |
| 323 | free: Vec<Picture>, |
| 324 | next_id: i32, |
| 325 | /// `max_dec_frame_buffering`. |
| 326 | max_frames: usize, |
| 327 | /// `max_num_reorder_frames`. |
| 328 | max_reorder: usize, |
| 329 | /// `MaxLongTermFrameIdx`, `None` = "no long-term frame indices". |
| 330 | max_long_term_idx: Option<u32>, |
| 331 | // Picture order count state (8.2.1). |
| 332 | prev_poc_msb: i32, |
| 333 | prev_poc_lsb: i32, |
| 334 | prev_frame_num: u32, |
| 335 | prev_frame_num_offset: i32, |
| 336 | prev_has_mmco5: bool, |
| 337 | /// `PrevRefFrameNum` for the gap detection of 8.2.5.2. |
| 338 | prev_ref_frame_num: u32, |
| 339 | /// Set once a picture has been decoded since the last reset. |
| 340 | started: bool, |
| 341 | /// Everything stored before [`Dpb::last_id`] must be output before it. |
| 342 | pending_flush: bool, |
| 343 | /// Identity of the most recently stored picture. |
| 344 | last_id: i32, |
| 345 | } |
| 346 | |
| 347 | impl Default for Dpb { |
| 348 | fn default() -> Dpb { |
| 349 | Dpb { |
| 350 | frames: Vec::new(), |
| 351 | free: Vec::new(), |
| 352 | next_id: 0, |
| 353 | max_frames: 16, |
| 354 | max_reorder: 16, |
| 355 | max_long_term_idx: None, |
| 356 | prev_poc_msb: 0, |
| 357 | prev_poc_lsb: 0, |
| 358 | prev_frame_num: 0, |
| 359 | prev_frame_num_offset: 0, |
| 360 | prev_has_mmco5: false, |
| 361 | prev_ref_frame_num: 0, |
| 362 | started: false, |
| 363 | pending_flush: false, |
| 364 | last_id: -1, |
| 365 | } |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | /// Output of the picture order count derivation (clause 8.2.1). |
| 370 | #[derive(Clone, Copy, Debug, Default)] |
| 371 | pub(crate) struct Poc { |
| 372 | /// `PicOrderCnt( )` of the frame. |
| 373 | pub value: i32, |
| 374 | /// `FrameNumOffset`, predicted from by the next picture. |
| 375 | pub frame_num_offset: i32, |
| 376 | /// `PicOrderCntMsb` (POC type 0 only). |
| 377 | pub msb: i32, |
| 378 | /// `pic_order_cnt_lsb` (POC type 0 only). |
| 379 | pub lsb: i32, |
| 380 | } |
| 381 | |
| 382 | /// Everything about the current picture the DPB needs, gathered from the first |
| 383 | /// slice header of that picture. |
| 384 | #[derive(Clone, Copy, Debug)] |
| 385 | pub(crate) struct PicInfo { |
| 386 | pub is_idr: bool, |
| 387 | pub is_reference: bool, |
| 388 | pub frame_num: u32, |
| 389 | pub pic_order_cnt_lsb: u32, |
| 390 | pub delta_pic_order_cnt_bottom: i32, |
| 391 | pub delta_pic_order_cnt: [i32; 2], |
| 392 | } |
| 393 | |
| 394 | impl Dpb { |
| 395 | /// Adopt the buffer limits of `sps` (Annex A / VUI), keeping whatever is |
| 396 | /// already stored. |
| 397 | pub(crate) fn configure(&mut self, sps: &Sps) { |
| 398 | let level_frames = max_dpb_frames(sps); |
| 399 | let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) { |
| 400 | Some(r) => ( |
| 401 | (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1), |
| 402 | (r.max_num_reorder_frames as usize).min(MAX_STORED - 1), |
| 403 | ), |
| 404 | // Without the VUI restriction the level limit is all we know. It |
| 405 | // over-buffers a low-delay stream, which costs latency but never |
| 406 | // order: pictures still leave smallest-POC-first. |
| 407 | None => (level_frames, level_frames), |
| 408 | }; |
| 409 | self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1); |
| 410 | self.max_reorder = reorder.min(self.max_frames); |
| 411 | } |
| 412 | |
| 413 | /// A picture buffer to decode into, off the free list when possible. |
| 414 | pub(crate) fn take_picture(&mut self) -> Picture { |
| 415 | let mut pic = self.free.pop().unwrap_or_default(); |
| 416 | pic.id = self.next_id; |
| 417 | self.next_id = self.next_id.wrapping_add(1); |
| 418 | pic |
| 419 | } |
| 420 | |
| 421 | /// Hand a picture buffer back for reuse. |
| 422 | pub(crate) fn recycle(&mut self, pic: Picture) { |
| 423 | if self.free.len() < MAX_STORED { |
| 424 | self.free.push(pic); |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | /// Drop every stored picture (seek / stream discontinuity). |
| 429 | pub(crate) fn clear(&mut self) { |
| 430 | while let Some(pic) = self.frames.pop() { |
| 431 | self.recycle(pic); |
| 432 | } |
| 433 | self.max_long_term_idx = None; |
| 434 | self.prev_poc_msb = 0; |
| 435 | self.prev_poc_lsb = 0; |
| 436 | self.prev_frame_num = 0; |
| 437 | self.prev_frame_num_offset = 0; |
| 438 | self.prev_has_mmco5 = false; |
| 439 | self.prev_ref_frame_num = 0; |
| 440 | self.started = false; |
| 441 | self.pending_flush = false; |
| 442 | self.last_id = -1; |
| 443 | } |
| 444 | |
| 445 | /// `PicOrderCnt( )` of a picture about to be decoded (clause 8.2.1), |
| 446 | /// together with the `FrameNumOffset` and `PicOrderCntMsb` the next |
| 447 | /// picture predicts from. |
| 448 | pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result<Poc> { |
| 449 | match sps.pic_order_cnt_type { |
| 450 | 0 => { |
| 451 | let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb; |
| 452 | let (prev_msb, prev_lsb) = if info.is_idr { |
| 453 | (0, 0) |
| 454 | } else { |
| 455 | (self.prev_poc_msb, self.prev_poc_lsb) |
| 456 | }; |
| 457 | let lsb = info.pic_order_cnt_lsb as i32; |
| 458 | let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { |
| 459 | prev_msb + max_lsb |
| 460 | } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { |
| 461 | prev_msb - max_lsb |
| 462 | } else { |
| 463 | prev_msb |
| 464 | }; |
| 465 | let top = msb + lsb; |
| 466 | let bottom = top + info.delta_pic_order_cnt_bottom; |
| 467 | Ok(Poc { |
| 468 | value: top.min(bottom), |
| 469 | frame_num_offset: 0, |
| 470 | msb, |
| 471 | lsb, |
| 472 | }) |
| 473 | } |
| 474 | 1 => { |
| 475 | let max_frame_num = 1i32 << sps.log2_max_frame_num; |
| 476 | let offset = self.frame_num_offset(info, max_frame_num); |
| 477 | let cycle_len = sps.offsets_for_ref_frame.len() as i32; |
| 478 | let mut abs_frame_num = if cycle_len != 0 { |
| 479 | offset + info.frame_num as i32 |
| 480 | } else { |
| 481 | 0 |
| 482 | }; |
| 483 | if !info.is_reference && abs_frame_num > 0 { |
| 484 | abs_frame_num -= 1; |
| 485 | } |
| 486 | let mut expected = 0i32; |
| 487 | if abs_frame_num > 0 { |
| 488 | let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum(); |
| 489 | let cycle_cnt = (abs_frame_num - 1) / cycle_len; |
| 490 | let in_cycle = (abs_frame_num - 1) % cycle_len; |
| 491 | expected = cycle_cnt.wrapping_mul(expected_delta); |
| 492 | for i in 0..=in_cycle as usize { |
| 493 | expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]); |
| 494 | } |
| 495 | } |
| 496 | if !info.is_reference { |
| 497 | expected = expected.wrapping_add(sps.offset_for_non_ref_pic); |
| 498 | } |
| 499 | let top = expected.wrapping_add(info.delta_pic_order_cnt[0]); |
| 500 | let bottom = top |
| 501 | .wrapping_add(sps.offset_for_top_to_bottom_field) |
| 502 | .wrapping_add(info.delta_pic_order_cnt[1]); |
| 503 | Ok(Poc { |
| 504 | value: top.min(bottom), |
| 505 | frame_num_offset: offset, |
| 506 | msb: 0, |
| 507 | lsb: 0, |
| 508 | }) |
| 509 | } |
| 510 | 2 => { |
| 511 | let max_frame_num = 1i32 << sps.log2_max_frame_num; |
| 512 | let offset = self.frame_num_offset(info, max_frame_num); |
| 513 | let poc = if info.is_idr { |
| 514 | 0 |
| 515 | } else if !info.is_reference { |
| 516 | 2 * (offset + info.frame_num as i32) - 1 |
| 517 | } else { |
| 518 | 2 * (offset + info.frame_num as i32) |
| 519 | }; |
| 520 | Ok(Poc { |
| 521 | value: poc, |
| 522 | frame_num_offset: offset, |
| 523 | msb: 0, |
| 524 | lsb: 0, |
| 525 | }) |
| 526 | } |
| 527 | other => Err(Error::corrupt(format!("pic_order_cnt_type {other}"))), |
| 528 | } |
| 529 | } |
| 530 | |
| 531 | /// `FrameNumOffset` (Equations 8-6 and 8-11). |
| 532 | fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 { |
| 533 | if info.is_idr { |
| 534 | return 0; |
| 535 | } |
| 536 | let prev = if self.prev_has_mmco5 { |
| 537 | 0 |
| 538 | } else { |
| 539 | self.prev_frame_num_offset |
| 540 | }; |
| 541 | if self.prev_frame_num > info.frame_num { |
| 542 | prev + max_frame_num |
| 543 | } else { |
| 544 | prev |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | /// True when `frame_num` skips values, i.e. pictures are missing |
| 549 | /// (clause 8.2.5.2). Editor seeks and lossy transports both produce this; |
| 550 | /// it is a normal condition, not a corrupt stream. |
| 551 | pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool { |
| 552 | let max = 1u32 << sps.log2_max_frame_num; |
| 553 | self.started |
| 554 | && frame_num != self.prev_ref_frame_num |
| 555 | && frame_num != (self.prev_ref_frame_num + 1) % max |
| 556 | } |
| 557 | |
| 558 | /// Insert the "non-existing" frames of clause 8.2.5.2 for a frame_num gap, |
| 559 | /// so that reference numbering stays aligned with the encoder's and the |
| 560 | /// pictures that follow decode instead of being dropped. |
| 561 | pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> { |
| 562 | let max = 1u32 << sps.log2_max_frame_num; |
| 563 | let mut unused = (self.prev_ref_frame_num + 1) % max; |
| 564 | // A gap can be as wide as MaxFrameNum; every inferred frame costs a |
| 565 | // sliding-window step, so bound the work at the buffer size. |
| 566 | let mut budget = MAX_STORED; |
| 567 | while unused != frame_num && budget > 0 { |
| 568 | budget -= 1; |
| 569 | let mut pic = self.take_picture(); |
| 570 | pic.start(sps); |
| 571 | // The samples are unspecified; the last reference picture is a far |
| 572 | // better guess than grey when a later picture wrongly predicts |
| 573 | // from the gap. |
| 574 | match self.frames.iter().max_by_key(|p| p.frame_num_wrap) { |
| 575 | Some(src) if src.y.data.len() == pic.y.data.len() => pic.copy_samples_from(src), |
| 576 | _ => pic.fill_grey(), |
| 577 | } |
| 578 | pic.non_existing = true; |
| 579 | pic.frame_num = unused; |
| 580 | pic.output = false; |
| 581 | pic.complete = true; |
| 582 | let info = PicInfo { |
| 583 | is_idr: false, |
| 584 | is_reference: true, |
| 585 | frame_num: unused, |
| 586 | pic_order_cnt_lsb: 0, |
| 587 | delta_pic_order_cnt_bottom: 0, |
| 588 | delta_pic_order_cnt: [0; 2], |
| 589 | }; |
| 590 | // 8.2.5.2: picture order count is only derived for a non-existing |
| 591 | // frame when pic_order_cnt_type is not 0. Under type 0 the frame |
| 592 | // has no output order, and 8.2.4.2.3 keeps it out of the B lists. |
| 593 | let poc = if sps.pic_order_cnt_type == 0 { |
| 594 | Poc::default() |
| 595 | } else { |
| 596 | self.picture_order_count(sps, &info)? |
| 597 | }; |
| 598 | pic.poc = poc.value; |
| 599 | pic.frame_num_offset = poc.frame_num_offset; |
| 600 | pic.mark = Mark::Short; |
| 601 | self.number_short_term(unused, sps); |
| 602 | self.sliding_window(sps)?; |
| 603 | pic.frame_num_wrap = unused as i32; |
| 604 | pic.pic_num = unused as i32; |
| 605 | self.frames.push(pic); |
| 606 | self.prev_frame_num = unused; |
| 607 | self.prev_frame_num_offset = poc.frame_num_offset; |
| 608 | self.prev_has_mmco5 = false; |
| 609 | self.prev_ref_frame_num = unused; |
| 610 | unused = (unused + 1) % max; |
| 611 | } |
| 612 | Ok(()) |
| 613 | } |
| 614 | |
| 615 | /// Recompute `FrameNumWrap` and `PicNum` for every stored reference |
| 616 | /// picture against the current `frame_num` (clause 8.2.4.1). |
| 617 | pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) { |
| 618 | let max_frame_num = 1i32 << sps.log2_max_frame_num; |
| 619 | for pic in &mut self.frames { |
| 620 | match pic.mark { |
| 621 | Mark::Short => { |
| 622 | pic.frame_num_wrap = if pic.frame_num > frame_num { |
| 623 | pic.frame_num as i32 - max_frame_num |
| 624 | } else { |
| 625 | pic.frame_num as i32 |
| 626 | }; |
| 627 | pic.pic_num = pic.frame_num_wrap; |
| 628 | } |
| 629 | Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32, |
| 630 | Mark::Unused => {} |
| 631 | } |
| 632 | } |
| 633 | } |
| 634 | |
| 635 | /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation |
| 636 | /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). |
| 637 | #[allow(clippy::too_many_arguments)] |
| 638 | pub(crate) fn build_ref_lists( |
| 639 | &self, |
| 640 | slice_type: SliceType, |
| 641 | curr_poc: i32, |
| 642 | curr_pic_num: i32, |
| 643 | max_pic_num: i32, |
| 644 | num_l0: usize, |
| 645 | num_l1: usize, |
| 646 | mods: (&[RefPicListMod], &[RefPicListMod]), |
| 647 | ) -> Result<([RefList; 2], bool)> { |
| 648 | let mut padded = false; |
| 649 | let mut lists = [RefList::default(), RefList::default()]; |
| 650 | // Short-term candidates, then long-term, both by index into `frames`. |
| 651 | let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; |
| 652 | let mut n_short = 0usize; |
| 653 | let mut long: [usize; MAX_STORED] = [0; MAX_STORED]; |
| 654 | let mut n_long = 0usize; |
| 655 | for (i, pic) in self.frames.iter().enumerate() { |
| 656 | // A frame inferred for a frame_num gap has no output order, so it |
| 657 | // cannot take part in the POC ordering a B list is built from |
| 658 | // (8.2.4.2.3); it stays a legal P reference by PicNum. |
| 659 | if pic.non_existing && slice_type == SliceType::B { |
| 660 | continue; |
| 661 | } |
| 662 | match pic.mark { |
| 663 | Mark::Short if n_short < MAX_STORED => { |
| 664 | short[n_short] = i; |
| 665 | n_short += 1; |
| 666 | } |
| 667 | Mark::Long if n_long < MAX_STORED => { |
| 668 | long[n_long] = i; |
| 669 | n_long += 1; |
| 670 | } |
| 671 | _ => {} |
| 672 | } |
| 673 | } |
| 674 | let long = &mut long[..n_long]; |
| 675 | long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx); |
| 676 | |
| 677 | if slice_type == SliceType::B { |
| 678 | let short = &mut short[..n_short]; |
| 679 | // List 0: earlier pictures by descending POC, then later ascending. |
| 680 | short.sort_unstable_by_key(|&i| { |
| 681 | let poc = self.frames[i].poc; |
| 682 | if poc < curr_poc { |
| 683 | (0i32, -poc) |
| 684 | } else { |
| 685 | (1, poc) |
| 686 | } |
| 687 | }); |
| 688 | for &i in short.iter() { |
| 689 | lists[0].push(i); |
| 690 | } |
| 691 | for &i in long.iter() { |
| 692 | lists[0].push(i); |
| 693 | } |
| 694 | // List 1: later pictures by ascending POC, then earlier descending. |
| 695 | short.sort_unstable_by_key(|&i| { |
| 696 | let poc = self.frames[i].poc; |
| 697 | if poc > curr_poc { |
| 698 | (0i32, poc) |
| 699 | } else { |
| 700 | (1, -poc) |
| 701 | } |
| 702 | }); |
| 703 | for &i in short.iter() { |
| 704 | lists[1].push(i); |
| 705 | } |
| 706 | for &i in long.iter() { |
| 707 | lists[1].push(i); |
| 708 | } |
| 709 | // 8.2.4.2.3 step 3. |
| 710 | if lists[1].len > 1 |
| 711 | && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] |
| 712 | { |
| 713 | lists[1].entries.swap(0, 1); |
| 714 | } |
| 715 | } else { |
| 716 | let short = &mut short[..n_short]; |
| 717 | short.sort_unstable_by_key(|&i| -self.frames[i].pic_num); |
| 718 | for &i in short.iter() { |
| 719 | lists[0].push(i); |
| 720 | } |
| 721 | for &i in long.iter() { |
| 722 | lists[0].push(i); |
| 723 | } |
| 724 | } |
| 725 | |
| 726 | let wanted = [num_l0, num_l1]; |
| 727 | let mods = [mods.0, mods.1]; |
| 728 | for x in 0..2 { |
| 729 | if x == 1 && slice_type != SliceType::B { |
| 730 | lists[1].len = 0; |
| 731 | continue; |
| 732 | } |
| 733 | if lists[x].len == 0 { |
| 734 | return Err(Error::corrupt("inter slice with an empty reference list")); |
| 735 | } |
| 736 | // 8.2.4.2: the initial list is truncated to the active count. A |
| 737 | // list shorter than that leaves the tail unspecified, and a |
| 738 | // conformant stream fills it by modification; repeating entry 0 |
| 739 | // keeps every index in range meanwhile. |
| 740 | let first = lists[x].entries[0]; |
| 741 | if lists[x].len < wanted[x] { |
| 742 | padded = true; |
| 743 | } |
| 744 | while lists[x].len < wanted[x] { |
| 745 | lists[x].push(usize::from(first)); |
| 746 | } |
| 747 | lists[x].len = wanted[x]; |
| 748 | self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); |
| 749 | } |
| 750 | Ok((lists, padded)) |
| 751 | } |
| 752 | |
| 753 | /// Reference picture list modification (clause 8.2.4.3), following the |
| 754 | /// insert-and-compact of Equations 8-37 and 8-38 with the one-longer |
| 755 | /// temporary list those equations use. |
| 756 | /// |
| 757 | /// Comparing DPB indices stands in for `PicNumF`/`LongTermPicNumF`: a |
| 758 | /// picture appears in the buffer once, and the sentinel those functions |
| 759 | /// return for a wrongly marked picture can never equal the target. |
| 760 | fn modify_list( |
| 761 | &self, |
| 762 | list: &mut RefList, |
| 763 | mods: &[RefPicListMod], |
| 764 | curr_pic_num: i32, |
| 765 | max_pic_num: i32, |
| 766 | ) { |
| 767 | if mods.is_empty() { |
| 768 | return; |
| 769 | } |
| 770 | let active = list.len; |
| 771 | let mut tmp = [0u8; 34]; |
| 772 | tmp[..active].copy_from_slice(&list.entries[..active]); |
| 773 | let mut pred = curr_pic_num; |
| 774 | let mut ref_idx = 0usize; |
| 775 | for op in mods { |
| 776 | let target = match *op { |
| 777 | RefPicListMod::ShortTerm { |
| 778 | abs_diff_pic_num_minus1, |
| 779 | add, |
| 780 | } => { |
| 781 | let diff = abs_diff_pic_num_minus1 as i32 + 1; |
| 782 | let no_wrap = if add { |
| 783 | if pred + diff >= max_pic_num { |
| 784 | pred + diff - max_pic_num |
| 785 | } else { |
| 786 | pred + diff |
| 787 | } |
| 788 | } else if pred - diff < 0 { |
| 789 | pred - diff + max_pic_num |
| 790 | } else { |
| 791 | pred - diff |
| 792 | }; |
| 793 | pred = no_wrap; |
| 794 | let pic_num = if no_wrap > curr_pic_num { |
| 795 | no_wrap - max_pic_num |
| 796 | } else { |
| 797 | no_wrap |
| 798 | }; |
| 799 | self.frames |
| 800 | .iter() |
| 801 | .position(|p| p.mark == Mark::Short && p.pic_num == pic_num) |
| 802 | } |
| 803 | RefPicListMod::LongTerm(num) => self |
| 804 | .frames |
| 805 | .iter() |
| 806 | .position(|p| p.mark == Mark::Long && p.pic_num == num as i32), |
| 807 | }; |
| 808 | // A modification naming a picture the buffer never received points |
| 809 | // at something that was lost; keeping the initial entry decodes a |
| 810 | // seek or a dropped packet instead of failing the slice. |
| 811 | let Some(target) = target else { continue }; |
| 812 | if ref_idx >= active { |
| 813 | break; |
| 814 | } |
| 815 | for c in (ref_idx + 1..=active).rev() { |
| 816 | tmp[c] = tmp[c - 1]; |
| 817 | } |
| 818 | tmp[ref_idx] = target as u8; |
| 819 | ref_idx += 1; |
| 820 | let mut n = ref_idx; |
| 821 | for c in ref_idx..=active { |
| 822 | if usize::from(tmp[c]) != target { |
| 823 | tmp[n] = tmp[c]; |
| 824 | n += 1; |
| 825 | } |
| 826 | } |
| 827 | } |
| 828 | list.entries[..active].copy_from_slice(&tmp[..active]); |
| 829 | list.len = active; |
| 830 | } |
| 831 | |
| 832 | /// Store a decoded picture and apply the reference marking of 8.2.5. |
| 833 | /// |
| 834 | /// `output_ok` is false for a picture that predicted from a reference |
| 835 | /// never decoded since the last `reset()` (a random-access leading |
| 836 | /// picture whose ref list build had to pad) — it still joins the DPB, as |
| 837 | /// a reference for later pictures and for `PicNum`/`FrameNumWrap` |
| 838 | /// bookkeeping, but the bumping process must never hand it to a caller. |
| 839 | pub(crate) fn store( |
| 840 | &mut self, |
| 841 | mut pic: Picture, |
| 842 | sps: &Sps, |
| 843 | info: &PicInfo, |
| 844 | marking: Option<&DecRefPicMarking>, |
| 845 | output_ok: bool, |
| 846 | ) -> Result<()> { |
| 847 | let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); |
| 848 | pic.output = output_ok; |
| 849 | pic.complete = true; |
| 850 | // Clause 8.2.4.1 against this picture's frame_num, which is what both |
| 851 | // the sliding window (8.2.5.3) and the MMCO picture numbers (8.2.5.4) |
| 852 | // compare. An intra slice never built a reference list, so this is the |
| 853 | // only place the numbering is guaranteed to be current — and the |
| 854 | // picture being stored has no FrameNumWrap of its own until now. |
| 855 | self.number_short_term(info.frame_num, sps); |
| 856 | pic.frame_num_wrap = pic.frame_num as i32; |
| 857 | pic.pic_num = pic.frame_num as i32; |
| 858 | |
| 859 | if info.is_idr { |
| 860 | let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics); |
| 861 | self.drain_prior(no_output); |
| 862 | pic.mark = Mark::Short; |
| 863 | if marking.is_some_and(|m| m.long_term_reference) { |
| 864 | pic.mark = Mark::Long; |
| 865 | pic.long_term_frame_idx = 0; |
| 866 | self.max_long_term_idx = Some(0); |
| 867 | } else { |
| 868 | self.max_long_term_idx = None; |
| 869 | } |
| 870 | } else if info.is_reference { |
| 871 | let m = marking.expect("a reference picture carries dec_ref_pic_marking"); |
| 872 | pic.mark = Mark::Short; |
| 873 | if m.adaptive { |
| 874 | self.apply_mmco(&mut pic, m, info)?; |
| 875 | } else { |
| 876 | self.sliding_window(sps)?; |
| 877 | } |
| 878 | } |
| 879 | |
| 880 | if has_mmco5 { |
| 881 | // 8.2.1: an MMCO 5 restarts frame_num and picture order count at |
| 882 | // this picture, so everything before it must leave first. |
| 883 | pic.poc = 0; |
| 884 | pic.frame_num = 0; |
| 885 | pic.frame_num_offset = 0; |
| 886 | pic.poc_msb = 0; |
| 887 | pic.poc_lsb = 0; |
| 888 | } |
| 889 | |
| 890 | self.prev_frame_num = pic.frame_num; |
| 891 | self.prev_frame_num_offset = pic.frame_num_offset; |
| 892 | self.prev_has_mmco5 = has_mmco5; |
| 893 | if info.is_reference { |
| 894 | self.prev_ref_frame_num = pic.frame_num; |
| 895 | self.prev_poc_msb = pic.poc_msb; |
| 896 | self.prev_poc_lsb = pic.poc_lsb; |
| 897 | } |
| 898 | self.started = true; |
| 899 | // An IDR or an MMCO 5 restarts picture order count, so POC no longer |
| 900 | // orders across the boundary: everything already in the buffer belongs |
| 901 | // ahead of this picture and has to leave first. |
| 902 | if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) { |
| 903 | self.pending_flush = true; |
| 904 | } |
| 905 | self.last_id = pic.id; |
| 906 | |
| 907 | if self.frames.len() >= MAX_STORED { |
| 908 | // Every stored picture is either a reference or waiting to be |
| 909 | // output, and both limits were enforced above; a stream that still |
| 910 | // overflows is not conformant. |
| 911 | return Err(Error::corrupt("decoded picture buffer overflow")); |
| 912 | } |
| 913 | self.frames.push(pic); |
| 914 | Ok(()) |
| 915 | } |
| 916 | |
| 917 | /// Output and remove every stored picture (IDR boundary or MMCO 5). |
| 918 | fn drain_prior(&mut self, discard: bool) { |
| 919 | for pic in &mut self.frames { |
| 920 | pic.mark = Mark::Unused; |
| 921 | if discard { |
| 922 | pic.output = false; |
| 923 | } |
| 924 | } |
| 925 | } |
| 926 | |
| 927 | /// Sliding window marking (clause 8.2.5.3). |
| 928 | fn sliding_window(&mut self, sps: &Sps) -> Result<()> { |
| 929 | let max_refs = (sps.max_num_ref_frames as usize).max(1); |
| 930 | loop { |
| 931 | let n = self |
| 932 | .frames |
| 933 | .iter() |
| 934 | .filter(|p| p.mark != Mark::Unused) |
| 935 | .count(); |
| 936 | if n < max_refs { |
| 937 | return Ok(()); |
| 938 | } |
| 939 | let Some(oldest) = self |
| 940 | .frames |
| 941 | .iter_mut() |
| 942 | .filter(|p| p.mark == Mark::Short) |
| 943 | .min_by_key(|p| p.frame_num_wrap) |
| 944 | else { |
| 945 | // Only long-term references left and the window is full: the |
| 946 | // stream must free one by MMCO, so refusing here would break a |
| 947 | // conformant stream. Leave the buffer as is. |
| 948 | return Ok(()); |
| 949 | }; |
| 950 | oldest.mark = Mark::Unused; |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | /// Adaptive marking (clause 8.2.5.4). |
| 955 | fn apply_mmco( |
| 956 | &mut self, |
| 957 | pic: &mut Picture, |
| 958 | m: &DecRefPicMarking, |
| 959 | info: &PicInfo, |
| 960 | ) -> Result<()> { |
| 961 | let curr_pic_num = info.frame_num as i32; |
| 962 | for op in &m.mmcos { |
| 963 | match op.op { |
| 964 | 1 => { |
| 965 | let target = curr_pic_num - (op.arg1 as i32 + 1); |
| 966 | if let Some(p) = self |
| 967 | .frames |
| 968 | .iter_mut() |
| 969 | .find(|p| p.mark == Mark::Short && p.pic_num == target) |
| 970 | { |
| 971 | p.mark = Mark::Unused; |
| 972 | } |
| 973 | } |
| 974 | 2 => { |
| 975 | if let Some(p) = self |
| 976 | .frames |
| 977 | .iter_mut() |
| 978 | .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32) |
| 979 | { |
| 980 | p.mark = Mark::Unused; |
| 981 | } |
| 982 | } |
| 983 | 3 => { |
| 984 | let target = curr_pic_num - (op.arg1 as i32 + 1); |
| 985 | let idx = op.arg2; |
| 986 | for p in &mut self.frames { |
| 987 | if p.mark == Mark::Long && p.long_term_frame_idx == idx { |
| 988 | p.mark = Mark::Unused; |
| 989 | } |
| 990 | } |
| 991 | if let Some(p) = self |
| 992 | .frames |
| 993 | .iter_mut() |
| 994 | .find(|p| p.mark == Mark::Short && p.pic_num == target) |
| 995 | { |
| 996 | p.mark = Mark::Long; |
| 997 | p.long_term_frame_idx = idx; |
| 998 | p.pic_num = idx as i32; |
| 999 | } |
| 1000 | } |
| 1001 | 4 => { |
| 1002 | self.max_long_term_idx = op.arg1.checked_sub(1); |
| 1003 | let limit = self.max_long_term_idx; |
| 1004 | for p in &mut self.frames { |
| 1005 | if p.mark == Mark::Long |
| 1006 | && limit.is_none_or(|max| p.long_term_frame_idx > max) |
| 1007 | { |
| 1008 | p.mark = Mark::Unused; |
| 1009 | } |
| 1010 | } |
| 1011 | } |
| 1012 | 5 => { |
| 1013 | for p in &mut self.frames { |
| 1014 | p.mark = Mark::Unused; |
| 1015 | } |
| 1016 | self.max_long_term_idx = None; |
| 1017 | } |
| 1018 | 6 => { |
| 1019 | let idx = op.arg1; |
| 1020 | for p in &mut self.frames { |
| 1021 | if p.mark == Mark::Long && p.long_term_frame_idx == idx { |
| 1022 | p.mark = Mark::Unused; |
| 1023 | } |
| 1024 | } |
| 1025 | pic.mark = Mark::Long; |
| 1026 | pic.long_term_frame_idx = idx; |
| 1027 | pic.pic_num = idx as i32; |
| 1028 | } |
| 1029 | other => { |
| 1030 | return Err(Error::corrupt(format!( |
| 1031 | "memory_management_control_operation {other}" |
| 1032 | ))); |
| 1033 | } |
| 1034 | } |
| 1035 | } |
| 1036 | Ok(()) |
| 1037 | } |
| 1038 | |
| 1039 | /// The next picture to output, or `None` while the buffer is still within |
| 1040 | /// its reordering and storage limits (the bumping process of C.4.5.3). |
| 1041 | /// |
| 1042 | /// `flush` empties the buffer, which is what end of stream and a seek do. |
| 1043 | pub(crate) fn next_output(&mut self, flush: bool) -> Option<usize> { |
| 1044 | if self.pending_flush { |
| 1045 | let last = self.last_id; |
| 1046 | let best = self |
| 1047 | .frames |
| 1048 | .iter() |
| 1049 | .enumerate() |
| 1050 | .filter(|(_, p)| p.output && p.id != last) |
| 1051 | .min_by_key(|(_, p)| p.poc) |
| 1052 | .map(|(i, _)| i); |
| 1053 | if best.is_some() { |
| 1054 | return best; |
| 1055 | } |
| 1056 | self.pending_flush = false; |
| 1057 | } |
| 1058 | let pending = self.frames.iter().filter(|p| p.output).count(); |
| 1059 | let stored = self.frames.iter().filter(|p| p.stored()).count(); |
| 1060 | if !flush && pending <= self.max_reorder && stored <= self.max_frames { |
| 1061 | return None; |
| 1062 | } |
| 1063 | let mut best: Option<usize> = None; |
| 1064 | for (i, pic) in self.frames.iter().enumerate() { |
| 1065 | if !pic.output { |
| 1066 | continue; |
| 1067 | } |
| 1068 | if best.is_none_or(|b| pic.poc < self.frames[b].poc) { |
| 1069 | best = Some(i); |
| 1070 | } |
| 1071 | } |
| 1072 | best |
| 1073 | } |
| 1074 | |
| 1075 | /// Mark picture `idx` as output and reclaim every slot that is now free. |
| 1076 | pub(crate) fn released(&mut self, idx: usize) { |
| 1077 | self.frames[idx].output = false; |
| 1078 | let mut i = 0; |
| 1079 | while i < self.frames.len() { |
| 1080 | if self.frames[i].stored() { |
| 1081 | i += 1; |
| 1082 | continue; |
| 1083 | } |
| 1084 | let pic = self.frames.swap_remove(i); |
| 1085 | self.recycle(pic); |
| 1086 | } |
| 1087 | } |
| 1088 | } |
| 1089 | |
| 1090 | /// `MaxDpbFrames` from the level limits of Table A-1, the buffer size a stream |
| 1091 | /// is allowed to assume when its VUI does not state one. |
| 1092 | fn max_dpb_frames(sps: &Sps) -> usize { |
| 1093 | let max_dpb_mbs = match sps.level_idc { |
| 1094 | 0..=10 => 396, |
| 1095 | 11 => { |
| 1096 | // constraint_set3_flag distinguishes level 1b from level 1.1; both |
| 1097 | // have the same MaxDpbMbs, so the flag does not change the answer. |
| 1098 | 396 |
| 1099 | } |
| 1100 | 12..=20 => 2376, |
| 1101 | 21 => 4752, |
| 1102 | 22..=30 => 8100, |
| 1103 | 31 => 18000, |
| 1104 | 32 => 20480, |
| 1105 | 33..=41 => 32768, |
| 1106 | 42 => 34816, |
| 1107 | 50 => 110400, |
| 1108 | 51..=52 => 184320, |
| 1109 | _ => 696320, |
| 1110 | }; |
| 1111 | let per_frame = (sps.mb_width as usize * sps.mb_height as usize).max(1); |
| 1112 | (max_dpb_mbs / per_frame).clamp(1, 16) |
| 1113 | } |
| 1114 | |
| 1115 | #[cfg(test)] |
| 1116 | mod tests { |
| 1117 | use super::*; |
| 1118 | |
| 1119 | fn plane(w: usize, h: usize) -> Plane8 { |
| 1120 | let mut p = Plane8::default(); |
| 1121 | p.resize(w, h, 4); |
| 1122 | for y in 0..h { |
| 1123 | for x in 0..w { |
| 1124 | let at = p.at(x, y); |
| 1125 | p.data[at] = (x + y * 10) as u8; |
| 1126 | } |
| 1127 | } |
| 1128 | p |
| 1129 | } |
| 1130 | |
| 1131 | /// Border replication makes an out-of-picture read equal the clipped |
| 1132 | /// in-picture read, which is what [`crate::inter`] relies on. |
| 1133 | #[test] |
| 1134 | fn extend_borders_replicates_edges() { |
| 1135 | let mut p = plane(6, 5); |
| 1136 | p.extend_borders(); |
| 1137 | let at = |
| 1138 | |x: i32, y: i32| -> u8 { p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] }; |
| 1139 | for y in -4..9i32 { |
| 1140 | for x in -4..10i32 { |
| 1141 | let cx = x.clamp(0, 5) as usize; |
| 1142 | let cy = y.clamp(0, 4) as usize; |
| 1143 | assert_eq!(at(x, y), p.data[p.at(cx, cy)], "({x}, {y})"); |
| 1144 | } |
| 1145 | } |
| 1146 | } |
| 1147 | |
| 1148 | fn sps_for(poc_type: u8) -> Sps { |
| 1149 | use ec_core::BitWriter; |
| 1150 | let mut w = BitWriter::new(); |
| 1151 | w.write_bits(66, 8); |
| 1152 | w.write_bits(0, 8); |
| 1153 | w.write_bits(30, 8); |
| 1154 | w.write_ue(0); // sps id |
| 1155 | w.write_ue(4); // log2_max_frame_num_minus4 -> 8 |
| 1156 | w.write_ue(u32::from(poc_type)); |
| 1157 | match poc_type { |
| 1158 | 0 => w.write_ue(4), // log2_max_pic_order_cnt_lsb_minus4 -> 8 |
| 1159 | 1 => { |
| 1160 | w.write_bit(false); // delta_pic_order_always_zero |
| 1161 | w.write_se(0); |
| 1162 | w.write_se(0); |
| 1163 | w.write_ue(1); // one offset_for_ref_frame |
| 1164 | w.write_se(2); |
| 1165 | } |
| 1166 | _ => {} |
| 1167 | } |
| 1168 | w.write_ue(2); // max_num_ref_frames |
| 1169 | w.write_bit(false); |
| 1170 | w.write_ue(10); |
| 1171 | w.write_ue(8); |
| 1172 | w.write_bit(true); // frame_mbs_only |
| 1173 | w.write_bit(true); // direct_8x8_inference |
| 1174 | w.write_bit(false); // no cropping |
| 1175 | w.write_bit(false); // no vui |
| 1176 | w.align_to_byte(); |
| 1177 | Sps::parse(w.as_bytes()).unwrap() |
| 1178 | } |
| 1179 | |
| 1180 | fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo { |
| 1181 | PicInfo { |
| 1182 | is_idr, |
| 1183 | is_reference: is_ref, |
| 1184 | frame_num, |
| 1185 | pic_order_cnt_lsb: lsb, |
| 1186 | delta_pic_order_cnt_bottom: 0, |
| 1187 | delta_pic_order_cnt: [0; 2], |
| 1188 | } |
| 1189 | } |
| 1190 | |
| 1191 | /// Picture order count type 0 wraps when pic_order_cnt_lsb rolls over. |
| 1192 | #[test] |
| 1193 | fn poc_type_0_tracks_the_msb_across_a_wrap() { |
| 1194 | let sps = sps_for(0); |
| 1195 | let mut dpb = Dpb::default(); |
| 1196 | let mut expect = |i: PicInfo, want: i32| { |
| 1197 | let poc = dpb.picture_order_count(&sps, &i).unwrap(); |
| 1198 | assert_eq!(poc.value, want, "{i:?}"); |
| 1199 | // Emulate the reference-picture bookkeeping of `store`. |
| 1200 | if i.is_reference { |
| 1201 | dpb.prev_poc_msb = poc.msb; |
| 1202 | dpb.prev_poc_lsb = poc.lsb; |
| 1203 | } |
| 1204 | }; |
| 1205 | expect(info(0, 0, true, true), 0); |
| 1206 | expect(info(1, 100, true, false), 100); |
| 1207 | expect(info(2, 200, true, false), 200); |
| 1208 | // 200 -> 40 is more than half of MaxPicOrderCntLsb backwards, so it is |
| 1209 | // read as a wrap forward rather than a jump back. |
| 1210 | expect(info(3, 40, true, false), 296); |
| 1211 | // A genuine step back stays a step back. |
| 1212 | expect(info(4, 100, true, false), 356); |
| 1213 | } |
| 1214 | |
| 1215 | /// Type 2 counts pictures in decode order, so a non-reference picture sits |
| 1216 | /// just before the reference picture that follows it. |
| 1217 | #[test] |
| 1218 | fn poc_type_2_is_twice_the_frame_number() { |
| 1219 | let sps = sps_for(2); |
| 1220 | let dpb = Dpb::default(); |
| 1221 | assert_eq!( |
| 1222 | dpb.picture_order_count(&sps, &info(0, 0, true, true)) |
| 1223 | .unwrap() |
| 1224 | .value, |
| 1225 | 0 |
| 1226 | ); |
| 1227 | assert_eq!( |
| 1228 | dpb.picture_order_count(&sps, &info(3, 0, true, false)) |
| 1229 | .unwrap() |
| 1230 | .value, |
| 1231 | 6 |
| 1232 | ); |
| 1233 | assert_eq!( |
| 1234 | dpb.picture_order_count(&sps, &info(3, 0, false, false)) |
| 1235 | .unwrap() |
| 1236 | .value, |
| 1237 | 5 |
| 1238 | ); |
| 1239 | } |
| 1240 | |
| 1241 | /// Type 1 walks the offset_for_ref_frame cycle. |
| 1242 | #[test] |
| 1243 | fn poc_type_1_follows_the_offset_cycle() { |
| 1244 | let sps = sps_for(1); |
| 1245 | let dpb = Dpb::default(); |
| 1246 | // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n. |
| 1247 | assert_eq!( |
| 1248 | dpb.picture_order_count(&sps, &info(0, 0, true, true)) |
| 1249 | .unwrap() |
| 1250 | .value, |
| 1251 | 0 |
| 1252 | ); |
| 1253 | assert_eq!( |
| 1254 | dpb.picture_order_count(&sps, &info(1, 0, true, false)) |
| 1255 | .unwrap() |
| 1256 | .value, |
| 1257 | 2 |
| 1258 | ); |
| 1259 | assert_eq!( |
| 1260 | dpb.picture_order_count(&sps, &info(4, 0, true, false)) |
| 1261 | .unwrap() |
| 1262 | .value, |
| 1263 | 8 |
| 1264 | ); |
| 1265 | } |
| 1266 | |
| 1267 | fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { |
| 1268 | let mut pic = dpb.take_picture(); |
| 1269 | pic.frame_num = frame_num; |
| 1270 | pic.frame_num_wrap = frame_num as i32; |
| 1271 | pic.pic_num = frame_num as i32; |
| 1272 | pic.poc = poc; |
| 1273 | pic.mark = mark; |
| 1274 | dpb.frames.push(pic); |
| 1275 | } |
| 1276 | |
| 1277 | /// P list 0 is short-term by descending PicNum then long-term ascending. |
| 1278 | #[test] |
| 1279 | fn p_list_initialisation_orders_by_pic_num() { |
| 1280 | let mut dpb = Dpb::default(); |
| 1281 | push_ref(&mut dpb, 2, 4, Mark::Short); |
| 1282 | push_ref(&mut dpb, 5, 10, Mark::Short); |
| 1283 | push_ref(&mut dpb, 3, 6, Mark::Short); |
| 1284 | let mut lt = dpb.take_picture(); |
| 1285 | lt.mark = Mark::Long; |
| 1286 | lt.long_term_frame_idx = 1; |
| 1287 | lt.pic_num = 1; |
| 1288 | dpb.frames.push(lt); |
| 1289 | let (lists, _) = dpb |
| 1290 | .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[])) |
| 1291 | .unwrap(); |
| 1292 | let nums: Vec<i32> = (0..lists[0].len()) |
| 1293 | .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) |
| 1294 | .collect(); |
| 1295 | assert_eq!(nums, vec![5, 3, 2, 1]); |
| 1296 | } |
| 1297 | |
| 1298 | /// B lists split around the current POC and mirror each other. |
| 1299 | #[test] |
| 1300 | fn b_list_initialisation_splits_around_the_current_poc() { |
| 1301 | let mut dpb = Dpb::default(); |
| 1302 | push_ref(&mut dpb, 0, 0, Mark::Short); |
| 1303 | push_ref(&mut dpb, 1, 8, Mark::Short); |
| 1304 | push_ref(&mut dpb, 2, 4, Mark::Short); |
| 1305 | push_ref(&mut dpb, 3, 12, Mark::Short); |
| 1306 | let (lists, _) = dpb |
| 1307 | .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) |
| 1308 | .unwrap(); |
| 1309 | let poc = |l: &RefList| -> Vec<i32> { |
| 1310 | (0..l.len()) |
| 1311 | .map(|i| dpb.frames[l.get(i).unwrap()].poc) |
| 1312 | .collect() |
| 1313 | }; |
| 1314 | assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); |
| 1315 | assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); |
| 1316 | } |
| 1317 | |
| 1318 | /// A single-entry list identical in both directions gets its first two |
| 1319 | /// entries swapped (8.2.4.2.3 step 3 only fires above one entry). |
| 1320 | #[test] |
| 1321 | fn identical_b_lists_swap_the_first_two_entries() { |
| 1322 | let mut dpb = Dpb::default(); |
| 1323 | push_ref(&mut dpb, 0, 0, Mark::Short); |
| 1324 | push_ref(&mut dpb, 1, 2, Mark::Short); |
| 1325 | // Both references precede the current picture, so initialisation gives |
| 1326 | // list 0 and list 1 the same descending-POC order. |
| 1327 | let (lists, _) = dpb |
| 1328 | .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) |
| 1329 | .unwrap(); |
| 1330 | let l0: Vec<i32> = (0..2) |
| 1331 | .map(|i| dpb.frames[lists[0].get(i).unwrap()].poc) |
| 1332 | .collect(); |
| 1333 | let l1: Vec<i32> = (0..2) |
| 1334 | .map(|i| dpb.frames[lists[1].get(i).unwrap()].poc) |
| 1335 | .collect(); |
| 1336 | assert_eq!(l0, vec![2, 0]); |
| 1337 | assert_eq!(l1, vec![0, 2], "identical lists swap"); |
| 1338 | } |
| 1339 | |
| 1340 | /// A short-term modification moves the named picture to the front. |
| 1341 | #[test] |
| 1342 | fn short_term_modification_reorders_the_list() { |
| 1343 | let mut dpb = Dpb::default(); |
| 1344 | push_ref(&mut dpb, 5, 10, Mark::Short); |
| 1345 | push_ref(&mut dpb, 4, 8, Mark::Short); |
| 1346 | push_ref(&mut dpb, 3, 6, Mark::Short); |
| 1347 | // CurrPicNum 6, abs_diff 3 -> picNum 3, which is the last entry. |
| 1348 | let mods = [RefPicListMod::ShortTerm { |
| 1349 | abs_diff_pic_num_minus1: 2, |
| 1350 | add: false, |
| 1351 | }]; |
| 1352 | let (lists, _) = dpb |
| 1353 | .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[])) |
| 1354 | .unwrap(); |
| 1355 | let nums: Vec<i32> = (0..3) |
| 1356 | .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) |
| 1357 | .collect(); |
| 1358 | assert_eq!(nums, vec![3, 5, 4]); |
| 1359 | } |
| 1360 | } |