kodecs-vaapi 0.2.1

VA-API H.264 and H.265 hardware encode and decode, forked from discord/cros-libva and discord/cros-codecs, with libva loaded at runtime
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use std::cmp::Reverse;
use std::fmt;

use tracing::debug;

use crate::codec::h264::picture::PictureData;
use crate::codec::h264::picture::Reference;
use kodecs_h264::PicOrderCnt;
use kodecs_h264::Sps;

pub type DpbPicRefList<'a, H> = Vec<&'a DpbEntry<H>>;

/// All the reference picture lists used to decode a picture, as indices into
/// the DPB's entries.
#[derive(Default)]
pub struct ReferencePicLists {
	/// Reference picture list for P slices. Retains the same meaning as in the
	/// specification. Derived once per picture.
	pub ref_pic_list_p0: Vec<usize>,
	/// Reference picture list 0 for B slices. Retains the same meaning as in
	/// the specification. Derived once per picture.
	pub ref_pic_list_b0: Vec<usize>,
	/// Reference picture list 1 for B slices. Retains the same meaning as in
	/// the specification. Derived once per picture.
	pub ref_pic_list_b1: Vec<usize>,
}

/// A single entry in the DPB.
pub struct DpbEntry<T> {
	/// `PictureData` of the frame in this entry.
	pub pic: PictureData,
	/// Reference to the decoded frame, ensuring that it doesn't get reused while in the DPB.
	pub reference: Option<T>,
	/// Decoded frame promise. It will be set when the frame enters the DPB, and taken during the
	/// bump process.
	pub decoded_frame: Option<T>,
	/// Whether the picture is still waiting to be bumped and displayed.
	needed_for_output: bool,
}

/// The decoded picture buffer of a progressive stream, one frame per entry.
pub struct Dpb<T> {
	/// List of `PictureData` and backend handles to decoded pictures.
	entries: Vec<DpbEntry<T>>,
	/// The maximum number of pictures that can be stored.
	max_num_pics: usize,
	/// Indicates an upper bound for the number of frames buffers, in the
	/// decoded picture buffer (DPB), that are required for storing frames
	/// before output. It is a requirement of bitstream conformance that the
	/// maximum number of frames that precede any frame in the coded video
	/// sequence in decoding order and follow it in output order shall be less
	/// than or equal to max_num_reorder_frames.
	max_num_reorder_frames: usize,
	/// Frames added to `max_num_reorder_frames` because the stream reordered
	/// more than its SPS declares. Kept across sequences, since an encoder
	/// that understates the limit once does so in every SPS it writes.
	reorder_shortfall: usize,
	/// The highest order count output since the DPB was last cleared.
	last_output_poc: Option<i32>,
}

#[derive(Debug)]
pub enum StorePictureError {
	DpbIsFull,
}

impl fmt::Display for StorePictureError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		write!(f, "DPB is full")
	}
}

impl std::error::Error for StorePictureError {}

#[derive(Debug)]
pub enum MmcoError {
	NoShortTermPic,
	NoLongTermPic,
	ExpectedExisting,
}

impl fmt::Display for MmcoError {
	fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
		match self {
			MmcoError::NoShortTermPic => {
				write!(f, "could not find ShortTerm picture to mark in the DPB")
			}
			MmcoError::NoLongTermPic => {
				write!(f, "could not find LongTerm picture to mark in the DPB")
			}
			MmcoError::ExpectedExisting => {
				write!(f, "picture cannot be marked as nonexisting for MMCO=3")
			}
		}
	}
}

impl std::error::Error for MmcoError {}

impl<T: Clone> Dpb<T> {
	/// Returns an iterator over the underlying H264 pictures stored in the
	/// DPB.
	fn pictures(&self) -> impl Iterator<Item = &PictureData> {
		self.entries.iter().map(|h| &h.pic)
	}

	/// Returns a mutable iterator over the underlying H264 pictures stored in
	/// the DPB.
	fn pictures_mut(&mut self) -> impl Iterator<Item = &mut PictureData> {
		self.entries.iter_mut().map(|h| &mut h.pic)
	}

	/// Returns the length of the DPB.
	pub fn len(&self) -> usize {
		self.entries.len()
	}

	pub fn is_empty(&self) -> bool {
		self.len() == 0
	}

	/// Get a reference to the whole DPB entries.
	pub fn entries(&self) -> &Vec<DpbEntry<T>> {
		&self.entries
	}

	/// Set the DPB's limits in terms of maximum number or pictures.
	pub fn set_limits(&mut self, max_num_pics: usize, max_num_reorder_frames: usize) {
		self.max_num_pics = max_num_pics;
		self.max_num_reorder_frames = max_num_reorder_frames;
	}

	/// Returns the number of reference frames.
	pub fn num_ref_frames(&self) -> usize {
		self.pictures().filter(|p| p.is_ref()).count()
	}

	/// Mark all pictures in the DPB as unused for reference.
	pub fn mark_all_as_unused_for_ref(&mut self) {
		for picture in self.pictures_mut() {
			picture.set_reference(Reference::None);
		}
	}

	/// Remove unused pictures from the DPB. A picture is not going to be used
	/// anymore if it's a) not a reference and b) not needed for output
	fn remove_unused(&mut self) {
		self.entries
			.retain(|entry| entry.pic.is_ref() || entry.needed_for_output);
	}

	/// Find a short term reference picture with the given `pic_num` value.
	fn find_short_term_with_pic_num_pos(&self, pic_num: i32) -> Option<usize> {
		self.pictures()
			.position(|p| matches!(p.reference(), Reference::ShortTerm) && p.pic_num == pic_num)
	}

	/// Find a short term reference picture with the given `pic_num` value.
	pub fn find_short_term_with_pic_num(&self, pic_num: i32) -> Option<&DpbEntry<T>> {
		let position = self.find_short_term_with_pic_num_pos(pic_num)?;
		Some(&self.entries[position])
	}

	/// Find a long term reference picture with the given `long_term_pic_num`
	/// value.
	fn find_long_term_with_long_term_pic_num_pos(&self, long_term_pic_num: u32) -> Option<usize> {
		self.pictures()
			.position(|p| matches!(p.reference(), Reference::LongTerm) && p.long_term_pic_num == long_term_pic_num)
	}

	/// Find a long term reference picture with the given `long_term_pic_num`
	/// value.
	pub fn find_long_term_with_long_term_pic_num(&self, long_term_pic_num: u32) -> Option<&DpbEntry<T>> {
		let position = self.find_long_term_with_long_term_pic_num_pos(long_term_pic_num)?;
		Some(&self.entries[position])
	}

	/// Store `picture` and its backend handle in the DPB.
	pub fn store_picture(&mut self, pic: PictureData, handle: Option<T>) -> Result<(), StorePictureError> {
		if self.entries.len() >= self.max_num_pics {
			return Err(StorePictureError::DpbIsFull);
		}

		// C.4.2. Decoding of gaps in frame_num and storage of "non-existing"
		// pictures
		let needed_for_output = !pic.nonexisting;

		debug!(
			"Stored picture POC {:?}, the DPB length is {:?}",
			pic.pic_order_cnt,
			self.entries.len()
		);

		self.entries.push(DpbEntry {
			pic,
			reference: handle.clone(),
			decoded_frame: handle,
			needed_for_output,
		});

		Ok(())
	}

	/// Whether the DPB has an empty slot for a new picture.
	pub fn has_empty_frame_buffer(&self) -> bool {
		self.entries.len() < self.max_num_pics
	}

	/// Whether the DPB needs bumping, as described by clauses 1, 4, 5, 6 of
	/// C.4.5.3 "Bumping" process.
	pub fn needs_bumping(&self, to_insert: &PictureData) -> bool {
		// In C.4.5.3 we handle clauses 2 and 3 separately. All other clauses
		// check for an empty frame buffer first. Here we handle:
		//    - There is no empty frame buffer and a empty frame buffer is
		//    needed for storage of an inferred "non-existing" frame.
		//
		//    - There is no empty frame buffer and an empty frame buffer is
		//    needed for storage of a decoded (non-IDR) reference picture.
		//
		//    - There is no empty frame buffer and the current picture is a non-
		//    reference picture and there are pictures in the DPB that are
		//    marked as "needed for output" that precede the current
		//    non-reference picture in output order.
		//
		// Clauses 2 and 3 are handled by H264Codec::handle_picture and
		// H264Codec::finish_picture, respectively.
		if self.has_empty_frame_buffer() {
			return false;
		}

		if to_insert.nonexisting {
			return true;
		}

		if to_insert.is_ref() && !to_insert.idr {
			return true;
		}

		match self.find_lowest_poc_for_bumping() {
			Some(lowest) => to_insert.pic_order_cnt > self.entries[lowest].pic.pic_order_cnt,
			None => false,
		}
	}

	/// Find the position of the lowest POC in the DPB that can be bumped.
	fn find_lowest_poc_for_bumping(&self) -> Option<usize> {
		self.entries
			.iter()
			.enumerate()
			.filter(|(_, entry)| entry.needed_for_output)
			.min_by_key(|(_, entry)| entry.pic.pic_order_cnt)
			.map(|(position, _)| position)
	}

	/// Bump the dpb, returning a picture as per the bumping process described in C.4.5.3.
	fn bump(&mut self) -> Option<Option<T>> {
		let position = self.find_lowest_poc_for_bumping()?;
		let dpb_entry = &mut self.entries[position];
		let handle = dpb_entry.decoded_frame.take();
		dpb_entry.needed_for_output = false;

		let poc = dpb_entry.pic.pic_order_cnt;
		debug!("Bumping picture POC {poc} from the dpb");
		self.last_output_poc = Some(self.last_output_poc.map_or(poc, |last| last.max(poc)));

		Some(handle)
	}

	/// Drains the DPB by continuously invoking the bumping process.
	pub fn drain(&mut self) -> Vec<Option<T>> {
		debug!("Draining the DPB.");

		let mut pics = vec![];

		while let Some(pic) = self.bump() {
			pics.push(pic);
		}

		self.clear();

		pics
	}

	/// Clears the DPB, dropping all the pictures.
	pub fn clear(&mut self) {
		debug!("Clearing the DPB");

		self.entries.clear();
		self.last_output_poc = None;
	}

	/// Returns an iterator of short term refs.
	pub fn short_term_refs_iter(&self) -> impl Iterator<Item = &DpbEntry<T>> {
		self.entries
			.iter()
			.filter(|&handle| matches!(handle.pic.reference(), Reference::ShortTerm))
	}

	/// Returns an iterator of long term refs.
	pub fn long_term_refs_iter(&self) -> impl Iterator<Item = &DpbEntry<T>> {
		self.entries
			.iter()
			.filter(|&handle| matches!(handle.pic.reference(), Reference::LongTerm))
	}

	/// 8.2.4.1: derives the picture numbers of the references for decoding the
	/// frame `frame_num`.
	pub fn update_pic_nums(&mut self, frame_num: u32, max_frame_num: u32) {
		for pic in self.pictures_mut() {
			match *pic.reference() {
				Reference::None => {}
				Reference::LongTerm => pic.long_term_pic_num = pic.long_term_frame_idx,
				Reference::ShortTerm => {
					pic.frame_num_wrap = if pic.frame_num > frame_num {
						pic.frame_num as i32 - max_frame_num as i32
					} else {
						pic.frame_num as i32
					};
					pic.pic_num = pic.frame_num_wrap;
				}
			}
		}
	}

	/// Bumps the DPB if needed. DPB bumping is described on C.4.5.3.
	pub fn bump_as_needed(&mut self, current_pic: &PictureData) -> Vec<Option<T>> {
		let mut pics = vec![];
		while self.needs_bumping(current_pic) && self.len() >= self.max_num_reorder_frames {
			match self.bump() {
				Some(pic) => pics.push(pic),
				None => return pics,
			}
			self.remove_unused();
		}

		pics
	}

	/// Stores or outputs a decoded picture whose reference marking has run,
	/// appending the pictures that leave the DPB to `output` in output order.
	///
	/// C.4.4 empties every frame buffer the marking left unused for reference
	/// and not needed for output, before C.4.5.3 bumps for the new picture. A
	/// picture already output stays only as a reference, so it must leave the
	/// moment memory management releases it, even when nothing is left to bump.
	/// C.4.5.1 stores a reference picture after bumping until a frame buffer is
	/// free. C.4.5.2 stores a non-reference picture when a buffer is free, and
	/// outputs it directly otherwise. Whatever the reorder limit already lets out
	/// then leaves now rather than when a later picture needs its buffer.
	pub fn finish_picture(
		&mut self,
		pic: PictureData,
		handle: T,
		output: &mut Vec<T>,
	) -> Result<(), StorePictureError> {
		self.check_output_order(&pic);
		self.remove_unused();

		output.extend(self.bump_as_needed(&pic).into_iter().flatten());
		if pic.is_ref() || self.has_empty_frame_buffer() {
			self.store_picture(pic, Some(handle))?;
		} else {
			self.output_unstored(&pic);
			output.push(handle);
		}
		output.extend(self.bump_over_reorder_limit().into_iter().flatten());

		Ok(())
	}

	/// Bumps the pictures the stream's reorder limit already lets out.
	///
	/// C.4.5.3 bumps only when a new picture needs a frame buffer, which fixes
	/// the output order but not how early a picture may leave. A stream that
	/// declares one frame buffer and no reordering would trail by a picture,
	/// released only when the next one needs its buffer. No more than
	/// `max_num_reorder_frames` frames may precede a frame in decoding order
	/// and follow it in output order, so once more than that wait for output,
	/// no later picture can come before the one with the lowest order count,
	/// and it is due now.
	fn bump_over_reorder_limit(&mut self) -> Vec<Option<T>> {
		let limit = self.reorder_limit();
		let mut pics = vec![];
		while self.entries.iter().filter(|entry| entry.needed_for_output).count() > limit {
			match self.bump() {
				Some(pic) => pics.push(pic),
				None => break,
			}
		}
		self.remove_unused();

		pics
	}

	/// Records that `pic` was output without passing through the DPB, as
	/// C.4.5.2 does with a non-reference picture when no frame buffer is free.
	fn output_unstored(&mut self, pic: &PictureData) {
		let poc = pic.pic_order_cnt;
		self.last_output_poc = Some(self.last_output_poc.map_or(poc, |last| last.max(poc)));
	}

	/// Raises the reorder limit when `pic` belongs before a picture already
	/// output.
	///
	/// A conforming stream never does this, but the VUI's limit is only as
	/// good as the encoder that wrote it, and bumping by it trusts the stream
	/// further than C.4.5.3 does. A stream that understates its reordering
	/// shows one picture out of order and then gets one more frame of slack,
	/// up to the DPB size, which is where C.4.5.3 alone would have left it.
	fn check_output_order(&mut self, pic: &PictureData) {
		let Some(last_output_poc) = self.last_output_poc else {
			return;
		};
		if pic.nonexisting || pic.pic_order_cnt >= last_output_poc || self.reorder_limit() >= self.max_num_pics {
			return;
		}

		self.reorder_shortfall += 1;
		tracing::warn!(
			poc = pic.pic_order_cnt,
			last_output_poc,
			declared = self.max_num_reorder_frames,
			limit = self.reorder_limit(),
			"H.264 stream reorders more than its SPS declares, raising the reorder limit"
		);
	}

	/// Returns how many frames may wait for output before the one with the
	/// lowest order count is due: the SPS's limit plus whatever the stream has
	/// shown it understates, bounded by the DPB size.
	fn reorder_limit(&self) -> usize {
		(self.max_num_reorder_frames + self.reorder_shortfall).min(self.max_num_pics)
	}

	// 8.2.5.3
	pub fn sliding_window_marking(&mut self, sps: &Sps) {
		let mut num_ref_pics = self.num_ref_frames();
		let max_num_ref_frames = std::cmp::max(1, usize::from(sps.max_num_ref_frames));

		if num_ref_pics < max_num_ref_frames {
			return;
		}

		while num_ref_pics >= max_num_ref_frames {
			let lowest = self
				.entries
				.iter_mut()
				.filter(|h| matches!(h.pic.reference(), Reference::ShortTerm))
				.min_by_key(|h| h.pic.frame_num_wrap);
			match lowest {
				Some(to_unmark) => {
					to_unmark.pic.set_reference(Reference::None);
					num_ref_pics -= 1;
				}
				None => {
					tracing::warn!("could not find a ShortTerm picture to unmark in the DPB");
					break;
				}
			}
		}

		self.remove_unused();
	}

	/// `memory_management_control_operation` 1: unmarks the short-term
	/// picture `difference_of_pic_nums_minus1 + 1` before `pic`.
	pub fn mmco_op_1(&mut self, pic: &PictureData, difference_of_pic_nums_minus1: u32) -> Result<(), MmcoError> {
		let pic_num_x = i32::try_from(i64::from(pic.pic_num) - i64::from(difference_of_pic_nums_minus1) - 1)
			.map_err(|_| MmcoError::NoShortTermPic)?;

		tracing::debug!("MMCO op 1 for pic_num_x {}", pic_num_x);

		let position = self
			.find_short_term_with_pic_num_pos(pic_num_x)
			.ok_or(MmcoError::NoShortTermPic)?;
		self.entries[position].pic.set_reference(Reference::None);

		Ok(())
	}

	/// `memory_management_control_operation` 2: unmarks the long-term picture
	/// `long_term_pic_num`.
	pub fn mmco_op_2(&mut self, long_term_pic_num: u32) -> Result<(), MmcoError> {
		tracing::debug!("MMCO op 2 for long_term_pic_num {}", long_term_pic_num);

		let position = self
			.find_long_term_with_long_term_pic_num_pos(long_term_pic_num)
			.ok_or(MmcoError::NoLongTermPic)?;
		self.entries[position].pic.set_reference(Reference::None);

		Ok(())
	}

	/// `memory_management_control_operation` 3: makes the short-term picture
	/// `difference_of_pic_nums_minus1 + 1` before `pic` long-term, at
	/// `long_term_frame_idx`.
	pub fn mmco_op_3(
		&mut self,
		pic: &PictureData,
		difference_of_pic_nums_minus1: u32,
		long_term_frame_idx: u32,
	) -> Result<(), MmcoError> {
		let pic_num_x = i32::try_from(i64::from(pic.pic_num) - i64::from(difference_of_pic_nums_minus1) - 1)
			.map_err(|_| MmcoError::NoShortTermPic)?;

		tracing::debug!("MMCO op 3 for pic_num_x {}", pic_num_x);

		let position = self
			.find_short_term_with_pic_num_pos(pic_num_x)
			.ok_or(MmcoError::NoShortTermPic)?;
		if self.entries[position].pic.nonexisting {
			return Err(MmcoError::ExpectedExisting);
		}

		// When LongTermFrameIdx equal to long_term_frame_idx is already
		// assigned to a long-term reference frame, that frame is marked as
		// "unused for reference".
		self.forget_long_term_frame_idx(long_term_frame_idx);

		let to_mark = &mut self.entries[position].pic;
		to_mark.set_reference(Reference::LongTerm);
		to_mark.long_term_frame_idx = long_term_frame_idx;

		Ok(())
	}

	/// `memory_management_control_operation` 4: unmarks the long-term pictures
	/// at or past `max_long_term_frame_idx_plus1`, which it returns.
	pub fn mmco_op_4(&mut self, max_long_term_frame_idx_plus1: u32) -> u32 {
		tracing::debug!(
			"MMCO op 4, max_long_term_frame_idx_plus1: {:?}",
			max_long_term_frame_idx_plus1
		);

		for dpb_pic in self
			.pictures_mut()
			.filter(|pic| matches!(pic.reference(), Reference::LongTerm))
			.filter(|pic| pic.long_term_frame_idx >= max_long_term_frame_idx_plus1)
		{
			dpb_pic.set_reference(Reference::None);
		}

		max_long_term_frame_idx_plus1
	}

	/// `memory_management_control_operation` 5: unmarks every picture, and
	/// returns the new `MaxLongTermFrameIdx + 1`, none.
	pub fn mmco_op_5(&mut self, pic: &mut PictureData) -> u32 {
		tracing::debug!("MMCO op 5, marking all pictures in the DPB as unused for reference");

		self.mark_all_as_unused_for_ref();

		pic.has_mmco_5 = true;

		// A picture including a memory_management_control_operation equal to 5
		// shall have frame_num constraints as described above and, after the
		// decoding of the current picture and the processing of the memory
		// management control operations, the picture shall be inferred to have
		// had frame_num equal to 0 for all subsequent use in the decoding
		// process, except as specified in clause 7.4.1.2.4.
		pic.frame_num = 0;

		// When the current picture includes a
		// memory_management_control_operation equal to 5, after the decoding of
		// the current picture, tempPicOrderCnt is set equal to PicOrderCnt(
		// CurrPic ), TopFieldOrderCnt of the current picture is set equal to
		// TopFieldOrderCnt − tempPicOrderCnt, and BottomFieldOrderCnt of the
		// current picture is set equal to BottomFieldOrderCnt − tempPicOrderCnt.
		// Saturates rather than overflows for a stream whose fields are further
		// apart than an `i32` holds, which no conforming one is.
		pic.top_field_order_cnt = pic.top_field_order_cnt.saturating_sub(pic.pic_order_cnt);
		pic.bottom_field_order_cnt = pic.bottom_field_order_cnt.saturating_sub(pic.pic_order_cnt);
		pic.pic_order_cnt = std::cmp::min(pic.top_field_order_cnt, pic.bottom_field_order_cnt);

		0
	}

	/// `memory_management_control_operation` 6: makes `pic` long-term at
	/// `long_term_frame_idx`.
	pub fn mmco_op_6(&mut self, pic: &mut PictureData, long_term_frame_idx: u32) {
		tracing::debug!("MMCO op 6, long_term_frame_idx: {}", long_term_frame_idx);

		// When a variable LongTermFrameIdx equal to long_term_frame_idx is
		// already assigned to a long-term reference frame, that frame is marked
		// as "unused for reference".
		self.forget_long_term_frame_idx(long_term_frame_idx);

		pic.set_reference(Reference::LongTerm);
		pic.long_term_frame_idx = long_term_frame_idx;
	}

	/// Unmarks the long-term frame at `long_term_frame_idx`, if there is one.
	fn forget_long_term_frame_idx(&mut self, long_term_frame_idx: u32) {
		if let Some(pic) = self.pictures_mut().find(|pic| {
			matches!(pic.reference(), Reference::LongTerm) && pic.long_term_frame_idx == long_term_frame_idx
		}) {
			pic.set_reference(Reference::None);
		}
	}

	/// The positions of the references `marked` as, in DPB order.
	fn refs(&self, marked: Reference, existing_only: bool) -> Vec<usize> {
		(0..self.entries.len())
			.filter(|&i| {
				let pic = &self.entries[i].pic;
				*pic.reference() == marked && !(existing_only && pic.nonexisting)
			})
			.collect()
	}

	/// 8.2.4.2.1 Initialization process for the reference picture list for P
	/// and SP slices in frames
	fn build_ref_pic_list_p(&self) -> Vec<usize> {
		let mut ref_pic_list_p0 = self.refs(Reference::ShortTerm, false);
		ref_pic_list_p0.sort_by_key(|&i| Reverse(self.entries[i].pic.pic_num));

		let mut long_term = self.refs(Reference::LongTerm, false);
		long_term.sort_by_key(|&i| self.entries[i].pic.long_term_pic_num);
		ref_pic_list_p0.extend(long_term);

		ref_pic_list_p0
	}

	// 8.2.4.2.3 Initialization process for reference picture lists for B slices
	// in frames
	fn build_ref_pic_list_b(&self, cur_pic: &PictureData, sps: &Sps) -> (Vec<usize>, Vec<usize>) {
		// When pic_order_cnt_type is equal to 0, reference pictures that are
		// marked as "non-existing" as specified in clause 8.2.5.2 are not
		// included in either RefPicList0 or RefPicList1.
		let short_term_refs = self.refs(
			Reference::ShortTerm,
			matches!(sps.pic_order_cnt, PicOrderCnt::Lsb { .. }),
		);
		let poc = |i: usize| self.entries[i].pic.pic_order_cnt;

		// b0 contains three inner lists of pictures, i.e. [[0] [1] [2]]
		// [0]: short term pictures with POC < current, sorted by descending POC.
		// [1]: short term pictures with POC > current, sorted by ascending POC.
		// [2]: long term pictures sorted by ascending long_term_pic_num
		let (mut ref_pic_list_b0, mut remaining): (Vec<usize>, Vec<usize>) =
			short_term_refs.iter().partition(|&&i| poc(i) < cur_pic.pic_order_cnt);
		ref_pic_list_b0.sort_by_key(|&i| Reverse(poc(i)));
		remaining.sort_by_key(|&i| poc(i));
		ref_pic_list_b0.extend(remaining);

		let mut long_term_refs = self.refs(Reference::LongTerm, true);
		long_term_refs.sort_by_key(|&i| self.entries[i].pic.long_term_pic_num);
		ref_pic_list_b0.extend(&long_term_refs);

		// b1 contains three inner lists of pictures, i.e. [[0] [1] [2]]
		// [0]: short term pictures with POC > current, sorted by ascending POC.
		// [1]: short term pictures with POC < current, sorted by descending POC.
		// [2]: long term pictures sorted by ascending long_term_pic_num
		let (mut ref_pic_list_b1, mut remaining): (Vec<usize>, Vec<usize>) =
			short_term_refs.iter().partition(|&&i| poc(i) > cur_pic.pic_order_cnt);
		ref_pic_list_b1.sort_by_key(|&i| poc(i));
		remaining.sort_by_key(|&i| Reverse(poc(i)));
		ref_pic_list_b1.extend(remaining);
		ref_pic_list_b1.extend(long_term_refs);

		// When the reference picture list RefPicList1 has more than one entry
		// and RefPicList1 is identical to the reference picture list
		// RefPicList0, the first two entries RefPicList1[0] and RefPicList1[1]
		// are switched.
		if ref_pic_list_b1.len() > 1 && ref_pic_list_b0 == ref_pic_list_b1 {
			ref_pic_list_b1.swap(0, 1);
		}

		(ref_pic_list_b0, ref_pic_list_b1)
	}

	/// Returns the lists of reference pictures for `pic`.
	pub fn build_ref_pic_lists(&self, pic: &PictureData, sps: &Sps) -> ReferencePicLists {
		let num_refs = self.pictures().filter(|p| p.is_ref() && !p.nonexisting).count();

		// 8.2.4.2.1 ~ 8.2.4.2.4: When this process is invoked, there shall be
		// at least one reference frame or complementary reference field pair
		// that is currently marked as "used for reference" (i.e., as "used for
		// short-term reference" or "used for long-term reference") and is not
		// marked as "non-existing".
		if num_refs == 0 {
			return Default::default();
		}

		let (ref_pic_list_b0, ref_pic_list_b1) = self.build_ref_pic_list_b(pic, sps);
		ReferencePicLists {
			ref_pic_list_p0: self.build_ref_pic_list_p(),
			ref_pic_list_b0,
			ref_pic_list_b1,
		}
	}
}

impl<T> Default for Dpb<T> {
	fn default() -> Self {
		// See https://github.com/rust-lang/rust/issues/26925 on why this can't
		// be derived.
		Self {
			entries: Default::default(),
			max_num_pics: Default::default(),
			max_num_reorder_frames: Default::default(),
			reorder_shortfall: Default::default(),
			last_output_poc: Default::default(),
		}
	}
}

#[cfg(test)]
mod tests {
	use super::*;

	/// A progressive non-reference frame with order count `poc`.
	fn frame(poc: i32) -> PictureData {
		let mut pic = PictureData::default();
		pic.pic_order_cnt = poc;
		pic
	}

	/// Decodes non-reference frames with order counts `pocs`, returning what
	/// comes out.
	fn decode(dpb: &mut Dpb<i32>, pocs: &[i32]) -> Vec<i32> {
		let mut output = Vec::new();
		for &poc in pocs {
			dpb.finish_picture(frame(poc), poc, &mut output)
				.expect("store a non-reference frame");
		}
		output
	}

	/// A reference that was output as soon as it decoded frees its frame buffer
	/// the moment memory management releases it, whether it was a short-term
	/// reference (MMCO 1) or a long-term one (MMCO 2). A one-frame DPB with no
	/// reordering has nothing left to bump, so it would otherwise stay full.
	#[test]
	fn a_released_reference_already_output_frees_its_buffer() {
		for long_term in [false, true] {
			let mut dpb = Dpb::default();
			dpb.set_limits(1, 0);
			let mut output = Vec::new();

			let mut idr = frame(0);
			idr.idr = true;
			if long_term {
				idr.set_reference(Reference::LongTerm);
			} else {
				idr.set_reference(Reference::ShortTerm);
			}
			dpb.finish_picture(idr, 0, &mut output).expect("store the IDR");
			assert_eq!(output, [0], "a stream without reordering lets the IDR out at once");

			let mut p = frame(2);
			p.frame_num = 1;
			p.pic_num = 1;
			p.set_reference(Reference::ShortTerm);
			dpb.update_pic_nums(p.frame_num, 16);
			if long_term {
				dpb.mmco_op_2(0).expect("release the long-term IDR");
			} else {
				dpb.mmco_op_1(&p, 0).expect("release the short-term IDR");
			}

			dpb.finish_picture(p, 2, &mut output)
				.expect("the released IDR frees its frame buffer");
			assert_eq!(output, [0, 2]);
			assert_eq!(dpb.len(), 1, "only the new reference is left");
		}
	}

	/// A stream that reorders by the amount it declares comes out in order, each
	/// picture as soon as the limit lets it out.
	#[test]
	fn bumping_by_the_reorder_limit_keeps_output_order() {
		let mut dpb = Dpb::default();
		dpb.set_limits(4, 1);
		assert_eq!(decode(&mut dpb, &[0, 4, 2, 8, 6]), [0, 2, 4, 6]);
		assert_eq!(dpb.drain().into_iter().flatten().collect::<Vec<_>>(), [8]);
	}

	/// A stream that reorders while declaring it does not shows one picture out
	/// of order, then gets the slack it needs and keeps it across a clear.
	#[test]
	fn understated_reordering_raises_the_limit() {
		let mut dpb = Dpb::default();
		dpb.set_limits(4, 0);
		assert_eq!(decode(&mut dpb, &[0, 4, 2]), [0, 4]);
		assert_eq!(dpb.reorder_limit(), 1);
		assert_eq!(decode(&mut dpb, &[8, 6, 12, 10]), [2, 6, 8, 10]);

		// A new sequence starts its order counts over, which is not a violation,
		// and an SPS that repeats the understated limit does not lose the slack.
		dpb.drain();
		dpb.set_limits(4, 0);
		assert_eq!(decode(&mut dpb, &[0, 4, 2, 8]), [0, 2, 4]);
		assert_eq!(dpb.reorder_limit(), 1);
	}

	/// The slack stops at the DPB size, which is all C.4.5.3 ever holds back.
	#[test]
	fn the_raised_limit_stops_at_the_dpb_size() {
		let mut dpb = Dpb::default();
		dpb.set_limits(2, 0);
		decode(&mut dpb, &[0, 10, 8, 6]);
		assert_eq!(dpb.reorder_limit(), 2);

		dpb.check_output_order(&frame(4));
		assert_eq!(dpb.reorder_limit(), 2);
	}
}