forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

interlaced.rs864 lines, 32.1 KiBHistoryRawDownload
1//! Storage, reference marking and reference list construction for streams
2//! with `frame_mbs_only_flag` 0 (clauses 8.2.4 and 8.2.5 with field pictures).
3//!
4//! A stored frame (a [`Picture`] with `structure == FRAME`) is a frame store:
5//! the woven frame planes, plus two field views in [`Picture::fields`]. A frame
6//! coded as two field pictures keeps the decoded half-height fields as those
7//! views (with their motion data) and has its frame planes woven from them
8//! when the second field arrives; a frame coded as a frame has its field views
9//! split out of the frame planes. Either way a field reference reads the
10//! padded planes of one field and a frame reference reads the woven frame.
11//!
12//! Marking is kept per field ([`Picture::fmark`]); `Picture::mark` is the
13//! aggregate the buffer's slot accounting reads. The progressive paths of the
14//! parent module are not touched: a stream with `frame_mbs_only_flag` 1 never
15//! comes through here.
16
17use super::*;
18
19/// `PicNum` of field `parity` (0 top, 1 bottom) of a short-term entry whose
20/// `FrameNumWrap` is `wrap`, seen from a picture of `structure` (8-28, 8-30,
21/// 8-31).
22fn short_pic_num(wrap: i32, parity: usize, structure: u8) -> i32 {
23 if structure == FRAME {
24 wrap
25 } else if parity + 1 == usize::from(structure) {
26 2 * wrap + 1
27 } else {
28 2 * wrap
29 }
30}
31
32/// `LongTermPicNum` of a long-term entry (8-29, 8-32, 8-33).
33fn long_pic_num(idx: u32, parity: usize, structure: u8) -> i32 {
34 let idx = idx as i32;
35 if structure == FRAME {
36 idx
37 } else if parity + 1 == usize::from(structure) {
38 2 * idx + 1
39 } else {
40 2 * idx
41 }
42}
43
44impl<S: Sample> Picture<S> {
45 /// Size the three planes for a field of an `mb_w` by `mb_h_field`
46 /// macroblock picture, leaving the per-macroblock arrays alone.
47 fn size_field_planes(&mut self, bd: u32, cat: u8, mb_w: usize, mb_h_field: usize, sps_id: u8) {
48 let (cw, cmb_h, cpad) = chroma_geometry(cat);
49 self.bd = bd;
50 self.cmb_h = cmb_h;
51 self.cw = cw;
52 self.cat = cat;
53 self.mb_w = mb_w;
54 self.mb_h = mb_h_field;
55 self.sps_id = sps_id;
56 if self.y.width != mb_w * 16
57 || self.y.height != mb_h_field * 16
58 || self.cb.height != mb_h_field * cmb_h
59 || self.cb.width != mb_w * cw
60 {
61 self.y.resize(mb_w * 16, mb_h_field * 16, PAD_Y);
62 self.cb.resize(mb_w * cw, mb_h_field * cmb_h, cpad);
63 self.cr.resize(mb_w * cw, mb_h_field * cmb_h, cpad);
64 }
65 }
66
67 /// Recompute the aggregate marking and the picture order count of a frame
68 /// store from its fields, and copy both into the field views.
69 pub(crate) fn refresh(&mut self) {
70 self.mark = if self.fmark.contains(&Mark::Short) {
71 Mark::Short
72 } else if self.fmark.contains(&Mark::Long) {
73 Mark::Long
74 } else {
75 Mark::Unused
76 };
77 self.poc = match self.have {
78 [true, true] => self.fpoc[0].min(self.fpoc[1]),
79 [true, false] => self.fpoc[0],
80 [false, true] => self.fpoc[1],
81 [false, false] => self.poc,
82 };
83 let (marks, pocs, idx) = (self.fmark, self.fpoc, self.long_term_frame_idx);
84 for (p, f) in self.fields.iter_mut().enumerate().take(2) {
85 f.mark = marks[p];
86 f.poc = pocs[p];
87 f.long_term_frame_idx = idx;
88 }
89 }
90}
91
92/// Copy field `parity` of `src` into `dst` (a half-height plane) and replicate
93/// its borders.
94fn split_plane<S: Sample>(src: &PicPlane<S>, parity: usize, dst: &mut PicPlane<S>) {
95 let w = src.width;
96 for y in 0..dst.height {
97 let s = src.at(0, 2 * y + parity);
98 let d = dst.at(0, y);
99 dst.data[d..d + w].copy_from_slice(&src.data[s..s + w]);
100 }
101 dst.extend_borders();
102}
103
104/// Interleave two field planes into a frame plane and replicate its borders.
105/// A field missing from the pair is stood in for by the other one.
106fn weave_plane<S: Sample>(dst: &mut PicPlane<S>, top: &PicPlane<S>, bottom: &PicPlane<S>) {
107 let w = dst.width;
108 for y in 0..top.height {
109 for (parity, src) in [top, bottom].into_iter().enumerate() {
110 let s = src.at(0, y);
111 let d = dst.at(0, 2 * y + parity);
112 dst.data[d..d + w].copy_from_slice(&src.data[s..s + w]);
113 }
114 }
115 dst.extend_borders();
116}
117
118impl<S: Sample> Dpb<S> {
119 /// Give a finished frame its two field views, split out of its planes.
120 pub(crate) fn attach_fields_from_frame(&mut self, pic: &mut Picture<S>) {
121 while pic.fields.len() < 2 {
122 let f = self.take_field_picture();
123 pic.fields.push(f);
124 }
125 pic.fields.truncate(2);
126 let (bd, cat, mb_w, sps_id) = (pic.bd, pic.cat, pic.mb_w, pic.sps_id);
127 let half = pic.mb_h / 2;
128 let (planes, fields) = ([&pic.y, &pic.cb, &pic.cr], &mut pic.fields);
129 for (p, f) in fields.iter_mut().enumerate() {
130 f.size_field_planes(bd, cat, mb_w, half, sps_id);
131 f.structure = p as u8 + 1;
132 split_plane(planes[0], p, &mut f.y);
133 split_plane(planes[1], p, &mut f.cb);
134 split_plane(planes[2], p, &mut f.cr);
135 }
136 let (id, marks, pocs) = (pic.id, pic.fmark, pic.fpoc);
137 for (p, f) in pic.fields.iter_mut().enumerate() {
138 f.id = id + 1 + p as i32;
139 f.mark = marks[p];
140 f.poc = pocs[p];
141 f.complete = true;
142 f.decoded_mbs = 0;
143 }
144 }
145
146 /// Weave the frame planes of a frame store from its decoded fields.
147 fn weave(pic: &mut Picture<S>) {
148 let [top, bottom] = match pic.have {
149 [true, true] => [0, 1],
150 [true, false] => [0, 0],
151 _ => [1, 1],
152 };
153 let (t, b) = (&pic.fields[top], &pic.fields[bottom]);
154 weave_plane(&mut pic.y, &t.y, &b.y);
155 weave_plane(&mut pic.cb, &t.cb, &b.cb);
156 weave_plane(&mut pic.cr, &t.cr, &b.cr);
157 }
158
159 /// The frame store whose first field was the previous picture and which
160 /// `structure` (of a picture with `frame_num`) completes, if any.
161 pub(crate) fn pending_first_field(
162 &self,
163 frame_num: u32,
164 structure: u8,
165 is_idr: bool,
166 ) -> Option<usize> {
167 if structure == FRAME || is_idr {
168 return None;
169 }
170 let p = usize::from(structure) - 1;
171 self.frames.iter().position(|f| {
172 f.awaiting_second && f.id == self.last_id && f.frame_num == frame_num && f.have[1 - p]
173 })
174 }
175
176 /// A picture that is not the second field of a waiting first field has
177 /// arrived: that field stays a non-paired field, and is complete.
178 pub(crate) fn finalize_unpaired(&mut self) {
179 for pic in &mut self.frames {
180 if pic.awaiting_second {
181 pic.awaiting_second = false;
182 Self::weave(pic);
183 pic.refresh();
184 }
185 }
186 }
187
188 /// `FrameNumWrap` for every stored frame with a short-term field (8.2.4.1).
189 pub(crate) fn number_short_term_i(&mut self, frame_num: u32, sps: &Sps) {
190 let max_frame_num = 1i32 << sps.log2_max_frame_num;
191 for pic in &mut self.frames {
192 if pic.fmark.contains(&Mark::Short) {
193 pic.frame_num_wrap = if pic.frame_num > frame_num {
194 pic.frame_num as i32 - max_frame_num
195 } else {
196 pic.frame_num as i32
197 };
198 }
199 }
200 }
201
202 /// `RefPicList0/1` for a slice of a picture with `structure`
203 /// (8.2.4.2.1 to 8.2.4.2.5, then 8.2.4.3).
204 #[allow(clippy::too_many_arguments)]
205 pub(crate) fn build_ref_lists_i(
206 &self,
207 slice_type: SliceType,
208 structure: u8,
209 curr_poc: i32,
210 curr_pic_num: i32,
211 max_pic_num: i32,
212 num_l0: usize,
213 num_l1: usize,
214 mods: (&[RefPicListMod], &[RefPicListMod]),
215 ) -> Result<([RefList; 2], bool)> {
216 let b = slice_type == SliceType::B;
217 let field = structure != FRAME;
218 let mut short = [0usize; MAX_STORED];
219 let mut n_short = 0;
220 let mut long = [0usize; MAX_STORED];
221 let mut n_long = 0;
222 for (i, pic) in self.frames.iter().enumerate() {
223 if pic.non_existing && b {
224 continue;
225 }
226 let (is_short, is_long) = if field {
227 (
228 (0..2).any(|p| pic.have[p] && pic.fmark[p] == Mark::Short),
229 (0..2).any(|p| pic.have[p] && pic.fmark[p] == Mark::Long),
230 )
231 } else {
232 (
233 pic.have == [true, true] && pic.fmark == [Mark::Short; 2],
234 pic.have == [true, true] && pic.fmark == [Mark::Long; 2],
235 )
236 };
237 if is_short && n_short < MAX_STORED {
238 short[n_short] = i;
239 n_short += 1;
240 }
241 if is_long && n_long < MAX_STORED {
242 long[n_long] = i;
243 n_long += 1;
244 }
245 }
246 let long = &mut long[..n_long];
247 long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx);
248 let short = &mut short[..n_short];
249
250 let mut lists = [RefList::default(), RefList::default()];
251 let cur_parity = usize::from(structure == BOTTOM);
252 let emit = |lists: &mut [RefList; 2], x: usize, short: &[usize]| {
253 if field {
254 self.alternate(short, cur_parity, Mark::Short, &mut lists[x]);
255 self.alternate(long, cur_parity, Mark::Long, &mut lists[x]);
256 } else {
257 for &i in short {
258 lists[x].push(i);
259 }
260 for &i in long.iter() {
261 lists[x].push(i);
262 }
263 }
264 };
265 if b {
266 // 8.2.4.2.3 / 8.2.4.2.4: by output order around the current picture.
267 // A field accepts equal counts on the "before" side (the first field
268 // of its own frame can tie it).
269 let before = |poc: i32| {
270 if field {
271 poc <= curr_poc
272 } else {
273 poc < curr_poc
274 }
275 };
276 short.sort_unstable_by_key(|&i| {
277 let poc = self.frames[i].poc;
278 if before(poc) { (0i32, -poc) } else { (1, poc) }
279 });
280 emit(&mut lists, 0, short);
281 short.sort_unstable_by_key(|&i| {
282 let poc = self.frames[i].poc;
283 if !before(poc) { (0i32, poc) } else { (1, -poc) }
284 });
285 emit(&mut lists, 1, short);
286 if lists[1].len > 1
287 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len]
288 {
289 lists[1].entries.swap(0, 1);
290 }
291 } else {
292 short.sort_unstable_by_key(|&i| -self.frames[i].frame_num_wrap);
293 emit(&mut lists, 0, short);
294 }
295
296 let wanted = [num_l0, num_l1];
297 let mods = [mods.0, mods.1];
298 let mut padded = false;
299 for x in 0..2 {
300 if x == 1 && !b {
301 lists[1].len = 0;
302 continue;
303 }
304 if lists[x].len == 0 {
305 return Err(Error::corrupt("inter slice with an empty reference list"));
306 }
307 let first = lists[x].entries[0];
308 if lists[x].len < wanted[x] {
309 padded = true;
310 }
311 while lists[x].len < wanted[x] {
312 let (i, s) = (usize::from(first & 31), first >> 5);
313 lists[x].push_ref(i, s);
314 }
315 lists[x].len = wanted[x];
316 self.modify_list_i(&mut lists[x], mods[x], curr_pic_num, max_pic_num, structure);
317 }
318 Ok((lists, padded))
319 }
320
321 /// 8.2.4.2.5: fields of `frames` (in list order) of marking `kind`,
322 /// alternating parity from the current field's own.
323 fn alternate(&self, frames: &[usize], cur_parity: usize, kind: Mark, out: &mut RefList) {
324 let has = |i: usize, p: usize| {
325 let f = &self.frames[i];
326 f.have[p] && f.fmark[p] == kind
327 };
328 let mut cursor = [0usize; 2];
329 let mut want = cur_parity;
330 loop {
331 let mut found = None;
332 while cursor[want] < frames.len() {
333 let i = frames[cursor[want]];
334 cursor[want] += 1;
335 if has(i, want) {
336 found = Some(i);
337 break;
338 }
339 }
340 match found {
341 Some(i) => {
342 out.push_ref(i, want as u8 + 1);
343 want ^= 1;
344 }
345 None => {
346 let o = want ^ 1;
347 while cursor[o] < frames.len() {
348 let i = frames[cursor[o]];
349 cursor[o] += 1;
350 if has(i, o) {
351 out.push_ref(i, o as u8 + 1);
352 }
353 }
354 break;
355 }
356 }
357 }
358 }
359
360 /// Reference picture list modification (8.2.4.3) over entries that name a
361 /// frame or one field of a frame.
362 fn modify_list_i(
363 &self,
364 list: &mut RefList,
365 mods: &[RefPicListMod],
366 curr_pic_num: i32,
367 max_pic_num: i32,
368 structure: u8,
369 ) {
370 if mods.is_empty() {
371 return;
372 }
373 let active = list.len;
374 let mut tmp = [0u8; 34];
375 tmp[..active].copy_from_slice(&list.entries[..active]);
376 let mut pred = curr_pic_num;
377 let mut ref_idx = 0usize;
378 // The picture an entry names, searched over every stored frame (and
379 // field): `want` tests (frame store, parity).
380 let find = |want: &dyn Fn(&Picture<S>, usize) -> bool| -> Option<u8> {
381 for (i, f) in self.frames.iter().enumerate() {
382 if structure == FRAME {
383 if want(f, 2) {
384 return Some(i as u8);
385 }
386 } else {
387 for p in 0..2 {
388 if f.have[p] && want(f, p) {
389 return Some(i as u8 | ((p as u8 + 1) << 5));
390 }
391 }
392 }
393 }
394 None
395 };
396 for op in mods {
397 let target = match *op {
398 RefPicListMod::ShortTerm {
399 abs_diff_pic_num_minus1,
400 add,
401 } => {
402 let diff = abs_diff_pic_num_minus1 as i32 + 1;
403 let no_wrap = if add {
404 if pred + diff >= max_pic_num {
405 pred + diff - max_pic_num
406 } else {
407 pred + diff
408 }
409 } else if pred - diff < 0 {
410 pred - diff + max_pic_num
411 } else {
412 pred - diff
413 };
414 pred = no_wrap;
415 let pic_num = if no_wrap > curr_pic_num {
416 no_wrap - max_pic_num
417 } else {
418 no_wrap
419 };
420 find(&|f, p| {
421 if p == 2 {
422 f.have == [true, true]
423 && f.fmark == [Mark::Short; 2]
424 && f.frame_num_wrap == pic_num
425 } else {
426 f.fmark[p] == Mark::Short
427 && short_pic_num(f.frame_num_wrap, p, structure) == pic_num
428 }
429 })
430 }
431 RefPicListMod::LongTerm(num) => find(&|f, p| {
432 if p == 2 {
433 f.have == [true, true]
434 && f.fmark == [Mark::Long; 2]
435 && f.long_term_frame_idx as i32 == num as i32
436 } else {
437 f.fmark[p] == Mark::Long
438 && long_pic_num(f.long_term_frame_idx, p, structure) == num as i32
439 }
440 }),
441 };
442 let Some(target) = target else { continue };
443 if ref_idx >= active {
444 break;
445 }
446 for c in (ref_idx + 1..=active).rev() {
447 tmp[c] = tmp[c - 1];
448 }
449 tmp[ref_idx] = target;
450 ref_idx += 1;
451 let mut n = ref_idx;
452 for c in ref_idx..=active {
453 if tmp[c] != target {
454 tmp[n] = tmp[c];
455 n += 1;
456 }
457 }
458 }
459 list.entries[..active].copy_from_slice(&tmp[..active]);
460 list.len = active;
461 }
462
463 /// Mark every stored picture unused (IDR and MMCO 5).
464 fn unmark_all(&mut self) {
465 for pic in &mut self.frames {
466 pic.fmark = [Mark::Unused; 2];
467 pic.refresh();
468 }
469 }
470
471 /// Sliding window marking (8.2.5.3) for a picture of `info.structure`.
472 fn sliding_window_i(&mut self, sps: &Sps, info: &PicInfo) -> Result<()> {
473 if info.structure != FRAME
474 && let Some(k) = info.second_of
475 {
476 // The second field of a pair whose first field is a short-term
477 // reference joins it without displacing anything.
478 let first = usize::from(info.structure == TOP);
479 if self.frames[k].fmark[first] == Mark::Short {
480 return Ok(());
481 }
482 }
483 let max_refs = (sps.max_num_ref_frames as usize).max(1);
484 loop {
485 let n = self
486 .frames
487 .iter()
488 .filter(|p| p.fmark != [Mark::Unused; 2])
489 .count();
490 if n < max_refs {
491 return Ok(());
492 }
493 let Some(oldest) = self
494 .frames
495 .iter_mut()
496 .filter(|p| p.fmark.contains(&Mark::Short))
497 .min_by_key(|p| p.frame_num_wrap)
498 else {
499 return Ok(());
500 };
501 for m in &mut oldest.fmark {
502 if *m == Mark::Short {
503 *m = Mark::Unused;
504 }
505 }
506 oldest.refresh();
507 }
508 }
509
510 /// Free `LongTermFrameIdx` `idx` for assignment to a picture of frame store
511 /// `keep` (8.2.5.4.3, 8.2.5.4.6): long-term fields elsewhere that hold it
512 /// become unused; the other field of `keep` may share it.
513 fn free_long_term_idx(&mut self, idx: u32, keep: Option<usize>) {
514 for (j, p) in self.frames.iter_mut().enumerate() {
515 if Some(j) == keep {
516 continue;
517 }
518 if p.long_term_frame_idx == idx && p.fmark.contains(&Mark::Long) {
519 for m in &mut p.fmark {
520 if *m == Mark::Long {
521 *m = Mark::Unused;
522 }
523 }
524 p.refresh();
525 }
526 }
527 }
528
529 /// Adaptive marking (8.2.5.4). Returns the marking the current picture
530 /// ends with and its `LongTermFrameIdx`.
531 fn apply_mmco_i(&mut self, m: &DecRefPicMarking, info: &PicInfo) -> Result<(Mark, u32)> {
532 let structure = info.structure;
533 let curr_pic_num = if structure == FRAME {
534 info.frame_num as i32
535 } else {
536 2 * info.frame_num as i32 + 1
537 };
538 let mut cur = (Mark::Short, 0u32);
539 for op in &m.mmcos {
540 match op.op {
541 1 | 3 => {
542 let target = curr_pic_num - (op.arg1 as i32 + 1);
543 // The short-term frame, or field, picNumX names.
544 let found = self.frames.iter().enumerate().find_map(|(k, f)| {
545 if structure == FRAME {
546 (f.fmark == [Mark::Short; 2] && f.frame_num_wrap == target)
547 .then_some((k, 2))
548 } else {
549 (0..2)
550 .find(|&p| {
551 f.fmark[p] == Mark::Short
552 && short_pic_num(f.frame_num_wrap, p, structure) == target
553 })
554 .map(|p| (k, p))
555 }
556 });
557 let Some((k, p)) = found else { continue };
558 if op.op == 1 {
559 if p == 2 {
560 self.frames[k].fmark = [Mark::Unused; 2];
561 } else {
562 self.frames[k].fmark[p] = Mark::Unused;
563 }
564 } else {
565 let idx = op.arg2;
566 self.free_long_term_idx(idx, Some(k));
567 let f = &mut self.frames[k];
568 if p == 2 {
569 f.fmark = [Mark::Long; 2];
570 } else {
571 f.fmark[p] = Mark::Long;
572 }
573 f.long_term_frame_idx = idx;
574 }
575 self.frames[k].refresh();
576 }
577 2 => {
578 let num = op.arg1 as i32;
579 let found = self.frames.iter().enumerate().find_map(|(k, f)| {
580 if structure == FRAME {
581 (f.fmark == [Mark::Long; 2] && f.long_term_frame_idx as i32 == num)
582 .then_some((k, 2))
583 } else {
584 (0..2)
585 .find(|&p| {
586 f.fmark[p] == Mark::Long
587 && long_pic_num(f.long_term_frame_idx, p, structure) == num
588 })
589 .map(|p| (k, p))
590 }
591 });
592 if let Some((k, p)) = found {
593 if p == 2 {
594 self.frames[k].fmark = [Mark::Unused; 2];
595 } else {
596 self.frames[k].fmark[p] = Mark::Unused;
597 }
598 self.frames[k].refresh();
599 }
600 }
601 4 => {
602 self.max_long_term_idx = op.arg1.checked_sub(1);
603 let limit = self.max_long_term_idx;
604 for p in &mut self.frames {
605 if p.long_term_frame_idx_over(limit) {
606 for mk in &mut p.fmark {
607 if *mk == Mark::Long {
608 *mk = Mark::Unused;
609 }
610 }
611 p.refresh();
612 }
613 }
614 }
615 5 => {
616 self.unmark_all();
617 self.max_long_term_idx = None;
618 }
619 6 => {
620 let idx = op.arg1;
621 self.free_long_term_idx(idx, info.second_of);
622 cur = (Mark::Long, idx);
623 }
624 other => {
625 return Err(Error::corrupt(format!(
626 "memory_management_control_operation {other}"
627 )));
628 }
629 }
630 }
631 Ok(cur)
632 }
633
634 /// Output and unmark everything (IDR boundary).
635 fn drain_prior_i(&mut self, discard: bool) {
636 for pic in &mut self.frames {
637 pic.fmark = [Mark::Unused; 2];
638 pic.refresh();
639 if discard {
640 pic.output = false;
641 }
642 }
643 }
644
645 /// Insert the "non-existing" frames of 8.2.5.2 for a `frame_num` gap.
646 pub(crate) fn fill_frame_num_gap_i(&mut self, sps: &Sps, frame_num: u32) -> Result<()> {
647 let max = 1u32 << sps.log2_max_frame_num;
648 let mut unused = (self.prev_ref_frame_num + 1) % max;
649 let mut budget = MAX_STORED;
650 while unused != frame_num && budget > 0 {
651 budget -= 1;
652 let mut pic = self.take_picture();
653 pic.start(sps);
654 match self.frames.iter().max_by_key(|p| p.frame_num_wrap) {
655 Some(src) if src.y.data.len() == pic.y.data.len() => pic.copy_samples_from(src),
656 _ => pic.fill_grey(),
657 }
658 pic.non_existing = true;
659 pic.frame_num = unused;
660 pic.output = false;
661 pic.complete = true;
662 let info = PicInfo {
663 structure: FRAME,
664 second_of: None,
665 is_idr: false,
666 is_reference: true,
667 frame_num: unused,
668 pic_order_cnt_lsb: 0,
669 delta_pic_order_cnt_bottom: 0,
670 delta_pic_order_cnt: [0; 2],
671 };
672 let poc = if sps.pic_order_cnt_type == 0 {
673 Poc::default()
674 } else {
675 self.picture_order_count(sps, &info)?
676 };
677 pic.poc = poc.value;
678 pic.fpoc = [poc.top, poc.bottom];
679 pic.have = [true, true];
680 pic.frame_num_offset = poc.frame_num_offset;
681 self.number_short_term_i(unused, sps);
682 self.sliding_window_i(sps, &info)?;
683 pic.fmark = [Mark::Short; 2];
684 pic.frame_num_wrap = unused as i32;
685 self.attach_fields_from_frame(&mut pic);
686 pic.refresh();
687 self.frames.push(pic);
688 self.prev_frame_num = unused;
689 self.prev_frame_num_offset = poc.frame_num_offset;
690 self.prev_has_mmco5 = false;
691 self.prev_ref_frame_num = unused;
692 unused = (unused + 1) % max;
693 }
694 Ok(())
695 }
696
697 /// Store a decoded frame or field and apply the reference marking of 8.2.5.
698 ///
699 /// A first field creates its frame store and leaves it awaiting the second;
700 /// a second field (`info.second_of`) completes the store it names.
701 pub(crate) fn store_i(
702 &mut self,
703 mut pic: Picture<S>,
704 sps: &Sps,
705 info: &PicInfo,
706 marking: Option<&DecRefPicMarking>,
707 output_ok: bool,
708 ) -> Result<()> {
709 let structure = info.structure;
710 let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5));
711 let (frame_num_offset, poc_msb, poc_lsb) = (pic.frame_num_offset, pic.poc_msb, pic.poc_lsb);
712 self.number_short_term_i(info.frame_num, sps);
713
714 let mut cur = (Mark::Unused, 0u32);
715 if info.is_idr {
716 let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics);
717 self.drain_prior_i(no_output);
718 cur = (Mark::Short, 0);
719 if marking.is_some_and(|m| m.long_term_reference) {
720 cur = (Mark::Long, 0);
721 self.max_long_term_idx = Some(0);
722 } else {
723 self.max_long_term_idx = None;
724 }
725 } else if info.is_reference {
726 let Some(m) = marking else {
727 return Err(Error::corrupt(
728 "a reference picture carries no dec_ref_pic_marking",
729 ));
730 };
731 cur = (Mark::Short, 0);
732 if m.adaptive {
733 cur = self.apply_mmco_i(m, info)?;
734 } else {
735 self.sliding_window_i(sps, info)?;
736 }
737 }
738 // A second field's store index may have shifted if MMCO emptied slots;
739 // the buffer only reclaims slots after output, so it has not.
740 let own = info.second_of;
741
742 if own.is_none() && self.frames.len() >= MAX_STORED {
743 return Err(Error::corrupt("decoded picture buffer overflow"));
744 }
745
746 // After MMCO 5 the picture counts as frame_num 0 with its POC rebased
747 // (8.2.1).
748 let mut fpoc_rebase = [0i32; 2];
749 if has_mmco5 {
750 pic.frame_num = 0;
751 pic.frame_num_offset = 0;
752 pic.poc_msb = 0;
753 match structure {
754 FRAME => {
755 let t = pic.fpoc[0].min(pic.fpoc[1]);
756 fpoc_rebase = [t, t];
757 }
758 TOP => fpoc_rebase[0] = pic.fpoc[0],
759 _ => fpoc_rebase[1] = pic.fpoc[1],
760 }
761 }
762
763 let prev_lsb_after_mmco5;
764 let stored_id;
765 match structure {
766 FRAME => {
767 pic.have = [true, true];
768 pic.fmark = [cur.0; 2];
769 if cur.0 == Mark::Long {
770 pic.long_term_frame_idx = cur.1;
771 }
772 pic.output = output_ok;
773 pic.complete = true;
774 pic.awaiting_second = false;
775 for (v, r) in pic.fpoc.iter_mut().zip(fpoc_rebase) {
776 *v -= r;
777 }
778 self.attach_fields_from_frame(&mut pic);
779 pic.refresh();
780 prev_lsb_after_mmco5 = pic.fpoc[0];
781 stored_id = pic.id;
782 self.frames.push(pic);
783 }
784 _ => {
785 let p = usize::from(structure) - 1;
786 let k = match own {
787 Some(k) => k,
788 None => {
789 let mut shell = self.take_picture();
790 shell.start(sps);
791 shell.coding = CODED_FLD;
792 shell.frame_num = pic.frame_num;
793 shell.frame_num_offset = pic.frame_num_offset;
794 shell.poc_msb = pic.poc_msb;
795 shell.poc_lsb = pic.poc_lsb;
796 shell.pts = pic.pts;
797 shell.color = pic.color;
798 shell.output = output_ok;
799 shell.awaiting_second = true;
800 shell.complete = true;
801 shell.long_term_frame_idx = 0;
802 while shell.fields.len() < 2 {
803 let mut f = self.take_field_picture();
804 f.structure = shell.fields.len() as u8 + 1;
805 shell.fields.push(f);
806 }
807 self.frames.push(shell);
808 self.frames.len() - 1
809 }
810 };
811 pic.fpoc[p] -= fpoc_rebase[p];
812 pic.poc = pic.fpoc[p];
813 let store = &mut self.frames[k];
814 pic.id = store.id + 1 + p as i32;
815 pic.complete = true;
816 pic.mark = cur.0;
817 let old = core::mem::replace(&mut store.fields[p], pic);
818 store.have[p] = true;
819 store.fpoc[p] = store.fields[p].poc;
820 store.fmark[p] = cur.0;
821 if cur.0 == Mark::Long {
822 store.long_term_frame_idx = cur.1;
823 }
824 if own.is_some() {
825 store.awaiting_second = false;
826 Self::weave(store);
827 }
828 if has_mmco5 {
829 store.frame_num = 0;
830 }
831 store.refresh();
832 prev_lsb_after_mmco5 = if structure == TOP { store.fpoc[0] } else { 0 };
833 stored_id = store.id;
834 self.recycle(old);
835 }
836 }
837
838 self.prev_frame_num = if has_mmco5 { 0 } else { info.frame_num };
839 self.prev_frame_num_offset = if has_mmco5 { 0 } else { frame_num_offset };
840 self.prev_has_mmco5 = has_mmco5;
841 if info.is_reference {
842 self.prev_ref_frame_num = if has_mmco5 { 0 } else { info.frame_num };
843 self.prev_poc_msb = if has_mmco5 { 0 } else { poc_msb };
844 self.prev_poc_lsb = if has_mmco5 {
845 prev_lsb_after_mmco5
846 } else {
847 poc_lsb
848 };
849 }
850 self.started = true;
851 if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) {
852 self.pending_flush = true;
853 }
854 self.last_id = stored_id;
855 Ok(())
856 }
857}
858
859impl<S: Sample> Picture<S> {
860 /// True when a long-term field of this store sits above the limit.
861 fn long_term_frame_idx_over(&self, limit: Option<u32>) -> bool {
862 self.fmark.contains(&Mark::Long) && limit.is_none_or(|max| self.long_term_frame_idx > max)
863 }
864}