forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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