forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

dpb264.rs968 lines, 32.8 KiBHistoryRawDownload
1//! The H.264 decoded picture buffer, clause 8.2, over surfaces.
2//!
3//! Same clauses as `ec-h264`'s software DPB — picture order count (8.2.1),
4//! reference numbering (8.2.4.1), list initialisation and modification
5//! (8.2.4.2/8.2.4.3), marking (8.2.5) and bumping (C.4.5.3) — but a stored
6//! picture here is a *surface*, not a plane of samples. A stateless driver is
7//! told the whole buffer on every picture, so these lists are the parameter
8//! buffer's contents rather than an internal detail.
9
10use std::sync::Arc;
11
12use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps};
13
14use crate::error::{Error, Result};
15use crate::pool::PooledSurface;
16
17/// Maximum pictures held at once (Annex A caps the DPB at 16 frames; the extra
18/// slot is the picture being decoded).
19pub(crate) const MAX_STORED: usize = 17;
20
21/// How a stored picture is marked for reference (8.2.5.1).
22#[derive(Clone, Copy, Debug, PartialEq, Eq)]
23pub(crate) enum Mark {
24 /// Not used for reference.
25 Unused,
26 /// Used for short-term reference.
27 Short,
28 /// Used for long-term reference.
29 Long,
30}
31
32/// One picture in the buffer.
33pub(crate) struct Picture {
34 /// Identity, so "the picture just stored" survives reordering.
35 pub id: i32,
36 /// The surface it decoded into.
37 pub surface: Arc<PooledSurface>,
38 /// Presentation timestamp of the access unit it came from.
39 pub timestamp: i64,
40 /// `frame_num`.
41 pub frame_num: u32,
42 /// `FrameNumWrap` (8.2.4.1).
43 pub frame_num_wrap: i32,
44 /// `PicNum` for short-term, `LongTermPicNum` for long-term pictures.
45 pub pic_num: i32,
46 /// `LongTermFrameIdx`.
47 pub long_term_frame_idx: u32,
48 /// `PicOrderCnt()`.
49 pub poc: i32,
50 /// `PicOrderCntMsb`, predicted from by the next picture.
51 pub poc_msb: i32,
52 /// `pic_order_cnt_lsb`.
53 pub poc_lsb: i32,
54 /// `FrameNumOffset`.
55 pub frame_num_offset: i32,
56 /// Reference marking.
57 pub mark: Mark,
58 /// Inferred for a `frame_num` gap (8.2.5.2): a legal P reference with
59 /// unspecified samples, never output.
60 pub non_existing: bool,
61 /// Still waiting to be handed to the caller.
62 pub output: bool,
63}
64
65impl Picture {
66 fn stored(&self) -> bool {
67 self.output || self.mark != Mark::Unused
68 }
69}
70
71/// One reference picture list (`RefPicList0` / `RefPicList1`), as DPB indices.
72#[derive(Clone, Copy, Debug)]
73pub(crate) struct RefList {
74 entries: [u8; 33],
75 len: usize,
76}
77
78impl Default for RefList {
79 fn default() -> RefList {
80 RefList {
81 entries: [0; 33],
82 len: 0,
83 }
84 }
85}
86
87impl RefList {
88 pub(crate) fn len(&self) -> usize {
89 self.len
90 }
91
92 /// The DPB index of `RefPicListX[idx]`, `None` past the end.
93 pub(crate) fn get(&self, idx: usize) -> Option<usize> {
94 (idx < self.len).then(|| usize::from(self.entries[idx]))
95 }
96
97 fn push(&mut self, idx: usize) {
98 if self.len < self.entries.len() {
99 self.entries[self.len] = idx as u8;
100 self.len += 1;
101 }
102 }
103}
104
105/// Output of the picture order count derivation (8.2.1).
106#[derive(Clone, Copy, Debug, Default)]
107pub(crate) struct Poc {
108 pub value: i32,
109 pub frame_num_offset: i32,
110 pub msb: i32,
111 pub lsb: i32,
112}
113
114/// What the DPB needs to know about the picture being decoded, taken from its
115/// first slice header.
116#[derive(Clone, Copy, Debug)]
117pub(crate) struct PicInfo {
118 pub is_idr: bool,
119 pub is_reference: bool,
120 pub frame_num: u32,
121 pub pic_order_cnt_lsb: u32,
122 pub delta_pic_order_cnt_bottom: i32,
123 pub delta_pic_order_cnt: [i32; 2],
124}
125
126/// The decoded picture buffer and the cross-picture state of clause 8.2.
127pub(crate) struct Dpb {
128 pub frames: Vec<Picture>,
129 next_id: i32,
130 max_frames: usize,
131 max_reorder: usize,
132 max_long_term_idx: Option<u32>,
133 prev_poc_msb: i32,
134 prev_poc_lsb: i32,
135 prev_frame_num: u32,
136 prev_frame_num_offset: i32,
137 prev_has_mmco5: bool,
138 prev_ref_frame_num: u32,
139 started: bool,
140 pending_flush: bool,
141 last_id: i32,
142}
143
144impl Default for Dpb {
145 fn default() -> Dpb {
146 Dpb {
147 frames: Vec::new(),
148 next_id: 0,
149 max_frames: 16,
150 max_reorder: 16,
151 max_long_term_idx: None,
152 prev_poc_msb: 0,
153 prev_poc_lsb: 0,
154 prev_frame_num: 0,
155 prev_frame_num_offset: 0,
156 prev_has_mmco5: false,
157 prev_ref_frame_num: 0,
158 started: false,
159 pending_flush: false,
160 last_id: -1,
161 }
162 }
163}
164
165impl Dpb {
166 /// Adopt the buffer limits of `sps` (Annex A / VUI).
167 pub(crate) fn configure(&mut self, sps: &Sps) {
168 let level_frames = max_dpb_frames(sps);
169 let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) {
170 Some(r) => (
171 (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1),
172 (r.max_num_reorder_frames as usize).min(MAX_STORED - 1),
173 ),
174 None => (level_frames, level_frames),
175 };
176 self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1);
177 self.max_reorder = reorder.min(self.max_frames);
178 }
179
180 /// How many frames the level allows, for sizing the surface pool.
181 pub(crate) fn capacity(&self) -> usize {
182 self.max_frames
183 }
184
185 pub(crate) fn next_id(&mut self) -> i32 {
186 let id = self.next_id;
187 self.next_id = self.next_id.wrapping_add(1);
188 id
189 }
190
191 /// Drop every stored picture (seek or stream discontinuity).
192 pub(crate) fn clear(&mut self) {
193 self.frames.clear();
194 self.max_long_term_idx = None;
195 self.prev_poc_msb = 0;
196 self.prev_poc_lsb = 0;
197 self.prev_frame_num = 0;
198 self.prev_frame_num_offset = 0;
199 self.prev_has_mmco5 = false;
200 self.prev_ref_frame_num = 0;
201 self.started = false;
202 self.pending_flush = false;
203 self.last_id = -1;
204 }
205
206 /// `PicOrderCnt()` of the picture about to be decoded (8.2.1).
207 pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result<Poc> {
208 match sps.pic_order_cnt_type {
209 0 => {
210 let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb;
211 let (prev_msb, prev_lsb) = if info.is_idr {
212 (0, 0)
213 } else {
214 (self.prev_poc_msb, self.prev_poc_lsb)
215 };
216 let lsb = info.pic_order_cnt_lsb as i32;
217 let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 {
218 prev_msb + max_lsb
219 } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 {
220 prev_msb - max_lsb
221 } else {
222 prev_msb
223 };
224 let top = msb + lsb;
225 let bottom = top + info.delta_pic_order_cnt_bottom;
226 Ok(Poc {
227 value: top.min(bottom),
228 frame_num_offset: 0,
229 msb,
230 lsb,
231 })
232 }
233 1 => {
234 let max_frame_num = 1i32 << sps.log2_max_frame_num;
235 let offset = self.frame_num_offset(info, max_frame_num);
236 let cycle_len = sps.offsets_for_ref_frame.len() as i32;
237 let mut abs_frame_num = if cycle_len != 0 {
238 offset + info.frame_num as i32
239 } else {
240 0
241 };
242 if !info.is_reference && abs_frame_num > 0 {
243 abs_frame_num -= 1;
244 }
245 let mut expected = 0i32;
246 if abs_frame_num > 0 {
247 let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum();
248 let cycle_cnt = (abs_frame_num - 1) / cycle_len;
249 let in_cycle = (abs_frame_num - 1) % cycle_len;
250 expected = cycle_cnt.wrapping_mul(expected_delta);
251 for i in 0..=in_cycle as usize {
252 expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]);
253 }
254 }
255 if !info.is_reference {
256 expected = expected.wrapping_add(sps.offset_for_non_ref_pic);
257 }
258 let top = expected.wrapping_add(info.delta_pic_order_cnt[0]);
259 let bottom = top
260 .wrapping_add(sps.offset_for_top_to_bottom_field)
261 .wrapping_add(info.delta_pic_order_cnt[1]);
262 Ok(Poc {
263 value: top.min(bottom),
264 frame_num_offset: offset,
265 msb: 0,
266 lsb: 0,
267 })
268 }
269 2 => {
270 let max_frame_num = 1i32 << sps.log2_max_frame_num;
271 let offset = self.frame_num_offset(info, max_frame_num);
272 let poc = if info.is_idr {
273 0
274 } else if !info.is_reference {
275 2 * (offset + info.frame_num as i32) - 1
276 } else {
277 2 * (offset + info.frame_num as i32)
278 };
279 Ok(Poc {
280 value: poc,
281 frame_num_offset: offset,
282 msb: 0,
283 lsb: 0,
284 })
285 }
286 other => Err(Error::Stream(ec_core::Error::corrupt(format!(
287 "H.264 pic_order_cnt_type {other}"
288 )))),
289 }
290 }
291
292 /// `FrameNumOffset` (8-6, 8-11).
293 fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 {
294 if info.is_idr {
295 return 0;
296 }
297 let prev = if self.prev_has_mmco5 {
298 0
299 } else {
300 self.prev_frame_num_offset
301 };
302 if self.prev_frame_num > info.frame_num {
303 prev + max_frame_num
304 } else {
305 prev
306 }
307 }
308
309 /// True when `frame_num` skips values (8.2.5.2).
310 ///
311 /// This is a *normal* condition — an editor seek or a lossy transport
312 /// produces it — and treating it as corruption is what used to knock a
313 /// hardware session back to software mid-timeline.
314 pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool {
315 let max = 1u32 << sps.log2_max_frame_num;
316 self.started
317 && frame_num != self.prev_ref_frame_num
318 && frame_num != (self.prev_ref_frame_num + 1) % max
319 }
320
321 /// Insert the "non-existing" frames of 8.2.5.2 so that reference numbering
322 /// stays aligned with the encoder's.
323 ///
324 /// The inferred frames share the newest reference picture's surface. Their
325 /// samples are unspecified by the spec, and the previous reference is both
326 /// a better guess than grey and the only choice this driver accepts: a
327 /// reference surface it has never decoded into makes `vaEndPicture` fail
328 /// with `operation failed` (measured on radeonsi with a two-picture gap).
329 pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<usize> {
330 let max = 1u32 << sps.log2_max_frame_num;
331 let mut unused = (self.prev_ref_frame_num + 1) % max;
332 let mut budget = MAX_STORED;
333 let mut filled = 0;
334 while unused != frame_num && budget > 0 {
335 budget -= 1;
336 let Some(surface) = self
337 .frames
338 .iter()
339 .max_by_key(|p| p.frame_num_wrap)
340 .map(|p| Arc::clone(&p.surface))
341 else {
342 // Nothing decoded yet: there is no picture to stand in for the
343 // missing ones, and the next IDR will resynchronise anyway.
344 break;
345 };
346 let info = PicInfo {
347 is_idr: false,
348 is_reference: true,
349 frame_num: unused,
350 pic_order_cnt_lsb: 0,
351 delta_pic_order_cnt_bottom: 0,
352 delta_pic_order_cnt: [0; 2],
353 };
354 // 8.2.5.2: a non-existing frame gets a picture order count only
355 // when pic_order_cnt_type is not 0; under type 0 it has no output
356 // order, and 8.2.4.2.3 keeps it out of the B lists.
357 let poc = if sps.pic_order_cnt_type == 0 {
358 Poc::default()
359 } else {
360 self.picture_order_count(sps, &info)?
361 };
362 self.number_short_term(unused, sps);
363 self.sliding_window(sps);
364 let id = self.next_id();
365 self.frames.push(Picture {
366 id,
367 surface,
368 timestamp: 0,
369 frame_num: unused,
370 frame_num_wrap: unused as i32,
371 pic_num: unused as i32,
372 long_term_frame_idx: 0,
373 poc: poc.value,
374 poc_msb: poc.msb,
375 poc_lsb: poc.lsb,
376 frame_num_offset: poc.frame_num_offset,
377 mark: Mark::Short,
378 non_existing: true,
379 output: false,
380 });
381 self.prev_frame_num = unused;
382 self.prev_frame_num_offset = poc.frame_num_offset;
383 self.prev_has_mmco5 = false;
384 self.prev_ref_frame_num = unused;
385 unused = (unused + 1) % max;
386 filled += 1;
387 }
388 Ok(filled)
389 }
390
391 /// Recompute `FrameNumWrap` and `PicNum` against the current `frame_num`
392 /// (8.2.4.1).
393 pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) {
394 let max_frame_num = 1i32 << sps.log2_max_frame_num;
395 for pic in &mut self.frames {
396 match pic.mark {
397 Mark::Short => {
398 pic.frame_num_wrap = if pic.frame_num > frame_num {
399 pic.frame_num as i32 - max_frame_num
400 } else {
401 pic.frame_num as i32
402 };
403 pic.pic_num = pic.frame_num_wrap;
404 }
405 Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32,
406 Mark::Unused => {}
407 }
408 }
409 }
410
411 /// Build `RefPicList0`/`RefPicList1` for one slice: initialisation
412 /// (8.2.4.2.1 / 8.2.4.2.3) then modification (8.2.4.3).
413 #[allow(clippy::too_many_arguments)]
414 pub(crate) fn build_ref_lists(
415 &self,
416 slice_type: SliceType,
417 curr_poc: i32,
418 curr_pic_num: i32,
419 max_pic_num: i32,
420 num_l0: usize,
421 num_l1: usize,
422 mods: (&[RefPicListMod], &[RefPicListMod]),
423 ) -> Result<([RefList; 2], bool)> {
424 let mut padded = false;
425 let mut lists = [RefList::default(), RefList::default()];
426 let mut short: [usize; MAX_STORED] = [0; MAX_STORED];
427 let mut n_short = 0usize;
428 let mut long: [usize; MAX_STORED] = [0; MAX_STORED];
429 let mut n_long = 0usize;
430 for (i, pic) in self.frames.iter().enumerate() {
431 if pic.non_existing && slice_type == SliceType::B {
432 continue;
433 }
434 match pic.mark {
435 Mark::Short if n_short < MAX_STORED => {
436 short[n_short] = i;
437 n_short += 1;
438 }
439 Mark::Long if n_long < MAX_STORED => {
440 long[n_long] = i;
441 n_long += 1;
442 }
443 _ => {}
444 }
445 }
446 let long = &mut long[..n_long];
447 long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx);
448
449 if slice_type == SliceType::B {
450 let short = &mut short[..n_short];
451 short.sort_unstable_by_key(|&i| {
452 let poc = self.frames[i].poc;
453 if poc < curr_poc {
454 (0i32, -poc)
455 } else {
456 (1, poc)
457 }
458 });
459 for &i in short.iter() {
460 lists[0].push(i);
461 }
462 for &i in long.iter() {
463 lists[0].push(i);
464 }
465 short.sort_unstable_by_key(|&i| {
466 let poc = self.frames[i].poc;
467 if poc > curr_poc {
468 (0i32, poc)
469 } else {
470 (1, -poc)
471 }
472 });
473 for &i in short.iter() {
474 lists[1].push(i);
475 }
476 for &i in long.iter() {
477 lists[1].push(i);
478 }
479 // 8.2.4.2.3 step 3.
480 if lists[1].len > 1
481 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len]
482 {
483 lists[1].entries.swap(0, 1);
484 }
485 } else {
486 let short = &mut short[..n_short];
487 short.sort_unstable_by_key(|&i| -self.frames[i].pic_num);
488 for &i in short.iter() {
489 lists[0].push(i);
490 }
491 for &i in long.iter() {
492 lists[0].push(i);
493 }
494 }
495
496 let wanted = [num_l0, num_l1];
497 let mods = [mods.0, mods.1];
498 for x in 0..2 {
499 if x == 1 && slice_type != SliceType::B {
500 lists[1].len = 0;
501 continue;
502 }
503 if lists[x].len == 0 {
504 return Err(Error::Stream(ec_core::Error::corrupt(
505 "H.264 inter slice with an empty reference list",
506 )));
507 }
508 let first = lists[x].entries[0];
509 if lists[x].len < wanted[x] {
510 padded = true;
511 }
512 while lists[x].len < wanted[x] {
513 lists[x].push(usize::from(first));
514 }
515 lists[x].len = wanted[x];
516 self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num);
517 }
518 Ok((lists, padded))
519 }
520
521 /// Reference picture list modification (8.2.4.3), by the insert-and-compact
522 /// of equations 8-37 and 8-38.
523 fn modify_list(
524 &self,
525 list: &mut RefList,
526 mods: &[RefPicListMod],
527 curr_pic_num: i32,
528 max_pic_num: i32,
529 ) {
530 if mods.is_empty() {
531 return;
532 }
533 let active = list.len;
534 let mut tmp = [0u8; 34];
535 tmp[..active].copy_from_slice(&list.entries[..active]);
536 let mut pred = curr_pic_num;
537 let mut ref_idx = 0usize;
538 for op in mods {
539 let target = match *op {
540 RefPicListMod::ShortTerm {
541 abs_diff_pic_num_minus1,
542 add,
543 } => {
544 let diff = abs_diff_pic_num_minus1 as i32 + 1;
545 let no_wrap = if add {
546 if pred + diff >= max_pic_num {
547 pred + diff - max_pic_num
548 } else {
549 pred + diff
550 }
551 } else if pred - diff < 0 {
552 pred - diff + max_pic_num
553 } else {
554 pred - diff
555 };
556 pred = no_wrap;
557 let pic_num = if no_wrap > curr_pic_num {
558 no_wrap - max_pic_num
559 } else {
560 no_wrap
561 };
562 self.frames
563 .iter()
564 .position(|p| p.mark == Mark::Short && p.pic_num == pic_num)
565 }
566 RefPicListMod::LongTerm(num) => self
567 .frames
568 .iter()
569 .position(|p| p.mark == Mark::Long && p.pic_num == num as i32),
570 };
571 // A modification naming a picture the buffer never received points
572 // at something that was lost; keeping the initial entry decodes a
573 // seek or a dropped packet instead of failing the slice.
574 let Some(target) = target else { continue };
575 if ref_idx >= active {
576 break;
577 }
578 for c in (ref_idx + 1..=active).rev() {
579 tmp[c] = tmp[c - 1];
580 }
581 tmp[ref_idx] = target as u8;
582 ref_idx += 1;
583 let mut n = ref_idx;
584 for c in ref_idx..=active {
585 if usize::from(tmp[c]) != target {
586 tmp[n] = tmp[c];
587 n += 1;
588 }
589 }
590 }
591 list.entries[..active].copy_from_slice(&tmp[..active]);
592 list.len = active;
593 }
594
595 /// Store a decoded picture and apply the reference marking of 8.2.5.
596 ///
597 /// `output_ok` is false for a picture that predicted from a reference
598 /// never decoded since the last `reset()` (a random-access leading
599 /// picture whose ref list build had to pad) — it still joins the DPB as
600 /// a reference and for bookkeeping, but must never be handed to a caller.
601 pub(crate) fn store(
602 &mut self,
603 mut pic: Picture,
604 sps: &Sps,
605 info: &PicInfo,
606 marking: Option<&DecRefPicMarking>,
607 output_ok: bool,
608 ) -> Result<()> {
609 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
610 pic.output = output_ok;
611 self.number_short_term(info.frame_num, sps);
612 pic.frame_num_wrap = pic.frame_num as i32;
613 pic.pic_num = pic.frame_num as i32;
614
615 if info.is_idr {
616 let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics);
617 self.drain_prior(no_output);
618 pic.mark = Mark::Short;
619 if marking.is_some_and(|m| m.long_term_reference) {
620 pic.mark = Mark::Long;
621 pic.long_term_frame_idx = 0;
622 self.max_long_term_idx = Some(0);
623 } else {
624 self.max_long_term_idx = None;
625 }
626 } else if info.is_reference {
627 pic.mark = Mark::Short;
628 match marking {
629 Some(m) if m.adaptive => self.apply_mmco(&mut pic, m, info)?,
630 _ => self.sliding_window(sps),
631 }
632 }
633
634 if has_mmco5 {
635 // 8.2.1: MMCO 5 restarts frame_num and picture order count here.
636 pic.poc = 0;
637 pic.frame_num = 0;
638 pic.frame_num_offset = 0;
639 pic.poc_msb = 0;
640 pic.poc_lsb = 0;
641 }
642
643 self.prev_frame_num = pic.frame_num;
644 self.prev_frame_num_offset = pic.frame_num_offset;
645 self.prev_has_mmco5 = has_mmco5;
646 if info.is_reference {
647 self.prev_ref_frame_num = pic.frame_num;
648 self.prev_poc_msb = pic.poc_msb;
649 self.prev_poc_lsb = pic.poc_lsb;
650 }
651 self.started = true;
652 if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) {
653 self.pending_flush = true;
654 }
655 self.last_id = pic.id;
656
657 if self.frames.len() >= MAX_STORED {
658 return Err(Error::Stream(ec_core::Error::corrupt(
659 "H.264 decoded picture buffer overflow",
660 )));
661 }
662 self.frames.push(pic);
663 Ok(())
664 }
665
666 /// Output and release every stored picture (IDR boundary or MMCO 5).
667 fn drain_prior(&mut self, discard: bool) {
668 for pic in &mut self.frames {
669 pic.mark = Mark::Unused;
670 if discard {
671 pic.output = false;
672 }
673 }
674 }
675
676 /// Sliding window marking (8.2.5.3).
677 fn sliding_window(&mut self, sps: &Sps) {
678 let max_refs = (sps.max_num_ref_frames as usize).max(1);
679 loop {
680 let n = self
681 .frames
682 .iter()
683 .filter(|p| p.mark != Mark::Unused)
684 .count();
685 if n < max_refs {
686 return;
687 }
688 let Some(oldest) = self
689 .frames
690 .iter_mut()
691 .filter(|p| p.mark == Mark::Short)
692 .min_by_key(|p| p.frame_num_wrap)
693 else {
694 // Only long-term references left: the stream must free one by
695 // MMCO, and refusing here would break a conformant stream.
696 return;
697 };
698 oldest.mark = Mark::Unused;
699 }
700 }
701
702 /// Adaptive marking (8.2.5.4).
703 fn apply_mmco(
704 &mut self,
705 pic: &mut Picture,
706 m: &DecRefPicMarking,
707 info: &PicInfo,
708 ) -> Result<()> {
709 let curr_pic_num = info.frame_num as i32;
710 for op in &m.mmcos {
711 match op.op {
712 1 => {
713 let target = curr_pic_num - (op.arg1 as i32 + 1);
714 if let Some(p) = self
715 .frames
716 .iter_mut()
717 .find(|p| p.mark == Mark::Short && p.pic_num == target)
718 {
719 p.mark = Mark::Unused;
720 }
721 }
722 2 => {
723 if let Some(p) = self
724 .frames
725 .iter_mut()
726 .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32)
727 {
728 p.mark = Mark::Unused;
729 }
730 }
731 3 => {
732 let target = curr_pic_num - (op.arg1 as i32 + 1);
733 let idx = op.arg2;
734 for p in &mut self.frames {
735 if p.mark == Mark::Long && p.long_term_frame_idx == idx {
736 p.mark = Mark::Unused;
737 }
738 }
739 if let Some(p) = self
740 .frames
741 .iter_mut()
742 .find(|p| p.mark == Mark::Short && p.pic_num == target)
743 {
744 p.mark = Mark::Long;
745 p.long_term_frame_idx = idx;
746 p.pic_num = idx as i32;
747 }
748 }
749 4 => {
750 self.max_long_term_idx = op.arg1.checked_sub(1);
751 let limit = self.max_long_term_idx;
752 for p in &mut self.frames {
753 if p.mark == Mark::Long
754 && limit.is_none_or(|max| p.long_term_frame_idx > max)
755 {
756 p.mark = Mark::Unused;
757 }
758 }
759 }
760 5 => {
761 for p in &mut self.frames {
762 p.mark = Mark::Unused;
763 }
764 self.max_long_term_idx = None;
765 }
766 6 => {
767 let idx = op.arg1;
768 for p in &mut self.frames {
769 if p.mark == Mark::Long && p.long_term_frame_idx == idx {
770 p.mark = Mark::Unused;
771 }
772 }
773 pic.mark = Mark::Long;
774 pic.long_term_frame_idx = idx;
775 pic.pic_num = idx as i32;
776 }
777 other => {
778 return Err(Error::Stream(ec_core::Error::corrupt(format!(
779 "H.264 memory_management_control_operation {other}"
780 ))));
781 }
782 }
783 }
784 Ok(())
785 }
786
787 /// The next picture to output, or `None` while the buffer is still within
788 /// its reordering and storage limits (bumping, C.4.5.3).
789 pub(crate) fn next_output(&mut self, flush: bool) -> Option<usize> {
790 if self.pending_flush {
791 let last = self.last_id;
792 let best = self
793 .frames
794 .iter()
795 .enumerate()
796 .filter(|(_, p)| p.output && p.id != last)
797 .min_by_key(|(_, p)| p.poc)
798 .map(|(i, _)| i);
799 if best.is_some() {
800 return best;
801 }
802 self.pending_flush = false;
803 }
804 let pending = self.frames.iter().filter(|p| p.output).count();
805 let stored = self.frames.iter().filter(|p| p.stored()).count();
806 if !flush && pending <= self.max_reorder && stored <= self.max_frames {
807 return None;
808 }
809 let mut best: Option<usize> = None;
810 for (i, pic) in self.frames.iter().enumerate() {
811 if !pic.output || pic.non_existing {
812 continue;
813 }
814 if best.is_none_or(|b| pic.poc < self.frames[b].poc) {
815 best = Some(i);
816 }
817 }
818 best
819 }
820
821 /// Mark picture `idx` as output and drop every slot that is now free.
822 ///
823 /// Dropping is what releases the surface back to the pool: nothing else
824 /// holds it once the buffer and the caller are done, which is the leak this
825 /// design makes structurally impossible.
826 pub(crate) fn released(&mut self, idx: usize) {
827 self.frames[idx].output = false;
828 self.frames.retain(|p| p.stored());
829 }
830}
831
832/// `MaxDpbFrames` from the level limits of Annex A, Table A-1.
833fn max_dpb_frames(sps: &Sps) -> usize {
834 // MaxDpbMbs per level, in the level_idc order of Table A-1.
835 const LIMITS: [(u8, u32); 17] = [
836 (10, 396),
837 (11, 900),
838 (12, 2376),
839 (13, 2376),
840 (20, 2376),
841 (21, 4752),
842 (22, 8100),
843 (30, 8100),
844 (31, 18000),
845 (32, 20480),
846 (40, 32768),
847 (41, 32768),
848 (42, 34816),
849 (50, 110400),
850 (51, 184320),
851 (52, 184320),
852 (60, 696320),
853 ];
854 let mbs = sps.mbs_per_picture().max(1);
855 let max_dpb_mbs = LIMITS
856 .iter()
857 .find(|(level, _)| *level >= sps.level_idc)
858 .map(|(_, mbs)| *mbs)
859 .unwrap_or(696_320);
860 ((max_dpb_mbs / mbs) as usize).clamp(1, 16)
861}
862
863#[cfg(test)]
864mod tests {
865 use super::*;
866
867 fn sps_for(poc_type: u8) -> Sps {
868 let mut sps = Sps {
869 profile_idc: 100,
870 constraint_flags: 0,
871 level_idc: 40,
872 id: 0,
873 chroma_format_idc: 1,
874 separate_colour_plane: false,
875 bit_depth_luma: 8,
876 bit_depth_chroma: 8,
877 transform_bypass: false,
878 scaling_lists: None,
879 log2_max_frame_num: 4,
880 pic_order_cnt_type: poc_type,
881 log2_max_pic_order_cnt_lsb: 4,
882 delta_pic_order_always_zero: false,
883 offset_for_non_ref_pic: 0,
884 offset_for_top_to_bottom_field: 0,
885 offsets_for_ref_frame: Vec::new(),
886 max_num_ref_frames: 4,
887 gaps_in_frame_num_allowed: true,
888 frame_mbs_only: true,
889 mb_adaptive_frame_field: false,
890 direct_8x8_inference: true,
891 crop: (0, 0, 0, 0),
892 vui: None,
893 mb_width: 120,
894 mb_height: 68,
895 coded_width: 1920,
896 coded_height: 1088,
897 width: 1920,
898 height: 1088,
899 };
900 if poc_type == 1 {
901 sps.offsets_for_ref_frame = vec![2, -2];
902 }
903 sps
904 }
905
906 fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo {
907 PicInfo {
908 is_idr,
909 is_reference: is_ref,
910 frame_num,
911 pic_order_cnt_lsb: lsb,
912 delta_pic_order_cnt_bottom: 0,
913 delta_pic_order_cnt: [0; 2],
914 }
915 }
916
917 #[test]
918 fn poc_type_0_tracks_the_msb_across_a_wrap() {
919 let sps = sps_for(0);
920 let mut dpb = Dpb::default();
921 let mut expect = |info: PicInfo, want: i32| {
922 let poc = dpb.picture_order_count(&sps, &info).unwrap();
923 assert_eq!(poc.value, want, "{info:?}");
924 // What `store` does for a reference picture.
925 if info.is_reference {
926 dpb.prev_poc_msb = poc.msb;
927 dpb.prev_poc_lsb = poc.lsb;
928 }
929 };
930 // MaxPicOrderCntLsb is 16 here, so a step of more than 8 is read as a
931 // wrap rather than as a jump.
932 expect(info(0, 0, true, true), 0);
933 expect(info(1, 7, true, false), 7);
934 expect(info(2, 14, true, false), 14);
935 expect(info(3, 2, true, false), 18);
936 // And a small step back really is a step back.
937 expect(info(4, 15, true, false), 15);
938 }
939
940 #[test]
941 fn frame_num_gaps_are_detected_but_not_at_the_start() {
942 let sps = sps_for(0);
943 let mut dpb = Dpb::default();
944 // Nothing decoded yet: a jump is a seek, not a gap.
945 assert!(!dpb.frame_num_gap(&sps, 7));
946 dpb.started = true;
947 dpb.prev_ref_frame_num = 3;
948 assert!(!dpb.frame_num_gap(&sps, 3));
949 assert!(!dpb.frame_num_gap(&sps, 4));
950 assert!(dpb.frame_num_gap(&sps, 6));
951 // MaxFrameNum is 16, so 15 -> 0 is contiguous, 15 -> 1 is a gap.
952 dpb.prev_ref_frame_num = 15;
953 assert!(!dpb.frame_num_gap(&sps, 0));
954 assert!(dpb.frame_num_gap(&sps, 1));
955 }
956
957 #[test]
958 fn level_limits_size_the_buffer() {
959 let mut sps = sps_for(0);
960 let mut dpb = Dpb::default();
961 dpb.configure(&sps);
962 // 1080p at level 4.0: 32768 / 8160 = 4 frames.
963 assert_eq!(dpb.capacity(), 4);
964 sps.level_idc = 51;
965 dpb.configure(&sps);
966 assert_eq!(dpb.capacity(), 16);
967 }
968}