forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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