forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'lane-h265enc-swap' (4808c4a): the HEVC encode seat is ec-h265 and oxideav-h265 leaves the tree (47+ vendor files, conformance-window patch with them -- ec-h265 self-pads and writes the crop) -- reviewer-executed validity: +1.22 dB PSNR-Y at -25.6% bytes vs the old seat at qp40 (+1.02 dB at -11.1% qp27), export wall 1.07-1.10x, mkv+mp4 decode back through the VA-API plugin seat, frame-parallel batching preserved byte-identically

Browse files at this commit

49b300a17cd73ab8fc921d86b96c6d9fb98ed8c7Ahmet Kaan GümüşParent: b4c6bea4808c4a
# Conflicts:
#	Cargo.toml
#	crates/engine/src/caps.rs

67 changed files +182 -68256

Cargo.lockmodified+18 -8
@@ -1647,6 +1647,22 @@ dependencies = [
1647 "ec-core",1647 "ec-core",
1648 ]1648 ]
1649 1649
1650+[[package]]
1651+name = "ec-h265"
1652+version = "0.1.0"
1653+dependencies = [
1654+ "ec-core",
1655+ "ec-h265-syntax",
1656+ "wide",
1657+]
1658+
1659+[[package]]
1660+name = "ec-h265-syntax"
1661+version = "0.1.0"
1662+dependencies = [
1663+ "ec-core",
1664+]
1665+
1650 [[package]]1666 [[package]]
1651 name = "ec-opus"1667 name = "ec-opus"
1652 version = "0.1.0"1668 version = "0.1.0"
@@ -1717,6 +1733,8 @@ dependencies = [
1717 "ec-av1",1733 "ec-av1",
1718 "ec-core",1734 "ec-core",
1719 "ec-h264",1735 "ec-h264",
1736+ "ec-h265",
1737+ "ec-h265-syntax",
1720 "ec-opus",1738 "ec-opus",
1721 "flacenc",1739 "flacenc",
1722 "hound",1740 "hound",
@@ -1727,7 +1745,6 @@ dependencies = [
1727 "mp4",1745 "mp4",
1728 "oxideav-ass",1746 "oxideav-ass",
1729 "oxideav-core",1747 "oxideav-core",
1730- "oxideav-h265",
1731 "oxideav-ogg",1748 "oxideav-ogg",
1732 "oxideav-sub-image",1749 "oxideav-sub-image",
1733 "oxideav-subtitle",1750 "oxideav-subtitle",
@@ -4043,13 +4060,6 @@ dependencies = [
4043 "thiserror 2.0.20",4060 "thiserror 2.0.20",
4044 ]4061 ]
4045 4062
4046-[[package]]
4047-name = "oxideav-h265"
4048-version = "0.0.9"
4049-dependencies = [
4050- "oxideav-core",
4051-]
4052-
4053 [[package]]4063 [[package]]
4054 name = "oxideav-ogg"4064 name = "oxideav-ogg"
4055 version = "0.1.8"4065 version = "0.1.8"
Cargo.tomlmodified+9 -15
@@ -5,7 +5,7 @@ members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/a
5 exclude = [5 exclude = [
6 "vendor/cros-libva",6 "vendor/cros-libva",
7 "vendor/cros-codecs",7 "vendor/cros-codecs",
8- "vendor/oxideav-h265",8+
9 "vendor/mp4",9 "vendor/mp4",
10 ]10 ]
11 11
@@ -13,9 +13,9 @@ exclude = [
13 version = "0.1.0"13 version = "0.1.0"
14 edition = "2024"14 edition = "2024"
15 15
16-# Four upstream crates vendored verbatim except for one clearly marked fix each,16+# Three upstream crates vendored verbatim except for one clearly marked fix each,
17 # all blockers on this machine and all still unfixed upstream as of17 # all blockers on this machine and all still unfixed upstream as of
18-# 0.0.6/0.0.13/0.0.9/0.14:18+# 0.0.6/0.0.13/0.14:
19 # cros-libva - fails to build against libva >= 1.23 headers19 # cros-libva - fails to build against libva >= 1.23 headers
20 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;20 # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses;
21 # and creates every decode context as 8-bit 4:2:0, which no HEVC21 # and creates every decode context as 8-bit 4:2:0, which no HEVC
@@ -46,17 +46,7 @@ edition = "2024"
46 # (2.2 GB over a 719-frame export). Both are fixed in place46 # (2.2 GB over a 719-frame export). Both are fixed in place
47 # and marked LOCAL PATCH47 # and marked LOCAL PATCH
48 48
49-# oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and49+
50-# refuses any dimension that is not a multiple of the 16-sample
51-# CTB, so 1920x1080 could not be written at all; the patch adds
52-# the §7.4.3.2.1 conformance window (`SpsCfg::conf_win`, one
53-# marked block in `encoder/intra.rs`) so the picture is coded
54-# padded to 1920x1088 and *displayed* at 1920x1080. Taken from
55-# git master rather than the registry -- crates.io 0.0.9 is the
56-# pre-encoder release -- at rev d35963a02c872d12e6878b4ed3cf17a
57-# 69bde5a6e, and it is a plain path dependency (no
58-# `[patch.crates-io]` line) because nothing else in the tree
59-# asks for it.
60 # mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes50 # mp4 - reads the `mp4a` sample entry as ISO only: the 8 bytes
61 # QuickTime uses for version/revision/vendor are skipped as51 # QuickTime uses for version/revision/vendor are skipped as
62 # reserved, so a version-1 SoundDescription's 16-byte tail52 # reserved, so a version-1 SoundDescription's 16-byte tail
@@ -77,7 +67,11 @@ edition = "2024"
77 # decoder's O(N^2) IMDCT through the encoder's N/4-point FFT67 # decoder's O(N^2) IMDCT through the encoder's N/4-point FFT
78 # (`dsp::dct4`, 40x the matrix version) so 5.1 was playable at68 # (`dsp::dct4`, 40x the matrix version) so 5.1 was playable at
79 # all -- a fix for a crate the tree no longer carries.69 # all -- a fix for a crate the tree no longer carries.
80-# Drop `vendor/` entirely once released versions handle all four.70+# oxideav-h265 - an eighth: `ec-h265` took the HEVC encode seat on
71+# 2026-09-13, and the vendored tree (with its §7.4.3.2.1
72+# conformance-window patch) went with it -- ec-h265 pads and
73+# writes the crop itself.
74+# Drop `vendor/` entirely once released versions handle all three.
81 [patch.crates-io]75 [patch.crates-io]
82 cros-libva = { path = "vendor/cros-libva" }76 cros-libva = { path = "vendor/cros-libva" }
83 cros-codecs = { path = "vendor/cros-codecs" }77 cros-codecs = { path = "vendor/cros-codecs" }
crates/app/src/export_ui.rsmodified+3 -3
@@ -78,9 +78,9 @@ pub(crate) fn sample_rate_choices(current: Option<u32>) -> Vec<ChoiceRow> {
78 /// `None` is exactly that kind of row, and there are two left. MP3 stopped78 /// `None` is exactly that kind of row, and there are two left. MP3 stopped
79 /// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL79 /// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
80 /// `shine-rs` was the licence question, and it is not the only encoder any80 /// `shine-rs` was the licence question, and it is not the only encoder any
81-/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an81+/// more), and HEVC stopped being one when this project gained a pure-Rust
82-/// encoder — an *intra-only* one, which the rows say rather than let a user82+/// H.265 encoder — an *intra-only* one, which the rows say rather than let a
83-/// find out from the size of the file. VP9 and VP8 are the ones this program83+/// user find out from the size of the file. VP9 and VP8 are the ones this program
84 /// still only *reads*: the plugin decodes them and there is no encoder for84 /// still only *reads*: the plugin decodes them and there is no encoder for
85 /// either here, so they are rows for the reason the refusals are rows at all —85 /// either here, so they are rows for the reason the refusals are rows at all —
86 /// a codec that opens but never comes back out is exactly the gap a user86 /// a codec that opens but never comes back out is exactly the gap a user
crates/engine/Cargo.tomlmodified+13 -8
@@ -181,14 +181,19 @@ oxideav-ass = { version = "0.0.9", default-features = false }
181 # inside rav1e itself and is what keeps an export minutes rather than tens of181 # inside rav1e itself and is what keeps an export minutes rather than tens of
182 # minutes; the cost of no assembly is measured in `export::Enc::open_av1`.182 # minutes; the cost of no assembly is measured in `export::Enc::open_av1`.
183 rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }183 rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }
184-# The software HEVC encoder, intra-only: OxideAV's pure-Rust H.265, MIT, no C184+# The software HEVC encoder, intra-only: the project's own `ec-h265`, the seat
185-# and no FFI like everything else here. Its *inter* modes run at 0.81 fps on185+# that replaces OxideAV's vendored intra encoder. Every picture is an IDR
186-# 1080p across 12 cores (measured 2026-08-11) and are therefore not an export186+# carrying its own VPS/SPS/PPS -- an intraframe master, ProRes-shaped, large
187-# anyone would wait for; its intra AU is a stateless free function that fans out187+# files and all, the same file the old seat wrote -- and the wavefront inside
188-# across cores at 4.30 fps for the same picture, which is the export this188+# one picture (WPP, a worker per CTB row) spends every core on it, where the
189-# project offers -- an intraframe master, ProRes-shaped, large files and all.189+# old seat fanned one core across each of twelve frames in flight. The rate
190-# Built from `vendor/oxideav-h265`; see the note in the workspace manifest.190+# knob stays a quality dial: the seat maps the bitrate row to a constant QP
191-oxideav-h265 = { path = "../../vendor/oxideav-h265" }191+# ([`crate::export`]) and the encoder's own target-bits correction pass stays
192+# unreached headroom.
193+ec-h265 = { path = "../../../edith_codecs/crates/ec-h265" }
194+# The HEVC bitstream syntax the encoder's config speaks -- the VUI types the
195+# seat builds the SPS's colour description from. Same family, same workspace.
196+ec-h265-syntax = { path = "../../../edith_codecs/crates/ec-h265-syntax" }
192 oxideav-sub-image = "0.0.7"197 oxideav-sub-image = "0.0.7"
193 198
194 [dev-dependencies]199 [dev-dependencies]
crates/engine/src/caps.rsmodified+5 -5
@@ -30,11 +30,11 @@ const HW_CODECS: [(u32, &str); 4] = [
30 30
31 /// The software half: the codec, the crate that carries it here, and which31 /// The software half: the codec, the crate that carries it here, and which
32 /// halves of the job that crate does. Named crates rather than a bare "SW",32 /// halves of the job that crate does. Named crates rather than a bare "SW",
33-/// because the answer to "why is my HEVC file so large" is `oxideav-h26533+/// because the answer to "why is my HEVC file so large" is `ec-h265 intra`,
34-/// intra`, and the row that says so is the row that answers it.34+/// and the row that says so is the row that answers it.
35 const SW_CODECS: [(&str, &str, bool, bool); 10] = [35 const SW_CODECS: [(&str, &str, bool, bool); 10] = [
36 ("H.264", "ec-h264", true, true),36 ("H.264", "ec-h264", true, true),
37- ("HEVC", "oxideav-h265 intra", false, true),37+ ("HEVC", "ec-h265 intra", false, true),
38 ("AV1", "rav1e", false, true),38 ("AV1", "rav1e", false, true),
39 // Decode is split by width: symphonia carries stereo and narrower, `ec-aac`39 // Decode is split by width: symphonia carries stereo and narrower, `ec-aac`
40 // everything wider; the encoder is `ec-aac` as well.40 // everything wider; the encoder is `ec-aac` as well.
@@ -159,13 +159,13 @@ mod tests {
159 #[test]159 #[test]
160 fn the_software_line_names_every_encoder_this_build_carries() {160 fn the_software_line_names_every_encoder_this_build_carries() {
161 let line = software();161 let line = software();
162- for name in ["ec-h264", "oxideav-h265 intra", "rav1e", "ec-aac"] {162+ for name in ["ec-h264", "ec-h265 intra", "rav1e", "ec-aac"] {
163 assert!(line.contains(name), "{name} missing from {line}");163 assert!(line.contains(name), "{name} missing from {line}");
164 }164 }
165 // Decode-only crates must not read as encoders, and the seat words are165 // Decode-only crates must not read as encoders, and the seat words are
166 // the only thing saying which is which.166 // the only thing saying which is which.
167 assert!(line.contains("AC-3 dec (ec-ac3)"));167 assert!(line.contains("AC-3 dec (ec-ac3)"));
168 assert!(line.contains("H.264 dec+enc (ec-h264)"));168 assert!(line.contains("H.264 dec+enc (ec-h264)"));
169- assert!(line.contains("HEVC enc (oxideav-h265 intra)"));169+ assert!(line.contains("HEVC enc (ec-h265 intra)"));
170 }170 }
171 }171 }
crates/engine/src/export.rsmodified+121 -170
@@ -3,9 +3,8 @@
3 //! MP3 or Ogg Vorbis of the timeline's audio alone.3 //! MP3 or Ogg Vorbis of the timeline's audio alone.
4 //!4 //!
5 //! The HEVC pair is **intra-only**, and says so wherever it is offered: every5 //! The HEVC pair is **intra-only**, and says so wherever it is offered: every
6-//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the6+//! frame is a self-contained IDR from `ec-h265`, the project's own pure-Rust
7-//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter7+//! HEVC encoder -- intra-only by construction, the same file the row promises.
8-//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30).
9 //! That makes it an intraframe master in the family of ProRes and DNxHD — large8 //! That makes it an intraframe master in the family of ProRes and DNxHD — large
10 //! files, every frame a cut point — and not a delivery codec.9 //! files, every frame a cut point — and not a delivery codec.
11 //!10 //!
@@ -67,6 +66,10 @@ use ec_core::registry::{CodecId, CodecParameters};
67 use ec_core::registry::Decoder as _;66 use ec_core::registry::Decoder as _;
68 use ec_core::{Packet, TimeBase};67 use ec_core::{Packet, TimeBase};
69 use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset};68 use ec_h264::{Encoder, EncoderConfig, H264Decoder, PictureView, Preset};
69+use ec_h265::encoder::{Encoder as HevcEncoder, EncoderConfig as HevcEncoderConfig, RateControl};
70+use ec_h265_syntax::vui::{
71+ ColourDescription as HevcColourDescription, VideoSignalType as HevcVideoSignalType,
72+};
70 73
71 use flacenc::component::BitRepr;74 use flacenc::component::BitRepr;
72 use flacenc::error::Verify;75 use flacenc::error::Verify;
@@ -139,15 +142,14 @@ pub const DEFAULT_AUDIO_KBPS: u32 = 256;
139 /// on a build with no assembly, which is what this one is.142 /// on a build with no assembly, which is what this one is.
140 const AV1_SPEED: u8 = 10;143 const AV1_SPEED: u8 = 10;
141 144
142-/// The HEVC coding tree block this encoder is fixed at: the coded picture is a145+/// How many lane encoders the intra HEVC seat spreads frames across. Twelve
143-/// whole number of them, which is what the conformance window crops back.146+/// is where the 2026-08-11 bench stopped scaling on this box; more lanes
144-const CTB: usize = 16;147+/// only holds more decoded frames in memory. The cores the lanes leave over
145-/// How many frames the intra HEVC encoder codes at once. Twelve is where the148+/// go to the wavefront inside each lane's encoder.
146-/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes
147-/// only holds more decoded frames in memory.
148 const HEVC_LANES: usize = 12;149 const HEVC_LANES: usize = 12;
149-/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench:150+/// Bits per pixel an intra HEVC encoder spends at QP 27: 0.607 at 720p and
150-/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through.151+/// 0.586 at 1080p on the old seat's bench, and `ec-h265` lands on the same
152+/// 0.6 anchor. What [`hevc_qp`] maps a bitrate row through.
151 const HEVC_BPP_AT_27: f64 = 0.6;153 const HEVC_BPP_AT_27: f64 = 0.6;
152 /// The band [`hevc_qp`] is clamped into, for the reason stated there.154 /// The band [`hevc_qp`] is clamped into, for the reason stated there.
153 const HEVC_QP_MIN: i32 = 22;155 const HEVC_QP_MIN: i32 = 22;
@@ -187,9 +189,9 @@ pub enum Format {
187 /// unchanged.189 /// unchanged.
188 Av1Mp4,190 Av1Mp4,
189 /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR191 /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR
190- /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC192+ /// picture ([`Enc::open_hevc`]) -- `ec-h265` codes intra and nothing else.
191- /// encoder fast enough to be an export at all. An intraframe master, like193+ /// An intraframe master, like ProRes or DNxHD -- large files, and every
192- /// ProRes or DNxHD -- large files, and every frame a cut point.194+ /// frame a cut point.
193 Hevc,195 Hevc,
194 /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4196 /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4
195 /// and not Matroska -- the AV1 pair's split, for the same reason.197 /// and not Matroska -- the AV1 pair's split, for the same reason.
@@ -793,7 +795,7 @@ pub const NO_HW_SEAT: &str = "no HW seat here — pick Auto or Software";
793 fn video_label(format: Format, hw: bool) -> &'static str {795 fn video_label(format: Format, hw: bool) -> &'static str {
794 match (format, hw) {796 match (format, hw) {
795 (_, true) => HW_LABEL,797 (_, true) => HW_LABEL,
796- (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)",798+ (Format::Hevc | Format::HevcMp4, false) => "SW encode (ec-h265 intra)",
797 (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)",799 (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)",
798 (_, false) => "SW encode (ec-h264)",800 (_, false) => "SW encode (ec-h264)",
799 }801 }
@@ -3810,43 +3812,46 @@ enum Enc {
3810 au: Vec<u8>,3812 au: Vec<u8>,
3811 flushed: bool,3813 flushed: bool,
3812 },3814 },
3813- /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a3815+ /// HEVC, intra-only and software only: `ec-h265` is an intra encoder --
3814- /// *stateless* function of one picture, so a batch of frames is coded on as3816+ /// every picture an IDR carrying its own VPS/SPS/PPS. A batch of frames
3815- /// many cores as there are lanes and collected back in order.3817+ /// codes on as many lane encoders as there are pictures, and each
3818+ /// encoder's wavefront splits whatever cores the lanes leave over -- the
3819+ /// same shape as the seat it replaced, the cores spent on frames and
3820+ /// inside one picture at the same time.
3816 Hevc(HevcEnc),3821 Hevc(HevcEnc),
3817 }3822 }
3818 3823
3819 /// The intra HEVC seat. Frames arrive one at a time (the export walk is one3824 /// The intra HEVC seat. Frames arrive one at a time (the export walk is one
3820-/// picture per timeline frame) and are held until there are [`lanes`] of them,3825+/// picture per timeline frame) and are held until there is a lane for each,
3821-/// then coded in parallel and queued in **display order** -- fanning out is the3826+/// then coded in parallel and queued in **display order**. `ec-h265`'s
3822-/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on3827+/// wavefront spreads one picture across the workers it is given and the lanes
3823-/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose3828+/// spread the frames across the machine, so decode and render keep filling
3824-/// frames came back shuffled would be no export at all.3829+/// the next batch while this one codes -- a seat that coded one picture at a
3830+/// time would serialize the whole walk behind its encoder (measured: 7.4 fps
3831+/// against 11.8 at 1080p on the same box, which is the regression this
3832+/// batching exists to prevent).
3825 ///3833 ///
3826-/// corner-cut: a batch of padded planes sits in memory (~3 MB a frame at 1080p,3834+/// corner-cut: a batch of display-size planes sits in memory (~3 MB a frame
3827-/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes3835+/// at 1080p, so ~37 MB at 12 lanes) and the tail of a timeline is coded on
3828-/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a3836+/// fewer lanes than the middle. Upgrade path is a pipeline that keeps every
3829-/// decoder running ahead of the encoder rather than a batch barrier.3837+/// lane fed from a decoder running ahead of the encoder rather than a batch
3838+/// barrier.
3830 struct HevcEnc {3839 struct HevcEnc {
3831- /// Padded I420 planes waiting for a lane, in display order.3840+ /// Display-size I420 pictures waiting for a lane, in display order. The
3841+ /// encoder pads to its own coded grid, so nothing is pre-padded here.
3832 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,3842 pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
3833 /// Coded access units not yet collected, in the same order.3843 /// Coded access units not yet collected, in the same order.
3834 ready: std::collections::VecDeque<Vec<u8>>,3844 ready: std::collections::VecDeque<Vec<u8>>,
3835- /// The unit currently lent out, for the reason `Sw` owns one.3845+ /// The unit currently lent out, for the reason `Sw` owns one: the encoder
3846+ /// hands back an owned `Vec`, the seat's contract lends a slice.
3836 au: Vec<u8>,3847 au: Vec<u8>,
3837- /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid.3848+ /// One encoder per lane. `ec-h265` is stateless from picture to picture
3849+ /// (every picture is an IDR), so a lane coding frame *n* needs nothing
3850+ /// the other lanes know.
3851+ lanes: Vec<HevcEncoder>,
3852+ /// The display width the planes arrive at; the height lives in each
3853+ /// encoder's config, where the coded grid is derived from it.
3838 width: usize,3854 width: usize,
3839- height: usize,
3840- /// Luma samples the conformance window crops off the right and the bottom,
3841- /// so a decoder outputs the picture's own size ([`pad_to_ctb`]).
3842- crop: (usize, usize),
3843- qp: i32,
3844- lanes: usize,
3845- /// What the SPS says the samples mean. A decoder reads the bitstream before
3846- /// it reads the container, so an HEVC stream without this renders BT.601 in
3847- /// libavcodec however the file is tagged -- the container's `Colour` element
3848- /// and `colr` box are not enough on their own.
3849- signal: oxideav_h265::vui::VideoSignalType,
3850 }3855 }
3851 3856
3852 impl Enc {3857 impl Enc {
@@ -4022,26 +4027,28 @@ impl Enc {
4022 }4027 }
4023 4028
4024 /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the4029 /// The HEVC pair: the plugin's VA-API seat where the GPU has one, and the
4025- /// frame-parallel software encoder everywhere else -- below the driver's4030+ /// software intra encoder everywhere else -- below the driver's 384x384
4026- /// 384x384 floor, on a plugin too old to carry the symbol, on a GPU with no4031+ /// floor, on a plugin too old to carry the symbol, on a GPU with no HEVC
4027- /// HEVC encode entrypoint. Silent either way, because both write the same4032+ /// encode entrypoint. Silent either way, because both write the same kind
4028- /// kind of file.4033+ /// of file.
4029 ///4034 ///
4030- /// **Intra-only, deliberately, on both seats.** The software encoder's inter4035+ /// **Intra-only, on both seats, by construction.** `ec-h265` codes intra
4031- /// modes code4036+ /// and nothing else -- every picture an IDR -- which is the file this row
4032- /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of4037+ /// has always promised: an intraframe master in the shape of ProRes or
4033- /// timeline in half an hour, which is not an export anybody waits for --4038+ /// DNxHD, large files, every frame a cut point. The seat it replaced had
4034- /// while the intra path does 4.30 fps on the same picture and the same4039+ /// inter modes and turned them off for speed; this one has none to turn
4035- /// cores. So every frame is an IDR, the file is an intraframe master in the4040+ /// off.
4036- /// shape of ProRes or DNxHD, and the card says so where a user picks it.
4037 ///4041 ///
4038- /// The picture is coded **padded** to the 16-sample CTB grid and the SPS4042+ /// The picture is coded at its own size and padded to whole minimum coding
4039- /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so4043+ /// blocks *by the encoder*, which crops the padding back off with the SPS
4040- /// 1920x1080 is a legal export rather than a refusal.4044+ /// conformance window, so 1920x1080 is a legal export rather than a
4045+ /// refusal.
4041 fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {4046 fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
4042 // The muxers time by it and the mp4 one wants an exact rational: asked4047 // The muxers time by it and the mp4 one wants an exact rational: asked
4043- // here so an impossible rate fails before a frame is coded.4048+ // here so an impossible rate fails before a frame is coded. The same
4044- crate::mux::frame_timing(meta.frame_rate)?;4049+ // rational goes into the SPS's VUI, whose timing is also where the
4050+ // encoder picks the level from.
4051+ let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate)?;
4045 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd4052 // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
4046 // picture cannot be cropped back to itself -- and an odd dimension has4053 // picture cannot be cropped back to itself -- and an odd dimension has
4047 // no chroma plane of its own to begin with. Named rather than padded to4054 // no chroma plane of its own to begin with. Named rather than padded to
@@ -4057,22 +4064,35 @@ impl Enc {
4057 eprintln!("export encoder: hardware HEVC intra (VA-API plugin)");4064 eprintln!("export encoder: hardware HEVC intra (VA-API plugin)");
4058 return Ok(Self::HevcHw(hw));4065 return Ok(Self::HevcHw(hw));
4059 }4066 }
4060- let (width, height) = (4067+ eprintln!("export encoder: software HEVC intra (ec-h265)");
4061- (meta.width as usize).next_multiple_of(CTB),4068+ // The cores are split between the lanes and the wavefront inside one:
4062- (meta.height as usize).next_multiple_of(CTB),4069+ // twelve lanes of one worker each on this box's twelve threads,
4063- );4070+ // fewer lanes on a smaller machine with a wider wavefront each.
4064- let lanes = std::thread::available_parallelism().map_or(1, |n| n.get());4071+ let cores = std::thread::available_parallelism().map_or(1, |n| n.get());
4065- eprintln!("export encoder: software HEVC intra (oxideav-h265)");4072+ let lane_count = cores.min(HEVC_LANES).max(1);
4073+ let per_lane = cores.div_ceil(lane_count);
4074+ let mut lanes = Vec::with_capacity(lane_count);
4075+ for _ in 0..lane_count {
4076+ let mut cfg = HevcEncoderConfig::new(meta.width, meta.height);
4077+ // The bitrate row a user picked, mapped through the same measured
4078+ // anchor as before ([`hevc_qp`]) and held: a *quality* dial, not a
4079+ // rate controller. The encoder's own per-picture target-bits mode
4080+ // would chase the number with a correction pass -- named headroom,
4081+ // not behaviour this seat takes silently.
4082+ cfg.rate_control = RateControl::ConstantQp(hevc_qp(meta, settings));
4083+ cfg.timing = Some((fps_den, fps_num));
4084+ cfg.video_signal_type = Some(video_signal_type(meta.height));
4085+ cfg.threads = per_lane;
4086+ lanes.push(
4087+ HevcEncoder::new(cfg).map_err(|e| format!("HEVC software encoder: {e}"))?,
4088+ );
4089+ }
4066 Ok(Self::Hevc(HevcEnc {4090 Ok(Self::Hevc(HevcEnc {
4067 pending: Vec::new(),4091 pending: Vec::new(),
4068 ready: std::collections::VecDeque::new(),4092 ready: std::collections::VecDeque::new(),
4069 au: Vec::new(),4093 au: Vec::new(),
4070- width,4094+ lanes,
4071- height,4095+ width: meta.width as usize,
4072- crop: (width - meta.width as usize, height - meta.height as usize),
4073- qp: hevc_qp(meta, settings),
4074- lanes: lanes.min(HEVC_LANES),
4075- signal: video_signal_type(meta.height),
4076 }))4096 }))
4077 }4097 }
4078 4098
@@ -4080,12 +4100,13 @@ impl Enc {
4080 /// a decoder may be started from -- which only the Matroska muxer asks, the4100 /// a decoder may be started from -- which only the Matroska muxer asks, the
4081 /// mp4 one reading its own sync flag off the IDR slice.4101 /// mp4 one reading its own sync flag off the IDR slice.
4082 ///4102 ///
4083- /// The contract is structural in the software seat now: `ec-h264` buffers4103+ /// The H.264 seat keeps the contract structurally: `ec-h264` buffers
4084 /// nothing -- no lookahead, and B pictures coded as none -- so one call is4104 /// nothing -- no lookahead, and B pictures coded as none -- so one call is
4085- /// one access unit by construction. The old seat only kept it because its4105+ /// one access unit by construction. The HEVC seat's lanes hold a small
4086- /// GOP-buffering lookahead needed a zero bitrate and this path was always4106+ /// batch of pictures until there is a lane for each, so it says "at most
4087- /// CBR; a future constant-QP mode would have had to split one buffer into4107+ /// one" and means it; the old H.264 seat only kept the contract because
4088- /// access units first.4108+ /// its GOP-buffering lookahead needed a zero bitrate and this path was
4109+ /// always CBR.
4089 fn encode(4110 fn encode(
4090 &mut self,4111 &mut self,
4091 y: &[u8],4112 y: &[u8],
@@ -4127,16 +4148,11 @@ impl Enc {
4127 // and not a driver's choice.4148 // and not a driver's choice.
4128 Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))),4149 Self::HevcHw(hw) => Ok(hw.encode(y, u, v, width, height, true)?.map(|au| (au, true))),
4129 Self::Hevc(hevc) => {4150 Self::Hevc(hevc) => {
4130- hevc.pending.push(pad_to_ctb(4151+ // The display-size planes are kept as they came: `ec-h265`
4131- y,4152+ // pads to its own coded grid and crops back through the SPS
4132- u,4153+ // conformance window.
4133- v,4154+ hevc.pending.push((y.to_vec(), u.to_vec(), v.to_vec()));
4134- width as usize,4155+ if hevc.pending.len() >= hevc.lanes.len() {
4135- height as usize,
4136- hevc.width,
4137- hevc.height,
4138- ));
4139- if hevc.pending.len() >= hevc.lanes {
4140 hevc.code_batch()?;4156 hevc.code_batch()?;
4141 }4157 }
4142 // Every intra AU is an IDR, so every one of them is a key4158 // Every intra AU is an IDR, so every one of them is a key
@@ -4225,9 +4241,9 @@ impl Enc {
4225 Ok(pop_av1(ready, au))4241 Ok(pop_av1(ready, au))
4226 }4242 }
4227 Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))),4243 Self::HevcHw(hw) => Ok(hw.drain()?.map(|au| (au, true))),
4244+ // The tail batch: fewer frames than lanes, coded on as many
4245+ // encoders as there are frames left.
4228 Self::Hevc(hevc) => {4246 Self::Hevc(hevc) => {
4229- // The tail batch: fewer frames than lanes, coded on as many
4230- // cores as there are frames left.
4231 if !hevc.pending.is_empty() {4247 if !hevc.pending.is_empty() {
4232 hevc.code_batch()?;4248 hevc.code_batch()?;
4233 }4249 }
@@ -4242,32 +4258,25 @@ impl Enc {
4242 }4258 }
4243 4259
4244 impl HevcEnc {4260 impl HevcEnc {
4245- /// The whole pending batch, one frame per lane, collected back in the order4261+ /// The whole pending batch, one frame per lane, collected back in the
4246- /// it went out -- `std::thread::scope`, because the encode borrows the4262+ /// order it went out -- `std::thread::scope`, because the encode borrows
4247- /// planes rather than copying them again. A panic inside a lane comes back4263+ /// the planes and the lanes rather than copying them again. A panic inside
4248- /// as an error rather than unwinding the export thread.4264+ /// a lane comes back as an error rather than unwinding the export thread.
4249 fn code_batch(&mut self) -> crate::Result<()> {4265 fn code_batch(&mut self) -> crate::Result<()> {
4250- let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop);4266+ let width = self.width;
4251- let signal = self.signal;4267+ let chroma = width / 2;
4268+ let pending = std::mem::take(&mut self.pending);
4252 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {4269 let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
4253 let lanes: Vec<_> = self4270 let lanes: Vec<_> = self
4254- .pending4271+ .lanes
4255 .iter()4272 .iter()
4256- .map(|(y, cb, cr)| {4273+ .zip(pending.iter())
4274+ .map(|(encoder, (y, cb, cr))| {
4257 scope.spawn(move || {4275 scope.spawn(move || {
4258- oxideav_h265::encoder::intra::encode_idr_intra_au_cropped(4276+ encoder
4259- y,4277+ .encode_idr_planes(y, width, cb, chroma, cr, chroma)
4260- cb,4278+ .map(|coded| coded.au)
4261- cr,4279+ .map_err(|e| crate::Error::from(format!("software HEVC encode: {e}")))
4262- width,
4263- height,
4264- qp,
4265- crop.0,
4266- crop.1,
4267- Some(signal),
4268- )
4269- .map(|coded| coded.au)
4270- .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}")))
4271 })4280 })
4272 })4281 })
4273 .collect();4282 .collect();
@@ -4282,50 +4291,17 @@ impl HevcEnc {
4282 for au in coded {4291 for au in coded {
4283 self.ready.push_back(au?);4292 self.ready.push_back(au?);
4284 }4293 }
4285- self.pending.clear();
4286 Ok(())4294 Ok(())
4287 }4295 }
4288 }4296 }
4289 4297
4290 /// The oldest coded intra AU, lent out under the same "valid until the next4298 /// The oldest coded intra AU, lent out under the same "valid until the next
4291-/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag4299+/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key
4292-/// is not a guess.4300+/// flag is not a guess.
4293 fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {4301 fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
4294 hevc.au = hevc.ready.pop_front()?;4302 hevc.au = hevc.ready.pop_front()?;
4295 Some((&hevc.au[..], true))4303 Some((&hevc.au[..], true))
4296 }4304 }
4297-
4298-/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the
4299-/// added rows and columns filled by **replicating the edge** rather than with
4300-/// black: the padding is coded and then cropped away, and a black border would
4301-/// bleed into the last real column through the intra prediction and the
4302-/// transform that straddles it.
4303-fn pad_to_ctb(
4304- y: &[u8],
4305- u: &[u8],
4306- v: &[u8],
4307- width: usize,
4308- height: usize,
4309- padded_w: usize,
4310- padded_h: usize,
4311-) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
4312- let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| {
4313- let mut out = vec![0u8; pw * ph];
4314- for row in 0..ph {
4315- let src_row = &src[row.min(h - 1) * w..][..w];
4316- let dst = &mut out[row * pw..][..pw];
4317- dst[..w].copy_from_slice(src_row);
4318- dst[w..].fill(src_row[w - 1]);
4319- }
4320- out
4321- };
4322- (
4323- plane(y, width, height, padded_w, padded_h),
4324- plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2),
4325- plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2),
4326- )
4327-}
4328-
4329 /// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a4305 /// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
4330 /// user picked -- the card has no QP control and this codec has no rate control,4306 /// user picked -- the card has no QP control and this codec has no rate control,
4331 /// so the two are joined by measurement rather than promised to each other.4307 /// so the two are joined by measurement rather than promised to each other.
@@ -4357,14 +4333,14 @@ fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
4357 /// which renders BT.601 -- a visible shift on a 709 export that a player reads4333 /// which renders BT.601 -- a visible shift on a 709 export that a player reads
4358 /// from the wrong matrix. Every export is limited range, which is what4334 /// from the wrong matrix. Every export is limited range, which is what
4359 /// `video_full_range_flag = false` says here.4335 /// `video_full_range_flag = false` says here.
4360-fn video_signal_type(height: u32) -> oxideav_h265::vui::VideoSignalType {4336+fn video_signal_type(height: u32) -> HevcVideoSignalType {
4361 let (primaries, transfer, matrix) = ColorDescription::output(height).codes();4337 let (primaries, transfer, matrix) = ColorDescription::output(height).codes();
4362- oxideav_h265::vui::VideoSignalType {4338+ HevcVideoSignalType {
4363 // "Unspecified", which is what every encoder here writes: the field is4339 // "Unspecified", which is what every encoder here writes: the field is
4364 // the analogue system a picture came off, and none of these did.4340 // the analogue system a picture came off, and none of these did.
4365 video_format: 5,4341 video_format: 5,
4366 video_full_range_flag: false,4342 video_full_range_flag: false,
4367- colour_description: Some(oxideav_h265::vui::ColourDescription {4343+ colour_description: Some(HevcColourDescription {
4368 colour_primaries: primaries as u8,4344 colour_primaries: primaries as u8,
4369 transfer_characteristics: transfer as u8,4345 transfer_characteristics: transfer as u8,
4370 matrix_coeffs: matrix as u8,4346 matrix_coeffs: matrix as u8,
@@ -5321,31 +5297,6 @@ mod tests {
5321 assert_eq!(at(1920, 1080, None), at(1280, 720, None));5297 assert_eq!(at(1920, 1080, None), at(1280, 720, None));
5322 }5298 }
5323 5299
5324- /// The padding a non-%16 picture is coded with replicates the edge instead
5325- /// of filling black: the coded rows past the picture carry its last row, so
5326- /// nothing bleeds into the last real line through the intra prediction.
5327- #[test]
5328- fn the_ctb_padding_replicates_the_edge() {
5329- // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the
5330- // copy itself with numbers small enough to read).
5331- let y: Vec<u8> = (1..=12).collect();
5332- let u: Vec<u8> = vec![40, 41, 42];
5333- let v: Vec<u8> = vec![50, 51, 52];
5334- let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4);
5335- assert_eq!(
5336- py,
5337- vec![
5338- 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice
5339- 7, 8, 9, 10, 11, 12, 12, 12, //
5340- 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated
5341- 7, 8, 9, 10, 11, 12, 12, 12,
5342- ]
5343- );
5344- // Chroma is half of everything, padded the same way.
5345- assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]);
5346- assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]);
5347- }
5348-
5349 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the5300 /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
5350 /// conformance window is stated in chroma samples -- so it is refused by5301 /// conformance window is stated in chroma samples -- so it is refused by
5351 /// name rather than written a column wider than the timeline.5302 /// name rather than written a column wider than the timeline.
crates/engine/tests/backends.rsmodified+1 -1
@@ -135,7 +135,7 @@ fn the_planned_encoders_are_the_ones_the_job_opens() {
135 assert!(planned.contains("AAC"), "{ext}: {planned}");135 assert!(planned.contains("AAC"), "{ext}: {planned}");
136 if matches!(format, Format::Hevc | Format::HevcMp4) {136 if matches!(format, Format::Hevc | Format::HevcMp4) {
137 assert!(137 assert!(
138- planned.contains("oxideav-h265 intra") || planned.contains("HW encode"),138+ planned.contains("ec-h265 intra") || planned.contains("HW encode"),
139 "{ext}: an HEVC job names one of the two HEVC seats: {planned}"139 "{ext}: an HEVC job names one of the two HEVC seats: {planned}"
140 );140 );
141 }141 }
crates/engine/tests/hevc_export.rsmodified+12 -11
@@ -1,8 +1,7 @@
1-//! HEVC export: the codec this project could read and not write until OxideAV's1+//! HEVC export: the codec this project could read and not write until a
2-//! pure-Rust H.265 gave it an encoder -- an **intra-only** one, every frame a2+//! pure-Rust encoder for it arrived -- `ec-h265` now, **intra-only**, every
3-//! self-contained IDR, which is the only shape of it fast enough to wait for3+//! frame a self-contained IDR coded on every core at once (WPP), where the
4-//! (the inter modes code 1080p at 0.81 fps across 12 cores; the intra path does4+//! seat it replaced fanned one core across each of twelve frames in flight.
5-//! 4.30 fps on the same picture).
6 //!5 //!
7 //! Three things are under test here: that the *containers* say HEVC in the6 //! Three things are under test here: that the *containers* say HEVC in the
8 //! words their readers expect (this project's own demuxer, and ffprobe where it7 //! words their readers expect (this project's own demuxer, and ffprobe where it
@@ -120,12 +119,14 @@ fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() {
120 }119 }
121 }120 }
122 121
123-/// The %16 half, and the reason the vendored encoder carries a patch at all:122+/// The conformance-window half: the encoder pads the coded picture to whole
124-/// 1080 is not a multiple of the 16-sample CTB, so the picture is coded at123+/// minimum coding blocks and the SPS crops the padding back off with the
125-/// 1920x1088 and the SPS crops it back with a §7.4.3.2.1 conformance window.124+/// §7.4.3.2.1 window -- 1080 is already a multiple of 8, so here the coded
126-/// ffprobe is what says whether that worked -- it reads the *bitstream*, not125+/// and displayed sizes agree.
127-/// the container's own claim -- and ffmpeg decoding the file without a126+///
128-/// complaint is what says the stream is legal.127+/// ffprobe reads the *bitstream* rather than the container's own claim, and
128+/// ffmpeg decoding the file without a complaint is what says the stream is
129+/// legal.
129 #[test]130 #[test]
130 fn a_1080p_export_states_1920x1080_through_the_conformance_window() {131 fn a_1080p_export_states_1920x1080_through_the_conformance_window() {
131 let Some(source) = fixture_1080p() else {132 let Some(source) = fixture_1080p() else {
vendor/oxideav-h265/Cargo.tomldeleted+0 -17
@@ -1,17 +0,0 @@
1-[package]
2-name = "oxideav-h265"
3-version = "0.0.9"
4-edition = "2021"
5-rust-version = "1.80"
6-license = "MIT"
7-repository = "https://github.com/OxideAV/oxideav-h265"
8-authors = ["Mark Karpeles"]
9-description = "Pure-Rust H.265 / HEVC (ITU-T H.265 | ISO/IEC 23008-2) bitstream parser + decoder scaffold for oxideav"
10-
11-readme = "README.md"
12-homepage = "https://github.com/OxideAV/oxideav-h265"
13-keywords = ["multimedia", "video", "h265", "hevc", "codec"]
14-categories = ["multimedia::encoding", "multimedia::video"]
15-
16-[dependencies]
17-oxideav-core = "0.1"
vendor/oxideav-h265/LICENSEdeleted+0 -21
@@ -1,21 +0,0 @@
1-MIT License
2-
3-Copyright (c) 2026 Karpelès Lab Inc.
4-
5-Permission is hereby granted, free of charge, to any person obtaining a copy
6-of this software and associated documentation files (the "Software"), to deal
7-in the Software without restriction, including without limitation the rights
8-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9-copies of the Software, and to permit persons to whom the Software is
10-furnished to do so, subject to the following conditions:
11-
12-The above copyright notice and this permission notice shall be included in all
13-copies or substantial portions of the Software.
14-
15-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21-SOFTWARE.
vendor/oxideav-h265/README.mddeleted+0 -243
@@ -1,243 +0,0 @@
1-# oxideav-h265
2-
3-[![CI](https://github.com/OxideAV/oxideav-h265/actions/workflows/ci.yml/badge.svg)](https://github.com/OxideAV/oxideav-h265/actions/workflows/ci.yml) [![crates.io](https://img.shields.io/crates/v/oxideav-h265.svg)](https://crates.io/crates/oxideav-h265) [![docs.rs](https://docs.rs/oxideav-h265/badge.svg)](https://docs.rs/oxideav-h265) [![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
4-
5-A pure-Rust H.265 / HEVC video codec for the
6-[oxideav](https://github.com/OxideAV/oxideav) framework, built
7-clean-room against ITU-T Recommendation H.265 | ISO/IEC 23008-2.
8-
9-## Status
10-
11-**Decoder: end to end.** Every Annex B bitstream in the staged
12-16-fixture conformance corpus decodes byte-exact to its expected YUV
13-through the whole-bitstream driver (`decode_annexb_sequence` /
14-`SequenceDecoder`) and the `oxideav_core::Decoder` registry entry
15-(`make_decoder`, ids `"h265"` / `"hevc"`, `hvc1` / `hev1` / `HEVC`
16-FourCCs, MP4 ObjectTypeIndication, Matroska tag) — plus self-built
17-conformance pins for the features the corpus lacks (rounds 413 / 416:
18-RDPCM, palette, cross-component prediction, adaptive colour
19-transform, intra block copy), and a 37-stream black-box tool-axis
20-sweep (round 410) held byte-exact by nine embedded pins. Against the
21-staged **official JCT-VC RExt / SCC conformance corpus** (61
22-decodable bitstreams with published output digests,
23-`docs/video/h265/conformance/`), 26 streams decode byte-exact
24-(round 437; docs-gated pins in `tests/conformance_official.rs`) —
25-including the transform-skip-context, wavefronts-inside-tiles /
26-aligned-bypass / high-throughput, persistent-Rice-seeded,
27-Monochrome 8/12-bit, Main 4:2:2 10 and 8-bit
28-extended-precision-intra families. Coverage:
29-
30-* intra pictures at every staged geometry / CTB size (16 / 32 / 64)
31- and QP extreme (slice QP 1 and 45), with SAO on and off;
32-* multi-picture sequences: all-intra IDR runs, an IDR+P pair, and an
33- eight-picture I/P/B pyramid with two reference lists, temporal MVP,
34- AMVP MVDs, skip/merge CUs and POC output reordering;
35-* Main10 and the 4:2:2 / 4:4:4 10-bit Range-Extensions streams;
36-* multi-CTU slices, four-independent-slice pictures, dependent slice
37- segments (§9.3.2.4/.5 `TableStateIdxDs` context carry + §7.4.7.1
38- header inheritance), per-slice loop-filter-across flags, and
39- `entropy_coding_sync_enabled_flag` (WPP) streams with per-row
40- entry-point substreams;
41-* **true tiles**: the staged `true-tiles-2x2` fixture (2×2 uniform
42- grid, one slice per tile, `loop_filter_across_tiles == 0`) decodes
43- byte-exact, and multi-tile SINGLE-slice streams work end to end —
44- §7.3.8.1 tile-boundary subsets (`end_of_subset_one_bit` + byte
45- alignment), §9.3.2.2 per-tile CABAC re-initialization, tile-relative
46- WPP row conditions, §8.6.1 per-tile `qPY_PREV` resets;
47-* §8.5.3.3.4.3 explicit weighted prediction (P uni and B uni/bi, with
48- non-default per-slice weights / offsets / denominators);
49-* B pyramids / temporal layers / open-GOP CRA + leading pictures /
50- RADL streams (a bi-predicted reference B as the §8.5.3.2.9
51- collocated picture), §7.4.5 scaling lists (default + explicit, all
52- TB sizes, intra + inter), §8.4.4.2.3 strong intra smoothing,
53- §8.4.4.2.1 constrained intra prediction, §7.3.8.11 transform skip,
54- rectangular/AMP partitions with deep inter RQTs (§7.3.8.10 deferred
55- chroma), WPP combined with multiple slices per picture, and
56- 4:2:2 stacked chroma halves (per-half cbf gating and placement);
57-* §7.3.8.7 PCM coding units, incl. the §8.7.2.5.4 / §8.7.3.1
58- loop-filter suppression (`pcm_loop_filter_disabled_flag`, and
59- transquant-bypass CUs);
60-* range-extension RDPCM (§8.6.5 implicit intra + explicit inter
61- directional residual modification) and SCC **palette mode**
62- (§7.3.8.13 parse incl. the predictor-palette machinery with WPP /
63- dependent-slice synchronization, §8.4.4.2.7 reconstruction with
64- transpose and bypass / quantized escapes) — pinned by self-built
65- conformance streams (`tests/fixture_bytes/r413-*.hevc`), the
66- implicit-RDPCM stream byte-exact against a black-box reference
67- decode;
68-* the Rext/SCC application tail: §8.6.6 **cross-component
69- prediction** (eq. 8-324 applied on the intra and inter residual
70- paths, cbf-clear chroma blocks included), §8.6.8 **adaptive colour
71- transform** (the §8.6.8.2 lifting inverse with ACT-adjusted
72- quantization, eqs 8-287/8-288/8-291), and **intra block copy**
73- (current-picture referencing: the §8.3.4 currPic list append,
74- `use_integer_mv_flag`, the eqs 8-98..8-101 / 8-124..8-125 integer
75- MV paths, the eqs 8-102/8-103 reduction, prediction from the
76- pre-filter reconstruction) — pinned by self-built conformance
77- streams (`tests/fixture_bytes/r416-*.hevc`), the CCP stream
78- byte-exact against a black-box reference decode (the surveyed
79- reference decoder rejects SCC streams outright, so the ACT / IBC
80- pins are decoder-pins);
81-* both transport forms: Annex B extradata/packets AND `hvcC`
82- (`HEVCDecoderConfigurationRecord`, ISO/IEC 14496-15 §8.3.3.1)
83- extradata with length-prefixed packets.
84-
85-**Encoder: intra + low-delay inter + hierarchical-B GOPs with AMP
86-and in-loop filters, registered.** `make_encoder` / `H265Encoder`
87-with three modes:
88-
89-* `mode = "inter"` (`qp` 0..=51, `gop` IDR period, `bslices`, `amp`,
90- `pyramid`) — low-delay `IDR, P, P, …` / `IDR, B, B, …` GOPs
91- (`encoder::inter::LowDelayPEncoder`, one frame in / one AU out) or
92- dyadic **hierarchical-B pyramids**
93- (`encoder::pyramid::PyramidEncoder`, `pyramid = 2/4/8/16`):
94- per-CTU **skip / merge / AMVP / two-PU-partition / intra**
95- decisions under an SSD + λ·rate heuristic, with **two active
96- reference pictures** on the low-delay path (POC − 1 / POC − 2,
97- `ref_idx_l0` signalled). Motion candidates are resolved through
98- the crate's own DECODE-side §8.5.3.2 merge/AMVP derivation against
99- the in-progress motion field (§6.4.2 availability included),
100- motion estimation is a seeded greedy integer diamond plus
101- half-/quarter-pel refinement against the crate's §8.5.3.3.3
102- interpolation, two-PU CUs carry the §7.4.9.8 forced depth-1 RQT,
103- and a `pred_mode_flag == 1` intra fallback rescues scene changes.
104- The **AMP configuration** (`amp` option / `with_amp`) moves the
105- stream to `MinCbSizeY == 8` + `amp_enabled_flag == 1` (explicit
106- `split_cu_flag`, the Table 9-45 big-CU `part_mode` column) and
107- elects `PART_2NxnU / PART_2NxnD / PART_nLx2N / PART_nRx2N`
108- alongside the symmetric shapes — on quarter-offset motion-boundary
109- content the shapes buy **−20 to −29 % bytes at equal PSNR**. The
110- **pyramid** codes each mini-GOP out of display order (next anchor
111- as P first, then the midpoint B recursion with the past boundary
112- on `RefPicList0` and the FUTURE boundary on `RefPicList1`),
113- signals per-slice negative + positive short-term RPS with
114- `sps_max_num_reorder_pics = log2(gop)`, allocates rate by
115- per-layer QP offsets, and searches uni-L0 / uni-L1 / **bi AMVP**
116- per PU (`inter_pred_idc` `PRED_L0/L1/BI` all emitted); on a
117- noisy-pan clip the GOP-8 pyramid takes **−11.5 % bytes** vs the
118- low-delay chain at qp 27. Every stream decodes **bit-exact** to
119- the encoder reconstruction through this crate's decoder AND a
120- black-box reference decoder (multi-QP, multi-shape sweeps; golden
121- GOP / AMP / pyramid / composition streams CI-pinned). Per-frame
122- `FrameStats` expose the skip/merge/AMVP/intra/bi/rect/amp/ref1
123- decisions.
124-* `mode = "intra"` — per-CTU §8.4 intra prediction over the
125- encoder's own reconstruction (all 35 modes, per-CTB `PART_2Nx2N`
126- vs `PART_NxN` rate-distortion decision with per-PB modes, §8.4.2
127- MPM signalling, mode-dependent scans), forward DCT-II + reciprocal
128- quantization, full §7.3.8 syntax through the bin-exact §7.3.8.11
129- residual encoder (golden interop stream CI-pinned).
130-* `mode = "pcm"` (default) — the lossless PCM-IDR bootstrap
131- (every CTB a 16×16 PCM CU; options for dependent segments,
132- multi-slice plans, deblocking, band / edge SAO syntax, and true
133- multi-tile single-slice pictures with §7.4.7.1 entry points).
134-
135-Both coding modes accept the §8.7 **in-loop filters** (`deblock` /
136-`sao` codec options, `LoopFilterCfg` on the direct APIs): the encoder
137-reconstructs through its own decode-side §8.7.2 deblocking (per-slice
138-election over off + a {−2, 0, 2}² β/tC-offset sweep, signalled via
139-the §7.3.6.1 override group) and §8.7.3 SAO (per-CTB statistics-driven band / edge
140-offset estimation with merge-left/up pricing, every candidate
141-measured with the decoder's own apply, `encode_sao_ctb` the bin-exact
142-§7.3.8.3 dual of the parse) — so the filtered pictures its references
143-and outputs hold are exactly a conforming decoder's. Filtered P/B
144-GOPs across a 72-configuration sweep decode byte-exact through a
145-black-box reference decoder (three golden filtered streams
146-CI-pinned); on the interop clip the filters buy up to +1.5 dB luma
147-PSNR at equal rate.
148-
149-4:2:0 8-bit, dimensions multiples of 16.
150-
151-## What's implemented
152-
153-* **Whole-bitstream decode driver** (`sequence`) — Annex B demux →
154- SPS/PPS activation → §7.3.6.1 slice headers (independent and
155- dependent segments) → the §7.3.8.1 CTU loop (tile-scan addressing,
156- per-slice CABAC init, the §9.3.2.4/.5 WPP and dependent-segment
157- context storage/sync, WPP substreams via the §7.4.7.1 entry
158- points) → picture reconstruction → §8.3.1..§8.3.5 reference
159- cycle → output reorder. Tile-scan CTU addressing with §9.3.2.2
160- per-tile context re-initialization and entry-point subsets shared
161- with WPP.
162-* **Registry codec** (`decoder` / `encoder`) — the
163- `oxideav_core::Decoder` + `Encoder` contracts: Annex B or
164- hvcC/length-prefixed packets in, output-order `VideoFrame`s out
165- (reorder queue bounded by `sps_max_num_reorder_pics`, packet-PTS
166- re-attachment, flush-then-`Eof`); frames in, IDR keyframe packets
167- out (`mode = "pcm"` lossless or `mode = "intra"` at a chosen QP).
168- `make_decoder` / `make_encoder` are the direct factory endpoints.
169-* **Headers** — VPS / SPS / PPS (§7.3.2, incl. range + SCC extension
170- bodies), VUI + HRD (§E.2), slice segment headers (§7.3.6, all slice
171- types, RPS forms, `ref_pic_lists_modification()`,
172- `pred_weight_table()`, entry points incl. dependent segments),
173- §7.4.8 RPS materialization, scaling lists (§7.3.4 / §7.4.5), and
174- the `hvcC` record (`hvcc`, ISO/IEC 14496-15 §8.3.3.1).
175-* **CABAC, both directions** — the §9.3 decode engine and the §9.3.5
176- encode engine (decision / bypass / terminate + flush, PCM
177- align-and-reinit), per-syntax-element binarizations (§9.3.4.2), the
178- complete §7.3.8 decode syntax tree, and the write-side §7.3.8.11
179- `residual_coding( )` dual (`encoder::residual`, differential-tested
180- to identical levels + context evolution).
181-* **Reconstruction** — §8.4 intra prediction (all 35 modes), §8.4.1
182- PCM sample write-back, §8.5 inter prediction (merge / MVP /
183- temporal candidates with the §8.5.3.2.3 raw-availability redundancy
184- gates, §8.5.3.3.3 interpolation, §8.5.3.3.4.2 default AND
185- §8.5.3.3.4.3 explicit weighted combines with the §7.4.7.3 table
186- resolution), §8.6 dequant / inverse transform, §8.6.1 per-QG QP
187- derivation.
188-* **In-loop filters** — §8.7.2 deblocking and §8.7.3 SAO with
189- per-slice `slice_loop_filter_across_slices_enabled_flag` gates
190- (deblocking per the current CU's slice; SAO per the §8.7.3.2
191- directional later-slice rule) and the PCM / transquant-bypass
192- sample suppression (`NoFilterMap`).
193-* **Reference machinery** — §8.3.1 POC, §8.3.2 RPS marking, §8.3.4
194- reference lists, §8.3.5 collocated picture, the DPB, and the
195- per-picture decode cycle threading motion fields for temporal MVP.
196-
197-Thirty-six embedded-fixture regression pins (the 17-stream staged
198-corpus incl. true tiles + self-built weighted-prediction,
199-per-slice-loop-filter, hvcC, golden-intra-interop, golden-P-GOP
200-interop, the round-431 AMP / pyramid / composition interop pins, and
201-the nine round-410 tool-axis conformance pins), lossless PCM /
202-exact-reconstruction intra / bit-exact low-delay- and
203-hierarchical-B-GOP encoder↔decoder roundtrips at multiple
204-geometries / QPs / partitions / slice types, and ~930 unit tests.
205-
206-## Not yet implemented
207-
208-* Larger encoder CTB sizes, deeper encoder RQTs / coding quadtrees
209- (the AMP configuration codes 16x16 CUs above an 8x8 MinCb, but
210- never splits), 4x4-luma DST TUs, encoder temporal MVP, more than
211- one active reference per list on the pyramid path, and adaptive
212- (non-dyadic) GOP structures.
213-* Non-uniform (`uniform_spacing_flag == 0`) tile-grid *encoding*
214- (decode side is implemented).
215-* Known corner: on the §8.7.3.2 SAO cross-slice neighbour rule with
216- heterogeneous per-slice flags, a black-box reference decoder
217- consults the current sample's slice flag where the spec text (both
218- 08/2021 and 01/2026 editions) names the later (decode-order)
219- slice's flag; this implementation follows the spec text.
220-* Known corner (RDPCM, spec text followed): §8.4.4.2.6 sets
221- `disableIntraBoundaryFilter` when implicit RDPCM combines with
222- transquant bypass, suppressing the mode-10/26 edge filters — a
223- black-box reference decoder applies those filters regardless.
224- (The r413 note claiming a reference deviation on explicit-RDPCM
225- *vertical* blocks is retired: the official `ExplicitRdpcm_A`
226- conformance stream matches the black-box decode exactly, this
227- crate's luma decode agrees byte-for-byte, and the remaining
228- divergence is an unrelated ±1 chroma artifact on isolated rows,
229- still under investigation.)
230-* Official-corpus families not yet byte-exact: the 4:4:4
231- multi-tool `GENERAL_*_444` / `WAVETILES` / `QMATRIX` parse
232- desync (mid-picture, first reproduces in a busy 4:4:4 intra CTB),
233- 16-bit extended-precision reconstruction (the 8-bit
234- extended-precision streams pass; 10/12/16-bit diverge on their
235- first picture), unequal luma/chroma bit depths (first divergence
236- at frame 4), the official CCP / SAO-offset-scale / persistent-Rice
237- single-stream anchors, and most SCC streams (palette-heavy parse
238- still desyncs mid-slice; two streams decode all 33 frames with
239- subtle reconstruction deltas).
240-
241-## License
242-
243-MIT — see [LICENSE](./LICENSE).
vendor/oxideav-h265/src/availability.rsdeleted+0 -569
@@ -1,569 +0,0 @@
1-//! §6.4 availability processes + the §6.5.1 / §6.5.2 picture-level
2-//! scanning conversions they depend on.
3-//!
4-//! Intra (and, later, inter) sample prediction asks, for each candidate
5-//! neighbour location `( xNbY, yNbY )`, whether that neighbour is
6-//! *available for prediction* — i.e. it lies inside the picture, has
7-//! already been decoded in the current decoding order, and sits in the
8-//! same slice segment and tile as the current block. ITU-T Rec. H.265
9-//! §6.4.1 answers that question, and it does so in terms of a
10-//! *minimum-transform-block address in z-scan order*, `MinTbAddrZs`.
11-//!
12-//! `MinTbAddrZs` (§6.5.2) in turn is built from `CtbAddrRsToTs`
13-//! (§6.5.1) — the CTB raster-scan ↔ tile-scan address conversion that
14-//! folds the picture's tile layout into the decoding order. So this
15-//! module implements three layers, bottom-up:
16-//!
17-//! * [`PictureTiling`] — §6.5.1. From the picture geometry in CTBs and
18-//! the §7.3.2.3.1 tile-partitioning parameters it derives `colWidth`
19-//! / `rowHeight` (eqs. 6-3 / 6-4), `colBd` / `rowBd` (eqs. 6-5 /
20-//! 6-6), `CtbAddrRsToTs` / `CtbAddrTsToRs` (eqs. 6-7 / 6-8), and
21-//! `TileId` (eq. 6-9).
22-//! * [`PictureTiling::min_tb_addr_zs`] — §6.5.2. The
23-//! `MinTbAddrZs[ x ][ y ]` array (eq. 6-10) mapping a minimum-block
24-//! `( x, y )` to its z-scan address, interleaving the within-CTB
25-//! Morton (z) order with the tile-scan CTB order.
26-//! * [`PictureTiling::z_scan_availability`] — §6.4.1, and
27-//! [`PictureTiling::prediction_block_availability`] — §6.4.2.
28-//!
29-//! ## Scope
30-//!
31-//! The numerics are self-contained. The caller supplies the picture
32-//! geometry (in CTBs and in luma samples), the `Log2SizeY` shifts, the
33-//! tile parameters from the active PPS, and a `slice_addr_rs` lookup
34-//! that maps a CTB raster address to the `SliceAddrRs` of the slice
35-//! segment that owns it (§6.4.1's slice-boundary test). For §6.4.2 the
36-//! caller additionally supplies a `CuPredMode` lookup (the final
37-//! `MODE_INTRA` masking step). Building those lookups is the slice-data
38-//! walk's responsibility; this module starts at the geometry and stops
39-//! at `availableN`.
40-
41-/// `CuPredMode` value `MODE_INTRA` — used by the §6.4.2 final masking
42-/// step. Mirrors the Table 7-10 enumeration without depending on the
43-/// slice module's richer type.
44-pub const MODE_INTRA: u8 = 1;
45-
46-/// Errors from constructing a [`PictureTiling`].
47-#[derive(Debug, Clone, PartialEq, Eq)]
48-pub enum AvailabilityError {
49- /// A geometry input was zero where the spec requires a positive
50- /// value (`PicWidthInCtbsY` / `PicHeightInCtbsY` must be ≥ 1).
51- ZeroGeometry {
52- /// Name of the offending field.
53- field: &'static str,
54- },
55- /// `CtbLog2SizeY` is smaller than `MinTbLog2SizeY`, which would make
56- /// the §6.5.2 `( CtbLog2SizeY − MinTbLog2SizeY )` shift negative.
57- InvalidLog2Sizes {
58- /// `CtbLog2SizeY`.
59- ctb_log2: u32,
60- /// `MinTbLog2SizeY`.
61- min_tb_log2: u32,
62- },
63- /// The explicit (`uniform_spacing_flag == 0`) tile-size array had a
64- /// length other than the required `num_tile_*_minus1`.
65- TileArrayLength {
66- /// Name of the offending array.
67- field: &'static str,
68- /// Length the spec requires.
69- expected: usize,
70- /// Length that was supplied.
71- got: usize,
72- },
73- /// An explicit tile column/row was wider/taller than the picture, so
74- /// the implied last tile would have a non-positive size.
75- TileOverflow {
76- /// `"column"` or `"row"`.
77- dimension: &'static str,
78- },
79-}
80-
81-impl core::fmt::Display for AvailabilityError {
82- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
83- match self {
84- Self::ZeroGeometry { field } => {
85- write!(f, "picture geometry field {field} must be positive")
86- }
87- Self::InvalidLog2Sizes {
88- ctb_log2,
89- min_tb_log2,
90- } => write!(
91- f,
92- "CtbLog2SizeY ({ctb_log2}) must be >= MinTbLog2SizeY ({min_tb_log2})"
93- ),
94- Self::TileArrayLength {
95- field,
96- expected,
97- got,
98- } => write!(f, "tile array {field} length {got} != expected {expected}"),
99- Self::TileOverflow { dimension } => {
100- write!(f, "explicit tile {dimension} sizes overflow the picture")
101- }
102- }
103- }
104-}
105-
106-impl std::error::Error for AvailabilityError {}
107-
108-/// The §7.3.2.3.1 tile-partitioning parameters needed to build the
109-/// CTB-scan conversion, as carried by the active PPS.
110-///
111-/// When `tiles_enabled_flag == 0` the picture is a single tile; pass
112-/// [`TilingParams::single_tile`] (one column, one row).
113-#[derive(Debug, Clone, PartialEq, Eq)]
114-pub struct TilingParams {
115- /// `num_tile_columns_minus1` — the number of tile columns is this
116- /// plus one.
117- pub num_tile_columns_minus1: u32,
118- /// `num_tile_rows_minus1` — the number of tile rows is this plus
119- /// one.
120- pub num_tile_rows_minus1: u32,
121- /// `uniform_spacing_flag`. When `true` the columns/rows are spread
122- /// as evenly as possible (eqs. 6-3 / 6-4 uniform branch) and the
123- /// explicit arrays are ignored.
124- pub uniform_spacing_flag: bool,
125- /// `column_width_minus1[ i ]` for `i` in
126- /// `0..num_tile_columns_minus1` (only when not uniform).
127- pub column_width_minus1: Vec<u32>,
128- /// `row_height_minus1[ j ]` for `j` in `0..num_tile_rows_minus1`
129- /// (only when not uniform).
130- pub row_height_minus1: Vec<u32>,
131-}
132-
133-impl TilingParams {
134- /// The single-tile layout used when `tiles_enabled_flag == 0`.
135- pub fn single_tile() -> Self {
136- Self {
137- num_tile_columns_minus1: 0,
138- num_tile_rows_minus1: 0,
139- uniform_spacing_flag: true,
140- column_width_minus1: Vec::new(),
141- row_height_minus1: Vec::new(),
142- }
143- }
144-}
145-
146-/// Picture-level geometry plus the derived §6.5.1 / §6.5.2 conversion
147-/// tables. Construct with [`PictureTiling::new`], then query availability
148-/// with [`PictureTiling::z_scan_availability`] /
149-/// [`PictureTiling::prediction_block_availability`].
150-#[derive(Debug, Clone)]
151-pub struct PictureTiling {
152- pic_width_in_ctbs_y: u32,
153- pic_height_in_ctbs_y: u32,
154- pic_width_in_luma_samples: u32,
155- pic_height_in_luma_samples: u32,
156- ctb_log2_size_y: u32,
157- min_tb_log2_size_y: u32,
158- /// `colBd[ 0..=num_tile_columns_minus1 + 1 ]` (eq. 6-5).
159- col_bd: Vec<u32>,
160- /// `rowBd[ 0..=num_tile_rows_minus1 + 1 ]` (eq. 6-6).
161- row_bd: Vec<u32>,
162- /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7).
163- ctb_addr_rs_to_ts: Vec<u32>,
164- /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8).
165- ctb_addr_ts_to_rs: Vec<u32>,
166- /// `TileId[ ctbAddrTs ]` (eq. 6-9).
167- tile_id: Vec<u32>,
168-}
169-
170-impl PictureTiling {
171- /// Build the §6.5.1 conversion tables from the picture geometry and
172- /// tile parameters.
173- ///
174- /// * `pic_width_in_ctbs_y` / `pic_height_in_ctbs_y` —
175- /// `PicWidthInCtbsY` / `PicHeightInCtbsY` (eqs. 7-20 / 7-21).
176- /// * `pic_width_in_luma_samples` / `pic_height_in_luma_samples` —
177- /// the SPS conformance-relevant `pic_width_in_luma_samples` /
178- /// `pic_height_in_luma_samples` used by §6.4.1's boundary test.
179- /// * `ctb_log2_size_y` — `CtbLog2SizeY` (eq. 7-11).
180- /// * `min_tb_log2_size_y` — `MinTbLog2SizeY`
181- /// (= `log2_min_luma_transform_block_size_minus2 + 2`).
182- /// * `tiles` — the active PPS tile-partitioning parameters.
183- pub fn new(
184- pic_width_in_ctbs_y: u32,
185- pic_height_in_ctbs_y: u32,
186- pic_width_in_luma_samples: u32,
187- pic_height_in_luma_samples: u32,
188- ctb_log2_size_y: u32,
189- min_tb_log2_size_y: u32,
190- tiles: &TilingParams,
191- ) -> Result<Self, AvailabilityError> {
192- if pic_width_in_ctbs_y == 0 {
193- return Err(AvailabilityError::ZeroGeometry {
194- field: "PicWidthInCtbsY",
195- });
196- }
197- if pic_height_in_ctbs_y == 0 {
198- return Err(AvailabilityError::ZeroGeometry {
199- field: "PicHeightInCtbsY",
200- });
201- }
202- if ctb_log2_size_y < min_tb_log2_size_y {
203- return Err(AvailabilityError::InvalidLog2Sizes {
204- ctb_log2: ctb_log2_size_y,
205- min_tb_log2: min_tb_log2_size_y,
206- });
207- }
208-
209- let num_cols = (tiles.num_tile_columns_minus1 + 1) as usize;
210- let num_rows = (tiles.num_tile_rows_minus1 + 1) as usize;
211-
212- // §6.5.1 eqs. 6-3 / 6-4 — colWidth / rowHeight (in CTBs).
213- let col_width = derive_tile_sizes(
214- pic_width_in_ctbs_y,
215- tiles.num_tile_columns_minus1,
216- tiles.uniform_spacing_flag,
217- &tiles.column_width_minus1,
218- "column_width_minus1",
219- "column",
220- )?;
221- let row_height = derive_tile_sizes(
222- pic_height_in_ctbs_y,
223- tiles.num_tile_rows_minus1,
224- tiles.uniform_spacing_flag,
225- &tiles.row_height_minus1,
226- "row_height_minus1",
227- "row",
228- )?;
229-
230- // §6.5.1 eqs. 6-5 / 6-6 — colBd / rowBd (cumulative boundaries).
231- let mut col_bd = vec![0u32; num_cols + 1];
232- for i in 0..num_cols {
233- col_bd[i + 1] = col_bd[i] + col_width[i];
234- }
235- let mut row_bd = vec![0u32; num_rows + 1];
236- for j in 0..num_rows {
237- row_bd[j + 1] = row_bd[j] + row_height[j];
238- }
239-
240- let pic_size_in_ctbs_y = (pic_width_in_ctbs_y * pic_height_in_ctbs_y) as usize;
241-
242- // §6.5.1 eq. 6-7 — CtbAddrRsToTs.
243- let mut ctb_addr_rs_to_ts = vec![0u32; pic_size_in_ctbs_y];
244- for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 {
245- let tb_x = ctb_addr_rs % pic_width_in_ctbs_y;
246- let tb_y = ctb_addr_rs / pic_width_in_ctbs_y;
247- let mut tile_x = 0usize;
248- for (i, &bd) in col_bd.iter().take(num_cols).enumerate() {
249- if tb_x >= bd {
250- tile_x = i;
251- }
252- }
253- let mut tile_y = 0usize;
254- for (j, &bd) in row_bd.iter().take(num_rows).enumerate() {
255- if tb_y >= bd {
256- tile_y = j;
257- }
258- }
259- let mut val = 0u32;
260- for &cw in col_width.iter().take(tile_x) {
261- val += row_height[tile_y] * cw;
262- }
263- for &rh in row_height.iter().take(tile_y) {
264- val += pic_width_in_ctbs_y * rh;
265- }
266- val += (tb_y - row_bd[tile_y]) * col_width[tile_x] + tb_x - col_bd[tile_x];
267- ctb_addr_rs_to_ts[ctb_addr_rs as usize] = val;
268- }
269-
270- // §6.5.1 eq. 6-8 — CtbAddrTsToRs (inverse permutation).
271- let mut ctb_addr_ts_to_rs = vec![0u32; pic_size_in_ctbs_y];
272- for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 {
273- ctb_addr_ts_to_rs[ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize] = ctb_addr_rs;
274- }
275-
276- // §6.5.1 eq. 6-9 — TileId.
277- let mut tile_id = vec![0u32; pic_size_in_ctbs_y];
278- let mut tile_idx = 0u32;
279- for j in 0..num_rows {
280- for i in 0..num_cols {
281- for y in row_bd[j]..row_bd[j + 1] {
282- for x in col_bd[i]..col_bd[i + 1] {
283- let rs = (y * pic_width_in_ctbs_y + x) as usize;
284- tile_id[ctb_addr_rs_to_ts[rs] as usize] = tile_idx;
285- }
286- }
287- tile_idx += 1;
288- }
289- }
290-
291- Ok(Self {
292- pic_width_in_ctbs_y,
293- pic_height_in_ctbs_y,
294- pic_width_in_luma_samples,
295- pic_height_in_luma_samples,
296- ctb_log2_size_y,
297- min_tb_log2_size_y,
298- col_bd,
299- row_bd,
300- ctb_addr_rs_to_ts,
301- ctb_addr_ts_to_rs,
302- tile_id,
303- })
304- }
305-
306- /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7). Panics on out-of-range
307- /// `ctb_addr_rs`; valid indices are `0..PicSizeInCtbsY`.
308- pub fn ctb_addr_rs_to_ts(&self, ctb_addr_rs: u32) -> u32 {
309- self.ctb_addr_rs_to_ts[ctb_addr_rs as usize]
310- }
311-
312- /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8).
313- pub fn ctb_addr_ts_to_rs(&self, ctb_addr_ts: u32) -> u32 {
314- self.ctb_addr_ts_to_rs[ctb_addr_ts as usize]
315- }
316-
317- /// `TileId[ ctbAddrTs ]` (eq. 6-9) — the tile a tile-scan CTB
318- /// address belongs to.
319- pub fn tile_id(&self, ctb_addr_ts: u32) -> u32 {
320- self.tile_id[ctb_addr_ts as usize]
321- }
322-
323- /// `colBd[ i ]` (eq. 6-5) — the i-th tile-column boundary in units
324- /// of CTBs, for `i` in `0..=num_tile_columns_minus1 + 1`.
325- pub fn col_bd(&self) -> &[u32] {
326- &self.col_bd
327- }
328-
329- /// `rowBd[ j ]` (eq. 6-6) — the j-th tile-row boundary in units of
330- /// CTBs, for `j` in `0..=num_tile_rows_minus1 + 1`.
331- pub fn row_bd(&self) -> &[u32] {
332- &self.row_bd
333- }
334-
335- /// `PicWidthInCtbsY`.
336- pub fn pic_width_in_ctbs_y(&self) -> u32 {
337- self.pic_width_in_ctbs_y
338- }
339-
340- /// `PicHeightInCtbsY`.
341- pub fn pic_height_in_ctbs_y(&self) -> u32 {
342- self.pic_height_in_ctbs_y
343- }
344-
345- /// The TileId of the tile covering luma sample `( xY, yY )`.
346- /// Convenience over [`Self::tile_id`] that converts the luma
347- /// location through the CTB raster→tile-scan conversion. The caller
348- /// is responsible for keeping `( xY, yY )` inside the picture.
349- fn tile_id_at_luma(&self, x_y: u32, y_y: u32) -> u32 {
350- let ctb_x = x_y >> self.ctb_log2_size_y;
351- let ctb_y = y_y >> self.ctb_log2_size_y;
352- let ctb_addr_rs = ctb_y * self.pic_width_in_ctbs_y + ctb_x;
353- self.tile_id[self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize]
354- }
355-
356- /// `MinTbAddrZs[ x ][ y ]` (§6.5.2 eq. 6-10) — the minimum-block
357- /// location `( x, y )` (in units of `MinTbLog2SizeY`-sized blocks)
358- /// converted to a minimum-block address in z-scan order.
359- ///
360- /// Combines the tile-scan CTB order (high bits) with the within-CTB
361- /// Morton / z interleave of the block's `( x, y )` low bits. The
362- /// caller is responsible for keeping `( x, y )` within the picture's
363- /// minimum-block grid.
364- pub fn min_tb_addr_zs(&self, x: u32, y: u32) -> u32 {
365- let shift = self.ctb_log2_size_y - self.min_tb_log2_size_y;
366- let tb_x = (x << self.min_tb_log2_size_y) >> self.ctb_log2_size_y;
367- let tb_y = (y << self.min_tb_log2_size_y) >> self.ctb_log2_size_y;
368- let ctb_addr_rs = self.pic_width_in_ctbs_y * tb_y + tb_x;
369- let mut addr = self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] << (shift * 2);
370- let mut p = 0u32;
371- for i in 0..shift {
372- let m = 1u32 << i;
373- p += if m & x != 0 { m * m } else { 0 } + if m & y != 0 { 2 * m * m } else { 0 };
374- }
375- addr += p;
376- addr
377- }
378-
379- /// §6.4.1 — derivation process for z-scan order block availability.
380- ///
381- /// Returns whether the neighbouring block covering luma location
382- /// `( x_nb_y, y_nb_y )` is available for the current block whose
383- /// top-left luma sample is `( x_curr, y_curr )`.
384- ///
385- /// `slice_addr_rs` maps a CTB raster-scan address to the
386- /// `SliceAddrRs` of the slice segment that owns that CTB — the
387- /// slice-boundary test of §6.4.1. The caller's slice-data walk
388- /// builds it; for a single-slice picture it is the constant `0`.
389- pub fn z_scan_availability<F>(
390- &self,
391- x_curr: u32,
392- y_curr: u32,
393- x_nb_y: i32,
394- y_nb_y: i32,
395- slice_addr_rs: F,
396- ) -> bool
397- where
398- F: Fn(u32) -> u32,
399- {
400- // eq. 6-1.
401- let min_block_addr_curr = self.min_tb_addr_zs(
402- x_curr >> self.min_tb_log2_size_y,
403- y_curr >> self.min_tb_log2_size_y,
404- );
405-
406- // eq. 6-2 — out-of-picture neighbours get minBlockAddrN = −1.
407- if x_nb_y < 0
408- || y_nb_y < 0
409- || x_nb_y as u32 >= self.pic_width_in_luma_samples
410- || y_nb_y as u32 >= self.pic_height_in_luma_samples
411- {
412- return false;
413- }
414- let x_nb_y = x_nb_y as u32;
415- let y_nb_y = y_nb_y as u32;
416- let min_block_addr_n = self.min_tb_addr_zs(
417- x_nb_y >> self.min_tb_log2_size_y,
418- y_nb_y >> self.min_tb_log2_size_y,
419- );
420-
421- // The neighbour must already be decoded (z-scan order test).
422- if min_block_addr_n > min_block_addr_curr {
423- return false;
424- }
425-
426- // Slice-segment boundary: compare the SliceAddrRs of the CTBs
427- // owning each block. The block addresses are in z-scan order;
428- // map them back to the owning CTB raster address.
429- let ctb_rs_curr = self.ctb_rs_of_z(min_block_addr_curr);
430- let ctb_rs_n = self.ctb_rs_of_z(min_block_addr_n);
431- if slice_addr_rs(ctb_rs_n) != slice_addr_rs(ctb_rs_curr) {
432- return false;
433- }
434-
435- // Tile boundary: the neighbour must be in the same tile.
436- if self.tile_id_at_luma(x_nb_y, y_nb_y) != self.tile_id_at_luma(x_curr, y_curr) {
437- return false;
438- }
439-
440- true
441- }
442-
443- /// §6.4.2 — derivation process for prediction block availability.
444- ///
445- /// Wraps [`Self::z_scan_availability`] with the `sameCb` short-cut
446- /// (a neighbour in the *same* coding block is unavailable when it
447- /// would not yet have been decoded under the §7.4.9 partitioning
448- /// order) and the final `MODE_INTRA` masking.
449- ///
450- /// * `( x_cb, y_cb )` / `n_cb_s` — the current coding block.
451- /// * `( x_pb, y_pb )` / `n_pb_w` / `n_pb_h` / `part_idx` — the
452- /// current prediction block and its partition index.
453- /// * `( x_nb_y, y_nb_y )` — the neighbour location.
454- /// * `slice_addr_rs` — as in [`Self::z_scan_availability`].
455- /// * `cu_pred_mode` — maps a luma location to its `CuPredMode`
456- /// (`MODE_INTRA` / `MODE_INTER` / `MODE_SKIP`). Only consulted for
457- /// in-picture neighbours that are otherwise available.
458- #[allow(clippy::too_many_arguments)]
459- pub fn prediction_block_availability<S, M>(
460- &self,
461- x_cb: u32,
462- y_cb: u32,
463- n_cb_s: u32,
464- x_pb: u32,
465- y_pb: u32,
466- n_pb_w: u32,
467- n_pb_h: u32,
468- part_idx: u32,
469- x_nb_y: i32,
470- y_nb_y: i32,
471- slice_addr_rs: S,
472- cu_pred_mode: M,
473- ) -> bool
474- where
475- S: Fn(u32) -> u32,
476- M: Fn(u32, u32) -> u8,
477- {
478- // sameCb: does the neighbour cover the current coding block?
479- let same_cb = x_nb_y >= 0
480- && y_nb_y >= 0
481- && x_cb <= x_nb_y as u32
482- && y_cb <= y_nb_y as u32
483- && (x_cb + n_cb_s) > x_nb_y as u32
484- && (y_cb + n_cb_s) > y_nb_y as u32;
485-
486- let mut available_n = if !same_cb {
487- self.z_scan_availability(x_pb, y_pb, x_nb_y, y_nb_y, slice_addr_rs)
488- } else if (n_pb_w << 1) == n_cb_s
489- && (n_pb_h << 1) == n_cb_s
490- && part_idx == 1
491- && (y_cb + n_pb_h) <= y_nb_y as u32
492- && (x_cb + n_pb_w) > x_nb_y as u32
493- {
494- // The Nx2N / 2NxN second partition cannot reference the not-
495- // yet-decoded partition-0 region inside the same CU.
496- false
497- } else {
498- true
499- };
500-
501- // Final §6.4.2 step: intra neighbours are unavailable for the
502- // (inter) prediction-block availability query.
503- if available_n {
504- let x = x_nb_y as u32;
505- let y = y_nb_y as u32;
506- if cu_pred_mode(x, y) == MODE_INTRA {
507- available_n = false;
508- }
509- }
510-
511- available_n
512- }
513-
514- /// Map a minimum-block z-scan address back to the CTB raster-scan
515- /// address that contains it. The high
516- /// `( CtbLog2SizeY − MinTbLog2SizeY ) * 2` bits of a z-scan block
517- /// address are the tile-scan CTB address (see eq. 6-10).
518- fn ctb_rs_of_z(&self, min_block_addr_z: u32) -> u32 {
519- let shift = (self.ctb_log2_size_y - self.min_tb_log2_size_y) * 2;
520- let ctb_addr_ts = min_block_addr_z >> shift;
521- self.ctb_addr_ts_to_rs[ctb_addr_ts as usize]
522- }
523-}
524-
525-/// §6.5.1 eqs. 6-3 / 6-4 — derive the per-tile sizes (`colWidth` /
526-/// `rowHeight`) in CTBs, for one dimension.
527-fn derive_tile_sizes(
528- pic_size_in_ctbs: u32,
529- num_tiles_minus1: u32,
530- uniform_spacing_flag: bool,
531- explicit_minus1: &[u32],
532- array_field: &'static str,
533- dimension: &'static str,
534-) -> Result<Vec<u32>, AvailabilityError> {
535- let num_tiles = (num_tiles_minus1 + 1) as usize;
536- let mut sizes = vec![0u32; num_tiles];
537- if uniform_spacing_flag {
538- for (i, slot) in sizes.iter_mut().enumerate() {
539- let i = i as u32;
540- *slot = ((i + 1) * pic_size_in_ctbs) / (num_tiles_minus1 + 1)
541- - (i * pic_size_in_ctbs) / (num_tiles_minus1 + 1);
542- }
543- } else {
544- if explicit_minus1.len() != num_tiles_minus1 as usize {
545- return Err(AvailabilityError::TileArrayLength {
546- field: array_field,
547- expected: num_tiles_minus1 as usize,
548- got: explicit_minus1.len(),
549- });
550- }
551- // The last tile takes the remainder; the first num_tiles_minus1
552- // are explicit.
553- sizes[num_tiles - 1] = pic_size_in_ctbs;
554- for i in 0..num_tiles_minus1 as usize {
555- sizes[i] = explicit_minus1[i] + 1;
556- if sizes[i] > sizes[num_tiles - 1] {
557- return Err(AvailabilityError::TileOverflow { dimension });
558- }
559- sizes[num_tiles - 1] -= sizes[i];
560- }
561- if sizes[num_tiles - 1] == 0 {
562- return Err(AvailabilityError::TileOverflow { dimension });
563- }
564- }
565- Ok(sizes)
566-}
567-
568-#[cfg(test)]
569-mod tests;
vendor/oxideav-h265/src/availability/tests.rsdeleted+0 -315
@@ -1,315 +0,0 @@
1-//! Tests for §6.4 availability + §6.5.1 / §6.5.2 scan conversions.
2-//!
3-//! Expected values are hand-derived from the ITU-T H.265 equations, not
4-//! taken from any implementation.
5-
6-use super::*;
7-
8-/// Build the simplest single-tile geometry: `w`×`h` CTBs, CtbLog2 = 6
9-/// (64-sample CTBs), MinTbLog2 = 2 (4-sample minimum blocks).
10-fn single_tile(w: u32, h: u32) -> PictureTiling {
11- PictureTiling::new(w, h, w * 64, h * 64, 6, 2, &TilingParams::single_tile()).unwrap()
12-}
13-
14-#[test]
15-fn single_tile_rs_to_ts_is_identity() {
16- let t = single_tile(3, 2);
17- for rs in 0..6 {
18- assert_eq!(t.ctb_addr_rs_to_ts(rs), rs, "rs->ts identity at {rs}");
19- assert_eq!(t.ctb_addr_ts_to_rs(rs), rs, "ts->rs identity at {rs}");
20- assert_eq!(t.tile_id(rs), 0, "single tile id at {rs}");
21- }
22-}
23-
24-#[test]
25-fn min_tb_addr_zs_within_one_ctb_is_morton() {
26- // One 64-sample CTB = 16×16 4-sample min-blocks. shift = 4.
27- // Within a single CTB (tile-scan addr 0), MinTbAddrZs is the pure
28- // Morton interleave of the block (x, y) bits (eq. 6-10 with the
29- // CtbAddrRsToTs term zero).
30- let t = single_tile(1, 1);
31- // (0,0) -> 0
32- assert_eq!(t.min_tb_addr_zs(0, 0), 0);
33- // (1,0): x bit0 set -> p += 1*1 = 1
34- assert_eq!(t.min_tb_addr_zs(1, 0), 1);
35- // (0,1): y bit0 set -> p += 2*1*1 = 2
36- assert_eq!(t.min_tb_addr_zs(0, 1), 2);
37- // (1,1): 1 + 2 = 3
38- assert_eq!(t.min_tb_addr_zs(1, 1), 3);
39- // (2,0): x bit1 (m=2) set -> p += 2*2 = 4
40- assert_eq!(t.min_tb_addr_zs(2, 0), 4);
41- // (0,2): y bit1 set -> p += 2*2*2 = 8
42- assert_eq!(t.min_tb_addr_zs(0, 2), 8);
43- // (3,3): x bits 0,1 -> 1 + 4 = 5; y bits 0,1 -> 2 + 8 = 10; sum 15
44- assert_eq!(t.min_tb_addr_zs(3, 3), 15);
45- // (15,15): all four x bits -> 1+4+16+64 = 85; y doubles -> 170; 255
46- assert_eq!(t.min_tb_addr_zs(15, 15), 255);
47-}
48-
49-#[test]
50-fn min_tb_addr_zs_second_ctb_offsets_by_256() {
51- // Two CTBs wide, single tile/slice. The min-block grid is 32 wide.
52- // A block in the second CTB (x >= 16) sits at tile-scan CTB addr 1,
53- // so its z-address starts at 1 << (shift*2) = 256.
54- let t = single_tile(2, 1);
55- assert_eq!(t.min_tb_addr_zs(16, 0), 256);
56- assert_eq!(t.min_tb_addr_zs(17, 0), 257);
57- // First CTB still occupies 0..255.
58- assert_eq!(t.min_tb_addr_zs(15, 15), 255);
59-}
60-
61-#[test]
62-fn uniform_two_column_tiles_split_evenly() {
63- // 4 CTBs wide, 1 tall, 2 uniform columns -> colWidth = [2, 2].
64- // colBd = [0, 2, 4]. CtbAddrRsToTs: tile 0 holds CTBs (0,1), tile 1
65- // holds (2,3); tile scan visits tile 0 fully then tile 1.
66- let tiles = TilingParams {
67- num_tile_columns_minus1: 1,
68- num_tile_rows_minus1: 0,
69- uniform_spacing_flag: true,
70- column_width_minus1: vec![],
71- row_height_minus1: vec![],
72- };
73- let t = PictureTiling::new(4, 1, 256, 64, 6, 2, &tiles).unwrap();
74- // rs 0,1 (tile 0) -> ts 0,1; rs 2,3 (tile 1) -> ts 2,3 (here the
75- // single row keeps tile-scan == raster for this layout).
76- assert_eq!(t.ctb_addr_rs_to_ts(0), 0);
77- assert_eq!(t.ctb_addr_rs_to_ts(1), 1);
78- assert_eq!(t.ctb_addr_rs_to_ts(2), 2);
79- assert_eq!(t.ctb_addr_rs_to_ts(3), 3);
80- assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0);
81- assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(2)), 1);
82-}
83-
84-#[test]
85-fn uniform_two_by_two_tiles_reorder_tile_scan() {
86- // 4×4 CTBs, 2×2 uniform tiles. colWidth = rowHeight = [2, 2].
87- // Tile scan visits tile (0,0)'s 4 CTBs, then (1,0), then (0,1),
88- // then (1,1). So raster CTB 2 (top-right tile) maps to tile-scan 4.
89- let tiles = TilingParams {
90- num_tile_columns_minus1: 1,
91- num_tile_rows_minus1: 1,
92- uniform_spacing_flag: true,
93- column_width_minus1: vec![],
94- row_height_minus1: vec![],
95- };
96- let t = PictureTiling::new(4, 4, 256, 256, 6, 2, &tiles).unwrap();
97- // Raster addr of CTB at (col=0,row=0) = 0 -> ts 0, tile 0.
98- assert_eq!(t.ctb_addr_rs_to_ts(0), 0);
99- assert_eq!(t.tile_id(0), 0);
100- // CTB at (col=2,row=0) raster = 2; it is tile (1,0) = tile idx 1,
101- // first CTB after tile 0's 4 -> ts 4.
102- assert_eq!(t.ctb_addr_rs_to_ts(2), 4);
103- assert_eq!(t.tile_id(4), 1);
104- // CTB at (col=0,row=2) raster = 8; tile (0,1) = tile idx 2 -> ts 8.
105- assert_eq!(t.ctb_addr_rs_to_ts(8), 8);
106- assert_eq!(t.tile_id(8), 2);
107- // CTB at (col=2,row=2) raster = 10; tile (1,1) = tile idx 3 -> ts 12.
108- assert_eq!(t.ctb_addr_rs_to_ts(10), 12);
109- assert_eq!(t.tile_id(12), 3);
110- // ts->rs is the inverse permutation.
111- for rs in 0..16 {
112- assert_eq!(t.ctb_addr_ts_to_rs(t.ctb_addr_rs_to_ts(rs)), rs);
113- }
114-}
115-
116-#[test]
117-fn explicit_tile_widths() {
118- // 5 CTBs wide, 1 tall, 2 columns, column_width_minus1[0] = 0
119- // -> colWidth = [1, 4].
120- let tiles = TilingParams {
121- num_tile_columns_minus1: 1,
122- num_tile_rows_minus1: 0,
123- uniform_spacing_flag: false,
124- column_width_minus1: vec![0],
125- row_height_minus1: vec![],
126- };
127- let t = PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles).unwrap();
128- assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0); // first CTB, tile 0
129- assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(1)), 1); // rest, tile 1
130- assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(4)), 1);
131-}
132-
133-#[test]
134-fn explicit_tile_overflow_rejected() {
135- // column_width_minus1[0] = 5 implies first tile is 6 CTBs wide in a
136- // 5-CTB-wide picture -> overflow.
137- let tiles = TilingParams {
138- num_tile_columns_minus1: 1,
139- num_tile_rows_minus1: 0,
140- uniform_spacing_flag: false,
141- column_width_minus1: vec![5],
142- row_height_minus1: vec![],
143- };
144- assert!(matches!(
145- PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles),
146- Err(AvailabilityError::TileOverflow {
147- dimension: "column"
148- })
149- ));
150-}
151-
152-#[test]
153-fn explicit_array_length_mismatch_rejected() {
154- let tiles = TilingParams {
155- num_tile_columns_minus1: 2, // expects 2 entries
156- num_tile_rows_minus1: 0,
157- uniform_spacing_flag: false,
158- column_width_minus1: vec![0], // only 1 supplied
159- row_height_minus1: vec![],
160- };
161- assert!(matches!(
162- PictureTiling::new(6, 1, 384, 64, 6, 2, &tiles),
163- Err(AvailabilityError::TileArrayLength { .. })
164- ));
165-}
166-
167-#[test]
168-fn invalid_log2_sizes_rejected() {
169- // CtbLog2 < MinTbLog2.
170- assert!(matches!(
171- PictureTiling::new(1, 1, 64, 64, 2, 4, &TilingParams::single_tile()),
172- Err(AvailabilityError::InvalidLog2Sizes { .. })
173- ));
174-}
175-
176-#[test]
177-fn zero_geometry_rejected() {
178- assert!(matches!(
179- PictureTiling::new(0, 1, 0, 64, 6, 2, &TilingParams::single_tile()),
180- Err(AvailabilityError::ZeroGeometry {
181- field: "PicWidthInCtbsY"
182- })
183- ));
184-}
185-
186-// ---- §6.4.1 z-scan availability ----
187-
188-#[test]
189-fn neighbour_outside_picture_is_unavailable() {
190- let t = single_tile(2, 2);
191- let same_slice = |_rs: u32| 0u32;
192- // Current block at (64, 64). Left neighbour at x = -1 -> out.
193- assert!(!t.z_scan_availability(64, 64, -1, 64, same_slice));
194- // Top neighbour at y = -1 -> out.
195- assert!(!t.z_scan_availability(64, 64, 64, -1, same_slice));
196- // Right of picture (picture is 128 wide).
197- assert!(!t.z_scan_availability(64, 64, 128, 64, same_slice));
198- // Below picture (128 tall).
199- assert!(!t.z_scan_availability(64, 64, 64, 128, same_slice));
200-}
201-
202-#[test]
203-fn already_decoded_left_and_above_are_available() {
204- // 2×2 CTBs, single slice/tile. Current block top-left at (64, 64)
205- // (the bottom-right CTB, decoded last in raster order). Its left
206- // (63, 64) and above (64, 63) neighbours decode earlier -> available.
207- let t = single_tile(2, 2);
208- let same_slice = |_rs: u32| 0u32;
209- assert!(t.z_scan_availability(64, 64, 63, 64, same_slice)); // left
210- assert!(t.z_scan_availability(64, 64, 64, 63, same_slice)); // above
211- assert!(t.z_scan_availability(64, 64, 63, 63, same_slice)); // above-left
212-}
213-
214-#[test]
215-fn not_yet_decoded_neighbour_is_unavailable() {
216- // Current at the top-left CTB (0,0). The below-right neighbour at
217- // (64, 64) decodes later -> minBlockAddrN > minBlockAddrCurr ->
218- // unavailable even though it is inside the picture.
219- let t = single_tile(2, 2);
220- let same_slice = |_rs: u32| 0u32;
221- assert!(!t.z_scan_availability(0, 0, 64, 64, same_slice));
222- // The above-right of the bottom-left CTB: current (0,64),
223- // neighbour (64, 63) is in the top-right CTB which decodes before
224- // the bottom-left CTB in raster order -> available.
225- assert!(t.z_scan_availability(0, 64, 64, 63, same_slice));
226-}
227-
228-#[test]
229-fn different_slice_is_unavailable() {
230- // 2×2 CTBs. Put the second slice starting at raster CTB 3 (the
231- // bottom-right). Current block in CTB 3, left neighbour in CTB 2.
232- let t = single_tile(2, 2);
233- let slice_of = |rs: u32| if rs >= 3 { 1u32 } else { 0u32 };
234- // current (64,64) is CTB 3 (slice 1); left (63,64) is CTB 2 (slice 0)
235- assert!(!t.z_scan_availability(64, 64, 63, 64, slice_of));
236- // within-slice neighbour: above (64,63) is CTB 1 (slice 0) too, but
237- // it differs from current's slice 1 -> still unavailable.
238- assert!(!t.z_scan_availability(64, 64, 64, 63, slice_of));
239-}
240-
241-#[test]
242-fn different_tile_is_unavailable() {
243- // 2 columns × 1 row of tiles over 2×1 CTBs: each CTB is its own
244- // tile. Current block in the right CTB, left neighbour in the left
245- // CTB -> different tile -> unavailable even within one slice.
246- let tiles = TilingParams {
247- num_tile_columns_minus1: 1,
248- num_tile_rows_minus1: 0,
249- uniform_spacing_flag: true,
250- column_width_minus1: vec![],
251- row_height_minus1: vec![],
252- };
253- let t = PictureTiling::new(2, 1, 128, 64, 6, 2, &tiles).unwrap();
254- let same_slice = |_rs: u32| 0u32;
255- // current (64,0) right tile; left (63,0) left tile.
256- assert!(!t.z_scan_availability(64, 0, 63, 0, same_slice));
257- // within the same (right) tile a left neighbour is available.
258- assert!(t.z_scan_availability(127, 0, 126, 0, same_slice));
259-}
260-
261-// ---- §6.4.2 prediction block availability ----
262-
263-#[test]
264-fn prediction_block_intra_neighbour_masked_out() {
265- // 2×2 CTBs single slice/tile. Current PB top-left (64,64). Left
266- // neighbour (63,64) would be z-scan available, but its CuPredMode
267- // is MODE_INTRA -> masked to unavailable for the inter query.
268- let t = single_tile(2, 2);
269- let same_slice = |_rs: u32| 0u32;
270- let all_intra = |_x: u32, _y: u32| MODE_INTRA;
271- let all_inter = |_x: u32, _y: u32| 0u8; // MODE_INTER
272- // 64×64 CU == one 64×64 PB (2Nx2N), partIdx 0.
273- assert!(!t.prediction_block_availability(
274- 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_intra,
275- ));
276- assert!(t.prediction_block_availability(
277- 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter,
278- ));
279-}
280-
281-#[test]
282-fn prediction_block_second_partition_cannot_see_first() {
283- // The §6.4.2 same-CB forced-FALSE branch fires only for the NxN
284- // partitioning ((nPbW << 1) == nCbS AND (nPbH << 1) == nCbS): a
285- // 64×64 CU split into four 32×32 PBs. The top-right PB (partIdx 1,
286- // top-left (32, 0)) must not reference the bottom-left PB region
287- // (yNbY >= yCb + nPbH = 32, xNbY < xCb + nPbW = 32), which the
288- // §7.4.9 partitioning order has not decoded yet.
289- let t = single_tile(2, 2);
290- let same_slice = |_rs: u32| 0u32;
291- let all_inter = |_x: u32, _y: u32| 0u8;
292- // CU (0,0) size 64; PB1 (32,0) 32×32, partIdx 1. Neighbour (31, 32)
293- // is the bottom-left PB region — same CB, the forced-FALSE branch.
294- assert!(!t
295- .prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 31, 32, same_slice, all_inter,));
296- // The bottom-right region (xNbY >= 32) is NOT forced false by this
297- // branch (it sits at xNbY = 32, failing xCb+nPbW > xNbY); it falls
298- // through to availableN = TRUE since it is the same CB.
299- assert!(
300- t.prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 32, 32, same_slice, all_inter,)
301- );
302-}
303-
304-#[test]
305-fn prediction_block_normal_left_neighbour_available() {
306- // Same-CB short-cut not triggered (neighbour outside the CU): a
307- // normal left neighbour of an inter 2Nx2N PB resolves through
308- // §6.4.1 and is available.
309- let t = single_tile(2, 2);
310- let same_slice = |_rs: u32| 0u32;
311- let all_inter = |_x: u32, _y: u32| 0u8;
312- assert!(t.prediction_block_availability(
313- 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter,
314- ));
315-}
vendor/oxideav-h265/src/binarization.rsdeleted+0 -8000

Diff too large; view file

@@ -1,8000 +0,0 @@
1-//! §9.3.4.2 per-syntax-element binarization + context-index derivation.
2-//!
3-//! Sits one layer above the §9.3 arithmetic decoding engine
4-//! ([`crate::cabac::CabacEngine`]). For each entropy-coded syntax
5-//! element this module supplies the §9.3.3 binarization shape (truncated
6-//! rice, fixed length, Exp-Golomb of order *k*, …) plus the §9.3.4.2.X
7-//! per-bin `ctxInc` derivation, returning a context-index into the
8-//! per-slice context-model array.
9-//!
10-//! Round 26 ships the two syntax elements unblocked by the clean-room
11-//! CABAC trace `docs/video/h265/fixtures/main-422-10bit/cabac-cu-qp-delta-last-sig-trace.md`:
12-//!
13-//! * **`cu_qp_delta_abs` / `cu_qp_delta_sign_flag`** (H.265 §7.3.8.14,
14-//! §7.4.9.14). Binarization: §9.3.3.10 TR prefix (`cMax = 5`,
15-//! `cRiceParam = 0`) followed, when the prefix is the all-ones escape
16-//! (`prefixVal == 5`), by an EGk suffix with `k = 0` (§9.3.3.11). The
17-//! per-bin `ctxInc` (§9.3.4.2.2, Table 9-32): bin 0 uses `ctxInc = 0`,
18-//! bins 1..=4 share `ctxInc = 1`. The sign flag is bypass-coded.
19-//! `CuQpDeltaVal = cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`.
20-//!
21-//! * **`last_sig_coeff_{x,y}_prefix`** (H.265 §7.3.8.11, §7.4.9.11).
22-//! Binarization: §9.3.3.10 TR prefix with
23-//! `cMax = (log2TrafoSize << 1) − 1` and `cRiceParam = 0`. The per-bin
24-//! `ctxInc` (§9.3.4.2.3) is
25-//! `ctxInc = (binIdx >> ctxShift) + ctxOffset`. For luma:
26-//! `ctxOffset = 3 * (log2TrafoSize − 2) + ((log2TrafoSize − 1) >> 2)`,
27-//! `ctxShift = (log2TrafoSize + 1) >> 2`. For chroma (cIdx > 0):
28-//! `ctxOffset = 15`, `ctxShift = log2TrafoSize − 2`. The X and Y
29-//! prefix bins live in separate context banks; this module hands back
30-//! only the bank-relative `ctxInc` and the matching
31-//! [`LastSigCoeffBank`] tag for caller-side routing.
32-//!
33-//! * **`last_sig_coeff_{x,y}_suffix`** (H.265 §7.3.8.11, §7.4.9.11). A
34-//! `nBits = (prefix >> 1) − 1`-bit fixed-length bypass field, present
35-//! only when `prefix > 3`. Together with the prefix the final
36-//! `LastSignificantCoeffX` / `Y` position is derived per equations
37-//! 7-74..7-77.
38-//!
39-//! Both elements live downstream of the §9.3.4.2 binarization layer
40-//! that the slice-data parser (§7.3.8) drives; this module is the
41-//! reusable per-element building block.
42-//!
43-//! Round 27 extends the ctxInc-derivation surface with three more
44-//! syntax elements that are pure-functional given their neighbour /
45-//! sub-block context (no CABAC engine drive needed at this layer —
46-//! callers compose the engine call themselves):
47-//!
48-//! * **`coded_sub_block_flag`** (H.265 §7.3.8.11, §7.4.9.11) — the
49-//! §9.3.4.2.4 derivation of `ctxInc` from the colour-component
50-//! index, the current sub-block scan location `(xS, yS)`, the
51-//! transform-block size, and the previously decoded
52-//! `coded_sub_block_flag[xS+1][yS]` / `coded_sub_block_flag[xS][yS+1]`
53-//! neighbours. Implemented in
54-//! [`coded_sub_block_flag_ctx_inc`] following equations 9-35..9-39.
55-//!
56-//! * **`split_cu_flag` / `cu_skip_flag`** (H.265 §7.3.8.4, §7.4.9.4,
57-//! §7.3.8.5, §7.4.9.5) — the §9.3.4.2.2 Table 9-49 derivation of
58-//! `ctxInc` from the left and above neighbours' `condL` / `condA`
59-//! booleans plus their availability:
60-//! `ctxInc = (condL && availableL) + (condA && availableA)`.
61-//! Implemented as the shared
62-//! [`left_above_ctx_inc`] helper (the body of Table 9-49) plus
63-//! the [`split_cu_flag_cond`] and [`cu_skip_flag_cond`] callbacks
64-//! the caller wires into it. The Table 9-49 row for
65-//! `split_cu_flag` compares each neighbour's `CtDepth[xNb][yNb]`
66-//! to the current `cqtDepth`; the row for `cu_skip_flag` reads
67-//! each neighbour's `cu_skip_flag[xNb][yNb]` directly. Both rows
68-//! produce a `ctxInc` in `{0, 1, 2}`.
69-//!
70-//! Round 28 extends the ctxInc-derivation surface with six more
71-//! syntax elements whose Table 9-48 entry is itself a closed-form
72-//! expression on parameters the caller already has in hand (no
73-//! neighbour table walk, no CABAC engine drive at this layer):
74-//!
75-//! * **`split_transform_flag[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10)
76-//! — Table 9-48 row: `ctxInc = 5 − log2TrafoSize`. Valid
77-//! `log2TrafoSize ∈ {2, 3, 4, 5}` for the residual-quadtree
78-//! transform-block sizes, so `ctxInc ∈ {0, 1, 2, 3}`. Implemented
79-//! in [`split_transform_flag_ctx_inc`].
80-//!
81-//! * **`cbf_luma[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10) — Table
82-//! 9-48 row: `ctxInc = (trafoDepth == 0) ? 1 : 0`. Implemented in
83-//! [`cbf_luma_ctx_inc`].
84-//!
85-//! * **`cbf_cb[ ][ ][ ]` / `cbf_cr[ ][ ][ ]`** (H.265 §7.3.8.10,
86-//! §7.4.9.10) — Table 9-48 row: `ctxInc = trafoDepth`. The two
87-//! syntax elements live in separate context banks (Table 9-22
88-//! shares the bank shape but each chroma component has its own
89-//! `ctxIdxOffset`); this layer hands back the bank-relative
90-//! `ctxInc` only. Implemented in [`cbf_cb_ctx_inc`] and
91-//! [`cbf_cr_ctx_inc`] (each is a wafer over the shared
92-//! [`cbf_chroma_ctx_inc`] helper).
93-//!
94-//! * **`inter_pred_idc[ x0 ][ y0 ]`** (H.265 §7.3.8.6, §7.4.9.6) —
95-//! Table 9-48 row: bin 0 uses
96-//! `ctxInc = (nPbW + nPbH != 12) ? CtDepth[x0][y0] : 4`; bin 1
97-//! uses `ctxInc = 4`. The `nPbW + nPbH == 12` condition picks out
98-//! the prediction-block shapes whose luma area is 16 samples
99-//! (8×4 and 4×8 PUs), which are encoded with the bin-0 escape
100-//! onto the bin-1 context bank. Implemented in
101-//! [`inter_pred_idc_ctx_inc`].
102-//!
103-//! * **`log2_res_scale_abs_plus1[ c ]`** (H.265 §7.3.8.13,
104-//! §7.4.9.13) — Table 9-48 row: `ctxInc = 4*c + binIdx` for
105-//! `binIdx ∈ {0, 1, 2, 3}` and `c ∈ {0, 1}` (Cb / Cr). The four
106-//! bins of the TR(`cMax = 4`) prefix occupy four consecutive
107-//! contexts per chroma component, so the per-component banks are
108-//! `{0, 1, 2, 3}` (Cb) and `{4, 5, 6, 7}` (Cr). Implemented in
109-//! [`log2_res_scale_abs_plus1_ctx_inc`].
110-//!
111-//! * **`res_scale_sign_flag[ c ]`** (H.265 §7.3.8.13, §7.4.9.13) —
112-//! Table 9-48 row: `ctxInc = c` for `c ∈ {0, 1}`. One bit per
113-//! chroma component, each on its own context. Implemented in
114-//! [`res_scale_sign_flag_ctx_inc`].
115-//!
116-//! All round-28 entries are bin-0 (and bin-1 for `inter_pred_idc` /
117-//! `log2_res_scale_abs_plus1`) ctxInc derivations only; the matching
118-//! binarization shapes (FL for the flags, TR(`cMax = 4`) for
119-//! `log2_res_scale_abs_plus1` followed by a bypass tail) are driven
120-//! by the slice-data parser the same way as the round-26 / 27
121-//! elements.
122-//!
123-//! Round 30 extends the surface with the §7.3.4 `sao()` per-CTU
124-//! syntax-element family. Every element has either a single
125-//! context-coded bin-0 followed by zero or more bypass-coded bins
126-//! (Table 9-48) or is fully bypass-coded; no neighbour walk is
127-//! needed at this layer.
128-//!
129-//! * **`sao_merge_left_flag` / `sao_merge_up_flag`** (H.265 §7.3.4,
130-//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`. The FL
131-//! binarization has `cMax = 1` (single bin). The two merge flags
132-//! share the Table 9-5 context bank (Table 9-4). Implemented in
133-//! [`sao_merge_flag_ctx_inc`] + [`SAO_MERGE_FLAG_FL_CMAX`].
134-//!
135-//! * **`sao_type_idx_luma` / `sao_type_idx_chroma`** (H.265 §7.3.4,
136-//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`, bin 1 bypass.
137-//! The TR(`cMax = 2`, `cRiceParam = 0`) binarization caps the
138-//! prefix at two bins, encoding `SaoTypeIdx ∈ {0, 1, 2}`. The two
139-//! variants share the Table 9-6 context bank. Implemented in
140-//! [`sao_type_idx_ctx_inc`] + [`SAO_TYPE_IDX_TR_CMAX`].
141-//!
142-//! * **`sao_offset_abs`** (H.265 §7.3.4, §7.4.9.3) — Table 9-48 row:
143-//! all bins bypass. TR(`cMax = (1 << min(bitDepth, 10) − 5) − 1`,
144-//! `cRiceParam = 0`). Implemented in [`sao_offset_abs_tr_cmax`].
145-//!
146-//! * **`sao_offset_sign`**, **`sao_band_position`**,
147-//! **`sao_eo_class_luma` / `sao_eo_class_chroma`** (H.265 §7.3.4,
148-//! §7.4.9.3) — Table 9-48 row: all bins bypass; FL binarizations
149-//! with `cMax = 1`, `cMax = 31`, `cMax = 3` respectively.
150-//! Implemented as [`SAO_OFFSET_SIGN_FL_CMAX`],
151-//! [`SAO_BAND_POSITION_FL_CMAX`] + [`SAO_BAND_POSITION_FL_NBITS`],
152-//! and [`SAO_EO_CLASS_FL_CMAX`] + [`SAO_EO_CLASS_FL_NBITS`].
153-//!
154-//! Round 31 extends the surface with the two §9.3.4.2.6 /
155-//! §9.3.4.2.7 derivations whose `ctxInc` carries *persistent*
156-//! per-transform-block state across sub-block invocations: the
157-//! greater-than-1 / greater-than-2 absolute-level flags. Both
158-//! elements are FL binarized with `cMax = 1` (one context-coded
159-//! bin) per Table 9-43, but the bin's ctxInc is driven by a small
160-//! sub-block-scoped state machine (`ctxSet`, `greater1Ctx`,
161-//! `lastGreater1Ctx`, `lastGreater1Flag`) that the residual-coding
162-//! loop threads from sub-block to sub-block within the same
163-//! transform block.
164-//!
165-//! * **`coeff_abs_level_greater1_flag[ n ]`** (H.265 §7.3.8.11,
166-//! §7.4.9.11) — §9.3.4.2.6, equations 9-56..9-60. The per-bin
167-//! `ctxInc = (ctxSet * 4) + min(3, greater1Ctx)` for luma; chroma
168-//! adds `+16`. `ctxSet` is initialised at the start of each
169-//! sub-block from the previous sub-block's terminal `greater1Ctx`
170-//! value, and rotates within `{0, 1, 2, 3}` per the spec's
171-//! `lastGreater1Ctx == 0` increment rule. Implemented as a
172-//! pure-functional state machine in [`Greater1State`] (the
173-//! walker the slice-data parser carries across the residual
174-//! sub-blocks of one transform block) plus the per-flag step
175-//! functions [`Greater1State::on_subblock_entry`] +
176-//! [`Greater1State::on_coeff_abs_level_greater1_flag`].
177-//!
178-//! * **`coeff_abs_level_greater2_flag[ lastGreater1ScanPos ]`**
179-//! (H.265 §7.3.8.11, §7.4.9.11) — §9.3.4.2.7, equations
180-//! 9-61..9-62. `ctxInc = ctxSet` (luma) / `ctxInc = ctxSet + 4`
181-//! (chroma). The element is signalled at most once per sub-block
182-//! at the first scan position that took the greater-1 escape
183-//! (`lastGreater1ScanPos`). Implemented in
184-//! [`coeff_abs_level_greater2_flag_ctx_inc`], reading the
185-//! `ctxSet` value the §9.3.4.2.6 walker has already produced for
186-//! that same sub-block.
187-//!
188-//! Round 32 extends the residual-coding surface with the
189-//! §9.3.4.2.5 `sig_coeff_flag` ctxInc derivation: the per-scan-position
190-//! significance bin that the §7.3.8.11 residual-coding loop emits
191-//! before any greater-1 / greater-2 step. The derivation is a
192-//! four-branch dispatch on `(log2TrafoSize, xC + yC,
193-//! transform_skip_context_enabled_flag && (transform_skip_flag ||
194-//! cu_transquant_bypass_flag))`:
195-//!
196-//! * **transform-skip / transquant-bypass fast path** (eq. 9-40):
197-//! `sigCtx = 42` (luma) / `sigCtx = 16` (chroma). One context
198-//! per colour component, position-independent. Implemented in
199-//! [`sig_coeff_flag_sig_ctx_transform_skip`].
200-//!
201-//! * **`log2TrafoSize == 2`** (eq. 9-41) — the 4×4 TB case reads
202-//! `sigCtx` from the 16-entry Table 9-50 lookup at
203-//! `(yC << 2) + xC`. Implemented in
204-//! [`sig_coeff_flag_sig_ctx_log2_2`] +
205-//! [`SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2`].
206-//!
207-//! * **DC position** (eq. 9-42) — `xC + yC == 0` on `log2 > 2` skips
208-//! the eq.-9-43..9-48 neighbour walk; `sigCtx` starts at 0 and
209-//! only the colour / size tail (eq.-9-49..9-53) applies.
210-//! Implemented in [`sig_coeff_flag_sig_ctx_dc`].
211-//!
212-//! * **general case** (eq. 9-43..9-53) — for `log2 > 2`, `xC +
213-//! yC > 0` the `prevCsbf` parity of the right / below sub-block
214-//! neighbours plus the inner sub-block position `(xC & 3, yC & 3)`
215-//! route through one of four `sigCtx` rules (eq. 9-45..9-48), then
216-//! the colour / size / scan-order tail (eq. 9-49..9-53). Implemented
217-//! in [`sig_coeff_flag_sig_ctx_general`], with the eq.-9-43 / 9-44
218-//! edge gates on `xS / yS < (1 << (log2TrafoSize − 2)) − 1`
219-//! applied internally.
220-//!
221-//! Eq. 9-54 / 9-55 carry the per-component `ctxInc` offset
222-//! (`ctxInc = sigCtx` for luma, `ctxInc = 27 + sigCtx` for chroma);
223-//! see [`sig_coeff_flag_ctx_inc_from_sig_ctx`]. Table 9-43 captures
224-//! the `sig_coeff_flag` binarization shape as FL with `cMax = 1` via
225-//! [`SIG_COEFF_FLAG_FL_CMAX`].
226-//!
227-//! Round 33 extends the ctxInc-derivation surface with the
228-//! §9.3.4.2.8 `palette_run_prefix` derivation — the §7.3.8.13
229-//! palette-coding (SCC) syntax element that signals the unary part
230-//! of the run length following a palette index or copy-above
231-//! decision. Inputs are the bin index `binIdx`, the per-pixel
232-//! `copy_above_palette_indices_flag`, and the `palette_idx_idc`
233-//! decoded at the start of the run. The `ctxInc` is:
234-//!
235-//! * **`copy_above_palette_indices_flag == 0` and `binIdx == 0`**
236-//! (eq. 9-63) — a piecewise function of `palette_idx_idc` in
237-//! `{0, 1, 2}`:
238-//! `ctxInc = (palette_idx_idc < 1) ? 0 : ((palette_idx_idc < 3)
239-//! ? 1 : 2)`. Implemented in
240-//! [`palette_run_prefix_ctx_inc_eq_9_63`].
241-//!
242-//! * **otherwise** — `ctxInc = ctxIdxMap[copy_above_palette_indices_flag][binIdx]`
243-//! per Table 9-51, captured verbatim in
244-//! [`PALETTE_RUN_PREFIX_CTX_IDX_MAP`]. The `binIdx >= 5` cells of
245-//! Table 9-51 are bypass-coded per Table 9-48, so the lookup
246-//! covers `binIdx ∈ {0, 1, 2, 3, 4}` and the public entry point
247-//! [`palette_run_prefix_ctx_inc`] dispatches both branches with
248-//! an `Option<u32>` return (`None` ⇒ bypass).
249-//!
250-//! Round 33 also captures the matching Table 9-43 binarization
251-//! shape: `palette_run_prefix` is a TR with
252-//! `cMax = Floor(Log2(PaletteMaxRunMinus1)) + 1` and `cRiceParam = 0`;
253-//! the helper [`palette_run_prefix_tr_cmax`] returns the per-block
254-//! `cMax` from the `PaletteMaxRunMinus1` input.
255-//!
256-//! Round 34 adds the §9.3.3.11 `coeff_abs_level_remaining[ n ]`
257-//! Rice-adaptive binarization + decode primitive (non-persistent
258-//! branch: `persistent_rice_adaptation_enabled_flag == 0`):
259-//!
260-//! * [`coeff_abs_level_remaining_c_rice_param_eq_9_24`] — eq. 9-24
261-//! adapts `cRiceParam` from the previous coefficient in the
262-//! sub-block: `cRiceParam = Min(cLastRiceParam + (cLastAbsLevel >
263-//! (3 << cLastRiceParam) ? 1 : 0), 4)`.
264-//! * [`coeff_abs_level_remaining_c_max_eq_9_26`] — eq. 9-26:
265-//! `cMax = 4 << cRiceParam`.
266-//! * [`coeff_abs_level_remaining_prefix_val_eq_9_27`] — eq. 9-27:
267-//! `prefixVal = Min(cMax, level)` (the value the §9.3.3.2 TR
268-//! prefix is built from).
269-//! * [`coeff_abs_level_remaining_suffix_val_eq_9_28`] — eq. 9-28:
270-//! `suffixVal = level - cMax` (only meaningful when the prefix is
271-//! the all-ones escape).
272-//! * [`decode_coeff_abs_level_remaining`] — full bypass-coded decode
273-//! driver: reads a unary prefix capped at
274-//! `COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN = 4`, and when
275-//! the prefix terminates short, returns
276-//! `prefix << cRiceParam`; otherwise reads an EGk suffix with
277-//! `k = cRiceParam + 1` and returns `cMax + suffixVal`.
278-//!
279-//! The persistent-Rice branch (eq. 9-25; the
280-//! `persistent_rice_adaptation_enabled_flag == 1` path that walks
281-//! the SCC `StatCoeff[sbType]` state via eq. 9-22/9-23) is left for
282-//! a follow-up round; the non-persistent branch is the Main-profile
283-//! path the slice-data parser drives by default.
284-//!
285-//! Round 35 adds the §9.3.4.2 / Table 9-48 entry for
286-//! `coeff_sign_flag[ n ]` — the per-scan-position sign bit that
287-//! pairs with `coeff_abs_level_remaining[ n ]` to form the signed
288-//! transform-coefficient level per §7.4.9.11. The element is fully
289-//! bypass-coded (Table 9-48 marks bin 0 `bypass`, all later columns
290-//! `na`) and FL binarized with `cMax = 1` (Table 9-43), so the
291-//! on-wire string is a single bin per invocation. The §9.3.4.3.6
292-//! alignment process (`ivlCurrRange := 256`) runs prior to the
293-//! bypass tail at slice-data-loop scope; the per-flag entry point
294-//! [`decode_coeff_sign_flag`] consumes one [`CabacEngine::decode_bypass`]
295-//! bin from the post-alignment engine state. The signed level is
296-//! composed via [`signed_level_from_sign_flag`] applying the
297-//! §7.4.9.11 `(1 − 2 * coeff_sign_flag[n])` factor; the FL shape
298-//! is captured as [`COEFF_SIGN_FLAG_FL_CMAX`] +
299-//! [`COEFF_SIGN_FLAG_FL_NBITS`].
300-//!
301-//! Round 36 adds the §9.3.4.2 / Table 9-48 entries for the
302-//! `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` transform-unit
303-//! syntax pair (H.265 §7.3.8.11, §7.4.9.10). Both elements have a
304-//! Table 9-48 row whose context-coded bins are all `ctxInc = 0` — the
305-//! flag occupies a single context (Table 9-34, three ctxIdx slots
306-//! across initType), and the idx occupies a single context (Table
307-//! 9-35, three ctxIdx slots across initType). The flag is FL
308-//! `cMax = 1`; the idx is TR with `cMax =
309-//! chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`. The §7.4.9.10
310-//! derivation pair the flag + idx feed is `CuQpOffsetCb = (flag == 1)
311-//! ? cb_qp_offset_list[idx] : 0` (and symmetric for Cr). The new
312-//! public surface: [`CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX`] (= 1, Table
313-//! 9-43 shape) and [`CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS`] (= 1);
314-//! [`cu_chroma_qp_offset_flag_ctx_inc`] returns the Table 9-48 bin-0
315-//! `ctxInc = 0` for the FL flag; [`cu_chroma_qp_offset_idx_tr_cmax`]
316-//! returns the per-TU `cMax` from the PPS-resolved
317-//! `chroma_qp_offset_list_len_minus1`; [`cu_chroma_qp_offset_idx_ctx_inc`]
318-//! returns the Table 9-48 `ctxInc = 0` (constant across the TR-prefix
319-//! bins 0..=4, since Table 9-48 lists `0` for every context-coded
320-//! binIdx column); and [`decode_cu_chroma_qp_offset`] drives the
321-//! CABAC engine to produce the typed [`CuChromaQpOffset`] (the
322-//! flag plus, when the flag is 1, the idx with the §7.4.9.10
323-//! derivation gates surfaced via [`CuChromaQpOffset::offset_indices`]).
324-//!
325-//! Round 37 adds the §9.3.4.2 / Table 9-48 entry for
326-//! `cu_transquant_bypass_flag` — the per-CU bypass switch that, when
327-//! set, replaces the scaling + transform + in-loop-filter path with a
328-//! verbatim residual passthrough (H.265 §7.3.8.5, §7.4.9.5). Per
329-//! Table 9-43 the flag is FL with `cMax = 1` (a single context-coded
330-//! bin); Table 9-48's row lists `ctxInc = 0` for bin 0 and `na` for
331-//! every later binIdx column. The flag occupies a single context
332-//! (Table 9-8: `initValue = 154` at all three initType slots) which
333-//! sits at the slice-init-allocated bank entry the parser hands to
334-//! the decode primitive. The PPS gate is
335-//! `transquant_bypass_enabled_flag` (§7.4.3.3.1): the flag is read
336-//! from the bitstream only when that PPS field is 1, otherwise
337-//! §7.4.9.5 infers the value to 0 (the normal scaling-and-transform
338-//! path). The new public surface:
339-//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and
340-//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS`] (= 1);
341-//! [`cu_transquant_bypass_flag_ctx_inc`] returns the Table 9-48 bin-0
342-//! `ctxInc = 0`; [`decode_cu_transquant_bypass_flag`] drives one
343-//! [`CabacEngine::decode_decision`] against the caller's context and
344-//! returns the decoded `u8`; [`cu_transquant_bypass_flag_inferred`]
345-//! surfaces the §7.4.9.5 "PPS gate off ⇒ value is 0" inference as a
346-//! pure helper for callers that branch on the PPS without entering
347-//! the engine.
348-//!
349-//! Round 38 adds the §9.3.4.2 / Table 9-48 entry for `rqt_root_cbf` —
350-//! the inter-CU gate that signals whether the `transform_tree( )`
351-//! syntax structure follows the current coding unit (H.265 §7.3.8.5,
352-//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single
353-//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0
354-//! and `na` for every later binIdx column. Table 9-14 supplies a
355-//! single ctxIdx slot with `initValue = 79` at both initType 1 and
356-//! initType 2 (initType 0 is `na` in Table 9-4 — `rqt_root_cbf` is
357-//! only ever read in inter slices, where §7.3.8.5 wires it under
358-//! `CuPredMode != MODE_INTRA && !cu_skip_flag`). When the §7.3.8.5
359-//! guard fails (intra CU, or skip CU) the flag is not present on the
360-//! wire and the §7.4.9.5 inferred value is 1 (the `transform_tree( )`
361-//! syntax structure is taken to be present). The new public surface:
362-//! [`RQT_ROOT_CBF_FL_CMAX`] (= 1, Table 9-43 shape) and
363-//! [`RQT_ROOT_CBF_FL_NBITS`] (= 1); [`rqt_root_cbf_ctx_inc`] returns
364-//! the Table 9-48 bin-0 `ctxInc = 0`; [`decode_rqt_root_cbf`] drives
365-//! one [`CabacEngine::decode_decision`] against the caller's context
366-//! and returns the decoded `u8`; [`rqt_root_cbf_inferred`] surfaces
367-//! the §7.4.9.5 "not present ⇒ value is 1" inference as a pure helper
368-//! for callers that branch on the §7.3.8.5 guard without entering the
369-//! engine.
370-//!
371-//! Round 39 adds the §9.3.4.2 / Table 9-48 entry for `pred_mode_flag` —
372-//! the per-CU bit that selects between MODE_INTER (value 0) and
373-//! MODE_INTRA (value 1) inside a P or B slice (H.265 §7.3.8.5,
374-//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single
375-//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0
376-//! and `na` for every later binIdx column. Table 9-10 supplies two
377-//! ctxIdx slots with `initValue = {149, 134}` for initType 1 and
378-//! initType 2 (initType 0 is `na` in Table 9-4 — the §7.3.8.5
379-//! `slice_type != I` guard skips the read for I slices, where the
380-//! mode is unconditionally intra). When the §7.3.8.5 guard fails the
381-//! flag is not present on the wire and §7.4.9.5 derives `CuPredMode`
382-//! directly: I slice ⇒ MODE_INTRA; P or B slice with
383-//! `cu_skip_flag == 1` ⇒ MODE_SKIP. The new public surface:
384-//! [`PRED_MODE_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and
385-//! [`PRED_MODE_FLAG_FL_NBITS`] (= 1); [`pred_mode_flag_ctx_inc`]
386-//! returns the Table 9-48 bin-0 `ctxInc = 0`;
387-//! [`decode_pred_mode_flag`] drives one
388-//! [`CabacEngine::decode_decision`] against the caller's context and
389-//! returns the decoded `u8`; the [`CuPredMode`] enum captures the
390-//! §7.4.9.5 mapping (`0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`, plus the
391-//! not-present-only MODE_SKIP state); [`cu_pred_mode_from_flag`]
392-//! applies the present-on-wire mapping; and
393-//! [`pred_mode_flag_inferred_cu_pred_mode`] applies the §7.4.9.5
394-//! not-present inference branching on `slice_type` and `cu_skip_flag`.
395-//!
396-//! Round 40 adds the §9.3.4.2 / Table 9-48 entry for
397-//! `prev_intra_luma_pred_flag` — the per-luma-prediction-block bit that
398-//! selects, for an intra CU, whether the luma intra prediction mode is
399-//! taken from the most-probable-mode list (`mpm_idx` follows) or from
400-//! the remaining-mode field (`rem_intra_luma_pred_mode` follows), per
401-//! H.265 §7.3.8.5, §7.4.9.2. Per Table 9-43 the flag is FL with
402-//! `cMax = 1` (a single context-coded bin); Table 9-48's row lists
403-//! `ctxInc = 0` for bin 0 and `na` for every later binIdx column.
404-//! Table 9-12 supplies three ctxIdx slots with
405-//! `initValue = {184, 154, 183}` for initType 0, 1 and 2 — unlike
406-//! `pred_mode_flag`, this element is read in I, P and B slices (intra
407-//! CUs occur in every slice type), so all three initType slots are
408-//! populated. The flag is always present when the §7.3.8.5 intra-PB
409-//! loop reaches it (no inferred-value rule); when it is 1 the §8.4.2
410-//! candidate-mode derivation supplies `IntraPredModeY` and `mpm_idx`
411-//! selects among the candidates, when it is 0
412-//! `rem_intra_luma_pred_mode` carries the mode directly. The new
413-//! public surface: [`PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX`] (= 1, Table
414-//! 9-43 shape) and [`PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS`] (= 1);
415-//! [`prev_intra_luma_pred_flag_ctx_inc`] returns the Table 9-48 bin-0
416-//! `ctxInc = 0`; the [`LumaIntraModeSource`] enum captures the
417-//! §7.4.9.2 selection (`1 ⇒ Mpm`, `0 ⇒ Remaining`);
418-//! [`luma_intra_mode_source_from_flag`] folds a decoded flag into the
419-//! enum; and [`decode_prev_intra_luma_pred_flag`] drives one
420-//! [`CabacEngine::decode_decision`] against the caller's context and
421-//! returns the decoded `u8`.
422-//!
423-//! Round 41 adds the two §7.3.8.5 luma-mode fields the round-40 flag
424-//! gates: `mpm_idx` (Table 9-43 TR with `cMax = 2`, `cRiceParam = 0`)
425-//! and `rem_intra_luma_pred_mode` (Table 9-43 FL with `cMax = 31`),
426-//! per H.265 §7.4.9.2 / §8.4.2. Both are fully bypass-coded (Table 9-48
427-//! marks every bin `bypass`), so neither consumes a context model and
428-//! presence is exactly the [`LumaIntraModeSource`] selection. The new
429-//! public surface: [`MPM_IDX_TR_CMAX`] (= 2) +
430-//! [`MPM_IDX_TR_C_RICE_PARAM`] (= 0) and [`decode_mpm_idx`] (the
431-//! truncated-unary prefix through the bypass decoder, output `0..=2`);
432-//! [`REM_INTRA_LUMA_PRED_MODE_FL_CMAX`] (= 31) +
433-//! [`REM_INTRA_LUMA_PRED_MODE_FL_NBITS`] (= 5) and
434-//! [`decode_rem_intra_luma_pred_mode`] (five FL bypass bins MSB-first,
435-//! output `0..=31`).
436-//!
437-//! Round 42 adds the §7.3.8.5 chroma-mode field that follows the
438-//! round-40/41 luma-mode group: `intra_chroma_pred_mode`, per H.265
439-//! §7.4.9.5 / §9.3.3.8 / §8.4.3. Unlike the Table 9-43 generic shapes,
440-//! this element has its own binarization process (§9.3.3.8 / Table
441-//! 9-46): the single-bin string `0` signals value 4, and a `1` prefix
442-//! followed by a two-bit FL suffix signals values 0..=3. Table 9-48
443-//! marks bin 0 context-coded with `ctxInc = 0` (Table 9-13 supplies
444-//! `initValue = {63, 152, 152}` for initType 0, 1 and 2) and bins 1..2
445-//! `bypass`. The §8.4.3 derivation maps the decoded value plus
446-//! `IntraPredModeY` to `modeIdx` via Table 8-2 (value 4 tracks the luma
447-//! mode; values 0..=3 select from {0, 26, 10, 1} with a collision
448-//! substitute of 34), then — when `ChromaArrayType == 2` — remaps
449-//! `modeIdx` through Table 8-3. The new public surface:
450-//! [`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`] (= 4, the Table 9-46
451-//! single-bin value), [`INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS`] (= 2),
452-//! [`intra_chroma_pred_mode_ctx_inc`] (the Table 9-48 bin-0
453-//! `ctxInc = 0`), [`decode_intra_chroma_pred_mode`] (one
454-//! [`CabacEngine::decode_decision`] then, for the `1` prefix, two
455-//! bypass bins; output `{0, 1, 2, 3, 4}`),
456-//! [`intra_pred_mode_c_mode_idx`] (Table 8-2),
457-//! [`INTRA_PRED_MODE_C_CHROMA_422_MAP`] /
458-//! [`intra_pred_mode_c_chroma_422`] (Table 8-3), and
459-//! [`derive_intra_pred_mode_c`] (the full §8.4.3 output).
460-
461-use crate::cabac::{CabacEngine, CabacError, ContextModel};
462-
463-// ---------------------------------------------------------------------
464-// Truncated-rice helper — §9.3.3.10
465-// ---------------------------------------------------------------------
466-
467-/// §9.3.3.10 — read a truncated-rice prefix with `cMax` and
468-/// `cRiceParam = 0` (the only configuration this module currently
469-/// needs). The prefix is unary up to a maximum of `cMax >> 0` = `cMax`
470-/// bins; a value of `cMax / (1 << 0)` = `cMax` is the "escape" form
471-/// signalling that a suffix follows for callers that pair TR with an
472-/// EGk continuation.
473-///
474-/// `read_bin(bin_idx)` decodes the bin at index `bin_idx` (0-based)
475-/// using the caller's choice of context-coded or bypass-coded path, and
476-/// returns the decoded bin (0 = continue, 1 = terminate / escape).
477-///
478-/// Returns `(prefix_val, is_escape)`. `is_escape` is `true` exactly
479-/// when `prefix_val == cMax`: i.e. all `cMax` bins were 1, signalling
480-/// that a TR + EGk continuation suffix must be read by the caller.
481-pub(crate) fn read_truncated_rice_prefix<F>(
482- c_max: u32,
483- mut read_bin: F,
484-) -> Result<(u32, bool), CabacError>
485-where
486- F: FnMut(u32) -> Result<u8, CabacError>,
487-{
488- // Unary: count leading 1s up to c_max. The decoded bin tally is
489- // simultaneously the prefix value (number of leading 1s) and the
490- // escape signal (all-ones when value == c_max).
491- let mut value: u32 = 0;
492- while value < c_max {
493- let bin = read_bin(value)?;
494- if bin == 0 {
495- return Ok((value, false));
496- }
497- value += 1;
498- }
499- Ok((value, true))
500-}
501-
502-// ---------------------------------------------------------------------
503-// §9.3.3.3 — Exp-Golomb of order k (bypass-coded, MSB-first prefix then
504-// suffix). Per the §9.3.3.3 NOTE the EGk prefix uses 1's and 0's in the
505-// reverse meaning of the §9.2 EG0 prefix: it is a unary run of `1` bins
506-// terminated by a single `0`, followed by `prefix_ones + k` suffix bits.
507-// ---------------------------------------------------------------------
508-
509-/// §9.3.3.3 — decode an EGk-coded value from the bypass stream for
510-/// arbitrary Exp-Golomb order `k`.
511-///
512-/// The reader counts leading `1` bypass bins until a terminating `0`
513-/// (call this count `prefix_ones`); reads `prefix_ones + k` more
514-/// bypass bins as the suffix; and returns
515-/// `((1 << prefix_ones) - 1) << k + suffix`.
516-///
517-/// For `k = 0` the reader collapses to the `cu_qp_delta_abs`-style
518-/// "(1 << lz) - 1 + suffix" form (suffix length == `leading_zeros`,
519-/// `<< 0` factor disappears) — preserved as
520-/// [`decode_eg_k0`] for callers that only need the `k = 0` case.
521-///
522-/// `leading_zeros` is capped at 32 to keep the decoder defensive
523-/// against runaway encodings; the cap is comfortably above any legal
524-/// HEVC bypass-coded suffix value (§7.4.9.11 puts the practical
525-/// ceiling well below `2^31`).
526-pub(crate) fn decode_eg_k(engine: &mut CabacEngine<'_>, k: u32) -> Result<u32, CabacError> {
527- read_eg_k_with(k, || engine.decode_bypass())
528-}
529-
530-/// §9.3.3.3 — decode an EGk-coded value of order `k` from a generic
531-/// bin reader (each call yields the next bypass bin). Factored out of
532-/// [`decode_eg_k`] so the §7.3.8.9 `abs_mvd_minus2` EG1 escape can be
533-/// composed and unit-tested without driving the arithmetic engine's
534-/// range/offset state. The decode follows the equation-9-13 do-while:
535-/// per the §9.3.3.3 NOTE the EGk unary prefix uses 1's and 0's in the
536-/// reverse meaning of the §9.2 EG0 prefix, so the prefix is a run of
537-/// `1` bins terminated by a single `0`. Count those leading `1` bins
538-/// (`prefix_ones`), then read `prefix_ones + k` suffix bins, yielding
539-/// `((1 << prefix_ones) − 1) << k + suffix`.
540-pub(crate) fn read_eg_k_with<F>(k: u32, mut read_bin: F) -> Result<u32, CabacError>
541-where
542- F: FnMut() -> Result<u8, CabacError>,
543-{
544- let mut prefix_ones: u32 = 0;
545- while prefix_ones < 32 {
546- let bin = read_bin()?;
547- if bin == 0 {
548- break;
549- }
550- prefix_ones += 1;
551- }
552- // Guard against accidental >32-bit reads (cap `prefix_ones` at
553- // 32 already bounds this; the saturate keeps the read width inside
554- // a single `u32` if `k` is unusually large).
555- let suffix_bits = (prefix_ones + k).min(32);
556- let mut suffix: u32 = 0;
557- for _ in 0..suffix_bits {
558- suffix = (suffix << 1) | u32::from(read_bin()?);
559- }
560- let base = ((1u64 << prefix_ones) - 1) << k;
561- let value = base + u64::from(suffix);
562- // The defensive cap above keeps `value` inside `u32`; the
563- // saturate keeps us inside the public return type if the
564- // pathological 32-bit edge is ever reached.
565- Ok(u32::try_from(value).unwrap_or(u32::MAX))
566-}
567-
568-/// §9.3.3.11 — decode an EGk-coded value with `k = 0` from the bypass
569-/// stream. Preserved as a named alias for the `cu_qp_delta_abs` /
570-/// `palette_escape_val` callers that historically used the `k = 0`
571-/// fast path; equivalent to `decode_eg_k(engine, 0)`.
572-fn decode_eg_k0(engine: &mut CabacEngine<'_>) -> Result<u32, CabacError> {
573- decode_eg_k(engine, 0)
574-}
575-
576-// ---------------------------------------------------------------------
577-// cu_qp_delta_abs / cu_qp_delta_sign_flag (§7.3.8.14, §7.4.9.14)
578-// ---------------------------------------------------------------------
579-
580-/// §9.3.4.2.2 Table 9-32 — per-bin `ctxInc` for `cu_qp_delta_abs`. Bin
581-/// 0 uses a dedicated context (`ctxInc = 0`); bins 1..=4 share a second
582-/// dedicated context (`ctxInc = 1`). The TR prefix carries at most
583-/// `cMax = 5` bins; the EGk(k=0) suffix is bypass-coded and not
584-/// indexed.
585-#[must_use]
586-pub fn cu_qp_delta_abs_ctx_inc(bin_idx: u32) -> u32 {
587- if bin_idx == 0 {
588- 0
589- } else {
590- 1
591- }
592-}
593-
594-/// `cu_qp_delta_abs` TR prefix `cMax`. §9.3.3.10 (with §9.3.4.2.2
595-/// row).
596-pub const CU_QP_DELTA_ABS_TR_CMAX: u32 = 5;
597-
598-/// Decoded `cu_qp_delta` pair plus the §7.4.9.14 derived
599-/// `CuQpDeltaVal`.
600-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
601-pub struct CuQpDelta {
602- /// `cu_qp_delta_abs` from the wire.
603- pub abs: u32,
604- /// `cu_qp_delta_sign_flag` from the wire; `None` when
605- /// `abs == 0` (the flag is not signalled in that case).
606- pub sign_flag: Option<u8>,
607- /// Derived signed delta:
608- /// `cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`.
609- /// Equals `0` when `abs == 0`.
610- pub value: i32,
611-}
612-
613-/// Decode the `cu_qp_delta` syntax pair (§7.3.8.14 / §7.4.9.14) from
614-/// the CABAC engine, consuming the two context variables for the
615-/// `cu_qp_delta_abs` TR prefix (bin 0 + bins 1..=4) and any required
616-/// bypass bins for the EGk(k=0) suffix and the sign flag.
617-///
618-/// `ctx_bin0` and `ctx_bin_rest` are the caller's
619-/// `(pStateIdx, valMps)` state for the two `cu_qp_delta_abs` contexts;
620-/// they are mutated in place per §9.3.4.3.2.2 state transition.
621-///
622-/// Returns the decoded [`CuQpDelta`] including the §7.4.9.14
623-/// `CuQpDeltaVal` derivation.
624-pub fn decode_cu_qp_delta(
625- engine: &mut CabacEngine<'_>,
626- ctx_bin0: &mut ContextModel,
627- ctx_bin_rest: &mut ContextModel,
628-) -> Result<CuQpDelta, CabacError> {
629- // Decode the §9.3.3.10 TR prefix using two contexts: bin 0 uses
630- // ctx_bin0, all subsequent bins share ctx_bin_rest.
631- let (prefix, is_escape) = read_truncated_rice_prefix(CU_QP_DELTA_ABS_TR_CMAX, |bin_idx| {
632- if cu_qp_delta_abs_ctx_inc(bin_idx) == 0 {
633- engine.decode_decision(ctx_bin0)
634- } else {
635- engine.decode_decision(ctx_bin_rest)
636- }
637- })?;
638-
639- // §9.3.3.10: if the prefix is the all-ones escape (== cMax), an
640- // EGk(k=0) suffix follows; the decoded value is prefix + suffix.
641- let abs = if is_escape {
642- prefix + decode_eg_k0(engine)?
643- } else {
644- prefix
645- };
646-
647- // §7.4.9.14: the sign flag is signalled only when abs != 0.
648- let (sign_flag, signed) = if abs == 0 {
649- (None, 0i32)
650- } else {
651- let s = engine.decode_bypass()?;
652- // CuQpDeltaVal = abs * (1 − 2 * sign_flag)
653- let sign_factor = 1i32 - 2 * (s as i32);
654- (Some(s), abs as i32 * sign_factor)
655- };
656-
657- Ok(CuQpDelta {
658- abs,
659- sign_flag,
660- value: signed,
661- })
662-}
663-
664-// ---------------------------------------------------------------------
665-// cu_chroma_qp_offset_flag / cu_chroma_qp_offset_idx
666-// (§7.3.8.11 transform_unit() / §7.4.9.10 — PPS chroma-QP-offset list
667-// gating). Table 9-43 binarizations + Table 9-48 ctxInc derivations.
668-// ---------------------------------------------------------------------
669-
670-/// Table 9-43 binarization shape for `cu_chroma_qp_offset_flag`: FL
671-/// with `cMax = 1` (a single context-coded bin).
672-pub const CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX: u32 = 1;
673-
674-/// FL-binarization bit count for `cu_chroma_qp_offset_flag`: one
675-/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
676-pub const CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS: u32 = 1;
677-
678-/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_flag`. Bin 0
679-/// is context-coded with `ctxInc = 0`; later bin-index columns are
680-/// `na` (the FL `cMax = 1` shape only emits a single bin).
681-///
682-/// The flag's Table 9-34 ctxIdx layout (`initValue = 154` at every
683-/// initType slot) is consumed at slice-init scope; this layer hands
684-/// back the bank-relative `ctxInc` only.
685-#[must_use]
686-pub fn cu_chroma_qp_offset_flag_ctx_inc() -> u32 {
687- 0
688-}
689-
690-/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_idx`. Every
691-/// context-coded bin column (binIdx 0..=4 of the TR prefix) lists
692-/// `ctxInc = 0`; binIdx 5 is `na` (the §7.4.9.10 idx range tops out
693-/// at `chroma_qp_offset_list_len_minus1 <= 5`, so the spec-mandated
694-/// `cMax <= 5` TR prefix can produce at most five bins).
695-///
696-/// The idx's Table 9-35 ctxIdx layout (`initValue = 154` at every
697-/// initType slot) is consumed at slice-init scope; this layer hands
698-/// back the bank-relative `ctxInc` only.
699-///
700-/// `bin_idx` is the §9.3.4.2 binIdx of the bin being coded; values
701-/// outside `0..=4` are `na` per Table 9-48.
702-#[must_use]
703-pub fn cu_chroma_qp_offset_idx_ctx_inc(bin_idx: u32) -> u32 {
704- debug_assert!(
705- bin_idx <= 4,
706- "cu_chroma_qp_offset_idx Table 9-48 row: binIdx > 4 is na"
707- );
708- 0
709-}
710-
711-/// §9.3.3.10 / Table 9-43 row for `cu_chroma_qp_offset_idx`: TR with
712-/// `cMax = chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`.
713-/// `chroma_qp_offset_list_len_minus1` is the PPS-signalled length of
714-/// `cb_qp_offset_list[ ]` / `cr_qp_offset_list[ ]` minus one
715-/// (§7.4.3.3.1: a `u(3)` field, bounded by `<= 5`).
716-#[must_use]
717-pub fn cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1: u32) -> u32 {
718- chroma_qp_offset_list_len_minus1
719-}
720-
721-/// Decoded `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` pair
722-/// with the §7.4.9.10 chroma-QP-offset-list dereference surfaced as a
723-/// typed accessor.
724-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
725-pub struct CuChromaQpOffset {
726- /// `cu_chroma_qp_offset_flag` from the wire.
727- pub flag: u8,
728- /// `cu_chroma_qp_offset_idx` from the wire; `None` when the flag
729- /// is 0 (the idx is not signalled in that case per §7.3.8.11).
730- /// When the flag is 1 and `chroma_qp_offset_list_len_minus1 == 0`
731- /// the idx is also not signalled (the TR prefix has `cMax = 0`,
732- /// emitting zero bins) and the value is inferred to be 0.
733- pub idx: Option<u32>,
734-}
735-
736-impl CuChromaQpOffset {
737- /// §7.4.9.10 — return the `(cb_qp_offset_list, cr_qp_offset_list)`
738- /// indices to dereference for `CuQpOffsetCb` / `CuQpOffsetCr`.
739- /// `None` is returned when the flag is 0: per §7.4.9.10 the
740- /// offsets are then both 0 (no list dereference).
741- #[must_use]
742- pub fn offset_indices(&self) -> Option<u32> {
743- if self.flag == 0 {
744- None
745- } else {
746- // §7.4.9.10: when present, idx defaults to 0; absent ⇒
747- // also 0 (the cMax = 0 / not-signalled paths share the
748- // same inferred value).
749- Some(self.idx.unwrap_or(0))
750- }
751- }
752-}
753-
754-/// Decode the `cu_chroma_qp_offset` syntax pair (§7.3.8.11 /
755-/// §7.4.9.10) from the CABAC engine, consuming one context for the
756-/// FL `cu_chroma_qp_offset_flag` bin and (when the flag is 1 and
757-/// `chroma_qp_offset_list_len_minus1 > 0`) one context for the TR
758-/// prefix of `cu_chroma_qp_offset_idx`. All bins of both elements
759-/// share `ctxInc = 0` per Table 9-48; the contexts live in separate
760-/// Table 9-4 banks (Table 9-34 for the flag, Table 9-35 for the
761-/// idx).
762-///
763-/// `ctx_flag` and `ctx_idx` are the caller's
764-/// `(pStateIdx, valMps)` state for the two contexts; they are
765-/// mutated in place per §9.3.4.3.2.2 state transition.
766-///
767-/// `chroma_qp_offset_list_len_minus1` is the PPS field that bounds
768-/// the TR prefix; the function panics in debug if it exceeds 5
769-/// (the §7.4.3.3.1 `u(3)` field's upper bound).
770-///
771-/// Returns the decoded [`CuChromaQpOffset`].
772-pub fn decode_cu_chroma_qp_offset(
773- engine: &mut CabacEngine<'_>,
774- ctx_flag: &mut ContextModel,
775- ctx_idx: &mut ContextModel,
776- chroma_qp_offset_list_len_minus1: u32,
777-) -> Result<CuChromaQpOffset, CabacError> {
778- debug_assert!(
779- chroma_qp_offset_list_len_minus1 <= 5,
780- "chroma_qp_offset_list_len_minus1 is a u(3) field bounded by 5 per §7.4.3.3.1"
781- );
782-
783- // §9.3.4.2.1 + Table 9-48 + Table 9-43: bin 0 of the FL flag
784- // uses ctxInc = 0 and the FL cMax = 1 shape emits exactly one
785- // bin.
786- let flag = engine.decode_decision(ctx_flag)?;
787-
788- // §7.3.8.11: the idx is signalled only when the flag is 1 and
789- // the list has more than one entry (else the TR cMax = 0 shape
790- // emits no bins and the idx is inferred to be 0 per §7.4.9.10).
791- let idx = if flag == 1 && chroma_qp_offset_list_len_minus1 > 0 {
792- let c_max = cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1);
793- // §9.3.3.10 TR prefix with cRiceParam = 0; every bin uses
794- // ctx_idx (Table 9-48 ctxInc = 0).
795- let (prefix, _is_escape) =
796- read_truncated_rice_prefix(c_max, |_bin_idx| engine.decode_decision(ctx_idx))?;
797- // The TR escape (all-ones prefix == cMax) terminates the
798- // idx — there is no suffix continuation for this element
799- // (Table 9-43 has no follow-on EGk row).
800- Some(prefix)
801- } else {
802- None
803- };
804-
805- Ok(CuChromaQpOffset { flag, idx })
806-}
807-
808-// ---------------------------------------------------------------------
809-// cu_transquant_bypass_flag (§7.3.8.5 coding_unit() / §7.4.9.5)
810-// PPS gate: transquant_bypass_enabled_flag (§7.4.3.3.1). Table 9-43
811-// FL binarization + Table 9-48 ctxInc + Table 9-8 ctxIdx initValue.
812-// ---------------------------------------------------------------------
813-
814-/// Table 9-43 binarization shape for `cu_transquant_bypass_flag`: FL
815-/// with `cMax = 1` (a single context-coded bin per CU).
816-pub const CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX: u32 = 1;
817-
818-/// FL-binarization bit count for `cu_transquant_bypass_flag`: one
819-/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
820-pub const CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS: u32 = 1;
821-
822-/// §9.3.4.2.1 / Table 9-48 row for `cu_transquant_bypass_flag`. Bin 0
823-/// is context-coded with `ctxInc = 0`; every later binIdx column is
824-/// `na` (the FL `cMax = 1` shape only emits a single bin).
825-///
826-/// The flag's Table 9-8 ctxIdx layout (`initValue = 154` at every
827-/// initType slot — same `pStateIdx`/`valMps` start at all three
828-/// slice-type initialisation rows) is consumed at slice-init scope;
829-/// this layer hands back the bank-relative `ctxInc` only.
830-#[must_use]
831-pub fn cu_transquant_bypass_flag_ctx_inc() -> u32 {
832- 0
833-}
834-
835-/// §7.4.9.5 — inferred value of `cu_transquant_bypass_flag` when the
836-/// PPS gate `transquant_bypass_enabled_flag` is 0 and the element is
837-/// not present on the wire. The spec mandates an inferred value of
838-/// `0` (normal scaling-and-transform path).
839-///
840-/// Exposed as a pure helper so the parser can branch on the PPS
841-/// without entering the CABAC engine: when the PPS gate is off the
842-/// caller skips [`decode_cu_transquant_bypass_flag`] entirely and
843-/// records the inferred `0`.
844-#[must_use]
845-pub fn cu_transquant_bypass_flag_inferred() -> u8 {
846- 0
847-}
848-
849-/// Decode `cu_transquant_bypass_flag` (§7.3.8.5 / §7.4.9.5) from the
850-/// CABAC engine, consuming one context for the FL bin.
851-///
852-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
853-/// Table 9-8 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per
854-/// §9.3.4.3.2.2 state transition.
855-///
856-/// The PPS gate `transquant_bypass_enabled_flag` (§7.4.3.3.1) is
857-/// upstream of this primitive: when the gate is 0 the parser does
858-/// **not** call this function — see [`cu_transquant_bypass_flag_inferred`]
859-/// for the §7.4.9.5 inferred value.
860-///
861-/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.6 / §8.7
862-/// transquant-bypass passthrough for the current CU per §7.4.9.5.
863-pub fn decode_cu_transquant_bypass_flag(
864- engine: &mut CabacEngine<'_>,
865- ctx: &mut ContextModel,
866-) -> Result<u8, CabacError> {
867- // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape
868- // emits exactly one bin; that bin uses ctxInc = 0 (a single Table
869- // 9-8 entry) per the Table 9-48 row.
870- debug_assert_eq!(
871- cu_transquant_bypass_flag_ctx_inc(),
872- 0,
873- "Table 9-48 row for cu_transquant_bypass_flag: bin 0 ctxInc = 0"
874- );
875- engine.decode_decision(ctx)
876-}
877-
878-// ---------------------------------------------------------------------
879-// rqt_root_cbf (§7.3.8.5 coding_unit() / §7.4.9.5)
880-// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-14 ctxIdx
881-// initValue. Present only when the current coding unit is not
882-// IntraPredMode (i.e. CuPredMode == MODE_INTER) and the cu_skip_flag
883-// is 0; absent ⇒ inferred to 1 (the §7.4.9.5 / 2021 spec wording).
884-// ---------------------------------------------------------------------
885-
886-/// Table 9-43 binarization shape for `rqt_root_cbf`: FL with `cMax = 1`
887-/// (a single context-coded bin per inter CU). Marks whether the
888-/// `transform_tree( )` syntax structure is present for the current
889-/// coding unit (§7.4.9.5).
890-pub const RQT_ROOT_CBF_FL_CMAX: u32 = 1;
891-
892-/// FL-binarization bit count for `rqt_root_cbf`: one context-coded bin
893-/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
894-pub const RQT_ROOT_CBF_FL_NBITS: u32 = 1;
895-
896-/// §9.3.4.2.1 / Table 9-48 row for `rqt_root_cbf`. Bin 0 is
897-/// context-coded with `ctxInc = 0`; every later binIdx column is `na`
898-/// (the FL `cMax = 1` shape only emits a single bin).
899-///
900-/// The flag's Table 9-14 ctxIdx layout has only the initType 1 and
901-/// initType 2 slots populated (`initValue = 79` at both); initType 0
902-/// is `na` per Table 9-4, since `rqt_root_cbf` is only ever read in
903-/// inter slices (§7.3.8.5 routes the read under
904-/// `CuPredMode != MODE_INTRA && !cu_skip_flag`). This layer hands back
905-/// the bank-relative `ctxInc` only; the Table 9-14 initValue plus
906-/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init
907-/// scope.
908-#[must_use]
909-pub fn rqt_root_cbf_ctx_inc() -> u32 {
910- 0
911-}
912-
913-/// §7.4.9.5 — inferred value of `rqt_root_cbf` when the element is not
914-/// present on the wire. The 2021 spec wording (V8/v8.0) mandates an
915-/// inferred value of `1` (the `transform_tree( )` syntax structure is
916-/// taken to be present); the V11/2026 revision conditions the
917-/// inference on `!DcOnlyFlag[ x0 ][ y0 ]`, but the V8 baseline this
918-/// rebuild targets is the unconditional 1.
919-///
920-/// Exposed as a pure helper so the parser can branch without entering
921-/// the CABAC engine when the §7.3.8.5 guard (`CuPredMode == MODE_INTRA
922-/// || cu_skip_flag == 1`) selects the not-present path.
923-#[must_use]
924-pub fn rqt_root_cbf_inferred() -> u8 {
925- 1
926-}
927-
928-/// Decode `rqt_root_cbf` (§7.3.8.5 / §7.4.9.5) from the CABAC engine,
929-/// consuming one context for the FL bin.
930-///
931-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
932-/// Table 9-14 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per
933-/// §9.3.4.3.2.2 state transition.
934-///
935-/// The §7.3.8.5 guard (`CuPredMode != MODE_INTRA && !cu_skip_flag`) is
936-/// upstream of this primitive: when the guard fails the parser does
937-/// **not** call this function — see [`rqt_root_cbf_inferred`] for the
938-/// §7.4.9.5 inferred value.
939-///
940-/// Returns the decoded `u8` (0 or 1) — 1 means the `transform_tree( )`
941-/// syntax structure follows the current coding-unit body; 0 means the
942-/// CU has no transform-tree (samples derive from prediction only per
943-/// §7.4.9.5).
944-pub fn decode_rqt_root_cbf(
945- engine: &mut CabacEngine<'_>,
946- ctx: &mut ContextModel,
947-) -> Result<u8, CabacError> {
948- // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape
949- // emits exactly one bin; that bin uses ctxInc = 0 (a single Table
950- // 9-14 entry) per the Table 9-48 row.
951- debug_assert_eq!(
952- rqt_root_cbf_ctx_inc(),
953- 0,
954- "Table 9-48 row for rqt_root_cbf: bin 0 ctxInc = 0"
955- );
956- engine.decode_decision(ctx)
957-}
958-
959-// ---------------------------------------------------------------------
960-// merge_flag (§7.3.8.6 prediction_unit() / §7.4.9.6)
961-// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-15 ctxIdx
962-// initValue. Read in the §7.3.8.6 `else /* MODE_INTER */` branch
963-// (i.e. cu_skip_flag == 0); when present and 1 the inter-prediction
964-// parameters are inferred from a neighbouring inter partition
965-// (merge_idx follows), when 0 the explicit motion fields
966-// (inter_pred_idc / ref_idx / mvp) are coded. Absent ⇒ inferred per
967-// §7.4.9.6 from CuPredMode (MODE_SKIP ⇒ 1, otherwise 0).
968-// ---------------------------------------------------------------------
969-
970-/// Table 9-43 binarization shape for `merge_flag`: FL with `cMax = 1`
971-/// (a single context-coded bin per non-skip inter prediction unit).
972-/// Selects between the merge path (value 1 — inter-prediction
973-/// parameters inferred from a neighbouring inter-predicted partition)
974-/// and the explicit-motion path (value 0) per §7.4.9.6.
975-pub const MERGE_FLAG_FL_CMAX: u32 = 1;
976-
977-/// FL-binarization bit count for `merge_flag`: one context-coded bin
978-/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
979-pub const MERGE_FLAG_FL_NBITS: u32 = 1;
980-
981-/// §9.3.4.2.1 / Table 9-48 row for `merge_flag`. Bin 0 is
982-/// context-coded with `ctxInc = 0`; every later binIdx column is `na`
983-/// (the FL `cMax = 1` shape only emits a single bin).
984-///
985-/// The flag's Table 9-15 ctxIdx layout has only the initType 1 and
986-/// initType 2 slots populated (`initValue = 110` at initType 1,
987-/// `initValue = 154` at initType 2); initType 0 is `na` in Table 9-4
988-/// because `merge_flag` is only ever read in inter (P/B) slices — the
989-/// §7.3.8.6 `prediction_unit( )` read sits under the coding-unit's
990-/// inter path (`CuPredMode != MODE_INTRA && !cu_skip_flag`), which is
991-/// unreachable in an I slice. This layer hands back the bank-relative
992-/// `ctxInc` only; the Table 9-15 initValue plus Table 9-4
993-/// initType-to-ctxIdx mapping is consumed at slice-init scope (see
994-/// `ctx_init::TABLE_9_15_MERGE_FLAG`).
995-#[must_use]
996-pub fn merge_flag_ctx_inc() -> u32 {
997- 0
998-}
999-
1000-/// §7.4.9.6 — inferred value of `merge_flag` when the element is not
1001-/// present on the wire. The §7.3.8.6 guard that suppresses the read is
1002-/// `cu_skip_flag == 1` (the skip path codes only `merge_idx`); the
1003-/// §7.4.9.6 inference is then:
1004-///
1005-/// * If `CuPredMode[ x0 ][ y0 ]` is equal to `MODE_SKIP`,
1006-/// `merge_flag` is inferred to be equal to 1.
1007-/// * Otherwise, `merge_flag` is inferred to be equal to 0.
1008-///
1009-/// `cu_pred_mode` is the §7.4.9.5 prediction mode of the current
1010-/// coding unit. The only not-present path the §7.3.8.6 syntax reaches
1011-/// is the `cu_skip_flag == 1` branch, whose CuPredMode is
1012-/// [`CuPredMode::Skip`] per §7.4.9.5 — so this returns 1 for
1013-/// [`CuPredMode::Skip`] and 0 for the inter/intra modes (which would
1014-/// only arise from a caller bug, since a present `merge_flag` is
1015-/// decoded rather than inferred on those paths).
1016-///
1017-/// Exposed as a pure helper so the parser can branch without entering
1018-/// the CABAC engine when the §7.3.8.6 skip path selects the
1019-/// not-present case.
1020-#[must_use]
1021-pub fn merge_flag_inferred(cu_pred_mode: CuPredMode) -> u8 {
1022- // §7.4.9.6: CuPredMode == MODE_SKIP ⇒ 1, otherwise ⇒ 0.
1023- u8::from(cu_pred_mode == CuPredMode::Skip)
1024-}
1025-
1026-/// Decode `merge_flag` (§7.3.8.6 / §7.4.9.6) from the CABAC engine,
1027-/// consuming one context for the FL bin.
1028-///
1029-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
1030-/// Table 9-15 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per
1031-/// §9.3.4.3.2.2 state transition.
1032-///
1033-/// The §7.3.8.6 guard (the `else /* MODE_INTER */` branch — i.e.
1034-/// `cu_skip_flag == 0`) is upstream of this primitive: when the CU
1035-/// takes the skip path the parser does **not** call this function —
1036-/// see [`merge_flag_inferred`] for the §7.4.9.6 not-present value.
1037-///
1038-/// Returns the decoded `u8` (0 or 1) — 1 selects the merge path (the
1039-/// inter-prediction parameters are inferred from a neighbouring
1040-/// inter-predicted partition, `merge_idx` follows per §7.3.8.6); 0
1041-/// selects the explicit-motion path (`inter_pred_idc` / `ref_idx_lX` /
1042-/// `mvp_lX_flag` / `mvd_coding` are coded).
1043-pub fn decode_merge_flag(
1044- engine: &mut CabacEngine<'_>,
1045- ctx: &mut ContextModel,
1046-) -> Result<u8, CabacError> {
1047- // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape
1048- // emits exactly one bin; that bin uses ctxInc = 0 (a single Table
1049- // 9-15 entry) per the Table 9-48 row.
1050- debug_assert_eq!(
1051- merge_flag_ctx_inc(),
1052- 0,
1053- "Table 9-48 row for merge_flag: bin 0 ctxInc = 0"
1054- );
1055- engine.decode_decision(ctx)
1056-}
1057-
1058-// ---------------------------------------------------------------------
1059-// pred_mode_flag (§7.3.8.5 coding_unit() / §7.4.9.5)
1060-// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-10 ctxIdx
1061-// initValue. Present only when the slice is P or B (slice_type != I)
1062-// and cu_skip_flag == 0; absent ⇒ CuPredMode is derived per §7.4.9.5
1063-// from slice_type and cu_skip_flag without entering the engine.
1064-// ---------------------------------------------------------------------
1065-
1066-/// Table 9-43 binarization shape for `pred_mode_flag`: FL with
1067-/// `cMax = 1` (a single context-coded bin per non-skip P/B coding
1068-/// unit). Selects between MODE_INTER (value 0) and MODE_INTRA (value
1069-/// 1) per §7.4.9.5.
1070-pub const PRED_MODE_FLAG_FL_CMAX: u32 = 1;
1071-
1072-/// FL-binarization bit count for `pred_mode_flag`: one context-coded
1073-/// bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
1074-pub const PRED_MODE_FLAG_FL_NBITS: u32 = 1;
1075-
1076-/// §9.3.4.2.1 / Table 9-48 row for `pred_mode_flag`. Bin 0 is
1077-/// context-coded with `ctxInc = 0`; every later binIdx column is `na`
1078-/// (the FL `cMax = 1` shape only emits a single bin).
1079-///
1080-/// The flag's Table 9-10 ctxIdx layout has only the initType 1 and
1081-/// initType 2 slots populated (`initValue = 149` at initType 1,
1082-/// `initValue = 134` at initType 2); initType 0 is `na` in Table 9-4
1083-/// because the §7.3.8.5 `slice_type != I` guard skips the read for I
1084-/// slices entirely. This layer hands back the bank-relative `ctxInc`
1085-/// only; the Table 9-10 initValue plus Table 9-4 initType-to-ctxIdx
1086-/// mapping is consumed at slice-init scope.
1087-#[must_use]
1088-pub fn pred_mode_flag_ctx_inc() -> u32 {
1089- 0
1090-}
1091-
1092-/// §7.4.9.5 / §9.5.1 — the coding-unit prediction mode. Selected by
1093-/// `pred_mode_flag` (when present on the wire) or inferred from
1094-/// slice-level state (when not present), per §7.4.9.5.
1095-///
1096-/// `pred_mode_flag == 0` maps to [`CuPredMode::Inter`];
1097-/// `pred_mode_flag == 1` maps to [`CuPredMode::Intra`].
1098-/// [`CuPredMode::Skip`] is reachable only via the §7.4.9.5
1099-/// not-present inference path: a P or B slice CU whose `cu_skip_flag`
1100-/// is 1 and whose `pred_mode_flag` was therefore not coded.
1101-///
1102-/// The enum is local to the binarization module because no other
1103-/// module currently expresses CuPredMode in code; the
1104-/// `coding_unit( )` syntax walker may promote it to a wider type in
1105-/// a future round.
1106-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1107-pub enum CuPredMode {
1108- /// MODE_INTER — inter-picture prediction (samples derived from a
1109- /// reference picture). Reachable from `pred_mode_flag == 0` (P
1110- /// or B slice, non-skip CU).
1111- Inter,
1112- /// MODE_INTRA — intra-picture prediction (samples derived from
1113- /// neighbouring reconstructed samples in the current picture).
1114- /// Reachable from `pred_mode_flag == 1` and from the I-slice
1115- /// not-present inference (§7.4.9.5).
1116- Intra,
1117- /// MODE_SKIP — inter-prediction skip path (no residual, no
1118- /// `pred_mode_flag`, no transform tree). Reachable only from
1119- /// §7.4.9.5 not-present inference when `slice_type != I` and
1120- /// `cu_skip_flag == 1`.
1121- Skip,
1122-}
1123-
1124-/// Map a decoded `pred_mode_flag` value to [`CuPredMode`] per
1125-/// §7.4.9.5: `0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`. The mapping is
1126-/// total over the FL `cMax = 1` shape (any other input is rejected
1127-/// in debug builds; release builds fall back to MODE_INTRA to keep
1128-/// the function `must_use`-friendly without panicking on accidental
1129-/// out-of-range inputs).
1130-#[must_use]
1131-pub fn cu_pred_mode_from_flag(pred_mode_flag: u8) -> CuPredMode {
1132- debug_assert!(
1133- pred_mode_flag <= 1,
1134- "pred_mode_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1"
1135- );
1136- if pred_mode_flag == 0 {
1137- CuPredMode::Inter
1138- } else {
1139- CuPredMode::Intra
1140- }
1141-}
1142-
1143-/// §7.4.9.5 — derive [`CuPredMode`] for a coding unit whose
1144-/// `pred_mode_flag` is not present on the wire. The §7.3.8.5 guard
1145-/// that suppresses the read is `slice_type == I` (no flag is coded
1146-/// because the slice is purely intra) or `cu_skip_flag == 1` (the
1147-/// skip path bypasses the flag).
1148-///
1149-/// `slice_type_is_i` is `true` iff the current slice has
1150-/// `slice_type == I` per §7.4.7.1.
1151-/// `cu_skip_flag` is the §7.3.8.5 / §7.4.9.5 decoded skip flag (or
1152-/// the 0-inferred value when `slice_type == I`).
1153-///
1154-/// The §7.4.9.5 derivation:
1155-///
1156-/// * If the slice is I, `CuPredMode` is inferred to MODE_INTRA
1157-/// regardless of `cu_skip_flag` (which is itself not coded for
1158-/// I slices and inferred to 0 per §7.4.9.5).
1159-/// * Otherwise (P or B slice), the only path that reaches this
1160-/// helper is `cu_skip_flag == 1`; the spec then infers
1161-/// `CuPredMode = MODE_SKIP`. A `cu_skip_flag == 0` input would
1162-/// contradict the §7.3.8.5 guard (the flag *would* be present
1163-/// and decoded); the function asserts this in debug builds and
1164-/// falls back to MODE_INTER in release builds to avoid panicking
1165-/// on a caller bug.
1166-#[must_use]
1167-pub fn pred_mode_flag_inferred_cu_pred_mode(slice_type_is_i: bool, cu_skip_flag: u8) -> CuPredMode {
1168- if slice_type_is_i {
1169- // §7.4.9.5: "If slice_type is equal to I, CuPredMode[ x ][ y ]
1170- // is inferred to be equal to MODE_INTRA." cu_skip_flag is not
1171- // coded for I slices (§7.3.8.5 `if( slice_type != I )` guard)
1172- // and is itself inferred to 0; the I-slice branch is therefore
1173- // unconditional on the skip flag.
1174- CuPredMode::Intra
1175- } else {
1176- // §7.4.9.5: "Otherwise (slice_type is equal to P or B), when
1177- // cu_skip_flag[ x0 ][ y0 ] is equal to 1, CuPredMode[ x ][ y ]
1178- // is inferred to be equal to MODE_SKIP." The §7.3.8.5
1179- // pred_mode_flag read is gated on `!cu_skip_flag[ x0 ][ y0 ]`,
1180- // so the only way this branch is reached on a P/B slice is
1181- // with cu_skip_flag == 1.
1182- debug_assert_eq!(
1183- cu_skip_flag, 1,
1184- "§7.4.9.5: pred_mode_flag not-present on a P/B slice requires cu_skip_flag == 1"
1185- );
1186- CuPredMode::Skip
1187- }
1188-}
1189-
1190-/// Decode `pred_mode_flag` (§7.3.8.5 / §7.4.9.5) from the CABAC
1191-/// engine, consuming one context for the FL bin.
1192-///
1193-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
1194-/// Table 9-10 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place
1195-/// per §9.3.4.3.2.2 state transition.
1196-///
1197-/// The §7.3.8.5 guard (`slice_type != I && !cu_skip_flag`) is
1198-/// upstream of this primitive: when the guard fails the parser does
1199-/// **not** call this function — see
1200-/// [`pred_mode_flag_inferred_cu_pred_mode`] for the §7.4.9.5
1201-/// not-present derivation.
1202-///
1203-/// Returns the decoded `u8` (0 or 1) — 0 selects MODE_INTER per
1204-/// §7.4.9.5 (`CuPredMode = MODE_INTER`), 1 selects MODE_INTRA
1205-/// (`CuPredMode = MODE_INTRA`). See [`cu_pred_mode_from_flag`] to
1206-/// fold the result into the [`CuPredMode`] enum.
1207-pub fn decode_pred_mode_flag(
1208- engine: &mut CabacEngine<'_>,
1209- ctx: &mut ContextModel,
1210-) -> Result<u8, CabacError> {
1211- // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape
1212- // emits exactly one bin; that bin uses ctxInc = 0 (a single Table
1213- // 9-10 entry) per the Table 9-48 row.
1214- debug_assert_eq!(
1215- pred_mode_flag_ctx_inc(),
1216- 0,
1217- "Table 9-48 row for pred_mode_flag: bin 0 ctxInc = 0"
1218- );
1219- engine.decode_decision(ctx)
1220-}
1221-
1222-// ---------------------------------------------------------------------
1223-// prev_intra_luma_pred_flag (§7.3.8.5 coding_unit() / §7.4.9.2)
1224-// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-12 ctxIdx
1225-// initValue. Read once per luma prediction block of an intra CU (the
1226-// §7.3.8.5 `for( j ) for( i )` PB loop). When the flag is 1 the luma
1227-// intra mode is taken from the §8.4.2 most-probable-mode list (mpm_idx
1228-// follows); when 0 it comes from rem_intra_luma_pred_mode. There is no
1229-// not-present inference: the §7.3.8.5 loop always reads it.
1230-// ---------------------------------------------------------------------
1231-
1232-/// Table 9-43 binarization shape for `prev_intra_luma_pred_flag`: FL
1233-/// with `cMax = 1` (a single context-coded bin per luma prediction
1234-/// block of an intra CU). Selects between the MPM-list mode source
1235-/// (value 1) and the remaining-mode field (value 0) per §7.4.9.2.
1236-pub const PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX: u32 = 1;
1237-
1238-/// FL-binarization bit count for `prev_intra_luma_pred_flag`: one
1239-/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`.
1240-pub const PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS: u32 = 1;
1241-
1242-/// §9.3.4.2.1 / Table 9-48 row for `prev_intra_luma_pred_flag`. Bin 0
1243-/// is context-coded with `ctxInc = 0`; every later binIdx column is
1244-/// `na` (the FL `cMax = 1` shape only emits a single bin).
1245-///
1246-/// Table 9-12 lists three ctxIdx slots with
1247-/// `initValue = {184, 154, 183}` for initType 0, 1 and 2 — the element
1248-/// is read in I, P and B slices (intra CUs occur in every slice type),
1249-/// so all three initType slots are populated (unlike `pred_mode_flag`,
1250-/// whose initType 0 column is `na`). This layer hands back the
1251-/// bank-relative `ctxInc` only; the Table 9-12 initValue plus the
1252-/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init
1253-/// scope.
1254-#[must_use]
1255-pub fn prev_intra_luma_pred_flag_ctx_inc() -> u32 {
1256- 0
1257-}
1258-
1259-/// §7.4.9.2 — the source of a luma prediction block's intra mode,
1260-/// selected by `prev_intra_luma_pred_flag`.
1261-///
1262-/// `prev_intra_luma_pred_flag == 1` maps to [`LumaIntraModeSource::Mpm`]
1263-/// (the §8.4.2 most-probable-mode candidate list; `mpm_idx` follows in
1264-/// the §7.3.8.5 syntax to select among the candidates).
1265-/// `prev_intra_luma_pred_flag == 0` maps to
1266-/// [`LumaIntraModeSource::Remaining`] (the §7.3.8.5
1267-/// `rem_intra_luma_pred_mode` field carries the mode directly).
1268-#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1269-pub enum LumaIntraModeSource {
1270- /// The luma intra mode is taken from the §8.4.2 most-probable-mode
1271- /// candidate list. Reachable from `prev_intra_luma_pred_flag == 1`;
1272- /// the §7.3.8.5 `mpm_idx` element follows to pick a candidate.
1273- Mpm,
1274- /// The luma intra mode is carried directly by the §7.3.8.5
1275- /// `rem_intra_luma_pred_mode` field. Reachable from
1276- /// `prev_intra_luma_pred_flag == 0`.
1277- Remaining,
1278-}
1279-
1280-/// Map a decoded `prev_intra_luma_pred_flag` value to
1281-/// [`LumaIntraModeSource`] per §7.4.9.2 / §7.3.8.5: `1 ⇒ Mpm`,
1282-/// `0 ⇒ Remaining`. The mapping is total over the FL `cMax = 1` shape
1283-/// (any other input is rejected in debug builds; release builds fall
1284-/// back to [`LumaIntraModeSource::Remaining`] to avoid panicking on an
1285-/// accidental out-of-range input).
1286-#[must_use]
1287-pub fn luma_intra_mode_source_from_flag(prev_intra_luma_pred_flag: u8) -> LumaIntraModeSource {
1288- debug_assert!(
1289- prev_intra_luma_pred_flag <= 1,
1290- "prev_intra_luma_pred_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1"
1291- );
1292- if prev_intra_luma_pred_flag == 1 {
1293- LumaIntraModeSource::Mpm
1294- } else {
1295- LumaIntraModeSource::Remaining
1296- }
1297-}
1298-
1299-/// Decode `prev_intra_luma_pred_flag` (§7.3.8.5 / §7.4.9.2) from the
1300-/// CABAC engine, consuming one context for the FL bin.
1301-///
1302-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
1303-/// Table 9-12 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per
1304-/// the §9.3.4.3.2.2 state transition.
1305-///
1306-/// The §7.3.8.5 intra-PB loop always reaches this read for an intra CU
1307-/// (there is no not-present inference rule for this element), so the
1308-/// parser unconditionally calls this primitive once per luma
1309-/// prediction block.
1310-///
1311-/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.4.2
1312-/// most-probable-mode source (`mpm_idx` follows), 0 selects the
1313-/// `rem_intra_luma_pred_mode` source. See
1314-/// [`luma_intra_mode_source_from_flag`] to fold the result into the
1315-/// [`LumaIntraModeSource`] enum.
1316-pub fn decode_prev_intra_luma_pred_flag(
1317- engine: &mut CabacEngine<'_>,
1318- ctx: &mut ContextModel,
1319-) -> Result<u8, CabacError> {
1320- // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape
1321- // emits exactly one bin; that bin uses ctxInc = 0 (a single Table
1322- // 9-12 entry) per the Table 9-48 row.
1323- debug_assert_eq!(
1324- prev_intra_luma_pred_flag_ctx_inc(),
1325- 0,
1326- "Table 9-48 row for prev_intra_luma_pred_flag: bin 0 ctxInc = 0"
1327- );
1328- engine.decode_decision(ctx)
1329-}
1330-
1331-// ---------------------------------------------------------------------
1332-// mpm_idx / rem_intra_luma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.2)
1333-// Table 9-43 binarization + Table 9-48 (both fully bypass-coded). These
1334-// are the two §7.3.8.5 intra-PB luma-mode fields that follow
1335-// prev_intra_luma_pred_flag: when the flag is 1 the §8.4.2 candidate
1336-// list is selected and `mpm_idx` (TR cMax = 2, cRiceParam = 0) picks
1337-// among the three candidates; when 0 `rem_intra_luma_pred_mode`
1338-// (FL cMax = 31) carries the residual mode directly. Neither element is
1339-// context-coded — Table 9-48 marks every bin `bypass` — so the slice
1340-// parser reads them through the §9.3.4.3.4 bypass arithmetic decoder
1341-// without allocating a context model. Presence is exactly the
1342-// LumaIntraModeSource selection: Mpm ⇒ mpm_idx present, Remaining ⇒
1343-// rem_intra_luma_pred_mode present (the two are mutually exclusive per
1344-// the §7.3.8.5 `if( prev_intra_luma_pred_flag ) … else …` syntax).
1345-// ---------------------------------------------------------------------
1346-
1347-/// Table 9-43 binarization shape for `mpm_idx`: TR with `cMax = 2` and
1348-/// `cRiceParam = 0`. The TR prefix with `cRiceParam = 0` collapses to
1349-/// truncated-unary, so the on-wire string is `0`, `10`, or `11` for the
1350-/// three values 0, 1, 2 — at most two bypass bins (Table 9-48 marks
1351-/// bin 0 and bin 1 `bypass`, binIdx ≥ 2 `na`).
1352-pub const MPM_IDX_TR_CMAX: u32 = 2;
1353-
1354-/// `cRiceParam` for the `mpm_idx` TR binarization (Table 9-43): 0. With
1355-/// `cRiceParam = 0` the §9.3.3.10 TR has no Rice suffix and the prefix
1356-/// is plain truncated-unary.
1357-pub const MPM_IDX_TR_C_RICE_PARAM: u32 = 0;
1358-
1359-/// Table 9-43 binarization shape for `rem_intra_luma_pred_mode`: FL with
1360-/// `cMax = 31`. The §9.3.3.5 derivation gives
1361-/// `fixedLength = Ceil(Log2(cMax + 1)) = Ceil(Log2(32)) = 5`, so the
1362-/// on-wire string is exactly five bypass bins (Table 9-48 marks
1363-/// binIdx 0..=4 `bypass`, binIdx 5 `na`) read MSB-first.
1364-pub const REM_INTRA_LUMA_PRED_MODE_FL_CMAX: u32 = 31;
1365-
1366-/// §9.3.3.5 — bit width of the FL string for `rem_intra_luma_pred_mode`.
1367-///
1368-/// `Ceil(Log2(REM_INTRA_LUMA_PRED_MODE_FL_CMAX + 1)) = Ceil(Log2(32))
1369-/// = 5`. The decoded 5-bit value is the §8.4.2 step-2 starting point
1370-/// (`IntraPredModeY` before the candModeList increment pass).
1371-pub const REM_INTRA_LUMA_PRED_MODE_FL_NBITS: u32 = 5;
1372-
1373-/// Decode `mpm_idx` (§7.3.8.5 / §7.4.9.2) from the CABAC engine.
1374-///
1375-/// Read when `prev_intra_luma_pred_flag == 1`
1376-/// ([`LumaIntraModeSource::Mpm`]): the §8.4.2 derivation sets
1377-/// `IntraPredModeY = candModeList[ mpm_idx ]`, so the returned value is
1378-/// the index into the three-entry most-probable-mode candidate list and
1379-/// is always in `0..=2`.
1380-///
1381-/// Binarization is TR with `cMax = 2`, `cRiceParam = 0` (Table 9-43) and
1382-/// every bin is bypass-coded (Table 9-48), so this reads the
1383-/// truncated-unary prefix straight from the §9.3.4.3.4 bypass decoder:
1384-/// a `0` bin terminates immediately (value 0), otherwise a second bin
1385-/// distinguishes value 1 (`10`) from value 2 (`11`). No context model is
1386-/// consumed.
1387-pub fn decode_mpm_idx(engine: &mut CabacEngine<'_>) -> Result<u8, CabacError> {
1388- // §9.3.3.10 TR prefix with cRiceParam = 0 driven entirely by the
1389- // bypass decoder. `is_escape` (all `cMax` bins were 1) is the
1390- // value == cMax case; with cRiceParam = 0 there is no suffix to
1391- // read, so the prefix value is the final value either way.
1392- let (value, _is_escape) =
1393- read_truncated_rice_prefix(MPM_IDX_TR_CMAX, |_bin_idx| engine.decode_bypass())?;
1394- debug_assert!(
1395- value <= MPM_IDX_TR_CMAX,
1396- "mpm_idx is TR cMax = 2 (Table 9-43); decoded value must be in 0..=2"
1397- );
1398- Ok(value as u8)
1399-}
1400-
1401-/// Decode `rem_intra_luma_pred_mode` (§7.3.8.5 / §7.4.9.2) from the
1402-/// CABAC engine.
1403-///
1404-/// Read when `prev_intra_luma_pred_flag == 0`
1405-/// ([`LumaIntraModeSource::Remaining`]): the §8.4.2 step-2 derivation
1406-/// seeds `IntraPredModeY = rem_intra_luma_pred_mode`, then increments it
1407-/// once for each sorted candModeList entry it meets or exceeds. The
1408-/// returned value is the pre-increment seed and is always in `0..=31`.
1409-///
1410-/// Binarization is FL with `cMax = 31` (Table 9-43) and every bin is
1411-/// bypass-coded (Table 9-48), so this reads exactly five bypass bins
1412-/// MSB-first via [`CabacEngine::decode_bypass_bits`]. No context model
1413-/// is consumed.
1414-pub fn decode_rem_intra_luma_pred_mode(engine: &mut CabacEngine<'_>) -> Result<u8, CabacError> {
1415- let value = engine.decode_bypass_bits(REM_INTRA_LUMA_PRED_MODE_FL_NBITS as u8)?;
1416- debug_assert!(
1417- value <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX,
1418- "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); decoded value must be in 0..=31"
1419- );
1420- Ok(value as u8)
1421-}
1422-
1423-// ---------------------------------------------------------------------
1424-// IntraPredModeY derivation (§8.4.2 — derivation process for luma intra
1425-// prediction mode). This is the process the §7.3.8.5 luma-mode signalling
1426-// group (prev_intra_luma_pred_flag, mpm_idx, rem_intra_luma_pred_mode)
1427-// feeds: given the two §8.4.2-step-2 candidate neighbour modes
1428-// candIntraPredModeA / candIntraPredModeB it builds the three-entry
1429-// candModeList (step 3) and then resolves IntraPredModeY from the
1430-// signalled fields (step 4 — either candModeList[ mpm_idx ] on the Mpm
1431-// path, or rem_intra_luma_pred_mode passed through the sorted-list
1432-// increment pass on the Remaining path).
1433-//
1434-// Table 8-1 names the modes: 0 = INTRA_PLANAR, 1 = INTRA_DC,
1435-// 2..34 = INTRA_ANGULAR2..INTRA_ANGULAR34 (35 modes total). The
1436-// §8.4.2-step-2 candidate reduction (availability via §6.4.1,
1437-// CuPredMode / pcm_flag tests, the CTB-row-boundary B clamp) is the
1438-// slice-data parser's responsibility — it holds the neighbour state and
1439-// the §6.4.1 z-scan availability — and yields the two candidate mode
1440-// values this process consumes, matching the availability-as-input
1441-// convention the §9.3.4.2.2 neighbour ctxInc derivations use.
1442-// ---------------------------------------------------------------------
1443-
1444-/// Table 8-1 — `INTRA_PLANAR`, the mode-0 planar predictor.
1445-pub const INTRA_PLANAR: u8 = 0;
1446-
1447-/// Table 8-1 — `INTRA_DC`, the mode-1 DC predictor. This is also the
1448-/// §8.4.2-step-2 substitute value `candIntraPredModeX` takes when the
1449-/// neighbour is unavailable, inter-coded, PCM, or (for B) lies in the
1450-/// CTB row above the current one.
1451-pub const INTRA_DC: u8 = 1;
1452-
1453-/// Table 8-1 — `INTRA_ANGULAR26`, the mode-26 vertical angular
1454-/// predictor. §8.4.2 step 3 uses it as `candModeList[ 2 ]` in the
1455-/// equal-and-low-candidate (eq. 8-23) and the both-PLANAR-and-DC-present
1456-/// (final step-3 else) fall-throughs.
1457-pub const INTRA_ANGULAR26: u8 = 26;
1458-
1459-/// Table 8-1 — the highest luma intra prediction mode index
1460-/// (`INTRA_ANGULAR34`); modes run `0..=34` inclusive.
1461-pub const INTRA_PRED_MODE_MAX: u8 = 34;
1462-
1463-/// §8.4.2 step 3 — build the three-entry most-probable-mode candidate
1464-/// list `candModeList[ 0..=2 ]` from the two §8.4.2-step-2 candidate
1465-/// neighbour modes `candIntraPredModeA` (left, location `(xPb − 1, yPb)`)
1466-/// and `candIntraPredModeB` (above, location `(xPb, yPb − 1)`).
1467-///
1468-/// Both candidate inputs are already the reduced step-2 values (an
1469-/// available intra neighbour's `IntraPredModeY`, else `INTRA_DC`); this
1470-/// function implements only the step-3 list construction:
1471-///
1472-/// * `candIntraPredModeB == candIntraPredModeA`:
1473-/// * candidate `< 2` (PLANAR or DC) ⇒ `{PLANAR, DC, ANGULAR26}`
1474-/// (eqs. 8-21..8-23).
1475-/// * otherwise (an angular candidate) ⇒ the candidate plus its two
1476-/// neighbouring angular modes (eqs. 8-24..8-26):
1477-/// `{candA, 2 + ((candA + 29) % 32), 2 + ((candA − 2 + 1) % 32)}`.
1478-/// * `candIntraPredModeB != candIntraPredModeA`:
1479-/// * `candModeList[ 0 ] = candA`, `candModeList[ 1 ] = candB`
1480-/// (eqs. 8-27/8-28); `candModeList[ 2 ]` is the first of
1481-/// `{PLANAR, DC, ANGULAR26}` not already present in the first two
1482-/// entries.
1483-///
1484-/// Both candidate inputs must be valid Table 8-1 modes (`0..=34`).
1485-#[must_use]
1486-pub fn intra_luma_cand_mode_list(
1487- cand_intra_pred_mode_a: u8,
1488- cand_intra_pred_mode_b: u8,
1489-) -> [u8; 3] {
1490- debug_assert!(
1491- cand_intra_pred_mode_a <= INTRA_PRED_MODE_MAX,
1492- "candIntraPredModeA is a Table 8-1 mode; must be in 0..=34"
1493- );
1494- debug_assert!(
1495- cand_intra_pred_mode_b <= INTRA_PRED_MODE_MAX,
1496- "candIntraPredModeB is a Table 8-1 mode; must be in 0..=34"
1497- );
1498-
1499- if cand_intra_pred_mode_b == cand_intra_pred_mode_a {
1500- if cand_intra_pred_mode_a < 2 {
1501- // eqs. 8-21..8-23 — equal low candidate.
1502- [INTRA_PLANAR, INTRA_DC, INTRA_ANGULAR26]
1503- } else {
1504- // eqs. 8-24..8-26 — equal angular candidate; the `% 32`
1505- // arithmetic wraps the two neighbouring angular modes back
1506- // into the 2..=33 angular band (the `2 +` re-bases the
1507- // 0..=31 residue onto INTRA_ANGULAR2).
1508- let a = u32::from(cand_intra_pred_mode_a);
1509- let one = 2 + ((a + 29) % 32);
1510- let two = 2 + ((a - 2 + 1) % 32);
1511- [cand_intra_pred_mode_a, one as u8, two as u8]
1512- }
1513- } else {
1514- // eqs. 8-27/8-28 — distinct candidates fill slots 0 and 1; slot
1515- // 2 is the first default mode (PLANAR, then DC, then ANGULAR26)
1516- // not already present.
1517- let zero = cand_intra_pred_mode_a;
1518- let one = cand_intra_pred_mode_b;
1519- let two = if zero != INTRA_PLANAR && one != INTRA_PLANAR {
1520- INTRA_PLANAR
1521- } else if zero != INTRA_DC && one != INTRA_DC {
1522- INTRA_DC
1523- } else {
1524- INTRA_ANGULAR26
1525- };
1526- [zero, one, two]
1527- }
1528-}
1529-
1530-/// §8.4.2 step 4 — derive `IntraPredModeY[ xPb ][ yPb ]` from the step-3
1531-/// `candModeList` and the §7.3.8.5 signalled luma-mode fields.
1532-///
1533-/// `cand_mode_list` is the [`intra_luma_cand_mode_list`] output; `source`
1534-/// is the [`LumaIntraModeSource`] the round-40 `prev_intra_luma_pred_flag`
1535-/// selects.
1536-///
1537-/// * [`LumaIntraModeSource::Mpm`] — `IntraPredModeY = candModeList[
1538-/// mpm_idx ]` (the `mpm_idx` field, `0..=2`, indexes the candidate
1539-/// list directly). `field` carries the decoded `mpm_idx`.
1540-/// * [`LumaIntraModeSource::Remaining`] — the step-4 ordered procedure:
1541-/// the candidate list is sorted ascending (the eqs. 8-29..8-31
1542-/// three-compare-and-swap sort), `IntraPredModeY` is seeded with
1543-/// `rem_intra_luma_pred_mode` (`field`, `0..=31`), then incremented by
1544-/// one for every sorted candidate it meets or exceeds (low-to-high, so
1545-/// the running value is re-compared against each successive candidate).
1546-/// This re-injects the three excluded most-probable modes, mapping the
1547-/// 31-value remaining field onto the 35-mode space.
1548-///
1549-/// The returned value is always a valid Table 8-1 mode (`0..=34`).
1550-#[must_use]
1551-pub fn derive_intra_pred_mode_y(
1552- cand_mode_list: [u8; 3],
1553- source: LumaIntraModeSource,
1554- field: u8,
1555-) -> u8 {
1556- match source {
1557- LumaIntraModeSource::Mpm => {
1558- debug_assert!(
1559- field <= MPM_IDX_TR_CMAX as u8,
1560- "mpm_idx is TR cMax = 2 (Table 9-43); must index the three-entry candModeList"
1561- );
1562- cand_mode_list[field as usize]
1563- }
1564- LumaIntraModeSource::Remaining => {
1565- debug_assert!(
1566- field <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX as u8,
1567- "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); must be in 0..=31"
1568- );
1569- // eqs. 8-29..8-31 — sort the three candidates ascending.
1570- let mut sorted = cand_mode_list;
1571- if sorted[0] > sorted[1] {
1572- sorted.swap(0, 1);
1573- }
1574- if sorted[0] > sorted[2] {
1575- sorted.swap(0, 2);
1576- }
1577- if sorted[1] > sorted[2] {
1578- sorted.swap(1, 2);
1579- }
1580- // step-4 increment pass: seed with rem_intra_luma_pred_mode,
1581- // then bump once per sorted candidate at-or-below the running
1582- // value. The candidates are distinct and ascending, so the
1583- // bump count is monotone and the result is the unsigned
1584- // remaining field shifted up past the three excluded modes.
1585- let mut mode = field;
1586- for &cand in &sorted {
1587- if mode >= cand {
1588- mode += 1;
1589- }
1590- }
1591- mode
1592- }
1593- }
1594-}
1595-
1596-// ---------------------------------------------------------------------
1597-// intra_chroma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.5)
1598-// §9.3.3.8 / Table 9-46 binarization + Table 9-48 + §8.4.3 derivation.
1599-// The chroma-mode field that follows the luma-mode group in §7.3.8.5:
1600-// present once per CU when ChromaArrayType != 0 and != 3, and once per
1601-// luma prediction block (the same i/j loop as the luma fields) when
1602-// ChromaArrayType == 3; absent entirely when ChromaArrayType == 0
1603-// (monochrome — §8.4.3 is only invoked when ChromaArrayType != 0).
1604-// ---------------------------------------------------------------------
1605-
1606-/// Table 9-46 — the `intra_chroma_pred_mode` value signalled by the
1607-/// single-bin string `0`: 4. Per Table 8-2 row 4 the §8.4.3 `modeIdx`
1608-/// for this value is `IntraPredModeY` itself (the chroma prediction
1609-/// mode tracks the luma mode; for `ChromaArrayType == 2` the tracked
1610-/// mode is then remapped through Table 8-3).
1611-pub const INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA: u8 = 4;
1612-
1613-/// §9.3.3.8 / Table 9-46 — bit width of the FL suffix that follows the
1614-/// `1` prefix bin: 2. The suffix carries values 0..=3 MSB-first
1615-/// (`100`⇒0, `101`⇒1, `110`⇒2, `111`⇒3); both suffix bins are
1616-/// bypass-coded per Table 9-48.
1617-pub const INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS: u32 = 2;
1618-
1619-/// §9.3.4.2.1 / Table 9-48 row for `intra_chroma_pred_mode`. Bin 0 is
1620-/// context-coded with `ctxInc = 0`; bins 1 and 2 are `bypass` and bins
1621-/// beyond binIdx 2 are `na` (the Table 9-46 strings are at most three
1622-/// bins long).
1623-///
1624-/// Table 9-13 lists three ctxIdx slots with
1625-/// `initValue = {63, 152, 152}` for initType 0, 1 and 2 — the element
1626-/// is read in I, P and B slices (intra CUs occur in every slice type),
1627-/// so all three initType slots are populated. This layer hands back
1628-/// the bank-relative `ctxInc` only; the Table 9-13 initValue plus the
1629-/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init
1630-/// scope.
1631-///
1632-/// Returns the ctxInc when called with `bin_idx == 0`; any other value
1633-/// is bypass (1, 2) or `na` per Table 9-48 and the function returns 0
1634-/// defensively (callers should not invoke this for the bypass bins).
1635-#[must_use]
1636-pub fn intra_chroma_pred_mode_ctx_inc(bin_idx: u32) -> u32 {
1637- debug_assert!(
1638- bin_idx == 0,
1639- "intra_chroma_pred_mode Table 9-48 row: only bin 0 is context-coded; bins 1..2 are bypass"
1640- );
1641- 0
1642-}
1643-
1644-/// Decode `intra_chroma_pred_mode` (§7.3.8.5 / §7.4.9.5) from the
1645-/// CABAC engine.
1646-///
1647-/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single
1648-/// Table 9-13 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per
1649-/// the §9.3.4.3.2.2 state transition.
1650-///
1651-/// Binarization is the §9.3.3.8 / Table 9-46 process: one
1652-/// context-coded prefix bin, then — only when that bin is 1 — a
1653-/// two-bit bypass FL suffix. A `0` prefix decodes to value 4
1654-/// ([`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`]; no suffix bins are read);
1655-/// a `1` prefix is followed by the MSB-first two-bit suffix carrying
1656-/// values 0..=3. The returned value is therefore always in
1657-/// `{0, 1, 2, 3, 4}` — feed it to [`intra_pred_mode_c_mode_idx`] /
1658-/// [`derive_intra_pred_mode_c`] for the §8.4.3 `IntraPredModeC`
1659-/// derivation.
1660-pub fn decode_intra_chroma_pred_mode(
1661- engine: &mut CabacEngine<'_>,
1662- ctx: &mut ContextModel,
1663-) -> Result<u8, CabacError> {
1664- // §9.3.4.2.1 + Table 9-48: bin 0 is context-coded with ctxInc = 0.
1665- debug_assert_eq!(
1666- intra_chroma_pred_mode_ctx_inc(0),
1667- 0,
1668- "Table 9-48 row for intra_chroma_pred_mode: bin 0 ctxInc = 0"
1669- );
1670- let prefix = engine.decode_decision(ctx)?;
1671- if prefix == 0 {
1672- // Table 9-46: the single-bin string `0` is value 4.
1673- return Ok(INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA);
1674- }
1675- // Table 9-46: `1` prefix + two-bit FL bypass suffix ⇒ values 0..=3.
1676- let suffix = engine.decode_bypass_bits(INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS as u8)?;
1677- debug_assert!(
1678- suffix <= 3,
1679- "intra_chroma_pred_mode suffix is two FL bins (Table 9-46); value must be in 0..=3"
1680- );
1681- Ok(suffix as u8)
1682-}
1683-
1684-/// §8.4.3 Table 8-2 — derive `modeIdx` from `intra_chroma_pred_mode`
1685-/// and `IntraPredModeY`.
1686-///
1687-/// Row 4 (`intra_chroma_pred_mode == 4`) yields `IntraPredModeY`
1688-/// itself. Rows 0..=3 select the base mode from `{0, 26, 10, 1}`
1689-/// (planar, vertical, horizontal, DC angular indices in
1690-/// `intra_chroma_pred_mode` order); when the selected base mode equals
1691-/// `IntraPredModeY` the table substitutes 34 instead (each Table 8-2
1692-/// column places 34 exactly where the row's base mode would collide
1693-/// with the luma mode).
1694-///
1695-/// `intra_pred_mode_y` must be a valid §8.4.2 mode (0..=34) and
1696-/// `intra_chroma_pred_mode` a decoded Table 9-46 value
1697-/// (`{0, 1, 2, 3, 4}`); out-of-range inputs are rejected in debug
1698-/// builds (release builds fall back to the luma-tracking row to avoid
1699-/// panicking on an accidental out-of-range input).
1700-#[must_use]
1701-pub fn intra_pred_mode_c_mode_idx(intra_chroma_pred_mode: u8, intra_pred_mode_y: u8) -> u8 {
1702- debug_assert!(
1703- intra_chroma_pred_mode <= 4,
1704- "intra_chroma_pred_mode is a Table 9-46 value; must be in 0..=4"
1705- );
1706- debug_assert!(
1707- intra_pred_mode_y <= 34,
1708- "IntraPredModeY is a §8.4.2 mode index; must be in 0..=34"
1709- );
1710- // Table 8-2 rows 0..=3 base modes, in intra_chroma_pred_mode order.
1711- const BASE_MODES: [u8; 4] = [0, 26, 10, 1];
1712- match BASE_MODES.get(intra_chroma_pred_mode as usize) {
1713- Some(&base) if base == intra_pred_mode_y => 34,
1714- Some(&base) => base,
1715- // Row 4 (and the release-build out-of-range fallback): modeIdx
1716- // tracks the luma mode.
1717- None => intra_pred_mode_y,
1718- }
1719-}
1720-
1721-/// §8.4.3 Table 8-3 — `IntraPredModeC` as a function of `modeIdx` when
1722-/// `ChromaArrayType == 2`. Indexed by `modeIdx` 0..=34; entries 0..=2
1723-/// pass through unchanged (the Table 8-3 `X <= 2` column).
1724-pub const INTRA_PRED_MODE_C_CHROMA_422_MAP: [u8; 35] = [
1725- 0, 1, 2, // X <= 2 passes through
1726- 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, // modeIdx 3..=14
1727- 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, // modeIdx 15..=25
1728- 26, 27, 27, 28, 28, 29, 29, 30, 31, // modeIdx 26..=34
1729-];
1730-
1731-/// §8.4.3 Table 8-3 — remap `modeIdx` to `IntraPredModeC` for
1732-/// `ChromaArrayType == 2` streams. `mode_idx` must be in 0..=34;
1733-/// out-of-range inputs are rejected in debug builds (release builds
1734-/// pass the value through unchanged to avoid panicking).
1735-#[must_use]
1736-pub fn intra_pred_mode_c_chroma_422(mode_idx: u8) -> u8 {
1737- debug_assert!(
1738- mode_idx <= 34,
1739- "modeIdx is a §8.4.3 Table 8-2 output; must be in 0..=34"
1740- );
1741- INTRA_PRED_MODE_C_CHROMA_422_MAP
1742- .get(mode_idx as usize)
1743- .copied()
1744- .unwrap_or(mode_idx)
1745-}
1746-
1747-/// §8.4.3 — the full `IntraPredModeC` derivation: Table 8-2 `modeIdx`
1748-/// from the decoded `intra_chroma_pred_mode` and the §8.4.2
1749-/// `IntraPredModeY`, then — when `ChromaArrayType == 2` — the Table
1750-/// 8-3 remap; otherwise `IntraPredModeC` is `modeIdx` itself.
1751-///
1752-/// §8.4.3 is only invoked when `ChromaArrayType != 0`; the §7.3.8.5
1753-/// syntax never emits `intra_chroma_pred_mode` for a monochrome
1754-/// stream, so a caller holding a decoded value is already past that
1755-/// gate.
1756-#[must_use]
1757-pub fn derive_intra_pred_mode_c(
1758- intra_chroma_pred_mode: u8,
1759- intra_pred_mode_y: u8,
1760- chroma_array_type_is_2: bool,
1761-) -> u8 {
1762- let mode_idx = intra_pred_mode_c_mode_idx(intra_chroma_pred_mode, intra_pred_mode_y);
1763- if chroma_array_type_is_2 {
1764- intra_pred_mode_c_chroma_422(mode_idx)
1765- } else {
1766- mode_idx
1767- }
1768-}
1769-
1770-// ---------------------------------------------------------------------
1771-// last_sig_coeff_{x,y}_{prefix,suffix} (§7.3.8.11, §7.4.9.11)
1772-// ---------------------------------------------------------------------
1773-
1774-/// Which `last_sig_coeff_*_prefix` bank the caller's context-model
1775-/// slice corresponds to. The X and Y prefixes live in separate banks
1776-/// of contexts; we tag the request so the caller can pick the right
1777-/// slice.
1778-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1779-pub enum LastSigCoeffBank {
1780- /// `last_sig_coeff_x_prefix` bank.
1781- X,
1782- /// `last_sig_coeff_y_prefix` bank.
1783- Y,
1784-}
1785-
1786-/// §9.3.4.2.3 — `(ctxOffset, ctxShift)` for the
1787-/// `last_sig_coeff_{x,y}_prefix` ctxInc derivation. `log2_trafo_size`
1788-/// is the transform-block log2 dimension (2..=5; 2 = 4×4, 5 = 32×32);
1789-/// `is_chroma` selects the chroma bank when `cIdx > 0`.
1790-///
1791-/// Spec equations (§9.3.4.2.3 Table 9-26 / 9-27):
1792-///
1793-/// ```text
1794-/// // luma (cIdx == 0):
1795-/// ctxOffset = 3 * (log2TrafoSize - 2) + ((log2TrafoSize - 1) >> 2)
1796-/// ctxShift = (log2TrafoSize + 1) >> 2
1797-///
1798-/// // chroma (cIdx > 0):
1799-/// ctxOffset = 15
1800-/// ctxShift = log2TrafoSize - 2
1801-/// ```
1802-#[must_use]
1803-pub fn last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size: u32, is_chroma: bool) -> (u32, u32) {
1804- if is_chroma {
1805- // §9.3.4.2.3 — chroma TBs always sit at ctxOffset = 15,
1806- // ctxShift = log2TrafoSize − 2.
1807- (15, log2_trafo_size - 2)
1808- } else {
1809- // §9.3.4.2.3 — luma: piecewise linear in log2TrafoSize.
1810- let offset = 3 * (log2_trafo_size - 2) + ((log2_trafo_size - 1) >> 2);
1811- let shift = (log2_trafo_size + 1) >> 2;
1812- (offset, shift)
1813- }
1814-}
1815-
1816-/// §9.3.4.2.3 — bank-relative `ctxInc` for a single
1817-/// `last_sig_coeff_*_prefix` bin:
1818-///
1819-/// ```text
1820-/// ctxInc = (binIdx >> ctxShift) + ctxOffset
1821-/// ```
1822-#[must_use]
1823-pub fn last_sig_coeff_prefix_ctx_inc(bin_idx: u32, ctx_offset: u32, ctx_shift: u32) -> u32 {
1824- (bin_idx >> ctx_shift) + ctx_offset
1825-}
1826-
1827-/// §9.3.3.10 — `cMax` for `last_sig_coeff_{x,y}_prefix`:
1828-/// `(log2TrafoSize << 1) − 1`. For a 4×4 TB (log2=2) the prefix is at
1829-/// most 3 bins; for a 32×32 TB (log2=5) at most 9 bins.
1830-#[must_use]
1831-pub fn last_sig_coeff_prefix_cmax(log2_trafo_size: u32) -> u32 {
1832- (log2_trafo_size << 1) - 1
1833-}
1834-
1835-/// §7.4.9.11 equations 7-74..7-77 — derive the final
1836-/// `LastSignificantCoeffX/Y` position from a decoded
1837-/// `(prefix, optional suffix)` pair. When `prefix <= 3` no suffix is
1838-/// signalled and the position equals the prefix. When `prefix > 3` the
1839-/// suffix is `nBits = (prefix >> 1) − 1` bits, and the position is
1840-///
1841-/// ```text
1842-/// pos = ( ( 2 + ( prefix & 1 ) ) << ( (prefix >> 1) - 1 ) ) + suffix
1843-/// ```
1844-///
1845-/// `suffix` is the unsigned suffix value (caller already decoded the
1846-/// `nBits` bypass bins, MSB-first); pass `None` when `prefix <= 3`.
1847-#[must_use]
1848-pub fn last_sig_coeff_position(prefix: u32, suffix: Option<u32>) -> u32 {
1849- if prefix <= 3 {
1850- // §7.4.9.11: no suffix, the prefix is the final value.
1851- prefix
1852- } else {
1853- let n_bits = (prefix >> 1) - 1;
1854- let base = (2 + (prefix & 1)) << n_bits;
1855- base + suffix.unwrap_or(0)
1856- }
1857-}
1858-
1859-/// Suffix bit count for `last_sig_coeff_{x,y}_suffix`: `nBits =
1860-/// (prefix >> 1) − 1` when `prefix > 3`, otherwise 0 (no suffix
1861-/// signalled).
1862-#[must_use]
1863-pub fn last_sig_coeff_suffix_n_bits(prefix: u32) -> u32 {
1864- if prefix > 3 {
1865- (prefix >> 1) - 1
1866- } else {
1867- 0
1868- }
1869-}
1870-
1871-/// Decoded `last_sig_coeff_*` element (one of X or Y; same shape for
1872-/// both banks).
1873-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1874-pub struct LastSigCoeff {
1875- /// `last_sig_coeff_*_prefix` from the wire.
1876- pub prefix: u32,
1877- /// `last_sig_coeff_*_suffix` from the wire (`None` when
1878- /// `prefix <= 3`, the no-suffix-signalled case).
1879- pub suffix: Option<u32>,
1880- /// §7.4.9.11 derived `LastSignificantCoeff{X,Y}` position. Range
1881- /// 0..=(1 << log2TrafoSize) - 1.
1882- pub position: u32,
1883-}
1884-
1885-/// Decode one `last_sig_coeff_*_{prefix,suffix}` pair from the CABAC
1886-/// engine. `ctx_bank` is the caller-supplied slice of context variables
1887-/// for the active bank ([`LastSigCoeffBank`]); the bin at index
1888-/// `binIdx` consumes the context at index
1889-/// `ctx_inc = (binIdx >> ctxShift) + ctxOffset` within that slice (the
1890-/// caller is responsible for sizing the slice so the highest used
1891-/// `ctx_inc` index is in-bounds).
1892-///
1893-/// Returns the decoded prefix, optional suffix, and the §7.4.9.11
1894-/// derived position. The arguments
1895-/// `log2_trafo_size` and `is_chroma` drive both the TR-prefix `cMax`
1896-/// and the §9.3.4.2.3 `(ctxOffset, ctxShift)` derivation.
1897-///
1898-/// The §7.4.9.11 swap for `scanIdx == 2` (the diagonal scan reflection
1899-/// of `LastSignificantCoeff{X,Y}`) is **not** applied here; the caller
1900-/// receives the on-wire X / Y positions and applies the swap at the
1901-/// residual-coding level where `scanIdx` is known.
1902-pub fn decode_last_sig_coeff(
1903- engine: &mut CabacEngine<'_>,
1904- log2_trafo_size: u32,
1905- is_chroma: bool,
1906- ctx_bank: &mut [ContextModel],
1907-) -> Result<LastSigCoeff, CabacError> {
1908- let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size);
1909- let (ctx_offset, ctx_shift) =
1910- last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma);
1911-
1912- let (prefix, _is_escape) = read_truncated_rice_prefix(c_max, |bin_idx| {
1913- let ctx_inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift) as usize;
1914- engine.decode_decision(&mut ctx_bank[ctx_inc])
1915- })?;
1916-
1917- let n_bits = last_sig_coeff_suffix_n_bits(prefix);
1918- let suffix = if n_bits > 0 {
1919- Some(engine.decode_bypass_bits(n_bits as u8)?)
1920- } else {
1921- None
1922- };
1923- let position = last_sig_coeff_position(prefix, suffix);
1924- Ok(LastSigCoeff {
1925- prefix,
1926- suffix,
1927- position,
1928- })
1929-}
1930-
1931-// ---------------------------------------------------------------------
1932-// coded_sub_block_flag ctxInc — §9.3.4.2.4
1933-// ---------------------------------------------------------------------
1934-
1935-/// §9.3.4.2.4 — derive the `ctxInc` for one bin of
1936-/// `coded_sub_block_flag` from the colour-component index, the
1937-/// current sub-block scan location `(xS, yS)`, the transform-block
1938-/// size `log2TrafoSize`, and the two previously decoded neighbour
1939-/// bins in sub-block scan order.
1940-///
1941-/// Spec equations:
1942-///
1943-/// ```text
1944-/// // §9.3.4.2.4, equations 9-35..9-39
1945-/// csbfCtx = 0
1946-/// if xS < (1 << (log2TrafoSize - 2)) - 1:
1947-/// csbfCtx += coded_sub_block_flag[xS + 1][yS]
1948-/// if yS < (1 << (log2TrafoSize - 2)) - 1:
1949-/// csbfCtx += coded_sub_block_flag[xS][yS + 1]
1950-/// if cIdx == 0:
1951-/// ctxInc = min(csbfCtx, 1)
1952-/// else:
1953-/// ctxInc = 2 + min(csbfCtx, 1)
1954-/// ```
1955-///
1956-/// `right_neighbour` is the previously decoded
1957-/// `coded_sub_block_flag[xS + 1][yS]` (0/1); pass `0` whenever the
1958-/// current sub-block sits on the right edge of the TB
1959-/// (`xS == (1 << (log2TrafoSize - 2)) - 1`), where equation 9-36 does
1960-/// not apply. `below_neighbour` is the previously decoded
1961-/// `coded_sub_block_flag[xS][yS + 1]` (0/1); pass `0` whenever the
1962-/// current sub-block sits on the bottom edge of the TB
1963-/// (`yS == (1 << (log2TrafoSize - 2)) - 1`).
1964-///
1965-/// Returns `ctxInc` in `{0, 1}` for luma (`cIdx == 0`) or
1966-/// `{2, 3}` for chroma (`cIdx > 0`).
1967-///
1968-/// # Panics
1969-/// Does not panic; both neighbour inputs are clamped via the boolean
1970-/// `>= 1` comparison.
1971-#[must_use]
1972-pub fn coded_sub_block_flag_ctx_inc(
1973- is_chroma: bool,
1974- right_neighbour: u8,
1975- below_neighbour: u8,
1976-) -> u32 {
1977- // §9.3.4.2.4: csbfCtx is the unsigned sum of the two neighbour
1978- // bins (each either 0 or 1), so it lies in {0, 1, 2}. The final
1979- // ctxInc clamps to {0, 1} via min(csbfCtx, 1).
1980- let csbf_ctx = (right_neighbour & 1) as u32 + (below_neighbour & 1) as u32;
1981- let clipped = csbf_ctx.min(1);
1982- if is_chroma {
1983- // §9.3.4.2.4 equation 9-39: chroma uses the {2, 3} bank.
1984- 2 + clipped
1985- } else {
1986- // §9.3.4.2.4 equation 9-38: luma uses the {0, 1} bank.
1987- clipped
1988- }
1989-}
1990-
1991-/// §9.3.4.2.4 — helper that takes the full sub-block location and
1992-/// transform-block size and applies the edge-gating from equations
1993-/// 9-36 / 9-37 before delegating to [`coded_sub_block_flag_ctx_inc`].
1994-/// The caller passes the previously decoded
1995-/// `coded_sub_block_flag[xS + 1][yS]` and
1996-/// `coded_sub_block_flag[xS][yS + 1]` values regardless of the edge
1997-/// condition; this function zeroes them when the corresponding
1998-/// equation 9-36 / 9-37 does not apply (sub-block on the right /
1999-/// bottom TB edge).
2000-///
vendor/oxideav-h265/src/bitreader.rsdeleted+0 -300
@@ -1,300 +0,0 @@
1-//! MSB-first bit reader for H.265 syntax-element parsing.
2-//!
3-//! H.265 syntax elements are read most-significant-bit-first from the
4-//! RBSP byte stream (see ITU-T Rec. H.265 §7.2 — the `read_bits(n)`
5-//! function described there returns the next `n` bits as an unsigned
6-//! integer with the MSB written first). This module provides the
7-//! minimum surface needed for §7.3.2.1 (VPS) and §7.3.3
8-//! (profile_tier_level):
9-//!
10-//! * [`BitReader::u`] — fixed-width unsigned integer (the `u(n)`
11-//! descriptor of §7.2).
12-//! * [`BitReader::ue`] — 0-th-order unsigned Exp-Golomb (the `ue(v)`
13-//! descriptor, parsed per §9.2).
14-//!
15-//! The reader takes an already-unescaped RBSP buffer (see
16-//! [`crate::nal::strip_emulation_prevention`]) and does not attempt to
17-//! locate the RBSP stop bit — that is left to the calling parser.
18-
19-/// Errors that can arise while consuming bits from an RBSP buffer.
20-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21-pub enum BitReaderError {
22- /// A read requested more bits than remained in the buffer.
23- EndOfBuffer,
24- /// More than 32 bits requested in a single `u()` read.
25- TooManyBits,
26- /// A 0-th-order Exp-Golomb code's leading-zero run exceeded 32
27- /// (the §9.2 contract caps `codeNum` at `2^32 - 2`). A run of 33
28- /// zeros would overflow the 32-bit return type.
29- ExpGolombOverflow,
30-}
31-
32-impl core::fmt::Display for BitReaderError {
33- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
34- match self {
35- Self::EndOfBuffer => f.write_str("read past end of RBSP buffer"),
36- Self::TooManyBits => f.write_str("u(n) called with n > 32"),
37- Self::ExpGolombOverflow => f.write_str("ue(v) leading-zero run exceeded 32"),
38- }
39- }
40-}
41-
42-impl std::error::Error for BitReaderError {}
43-
44-/// MSB-first bit reader.
45-#[derive(Debug, Clone)]
46-pub struct BitReader<'a> {
47- buf: &'a [u8],
48- /// Bit cursor measured from the start of `buf` (0 == MSB of
49- /// `buf[0]`).
50- bit_pos: usize,
51-}
52-
53-impl<'a> BitReader<'a> {
54- /// Construct a bit reader over `buf`.
55- pub fn new(buf: &'a [u8]) -> Self {
56- Self { buf, bit_pos: 0 }
57- }
58-
59- /// Number of bits still available.
60- pub fn bits_left(&self) -> usize {
61- self.buf
62- .len()
63- .saturating_mul(8)
64- .saturating_sub(self.bit_pos)
65- }
66-
67- /// Read a single bit (the `u(1)` descriptor).
68- pub fn u1(&mut self) -> Result<u8, BitReaderError> {
69- if self.bit_pos >= self.buf.len() * 8 {
70- return Err(BitReaderError::EndOfBuffer);
71- }
72- let byte = self.buf[self.bit_pos / 8];
73- let bit = 7 - (self.bit_pos % 8);
74- self.bit_pos += 1;
75- Ok((byte >> bit) & 0x01)
76- }
77-
78- /// Read `n` bits MSB-first as an unsigned integer (the `u(n)`
79- /// descriptor, with `n` in `0..=32`). `n == 0` returns 0 and does
80- /// not advance the cursor.
81- pub fn u(&mut self, n: u8) -> Result<u32, BitReaderError> {
82- if n > 32 {
83- return Err(BitReaderError::TooManyBits);
84- }
85- if n == 0 {
86- return Ok(0);
87- }
88- if self.bits_left() < n as usize {
89- return Err(BitReaderError::EndOfBuffer);
90- }
91- let mut value: u32 = 0;
92- for _ in 0..n {
93- value = (value << 1) | (self.u1()? as u32);
94- }
95- Ok(value)
96- }
97-
98- /// Skip `n` bits without interpreting them. Useful when a syntax
99- /// element appears in the bitstream but is not needed by the
100- /// caller (e.g. the 32 profile_compatibility flags after the
101- /// caller has already recorded the few of interest).
102- pub fn skip(&mut self, n: usize) -> Result<(), BitReaderError> {
103- if self.bits_left() < n {
104- return Err(BitReaderError::EndOfBuffer);
105- }
106- self.bit_pos += n;
107- Ok(())
108- }
109-
110- /// Read a 0-th-order unsigned Exp-Golomb code (the `ue(v)`
111- /// descriptor). Per ITU-T Rec. H.265 §9.2: count `leadingZeroBits`
112- /// 0 bits until the first 1 bit is seen; then read another
113- /// `leadingZeroBits` bits and compute
114- /// `codeNum = 2^leadingZeroBits + read_bits(leadingZeroBits) - 1`.
115- pub fn ue(&mut self) -> Result<u32, BitReaderError> {
116- let mut leading_zero_bits: u32 = 0;
117- loop {
118- if leading_zero_bits > 32 {
119- return Err(BitReaderError::ExpGolombOverflow);
120- }
121- let b = self.u1()?;
122- if b == 1 {
123- break;
124- }
125- leading_zero_bits += 1;
126- }
127- if leading_zero_bits == 0 {
128- return Ok(0);
129- }
130- if leading_zero_bits == 32 {
131- // 2^32 would overflow u32; the suffix must therefore be 0
132- // to keep `codeNum` representable. Treat any other input
133- // as an overflow.
134- let suffix = self.u(32)?;
135- return suffix
136- .checked_sub(1)
137- .and_then(|v| (1u64 << 32).checked_add(v as u64))
138- .and_then(|big| u32::try_from(big).ok())
139- .ok_or(BitReaderError::ExpGolombOverflow);
140- }
141- let suffix = self.u(leading_zero_bits as u8)?;
142- Ok((1u32 << leading_zero_bits) - 1 + suffix)
143- }
144-
145- /// Read a 0-th-order signed Exp-Golomb code (the `se(v)`
146- /// descriptor). Per ITU-T Rec. H.265 §9.2.2: read a `ue(v)`
147- /// `codeNum`, then map it to a signed value per Table 9-3 as
148- /// `(-1)^(codeNum + 1) * Ceil(codeNum / 2)` — `codeNum` 0 → 0,
149- /// 1 → +1, 2 → -1, 3 → +2, 4 → -2, …
150- pub fn se(&mut self) -> Result<i32, BitReaderError> {
151- let code_num = self.ue()?;
152- // Ceil(codeNum / 2) without overflow: (codeNum + 1) / 2.
153- let magnitude = ((code_num as i64) + 1) / 2;
154- let value = if code_num % 2 == 0 {
155- // Even codeNum (0, 2, 4, …) maps to a non-positive value
156- // (0, -1, -2, …).
157- -magnitude
158- } else {
159- // Odd codeNum (1, 3, 5, …) maps to a positive value.
160- magnitude
161- };
162- // `value` is bounded by ±2^31 because `ue()` caps `codeNum`
163- // at `2^32 - 2`, whose mapped magnitude is `2^31 - 1`.
164- i32::try_from(value).map_err(|_| BitReaderError::ExpGolombOverflow)
165- }
166-
167- /// Current bit position from the start of the buffer.
168- pub fn bit_pos(&self) -> usize {
169- self.bit_pos
170- }
171-}
172-
173-#[cfg(test)]
174-mod tests {
175- use super::*;
176-
177- #[test]
178- fn reads_individual_bits_msb_first() {
179- // 0b1010_0110, 0b1100_0011 → bits: 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 1
180- let buf = [0xA6, 0xC3];
181- let mut br = BitReader::new(&buf);
182- let want = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1];
183- for &w in &want {
184- assert_eq!(br.u1().unwrap(), w);
185- }
186- assert!(br.u1().is_err());
187- }
188-
189- #[test]
190- fn reads_u_n_across_byte_boundary() {
191- // Two bytes: 0xAB, 0xCD → 0b1010_1011_1100_1101
192- let buf = [0xAB, 0xCD];
193- let mut br = BitReader::new(&buf);
194- // Take 12 bits: 0b1010_1011_1100 = 0xABC
195- assert_eq!(br.u(12).unwrap(), 0xABC);
196- // Remaining 4 bits: 0xD
197- assert_eq!(br.u(4).unwrap(), 0xD);
198- }
199-
200- #[test]
201- fn u_zero_returns_zero_and_does_not_consume() {
202- let buf = [0xFF];
203- let mut br = BitReader::new(&buf);
204- assert_eq!(br.u(0).unwrap(), 0);
205- assert_eq!(br.bit_pos(), 0);
206- }
207-
208- #[test]
209- fn u_thirty_two_full_word() {
210- let buf = [0x12, 0x34, 0x56, 0x78];
211- let mut br = BitReader::new(&buf);
212- assert_eq!(br.u(32).unwrap(), 0x1234_5678);
213- }
214-
215- #[test]
216- fn ue_table_b9_2() {
217- // Per H.265 §9.2 Table 9-2 first few codewords:
218- // codeNum=0 → '1' (1 bit)
219- // codeNum=1 → '010' (3 bits)
220- // codeNum=2 → '011' (3 bits)
221- // codeNum=3 → '00100' (5 bits)
222- // codeNum=4 → '00101' (5 bits)
223- // codeNum=5 → '00110' (5 bits)
224- // codeNum=6 → '00111' (5 bits)
225- // Pack codewords 0..=6 into a byte stream MSB-first:
226- // Bits: 1 010 011 00100 00101 00110 00111 = 27 bits, padded
227- // with 5 zero bits to land on a 32-bit byte boundary.
228- // Group as bytes (MSB first):
229- // bit 0..7 : 1 0 1 0 0 1 1 0 = 0xA6
230- // bit 8..15 : 0 1 0 0 0 0 1 0 = 0x42
231- // bit 16..23: 1 0 0 1 1 0 0 0 = 0x98
232- // bit 24..31: 1 1 1 0 0 0 0 0 = 0xE0 (last 5 bits are pad)
233- let buf = [0xA6, 0x42, 0x98, 0xE0];
234- let mut br = BitReader::new(&buf);
235- let got: Vec<u32> = (0..7).map(|_| br.ue().unwrap()).collect();
236- assert_eq!(got, vec![0, 1, 2, 3, 4, 5, 6]);
237- }
238-
239- #[test]
240- fn ue_zero_is_single_one_bit() {
241- let buf = [0b1000_0000];
242- let mut br = BitReader::new(&buf);
243- assert_eq!(br.ue().unwrap(), 0);
244- assert_eq!(br.bit_pos(), 1);
245- }
246-
247- #[test]
248- fn end_of_buffer_errors() {
249- let buf = [0xFF];
250- let mut br = BitReader::new(&buf);
251- assert_eq!(br.u(8).unwrap(), 0xFF);
252- assert_eq!(br.u(1), Err(BitReaderError::EndOfBuffer));
253- }
254-
255- #[test]
256- fn too_many_bits_errors() {
257- let buf = [0xFF; 8];
258- let mut br = BitReader::new(&buf);
259- assert_eq!(br.u(33), Err(BitReaderError::TooManyBits));
260- }
261-
262- #[test]
263- fn skip_advances_cursor() {
264- let buf = [0xFF, 0xAA];
265- let mut br = BitReader::new(&buf);
266- br.skip(8).unwrap();
267- assert_eq!(br.u(8).unwrap(), 0xAA);
268- }
269-
270- #[test]
271- fn se_table_9_3() {
272- // Per H.265 §9.2.2 Table 9-3, codeNum → se(v) value:
273- // 0 → 0, 1 → +1, 2 → -1, 3 → +2, 4 → -2, 5 → +3, 6 → -3.
274- // codeNum is itself ue(v); reuse the codewords 0..=6 packing
275- // from `ue_table_b9_2` (bits 1 010 011 00100 00101 00110 00111).
276- let buf = [0xA6, 0x42, 0x98, 0xE0];
277- let mut br = BitReader::new(&buf);
278- let got: Vec<i32> = (0..7).map(|_| br.se().unwrap()).collect();
279- assert_eq!(got, vec![0, 1, -1, 2, -2, 3, -3]);
280- }
281-
282- #[test]
283- fn se_zero_is_single_one_bit() {
284- // codeNum 0 ('1') maps to value 0 and consumes one bit.
285- let buf = [0b1000_0000];
286- let mut br = BitReader::new(&buf);
287- assert_eq!(br.se().unwrap(), 0);
288- assert_eq!(br.bit_pos(), 1);
289- }
290-
291- #[test]
292- fn ue_overflow_run_too_long() {
293- // 33 leading zero bits with no terminating 1 in the buffer.
294- // The reader should surface ExpGolombOverflow before running
295- // off the end (we never reach the suffix read).
296- let buf = [0u8; 8]; // 64 zero bits
297- let mut br = BitReader::new(&buf);
298- assert_eq!(br.ue(), Err(BitReaderError::ExpGolombOverflow));
299- }
300-}
vendor/oxideav-h265/src/cabac.rsdeleted+0 -820
@@ -1,820 +0,0 @@
1-//! §9.3 CABAC arithmetic decoding engine.
2-//!
3-//! This module is a clean-room transcription of the ITU-T Rec. H.265 |
4-//! ISO/IEC 23008-2 §9.3 context-adaptive binary arithmetic coding
5-//! *decode* engine — the lowest layer of HEVC entropy decoding, the
6-//! gateway through which all slice-data syntax elements (§7.3.8) are
7-//! read. It deliberately stops at the engine boundary: it exposes the
8-//! four arithmetic-decode primitives plus the context-variable model,
9-//! but does not implement the §9.3.4.2 binarization / context-index
10-//! derivation for any specific syntax element (those sit one layer up,
11-//! in the slice-data parser).
12-//!
13-//! The pieces transcribed here are:
14-//!
15-//! * §9.3.2.6 — [`CabacEngine::new`] / [`CabacEngine::init_engine`]:
16-//! `ivlCurrRange = 510`, `ivlOffset = read_bits(9)`.
17-//! * §9.3.2.2 — [`ContextModel::init`] (equations 9-4, 9-5, 9-6) plus
18-//! the §9.3.2.2 `initType` derivation (equation 9-7,
19-//! [`init_type`]). A context variable is a `(pStateIdx, valMps)`
20-//! pair derived from an 8-bit `initValue` and the slice QP.
21-//! * §9.3.4.3.2 — [`CabacEngine::decode_decision`] (DecodeDecision):
22-//! the regular context-coded bin, with the Table 9-52 `rangeTabLps`
23-//! interval split, the §9.3.4.3.2.2 state transition (Table 9-53),
24-//! and the §9.3.4.3.3 renormalization.
25-//! * §9.3.4.3.4 — [`CabacEngine::decode_bypass`] (DecodeBypass): the
26-//! equal-probability bin.
27-//! * §9.3.4.3.5 — [`CabacEngine::decode_terminate`] (DecodeTerminate):
28-//! the `end_of_slice_segment_flag` / `end_of_subset_one_bit` /
29-//! `pcm_flag` decision before termination.
30-//! * §9.3.4.3.6 — [`CabacEngine::align`] (the alignment process prior
31-//! to aligned bypass decoding for `coeff_abs_level_remaining[ ]` /
32-//! `coeff_sign_flag[ ]`): `ivlCurrRange = 256`.
33-//!
34-//! The Table 9-52 / Table 9-53 values are transcribed directly from the
35-//! H.265 specification text (`docs/video/h265/`). They are arithmetic
36-//! constants of the format, not external-library code.
37-//!
38-//! # Bit source
39-//!
40-//! The engine reads raw bits via [`BitReader`] (`read_bits(1)` in the
41-//! spec is [`BitReader::u1`], `read_bits(9)` is `BitReader::u(9)`). The
42-//! caller positions the reader at the first byte of `slice_segment_data()`
43-//! — for example via
44-//! [`crate::slice::SliceSegmentHeader::byte_offset_to_slice_data`] — and
45-//! then constructs the engine, which immediately consumes the 9-bit
46-//! initial `ivlOffset` per §9.3.2.6.
47-
48-use crate::bitreader::{BitReader, BitReaderError};
49-
50-/// Errors that can arise while running the CABAC decode engine.
51-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52-pub enum CabacError {
53- /// The bit reader ran out of bits (a `read_bits()` past the end of
54- /// the slice-segment-data buffer). A conforming bitstream never
55- /// reaches this state during a valid decode, so it indicates a
56- /// truncated or malformed stream.
57- EndOfBuffer,
58- /// §9.3.2.6 forbids `ivlOffset` taking the value 510 or 511 after
59- /// the initial 9-bit read ("The bitstream shall not contain data
60- /// that result in a value of ivlOffset being equal to 510 or
61- /// 511.").
62- InvalidInitOffset(u16),
63-}
64-
65-impl core::fmt::Display for CabacError {
66- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
67- match self {
68- Self::EndOfBuffer => f.write_str("CABAC engine read past end of slice-data buffer"),
69- Self::InvalidInitOffset(v) => {
70- write!(f, "CABAC init ivlOffset {v} is forbidden (must be < 510)")
71- }
72- }
73- }
74-}
75-
76-impl std::error::Error for CabacError {}
77-
78-impl From<BitReaderError> for CabacError {
79- fn from(_: BitReaderError) -> Self {
80- // The only `BitReaderError` the engine can provoke is running
81- // out of bits — every other `BitReader` failure mode (too many
82- // bits, Exp-Golomb overflow) is unreachable from `u1()` /
83- // `u(9)`.
84- Self::EndOfBuffer
85- }
86-}
87-
88-/// The §9.3.2.2 `initType` selector (equation 9-7). `slice_type` is the
89-/// §7.4.7.1 enum (0 = B, 1 = P, 2 = I); `cabac_init_flag` is the
90-/// slice-header flag (only present for P / B slices).
91-///
92-/// ```text
93-/// if( slice_type == I ) initType = 0
94-/// else if( slice_type == P ) initType = cabac_init_flag ? 2 : 1
95-/// else /* B */ initType = cabac_init_flag ? 1 : 2
96-/// ```
97-///
98-/// `slice_type` here uses [`crate::slice::SliceType`]'s numeric values:
99-/// `SliceType::B == 0`, `SliceType::P == 1`, `SliceType::I == 2`.
100-#[must_use]
101-pub fn init_type(slice_type: u8, cabac_init_flag: bool) -> u8 {
102- match slice_type {
103- // I slice.
104- 2 => 0,
105- // P slice.
106- 1 => {
107- if cabac_init_flag {
108- 2
109- } else {
110- 1
111- }
112- }
113- // B slice (any other slice_type value funnels here).
114- _ => {
115- if cabac_init_flag {
116- 1
117- } else {
118- 2
119- }
120- }
121- }
122-}
123-
124-/// A single CABAC context variable: the §9.3.4.3 probability-state
125-/// index `pStateIdx` (0..=63) paired with the most-probable-symbol
126-/// value `valMps` (0 or 1).
127-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128-pub struct ContextModel {
129- /// §9.3.4.3 probability state index, 0..=63. State 0 is the
130- /// `pLPS == 0.5` extreme; higher indices have lower LPS
131- /// probability.
132- pub p_state_idx: u8,
133- /// The value of the most probable symbol (0 or 1).
134- pub val_mps: u8,
135-}
136-
137-impl ContextModel {
138- /// §9.3.2.2 context-variable initialization (equations 9-4, 9-5,
139- /// 9-6). `init_value` is the 8-bit `initValue` table entry for the
140- /// context; `slice_qp_y` is `SliceQpY` (equation 7-54).
141- ///
142- /// ```text
143- /// slopeIdx = initValue >> 4
144- /// offsetIdx = initValue & 15 (9-4)
145- /// m = slopeIdx * 5 − 45
146- /// n = ( offsetIdx << 3 ) − 16 (9-5)
147- /// preCtxState = Clip3( 1, 126,
148- /// ( ( m * Clip3( 0, 51, SliceQpY ) ) >> 4 ) + n )
149- /// valMps = ( preCtxState <= 63 ) ? 0 : 1
150- /// pStateIdx = valMps ? ( preCtxState − 64 ) : ( 63 − preCtxState ) (9-6)
151- /// ```
152- ///
153- /// The `>> 4` in equation 9-6 is an arithmetic shift of a signed
154- /// product (`m` can be negative); this is reproduced with signed
155- /// arithmetic.
156- #[must_use]
157- pub fn init(init_value: u8, slice_qp_y: i32) -> Self {
158- // Equation 9-4.
159- let slope_idx = (init_value >> 4) as i32;
160- let offset_idx = (init_value & 15) as i32;
161- // Equation 9-5.
162- let m = slope_idx * 5 - 45;
163- let n = (offset_idx << 3) - 16;
164- // Equation 9-6: Clip3(0, 51, SliceQpY) then the signed
165- // arithmetic-shift product, then Clip3(1, 126, …).
166- let qp = slice_qp_y.clamp(0, 51);
167- let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126);
168- let (val_mps, p_state_idx) = if pre_ctx_state <= 63 {
169- (0u8, (63 - pre_ctx_state) as u8)
170- } else {
171- (1u8, (pre_ctx_state - 64) as u8)
172- };
173- Self {
174- p_state_idx,
175- val_mps,
176- }
177- }
178-
179- /// The non-adapting state described in §9.3.2.2 NOTE 2 for
180- /// `ctxTable == 0`, `ctxIdx == 0` (the `end_of_slice_segment_flag`
181- /// / `end_of_subset_one_bit` / `pcm_flag` decision when emulated
182- /// through DecodeDecision): `pStateIdx = 63`, `valMps = 0`.
183- /// `decode_terminate` does not need this state — it is provided for
184- /// completeness of the model.
185- #[must_use]
186- pub fn terminate_state() -> Self {
187- Self {
188- p_state_idx: 63,
189- val_mps: 0,
190- }
191- }
192-}
193-
194-/// Table 9-52 — `rangeTabLps[ pStateIdx ][ qRangeIdx ]`. 64 states ×
195-/// 4 quantized-range columns. Transcribed from the H.265 specification
196-/// text (§9.3.4.3.2.1).
197-#[rustfmt::skip]
198-pub(crate) const RANGE_TAB_LPS: [[u8; 4]; 64] = [
199- [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
200- [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
201- [ 95, 116, 137, 158], [ 90, 110, 130, 150], [ 85, 104, 123, 142], [ 81, 99, 117, 135],
202- [ 77, 94, 111, 128], [ 73, 89, 105, 122], [ 69, 85, 100, 116], [ 66, 80, 95, 110],
203- [ 62, 76, 90, 104], [ 59, 72, 86, 99], [ 56, 69, 81, 94], [ 53, 65, 77, 89],
204- [ 51, 62, 73, 85], [ 48, 59, 69, 80], [ 46, 56, 66, 76], [ 43, 53, 63, 72],
205- [ 41, 50, 59, 69], [ 39, 48, 56, 65], [ 37, 45, 54, 62], [ 35, 43, 51, 59],
206- [ 33, 41, 48, 56], [ 32, 39, 46, 53], [ 30, 37, 43, 50], [ 29, 35, 41, 48],
207- [ 27, 33, 39, 45], [ 26, 31, 37, 43], [ 24, 30, 35, 41], [ 23, 28, 33, 39],
208- [ 22, 27, 32, 37], [ 21, 26, 30, 35], [ 20, 24, 29, 33], [ 19, 23, 27, 31],
209- [ 18, 22, 26, 30], [ 17, 21, 25, 28], [ 16, 20, 23, 27], [ 15, 19, 22, 25],
210- [ 14, 18, 21, 24], [ 14, 17, 20, 23], [ 13, 16, 19, 22], [ 12, 15, 18, 21],
211- [ 12, 14, 17, 20], [ 11, 14, 16, 19], [ 11, 13, 15, 18], [ 10, 12, 15, 17],
212- [ 10, 12, 14, 16], [ 9, 11, 13, 15], [ 9, 11, 12, 14], [ 8, 10, 12, 14],
213- [ 8, 9, 11, 13], [ 7, 9, 11, 12], [ 7, 9, 10, 12], [ 7, 8, 10, 11],
214- [ 6, 8, 9, 11], [ 6, 7, 9, 10], [ 6, 7, 8, 9], [ 2, 2, 2, 2],
215-];
216-
217-/// Table 9-53 — `transIdxLps[ pStateIdx ]`, the probability-state
218-/// transition after decoding the LPS (`1 − valMps`). Transcribed from
219-/// the H.265 specification text (§9.3.4.3.2.2).
220-#[rustfmt::skip]
221-pub(crate) const TRANS_IDX_LPS: [u8; 64] = [
222- 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
223- 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
224- 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
225- 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
226-];
227-
228-/// Table 9-53 — `transIdxMps[ pStateIdx ]`, the probability-state
229-/// transition after decoding the MPS (`valMps`). Transcribed from the
230-/// H.265 specification text (§9.3.4.3.2.2).
231-#[rustfmt::skip]
232-pub(crate) const TRANS_IDX_MPS: [u8; 64] = [
233- 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
234- 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
235- 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
236- 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
237-];
238-
239-/// The §9.3.4.3 arithmetic decoding engine state plus its bit source.
240-///
241-/// The engine holds the two §9.3.2.6 registers `ivlCurrRange` and
242-/// `ivlOffset` and the [`BitReader`] from which renormalization /
243-/// bypass pull `read_bits(1)`. Context variables ([`ContextModel`])
244-/// live in the caller's context-model array; each
245-/// [`decode_decision`](CabacEngine::decode_decision) call takes and
246-/// mutates one in place.
247-#[derive(Debug)]
248-pub struct CabacEngine<'a> {
249- reader: BitReader<'a>,
250- /// §9.3.2.6 `ivlCurrRange` (held in a 16-bit-wide register; values
251- /// stay within 9 bits during decode).
252- ivl_curr_range: u16,
253- /// §9.3.2.6 `ivlOffset` (10-bit register precision is required for
254- /// bypass).
255- ivl_offset: u16,
256-}
257-
258-impl<'a> CabacEngine<'a> {
259- /// §9.3.2.6 — construct and initialize the arithmetic decoding
260- /// engine over `reader`, which the caller has positioned at the
261- /// first bit of `slice_segment_data()`. Sets `ivlCurrRange = 510`
262- /// and `ivlOffset = read_bits(9)`, and validates the §9.3.2.6
263- /// constraint that `ivlOffset` is not 510 or 511.
264- pub fn new(mut reader: BitReader<'a>) -> Result<Self, CabacError> {
265- let ivl_offset = reader.u(9)? as u16;
266- if ivl_offset >= 510 {
267- return Err(CabacError::InvalidInitOffset(ivl_offset));
268- }
269- Ok(Self {
270- reader,
271- ivl_curr_range: 510,
272- ivl_offset,
273- })
274- }
275-
276- /// §9.3.2.6 — re-initialize the engine registers on an already
277- /// constructed engine (e.g. after `pcm_flag == 1` data is consumed,
278- /// per §9.3.2.5 / §9.3.2.6). The bit reader is *not* repositioned;
279- /// the caller is responsible for having advanced it to the byte
280- /// boundary following the PCM samples before calling this.
281- pub fn init_engine(&mut self) -> Result<(), CabacError> {
282- let ivl_offset = self.reader.u(9)? as u16;
283- if ivl_offset >= 510 {
284- return Err(CabacError::InvalidInitOffset(ivl_offset));
285- }
286- self.ivl_curr_range = 510;
287- self.ivl_offset = ivl_offset;
288- Ok(())
289- }
290-
291- /// Current `ivlCurrRange` register value (for tests / inspection).
292- #[must_use]
293- pub fn ivl_curr_range(&self) -> u16 {
294- self.ivl_curr_range
295- }
296-
297- /// §9.3.4.3.6 — alignment process prior to aligned bypass
298- /// decoding: `ivlCurrRange` is set equal to 256. Invoked when
299- /// `cabac_bypass_alignment_enabled_flag == 1` before the bypass
300- /// decoding of `coeff_sign_flag[ ]` / `coeff_abs_level_remaining[
301- /// ]` (and the §7.3.8.13 palette escape group) when
302- /// `escapeDataPresent == 1`. After alignment every bypass bin
303- /// consumes exactly one stream bit (the NOTE's shift-register
304- /// view); bypass decoding itself never changes `ivlCurrRange`, so
305- /// repeated invocations inside one aligned run are no-ops.
306- pub fn align_bypass(&mut self) {
307- self.ivl_curr_range = 256;
308- }
309-
310- /// Current `ivlOffset` register value (for tests / inspection).
311- #[must_use]
312- pub fn ivl_offset(&self) -> u16 {
313- self.ivl_offset
314- }
315-
316- /// Bit position of the underlying reader (for tests / locating the
317- /// engine's consumption point in the buffer).
318- #[must_use]
319- pub fn bit_pos(&self) -> usize {
320- self.reader.bit_pos()
321- }
322-
323- /// §7.3.8.7 support — consume `pcm_alignment_zero_bit` from the
324- /// raw bit source until it is byte-aligned. Called right after a
325- /// `pcm_flag == 1` terminate bin: §9.3.4.3.5 leaves the bitstream
326- /// pointer directly after the terminating one bit, so the raw
327- /// reader position is authoritative for `byte_aligned()`.
328- ///
329- /// # Errors
330- /// [`CabacError::EndOfBuffer`] on a truncated stream.
331- pub fn pcm_align(&mut self) -> Result<(), CabacError> {
332- while self.reader.bit_pos() % 8 != 0 {
333- let _ = self.reader.u1()?;
334- }
335- Ok(())
336- }
337-
338- /// §7.3.8.7 support — read one raw `u(n)` field (a
339- /// `pcm_sample_luma` / `pcm_sample_chroma` value) directly from the
340- /// bit source, bypassing the arithmetic engine.
341- ///
342- /// # Errors
343- /// [`CabacError::EndOfBuffer`] on a truncated stream.
344- pub fn read_raw_bits(&mut self, n: u8) -> Result<u32, CabacError> {
345- Ok(self.reader.u(n)?)
346- }
347-
348- /// Consume the engine and hand back its bit source (tests / callers
349- /// that continue non-CABAC parsing after termination).
350- #[must_use]
351- pub fn into_reader(self) -> BitReader<'a> {
352- self.reader
353- }
354-
355- /// §9.3.4.3.3 — renormalization in the arithmetic decoding engine
356- /// (RenormD). While `ivlCurrRange < 256`, double `ivlCurrRange` and
357- /// shift one fresh bit into `ivlOffset`.
358- fn renorm(&mut self) -> Result<(), CabacError> {
359- while self.ivl_curr_range < 256 {
360- self.ivl_curr_range <<= 1;
361- let bit = self.reader.u1()? as u16;
362- self.ivl_offset = (self.ivl_offset << 1) | bit;
363- }
364- Ok(())
365- }
366-
367- /// §9.3.4.3.2 — DecodeDecision: decode one regular context-coded
368- /// bin against the supplied context variable `ctx`, mutating it
369- /// per the §9.3.4.3.2.2 state-transition process. Returns the
370- /// decoded bin value (0 or 1).
371- pub fn decode_decision(&mut self, ctx: &mut ContextModel) -> Result<u8, CabacError> {
372- // Step 1 (equations 9-64, 9-65): the LPS sub-range.
373- let q_range_idx = ((self.ivl_curr_range >> 6) & 3) as usize;
374- let ivl_lps_range = RANGE_TAB_LPS[ctx.p_state_idx as usize][q_range_idx] as u16;
375-
376- // Step 2: subtract the LPS range; compare ivlOffset.
377- self.ivl_curr_range -= ivl_lps_range;
378- let bin_val;
379- if self.ivl_offset >= self.ivl_curr_range {
380- // LPS path.
381- bin_val = 1 - ctx.val_mps;
382- self.ivl_offset -= self.ivl_curr_range;
383- self.ivl_curr_range = ivl_lps_range;
384- } else {
385- // MPS path.
386- bin_val = ctx.val_mps;
387- }
388-
389- // §9.3.4.3.2.2 state transition (equation 9-66).
390- if bin_val == ctx.val_mps {
391- ctx.p_state_idx = TRANS_IDX_MPS[ctx.p_state_idx as usize];
392- } else {
393- if ctx.p_state_idx == 0 {
394- ctx.val_mps = 1 - ctx.val_mps;
395- }
396- ctx.p_state_idx = TRANS_IDX_LPS[ctx.p_state_idx as usize];
397- }
398-
399- // §9.3.4.3.3 renormalization.
400- self.renorm()?;
401- Ok(bin_val)
402- }
403-
404- /// §9.3.4.3.4 — DecodeBypass: decode one equal-probability bin.
405- /// Doubles `ivlOffset` (shifting in one fresh bit), then compares
406- /// against `ivlCurrRange`. Returns the decoded bin (0 or 1).
407- pub fn decode_bypass(&mut self) -> Result<u8, CabacError> {
408- let bit = self.reader.u1()? as u16;
409- self.ivl_offset = (self.ivl_offset << 1) | bit;
410- if self.ivl_offset >= self.ivl_curr_range {
411- self.ivl_offset -= self.ivl_curr_range;
412- Ok(1)
413- } else {
414- Ok(0)
415- }
416- }
417-
418- /// §9.3.4.3.4 — convenience wrapper: decode `n` bypass bins
419- /// MSB-first and accumulate them into an integer (`n` in 0..=32).
420- /// This is the common pattern for fixed-length bypass-coded fields.
421- /// `n == 0` returns 0 and consumes nothing.
422- pub fn decode_bypass_bits(&mut self, n: u8) -> Result<u32, CabacError> {
423- let mut value: u32 = 0;
424- for _ in 0..n {
425- value = (value << 1) | (self.decode_bypass()? as u32);
426- }
427- Ok(value)
428- }
429-
430- /// §9.3.4.3.5 — DecodeTerminate: the decision before termination
431- /// (`end_of_slice_segment_flag`, `end_of_subset_one_bit`,
432- /// `pcm_flag`; `ctxTable == 0`, `ctxIdx == 0`). Decrements
433- /// `ivlCurrRange` by 2; if `ivlOffset >= ivlCurrRange` the result
434- /// is 1 (no renormalization, decoding is terminated), otherwise the
435- /// result is 0 and renormalization is applied.
436- pub fn decode_terminate(&mut self) -> Result<u8, CabacError> {
437- self.ivl_curr_range -= 2;
438- if self.ivl_offset >= self.ivl_curr_range {
439- Ok(1)
440- } else {
441- self.renorm()?;
442- Ok(0)
443- }
444- }
445-
446- /// §9.3.4.3.6 — alignment process prior to aligned bypass decoding
447- /// (applied before `coeff_abs_level_remaining[ ]` and
448- /// `coeff_sign_flag[ ]`): `ivlCurrRange = 256`. The bit reader and
449- /// `ivlOffset` are left untouched.
450- pub fn align(&mut self) {
451- self.ivl_curr_range = 256;
452- }
453-}
454-
455-#[cfg(test)]
456-mod tests {
457- use super::*;
458-
459- // --- §9.3.2.2 context-variable init (equations 9-4..9-6) ---
460-
461- #[test]
462- fn init_type_eq_9_7() {
463- // I slice (slice_type == 2) → 0 regardless of cabac_init_flag.
464- assert_eq!(init_type(2, false), 0);
465- assert_eq!(init_type(2, true), 0);
466- // P slice (slice_type == 1).
467- assert_eq!(init_type(1, false), 1);
468- assert_eq!(init_type(1, true), 2);
469- // B slice (slice_type == 0).
470- assert_eq!(init_type(0, false), 2);
471- assert_eq!(init_type(0, true), 1);
472- }
473-
474- #[test]
475- fn context_init_worked_example() {
476- // Hand-evaluate equations 9-4..9-6 for initValue = 154,
477- // SliceQpY = 26 (a common mid-range QP).
478- // slopeIdx = 154 >> 4 = 9
479- // offsetIdx = 154 & 15 = 10
480- // m = 9*5 - 45 = 0
481- // n = (10 << 3) - 16 = 64
482- // preCtxState = Clip3(1,126, (0*26 >> 4) + 64) = 64
483- // valMps = (64 <= 63) ? 0 : 1 = 1
484- // pStateIdx = 1 ? (64-64) : … = 0
485- let c = ContextModel::init(154, 26);
486- assert_eq!(c.val_mps, 1);
487- assert_eq!(c.p_state_idx, 0);
488- }
489-
490- #[test]
491- fn context_init_negative_slope() {
492- // initValue = 0, SliceQpY = 51 (max). Exercises a negative m
493- // and the signed arithmetic shift in equation 9-6.
494- // slopeIdx = 0, offsetIdx = 0
495- // m = -45, n = -16
496- // m*Clip3(0,51,51) = -45*51 = -2295
497- // -2295 >> 4 = -144 (arithmetic shift toward -inf)
498- // preCtxState = Clip3(1,126, -144 + -16) = Clip3(1,126,-160) = 1
499- // valMps = (1 <= 63) ? 0 : 1 = 0
500- // pStateIdx = 0 ? … : (63 - 1) = 62
501- let c = ContextModel::init(0, 51);
502- assert_eq!(c.val_mps, 0);
503- assert_eq!(c.p_state_idx, 62);
504- }
505-
506- #[test]
507- fn context_init_high_initvalue() {
508- // initValue = 255, SliceQpY = 0. Drives preCtxState toward the
509- // high clip.
510- // slopeIdx = 15, offsetIdx = 15
511- // m = 15*5 - 45 = 30
512- // n = (15 << 3) - 16 = 104
513- // preCtxState = Clip3(1,126, (30*0 >> 4) + 104) = 104
514- // valMps = (104 <= 63) ? 0 : 1 = 1
515- // pStateIdx = 104 - 64 = 40
516- let c = ContextModel::init(255, 0);
517- assert_eq!(c.val_mps, 1);
518- assert_eq!(c.p_state_idx, 40);
519- }
520-
521- #[test]
522- fn context_init_clips_low_qp_range() {
523- // SliceQpY below 0 is clipped to 0 by Clip3(0,51,SliceQpY);
524- // verify the negative-QP input lands at the same state as QP 0.
525- let c_neg = ContextModel::init(154, -10);
526- let c_zero = ContextModel::init(154, 0);
527- assert_eq!(c_neg, c_zero);
528- }
529-
530- #[test]
531- fn terminate_state_is_non_adapting() {
532- // §9.3.2.2 NOTE 2: pStateIdx = 63, valMps = 0.
533- let c = ContextModel::terminate_state();
534- assert_eq!(c.p_state_idx, 63);
535- assert_eq!(c.val_mps, 0);
536- }
537-
538- // --- Table integrity ---
539-
540- #[test]
541- fn range_tab_lps_corner_values() {
542- // Spot-check the four corners of Table 9-52.
543- assert_eq!(RANGE_TAB_LPS[0], [128, 176, 208, 240]);
544- assert_eq!(RANGE_TAB_LPS[31], [29, 35, 41, 48]);
545- assert_eq!(RANGE_TAB_LPS[32], [27, 33, 39, 45]);
546- assert_eq!(RANGE_TAB_LPS[63], [2, 2, 2, 2]);
547- // The whole table is non-increasing down each column (a
548- // structural property of the LPS-range quantization).
549- for (s, row) in RANGE_TAB_LPS.iter().enumerate().skip(1) {
550- let prev = &RANGE_TAB_LPS[s - 1];
551- for (col, (cur, p)) in row.iter().zip(prev.iter()).enumerate() {
552- assert!(cur <= p, "column {col} not non-increasing at state {s}");
553- }
554- }
555- }
556-
557- #[test]
558- fn trans_idx_tables_bounds_and_endpoints() {
559- // Every transition target is a valid state index (0..=63).
560- for s in 0..64usize {
561- assert!(TRANS_IDX_LPS[s] < 64);
562- assert!(TRANS_IDX_MPS[s] < 64);
563- }
564- // State 0 LPS stays at 0; state 63 is the absorbing terminal
565- // state for both transitions.
566- assert_eq!(TRANS_IDX_LPS[0], 0);
567- assert_eq!(TRANS_IDX_MPS[63], 63);
568- assert_eq!(TRANS_IDX_LPS[63], 63);
569- // transIdxMps is monotonically non-decreasing — confidence
570- // never goes backward after an MPS. (Equality is allowed near
571- // the upper extreme: index 62 maps to 62 in Table 9-53.)
572- for (s, &mps) in TRANS_IDX_MPS.iter().enumerate().take(63) {
573- assert!(
574- mps >= s as u8,
575- "transIdxMps[{s}] = {mps} is below the state"
576- );
577- }
578- // transIdxLps is monotonically non-decreasing too (LPS at a
579- // high-confidence state drops to a less-confident state, but
580- // not below the LPS landing at a lower state).
581- for win in TRANS_IDX_LPS.windows(2) {
582- assert!(win[1] >= win[0]);
583- }
584- }
585-
586- // --- §9.3.2.6 engine init ---
587-
588- #[test]
589- fn engine_init_reads_nine_bit_offset() {
590- // First 9 bits = "1 01010101" = 341; ivlCurrRange = 510.
591- // byte0 = 0b10101010, byte1 MSB = 1 → 9-bit value 0x155 = 341.
592- let buf = [0b1010_1010, 0b1000_0000];
593- let eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
594- assert_eq!(eng.ivl_curr_range(), 510);
595- assert_eq!(eng.ivl_offset(), 341);
596- assert_eq!(eng.bit_pos(), 9);
597- }
598-
599- #[test]
600- fn engine_init_rejects_offset_510_511() {
601- // 9 bits = 0x1FE = 510 → forbidden. byte0 = 0xFF, byte1 MSB
602- // = 0.
603- let buf = [0xFF, 0b0000_0000];
604- match CabacEngine::new(BitReader::new(&buf)) {
605- Err(CabacError::InvalidInitOffset(510)) => {}
606- other => panic!("expected InvalidInitOffset(510), got {other:?}"),
607- }
608- // 9 bits = 0x1FF = 511 → forbidden. byte0 = 0xFF, byte1 MSB
609- // = 1.
610- let buf = [0xFF, 0b1000_0000];
611- match CabacEngine::new(BitReader::new(&buf)) {
612- Err(CabacError::InvalidInitOffset(511)) => {}
613- other => panic!("expected InvalidInitOffset(511), got {other:?}"),
614- }
615- // 509 is allowed: 0x1FD; byte0 = 0xFE, byte1 MSB = 1.
616- let buf = [0xFE, 0b1000_0000];
617- assert!(CabacEngine::new(BitReader::new(&buf)).is_ok());
618- }
619-
620- // --- §9.3.4.3.4 bypass ---
621-
622- #[test]
623- fn bypass_reads_bits_msb_first() {
624- // After init, ivlCurrRange = 510, ivlOffset is the first 9
625- // bits. Each bypass doubles ivlOffset (shift in one bit) and
626- // compares to 510.
627- //
628- // Construct so the bypass bins are deterministic. Init offset
629- // = 0 (9 zero bits at stream bits 0..=8). The next 4 stream
630- // bits feed four bypass decisions and must come out MSB-first.
631- // 9 init bits use byte0 (bits 0..=7) and bit 8 = byte1 MSB.
632- // For init = 0, byte0 = 0x00 and byte1 MSB = 0. The bypass
633- // bits start at stream bit 9 = byte1 bits 1..=4. We want them
634- // to be 1, 0, 1, 1 → byte1 bits 1..=4 = 1011 → byte1 LSBs are
635- // ignored, byte1 = 0b0_1011_000 = 0x58.
636- // bin0: offset = (0<<1)|1 = 1; 1 < 510 → 0
637- // bin1: offset = (1<<1)|0 = 2; 2 < 510 → 0
638- // bin2: offset = (2<<1)|1 = 5; 5 < 510 → 0
639- // bin3: offset = (5<<1)|1 = 11; 11 < 510 → 0
640- // Small offsets always yield 0 — verify offset accumulation.
641- let buf = [0x00, 0x58, 0x00];
642- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
643- assert_eq!(eng.ivl_offset(), 0);
644- assert_eq!(eng.decode_bypass().unwrap(), 0);
645- assert_eq!(eng.ivl_offset(), 1);
646- assert_eq!(eng.decode_bypass().unwrap(), 0);
647- assert_eq!(eng.ivl_offset(), 2);
648- assert_eq!(eng.decode_bypass().unwrap(), 0);
649- assert_eq!(eng.ivl_offset(), 5);
650- assert_eq!(eng.decode_bypass().unwrap(), 0);
651- assert_eq!(eng.ivl_offset(), 11);
652- }
653-
654- #[test]
655- fn bypass_one_when_offset_exceeds_range() {
656- // Init offset = 256. After one bypass shifting in a 1: offset
657- // = (256<<1)|1 = 513 >= 510 → bin 1, offset -= 510 → 3.
658- //
659- // 9-bit offset stream bits 0..=8: 1, 0, 0, 0, 0, 0, 0, 0, 0
660- // → byte0 = 0b1000_0000, byte1 MSB = 0. We then want bypass
661- // bit (stream bit 9) = 1 → byte1 bit1 = 1 → byte1 = 0b0100_0000.
662- let buf = [0b1000_0000, 0b0100_0000];
663- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
664- assert_eq!(eng.ivl_offset(), 256);
665- let bin = eng.decode_bypass().unwrap();
666- assert_eq!(bin, 1);
667- assert_eq!(eng.ivl_offset(), 513 - 510);
668- }
669-
670- #[test]
671- fn bypass_bits_accumulates_msb_first() {
672- // decode_bypass_bits(0) is a no-op returning 0.
673- let buf = [0x00, 0x00, 0xFF];
674- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
675- assert_eq!(eng.decode_bypass_bits(0).unwrap(), 0);
676- assert_eq!(eng.bit_pos(), 9);
677- }
678-
679- // --- §9.3.4.3.5 terminate ---
680-
681- #[test]
682- fn terminate_returns_one_and_stops() {
683- // Init offset = 509 (max legal). ivlCurrRange = 510. terminate:
684- // range -= 2 → 508; offset (509) >= 508 → return 1, no renorm.
685- let buf = [0xFE, 0b1000_0000];
686- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
687- assert_eq!(eng.ivl_offset(), 509);
688- let pos_before = eng.bit_pos();
689- assert_eq!(eng.decode_terminate().unwrap(), 1);
690- assert_eq!(eng.ivl_curr_range(), 508);
691- // No renormalization → no further bits consumed.
692- assert_eq!(eng.bit_pos(), pos_before);
693- }
694-
695- #[test]
696- fn terminate_returns_zero_and_renorms() {
697- // Init offset = 0. ivlCurrRange = 510. terminate: range -= 2 →
698- // 508; offset (0) < 508 → return 0, then renorm: 508 >= 256 so
699- // no renorm bits consumed.
700- let buf = [0x00, 0x00, 0x00];
701- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
702- assert_eq!(eng.decode_terminate().unwrap(), 0);
703- assert_eq!(eng.ivl_curr_range(), 508);
704- assert_eq!(eng.bit_pos(), 9);
705- }
706-
707- // --- §9.3.4.3.6 alignment ---
708-
709- #[test]
710- fn align_sets_range_256() {
711- let buf = [0x00, 0x00, 0x00];
712- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
713- eng.align();
714- assert_eq!(eng.ivl_curr_range(), 256);
715- // ivlOffset and the reader are untouched.
716- assert_eq!(eng.ivl_offset(), 0);
717- assert_eq!(eng.bit_pos(), 9);
718- }
719-
720- // --- §9.3.4.3.2 DecodeDecision: MPS / LPS paths + renorm ---
721-
722- #[test]
723- fn decode_decision_mps_path_no_renorm() {
724- // Init offset = 0, ivlCurrRange = 510. Context: pStateIdx = 0,
725- // valMps = 0.
726- // qRangeIdx = (510 >> 6) & 3 = 7 & 3 = 3
727- // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240
728- // ivlCurrRange = 510 - 240 = 270
729- // offset (0) < 270 → MPS → binVal = valMps = 0
730- // transition: binVal == valMps → pStateIdx = transIdxMps[0]=1
731- // renorm: 270 >= 256 → none
732- let buf = [0x00, 0x00, 0x00];
733- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
734- let mut ctx = ContextModel {
735- p_state_idx: 0,
736- val_mps: 0,
737- };
738- let bin = eng.decode_decision(&mut ctx).unwrap();
739- assert_eq!(bin, 0);
740- assert_eq!(eng.ivl_curr_range(), 270);
741- assert_eq!(ctx.p_state_idx, 1);
742- assert_eq!(ctx.val_mps, 0);
743- assert_eq!(eng.bit_pos(), 9); // no renorm bits
744- }
745-
746- #[test]
747- fn decode_decision_lps_path_flips_mps_and_renorms() {
748- // Drive the LPS path with pStateIdx = 0 (so valMps flips).
749- // Init offset must be >= ivlCurrRange after the LPS subtraction.
750- // qRangeIdx = (510 >> 6) & 3 = 3
751- // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240
752- // ivlCurrRange = 510 - 240 = 270
753- // Need offset >= 270. Use init offset = 300 (0b1_0010_1100).
754- // LPS: binVal = 1 - valMps = 1
755- // offset = 300 - 270 = 30
756- // ivlCurrRange = 240
757- // transition: binVal != valMps, pStateIdx==0 → valMps flips
758- // to 1; pStateIdx = transIdxLps[0] = 0
759- // renorm: 240 < 256 → one doubling: range = 480, offset =
760- // (30<<1)|nextbit.
761- // 9-bit offset 300 = 0b1_0010_1100. Pack into bytes:
762- // byte0 = 0b1001_0110 (bits 0..7), byte1 MSB = 0 (bit 8).
763- // 300 binary (9 bits): 1 0010 1100.
764- // bit0=1 bit1=0 bit2=0 bit3=1 bit4=0 bit5=1 bit6=1 bit7=0 → 0x96
765- // bit8=0 → byte1 MSB 0.
766- // The renorm bit (stream bit 9) = byte1 bit1; set it to 1.
767- let buf = [0x96, 0b0100_0000, 0x00];
768- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
769- assert_eq!(eng.ivl_offset(), 300);
770- let mut ctx = ContextModel {
771- p_state_idx: 0,
772- val_mps: 0,
773- };
774- let bin = eng.decode_decision(&mut ctx).unwrap();
775- assert_eq!(bin, 1);
776- assert_eq!(ctx.val_mps, 1); // flipped
777- assert_eq!(ctx.p_state_idx, 0); // transIdxLps[0]
778- assert_eq!(eng.ivl_curr_range(), 480); // 240 << 1
779- assert_eq!(eng.ivl_offset(), (30 << 1) | 1);
780- assert_eq!(eng.bit_pos(), 10); // one renorm bit
781- }
782-
783- #[test]
784- fn end_of_buffer_surfaces_error() {
785- // Provide exactly 9 bits (one byte + one bit). After init, the
786- // bit reader is at its end, so the next bypass fails. We pad
787- // the buffer to 9 bits by giving 2 bytes but truncating the
788- // BitReader via `skip` would be circular — instead exercise
789- // the path that needs more than the buffer holds by consuming
790- // enough bypass bits to overrun.
791- let buf = [0x00, 0x00];
792- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
793- // 16 - 9 = 7 bits left; the 8th bypass call must fail.
794- for _ in 0..7 {
795- eng.decode_bypass().unwrap();
796- }
797- assert_eq!(eng.decode_bypass(), Err(CabacError::EndOfBuffer));
798- }
799-
800- #[test]
801- fn round_trips_a_known_state_sequence() {
802- // Decode several MPS bins in a row from an all-zero stream with
803- // a fresh I-slice-style context and confirm the probability
804- // state walks up the transIdxMps ladder deterministically.
805- let buf = [0u8; 8];
806- let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap();
807- let mut ctx = ContextModel {
808- p_state_idx: 0,
809- val_mps: 0,
810- };
811- let mut states = Vec::new();
812- for _ in 0..5 {
813- let bin = eng.decode_decision(&mut ctx).unwrap();
814- assert_eq!(bin, 0); // all-zero offset always takes MPS here
815- states.push(ctx.p_state_idx);
816- }
817- // transIdxMps ladder from 0: 1, 2, 3, 4, 5.
818- assert_eq!(states, vec![1, 2, 3, 4, 5]);
819- }
820-}
vendor/oxideav-h265/src/ctx_init.rsdeleted+0 -994
@@ -1,994 +0,0 @@
1-//! §9.3.2.2 context-variable initialization — the `initValue` tables
2-//! (Tables 9-5 .. 9-42) and the per-slice context-array setup.
3-//!
4-//! This module is a clean-room transcription from the ITU-T Rec. H.265
5-//! | ISO/IEC 23008-2 specification text (`docs/video/h265/`):
6-//!
7-//! * The 8-bit `initValue` tables for every context-coded syntax
8-//! element of clauses 7.3.8.1 through 7.3.8.12 (except
9-//! `end_of_slice_segment_flag`, `end_of_subset_one_bit` and
10-//! `pcm_flag`, which use the §9.3.2.2 NOTE 2 non-adapting
11-//! `ctxTable == 0` state — [`ContextModel::terminate_state`]).
12-//! Each constant is laid out flat over the table's printed ctxIdx
13-//! axis, exactly as in the spec.
14-//! * The Table 9-4 association of ctxIdx ranges to the three
15-//! initialization types: most tables devote a contiguous span of
16-//! `N` ctxIdx slots to each `initType` column, but several are
17-//! irregular (`part_mode`, `cbf_cb`/`cbf_cr`, the
18-//! `abs_mvd_greater0_flag`/`abs_mvd_greater1_flag` interleave,
19-//! `transform_skip_flag`, the `explicit_rdpcm_*` pairs and the
20-//! `sig_coeff_flag` transform-skip tail) — see the per-bank
21-//! helpers.
22-//! * [`SliceContexts`] — the whole per-slice context array, one bank
23-//! per syntax element (or per Table 9-4 shared-variable group),
24-//! initialised for a given `initType` and `SliceQpY` through the
25-//! §9.3.2.2 process ([`ContextModel::init`], equations 9-4..9-6).
26-//! [`SliceContexts::for_slice`] additionally applies the
27-//! equation 9-7 `initType` derivation from `slice_type` and
28-//! `cabac_init_flag` ([`crate::cabac::init_type`]).
29-//!
30-//! # Shared context variables
31-//!
32-//! Table 9-4 assigns the *same* `(ctxTable, ctxIdx)` slots to a few
33-//! element groups, which therefore share one adapting context
34-//! variable per `initType`:
35-//!
36-//! * `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5),
37-//! * `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6),
38-//! * `ref_idx_l0` / `ref_idx_l1` (Table 9-18),
39-//! * `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19),
40-//! * `cbf_cb` / `cbf_cr` (Table 9-22),
41-//! * `copy_above_palette_indices_flag` /
42-//! `copy_above_indices_for_final_run_flag` (Table 9-41),
43-//! * the chroma planes of `transform_skip_flag[ ][ ][ 1 ]` /
44-//! `[ 2 ]` (Table 9-25), `explicit_rdpcm_flag[ ][ ][ 1 ]` / `[ 2 ]`
45-//! (Table 9-32) and `explicit_rdpcm_dir_flag[ ][ ][ 1 ]` / `[ 2 ]`
46-//! (Table 9-33).
47-//!
48-//! # Inter-only elements in I slices
49-//!
50-//! Table 9-4 leaves the `initType == 0` column empty for the elements
51-//! that can only occur in P / B slices (`cu_skip_flag`,
52-//! `pred_mode_flag`, `rqt_root_cbf`, `merge_flag`, `merge_idx`,
53-//! `inter_pred_idc`, `ref_idx_l0`/`l1`, `mvp_l0_flag`/`l1`,
54-//! `abs_mvd_greater0_flag`/`greater1_flag`, `explicit_rdpcm_flag` and
55-//! `explicit_rdpcm_dir_flag`) — no initialization is specified
56-//! because a conforming I slice never decodes them. [`SliceContexts`]
57-//! still materialises those banks so the array shape is
58-//! `initType`-independent; at `initType == 0` they are populated with
59-//! the §9.3.2.2 NOTE 2 non-adapting state
60-//! ([`ContextModel::terminate_state`], `pStateIdx = 63`,
61-//! `valMps = 0`), which no table-derived context can take
62-//! (equations 9-4..9-6 bound `pStateIdx` to 0..=62), making an
63-//! accidental read recognisable. The same placeholder fills the
64-//! `part_mode` slots 1..=3 at `initType == 0` (Table 9-4 gives
65-//! `part_mode` only ctxIdx 0 there: the I-slice §9.3.4.2 binarization
66-//! uses a single context-coded bin).
67-
68-use crate::cabac::{init_type, ContextModel};
69-use crate::residual::ResidualContexts;
70-use crate::slice::SliceType;
71-
72-// ---------------------------------------------------------------------
73-// initValue tables (Tables 9-5 .. 9-42)
74-// ---------------------------------------------------------------------
75-
76-/// Table 9-5 — `initValue` for ctxIdx of `sao_merge_left_flag` and
77-/// `sao_merge_up_flag` (one shared context per `initType`; ctxIdx
78-/// 0 / 1 / 2 for `initType` 0 / 1 / 2).
79-pub const TABLE_9_5_SAO_MERGE_FLAG: [u8; 3] = [153, 153, 153];
80-
81-/// Table 9-6 — `initValue` for ctxIdx of `sao_type_idx_luma` and
82-/// `sao_type_idx_chroma` (one shared context per `initType`).
83-pub const TABLE_9_6_SAO_TYPE_IDX: [u8; 3] = [200, 185, 160];
84-
85-/// Table 9-7 — `initValue` for ctxIdx of `split_cu_flag` (ctxIdx
86-/// 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2 per Table 9-4).
87-pub const TABLE_9_7_SPLIT_CU_FLAG: [u8; 9] = [139, 141, 157, 107, 139, 126, 107, 139, 126];
88-
89-/// Table 9-8 — `initValue` for ctxIdx of `cu_transquant_bypass_flag`.
90-pub const TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG: [u8; 3] = [154, 154, 154];
91-
92-/// Table 9-9 — `initValue` for ctxIdx of `cu_skip_flag` (ctxIdx 0..2 /
93-/// 3..5 for `initType` 1 / 2; the element does not occur in I slices).
94-pub const TABLE_9_9_CU_SKIP_FLAG: [u8; 6] = [197, 185, 201, 197, 185, 201];
95-
96-/// Table 9-10 — `initValue` for ctxIdx of `pred_mode_flag` (ctxIdx
97-/// 0 / 1 for `initType` 1 / 2; inter-only).
98-pub const TABLE_9_10_PRED_MODE_FLAG: [u8; 2] = [149, 134];
99-
100-/// Table 9-11 — `initValue` for ctxIdx of `part_mode`. Irregular
101-/// Table 9-4 mapping: ctxIdx 0 for `initType` 0 (the I-slice
102-/// binarization has one context-coded bin), ctxIdx 1..4 / 5..8 for
103-/// `initType` 1 / 2.
104-pub const TABLE_9_11_PART_MODE: [u8; 9] = [184, 154, 139, 154, 154, 154, 139, 154, 154];
105-
106-/// Table 9-12 — `initValue` for ctxIdx of `prev_intra_luma_pred_flag`.
107-pub const TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG: [u8; 3] = [184, 154, 183];
108-
109-/// Table 9-13 — `initValue` for ctxIdx of `intra_chroma_pred_mode`.
110-pub const TABLE_9_13_INTRA_CHROMA_PRED_MODE: [u8; 3] = [63, 152, 152];
111-
112-/// Table 9-14 — `initValue` for ctxIdx of `rqt_root_cbf` (ctxIdx 0 / 1
113-/// for `initType` 1 / 2; inter-only).
114-pub const TABLE_9_14_RQT_ROOT_CBF: [u8; 2] = [79, 79];
115-
116-/// Table 9-15 — `initValue` for ctxIdx of `merge_flag` (`initType`
117-/// 1 / 2; inter-only).
118-pub const TABLE_9_15_MERGE_FLAG: [u8; 2] = [110, 154];
119-
120-/// Table 9-16 — `initValue` for ctxIdx of `merge_idx` (`initType`
121-/// 1 / 2; inter-only).
122-pub const TABLE_9_16_MERGE_IDX: [u8; 2] = [122, 137];
123-
124-/// Table 9-17 — `initValue` for ctxIdx of `inter_pred_idc` (ctxIdx
125-/// 0..4 / 5..9 for `initType` 1 / 2; inter-only).
126-pub const TABLE_9_17_INTER_PRED_IDC: [u8; 10] = [95, 79, 63, 31, 31, 95, 79, 63, 31, 31];
127-
128-/// Table 9-18 — `initValue` for ctxIdx of `ref_idx_l0` and
129-/// `ref_idx_l1` (shared bank; ctxIdx 0..1 / 2..3 for `initType` 1 / 2;
130-/// inter-only).
131-pub const TABLE_9_18_REF_IDX: [u8; 4] = [153, 153, 153, 153];
132-
133-/// Table 9-19 — `initValue` for ctxIdx of `mvp_l0_flag` and
134-/// `mvp_l1_flag` (shared bank; ctxIdx 0 / 1 for `initType` 1 / 2;
135-/// inter-only).
136-pub const TABLE_9_19_MVP_FLAG: [u8; 2] = [168, 168];
137-
138-/// Table 9-20 — `initValue` for ctxIdx of `split_transform_flag`
139-/// (ctxIdx 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2).
140-pub const TABLE_9_20_SPLIT_TRANSFORM_FLAG: [u8; 9] = [153, 138, 138, 124, 138, 94, 224, 167, 122];
141-
142-/// Table 9-21 — `initValue` for ctxIdx of `cbf_luma` (ctxIdx 0..1 /
143-/// 2..3 / 4..5 for `initType` 0 / 1 / 2).
144-pub const TABLE_9_21_CBF_LUMA: [u8; 6] = [111, 141, 153, 111, 153, 111];
145-
146-/// Table 9-22 — `initValue` for ctxIdx of `cbf_cb` and `cbf_cr`
147-/// (shared bank). Irregular Table 9-4 mapping: ctxIdx 0..3 / 4..7 /
148-/// 8..11 carry the four trafo-depth contexts for `initType` 0 / 1 / 2
149-/// and ctxIdx 12 / 13 / 14 carry the fifth (`ctxInc == 4`) context
150-/// for `initType` 0 / 1 / 2.
151-#[rustfmt::skip]
152-pub const TABLE_9_22_CBF_CHROMA: [u8; 15] = [
153- 94, 138, 182, 154,
154- 149, 107, 167, 154,
155- 149, 92, 167, 154,
156- 154, 154, 154,
157-];
158-
159-/// Table 9-23 — `initValue` for ctxIdx of `abs_mvd_greater0_flag` and
160-/// `abs_mvd_greater1_flag`. Irregular Table 9-4 mapping (inter-only):
161-/// `abs_mvd_greater0_flag` takes ctxIdx 0 / 2 for `initType` 1 / 2 and
162-/// `abs_mvd_greater1_flag` takes ctxIdx 1 / 3.
163-pub const TABLE_9_23_ABS_MVD_GREATER_FLAG: [u8; 4] = [140, 198, 169, 198];
164-
165-/// Table 9-24 — `initValue` for ctxIdx of `cu_qp_delta_abs` (ctxIdx
166-/// 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2).
167-pub const TABLE_9_24_CU_QP_DELTA_ABS: [u8; 6] = [154, 154, 154, 154, 154, 154];
168-
169-/// Table 9-25 — `initValue` for ctxIdx of `transform_skip_flag`.
170-/// Irregular Table 9-4 mapping: ctxIdx 0 / 1 / 2 carry the luma
171-/// (`cIdx == 0`) context for `initType` 0 / 1 / 2 and ctxIdx 3 / 4 / 5
172-/// the context shared by both chroma planes (`cIdx == 1` / `2`).
173-pub const TABLE_9_25_TRANSFORM_SKIP_FLAG: [u8; 6] = [139, 139, 139, 139, 139, 139];
174-
175-/// Table 9-26 — `initValue` for ctxIdx of `last_sig_coeff_x_prefix`
176-/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2).
177-#[rustfmt::skip]
178-pub const TABLE_9_26_LAST_SIG_COEFF_X_PREFIX: [u8; 54] = [
179- 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
180- 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108,
181- 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93,
182-];
183-
184-/// Table 9-27 — `initValue` for ctxIdx of `last_sig_coeff_y_prefix`
185-/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2). The
186-/// printed values coincide with Table 9-26 entry-for-entry, but the
187-/// two elements adapt separate context variables.
188-#[rustfmt::skip]
189-pub const TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX: [u8; 54] = [
190- 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
191- 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108,
192- 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93,
193-];
194-
195-/// Table 9-28 — `initValue` for ctxIdx of `coded_sub_block_flag`
196-/// (ctxIdx 0..3 / 4..7 / 8..11 for `initType` 0 / 1 / 2).
197-#[rustfmt::skip]
198-pub const TABLE_9_28_CODED_SUB_BLOCK_FLAG: [u8; 12] = [
199- 91, 171, 134, 141,
200- 121, 140, 61, 154,
201- 121, 140, 61, 154,
202-];
203-
204-/// Table 9-29 — `initValue` for ctxIdx of `sig_coeff_flag`. Irregular
205-/// Table 9-4 mapping: ctxIdx 0..41 / 42..83 / 84..125 carry the 42
206-/// §9.3.4.2.5 contexts for `initType` 0 / 1 / 2 and ctxIdx 126..127 /
207-/// 128..129 / 130..131 carry the two equation 9-40 transform-skip
208-/// contexts (luma, chroma) for `initType` 0 / 1 / 2.
209-#[rustfmt::skip]
210-pub const TABLE_9_29_SIG_COEFF_FLAG: [u8; 132] = [
211- 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107,
212- 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152,
213- 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 155, 154, 139, 153, 139, 123,
214- 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166,
215- 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183,
216- 140, 151, 183, 140, 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140,
217- 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170,
218- 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 141, 111,
219- 140, 140, 140, 140,
220-];
221-
222-/// Table 9-30 — `initValue` for ctxIdx of
223-/// `coeff_abs_level_greater1_flag` (ctxIdx 0..23 / 24..47 / 48..71 for
224-/// `initType` 0 / 1 / 2).
225-#[rustfmt::skip]
226-pub const TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG: [u8; 72] = [
227- 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152,
228- 140, 179, 166, 182, 140, 227, 122, 197, 154, 196, 196, 167, 154, 152, 167, 182,
229- 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182,
230- 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122,
231- 169, 208, 166, 167, 154, 152, 167, 182,
232-];
233-
234-/// Table 9-31 — `initValue` for ctxIdx of
235-/// `coeff_abs_level_greater2_flag` (ctxIdx 0..5 / 6..11 / 12..17 for
236-/// `initType` 0 / 1 / 2).
237-#[rustfmt::skip]
238-pub const TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG: [u8; 18] = [
239- 138, 153, 136, 167, 152, 152,
240- 107, 167, 91, 122, 107, 167,
241- 107, 167, 91, 107, 107, 167,
242-];
243-
244-/// Table 9-32 — `initValue` for ctxIdx of `explicit_rdpcm_flag`.
245-/// Irregular Table 9-4 mapping (inter-only): ctxIdx 0 / 1 carry the
246-/// luma (`cIdx == 0`) context for `initType` 1 / 2 and ctxIdx 2 / 3
247-/// the context shared by both chroma planes.
248-pub const TABLE_9_32_EXPLICIT_RDPCM_FLAG: [u8; 4] = [139, 139, 139, 139];
249-
250-/// Table 9-33 — `initValue` for ctxIdx of `explicit_rdpcm_dir_flag`
251-/// (same irregular mapping as Table 9-32; inter-only).
252-pub const TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG: [u8; 4] = [139, 139, 139, 139];
253-
254-/// Table 9-34 — `initValue` for ctxIdx of `cu_chroma_qp_offset_flag`.
255-pub const TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG: [u8; 3] = [154, 154, 154];
256-
257-/// Table 9-35 — `initValue` for ctxIdx of `cu_chroma_qp_offset_idx`.
258-pub const TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX: [u8; 3] = [154, 154, 154];
259-
260-/// Table 9-36 — `initValue` for ctxIdx of `log2_res_scale_abs_plus1`
261-/// (ctxIdx 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2).
262-pub const TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1: [u8; 24] = [154; 24];
263-
264-/// Table 9-37 — `initValue` for ctxIdx of `res_scale_sign_flag`
265-/// (ctxIdx 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2).
266-pub const TABLE_9_37_RES_SCALE_SIGN_FLAG: [u8; 6] = [154; 6];
267-
268-/// Table 9-38 — `initValue` for ctxIdx of `palette_mode_flag`.
269-pub const TABLE_9_38_PALETTE_MODE_FLAG: [u8; 3] = [154, 154, 154];
270-
271-/// Table 9-39 — `initValue` for ctxIdx of `tu_residual_act_flag`.
272-pub const TABLE_9_39_TU_RESIDUAL_ACT_FLAG: [u8; 3] = [154, 154, 154];
273-
274-/// Table 9-40 — `initValue` for ctxIdx of `palette_run_prefix` (ctxIdx
275-/// 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2).
276-pub const TABLE_9_40_PALETTE_RUN_PREFIX: [u8; 24] = [154; 24];
277-
278-/// Table 9-41 — `initValue` for ctxIdx of
279-/// `copy_above_palette_indices_flag` and
280-/// `copy_above_indices_for_final_run_flag` (shared bank: Table 9-4
281-/// assigns both elements ctxIdx 0 / 1 / 2 of this table).
282-pub const TABLE_9_41_PALETTE_COPY_ABOVE_FLAG: [u8; 3] = [154, 154, 154];
283-
284-/// Table 9-42 — `initValue` for ctxIdx of `palette_transpose_flag`.
285-pub const TABLE_9_42_PALETTE_TRANSPOSE_FLAG: [u8; 3] = [154, 154, 154];
286-
287-// ---------------------------------------------------------------------
288-// Table 9-4 ctxIdx-span selection helpers
289-// ---------------------------------------------------------------------
290-
291-/// Select the `N` per-`initType` `initValue` entries from a table
292-/// whose Table 9-4 mapping is the regular contiguous layout (ctxIdx
293-/// `0..N` / `N..2N` / `2N..3N` for `initType` 0 / 1 / 2).
294-///
295-/// # Panics
296-///
297-/// Panics when `init_type > 2` or `table.len() != 3 * N`.
298-#[must_use]
299-pub fn uniform_init_values<const N: usize>(table: &[u8], init_type: u8) -> [u8; N] {
300- assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)");
301- assert_eq!(table.len(), 3 * N, "table is not a 3-initType layout");
302- let base = N * init_type as usize;
303- core::array::from_fn(|i| table[base + i])
304-}
305-
306-/// Select the `N` per-`initType` `initValue` entries from a table for
307-/// an inter-only element (Table 9-4 leaves `initType == 0` empty;
308-/// ctxIdx `0..N` / `N..2N` map to `initType` 1 / 2). Returns `None`
309-/// for `init_type == 0` — the element cannot occur in an I slice.
310-///
311-/// # Panics
312-///
313-/// Panics when `init_type > 2` or `table.len() != 2 * N`.
314-#[must_use]
315-pub fn inter_init_values<const N: usize>(table: &[u8], init_type: u8) -> Option<[u8; N]> {
316- assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)");
317- assert_eq!(table.len(), 2 * N, "table is not a 2-initType layout");
318- if init_type == 0 {
319- return None;
320- }
321- let base = N * (init_type as usize - 1);
322- Some(core::array::from_fn(|i| table[base + i]))
323-}
324-
325-/// The per-`initType` `sig_coeff_flag` `initValue` bank (44 entries):
326-/// the 42 §9.3.4.2.5 contexts from the Table 9-29 ctxIdx span
327-/// `42 * initType ..`, followed by the two equation 9-40
328-/// transform-skip contexts (luma then chroma) from ctxIdx
329-/// `126 + 2 * initType ..`. Matches the
330-/// [`crate::residual::ResidualContexts`] bank layout (slots 42 / 43
331-/// are the transform-skip contexts).
332-///
333-/// # Panics
334-///
335-/// Panics when `init_type > 2`.
336-#[must_use]
337-pub fn sig_coeff_flag_init_values(init_type: u8) -> [u8; 44] {
338- assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)");
339- let t = init_type as usize;
340- core::array::from_fn(|i| {
341- if i < 42 {
342- TABLE_9_29_SIG_COEFF_FLAG[42 * t + i]
343- } else {
344- TABLE_9_29_SIG_COEFF_FLAG[126 + 2 * t + (i - 42)]
345- }
346- })
347-}
348-
349-/// Initialize an inter-only bank: table entries through
350-/// [`ContextModel::init`] for `initType` 1 / 2, the
351-/// [`ContextModel::terminate_state`] placeholder for `initType` 0
352-/// (see the module docs).
353-fn inter_bank<const N: usize>(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] {
354- match inter_init_values::<N>(table, init_type) {
355- Some(values) => values.map(|v| ContextModel::init(v, slice_qp_y)),
356- None => [ContextModel::terminate_state(); N],
357- }
358-}
359-
360-/// Initialize a regular three-`initType` bank.
361-fn uniform_bank<const N: usize>(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] {
362- uniform_init_values::<N>(table, init_type).map(|v| ContextModel::init(v, slice_qp_y))
363-}
364-
365-// ---------------------------------------------------------------------
366-// SliceContexts
367-// ---------------------------------------------------------------------
368-
369-/// The complete per-slice CABAC context array of §9.3.2.2 / Table 9-4:
370-/// one bank per syntax element (or per Table 9-4 shared-variable
371-/// group; see the module docs), each slot a `(pStateIdx, valMps)`
372-/// [`ContextModel`]. Bank-internal indices are the *bank-relative*
373-/// ctxIdx (the §9.3.4.2 `ctxInc` value), not the absolute Table 9-4
374-/// ctxIdx.
375-#[derive(Debug, Clone, PartialEq, Eq)]
376-pub struct SliceContexts {
377- /// `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5, shared).
378- pub sao_merge_flag: [ContextModel; 1],
379- /// `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6, shared).
380- pub sao_type_idx: [ContextModel; 1],
381- /// `split_cu_flag` (Table 9-7).
382- pub split_cu_flag: [ContextModel; 3],
383- /// `cu_transquant_bypass_flag` (Table 9-8).
384- pub cu_transquant_bypass_flag: [ContextModel; 1],
385- /// `cu_skip_flag` (Table 9-9; inter-only).
386- pub cu_skip_flag: [ContextModel; 3],
387- /// `palette_mode_flag` (Table 9-38).
388- pub palette_mode_flag: [ContextModel; 1],
389- /// `pred_mode_flag` (Table 9-10; inter-only).
390- pub pred_mode_flag: [ContextModel; 1],
391- /// `part_mode` (Table 9-11; slot 0 only at `initType == 0`).
392- pub part_mode: [ContextModel; 4],
393- /// `prev_intra_luma_pred_flag` (Table 9-12).
394- pub prev_intra_luma_pred_flag: [ContextModel; 1],
395- /// `intra_chroma_pred_mode` (Table 9-13).
396- pub intra_chroma_pred_mode: [ContextModel; 1],
397- /// `rqt_root_cbf` (Table 9-14; inter-only).
398- pub rqt_root_cbf: [ContextModel; 1],
399- /// `merge_flag` (Table 9-15; inter-only).
400- pub merge_flag: [ContextModel; 1],
401- /// `merge_idx` (Table 9-16; inter-only).
402- pub merge_idx: [ContextModel; 1],
403- /// `inter_pred_idc` (Table 9-17; inter-only).
404- pub inter_pred_idc: [ContextModel; 5],
405- /// `ref_idx_l0` / `ref_idx_l1` (Table 9-18, shared; inter-only).
406- pub ref_idx: [ContextModel; 2],
407- /// `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19, shared; inter-only).
408- pub mvp_flag: [ContextModel; 1],
409- /// `split_transform_flag` (Table 9-20).
410- pub split_transform_flag: [ContextModel; 3],
411- /// `cbf_luma` (Table 9-21).
412- pub cbf_luma: [ContextModel; 2],
413- /// `cbf_cb` / `cbf_cr` (Table 9-22, shared; slot 4 is the
414- /// Table 9-4 ctxIdx 12 / 13 / 14 fifth context).
415- pub cbf_chroma: [ContextModel; 5],
416- /// `abs_mvd_greater0_flag` (Table 9-23 ctxIdx 0 / 2; inter-only).
417- pub abs_mvd_greater0_flag: [ContextModel; 1],
418- /// `abs_mvd_greater1_flag` (Table 9-23 ctxIdx 1 / 3; inter-only).
419- pub abs_mvd_greater1_flag: [ContextModel; 1],
420- /// `tu_residual_act_flag` (Table 9-39).
421- pub tu_residual_act_flag: [ContextModel; 1],
422- /// `log2_res_scale_abs_plus1` (Table 9-36).
423- pub log2_res_scale_abs_plus1: [ContextModel; 8],
424- /// `res_scale_sign_flag` (Table 9-37).
425- pub res_scale_sign_flag: [ContextModel; 2],
426- /// `transform_skip_flag` (Table 9-25; slot 0 luma, slot 1 the
427- /// shared chroma context).
428- pub transform_skip_flag: [ContextModel; 2],
429- /// `explicit_rdpcm_flag` (Table 9-32; slot 0 luma, slot 1 the
430- /// shared chroma context; inter-only).
431- pub explicit_rdpcm_flag: [ContextModel; 2],
432- /// `explicit_rdpcm_dir_flag` (Table 9-33; same layout; inter-only).
433- pub explicit_rdpcm_dir_flag: [ContextModel; 2],
434- /// The §7.3.8.11 `residual_coding( )` banks (Tables 9-26..9-31).
435- pub residual: ResidualContexts,
436- /// `palette_run_prefix` (Table 9-40).
437- pub palette_run_prefix: [ContextModel; 8],
438- /// `copy_above_palette_indices_flag` /
439- /// `copy_above_indices_for_final_run_flag` (Table 9-41, shared).
440- pub palette_copy_above_flag: [ContextModel; 1],
441- /// `palette_transpose_flag` (Table 9-42).
442- pub palette_transpose_flag: [ContextModel; 1],
443- /// `cu_qp_delta_abs` (Table 9-24).
444- pub cu_qp_delta_abs: [ContextModel; 2],
445- /// `cu_chroma_qp_offset_flag` (Table 9-34).
446- pub cu_chroma_qp_offset_flag: [ContextModel; 1],
447- /// `cu_chroma_qp_offset_idx` (Table 9-35).
448- pub cu_chroma_qp_offset_idx: [ContextModel; 1],
449- /// §9.3.2.1 palette predictor variables (`PredictorPaletteSize` /
450- /// `PredictorPaletteEntries`) — parse state that initializes,
451- /// stores and synchronizes ALONGSIDE the context variables
452- /// (§9.3.2.3 / §9.3.2.4 / §9.3.2.5), so it travels inside this
453- /// struct. [`Self::init`] leaves it empty; the slice driver
454- /// assigns the PPS / SPS initializer-derived predictor at every
455- /// §9.3.2.2 re-initialization point.
456- pub palette_predictor: crate::palette::PalettePredictor,
457-}
458-
459-impl SliceContexts {
460- /// The number of distinct adapting context variables per
461- /// `initType` (shared Table 9-4 groups counted once).
462- pub const CONTEXT_COUNT: usize = 185;
463-
464- /// §9.3.2.2 initialization of the whole context array for one
465- /// `initType` (0, 1 or 2) and `SliceQpY` (equation 7-54). Every
466- /// table entry goes through [`ContextModel::init`]
467- /// (equations 9-4..9-6); inter-only banks at `initType == 0` take
468- /// the non-adapting placeholder described in the module docs.
469- ///
470- /// # Panics
471- ///
472- /// Panics when `init_type > 2`.
473- #[must_use]
474- pub fn init(init_type: u8, slice_qp_y: i32) -> Self {
475- assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)");
476- let t = init_type as usize;
477- let init = |v: u8| ContextModel::init(v, slice_qp_y);
478- // Table 9-11 `part_mode`: ctxIdx 0 at initType 0, 1..4 / 5..8
479- // at initType 1 / 2.
480- let part_mode = if init_type == 0 {
481- let mut bank = [ContextModel::terminate_state(); 4];
482- bank[0] = init(TABLE_9_11_PART_MODE[0]);
483- bank
484- } else {
485- core::array::from_fn(|i| init(TABLE_9_11_PART_MODE[1 + 4 * (t - 1) + i]))
486- };
487- // Table 9-22 `cbf_cb` / `cbf_cr`: ctxIdx 4t..4t+3 plus 12 + t.
488- let cbf_chroma = core::array::from_fn(|i| {
489- init(if i < 4 {
490- TABLE_9_22_CBF_CHROMA[4 * t + i]
491- } else {
492- TABLE_9_22_CBF_CHROMA[12 + t]
493- })
494- });
495- // Table 9-23 interleave: greater0 at ctxIdx 0 / 2, greater1 at
496- // ctxIdx 1 / 3 for initType 1 / 2.
497- let (abs_mvd_greater0_flag, abs_mvd_greater1_flag) = if init_type == 0 {
498- (
499- [ContextModel::terminate_state(); 1],
500- [ContextModel::terminate_state(); 1],
501- )
502- } else {
503- (
504- [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1)])],
505- [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1) + 1])],
506- )
507- };
508- // Table 9-25 `transform_skip_flag`: luma at ctxIdx t, the
509- // shared chroma context at ctxIdx 3 + t.
510- let transform_skip_flag = [
511- init(TABLE_9_25_TRANSFORM_SKIP_FLAG[t]),
512- init(TABLE_9_25_TRANSFORM_SKIP_FLAG[3 + t]),
513- ];
514- // Tables 9-32 / 9-33 (inter-only): luma at ctxIdx t − 1, the
515- // shared chroma context at ctxIdx 2 + (t − 1).
516- let rdpcm_bank = |table: &[u8; 4]| {
517- if init_type == 0 {
518- [ContextModel::terminate_state(); 2]
519- } else {
520- [init(table[t - 1]), init(table[2 + (t - 1)])]
521- }
522- };
523- Self {
524- sao_merge_flag: uniform_bank(&TABLE_9_5_SAO_MERGE_FLAG, init_type, slice_qp_y),
525- sao_type_idx: uniform_bank(&TABLE_9_6_SAO_TYPE_IDX, init_type, slice_qp_y),
526- split_cu_flag: uniform_bank(&TABLE_9_7_SPLIT_CU_FLAG, init_type, slice_qp_y),
527- cu_transquant_bypass_flag: uniform_bank(
528- &TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG,
529- init_type,
530- slice_qp_y,
531- ),
532- cu_skip_flag: inter_bank(&TABLE_9_9_CU_SKIP_FLAG, init_type, slice_qp_y),
533- palette_mode_flag: uniform_bank(&TABLE_9_38_PALETTE_MODE_FLAG, init_type, slice_qp_y),
534- pred_mode_flag: inter_bank(&TABLE_9_10_PRED_MODE_FLAG, init_type, slice_qp_y),
535- part_mode,
536- prev_intra_luma_pred_flag: uniform_bank(
537- &TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG,
538- init_type,
539- slice_qp_y,
540- ),
541- intra_chroma_pred_mode: uniform_bank(
542- &TABLE_9_13_INTRA_CHROMA_PRED_MODE,
543- init_type,
544- slice_qp_y,
545- ),
546- rqt_root_cbf: inter_bank(&TABLE_9_14_RQT_ROOT_CBF, init_type, slice_qp_y),
547- merge_flag: inter_bank(&TABLE_9_15_MERGE_FLAG, init_type, slice_qp_y),
548- merge_idx: inter_bank(&TABLE_9_16_MERGE_IDX, init_type, slice_qp_y),
549- inter_pred_idc: inter_bank(&TABLE_9_17_INTER_PRED_IDC, init_type, slice_qp_y),
550- ref_idx: inter_bank(&TABLE_9_18_REF_IDX, init_type, slice_qp_y),
551- mvp_flag: inter_bank(&TABLE_9_19_MVP_FLAG, init_type, slice_qp_y),
552- split_transform_flag: uniform_bank(
553- &TABLE_9_20_SPLIT_TRANSFORM_FLAG,
554- init_type,
555- slice_qp_y,
556- ),
557- cbf_luma: uniform_bank(&TABLE_9_21_CBF_LUMA, init_type, slice_qp_y),
558- cbf_chroma,
559- abs_mvd_greater0_flag,
560- abs_mvd_greater1_flag,
561- tu_residual_act_flag: uniform_bank(
562- &TABLE_9_39_TU_RESIDUAL_ACT_FLAG,
563- init_type,
564- slice_qp_y,
565- ),
566- log2_res_scale_abs_plus1: uniform_bank(
567- &TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1,
568- init_type,
569- slice_qp_y,
570- ),
571- res_scale_sign_flag: uniform_bank(
572- &TABLE_9_37_RES_SCALE_SIGN_FLAG,
573- init_type,
574- slice_qp_y,
575- ),
576- transform_skip_flag,
577- explicit_rdpcm_flag: rdpcm_bank(&TABLE_9_32_EXPLICIT_RDPCM_FLAG),
578- explicit_rdpcm_dir_flag: rdpcm_bank(&TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG),
579- residual: ResidualContexts::init(init_type, slice_qp_y),
580- palette_run_prefix: uniform_bank(&TABLE_9_40_PALETTE_RUN_PREFIX, init_type, slice_qp_y),
581- palette_copy_above_flag: uniform_bank(
582- &TABLE_9_41_PALETTE_COPY_ABOVE_FLAG,
583- init_type,
584- slice_qp_y,
585- ),
586- palette_transpose_flag: uniform_bank(
587- &TABLE_9_42_PALETTE_TRANSPOSE_FLAG,
588- init_type,
589- slice_qp_y,
590- ),
591- cu_qp_delta_abs: uniform_bank(&TABLE_9_24_CU_QP_DELTA_ABS, init_type, slice_qp_y),
592- cu_chroma_qp_offset_flag: uniform_bank(
593- &TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG,
594- init_type,
595- slice_qp_y,
596- ),
597- cu_chroma_qp_offset_idx: uniform_bank(
598- &TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX,
599- init_type,
600- slice_qp_y,
601- ),
602- palette_predictor: crate::palette::PalettePredictor::default(),
603- }
604- }
605-
606- /// Initialize the context array for a slice: derives `initType`
607- /// from `slice_type` and `cabac_init_flag` per equation 9-7
608- /// ([`init_type`]), then runs [`SliceContexts::init`].
609- /// `cabac_init_flag` is the §7.3.6.1 header flag (inferred 0 when
610- /// absent — pass `false` for I slices or when
611- /// `cabac_init_present_flag == 0`); `slice_qp_y` is `SliceQpY`
612- /// per equation 7-54 (`26 + init_qp_minus26 + slice_qp_delta`).
613- #[must_use]
614- pub fn for_slice(slice_type: SliceType, cabac_init_flag: bool, slice_qp_y: i32) -> Self {
615- let raw = match slice_type {
616- SliceType::B => 0,
617- SliceType::P => 1,
618- SliceType::I => 2,
619- };
620- Self::init(init_type(raw, cabac_init_flag), slice_qp_y)
621- }
622-}
623-
624-// ---------------------------------------------------------------------
625-// Tests
626-// ---------------------------------------------------------------------
627-
628-#[cfg(test)]
629-mod tests {
630- use super::*;
631-
632- /// Every table's printed ctxIdx span (Tables 9-5..9-42).
633- #[test]
634- fn table_shapes() {
635- assert_eq!(TABLE_9_5_SAO_MERGE_FLAG.len(), 3);
636- assert_eq!(TABLE_9_6_SAO_TYPE_IDX.len(), 3);
637- assert_eq!(TABLE_9_7_SPLIT_CU_FLAG.len(), 9);
638- assert_eq!(TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG.len(), 3);
639- assert_eq!(TABLE_9_9_CU_SKIP_FLAG.len(), 6);
640- assert_eq!(TABLE_9_10_PRED_MODE_FLAG.len(), 2);
641- assert_eq!(TABLE_9_11_PART_MODE.len(), 9);
642- assert_eq!(TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG.len(), 3);
643- assert_eq!(TABLE_9_13_INTRA_CHROMA_PRED_MODE.len(), 3);
644- assert_eq!(TABLE_9_14_RQT_ROOT_CBF.len(), 2);
645- assert_eq!(TABLE_9_15_MERGE_FLAG.len(), 2);
646- assert_eq!(TABLE_9_16_MERGE_IDX.len(), 2);
647- assert_eq!(TABLE_9_17_INTER_PRED_IDC.len(), 10);
648- assert_eq!(TABLE_9_18_REF_IDX.len(), 4);
649- assert_eq!(TABLE_9_19_MVP_FLAG.len(), 2);
650- assert_eq!(TABLE_9_20_SPLIT_TRANSFORM_FLAG.len(), 9);
651- assert_eq!(TABLE_9_21_CBF_LUMA.len(), 6);
652- assert_eq!(TABLE_9_22_CBF_CHROMA.len(), 15);
653- assert_eq!(TABLE_9_23_ABS_MVD_GREATER_FLAG.len(), 4);
654- assert_eq!(TABLE_9_24_CU_QP_DELTA_ABS.len(), 6);
655- assert_eq!(TABLE_9_25_TRANSFORM_SKIP_FLAG.len(), 6);
656- assert_eq!(TABLE_9_26_LAST_SIG_COEFF_X_PREFIX.len(), 54);
657- assert_eq!(TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX.len(), 54);
658- assert_eq!(TABLE_9_28_CODED_SUB_BLOCK_FLAG.len(), 12);
659- assert_eq!(TABLE_9_29_SIG_COEFF_FLAG.len(), 132);
660- assert_eq!(TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG.len(), 72);
661- assert_eq!(TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG.len(), 18);
662- assert_eq!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.len(), 4);
663- assert_eq!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.len(), 4);
664- assert_eq!(TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG.len(), 3);
665- assert_eq!(TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX.len(), 3);
666- assert_eq!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1.len(), 24);
667- assert_eq!(TABLE_9_37_RES_SCALE_SIGN_FLAG.len(), 6);
668- assert_eq!(TABLE_9_38_PALETTE_MODE_FLAG.len(), 3);
669- assert_eq!(TABLE_9_39_TU_RESIDUAL_ACT_FLAG.len(), 3);
670- assert_eq!(TABLE_9_40_PALETTE_RUN_PREFIX.len(), 24);
671- assert_eq!(TABLE_9_41_PALETTE_COPY_ABOVE_FLAG.len(), 3);
672- assert_eq!(TABLE_9_42_PALETTE_TRANSPOSE_FLAG.len(), 3);
673- // The all-154 tables really are uniform.
674- assert!(TABLE_9_24_CU_QP_DELTA_ABS.iter().all(|&v| v == 154));
675- assert!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1
676- .iter()
677- .all(|&v| v == 154));
678- assert!(TABLE_9_37_RES_SCALE_SIGN_FLAG.iter().all(|&v| v == 154));
679- assert!(TABLE_9_40_PALETTE_RUN_PREFIX.iter().all(|&v| v == 154));
680- // The all-139 tables (transform-skip / RDPCM group).
681- assert!(TABLE_9_25_TRANSFORM_SKIP_FLAG.iter().all(|&v| v == 139));
682- assert!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.iter().all(|&v| v == 139));
683- assert!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.iter().all(|&v| v == 139));
684- }
685-
686- /// Tables 9-26 and 9-27 print identical values (the elements still
687- /// adapt independent variables).
688- #[test]
689- fn last_sig_coeff_tables_print_identically() {
690- assert_eq!(
691- TABLE_9_26_LAST_SIG_COEFF_X_PREFIX,
692- TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX
693- );
694- }
695-
696- fn cm(p_state_idx: u8, val_mps: u8) -> ContextModel {
697- ContextModel {
698- p_state_idx,
699- val_mps,
700- }
701- }
702-
703- /// §9.3.2.2 derived `(pStateIdx, valMps)` pins across QPs for
704- /// elements drawn from regular three-`initType` tables. Expected
705- /// values hand-evaluated from equations 9-4..9-6 on the cited
706- /// table entries.
707- #[test]
708- fn derived_state_pins_uniform_tables() {
709- // Table 9-7 `split_cu_flag`, initType 0 slot 0 (initValue 139).
710- assert_eq!(SliceContexts::init(0, 0).split_cu_flag[0], cm(8, 1));
711- assert_eq!(SliceContexts::init(0, 26).split_cu_flag[0], cm(0, 0));
712- assert_eq!(SliceContexts::init(0, 51).split_cu_flag[0], cm(7, 0));
713- // Table 9-7 `split_cu_flag`, initType 2 slot 0 (initValue 107).
714- assert_eq!(SliceContexts::init(2, 17).split_cu_flag[0], cm(7, 0));
715- assert_eq!(SliceContexts::init(2, 26).split_cu_flag[0], cm(16, 0));
716- assert_eq!(SliceContexts::init(2, 51).split_cu_flag[0], cm(39, 0));
717- // Table 9-6 `sao_type_idx`, initType 0 (initValue 200): the
718- // valMps flip across the QP range.
719- assert_eq!(SliceContexts::init(0, 0).sao_type_idx[0], cm(15, 0));
720- assert_eq!(SliceContexts::init(0, 26).sao_type_idx[0], cm(8, 1));
721- assert_eq!(SliceContexts::init(0, 51).sao_type_idx[0], cm(31, 1));
722- // Table 9-6 `sao_type_idx`, initType 2 (initValue 160):
723- // slopeIdx 10 ⇒ m == 5; the state barely moves with QP.
724- assert_eq!(SliceContexts::init(2, 0).sao_type_idx[0], cm(62, 0));
725- assert_eq!(SliceContexts::init(2, 51).sao_type_idx[0], cm(62, 0));
726- // Table 9-20 `split_transform_flag`, initType 2 slot 0
727- // (initValue 224).
728- assert_eq!(SliceContexts::init(2, 0).split_transform_flag[0], cm(62, 0));
729- assert_eq!(
730- SliceContexts::init(2, 37).split_transform_flag[0],
731- cm(22, 0)
732- );
733- assert_eq!(SliceContexts::init(2, 51).split_transform_flag[0], cm(0, 0));
734- // Table 9-21 `cbf_luma`, initType 0 slot 0 (initValue 111).
735- assert_eq!(SliceContexts::init(0, 17).cbf_luma[0], cm(24, 1));
736- assert_eq!(SliceContexts::init(0, 51).cbf_luma[0], cm(7, 0));
737- // QP clamp (equation 9-6 Clip3( 0, 51, SliceQpY )): out-of-range
738- // QPs pin to the endpoints.
739- assert_eq!(
740- SliceContexts::init(0, -7).cbf_luma[0],
741- SliceContexts::init(0, 0).cbf_luma[0]
742- );
743- assert_eq!(
744- SliceContexts::init(0, 60).cbf_luma[0],
745- SliceContexts::init(0, 51).cbf_luma[0]
746- );
747- }
748-
749- /// Pins for the inter-only banks (Table 9-4 `initType` 1 / 2
750- /// columns).
751- #[test]
752- fn derived_state_pins_inter_tables() {
753- // Table 9-9 `cu_skip_flag`, initType 1 slot 0 (initValue 197).
754- assert_eq!(SliceContexts::init(1, 17).cu_skip_flag[0], cm(24, 0));
755- assert_eq!(SliceContexts::init(1, 26).cu_skip_flag[0], cm(15, 0));
756- assert_eq!(SliceContexts::init(1, 51).cu_skip_flag[0], cm(7, 1));
757- // Table 9-16 `merge_idx`, initType 1 (initValue 122).
758- assert_eq!(SliceContexts::init(1, 0).merge_idx[0], cm(0, 1));
759- assert_eq!(SliceContexts::init(1, 26).merge_idx[0], cm(16, 0));
760- assert_eq!(SliceContexts::init(1, 51).merge_idx[0], cm(31, 0));
761- // Table 9-17 `inter_pred_idc`, initType 1 slot 0 (initValue 95).
762- assert_eq!(SliceContexts::init(1, 26).inter_pred_idc[0], cm(7, 1));
763- assert_eq!(SliceContexts::init(1, 51).inter_pred_idc[0], cm(23, 0));
764- // The initType 2 column starts at the table's second span:
765- // Table 9-17 ctxIdx 5 also holds 95.
766- assert_eq!(
767- SliceContexts::init(2, 26).inter_pred_idc[0],
768- SliceContexts::init(1, 26).inter_pred_idc[0]
769- );
770- // Table 9-23 interleave: `abs_mvd_greater0_flag` initType 2
771- // reads ctxIdx 2 (initValue 169), `abs_mvd_greater1_flag`
772- // initType 1 reads ctxIdx 1 (initValue 198).
773- assert_eq!(
774- SliceContexts::init(2, 26).abs_mvd_greater0_flag[0],
775- cm(0, 1)
776- );
777- assert_eq!(
778- SliceContexts::init(2, 51).abs_mvd_greater0_flag[0],
779- cm(7, 1)
780- );
781- assert_eq!(
782- SliceContexts::init(1, 26).abs_mvd_greater1_flag[0],
783- cm(7, 0)
784- );
785- assert_eq!(
786- SliceContexts::init(1, 51).abs_mvd_greater1_flag[0],
787- cm(15, 1)
788- );
789- }
790-
791- /// Pins for the irregular Table 9-4 layouts (`part_mode`,
792- /// `cbf_cb`/`cbf_cr`).
793- #[test]
794- fn derived_state_pins_irregular_tables() {
795- // Table 9-11 `part_mode` initType 0: only ctxIdx 0
796- // (initValue 184) is initialized; slots 1..3 take the
797- // non-adapting placeholder.
798- let i_slice = SliceContexts::init(0, 26);
799- assert_eq!(i_slice.part_mode[0], cm(0, 1));
800- for slot in 1..4 {
801- assert_eq!(i_slice.part_mode[slot], ContextModel::terminate_state());
802- }
803- assert_eq!(SliceContexts::init(0, 0).part_mode[0], cm(15, 0));
804- assert_eq!(SliceContexts::init(0, 51).part_mode[0], cm(15, 1));
805- // `part_mode` initType 1 slot 1 reads Table 9-11 ctxIdx 2
806- // (initValue 139); initType 2 slot 1 reads ctxIdx 6 (also 139).
807- assert_eq!(SliceContexts::init(1, 26).part_mode[1], cm(0, 0));
808- assert_eq!(
809- SliceContexts::init(2, 26).part_mode[1],
810- SliceContexts::init(1, 26).part_mode[1]
811- );
812- // Table 9-22 `cbf_cb`/`cbf_cr` initType 0: slot 0 reads ctxIdx 0
813- // (initValue 94), slot 4 reads ctxIdx 12 (initValue 154).
814- assert_eq!(SliceContexts::init(0, 0).cbf_chroma[0], cm(32, 1));
815- assert_eq!(SliceContexts::init(0, 26).cbf_chroma[0], cm(0, 0));
816- assert_eq!(SliceContexts::init(0, 51).cbf_chroma[0], cm(31, 0));
817- for qp in [0, 26, 51] {
818- // initValue 154 ⇒ m == 0, n == 64 ⇒ preCtxState == 64 at
819- // every QP: pStateIdx 0, valMps 1.
820- assert_eq!(SliceContexts::init(0, qp).cbf_chroma[4], cm(0, 1));
821- }
822- // Table 9-25 `transform_skip_flag` (initValue 139 everywhere):
823- // luma and chroma slots agree at each initType.
824- let b = SliceContexts::init(2, 26);
825- assert_eq!(b.transform_skip_flag[0], b.transform_skip_flag[1]);
826- assert_eq!(b.transform_skip_flag[0], cm(0, 0));
827- }
828-
829- /// Whole-array smoke test per `initType`: every table-derived
830- /// context lands in the equations-9-4..9-6 range
831- /// (`pStateIdx <= 62`), and the `initType == 0` placeholder
832- /// (`pStateIdx == 63`) appears exactly on the inter-only banks.
833- #[test]
834- fn whole_array_smoke_per_init_type() {
835- for init_type in 0u8..=2 {
836- for qp in [0, 26, 51] {
837- let ctx = SliceContexts::init(init_type, qp);
838- let inter_only: Vec<&[ContextModel]> = vec![
839- &ctx.cu_skip_flag,
840- &ctx.pred_mode_flag,
841- &ctx.rqt_root_cbf,
842- &ctx.merge_flag,
843- &ctx.merge_idx,
844- &ctx.inter_pred_idc,
845- &ctx.ref_idx,
846- &ctx.mvp_flag,
847- &ctx.abs_mvd_greater0_flag,
848- &ctx.abs_mvd_greater1_flag,
849- &ctx.explicit_rdpcm_flag,
850- &ctx.explicit_rdpcm_dir_flag,
851- ];
852- let every_type: Vec<&[ContextModel]> = vec![
853- &ctx.sao_merge_flag,
854- &ctx.sao_type_idx,
855- &ctx.split_cu_flag,
856- &ctx.cu_transquant_bypass_flag,
857- &ctx.palette_mode_flag,
858- &ctx.prev_intra_luma_pred_flag,
859- &ctx.intra_chroma_pred_mode,
860- &ctx.split_transform_flag,
861- &ctx.cbf_luma,
862- &ctx.cbf_chroma,
863- &ctx.tu_residual_act_flag,
864- &ctx.log2_res_scale_abs_plus1,
865- &ctx.res_scale_sign_flag,
866- &ctx.transform_skip_flag,
867- &ctx.residual.last_sig_coeff_x_prefix,
868- &ctx.residual.last_sig_coeff_y_prefix,
869- &ctx.residual.coded_sub_block_flag,
870- &ctx.residual.sig_coeff_flag,
871- &ctx.residual.coeff_abs_level_greater1_flag,
872- &ctx.residual.coeff_abs_level_greater2_flag,
873- &ctx.palette_run_prefix,
874- &ctx.palette_copy_above_flag,
875- &ctx.palette_transpose_flag,
876- &ctx.cu_qp_delta_abs,
877- &ctx.cu_chroma_qp_offset_flag,
878- &ctx.cu_chroma_qp_offset_idx,
879- ];
880- let mut total = 0usize;
881- for bank in &every_type {
882- for c in bank.iter() {
883- assert!(c.p_state_idx <= 62, "table-derived state out of range");
884- assert!(c.val_mps <= 1);
885- total += 1;
886- }
887- }
888- // `part_mode` slot 0 is table-derived at every
889- // initType; slots 1..3 only for initType 1 / 2.
890- assert!(ctx.part_mode[0].p_state_idx <= 62);
891- total += 4;
892- for bank in &inter_only {
893- for c in bank.iter() {
894- if init_type == 0 {
895- assert_eq!(*c, ContextModel::terminate_state());
896- } else {
897- assert!(c.p_state_idx <= 62);
898- }
899- total += 1;
900- }
901- }
902- if init_type == 0 {
903- for slot in 1..4 {
904- assert_eq!(ctx.part_mode[slot], ContextModel::terminate_state());
905- }
906- } else {
907- for slot in 1..4 {
908- assert!(ctx.part_mode[slot].p_state_idx <= 62);
909- }
910- }
911- assert_eq!(total, SliceContexts::CONTEXT_COUNT);
912- }
913- }
914- }
915-
916- /// Equation 9-7 routing through [`SliceContexts::for_slice`]: the
917- /// `cabac_init_flag` swap between P and B, and its irrelevance for
918- /// I slices.
919- #[test]
920- fn for_slice_eq_9_7_routing() {
921- let qp = 30;
922- assert_eq!(
923- SliceContexts::for_slice(SliceType::I, false, qp),
924- SliceContexts::init(0, qp)
925- );
926- assert_eq!(
927- SliceContexts::for_slice(SliceType::I, true, qp),
928- SliceContexts::init(0, qp)
929- );
930- assert_eq!(
931- SliceContexts::for_slice(SliceType::P, false, qp),
932- SliceContexts::init(1, qp)
933- );
934- assert_eq!(
935- SliceContexts::for_slice(SliceType::P, true, qp),
936- SliceContexts::init(2, qp)
937- );
938- assert_eq!(
939- SliceContexts::for_slice(SliceType::B, false, qp),
940- SliceContexts::init(2, qp)
941- );
942- assert_eq!(
943- SliceContexts::for_slice(SliceType::B, true, qp),
944- SliceContexts::init(1, qp)
945- );
946- // P with the flag and B without select the same array; P
947- // without and B with likewise.
948- assert_eq!(
949- SliceContexts::for_slice(SliceType::P, true, qp),
950- SliceContexts::for_slice(SliceType::B, false, qp)
951- );
952- assert_eq!(
953- SliceContexts::for_slice(SliceType::P, false, qp),
954- SliceContexts::for_slice(SliceType::B, true, qp)
955- );
956- // The three initTypes produce three distinct arrays.
957- assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(1, qp));
958- assert_ne!(SliceContexts::init(1, qp), SliceContexts::init(2, qp));
959- assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(2, qp));
960- }
961-
962- /// The span-selection helpers reject malformed inputs and slice
963- /// the right ctxIdx ranges.
964- #[test]
965- fn span_selection_helpers() {
966- assert_eq!(
967- uniform_init_values::<3>(&TABLE_9_7_SPLIT_CU_FLAG, 1),
968- [107, 139, 126]
969- );
970- assert_eq!(
971- inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 2),
972- Some([197, 185, 201])
973- );
974- assert_eq!(inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 0), None);
975- let sig0 = sig_coeff_flag_init_values(0);
976- assert_eq!(sig0[0], 111);
977- assert_eq!(sig0[41], 111);
978- // The transform-skip tail: Table 9-29 ctxIdx 126 / 127.
979- assert_eq!(sig0[42], 141);
980- assert_eq!(sig0[43], 111);
981- let sig1 = sig_coeff_flag_init_values(1);
982- assert_eq!(sig1[0], 155);
983- assert_eq!(sig1[41], 140);
984- let sig2 = sig_coeff_flag_init_values(2);
985- assert_eq!(sig2[0], 170);
986- assert_eq!(sig2[41], 140);
987- }
988-
989- #[test]
990- #[should_panic(expected = "initType must be 0, 1 or 2")]
991- fn init_rejects_init_type_3() {
992- let _ = SliceContexts::init(3, 26);
993- }
994-}
vendor/oxideav-h265/src/deblock.rsdeleted+0 -2484

Diff too large; view file

@@ -1,2484 +0,0 @@
1-//! §8.7.2.4 — derivation of the deblocking boundary filtering strength.
2-//!
3-//! The deblocking filter (§8.7.2) operates on an 8×8 luma grid: vertical
4-//! edges first, then horizontal edges. For each candidate edge segment
5-//! the boundary filtering strength `bS ∈ {0, 1, 2}` is derived per
6-//! §8.7.2.4 from the intra/inter mode, the transform coded-block flags,
7-//! and the motion vectors / reference pictures of the two prediction
8-//! blocks straddling the edge. This module implements that derivation —
9-//! [`derive_boundary_strength`] — reading the per-4×4-block motion / mode
10-//! state from a [`crate::motion::MotionField`].
11-//!
12-//! The §8.7.2.2 / §8.7.2.3 edge-flag derivation (which marks the
13-//! transform-block / prediction-block boundaries an edge falls on, from
14-//! the coding / transform tree geometry) is the input `edgeFlags` array;
15-//! producing it from the decoded partition tree is the picture driver's
16-//! follow-up. The §8.7.2.5 edge filtering process (the actual sample
17-//! modification using `bS`, `β` and `tC`) is implemented by the
18-//! per-sample primitives [`luma_beta_tc`] (§8.7.2.5.3 β/tC, Table 8-12
19-//! via [`beta_prime`] / [`tc_prime`]), [`luma_sample_decision`]
20-//! (§8.7.2.5.6), [`luma_edge_decision`] (§8.7.2.5.3 `dE`/`dEp`/`dEq`)
21-//! and [`filter_luma_sample`] (§8.7.2.5.7 strong/weak), plus the chroma
22-//! path [`chroma_tc`] (§8.7.2.5.5, Table 8-10 via [`chroma_qpc_420`])
23-//! and [`filter_chroma_sample`] (§8.7.2.5.8). The plane-level block-edge
24-//! drivers [`filter_luma_block_edge`] (§8.7.2.5.4) and
25-//! [`filter_chroma_block_edge`] (§8.7.2.5.5) gather/apply those
26-//! primitives across a 4-row edge segment of a [`SamplePlane`] in place.
27-
28-use crate::binarization::PartMode;
29-use crate::motion::MotionField;
30-use crate::picture::{sub_wh_c, Picture, Plane};
31-
32-/// §8.7.2.1 — the edge orientation being filtered.
33-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34-pub enum EdgeType {
35- /// `EDGE_VER` — a vertical edge (filtered left-to-right).
36- Vertical,
37- /// `EDGE_HOR` — a horizontal edge (filtered top-to-bottom).
38- Horizontal,
39-}
40-
41-/// The transform-tree split geometry of one luma coding block, used by the
42-/// §8.7.2.2 edge-flag derivation.
43-///
44-/// Each node is either a `Split` (a `split_transform_flag == 1` node whose
45-/// four quadrants recurse) or a `Leaf` (a `split_transform_flag == 0`
46-/// transform block). The deblocker only needs the split structure, not the
47-/// residual coefficients — the leaves mark where transform-block edges
48-/// fall on the 8×8 grid.
49-#[derive(Debug, Clone, PartialEq, Eq)]
50-pub enum TransformSplit {
51- /// A `split_transform_flag == 1` node: four quadrants in raster order
52- /// (top-left, top-right, bottom-left, bottom-right), each spanning
53- /// `1 << (log2TrafoSize − 1)` luma samples.
54- Split(Box<[TransformSplit; 4]>),
55- /// A `split_transform_flag == 0` transform-block leaf.
56- Leaf,
57-}
58-
59-impl TransformSplit {
60- /// A leaf spanning the whole coding block (no transform split).
61- #[inline]
62- #[must_use]
63- pub fn leaf() -> Self {
64- TransformSplit::Leaf
65- }
66-
67- /// A single-level split into four equal quadrants, each a leaf.
68- #[inline]
69- #[must_use]
70- pub fn split_once() -> Self {
71- TransformSplit::Split(Box::new([
72- TransformSplit::Leaf,
73- TransformSplit::Leaf,
74- TransformSplit::Leaf,
75- TransformSplit::Leaf,
76- ]))
77- }
78-
79- /// Map a parsed §7.3.8.8 [`crate::transform_tree::TransformTree`] to the
80- /// deblocking transform-split structure the §8.7.2.2 transform-block
81- /// boundary recursion consumes (only the split topology matters, not the
82- /// per-leaf residual). A CU with no transform tree (skip / `rqt_root_cbf
83- /// == 0`) is a single whole-CB leaf.
84- #[must_use]
85- pub fn from_tree(tree: Option<&crate::transform_tree::TransformTree>) -> Self {
86- use crate::transform_tree::TransformTree;
87- match tree {
88- None | Some(TransformTree::Leaf { .. }) => TransformSplit::Leaf,
89- Some(TransformTree::Split { children, .. }) => TransformSplit::Split(Box::new([
90- Self::from_tree(Some(&children[0])),
91- Self::from_tree(Some(&children[1])),
92- Self::from_tree(Some(&children[2])),
93- Self::from_tree(Some(&children[3])),
94- ])),
95- }
96- }
97-}
98-
99-/// The invariant context threaded through the §8.7.2.2 recursion.
100-struct TbBoundaryCtx<'a> {
101- filter_edge_flag: bool,
102- edge_type: EdgeType,
103- n_cbs: usize,
104- edge_flags: &'a mut [bool],
105- tb_edge: &'a mut [bool],
106-}
107-
108-/// §8.7.2.2 transform-block-boundary recursion: walk one node of the
109-/// transform tree, marking the `edge_flags` (any block boundary the edge
110-/// falls on) and `tb_edge` (transform-block boundaries only) grids.
111-///
112-/// `(xb0, yb0)` is the node's top-left luma sample relative to the coding
113-/// block; `log2_trafo_size` is the node side. The `ctx.filter_edge_flag`
114-/// is the §8.7.2.1 `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` that
115-/// gates the coding-block boundary (xB0/yB0 == 0) edge.
116-fn transform_block_boundary(
117- node: &TransformSplit,
118- xb0: usize,
119- yb0: usize,
120- log2_trafo_size: u32,
121- ctx: &mut TbBoundaryCtx<'_>,
122-) {
123- if let TransformSplit::Split(children) = node {
124- let half = 1usize << (log2_trafo_size - 1);
125- let xb1 = xb0 + half;
126- let yb1 = yb0 + half;
127- let quad_origins = [(xb0, yb0), (xb1, yb0), (xb0, yb1), (xb1, yb1)];
128- for (child, &(cx, cy)) in children.iter().zip(quad_origins.iter()) {
129- transform_block_boundary(child, cx, cy, log2_trafo_size - 1, ctx);
130- }
131- return;
132- }
133- // Leaf: mark the leading edge of this transform block. EDGE_VER marks
134- // the column xB0 for k = 0..size; EDGE_HOR marks the row yB0.
135- let size = 1usize << log2_trafo_size;
136- let n_cbs = ctx.n_cbs;
137- match ctx.edge_type {
138- EdgeType::Vertical => {
139- // edgeFlags[xB0][yB0+k]: filterEdgeFlag at the CB boundary
140- // (xB0 == 0), else 1.
141- let val = if xb0 == 0 { ctx.filter_edge_flag } else { true };
142- for k in 0..size {
143- let idx = (yb0 + k) * n_cbs + xb0;
144- ctx.edge_flags[idx] = val;
145- ctx.tb_edge[idx] = val;
146- }
147- }
148- EdgeType::Horizontal => {
149- let val = if yb0 == 0 { ctx.filter_edge_flag } else { true };
150- for k in 0..size {
151- let idx = yb0 * n_cbs + (xb0 + k);
152- ctx.edge_flags[idx] = val;
153- ctx.tb_edge[idx] = val;
154- }
155- }
156- }
157-}
158-
159-/// §8.7.2.3 prediction-block-boundary derivation: mark the internal
160-/// prediction-partition edge of a coding block into `edge_flags` (a
161-/// prediction edge is *not* a transform-block edge, so `tb_edge` is left
162-/// untouched).
163-fn prediction_block_boundary(
164- part_mode: PartMode,
165- log2_cb_size: u32,
166- edge_type: EdgeType,
167- n_cbs: usize,
168- edge_flags: &mut [bool],
169-) {
170- // The internal partition column (EDGE_VER) / row (EDGE_HOR), if any.
171- let half = 1usize << (log2_cb_size - 1);
172- let quarter = 1usize << (log2_cb_size.saturating_sub(2));
173- let pos = match (edge_type, part_mode) {
174- (EdgeType::Vertical, PartMode::PartNx2N | PartMode::PartNxN) => Some(half),
175- (EdgeType::Vertical, PartMode::PartNLx2N) => Some(quarter),
176- (EdgeType::Vertical, PartMode::PartNRx2N) => Some(3 * quarter),
177- (EdgeType::Horizontal, PartMode::Part2NxN | PartMode::PartNxN) => Some(half),
178- (EdgeType::Horizontal, PartMode::Part2NxnU) => Some(quarter),
179- (EdgeType::Horizontal, PartMode::Part2NxnD) => Some(3 * quarter),
180- _ => None,
181- };
182- if let Some(p) = pos {
183- for k in 0..n_cbs {
184- let idx = match edge_type {
185- EdgeType::Vertical => k * n_cbs + p,
186- EdgeType::Horizontal => p * n_cbs + k,
187- };
188- edge_flags[idx] = true;
189- }
190- }
191-}
192-
193-/// The §8.7.2.2 / §8.7.2.3 edge-flag grids for one coding block.
194-#[derive(Debug, Clone, PartialEq, Eq)]
195-pub struct EdgeFlags {
196- n_cbs: usize,
197- /// Row-major `n_cbs²`, `true` where a transform / prediction block
198- /// boundary falls (the §8.7.2.4 bS input).
199- edge_flags: Vec<bool>,
200- /// Row-major `n_cbs²`, `true` where the edge is *also* a
201- /// transform-block boundary (the §8.7.2.4 second-bullet `cbf` test).
202- tb_edge: Vec<bool>,
203-}
204-
205-impl EdgeFlags {
206- /// The `edge_flags` grid (row-major, `[y * nCbS + x]`).
207- #[inline]
208- #[must_use]
209- pub fn edge_flags(&self) -> &[bool] {
210- &self.edge_flags
211- }
212-
213- /// The `tb_edge` grid (row-major, `[y * nCbS + x]`).
214- #[inline]
215- #[must_use]
216- pub fn tb_edge(&self) -> &[bool] {
217- &self.tb_edge
218- }
219-
220- /// `edge_flags[x][y]`.
221- #[inline]
222- #[must_use]
223- pub fn edge_at(&self, x: usize, y: usize) -> bool {
224- self.edge_flags[y * self.n_cbs + x]
225- }
226-
227- /// `tb_edge[x][y]`.
228- #[inline]
229- #[must_use]
230- pub fn tb_at(&self, x: usize, y: usize) -> bool {
231- self.tb_edge[y * self.n_cbs + x]
232- }
233-}
234-
235-/// §8.7.2.2 + §8.7.2.3 — derive the `edge_flags` + `tb_edge` grids for one
236-/// coding block in one edge direction.
237-///
238-/// `transform_split` is the coding block's transform-tree split geometry
239-/// ([`TransformSplit`]); `part_mode` is the prediction `PartMode`;
240-/// `log2_cb_size` is the luma coding-block side; `filter_edge_flag` is the
241-/// §8.7.2.1 `filterLeftCbEdgeFlag` (EDGE_VER) / `filterTopCbEdgeFlag`
242-/// (EDGE_HOR) gating the coding-block boundary edge.
243-///
244-/// The result feeds [`derive_boundary_strength`] (`edge_flags` + `tb_edge`)
245-/// and, after bS, the §8.7.2.5.1 / .2 CU edge filtering driver.
246-#[must_use]
247-pub fn derive_edge_flags(
248- transform_split: &TransformSplit,
249- part_mode: PartMode,
250- log2_cb_size: u32,
251- edge_type: EdgeType,
252- filter_edge_flag: bool,
253-) -> EdgeFlags {
254- let n_cbs = 1usize << log2_cb_size;
255- let mut edge_flags = vec![false; n_cbs * n_cbs];
256- let mut tb_edge = vec![false; n_cbs * n_cbs];
257- {
258- let mut ctx = TbBoundaryCtx {
259- filter_edge_flag,
260- edge_type,
261- n_cbs,
262- edge_flags: &mut edge_flags,
263- tb_edge: &mut tb_edge,
264- };
265- transform_block_boundary(transform_split, 0, 0, log2_cb_size, &mut ctx);
266- }
267- prediction_block_boundary(part_mode, log2_cb_size, edge_type, n_cbs, &mut edge_flags);
268- EdgeFlags {
269- n_cbs,
270- edge_flags,
271- tb_edge,
272- }
273-}
274-
275-/// The §8.7.2.4 boundary filtering strength for one CU's edges, a
276-/// `(nCbS)×(nCbS)` grid indexed in luma samples (only the §8.7.2.4
277-/// sampled positions `xDi`/`yDj` carry meaningful values; the rest are 0).
278-#[derive(Debug, Clone, PartialEq, Eq)]
279-pub struct BoundaryStrength {
280- n_cbs: usize,
281- /// Row-major `n_cbs * n_cbs`, `bs[y * n_cbs + x]`.
282- bs: Vec<u8>,
283-}
284-
285-impl BoundaryStrength {
286- /// `bS[x][y]` at luma offset `(x, y)` within the coding block.
287- ///
288- /// # Panics
289- /// Panics if `(x, y)` lies outside the `(nCbS)×(nCbS)` block.
290- #[must_use]
291- pub fn at(&self, x: usize, y: usize) -> u8 {
292- self.bs[y * self.n_cbs + x]
293- }
294-
295- /// The coding-block side `nCbS` in luma samples.
296- #[inline]
297- #[must_use]
298- pub fn n_cbs(&self) -> usize {
299- self.n_cbs
300- }
301-}
302-
303-/// Whether the §8.7.2.4 "different reference pictures or different number
304-/// of motion vectors" predicate holds between the p- and q-side blocks.
305-///
306-/// The reference-picture comparison uses the picture identities
307-/// (`ref_poc_lX`), not the `RefIdxLX` list positions, and is order- and
308-/// list-independent (spec NOTE 1): block p uses reference-picture set
309-/// `{ p.l0?, p.l1? }`, block q uses `{ q.l0?, q.l1? }`.
310-fn different_refs_or_count(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool {
311- let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1);
312- let q_count = u8::from(q.pred_flag_l0) + u8::from(q.pred_flag_l1);
313- if p_count != q_count {
314- return true;
315- }
316- // Compare the *sets* of reference pictures (POCs), list-independent.
317- let mut p_refs = Vec::new();
318- if p.pred_flag_l0 {
319- p_refs.push(p.ref_poc_l0);
320- }
321- if p.pred_flag_l1 {
322- p_refs.push(p.ref_poc_l1);
323- }
324- let mut q_refs = Vec::new();
325- if q.pred_flag_l0 {
326- q_refs.push(q.ref_poc_l0);
327- }
328- if q.pred_flag_l1 {
329- q_refs.push(q.ref_poc_l1);
330- }
331- p_refs.sort_unstable();
332- q_refs.sort_unstable();
333- p_refs != q_refs
334-}
335-
336-/// `|a − b| >= 4` on either component (the §8.7.2.4 quarter-luma-sample
337-/// MV-difference test).
338-#[inline]
339-fn mv_diff_ge4(a: [i32; 2], b: [i32; 2]) -> bool {
340- (a[0] - b[0]).abs() >= 4 || (a[1] - b[1]).abs() >= 4
341-}
342-
343-/// §8.7.2.4 motion-only bS test for two inter prediction blocks `p` / `q`
344-/// (the third bullet onward: same/different references, MV differences).
345-/// Returns `true` when bS should be 1 on motion grounds.
346-fn motion_bs_is_one(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool {
347- // Bullet 1: different reference pictures or different number of MVs.
348- if different_refs_or_count(p, q) {
349- return true;
350- }
351-
352- let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1);
353-
354- // Bullet 2: one MV each, |Δmv| >= 4.
355- if p_count == 1 {
356- let pmv = if p.pred_flag_l0 { p.mv_l0 } else { p.mv_l1 };
357- let qmv = if q.pred_flag_l0 { q.mv_l0 } else { q.mv_l1 };
358- return mv_diff_ge4(pmv, qmv);
359- }
360-
361- // Two MVs each (p_count == 2). The reference-picture sets are equal
362- // (different_refs_or_count returned false).
363- if p.ref_poc_l0 != p.ref_poc_l1 {
364- // Bullet 3: two different reference pictures. Match each list to
365- // the q-side list referencing the same picture.
366- // p.l0 ↔ q.(list with same poc as p.l0), p.l1 ↔ the other.
367- let (q0, q1) = if q.ref_poc_l0 == p.ref_poc_l0 {
368- (q.mv_l0, q.mv_l1)
369- } else {
370- (q.mv_l1, q.mv_l0)
371- };
372- mv_diff_ge4(p.mv_l0, q0) || mv_diff_ge4(p.mv_l1, q1)
373- } else {
374- // Bullet 4: both MVs use the same reference picture. bS = 1 iff
375- // (|Δl0| or |Δl1| >= 4) AND (|p.l0−q.l1| or |p.l1−q.l0| >= 4).
376- let straight = mv_diff_ge4(p.mv_l0, q.mv_l0) || mv_diff_ge4(p.mv_l1, q.mv_l1);
377- let crossed = mv_diff_ge4(p.mv_l0, q.mv_l1) || mv_diff_ge4(p.mv_l1, q.mv_l0);
378- straight && crossed
379- }
380-}
381-
382-/// §8.7.2.4 — derive the `(nCbS)×(nCbS)` boundary filtering strength grid
383-/// for one luma coding block.
384-///
385-/// Inputs:
386-/// * `field` — the picture's per-4×4-block motion / mode store
387-/// ([`MotionField`]); the p / q sample look-ups read from it.
388-/// * `(x_cb, y_cb)` — the coding block's luma top-left position.
389-/// * `log2_cb_size` — the coding-block side `log2CbSize`.
390-/// * `edge_type` — `EDGE_VER` or `EDGE_HOR`.
391-/// * `edge_flags` — the §8.7.2.2/§8.7.2.3 `(nCbS)×(nCbS)` edge-flag grid
392-/// (row-major, `edge_flags[y * nCbS + x]`), `true` where a transform /
393-/// prediction block boundary falls.
394-/// * `tb_edge` — `(nCbS)×(nCbS)` grid, `true` where the edge at that
395-/// position is *also* a transform-block edge (the §8.7.2.4 second
396-/// bullet `cbf` test only fires on transform-block edges).
397-///
398-/// The bS at every sampled `(xDi, yDj)` is 2 when either neighbouring
399-/// sample is intra; 1 when the edge is a transform-block edge and either
400-/// transform block holds a non-zero coefficient; 1 on the §8.7.2.4
401-/// motion criteria; otherwise 0. Positions not sampled by §8.7.2.4 are 0.
402-///
403-/// # Panics
404-/// Panics if `edge_flags` / `tb_edge` are not `(1 << log2_cb_size)`²
405-/// long, or if a sampled p / q location falls outside `field`.
406-pub fn derive_boundary_strength(
407- field: &MotionField,
408- x_cb: usize,
409- y_cb: usize,
410- log2_cb_size: u32,
411- edge_type: EdgeType,
412- edge_flags: &[bool],
413- tb_edge: &[bool],
414-) -> BoundaryStrength {
415- let n_cbs = 1usize << log2_cb_size;
416- assert_eq!(edge_flags.len(), n_cbs * n_cbs, "edge_flags is nCbS^2");
417- assert_eq!(tb_edge.len(), n_cbs * n_cbs, "tb_edge is nCbS^2");
418- let mut bs = vec![0u8; n_cbs * n_cbs];
419-
420- // §8.7.2.4 sampling grid: EDGE_VER strides 8 in x, 4 in y; EDGE_HOR
421- // strides 4 in x, 8 in y.
422- let (step_x, step_y) = match edge_type {
423- EdgeType::Vertical => (8usize, 4usize),
424- EdgeType::Horizontal => (4usize, 8usize),
425- };
426-
427- let mut y_dj = 0;
428- while y_dj < n_cbs {
429- let mut x_di = 0;
430- while x_di < n_cbs {
431- let idx = y_dj * n_cbs + x_di;
432- if edge_flags[idx] {
433- // p0 / q0 sample positions (§8.7.2.4).
434- let (px, py, qx, qy) = match edge_type {
435- EdgeType::Vertical => (x_cb + x_di - 1, y_cb + y_dj, x_cb + x_di, y_cb + y_dj),
436- EdgeType::Horizontal => {
437- (x_cb + x_di, y_cb + y_dj - 1, x_cb + x_di, y_cb + y_dj)
438- }
439- };
440- let p = field.cell_at(px, py);
441- let q = field.cell_at(qx, qy);
442-
443- // §8.7.2.4 cascade: intra ⇒ 2; else a coded-coeff
444- // transform-block edge OR the motion criteria ⇒ 1; else 0.
445- let coeff_edge = tb_edge[idx] && (p.has_nonzero_coeff || q.has_nonzero_coeff);
446- let val = if p.is_intra || q.is_intra {
447- 2
448- } else if coeff_edge || motion_bs_is_one(&p, &q) {
449- 1
450- } else {
451- 0
452- };
453- bs[idx] = val;
454- }
455- x_di += step_x;
456- }
457- y_dj += step_y;
458- }
459-
460- BoundaryStrength { n_cbs, bs }
461-}
462-
463-/// Table 8-12 — `β′` as a function of the input variable `Q` (0..=51).
464-///
465-/// The deblocking threshold `β′` is 0 for `Q < 16`, then rises in the
466-/// pattern documented in Table 8-12. `Q` outside `0..=51` returns the
467-/// boundary value (the callers clip `Q` to `0..=51` for `β′`, eq. 8-348).
468-#[must_use]
469-pub fn beta_prime(q: i32) -> i32 {
470- const BETA: [i32; 52] = [
471- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Q 0..15
472- 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, // Q 16..31
473- 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, // Q 32..47
474- 58, 60, 62, 64, // Q 48..51
475- ];
476- BETA[q.clamp(0, 51) as usize]
477-}
478-
479-/// Table 8-12 — `tC′` as a function of the input variable `Q` (0..=53).
480-///
481-/// The clipping threshold `tC′` is 0 for `Q <= 17`, `1` at `Q = 18`,
482-/// then rises per Table 8-12 up to `24` at `Q = 53`. `Q` outside
483-/// `0..=53` returns the boundary value (callers clip `Q` to `0..=53`,
484-/// eqs. 8-350 / 8-383).
485-#[must_use]
486-pub fn tc_prime(q: i32) -> i32 {
487- const TC: [i32; 54] = [
488- 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // Q 0..18
489- 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, // Q 19..37
490- 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, // Q 38..53
491- ];
492- TC[q.clamp(0, 53) as usize]
493-}
494-
495-/// §8.7.2.5.3 — derive `β` and `tC` for a luma block edge.
496-///
497-/// `qp_q` / `qp_p` are the `QpY` values of the coding units containing
498-/// the `q0,0` and `p0,0` samples; `bs` is the §8.7.2.4 boundary strength
499-/// (must be 1 or 2 for a filtered edge); `beta_offset_div2` /
500-/// `tc_offset_div2` are the per-slice `slice_beta_offset_div2` /
501-/// `slice_tc_offset_div2` syntax-element values; `bit_depth` is
502-/// `BitDepthY`.
503-///
504-/// Returns `(β, tC)` per eqs. 8-347..8-351.
505-#[must_use]
506-pub fn luma_beta_tc(
507- qp_q: i32,
508- qp_p: i32,
509- bs: u8,
510- beta_offset_div2: i32,
511- tc_offset_div2: i32,
512- bit_depth: u8,
513-) -> (i32, i32) {
514- let qp_l = (qp_q + qp_p + 1) >> 1; // eq. 8-347
515- let q_beta = (qp_l + (beta_offset_div2 << 1)).clamp(0, 51); // eq. 8-348
516- let beta = beta_prime(q_beta) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-349
517- let q_tc = (qp_l + 2 * (i32::from(bs) - 1) + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-350
518- let tc = tc_prime(q_tc) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-351
519- (beta, tc)
520-}
521-
522-/// §8.7.2.5.6 — decision process for a luma sample.
523-///
524-/// Returns `dSam`: `true` (1) when the long (strong) filter conditions
525-/// across `p0`/`p3`/`q0`/`q3` hold, given `dpq`, `β` and `tC`.
526-#[inline]
527-#[must_use]
528-pub fn luma_sample_decision(
529- p0: i32,
530- p3: i32,
531- q0: i32,
532- q3: i32,
533- dpq: i32,
534- beta: i32,
535- tc: i32,
536-) -> bool {
537- dpq < (beta >> 2)
538- && (p3 - p0).abs() + (q0 - q3).abs() < (beta >> 3)
539- && (p0 - q0).abs() < (5 * tc + 1) >> 1
540-}
541-
542-/// Decisions emitted by the §8.7.2.5.3 luma edge decision process for a
543-/// 4-row edge segment.
544-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
545-pub struct LumaEdgeDecision {
546- /// `dE`: 0 = no filtering, 1 = weak (normal), 2 = strong (long).
547- pub de: u8,
548- /// `dEp`: when 1, the `p1` sample is also filtered (weak filter).
549- pub dep: u8,
550- /// `dEq`: when 1, the `q1` sample is also filtered (weak filter).
551- pub deq: u8,
552- /// `β` (eq. 8-349).
553- pub beta: i32,
554- /// `tC` (eq. 8-351).
555- pub tc: i32,
556-}
557-
558-/// The result of §8.7.2.5.7 luma-sample filtering for one boundary row.
559-///
560-/// `p[i]` / `q[i]` are the filtered sample values (`pi'` / `qj'`); only
561-/// the first `ndp` `p[]` and `ndq` `q[]` entries are valid replacements
562-/// for the input samples.
563-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
564-pub struct LumaFilterOut {
565- /// `nDp` — number of filtered samples on the p side (0..=3).
566- pub ndp: usize,
567- /// `nDq` — number of filtered samples on the q side (0..=3).
568- pub ndq: usize,
569- /// `p0'`, `p1'`, `p2'` (only `0..ndp` valid).
570- pub p: [i32; 3],
571- /// `q0'`, `q1'`, `q2'` (only `0..ndq` valid).
572- pub q: [i32; 3],
573-}
574-
575-/// §8.7.2.5.7 — filtering process for a luma sample row.
576-///
577-/// `p` / `q` are the four samples each side of the boundary (`p[0]` is
578-/// `p0`, closest to the edge); `dec` carries `dE` / `dEp` / `dEq` and
579-/// `tC`; `bit_depth` is `BitDepthY` for the final `Clip1Y`.
580-///
581-/// Strong filtering (`dE == 2`) writes `p0'..p2'` / `q0'..q2'`; weak
582-/// filtering (`dE == 1`) writes `p0'` (+`p1'` when `dEp`) and `q0'`
583-/// (+`q1'` when `dEq`). The PCM / transquant-bypass / palette
584-/// suppressions are applied by the caller (they need per-CU state).
585-#[must_use]
586-pub fn filter_luma_sample(
587- p: [i32; 4],
588- q: [i32; 4],
589- de: u8,
590- dep: u8,
591- deq: u8,
592- tc: i32,
593- bit_depth: u8,
594-) -> LumaFilterOut {
595- let [p0, p1, p2, p3] = p;
596- let [q0, q1, q2, q3] = q;
597- let clip = |v: i32| crate::picture::clip1(v, bit_depth);
598- if de == 2 {
599- // Strong filter (eqs. 8-389..8-394).
600- let p0p =
601- (p0 - 2 * tc).max((p0 + 2 * tc).min((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3));
602- let p1p = (p1 - 2 * tc).max((p1 + 2 * tc).min((p2 + p1 + p0 + q0 + 2) >> 2));
603- let p2p = (p2 - 2 * tc).max((p2 + 2 * tc).min((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3));
604- let q0p =
605- (q0 - 2 * tc).max((q0 + 2 * tc).min((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3));
606- let q1p = (q1 - 2 * tc).max((q1 + 2 * tc).min((p0 + q0 + q1 + q2 + 2) >> 2));
607- let q2p = (q2 - 2 * tc).max((q2 + 2 * tc).min((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3));
608- return LumaFilterOut {
609- ndp: 3,
610- ndq: 3,
611- p: [p0p, p1p, p2p],
612- q: [q0p, q1p, q2p],
613- };
614- }
615- // Weak filter (eqs. 8-395..8-402).
616- let mut out = LumaFilterOut {
617- ndp: 0,
618- ndq: 0,
619- p: [p0, p1, p2],
620- q: [q0, q1, q2],
621- };
622- let delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4; // eq. 8-395
623- if delta.abs() < tc * 10 {
624- let delta = delta.clamp(-tc, tc); // eq. 8-396
625- out.p[0] = clip(p0 + delta); // eq. 8-397
626- out.q[0] = clip(q0 - delta); // eq. 8-398
627- if dep == 1 {
628- let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-399
629- out.p[1] = clip(p1 + dp); // eq. 8-400
630- }
631- if deq == 1 {
632- let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-401
633- out.q[1] = clip(q1 + dq); // eq. 8-402
634- }
635- out.ndp = (dep + 1) as usize; // eq. 8-403 (nDp = dEp + 1)
636- out.ndq = (deq + 1) as usize; // (nDq = dEq + 1)
637- }
638- out
639-}
640-
641-/// §8.7.2.5.3 — decision process for a luma block edge.
642-///
643-/// `p` / `q` are the `(i=0..3) × (k=0,3)` sample grids on each side of
644-/// the edge, laid out as `p[i][k_idx]` where `k_idx` selects row 0 or
645-/// row 3 of the edge segment (`p[i][0]` = `pi,0`, `p[i][1]` = `pi,3`).
646-/// `beta` / `tc` come from [`luma_beta_tc`]. Returns the
647-/// [`LumaEdgeDecision`] (`dE`, `dEp`, `dEq`) that drives §8.7.2.5.4.
648-///
649-/// The result's `beta` / `tc` fields echo the inputs so a caller can
650-/// pass the whole decision straight into [`filter_luma_sample`].
651-#[must_use]
652-pub fn luma_edge_decision(
653- p: [[i32; 2]; 4],
654- q: [[i32; 2]; 4],
655- beta: i32,
656- tc: i32,
657-) -> LumaEdgeDecision {
658- // Row 0 (k_idx 0) and row 3 (k_idx 1) second differences (eqs.
659- // 8-352..8-360 for EDGE_VER, identical form 8-361..8-369 for HOR).
660- let dp0 = (p[2][0] - 2 * p[1][0] + p[0][0]).abs(); // eq. 8-352
661- let dp3 = (p[2][1] - 2 * p[1][1] + p[0][1]).abs(); // eq. 8-353
662- let dq0 = (q[2][0] - 2 * q[1][0] + q[0][0]).abs(); // eq. 8-354
663- let dq3 = (q[2][1] - 2 * q[1][1] + q[0][1]).abs(); // eq. 8-355
664- let dpq0 = dp0 + dq0; // eq. 8-356
665- let dpq3 = dp3 + dq3; // eq. 8-357
666- let dp = dp0 + dp3; // eq. 8-358
667- let dq = dq0 + dq3; // eq. 8-359
668- let d = dpq0 + dpq3; // eq. 8-360
669-
670- let mut dec = LumaEdgeDecision {
671- de: 0,
672- dep: 0,
673- deq: 0,
674- beta,
675- tc,
676- };
677- if d < beta {
678- // Strong/weak split (eqs. 8-360 step 3).
679- let dsam0 = luma_sample_decision(p[0][0], p[3][0], q[0][0], q[3][0], 2 * dpq0, beta, tc);
680- let dsam3 = luma_sample_decision(p[0][1], p[3][1], q[0][1], q[3][1], 2 * dpq3, beta, tc);
681- dec.de = if dsam0 && dsam3 { 2 } else { 1 };
682- let thr = (beta + (beta >> 1)) >> 3;
683- if dp < thr {
684- dec.dep = 1; // eq. step g
685- }
686- if dq < thr {
687- dec.deq = 1; // eq. step h
688- }
689- }
690- dec
691-}
692-
693-/// Table 8-10 — `ChromaArrayType == 1` chroma-QP mapping `QpC = f(qPi)`.
694-///
695-/// The piecewise mapping is identity below `qPi == 30`, a flat-ish run
696-/// `29..37` across `qPi 30..43`, then `qPi − 6` for `qPi >= 44`.
697-#[must_use]
698-pub fn chroma_qpc_420(qpi: i32) -> i32 {
699- match qpi {
700- x if x < 30 => x,
701- 30 => 29,
702- 31 => 30,
703- 32 => 31,
704- 33 => 32,
705- 34 => 33,
706- 35 => 33,
707- 36 => 34,
708- 37 => 34,
709- 38 => 35,
710- 39 => 35,
711- 40 => 36,
712- 41 => 36,
713- 42 => 37,
714- 43 => 37,
715- x => x - 6,
716- }
717-}
718-
719-/// §8.7.2.5.5 — derive `tC` for a chroma block edge.
720-///
721-/// `qp_q` / `qp_p` are the luma `QpY` values of the CUs containing the
722-/// `q0,0` / `p0,0` chroma samples; `c_qp_pic_offset` is the picture-level
723-/// `pps_cb_qp_offset` / `pps_cr_qp_offset` for the filtered component;
724-/// `chroma_array_type` selects Table 8-10 (`== 1`) vs `Min(qPi, 51)`;
725-/// `tc_offset_div2` is `slice_tc_offset_div2`; `bit_depth` is
726-/// `BitDepthC`.
727-///
728-/// Returns `tC` per eqs. 8-382..8-384.
729-#[must_use]
730-pub fn chroma_tc(
731- qp_q: i32,
732- qp_p: i32,
733- c_qp_pic_offset: i32,
734- chroma_array_type: u8,
735- tc_offset_div2: i32,
736- bit_depth: u8,
737-) -> i32 {
738- let qpi = ((qp_q + qp_p + 1) >> 1) + c_qp_pic_offset; // eq. 8-382
739- let qp_c = if chroma_array_type == 1 {
740- chroma_qpc_420(qpi)
741- } else {
742- qpi.min(51)
743- };
744- let q = (qp_c + 2 + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-383
745- tc_prime(q) * (1 << (i32::from(bit_depth) - 8)) // eq. 8-384
746-}
747-
748-/// §8.7.2.5.8 — filtering process for a chroma sample.
749-///
750-/// `p` / `q` are the two samples each side of the boundary (`p[0]` is
751-/// `p0`, closest to the edge); `tc` is from [`chroma_tc`]; `bit_depth`
752-/// is `BitDepthC` for the final `Clip1C`. Returns `(p0', q0')`. The
753-/// PCM / transquant-bypass / palette suppressions (which restore the
754-/// input sample) are applied by the caller.
755-#[inline]
756-#[must_use]
757-pub fn filter_chroma_sample(p: [i32; 2], q: [i32; 2], tc: i32, bit_depth: u8) -> (i32, i32) {
758- let [p0, p1] = p;
759- let [q0, q1] = q;
760- let delta = (((q0 - p0) << 2) + p1 - q1 + 4) >> 3; // eq. 8-403
761- let delta = delta.clamp(-tc, tc);
762- let p0p = crate::picture::clip1(p0 + delta, bit_depth); // eq. 8-404
763- let q0p = crate::picture::clip1(q0 - delta, bit_depth); // eq. 8-405
764- (p0p, q0p)
765-}
766-
767-/// A mutable sample plane: row-major `samples[y * stride + x]`.
768-///
769-/// The §8.7.2.5.4 / .5 block-edge filtering processes read and write
770-/// this plane in place. Callers wrap their reconstructed luma / chroma
771-/// component buffer (as `i32` samples) in a [`SamplePlane`].
772-pub struct SamplePlane<'a> {
773- /// Row-major sample storage, `width * height` long.
774- pub samples: &'a mut [i32],
775- /// Plane width in samples.
776- pub width: usize,
777- /// Row stride in samples (usually equal to `width`).
778- pub stride: usize,
779-}
780-
781-impl core::fmt::Debug for SamplePlane<'_> {
782- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
783- f.debug_struct("SamplePlane")
784- .field("len", &self.samples.len())
785- .field("width", &self.width)
786- .field("stride", &self.stride)
787- .finish()
788- }
789-}
790-
791-impl SamplePlane<'_> {
792- #[inline]
793- fn get(&self, x: usize, y: usize) -> i32 {
794- self.samples[y * self.stride + x]
795- }
796- #[inline]
797- fn set(&mut self, x: usize, y: usize, v: i32) {
798- self.samples[y * self.stride + x] = v;
799- }
800- /// `(x, y)` plane coordinates for the `i`-th sample on the p (`pi`,
801- /// negative side) or q (`qi`, positive side) of an edge at `(ex, ey)`
802- /// for row offset `k` along the edge.
803- #[inline]
804- fn edge_xy(
805- &self,
806- ex: usize,
807- ey: usize,
808- edge: EdgeType,
809- side_p: bool,
810- i: usize,
811- k: usize,
812- ) -> (usize, usize) {
813- match (edge, side_p) {
814- // EDGE_VER: q at x = ex+i, p at x = ex-i-1; both at y = ey+k.
815- (EdgeType::Vertical, false) => (ex + i, ey + k),
816- (EdgeType::Vertical, true) => (ex - i - 1, ey + k),
817- // EDGE_HOR: q at y = ey+i, p at y = ey-i-1; both at x = ex+k.
818- (EdgeType::Horizontal, false) => (ex + k, ey + i),
819- (EdgeType::Horizontal, true) => (ex + k, ey - i - 1),
820- }
821- }
822-}
823-
824-/// The position + orientation of one 4-row deblocking edge segment.
825-///
826-/// `(ex, ey)` is the plane location of `q0,0`: for `EDGE_VER` the column
827-/// `ex` is the first q-side column; for `EDGE_HOR` the row `ey` is the
828-/// first q-side row.
829-#[derive(Debug, Clone, Copy)]
830-pub struct EdgePos {
831- /// `q0,0` x location in the plane.
832- pub ex: usize,
833- /// `q0,0` y location in the plane.
834- pub ey: usize,
835- /// Edge orientation (`EDGE_VER` / `EDGE_HOR`).
836- pub edge: EdgeType,
837-}
838-
839-/// The §8.7.2.5.3 / .5 QP + offset context for one block edge.
840-///
841-/// `qp_q` / `qp_p` are the `QpY` values of the CUs containing `q0,0` /
842-/// `p0,0`; the `*_div2` fields are the per-slice
843-/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; `bit_depth` is
844-/// `BitDepthY` (luma) or `BitDepthC` (chroma).
845-#[derive(Debug, Clone, Copy)]
846-pub struct EdgeQp {
847- /// `QpY` of the q-side CU.
848- pub qp_q: i32,
849- /// `QpY` of the p-side CU.
850- pub qp_p: i32,
851- /// `slice_beta_offset_div2` (luma only; ignored for chroma).
852- pub beta_offset_div2: i32,
853- /// `slice_tc_offset_div2`.
854- pub tc_offset_div2: i32,
855- /// `BitDepthY` (luma) or `BitDepthC` (chroma).
856- pub bit_depth: u8,
857-}
858-
859-/// §8.7.2.5.4 — filtering process for a luma block edge.
860-///
861-/// Filters the 4-row edge segment positioned by `pos` (the `q0,0`
862-/// boundary location). `bs` (1 or 2) and the [`EdgeQp`] context drive
863-/// [`luma_beta_tc`] / [`luma_edge_decision`] / [`filter_luma_sample`].
864-///
865-/// Returns the [`LumaEdgeDecision`] that was applied (for inspection /
866-/// trace); the plane is modified in place. A `bs == 0` edge is a no-op.
867-///
868-/// # Panics
869-/// Panics if the edge segment reads/writes outside the plane.
870-pub fn filter_luma_block_edge(
871- plane: &mut SamplePlane<'_>,
872- pos: EdgePos,
873- bs: u8,
874- qp: EdgeQp,
875-) -> LumaEdgeDecision {
876- filter_luma_block_edge_gated(plane, pos, bs, qp, None)
877-}
878-
879-/// [`filter_luma_block_edge`] with the per-CU loop-filter suppression
880-/// map: a p- / q-side sample whose cell is flagged is left unmodified
881-/// (the §8.7.2.5.4 `nDp = 0` / `nDq = 0` rule for PCM /
882-/// transquant-bypass / palette coding units); the filter decision
883-/// itself still reads both sides.
884-pub fn filter_luma_block_edge_gated(
885- plane: &mut SamplePlane<'_>,
886- pos: EdgePos,
887- bs: u8,
888- qp: EdgeQp,
889- no_filter: Option<&NoFilterMap<'_>>,
890-) -> LumaEdgeDecision {
891- let EdgePos { ex, ey, edge } = pos;
892- let zero = LumaEdgeDecision {
893- de: 0,
894- dep: 0,
895- deq: 0,
896- beta: 0,
897- tc: 0,
898- };
899- if bs == 0 {
900- return zero;
901- }
902- let (beta, tc) = luma_beta_tc(
903- qp.qp_q,
904- qp.qp_p,
905- bs,
906- qp.beta_offset_div2,
907- qp.tc_offset_div2,
908- qp.bit_depth,
909- );
910- let bit_depth = qp.bit_depth;
911- // Gather the decision grid: rows k=0 and k=3, samples i=0..3 each side.
912- let mut pg = [[0i32; 2]; 4];
913- let mut qg = [[0i32; 2]; 4];
914- for (k_idx, &k) in [0usize, 3].iter().enumerate() {
915- for i in 0..4 {
916- let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k);
917- let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k);
918- pg[i][k_idx] = plane.get(px, py);
919- qg[i][k_idx] = plane.get(qx, qy);
920- }
921- }
922- let dec = luma_edge_decision(pg, qg, beta, tc);
923- if dec.de == 0 {
924- return dec;
925- }
926- // Apply the filter to each of the 4 rows (eq. 8-372/8-373 layout).
927- for k in 0..4 {
928- let mut p = [0i32; 4];
929- let mut q = [0i32; 4];
930- for i in 0..4 {
931- let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k);
932- let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k);
933- p[i] = plane.get(px, py);
934- q[i] = plane.get(qx, qy);
935- }
936- let out = filter_luma_sample(p, q, dec.de, dec.dep, dec.deq, tc, bit_depth);
937- for i in 0..out.ndp {
938- let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k);
939- if no_filter.is_some_and(|m| m.at_luma(px, py)) {
940- continue; // §8.7.2.5.4 nDp = 0 (PCM / bypass / palette)
941- }
942- plane.set(px, py, out.p[i]);
943- }
944- for j in 0..out.ndq {
945- let (qx, qy) = plane.edge_xy(ex, ey, edge, false, j, k);
946- if no_filter.is_some_and(|m| m.at_luma(qx, qy)) {
947- continue; // §8.7.2.5.4 nDq = 0
948- }
949- plane.set(qx, qy, out.q[j]);
950- }
951- }
952- dec
953-}
954-
955-/// §8.7.2.5.5 — filtering process for a chroma block edge.
956-///
957-/// Filters the 4-row chroma edge segment positioned by `pos` (the `q0,0`
958-/// chroma location). The [`EdgeQp`] context carries the luma `QpY`
959-/// values + `slice_tc_offset_div2` + `BitDepthC`; `c_qp_pic_offset` is
960-/// the picture chroma offset; `chroma_array_type` selects Table 8-10
961-/// (`== 1`) vs `Min(qPi, 51)`. Only `p0`/`q0` are modified (eqs.
962-/// 8-385..8-388). Returns the `tC` that was applied.
963-///
964-/// # Panics
965-/// Panics if the edge segment reads/writes outside the plane.
966-pub fn filter_chroma_block_edge(
967- plane: &mut SamplePlane<'_>,
968- pos: EdgePos,
969- qp: EdgeQp,
970- c_qp_pic_offset: i32,
971- chroma_array_type: u8,
972-) -> i32 {
973- filter_chroma_block_edge_gated(plane, pos, qp, c_qp_pic_offset, chroma_array_type, None)
974-}
975-
976-/// [`filter_chroma_block_edge`] with the per-CU loop-filter
977-/// suppression map (§8.7.2.5.5: the flagged side's `p0'` / `q0'` is
978-/// not written). Chroma sample positions map onto the luma cell grid
979-/// through the `SubWidthC` / `SubHeightC` factors of
980-/// `chroma_array_type`.
981-pub fn filter_chroma_block_edge_gated(
982- plane: &mut SamplePlane<'_>,
983- pos: EdgePos,
984- qp: EdgeQp,
985- c_qp_pic_offset: i32,
986- chroma_array_type: u8,
987- no_filter: Option<&NoFilterMap<'_>>,
988-) -> i32 {
989- let (sub_w, sub_h) = sub_wh_c(chroma_array_type);
990- let EdgePos { ex, ey, edge } = pos;
991- let bit_depth = qp.bit_depth;
992- let tc = chroma_tc(
993- qp.qp_q,
994- qp.qp_p,
995- c_qp_pic_offset,
996- chroma_array_type,
997- qp.tc_offset_div2,
998- bit_depth,
999- );
1000- for k in 0..4 {
1001- let mut p = [0i32; 2];
1002- let mut q = [0i32; 2];
1003- for i in 0..2 {
1004- let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k);
1005- let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k);
1006- p[i] = plane.get(px, py);
1007- q[i] = plane.get(qx, qy);
1008- }
1009- let (p0p, q0p) = filter_chroma_sample(p, q, tc, bit_depth);
1010- let (px, py) = plane.edge_xy(ex, ey, edge, true, 0, k);
1011- let (qx, qy) = plane.edge_xy(ex, ey, edge, false, 0, k);
1012- if !no_filter.is_some_and(|m| m.at_luma(px * sub_w, py * sub_h)) {
1013- plane.set(px, py, p0p);
1014- }
1015- if !no_filter.is_some_and(|m| m.at_luma(qx * sub_w, qy * sub_h)) {
1016- plane.set(qx, qy, q0p);
1017- }
1018- }
1019- tc
1020-}
1021-
1022-/// The §8.7.2.5.1 / .2 per-CU deblocking context: the QP + offset state a
1023-/// coding unit contributes to its edge filtering.
1024-///
1025-/// `qp_y` is the CU's `QpY`; the `*_offset_div2` are the per-slice
1026-/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; the `pps_c*_qp_offset`
1027-/// are the picture chroma QP offsets; the bit depths are `BitDepthY` /
1028-/// `BitDepthC`. The driver reads neighbour `QpY` from `qp_y_at` so a
1029-/// boundary edge can use the p-side CU's `QpY` for `qP,p` (eq. 8-347).
1030-#[derive(Debug, Clone, Copy)]
1031-pub struct DeblockCuParams {
1032- /// The CU's `QpY` (the q-side QP at every edge inside the CU).
1033- pub qp_y: i32,
1034- /// `slice_beta_offset_div2`.
1035- pub beta_offset_div2: i32,
1036- /// `slice_tc_offset_div2`.
1037- pub tc_offset_div2: i32,
1038- /// `pps_cb_qp_offset` for the Cb component — the §8.7.2.5.1/.2
1039- /// `cQpPicOffset` (slice-level and CU-level chroma QP adjustments
1040- /// are excluded from chroma deblocking by the invocation text).
1041- pub cb_qp_offset: i32,
1042- /// `pps_cr_qp_offset` for the Cr component.
1043- pub cr_qp_offset: i32,
1044- /// `BitDepthY`.
1045- pub bit_depth_luma: u8,
1046- /// `BitDepthC`.
1047- pub bit_depth_chroma: u8,
1048- /// `ChromaArrayType` (selects Table 8-10 / `Min(qPi,51)` + subsampling).
1049- pub chroma_array_type: u8,
1050-}
1051-
1052-/// The geometry + QP context of one coding unit for the §8.7.2.5.1 / .2
1053-/// edge-filtering driver.
1054-#[derive(Debug, Clone, Copy)]
1055-pub struct DeblockCu {
1056- /// The CU's luma top-left x.
1057- pub x_cb: usize,
1058- /// The CU's luma top-left y.
1059- pub y_cb: usize,
1060- /// `log2CbSize`.
1061- pub log2_cb_size: u32,
1062- /// The CU QP / offset / chroma context.
1063- pub params: DeblockCuParams,
1064- /// The left-neighbour CU's `QpY` at the vertical coding-block
1065- /// boundary edge (xDk == 0); interior edges use `params.qp_y` on
1066- /// both sides.
1067- pub qp_y_p_left: i32,
1068- /// The above-neighbour CU's `QpY` at the horizontal coding-block
1069- /// boundary edge (yDm == 0).
1070- pub qp_y_p_top: i32,
1071-}
1072-
1073-/// §8.7.2.5.1 / .2 — filter all edges of one coding unit in one direction.
1074-///
1075-/// Applies the §8.7.2.5.4 luma block-edge filter at every `bS > 0` sampled
1076-/// position, then (when `ChromaArrayType != 0`) the §8.7.2.5.5 chroma
1077-/// block-edge filter at every `bS == 2`, 8-luma-sample-aligned position.
1078-/// The luma sampling grid is 8-stride along the edge axis and 4-stride
1079-/// across; the chroma grid steps `8 / SubWidthC` (vertical) /
1080-/// `8 / SubHeightC` (horizontal) in the edge axis.
1081-///
1082-/// `cu` carries the CU's geometry + QP context; `bs` is the §8.7.2.4 grid
1083-/// for `edge_type`.
1084-///
1085-/// # Panics
1086-/// Panics if a filtered edge segment reads/writes outside a plane.
1087-pub fn filter_cu_edges(
1088- pic: &mut Picture,
1089- cu: &DeblockCu,
1090- edge_type: EdgeType,
1091- bs: &BoundaryStrength,
1092-) {
1093- filter_cu_edges_with_qp_map(pic, cu, edge_type, bs, None);
1094-}
1095-
1096-/// [`filter_cu_edges`] with the per-position [`QpMap`] (exact `QpQ` /
1097-/// `QpP` when quantization groups vary inside / around the CU).
1098-pub fn filter_cu_edges_with_qp_map(
1099- pic: &mut Picture,
1100- cu: &DeblockCu,
1101- edge_type: EdgeType,
1102- bs: &BoundaryStrength,
1103- qp_map: Option<QpMap<'_>>,
1104-) {
1105- filter_cu_edges_full(pic, cu, edge_type, bs, qp_map, None);
1106-}
1107-
1108-/// [`filter_cu_edges_with_qp_map`] with the per-CU loop-filter
1109-/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 `nDp` / `nDq` zeroing).
1110-pub fn filter_cu_edges_full(
1111- pic: &mut Picture,
1112- cu: &DeblockCu,
1113- edge_type: EdgeType,
1114- bs: &BoundaryStrength,
1115- qp_map: Option<QpMap<'_>>,
1116- no_filter: Option<&NoFilterMap<'_>>,
1117-) {
1118- let DeblockCu {
1119- x_cb,
1120- y_cb,
1121- log2_cb_size,
1122- params,
1123- qp_y_p_left,
1124- qp_y_p_top,
1125- } = *cu;
1126- let n_d = 1usize << (log2_cb_size - 3);
1127- let (sub_w, sub_h) = sub_wh_c(params.chroma_array_type);
1128-
1129- // ----- luma (§8.7.2.5.1 step 2 / §8.7.2.5.2 step 2) -----
1130- // EDGE_VER: xDk = k<<3 (k=0..nD-1), yDm = m<<2 (m=0..2nD-1).
1131- // EDGE_HOR: yDm = m<<3 (m=0..nD-1), xDk = k<<2 (k=0..2nD-1).
1132- // `edges` indexes the 8-strided axis (nD); `segs` the 4-strided axis.
1133- let (n_edges, n_segs) = (n_d, n_d * 2);
1134- for e in 0..n_edges {
1135- for s_idx in 0..n_segs {
1136- let (x_dk, y_dm) = match edge_type {
1137- EdgeType::Vertical => (e << 3, s_idx << 2),
1138- EdgeType::Horizontal => (s_idx << 2, e << 3),
1139- };
1140- let s = bs.at(x_dk, y_dm);
1141- if s == 0 {
1142- continue;
1143- }
1144- // p-side QpY: the neighbour CU only at the coding-block
1145- // boundary edge; interior edges share the CU's QpY.
1146- let (boundary, qp_y_p) = match edge_type {
1147- EdgeType::Vertical => (x_dk == 0, qp_y_p_left),
1148- EdgeType::Horizontal => (y_dm == 0, qp_y_p_top),
1149- };
1150- // §8.7.2.5.3: QpQ / QpP are the QpY of the coding units
1151- // containing the q0 / p0 samples — per position from the QP
1152- // map when supplied, else the per-CU scalars.
1153- let (qp_q, qp_p) = match qp_map {
1154- Some(m) => {
1155- let (qx, qy) = (x_cb + x_dk, y_cb + y_dm);
1156- let (px, py) = match edge_type {
1157- EdgeType::Vertical => (qx - 1, qy),
1158- EdgeType::Horizontal => (qx, qy - 1),
1159- };
1160- (m.qp_at(qx, qy), m.qp_at(px, py))
1161- }
1162- None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }),
1163- };
1164- let qp = EdgeQp {
1165- qp_q,
1166- qp_p,
1167- beta_offset_div2: params.beta_offset_div2,
1168- tc_offset_div2: params.tc_offset_div2,
1169- bit_depth: params.bit_depth_luma,
1170- };
1171- let (buf, stride) = pic.plane_mut(Plane::Luma);
1172- let mut plane = SamplePlane {
1173- samples: buf,
1174- width: stride,
1175- stride,
1176- };
1177- let pos = EdgePos {
1178- ex: x_cb + x_dk,
1179- ey: y_cb + y_dm,
1180- edge: edge_type,
1181- };
1182- filter_luma_block_edge_gated(&mut plane, pos, s, qp, no_filter);
1183- }
1184- }
1185-
1186- // ----- chroma (§8.7.2.5.1 / .2 chroma steps) -----
1187- if params.chroma_array_type == 0 {
1188- return;
1189- }
1190- let (xc_cb, yc_cb) = (x_cb / sub_w, y_cb / sub_h);
1191- // edgeSpacing / edgeSections per direction.
1192- let (spacing, sections, n_edges) = match edge_type {
1193- EdgeType::Vertical => (8 / sub_w, n_d * (2 / sub_h), n_d),
1194- EdgeType::Horizontal => (8 / sub_h, n_d * (2 / sub_w), n_d),
1195- };
1196- for plane in [Plane::Cb, Plane::Cr] {
1197- let c_qp_offset = if plane == Plane::Cb {
1198- params.cb_qp_offset
1199- } else {
1200- params.cr_qp_offset
1201- };
1202- // EDGE_VER: xDk = k*spacing (k=0..nD-1), yDm = m<<2 (m=0..sections-1).
1203- // EDGE_HOR: yDm = m*spacing, xDk = k<<2.
1204- let (k_max, m_max) = match edge_type {
1205- EdgeType::Vertical => (n_edges, sections),
1206- EdgeType::Horizontal => (sections, n_edges),
1207- };
1208- for kk in 0..k_max {
1209- for mm in 0..m_max {
1210- let (x_dk, y_dm) = match edge_type {
1211- EdgeType::Vertical => (kk * spacing, mm << 2),
1212- EdgeType::Horizontal => (kk << 2, mm * spacing),
1213- };
1214- // bS[xDk*SubWidthC][yDm*SubHeightC] == 2.
1215- let bx = x_dk * sub_w;
1216- let by = y_dm * sub_h;
1217- if bs.at(bx, by) != 2 {
1218- continue;
1219- }
1220- // 8-luma-grid alignment of the chroma edge position.
1221- let aligned = match edge_type {
1222- EdgeType::Vertical => ((xc_cb + x_dk) >> 3) << 3 == xc_cb + x_dk,
1223- EdgeType::Horizontal => ((yc_cb + y_dm) >> 3) << 3 == yc_cb + y_dm,
1224- };
1225- if !aligned {
1226- continue;
1227- }
1228- let (boundary, qp_y_p) = match edge_type {
1229- EdgeType::Vertical => (bx == 0, qp_y_p_left),
1230- EdgeType::Horizontal => (by == 0, qp_y_p_top),
1231- };
1232- // §8.7.2.5.5: QpQ / QpP from the coding units containing
1233- // the chroma edge's q0 / p0 samples (luma positions).
1234- let (qp_q, qp_p) = match qp_map {
1235- Some(m) => {
1236- let (qx, qy) = ((xc_cb + x_dk) * sub_w, (yc_cb + y_dm) * sub_h);
1237- let (px, py) = match edge_type {
1238- EdgeType::Vertical => (qx - 1, qy),
1239- EdgeType::Horizontal => (qx, qy - 1),
1240- };
1241- (m.qp_at(qx, qy), m.qp_at(px, py))
1242- }
1243- None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }),
1244- };
1245- let qp = EdgeQp {
1246- qp_q,
1247- qp_p,
1248- beta_offset_div2: params.beta_offset_div2,
1249- tc_offset_div2: params.tc_offset_div2,
1250- bit_depth: params.bit_depth_chroma,
1251- };
1252- let (buf, stride) = pic.plane_mut(plane);
1253- let mut cplane = SamplePlane {
1254- samples: buf,
1255- width: stride,
1256- stride,
1257- };
1258- let pos = EdgePos {
1259- ex: xc_cb + x_dk,
1260- ey: yc_cb + y_dm,
1261- edge: edge_type,
1262- };
1263- filter_chroma_block_edge_gated(
1264- &mut cplane,
1265- pos,
1266- qp,
1267- c_qp_offset,
1268- params.chroma_array_type,
1269- no_filter,
1270- );
1271- }
1272- }
1273- }
1274-}
1275-
1276-/// One coding unit's full §8.7.2 deblocking description, as the
1277-/// picture-level driver [`deblock_picture`] consumes it.
1278-///
1279-/// Carries everything the §8.7.2.2 / .3 edge-flag derivation, the §8.7.2.4
1280-/// bS derivation and the §8.7.2.5.1 / .2 filtering need for one CU: its
1281-/// geometry + QP context ([`DeblockCu`]), its transform-tree split
1282-/// ([`TransformSplit`]) + prediction [`PartMode`], and the §8.7.2.1
1283-/// `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` the caller computes from
1284-/// the picture / tile / slice geometry (`false` at a non-filtered
1285-/// boundary).
1286-#[derive(Debug, Clone)]
1287-pub struct DeblockCuDesc {
1288- /// Geometry + QP context.
1289- pub cu: DeblockCu,
1290- /// The CU's transform-tree split structure.
1291- pub transform_split: TransformSplit,
1292- /// The CU's prediction partition mode.
1293- pub part_mode: PartMode,
1294- /// §8.7.2.1 `filterLeftCbEdgeFlag` (gates the left CB-boundary
1295- /// vertical edge).
1296- pub filter_left: bool,
1297- /// §8.7.2.1 `filterTopCbEdgeFlag` (gates the top CB-boundary
1298- /// horizontal edge).
1299- pub filter_top: bool,
1300-}
1301-
1302-/// §8.7.2.1 — the picture-level deblocking filter driver.
1303-///
1304-/// Filters all vertical edges of the picture first, then all horizontal
1305-/// edges (with the vertically-filtered samples as input), per §8.7.2.1.
1306-/// Each pass walks `cus` in order and, for each CU: derives the
1307-/// §8.7.2.2 / .3 edge flags, the §8.7.2.4 boundary strengths from `field`,
1308-/// then applies the §8.7.2.5.1 / .2 luma + chroma filters via
1309-/// [`filter_cu_edges`].
1310-///
1311-/// `cus` must be in coding (z-scan) order; the caller is responsible for
1312-/// the §8.7.2.1 boundary exclusions (picture / tile / slice edges, and the
1313-/// `slice_deblocking_filter_disabled_flag` skip) by setting each
1314-/// descriptor's `filter_left` / `filter_top` (and omitting CUs whose slice
1315-/// disables deblocking).
1316-///
1317-/// # Panics
1318-/// Panics if a CU's edges read/write outside a `pic` plane.
1319-pub fn deblock_picture(pic: &mut Picture, field: &MotionField, cus: &[DeblockCuDesc]) {
1320- deblock_picture_with_qp_map(pic, field, cus, None);
1321-}
1322-
1323-/// Per-4×4-cell `QpY` map for the §8.7.2.5.3 / §8.7.2.5.5 per-position
1324-/// `QpQ` / `QpP` reads (row-major over the picture's 4×4 cells). When a
1325-/// picture carries per-quantization-group `cu_qp_delta` values, the
1326-/// p-side QP can change along a single coding-block edge, so the
1327-/// per-CU scalar fallback in [`DeblockCu`] is not exact.
1328-#[derive(Debug, Clone, Copy)]
1329-pub struct QpMap<'a> {
1330- /// Per-cell `QpY`.
1331- pub cells: &'a [i8],
1332- /// Cell-grid width (`ceil(pic_width / 4)`).
1333- pub w_cells: usize,
1334-}
1335-
1336-impl QpMap<'_> {
1337- fn qp_at(&self, x_luma: usize, y_luma: usize) -> i32 {
1338- let idx = (y_luma >> 2) * self.w_cells + (x_luma >> 2);
1339- self.cells.get(idx).copied().map_or(0, i32::from)
1340- }
1341-}
1342-
1343-/// Per-4×4-luma-cell in-loop-filter suppression map: `true` cells
1344-/// belong to a coding unit whose reconstructed samples the loop
1345-/// filters must not modify — a `pcm_flag == 1` CU when
1346-/// `pcm_loop_filter_disabled_flag == 1` (§7.4.3.2.1), or a
1347-/// `cu_transquant_bypass_flag == 1` CU (§7.4.9.5). The §8.7.2.5.4 /
1348-/// §8.7.2.5.5 filters zero `nDp` / `nDq` on the flagged side (the
1349-/// decision still reads both sides); §8.7.3 SAO skips flagged samples.
1350-#[derive(Debug, Clone, Copy)]
1351-pub struct NoFilterMap<'a> {
1352- /// Per-cell suppression flags, row-major.
1353- pub cells: &'a [bool],
1354- /// Cell-grid width (`ceil(pic_width / 4)`).
1355- pub w_cells: usize,
1356-}
1357-
1358-impl NoFilterMap<'_> {
1359- /// Suppression flag of the cell covering luma sample
1360- /// `(x_luma, y_luma)` (out-of-range positions are not suppressed).
1361- #[must_use]
1362- pub fn at_luma(&self, x_luma: usize, y_luma: usize) -> bool {
1363- self.cells
1364- .get((y_luma >> 2) * self.w_cells + (x_luma >> 2))
1365- .copied()
1366- .unwrap_or(false)
1367- }
1368-}
1369-
1370-/// [`deblock_picture`] with the per-position QP map.
1371-pub fn deblock_picture_with_qp_map(
1372- pic: &mut Picture,
1373- field: &MotionField,
1374- cus: &[DeblockCuDesc],
1375- qp_map: Option<QpMap<'_>>,
1376-) {
1377- deblock_picture_full(pic, field, cus, qp_map, None);
1378-}
1379-
1380-/// [`deblock_picture_with_qp_map`] with the per-CU loop-filter
1381-/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 — PCM with
1382-/// `pcm_loop_filter_disabled_flag` and transquant-bypass coding units
1383-/// keep their reconstructed samples).
1384-pub fn deblock_picture_full(
1385- pic: &mut Picture,
1386- field: &MotionField,
1387- cus: &[DeblockCuDesc],
1388- qp_map: Option<QpMap<'_>>,
1389- no_filter: Option<&NoFilterMap<'_>>,
1390-) {
1391- // Pass 1: all vertical edges.
1392- for desc in cus {
1393- apply_cu_direction(pic, field, desc, EdgeType::Vertical, qp_map, no_filter);
1394- }
1395- // Pass 2: all horizontal edges (on the vertically-filtered samples).
1396- for desc in cus {
1397- apply_cu_direction(pic, field, desc, EdgeType::Horizontal, qp_map, no_filter);
1398- }
1399-}
1400-
1401-/// Derive the edge flags + bS for one CU in one direction and filter it.
1402-fn apply_cu_direction(
1403- pic: &mut Picture,
1404- field: &MotionField,
1405- desc: &DeblockCuDesc,
1406- edge_type: EdgeType,
1407- qp_map: Option<QpMap<'_>>,
1408- no_filter: Option<&NoFilterMap<'_>>,
1409-) {
1410- let DeblockCu {
1411- x_cb,
1412- y_cb,
1413- log2_cb_size,
1414- ..
1415- } = desc.cu;
1416- let filter_edge_flag = match edge_type {
1417- EdgeType::Vertical => desc.filter_left,
1418- EdgeType::Horizontal => desc.filter_top,
1419- };
1420- let ef = derive_edge_flags(
1421- &desc.transform_split,
1422- desc.part_mode,
1423- log2_cb_size,
1424- edge_type,
1425- filter_edge_flag,
1426- );
1427- let bs = derive_boundary_strength(
1428- field,
1429- x_cb,
1430- y_cb,
1431- log2_cb_size,
1432- edge_type,
1433- ef.edge_flags(),
1434- ef.tb_edge(),
1435- );
1436- filter_cu_edges_full(pic, &desc.cu, edge_type, &bs, qp_map, no_filter);
1437-}
1438-
1439-#[cfg(test)]
1440-mod tests {
1441- use super::*;
1442- use crate::motion::MotionCell;
1443-
1444- fn inter_cell(mv0: [i32; 2], poc0: i32) -> MotionCell {
1445- MotionCell {
1446- is_intra: false,
1447- has_nonzero_coeff: false,
1448- pred_flag_l0: true,
1449- pred_flag_l1: false,
1450- ref_poc_l0: poc0,
1451- ref_poc_l1: i32::MIN,
1452- mv_l0: mv0,
1453- mv_l1: [0, 0],
1454- }
1455- }
1456-
1457- /// A 16×16 CU's internal vertical edge at xDi=8, with the left
1458- /// (p-side) half intra ⇒ bS == 2 at the sampled positions.
1459- ///
1460- /// The §8.7.2.4 vertical-edge x stride is 8, so a 16-wide CU samples
1461- /// xDi ∈ {0, 8}; the internal edge is at xDi=8.
1462- #[test]
1463- fn intra_neighbour_gives_bs2() {
1464- let mut field = MotionField::new(32, 32);
1465- // CU at (0,0), 16×16. q-side (right half) inter; p-side (left)
1466- // stays intra (background).
1467- field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0));
1468- let n = 16;
1469- let mut edge_flags = vec![false; n * n];
1470- let tb_edge = vec![false; n * n];
1471- // Internal vertical edge at xDi=8, sampled yDj 0,4,8,12.
1472- for yj in (0..16).step_by(4) {
1473- edge_flags[yj * n + 8] = true;
1474- }
1475- let bs =
1476- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1477- // p0 = col 7 (intra), q0 = col 8 (inter) ⇒ bS == 2.
1478- assert_eq!(bs.at(8, 0), 2);
1479- assert_eq!(bs.at(8, 12), 2);
1480- // xDi=4 not sampled for EDGE_VER (8-stride).
1481- assert_eq!(bs.at(4, 0), 0);
1482- }
1483-
1484- /// Transform-block edge with a non-zero coefficient on an inter block
1485- /// ⇒ bS == 1.
1486- #[test]
1487- fn tb_edge_with_coeff_gives_bs1() {
1488- let mut field = MotionField::new(32, 32);
1489- let mut p = inter_cell([0, 0], 0);
1490- p.has_nonzero_coeff = true;
1491- let q = inter_cell([0, 0], 0);
1492- field.fill_rect(0, 0, 16, 16, q);
1493- field.fill_rect(0, 0, 8, 16, p); // left half carries the coeff
1494- let n = 16;
1495- let mut edge_flags = vec![false; n * n];
1496- let mut tb_edge = vec![false; n * n];
1497- // Vertical edge at xDi=8 (a transform-block edge).
1498- for yj in (0..16).step_by(4) {
1499- edge_flags[yj * n + 8] = true;
1500- tb_edge[yj * n + 8] = true;
1501- }
1502- let bs =
1503- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1504- // p0 = col 7 (coeff block), q0 = col 8 ⇒ bS == 1.
1505- assert_eq!(bs.at(8, 0), 1);
1506- assert_eq!(bs.at(8, 4), 1);
1507- }
1508-
1509- /// Two inter blocks, same reference, MV difference >= 4 ⇒ bS == 1.
1510- #[test]
1511- fn mv_diff_gives_bs1() {
1512- let mut field = MotionField::new(32, 32);
1513- field.fill_rect(0, 0, 8, 16, inter_cell([0, 0], 0)); // p side
1514- field.fill_rect(8, 0, 8, 16, inter_cell([4, 0], 0)); // q side, Δ=4
1515- let n = 16;
1516- let mut edge_flags = vec![false; n * n];
1517- let tb_edge = vec![false; n * n];
1518- for yj in (0..16).step_by(4) {
1519- edge_flags[yj * n + 8] = true;
1520- }
1521- let bs =
1522- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1523- assert_eq!(bs.at(8, 0), 1);
1524- assert_eq!(bs.at(8, 12), 1);
1525- }
1526-
1527- /// Two inter blocks, same reference + same MV ⇒ bS == 0.
1528- #[test]
1529- fn same_motion_gives_bs0() {
1530- let mut field = MotionField::new(32, 32);
1531- field.fill_rect(0, 0, 16, 16, inter_cell([3, 1], 0)); // identical motion
1532- let n = 16;
1533- let mut edge_flags = vec![false; n * n];
1534- let tb_edge = vec![false; n * n];
1535- for yj in (0..16).step_by(4) {
1536- edge_flags[yj * n + 8] = true;
1537- }
1538- let bs =
1539- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1540- assert_eq!(bs.at(8, 0), 0);
1541- }
1542-
1543- /// Different reference pictures ⇒ bS == 1 even with identical MVs.
1544- #[test]
1545- fn different_ref_gives_bs1() {
1546- let mut field = MotionField::new(32, 32);
1547- field.fill_rect(0, 0, 8, 16, inter_cell([2, 2], 0)); // poc 0
1548- field.fill_rect(8, 0, 8, 16, inter_cell([2, 2], 8)); // poc 8
1549- let n = 16;
1550- let mut edge_flags = vec![false; n * n];
1551- let tb_edge = vec![false; n * n];
1552- for yj in (0..16).step_by(4) {
1553- edge_flags[yj * n + 8] = true;
1554- }
1555- let bs =
1556- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1557- assert_eq!(bs.at(8, 0), 1);
1558- }
1559-
1560- /// Horizontal edges sample 4-stride x, 8-stride y.
1561- #[test]
1562- fn horizontal_edge_sampling() {
1563- let mut field = MotionField::new(32, 32);
1564- // top half intra (background), bottom half inter; internal
1565- // horizontal edge at yDj=8.
1566- field.fill_rect(0, 8, 16, 8, inter_cell([0, 0], 0));
1567- let n = 16;
1568- let mut edge_flags = vec![false; n * n];
1569- let tb_edge = vec![false; n * n];
1570- for xi in (0..16).step_by(4) {
1571- edge_flags[8 * n + xi] = true;
1572- }
1573- let bs =
1574- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Horizontal, &edge_flags, &tb_edge);
1575- // yDj=8: p0 = row 7 (intra), q0 = row 8 (inter) ⇒ bS == 2.
1576- assert_eq!(bs.at(0, 8), 2);
1577- assert_eq!(bs.at(12, 8), 2);
1578- // yDj=4 not sampled for EDGE_HOR.
1579- assert_eq!(bs.at(0, 4), 0);
1580- }
1581-
1582- /// edgeFlags == 0 ⇒ bS stays 0 regardless of mode.
1583- #[test]
1584- fn no_edge_flag_gives_bs0() {
1585- let field = MotionField::new(16, 16); // intra background
1586- let n = 8;
1587- let edge_flags = vec![false; n * n];
1588- let tb_edge = vec![false; n * n];
1589- let bs =
1590- derive_boundary_strength(&field, 0, 0, 3, EdgeType::Vertical, &edge_flags, &tb_edge);
1591- assert_eq!(bs.at(0, 0), 0);
1592- }
1593-
1594- /// Bullet-4 path: two MVs each, same single reference picture on both
1595- /// sides; bS == 1 only when both the straight and crossed MV-pair
1596- /// differences reach 4.
1597- #[test]
1598- fn bipred_same_ref_bullet4() {
1599- let mut field = MotionField::new(32, 32);
1600- let bi = |mv0: [i32; 2], mv1: [i32; 2]| MotionCell {
1601- is_intra: false,
1602- has_nonzero_coeff: false,
1603- pred_flag_l0: true,
1604- pred_flag_l1: true,
1605- ref_poc_l0: 0,
1606- ref_poc_l1: 0, // same reference picture for both lists
1607- mv_l0: mv0,
1608- mv_l1: mv1,
1609- };
1610- // p: l0=[0,0] l1=[0,0]; q: l0=[4,0] l1=[4,0].
1611- // straight: |Δl0|>=4 ⇒ true. crossed: |p.l0−q.l1|=4 ⇒ true ⇒ bS 1.
1612- field.fill_rect(0, 0, 8, 16, bi([0, 0], [0, 0]));
1613- field.fill_rect(8, 0, 8, 16, bi([4, 0], [4, 0]));
1614- let n = 16;
1615- let mut edge_flags = vec![false; n * n];
1616- let tb_edge = vec![false; n * n];
1617- for yj in (0..16).step_by(4) {
1618- edge_flags[yj * n + 8] = true;
1619- }
1620- let bs =
1621- derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge);
1622- assert_eq!(bs.at(8, 0), 1);
1623- }
1624-
1625- // ----- §8.7.2.2 / §8.7.2.3 edge-flag derivation -----
1626-
1627- /// §8.7.2.2: an un-split 16×16 CB marks only its left CB-boundary
1628- /// column (EDGE_VER), gated by filterEdgeFlag. No internal TB edges.
1629- #[test]
1630- fn edge_flags_single_tb_left_boundary() {
1631- let n = 16;
1632- // filterEdgeFlag = true ⇒ the CB-left column (x=0) is an edge.
1633- let ef = derive_edge_flags(
1634- &TransformSplit::leaf(),
1635- PartMode::Part2Nx2N,
1636- 4,
1637- EdgeType::Vertical,
1638- true,
1639- );
1640- for y in 0..n {
1641- assert!(ef.edge_at(0, y), "left CB-boundary column must be set");
1642- assert!(ef.tb_at(0, y), "left CB-boundary is a TB edge");
1643- }
1644- // No internal column is set (no split, PART_2Nx2N).
1645- for x in 1..n {
1646- for y in 0..n {
1647- assert!(!ef.edge_at(x, y), "interior ({x},{y}) must be clear");
1648- }
1649- }
1650- }
1651-
1652- /// filterEdgeFlag = false suppresses the CB-boundary edge entirely.
1653- #[test]
1654- fn edge_flags_cb_boundary_gated_off() {
1655- let ef = derive_edge_flags(
1656- &TransformSplit::leaf(),
1657- PartMode::Part2Nx2N,
1658- 4,
1659- EdgeType::Vertical,
1660- false,
1661- );
1662- for y in 0..16 {
1663- assert!(!ef.edge_at(0, y), "gated-off CB boundary stays clear");
1664- }
1665- }
1666-
1667- /// §8.7.2.2: a one-level transform split of a 16×16 CB marks the
1668- /// internal vertical TB edge at column 8 (always 1, not gated), plus
1669- /// the gated left boundary.
1670- #[test]
1671- fn edge_flags_split_marks_internal_tb_edge() {
1672- let ef = derive_edge_flags(
1673- &TransformSplit::split_once(),
1674- PartMode::Part2Nx2N,
1675- 4,
1676- EdgeType::Vertical,
1677- true,
1678- );
1679- for y in 0..16 {
1680- assert!(ef.edge_at(0, y), "left boundary set");
1681- assert!(ef.edge_at(8, y), "internal split column 8 set");
1682- assert!(ef.tb_at(8, y), "internal split is a TB edge");
1683- }
1684- }
1685-
1686- /// §8.7.2.2 EDGE_HOR: the split marks the internal horizontal TB edge
1687- /// at row 8.
1688- #[test]
1689- fn edge_flags_split_horizontal() {
1690- let ef = derive_edge_flags(
1691- &TransformSplit::split_once(),
1692- PartMode::Part2Nx2N,
1693- 4,
1694- EdgeType::Horizontal,
1695- true,
1696- );
1697- for x in 0..16 {
1698- assert!(ef.edge_at(x, 0), "top boundary set");
1699- assert!(ef.edge_at(x, 8), "internal split row 8 set");
1700- assert!(ef.tb_at(x, 8), "internal split is a TB edge");
1701- }
1702- }
1703-
1704- /// §8.7.2.3 PART_Nx2N marks the prediction column at nCbS/2 — and it
1705- /// is NOT a transform-block edge (tb_edge stays clear there).
1706- #[test]
1707- fn edge_flags_part_nx2n_prediction_edge() {
1708- let ef = derive_edge_flags(
1709- &TransformSplit::leaf(),
1710- PartMode::PartNx2N,
1711- 4,
1712- EdgeType::Vertical,
1713- true,
1714- );
1715- for y in 0..16 {
1716- assert!(ef.edge_at(8, y), "PART_Nx2N prediction column 8 set");
1717- assert!(!ef.tb_at(8, y), "prediction edge is not a TB edge");
1718- }
1719- }
1720-
1721- /// §8.7.2.3 AMP PART_nLx2N marks column nCbS/4; PART_nRx2N marks
1722- /// 3·nCbS/4.
1723- #[test]
1724- fn edge_flags_amp_columns() {
1725- let l = derive_edge_flags(
1726- &TransformSplit::leaf(),
1727- PartMode::PartNLx2N,
1728- 4,
1729- EdgeType::Vertical,
1730- true,
1731- );
1732- assert!(l.edge_at(4, 0), "PART_nLx2N column 4");
1733- let r = derive_edge_flags(
1734- &TransformSplit::leaf(),
1735- PartMode::PartNRx2N,
1736- 4,
1737- EdgeType::Vertical,
1738- true,
1739- );
1740- assert!(r.edge_at(12, 0), "PART_nRx2N column 12");
1741- }
1742-
1743- /// §8.7.2.3 horizontal AMP: PART_2NxnU row nCbS/4, PART_2NxnD row
1744- /// 3·nCbS/4.
1745- #[test]
1746- fn edge_flags_amp_rows() {
1747- let u = derive_edge_flags(
1748- &TransformSplit::leaf(),
1749- PartMode::Part2NxnU,
1750- 4,
1751- EdgeType::Horizontal,
1752- true,
1753- );
1754- assert!(u.edge_at(0, 4), "PART_2NxnU row 4");
1755- let d = derive_edge_flags(
1756- &TransformSplit::leaf(),
1757- PartMode::Part2NxnD,
1758- 4,
1759- EdgeType::Horizontal,
1760- true,
1761- );
1762- assert!(d.edge_at(0, 12), "PART_2NxnD row 12");
1763- }
1764-
1765- /// A nested split (one quadrant splits again) marks the deeper TB edge
1766- /// at the 4-sample sub-block column.
1767- #[test]
1768- fn edge_flags_nested_split() {
1769- // 16×16 CB: TL quadrant (8×8) splits into four 4×4; others leaf.
1770- let nested = TransformSplit::Split(Box::new([
1771- TransformSplit::split_once(), // TL 8×8 → 4×4 leaves
1772- TransformSplit::Leaf,
1773- TransformSplit::Leaf,
1774- TransformSplit::Leaf,
1775- ]));
1776- let ef = derive_edge_flags(&nested, PartMode::Part2Nx2N, 4, EdgeType::Vertical, true);
1777- // The TL quadrant's internal vertical edge is at column 4.
1778- for y in 0..8 {
1779- assert!(ef.edge_at(4, y), "nested TB edge at column 4, row {y}");
1780- assert!(ef.tb_at(4, y));
1781- }
1782- // The CB-internal split at column 8 is still present.
1783- for y in 0..16 {
1784- assert!(ef.edge_at(8, y), "CB-level split column 8");
1785- }
1786- // Column 4 below the TL quadrant (y>=8) is not an edge (BL leaf is
1787- // 8 wide, its only internal edge would be column 8, not 4).
1788- assert!(!ef.edge_at(4, 8), "column 4 row 8 clear (BL leaf)");
1789- }
1790-
1791- /// The §8.7.2.4 bS derivation consumes the derived flags: an
1792- /// intra/inter split CU with a derived internal TB edge yields bS=2
1793- /// at the internal column.
1794- #[test]
1795- fn edge_flags_feed_boundary_strength() {
1796- // filterEdgeFlag = false: this CB is at the picture's left edge, so
1797- // only the internal split column (8) is an edge — the bS sampler
1798- // never reads a p-sample at x = −1.
1799- let ef = derive_edge_flags(
1800- &TransformSplit::split_once(),
1801- PartMode::Part2Nx2N,
1802- 4,
1803- EdgeType::Vertical,
1804- false,
1805- );
1806- let mut field = MotionField::new(32, 32);
1807- // Left half intra (background), right half inter.
1808- field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0));
1809- let bs = derive_boundary_strength(
1810- &field,
1811- 0,
1812- 0,
1813- 4,
1814- EdgeType::Vertical,
1815- ef.edge_flags(),
1816- ef.tb_edge(),
1817- );
1818- // Internal column 8: p (col 7, intra) vs q (col 8, inter) ⇒ bS 2.
1819- assert_eq!(bs.at(8, 0), 2);
1820- }
1821-
1822- // ----- §8.7.2.5.3 / .6 / .7 luma filtering primitives -----
1823-
1824- /// Table 8-12 spot checks: β′ is 0 below Q=16 and tracks the listed
1825- /// breakpoints; tC′ is 0 up to Q=17 and 1 at Q=18.
1826- #[test]
1827- fn table_8_12_breakpoints() {
1828- assert_eq!(beta_prime(15), 0);
1829- assert_eq!(beta_prime(16), 6);
1830- assert_eq!(beta_prime(29), 20);
1831- assert_eq!(beta_prime(51), 64);
1832- assert_eq!(tc_prime(17), 0);
1833- assert_eq!(tc_prime(18), 1);
1834- assert_eq!(tc_prime(53), 24);
1835- // Clip behaviour at the table edges.
1836- assert_eq!(beta_prime(-3), 0);
1837- assert_eq!(tc_prime(99), 24);
1838- }
1839-
1840- /// §8.7.2.5.3 β/tC at 8-bit: qPL = (QpQ+QpP+1)>>1, no offsets, bS=2.
1841- /// QpQ=QpP=37 ⇒ qPL=37 ⇒ Q_beta=37 ⇒ β′=36, β=36; Q_tc=37+2=39 ⇒
1842- /// tC′=5, tC=5.
1843- #[test]
1844- fn luma_beta_tc_no_offset_8bit() {
1845- let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 8);
1846- assert_eq!(beta, 36);
1847- assert_eq!(tc, 5);
1848- // bS=1 lowers the tC index by 2 (Q_tc=37): tC′=4.
1849- let (_, tc1) = luma_beta_tc(37, 37, 1, 0, 0, 8);
1850- assert_eq!(tc1, 4);
1851- }
1852-
1853- /// 10-bit scaling: β and tC are multiplied by 1<<(BitDepthY−8)=4.
1854- #[test]
1855- fn luma_beta_tc_10bit_scaled() {
1856- let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 10);
1857- assert_eq!(beta, 36 * 4);
1858- assert_eq!(tc, 5 * 4);
1859- }
1860-
1861- /// §8.7.2.5.6: a flat region (all-equal samples) passes the decision.
1862- #[test]
1863- fn luma_sample_decision_flat_passes() {
1864- // dpq=0 < β>>2; |p3−p0|+|q0−q3|=0 < β>>3; |p0−q0|=0 < (5tC+1)>>1.
1865- assert!(luma_sample_decision(128, 128, 128, 128, 0, 32, 4));
1866- // A large step at the boundary fails the |p0−q0| test.
1867- assert!(!luma_sample_decision(64, 64, 200, 200, 0, 32, 4));
1868- }
1869-
1870- /// §8.7.2.5.7 strong filter: a flat block stays flat (idempotent).
1871- #[test]
1872- fn strong_filter_flat_is_idempotent() {
1873- let s = [100; 4];
1874- let out = filter_luma_sample(s, s, 2, 0, 0, 6, 8);
1875- assert_eq!(out.ndp, 3);
1876- assert_eq!(out.ndq, 3);
1877- assert_eq!(out.p, [100, 100, 100]);
1878- assert_eq!(out.q, [100, 100, 100]);
1879- }
1880-
1881- /// §8.7.2.5.7 strong filter clips each output to ±2·tC of the input.
1882- #[test]
1883- fn strong_filter_clips_to_two_tc() {
1884- // A hard step: p side 0, q side 255. tC=2 ⇒ p0' clipped to
1885- // p0+2·tC = 0+4 = 4; q0' clipped to q0−2·tC = 255−4 = 251.
1886- let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 2, 0, 0, 2, 8);
1887- assert_eq!(out.p[0], 4);
1888- assert_eq!(out.q[0], 251);
1889- }
1890-
1891- /// §8.7.2.5.7 weak filter: small ramp, dEp=dEq=0 filters only p0/q0.
1892- /// p0=98,q0=102,p1=q1=100 ⇒ δ=(9·4−3·0+8)>>4=2; |δ|<10·tC; clamp to
1893- /// [−tC,tC]=2 ⇒ p0'=100, q0'=100; nDp=nDq=1.
1894- #[test]
1895- fn weak_filter_centres_small_step() {
1896- let out = filter_luma_sample([98, 100, 100, 100], [102, 100, 100, 100], 1, 0, 0, 5, 8);
1897- assert_eq!(out.ndp, 1);
1898- assert_eq!(out.ndq, 1);
1899- assert_eq!(out.p[0], 100);
1900- assert_eq!(out.q[0], 100);
1901- }
1902-
1903- /// §8.7.2.5.7 weak filter no-op when |δ| ≥ 10·tC.
1904- #[test]
1905- fn weak_filter_skips_large_delta() {
1906- // Big step with tiny tC ⇒ |δ| ≥ 10·tC ⇒ nDp=nDq=0, no change.
1907- let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 1, 1, 1, 1, 8);
1908- assert_eq!(out.ndp, 0);
1909- assert_eq!(out.ndq, 0);
1910- assert_eq!(out.p[0], 0);
1911- assert_eq!(out.q[0], 255);
1912- }
1913-
1914- // ----- §8.7.2.5.3 edge decision + §8.7.2.5.5 / .8 chroma -----
1915-
1916- /// §8.7.2.5.3: a perfectly flat edge (d=0 < β) with no step picks the
1917- /// strong filter (dE=2) and sets dEp=dEq=1 (dp=dq=0 < threshold).
1918- #[test]
1919- fn edge_decision_flat_is_strong() {
1920- let flat = [[128, 128], [128, 128], [128, 128], [128, 128]];
1921- let dec = luma_edge_decision(flat, flat, 32, 6);
1922- assert_eq!(dec.de, 2);
1923- assert_eq!(dec.dep, 1);
1924- assert_eq!(dec.deq, 1);
1925- }
1926-
1927- /// §8.7.2.5.3: a large hard step (d ≥ β) leaves dE=0 (no filtering).
1928- #[test]
1929- fn edge_decision_hard_step_no_filter() {
1930- // p side ramps strongly so the second differences make d ≥ β.
1931- let p = [[0, 0], [60, 60], [0, 0], [0, 0]];
1932- let q = [[255, 255], [255, 255], [255, 255], [255, 255]];
1933- let dec = luma_edge_decision(p, q, 8, 2);
1934- assert_eq!(dec.de, 0);
1935- assert_eq!(dec.dep, 0);
1936- assert_eq!(dec.deq, 0);
1937- }
1938-
1939- /// §8.7.2.5.3: a smooth region that passes d<β but fails the strong
1940- /// per-sample decision (a moderate boundary step) selects the weak
1941- /// filter (dE=1).
1942- #[test]
1943- fn edge_decision_moderate_step_is_weak() {
1944- // Flat halves with a step at the boundary: second differences are
1945- // 0 (d=0<β) but |p0−q0| is large ⇒ luma_sample_decision fails.
1946- let p = [[100, 100], [100, 100], [100, 100], [100, 100]];
1947- let q = [[140, 140], [140, 140], [140, 140], [140, 140]];
1948- let dec = luma_edge_decision(p, q, 64, 4);
1949- assert_eq!(dec.de, 1);
1950- }
1951-
1952- /// Table 8-10 (4:2:0) chroma-QP mapping breakpoints.
1953- #[test]
1954- fn table_8_10_chroma_qpc() {
1955- assert_eq!(chroma_qpc_420(29), 29);
1956- assert_eq!(chroma_qpc_420(30), 29);
1957- assert_eq!(chroma_qpc_420(35), 33);
1958- assert_eq!(chroma_qpc_420(43), 37);
1959- assert_eq!(chroma_qpc_420(44), 38);
1960- assert_eq!(chroma_qpc_420(51), 45);
1961- }
1962-
1963- /// §8.7.2.5.5 chroma tC: 4:2:0, QpY=37 both sides, no offsets.
1964- /// qPi=37 ⇒ QpC=34 (Table 8-10) ⇒ Q=34+2=36 ⇒ tC′=4, tC=4 at 8-bit.
1965- #[test]
1966- fn chroma_tc_420_8bit() {
1967- assert_eq!(chroma_tc(37, 37, 0, 1, 0, 8), 4);
1968- // 4:4:4 (chroma_array_type=3): QpC=Min(qPi,51)=37 ⇒ Q=39 ⇒ tC′=5.
1969- assert_eq!(chroma_tc(37, 37, 0, 3, 0, 8), 5);
1970- // 10-bit scales by 1<<(BitDepthC−8)=4.
1971- assert_eq!(chroma_tc(37, 37, 0, 1, 0, 10), 4 * 4);
1972- }
1973-
1974- /// §8.7.2.5.8 chroma sample filter: a flat edge is unchanged.
1975- #[test]
1976- fn chroma_filter_flat_unchanged() {
1977- let (p0, q0) = filter_chroma_sample([100, 100], [100, 100], 6, 8);
1978- assert_eq!(p0, 100);
1979- assert_eq!(q0, 100);
1980- }
1981-
1982- /// §8.7.2.5.8 chroma sample filter centres a small step and clips δ.
1983- /// p0=98,q0=102,p1=q1=100 ⇒ δ=((4·4)+0+4)>>3 = 20>>3 = 2 ⇒ clamp 2 ⇒
1984- /// p0'=100, q0'=100.
1985- #[test]
1986- fn chroma_filter_small_step() {
1987- let (p0, q0) = filter_chroma_sample([98, 100], [102, 100], 6, 8);
1988- assert_eq!(p0, 100);
1989- assert_eq!(q0, 100);
1990- // tC clamp: hard step 0/255, tC=3 ⇒ δ clamped to 3.
1991- let (p0, q0) = filter_chroma_sample([0, 0], [255, 255], 3, 8);
1992- assert_eq!(p0, 3);
1993- assert_eq!(q0, 252);
1994- }
1995-
1996- // ----- §8.7.2.5.4 / .5 plane-level block-edge filtering -----
1997-
1998- /// A vertical edge at plane `(x, y)`.
1999- fn vpos(x: usize, y: usize) -> EdgePos {
2000- EdgePos {
vendor/oxideav-h265/src/decode.rsdeleted+0 -349
@@ -1,349 +0,0 @@
1-//! Picture-sequence decode state machine: the §8.3.1 → §8.3.2 → §8.3.4 →
2-//! §8.3.5 per-picture chain that ties the [`crate::poc`] POC derivation
3-//! and the [`crate::dpb`] decoded-picture buffer together.
4-//!
5-//! [`PictureSequenceState`] threads the cross-picture state — the
6-//! [`crate::poc::PocState`] (`prevTid0Pic`) and the [`crate::dpb::Dpb`] —
7-//! across a coded video sequence. For each coded picture the driver:
8-//!
9-//! 1. derives `PicOrderCntVal` (§8.3.1) from the picture's `NalKind`,
10-//! `TemporalId`, `NoRaslOutputFlag` and `slice_pic_order_cnt_lsb`;
11-//! 2. builds the five §8.3.2 RPS POC lists and applies the §8.3.2 marking
12-//! to the DPB, resolving the RPS to concrete DPB entries;
13-//! 3. for a P / B slice, constructs `RefPicList0` / `RefPicList1` (§8.3.4)
14-//! and selects the §8.3.5 `ColPic` + `NoBackwardPredFlag` for temporal
15-//! MV prediction.
16-//!
17-//! After the picture's samples + per-PU motion field are reconstructed,
18-//! [`PictureSequenceState::store_picture`] inserts it into the DPB as a
19-//! short-term reference, completing the per-picture cycle.
20-
21-use crate::dpb::{
22- build_rps_poc_lists, no_backward_pred_flag, select_col_pic, Dpb, DpbEntry, LongTermEntry,
23- Marking, RefPicListParams, RefPicLists, ResolvedRps,
24-};
25-use crate::motion::MotionField;
26-use crate::picture::Picture;
27-use crate::poc::{NalKind, PicOrderCnt, PocState};
28-use crate::sps::MaterializedShortTermRefPicSet;
29-
30-/// The per-picture §8.3 inputs the [`PictureSequenceState`] driver needs,
31-/// resolved from the picture's NAL header + activated SPS + parsed slice
32-/// segment header.
33-#[derive(Debug, Clone)]
34-pub struct PictureHeaderInfo {
35- /// The picture's `nal_unit_type` classification.
36- pub nal_kind: NalKind,
37- /// `TemporalId`.
38- pub temporal_id: u8,
39- /// `nuh_layer_id`.
40- pub layer_id: u8,
41- /// `NoRaslOutputFlag`.
42- pub no_rasl_output: bool,
43- /// `slice_pic_order_cnt_lsb` (0 for an IDR).
44- pub poc_lsb: u32,
45- /// `MaxPicOrderCntLsb` from the active SPS.
46- pub max_poc_lsb: u32,
47- /// The current picture's materialized short-term RPS
48- /// (`DeltaPocS0` / `UsedByCurrPicS0` / …).
49- pub short_term_rps: MaterializedShortTermRefPicSet,
50- /// The current picture's long-term RPS entries (§7.4.7.1-resolved).
51- pub long_term: Vec<LongTermEntry>,
52-}
53-
54-/// The §8.3 per-picture decode outputs the slice / CU decode then uses.
55-#[derive(Debug, Clone)]
56-pub struct PictureRefState {
57- /// The derived `PicOrderCntVal` (§8.3.1).
58- pub poc: PicOrderCnt,
59- /// The §8.3.2 RPS resolved to DPB entry indices.
60- pub rps: ResolvedRps,
61- /// `RefPicList0` / `RefPicList1` (§8.3.4), `None` for an I slice.
62- pub ref_pic_lists: Option<RefPicLists>,
63- /// `ColPic` (§8.3.5) — DPB index of the collocated picture, when
64- /// `slice_temporal_mvp_enabled_flag` and a P / B slice selected one.
65- pub col_pic: Option<usize>,
66- /// `NoBackwardPredFlag` (§8.3.5).
67- pub no_backward_pred: bool,
68-}
69-
70-/// The per-slice §8.3.4 / §8.3.5 inputs (the reference-list sizing + the
71-/// collocated-picture selectors from the slice segment header).
72-#[derive(Debug, Clone, Copy)]
73-pub struct SliceRefParams {
74- /// `true` for a P or B slice (builds reference lists).
75- pub is_inter: bool,
76- /// `true` for a B slice (builds `RefPicList1`).
77- pub is_b: bool,
78- /// `num_ref_idx_l0_active_minus1`.
79- pub num_ref_idx_l0_active_minus1: u32,
80- /// `num_ref_idx_l1_active_minus1`.
81- pub num_ref_idx_l1_active_minus1: u32,
82- /// `NumPicTotalCurr` (§7.4.7.2).
83- pub num_pic_total_curr: u32,
84- /// `slice_temporal_mvp_enabled_flag`.
85- pub temporal_mvp_enabled: bool,
86- /// `collocated_from_l0_flag` (inferred 1 for a P slice).
87- pub collocated_from_l0_flag: bool,
88- /// `collocated_ref_idx` (inferred 0 when absent).
89- pub collocated_ref_idx: u32,
90- /// `pps_curr_pic_ref_enabled_flag` — the §8.3.4 currPic append
91- /// (intra block copy).
92- pub curr_pic_ref_enabled: bool,
93-}
94-
95-/// The cross-picture decode state for one coded video sequence.
96-#[derive(Debug, Default)]
97-pub struct PictureSequenceState {
98- poc_state: PocState,
99- dpb: Dpb,
100-}
101-
102-impl PictureSequenceState {
103- /// A fresh state at the start of a coded video sequence.
104- #[must_use]
105- pub fn new() -> Self {
106- Self::default()
107- }
108-
109- /// Borrow the decoded-picture buffer (reference-picture inspection).
110- #[must_use]
111- pub fn dpb(&self) -> &Dpb {
112- &self.dpb
113- }
114-
115- /// §8.3.1 → §8.3.2 → §8.3.4 → §8.3.5 — run the per-picture reference
116- /// derivation for a picture about to be decoded.
117- ///
118- /// `header` carries the POC + RPS inputs; `slice` carries the
119- /// reference-list / collocated-picture selectors. The returned
120- /// [`PictureRefState`] is consumed by the slice / CU decode (its
121- /// `RefPicList0` / `ColPic` resolve `RefPicListX[ refIdx ]` and the
122- /// temporal-MV collocated picture).
123- pub fn begin_picture(
124- &mut self,
125- header: &PictureHeaderInfo,
126- slice: &SliceRefParams,
127- ) -> PictureRefState {
128- // Step 1 — §8.3.1 POC.
129- let poc = self.poc_state.decode_picture_poc(
130- header.nal_kind,
131- header.temporal_id,
132- header.no_rasl_output,
133- header.poc_lsb,
134- header.max_poc_lsb,
135- );
136-
137- // Step 2 — §8.3.2 RPS POC lists + DPB marking.
138- let lists = build_rps_poc_lists(
139- header.nal_kind.is_idr(),
140- poc.val,
141- header.max_poc_lsb,
142- &header.short_term_rps,
143- &header.long_term,
144- );
145- let is_irap_no_rasl = header.nal_kind.is_irap() && header.no_rasl_output;
146- let rps = self
147- .dpb
148- .apply_rps(is_irap_no_rasl, header.layer_id, &lists, header.max_poc_lsb);
149-
150- // Step 3 — §8.3.4 reference picture lists (P / B only).
151- let ref_pic_lists = if slice.is_inter {
152- Some(self.dpb.build_ref_pic_lists(
153- &rps,
154- &RefPicListParams {
155- num_ref_idx_l0_active_minus1: slice.num_ref_idx_l0_active_minus1,
156- num_ref_idx_l1_active_minus1: slice.num_ref_idx_l1_active_minus1,
157- num_pic_total_curr: slice.num_pic_total_curr,
158- is_b: slice.is_b,
159- list_entry_l0: None,
160- list_entry_l1: None,
161- curr_pic_ref_enabled: slice.curr_pic_ref_enabled,
162- },
163- ))
164- } else {
165- None
166- };
167-
168- // Step 4 — §8.3.5 ColPic + NoBackwardPredFlag.
169- let (col_pic, no_backward_pred) = match &ref_pic_lists {
170- Some(rpl) if slice.temporal_mvp_enabled => (
171- select_col_pic(
172- rpl,
173- slice.is_b,
174- slice.collocated_from_l0_flag,
175- slice.collocated_ref_idx,
176- ),
177- no_backward_pred_flag(&self.dpb, rpl, poc.val),
178- ),
179- Some(rpl) => (None, no_backward_pred_flag(&self.dpb, rpl, poc.val)),
180- None => (None, true),
181- };
182-
183- PictureRefState {
184- poc,
185- rps,
186- ref_pic_lists,
187- col_pic,
188- no_backward_pred,
189- }
190- }
191-
192- /// Insert a freshly-decoded picture into the DPB as a short-term
193- /// reference, completing the per-picture cycle. `picture` are the
194- /// reconstructed (in-loop-filtered) samples; `motion` is the per-PU
195- /// motion field for the §8.5.3.2.9 collocated-MV derivation of future
196- /// pictures.
197- pub fn store_picture(
198- &mut self,
199- poc: PicOrderCnt,
200- layer_id: u8,
201- picture: Picture,
202- motion: MotionField,
203- ) {
204- self.dpb.insert(DpbEntry {
205- poc: poc.val,
206- layer_id,
207- marking: Marking::ShortTerm,
208- picture,
209- motion,
210- });
211- }
212-}
213-
214-#[cfg(test)]
215-mod tests {
216- use super::*;
217-
218- fn empty_rps() -> MaterializedShortTermRefPicSet {
219- MaterializedShortTermRefPicSet {
220- delta_poc_s0: vec![],
221- used_by_curr_pic_s0: vec![],
222- delta_poc_s1: vec![],
223- used_by_curr_pic_s1: vec![],
224- }
225- }
226-
227- fn idr_header() -> PictureHeaderInfo {
228- PictureHeaderInfo {
229- nal_kind: NalKind::new(NalKind::IDR_N_LP),
230- temporal_id: 0,
231- layer_id: 0,
232- no_rasl_output: true,
233- poc_lsb: 0,
234- max_poc_lsb: 256,
235- short_term_rps: empty_rps(),
236- long_term: vec![],
237- }
238- }
239-
240- fn i_slice() -> SliceRefParams {
241- SliceRefParams {
242- is_inter: false,
243- is_b: false,
244- num_ref_idx_l0_active_minus1: 0,
245- num_ref_idx_l1_active_minus1: 0,
246- num_pic_total_curr: 0,
247- temporal_mvp_enabled: false,
248- collocated_from_l0_flag: true,
249- collocated_ref_idx: 0,
250- curr_pic_ref_enabled: false,
251- }
252- }
253-
254- #[test]
255- fn idr_then_p_frame_resolves_ref_pic_list() {
256- let mut st = PictureSequenceState::new();
257- // IDR (POC 0), I slice, no references.
258- let idr = st.begin_picture(&idr_header(), &i_slice());
259- assert_eq!(idr.poc.val, 0);
260- assert!(idr.ref_pic_lists.is_none());
261- st.store_picture(
262- idr.poc,
263- 0,
264- Picture::new(16, 16, 1, 8, 8),
265- MotionField::new(16, 16),
266- );
267-
268- // P frame (POC 1), one short-term-before ref at POC 0.
269- let p_header = PictureHeaderInfo {
270- nal_kind: NalKind::new(NalKind::TRAIL_R),
271- no_rasl_output: false,
272- poc_lsb: 1,
273- short_term_rps: MaterializedShortTermRefPicSet {
274- delta_poc_s0: vec![-1],
275- used_by_curr_pic_s0: vec![true],
276- delta_poc_s1: vec![],
277- used_by_curr_pic_s1: vec![],
278- },
279- ..idr_header()
280- };
281- let p_slice = SliceRefParams {
282- is_inter: true,
283- num_pic_total_curr: 1,
284- ..i_slice()
285- };
286- let p = st.begin_picture(&p_header, &p_slice);
287- assert_eq!(p.poc.val, 1);
288- let rpl = p.ref_pic_lists.expect("P slice builds RefPicList0");
289- // RefPicList0[0] points at the IDR (DPB index 0).
290- assert_eq!(rpl.list0, vec![Some(0)]);
291- // The IDR stays short-term (it is in the P frame's RPS).
292- assert_eq!(st.dpb().entries()[0].marking, Marking::ShortTerm);
293- // NoBackwardPredFlag: the only ref (POC 0) is in the past of POC 1.
294- assert!(p.no_backward_pred);
295- }
296-
297- #[test]
298- fn temporal_mvp_selects_col_pic() {
299- let mut st = PictureSequenceState::new();
300- let idr = st.begin_picture(&idr_header(), &i_slice());
301- st.store_picture(
302- idr.poc,
303- 0,
304- Picture::new(16, 16, 1, 8, 8),
305- MotionField::new(16, 16),
306- );
307-
308- let p_header = PictureHeaderInfo {
309- nal_kind: NalKind::new(NalKind::TRAIL_R),
310- no_rasl_output: false,
311- poc_lsb: 1,
312- short_term_rps: MaterializedShortTermRefPicSet {
313- delta_poc_s0: vec![-1],
314- used_by_curr_pic_s0: vec![true],
315- delta_poc_s1: vec![],
316- used_by_curr_pic_s1: vec![],
317- },
318- ..idr_header()
319- };
320- let p_slice = SliceRefParams {
321- is_inter: true,
322- num_pic_total_curr: 1,
323- temporal_mvp_enabled: true,
324- collocated_from_l0_flag: true,
325- collocated_ref_idx: 0,
326- curr_pic_ref_enabled: false,
327- ..i_slice()
328- };
329- let p = st.begin_picture(&p_header, &p_slice);
330- // ColPic = RefPicList0[0] = the IDR at DPB index 0.
331- assert_eq!(p.col_pic, Some(0));
332- }
333-
334- #[test]
335- fn second_idr_unmarks_prior_references() {
336- let mut st = PictureSequenceState::new();
337- let idr = st.begin_picture(&idr_header(), &i_slice());
338- st.store_picture(
339- idr.poc,
340- 0,
341- Picture::new(16, 16, 1, 8, 8),
342- MotionField::new(16, 16),
343- );
344- // A second IDR with NoRaslOutputFlag == 1 marks the prior IDR
345- // "unused for reference".
346- let _ = st.begin_picture(&idr_header(), &i_slice());
347- assert_eq!(st.dpb().entries()[0].marking, Marking::Unused);
348- }
349-}
vendor/oxideav-h265/src/decoder.rsdeleted+0 -214
@@ -1,214 +0,0 @@
1-//! Registry decoder — the [`oxideav_core::Decoder`] contract over the
2-//! whole-bitstream [`crate::sequence`] driver.
3-//!
4-//! [`make_decoder`] is the direct factory endpoint (the crate's
5-//! historical direct-API convention); [`crate::register`] wires the
6-//! same factory into the [`oxideav_core`] codec registry under the
7-//! `"h265"` / `"hevc"` ids and the common container tags.
8-//!
9-//! Packets carry either Annex B byte-stream chunks (start-code
10-//! delimited NAL units) or, when `CodecParameters::extradata` is an
11-//! `hvcC` / `HEVCDecoderConfigurationRecord` (ISO/IEC 14496-15
12-//! §8.3.3.1), length-prefixed NAL runs as ISO-BMFF samples carry them.
13-//! Extradata in either form is fed ahead of the first packet so
14-//! out-of-band parameter sets activate. Output frames come in output
15-//! (PicOrderCntVal) order, with packet PTS values re-attached in
16-//! ascending order; an empty packet flushes the reorder queue.
17-
18-use std::collections::BinaryHeap;
19-use std::collections::VecDeque;
20-
21-use oxideav_core::{
22- CodecId, CodecParameters, Decoder, Error, Frame, Packet, Result, VideoFrame, VideoPlane,
23-};
24-
25-use crate::hvcc::{extradata_is_hvcc, parse_hvcc, split_length_prefixed};
26-use crate::picture::{Picture, Plane};
27-use crate::sequence::{DecodedFrame, SequenceDecoder};
28-
29-/// The default reorder depth when no SPS has been activated yet (the
30-/// §7.4.3.2.1 `sps_max_num_reorder_pics` bound once one has).
31-const DEFAULT_REORDER: usize = 8;
32-
33-/// H.265 / HEVC Annex B streaming decoder.
34-pub struct H265Decoder {
35- codec_id: CodecId,
36- seq: SequenceDecoder,
37- /// Decoded pictures not yet emitted, sorted on demand by
38- /// `(cvs_index, poc)`.
39- reorder: Vec<DecodedFrame>,
40- /// Frames ready to hand out.
41- ready: VecDeque<Frame>,
42- /// Min-heap of packet PTS values, re-attached in output order.
43- pts_queue: BinaryHeap<std::cmp::Reverse<i64>>,
44- /// `Some(n)` when the extradata was an `hvcC` record: packets are
45- /// length-prefixed NAL runs with `n`-byte big-endian sizes
46- /// (ISO/IEC 14496-15 §8.3.3.1.3 `lengthSizeMinusOne + 1`).
47- /// `None` for Annex B packets.
48- nal_length_size: Option<usize>,
49- flushed: bool,
50-}
51-
52-impl std::fmt::Debug for H265Decoder {
53- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54- f.debug_struct("H265Decoder")
55- .field("codec_id", &self.codec_id)
56- .field("reorder", &self.reorder.len())
57- .field("ready", &self.ready.len())
58- .finish()
59- }
60-}
61-
62-/// Direct factory endpoint: construct the software H.265 decoder.
63-///
64-/// The `extradata` form selects the packet framing: an `hvcC`
65-/// (`HEVCDecoderConfigurationRecord`) extradata activates its carried
66-/// parameter sets and switches packets to length-prefixed NAL runs;
67-/// Annex B extradata (or none) keeps start-code framing.
68-///
69-/// # Errors
70-/// [`Error::InvalidData`] when the `extradata` fails to parse.
71-pub fn make_decoder(params: &CodecParameters) -> Result<Box<dyn Decoder>> {
72- let mut seq = SequenceDecoder::new();
73- let mut nal_length_size = None;
74- if !params.extradata.is_empty() {
75- if extradata_is_hvcc(&params.extradata) {
76- // hvcC record: out-of-band VPS/SPS/PPS (+ SEI) arrays.
77- let rec = parse_hvcc(&params.extradata)
78- .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?;
79- for unit in rec.nal_units {
80- seq.push_nal_unit(unit)
81- .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?;
82- }
83- nal_length_size = Some(rec.length_size);
84- } else {
85- // Out-of-band parameter sets in Annex B form.
86- seq.push_annexb(&params.extradata)
87- .map_err(|e| Error::InvalidData(format!("h265 extradata: {e}")))?;
88- }
89- }
90- Ok(Box::new(H265Decoder {
91- codec_id: params.codec_id.clone(),
92- seq,
93- reorder: Vec::new(),
94- ready: VecDeque::new(),
95- pts_queue: BinaryHeap::new(),
96- nal_length_size,
97- flushed: false,
98- }))
99-}
100-
101-impl H265Decoder {
102- /// Move decoded pictures into the reorder buffer and emit every
103- /// frame that is guaranteed next in output order.
104- fn drain(&mut self, flush: bool) {
105- self.reorder.extend(self.seq.take_decoded());
106- self.reorder.sort_by_key(|f| (f.cvs_index, f.poc));
107- let depth = if flush {
108- 0
109- } else {
110- self.seq
111- .max_num_reorder_pics()
112- .map_or(DEFAULT_REORDER, |n| n as usize)
113- };
114- while self.reorder.len() > depth {
115- let f = self.reorder.remove(0);
116- if !f.output {
117- continue;
118- }
119- let pts = self.pts_queue.pop().map(|r| r.0);
120- self.ready
121- .push_back(Frame::Video(video_frame(&f.picture, pts)));
122- }
123- }
124-}
125-
126-impl Decoder for H265Decoder {
127- fn codec_id(&self) -> &CodecId {
128- &self.codec_id
129- }
130-
131- fn send_packet(&mut self, packet: &Packet) -> Result<()> {
132- if packet.data.is_empty() {
133- // An empty packet is treated as a flush signal too.
134- return self.flush();
135- }
136- if let Some(pts) = packet.pts {
137- self.pts_queue.push(std::cmp::Reverse(pts));
138- }
139- if let Some(length_size) = self.nal_length_size {
140- let units = split_length_prefixed(&packet.data, length_size)
141- .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?;
142- for unit in units {
143- self.seq
144- .push_nal_unit(unit)
145- .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?;
146- }
147- } else {
148- self.seq
149- .push_annexb(&packet.data)
150- .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?;
151- }
152- self.drain(false);
153- Ok(())
154- }
155-
156- fn receive_frame(&mut self) -> Result<Frame> {
157- if let Some(f) = self.ready.pop_front() {
158- return Ok(f);
159- }
160- if self.flushed {
161- if !self.reorder.is_empty() {
162- self.drain(true);
163- if let Some(f) = self.ready.pop_front() {
164- return Ok(f);
165- }
166- }
167- return Err(Error::Eof);
168- }
169- Err(Error::NeedMore)
170- }
171-
172- fn flush(&mut self) -> Result<()> {
173- // Decode any pending picture and release the reorder queue.
174- self.seq
175- .flush()
176- .map_err(|e| Error::InvalidData(format!("h265 flush: {e}")))?;
177- self.flushed = true;
178- self.drain(true);
179- Ok(())
180- }
181-}
182-
183-/// Pack a reconstructed [`Picture`] into a [`VideoFrame`] (8-bit planes
184-/// as one byte per sample; higher bit depths as little-endian 16-bit,
185-/// the planar `p010le`-family layout).
186-fn video_frame(pic: &Picture, pts: Option<i64>) -> VideoFrame {
187- let planes = if pic.chroma_array_type() == 0 {
188- vec![Plane::Luma]
189- } else {
190- vec![Plane::Luma, Plane::Cb, Plane::Cr]
191- };
192- let wide = pic.bit_depth(Plane::Luma) > 8
193- || (pic.chroma_array_type() != 0 && pic.bit_depth(Plane::Cb) > 8);
194- let mut out = Vec::with_capacity(planes.len());
195- for plane in planes {
196- let (w, h) = pic.plane_dims(plane);
197- let buf = pic.plane(plane);
198- let mut data;
199- let stride;
200- if wide {
201- stride = w * 2;
202- data = Vec::with_capacity(w * h * 2);
203- for &v in buf.iter().take(w * h) {
204- data.extend_from_slice(&(v as u16).to_le_bytes());
205- }
206- } else {
207- stride = w;
208- data = Vec::with_capacity(w * h);
209- data.extend(buf.iter().take(w * h).map(|&v| v as u8));
210- }
211- out.push(VideoPlane { stride, data });
212- }
213- VideoFrame { pts, planes: out }
214-}
vendor/oxideav-h265/src/dpb.rsdeleted+0 -833
@@ -1,833 +0,0 @@
1-//! §8.3.2 reference-picture-set marking, §8.3.4 reference-picture-list
2-//! construction, §8.3.5 collocated-picture selection, and the
3-//! decoded-picture-buffer (DPB) storage that ties them together.
4-//!
5-//! A [`Dpb`] holds the previously-decoded pictures available for
6-//! inter prediction of the current and future pictures. Each
7-//! [`DpbEntry`] carries:
8-//!
9-//! * the reconstructed [`crate::picture::Picture`] samples
10-//! (`refPicLXL` / `refPicLXCb` / `refPicLXCr` of §8.5.3.3.2),
11-//! * its `PicOrderCntVal` (the §8.3.1 identity used to address it),
12-//! * its short/long-term reference [`Marking`],
13-//! * its per-PU [`crate::motion::MotionField`] (the `MvLXCol` /
14-//! `PredFlagLXCol` / `RefIdxLXCol`-equivalent arrays the §8.5.3.2.9
15-//! collocated-MV derivation reads).
16-//!
17-//! The picture-decode driver, after deriving the current picture's POC
18-//! (§8.3.1), calls [`Dpb::apply_rps`] to build the five §8.3.2 RPS lists
19-//! (`RefPicSetStCurrBefore` … `RefPicSetLtFoll`) and mark every DPB
20-//! picture accordingly. For a P / B slice it then calls
21-//! [`Dpb::build_ref_pic_lists`] (§8.3.4) to construct `RefPicList0` /
22-//! `RefPicList1`, and [`select_col_pic`] (§8.3.5) to pick the collocated
23-//! picture for temporal MV prediction.
24-
25-use crate::motion::MotionField;
26-use crate::picture::Picture;
27-use crate::poc::diff_pic_order_cnt;
28-use crate::sps::MaterializedShortTermRefPicSet;
29-
30-/// A decoded picture's reference marking (§8.3.2). Exactly one of these
31-/// applies at any moment.
32-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33-pub enum Marking {
34- /// "unused for reference".
35- Unused,
36- /// "used for short-term reference".
37- ShortTerm,
38- /// "used for long-term reference".
39- LongTerm,
40-}
41-
42-/// One decoded picture stored in the [`Dpb`].
43-#[derive(Debug)]
44-pub struct DpbEntry {
45- /// `PicOrderCntVal` (§8.3.1).
46- pub poc: i32,
47- /// `nuh_layer_id` of the picture.
48- pub layer_id: u8,
49- /// The current reference [`Marking`].
50- pub marking: Marking,
51- /// The reconstructed sample planes (`SL` / `SCb` / `SCr`).
52- pub picture: Picture,
53- /// The per-PU motion field — the §8.5.3.2.9 collocated arrays
54- /// (`PredFlagLXCol`, `MvLXCol`, the per-cell reference-picture POC
55- /// identity standing in for `RefIdxLXCol` → `refPicListCol`).
56- pub motion: MotionField,
57-}
58-
59-impl DpbEntry {
60- /// `( PicOrderCntVal & ( MaxPicOrderCntLsb − 1 ) )` — the LSB-only
61- /// identity used for the §8.3.2 short-term-vs-long-term lookup of a
62- /// long-term entry whose `delta_poc_msb_present_flag` is 0.
63- #[inline]
64- #[must_use]
65- fn poc_lsb(&self, max_poc_lsb: u32) -> u32 {
66- (self.poc as u32) & (max_poc_lsb - 1)
67- }
68-}
69-
70-/// The five §8.3.2 RPS POC lists (equation 8-5).
71-#[derive(Debug, Clone, Default, PartialEq, Eq)]
72-pub struct RpsPocLists {
73- /// `PocStCurrBefore`.
74- pub st_curr_before: Vec<i32>,
75- /// `PocStCurrAfter`.
76- pub st_curr_after: Vec<i32>,
77- /// `PocStFoll`.
78- pub st_foll: Vec<i32>,
79- /// `PocLtCurr`.
80- pub lt_curr: Vec<i32>,
81- /// `PocLtFoll`.
82- pub lt_foll: Vec<i32>,
83- /// `CurrDeltaPocMsbPresentFlag[i]` (paired with `lt_curr`).
84- pub curr_delta_poc_msb_present: Vec<bool>,
85- /// `FollDeltaPocMsbPresentFlag[i]` (paired with `lt_foll`).
86- pub foll_delta_poc_msb_present: Vec<bool>,
87-}
88-
89-/// One long-term RPS input entry — the §7.4.7.1 / §8.3.2 long-term
90-/// reference, already resolved to `PocLsbLt[i]` plus the MSB-cycle block.
91-#[derive(Debug, Clone, Copy)]
92-pub struct LongTermEntry {
93- /// `PocLsbLt[i]`.
94- pub poc_lsb_lt: u32,
95- /// `UsedByCurrPicLt[i]`.
96- pub used_by_curr_pic_lt: bool,
97- /// `delta_poc_msb_present_flag[i]`.
98- pub delta_poc_msb_present: bool,
99- /// `DeltaPocMsbCycleLt[i]` (the §7.4.7.1 accumulated cycle).
100- pub delta_poc_msb_cycle_lt: u32,
101-}
102-
103-/// Build the five §8.3.2 POC lists (equation 8-5) for the current
104-/// picture from its current short-term RPS + long-term entries.
105-///
106-/// `is_idr` short-circuits all five lists to empty (the §8.3.2 IDR rule).
107-/// `poc` is the current `PicOrderCntVal`; `max_poc_lsb` is
108-/// `MaxPicOrderCntLsb`.
109-#[must_use]
110-pub fn build_rps_poc_lists(
111- is_idr: bool,
112- poc: i32,
113- max_poc_lsb: u32,
114- st_rps: &MaterializedShortTermRefPicSet,
115- lt_entries: &[LongTermEntry],
116-) -> RpsPocLists {
117- let mut out = RpsPocLists::default();
118- if is_idr {
119- return out;
120- }
121- // Negative (S0) pics — equation 8-5 first loop.
122- for (i, &delta) in st_rps.delta_poc_s0.iter().enumerate() {
123- let p = poc + delta;
124- if st_rps.used_by_curr_pic_s0[i] {
125- out.st_curr_before.push(p);
126- } else {
127- out.st_foll.push(p);
128- }
129- }
130- // Positive (S1) pics — equation 8-5 second loop.
131- for (i, &delta) in st_rps.delta_poc_s1.iter().enumerate() {
132- let p = poc + delta;
133- if st_rps.used_by_curr_pic_s1[i] {
134- out.st_curr_after.push(p);
135- } else {
136- out.st_foll.push(p);
137- }
138- }
139- // Long-term — equation 8-5 third loop.
140- for e in lt_entries {
141- let mut poc_lt = e.poc_lsb_lt as i32;
142- if e.delta_poc_msb_present {
143- poc_lt += poc
144- - (e.delta_poc_msb_cycle_lt as i32) * (max_poc_lsb as i32)
145- - (poc & (max_poc_lsb as i32 - 1));
146- }
147- if e.used_by_curr_pic_lt {
148- out.lt_curr.push(poc_lt);
149- out.curr_delta_poc_msb_present.push(e.delta_poc_msb_present);
150- } else {
151- out.lt_foll.push(poc_lt);
152- out.foll_delta_poc_msb_present.push(e.delta_poc_msb_present);
153- }
154- }
155- out
156-}
157-
158-/// The decoded-picture buffer.
159-#[derive(Debug, Default)]
160-pub struct Dpb {
161- entries: Vec<DpbEntry>,
162-}
163-
164-impl Dpb {
165- /// An empty DPB.
166- #[must_use]
167- pub fn new() -> Self {
168- Self::default()
169- }
170-
171- /// Number of pictures currently stored.
172- #[inline]
173- #[must_use]
174- pub fn len(&self) -> usize {
175- self.entries.len()
176- }
177-
178- /// Whether the DPB holds no pictures.
179- #[inline]
180- #[must_use]
181- pub fn is_empty(&self) -> bool {
182- self.entries.is_empty()
183- }
184-
185- /// Borrow the stored entries (output / bumping inspection).
186- #[must_use]
187- pub fn entries(&self) -> &[DpbEntry] {
188- &self.entries
189- }
190-
191- /// Insert a freshly-decoded picture, marked "used for short-term
192- /// reference" per the §8.3.2 default. The picture-decode driver calls
193- /// this after reconstruction + in-loop filtering, having already run
194- /// [`Dpb::apply_rps`] for the picture's own RPS.
195- pub fn insert(&mut self, entry: DpbEntry) {
196- self.entries.push(entry);
197- }
198-
199- /// Find a stored picture by exact `PicOrderCntVal` and `nuh_layer_id`.
200- #[must_use]
201- pub fn find_by_poc(&self, poc: i32, layer_id: u8) -> Option<&DpbEntry> {
202- self.entries
203- .iter()
204- .find(|e| e.poc == poc && e.layer_id == layer_id)
205- }
206-
207- /// Find a short-term reference picture by exact POC (§8.3.2 step 3).
208- fn find_short_term(&self, poc: i32, layer_id: u8) -> Option<usize> {
209- self.entries
210- .iter()
211- .position(|e| e.poc == poc && e.layer_id == layer_id && e.marking == Marking::ShortTerm)
212- }
213-
214- /// Find a long-term candidate by exact POC or by LSB-only POC
215- /// (§8.3.2 step 1).
216- fn find_long_term(
217- &self,
218- target: i32,
219- msb_present: bool,
220- max_poc_lsb: u32,
221- layer_id: u8,
222- ) -> Option<usize> {
223- self.entries.iter().position(|e| {
224- e.layer_id == layer_id
225- && if msb_present {
226- e.poc == target
227- } else {
228- e.poc_lsb(max_poc_lsb) == (target as u32) & (max_poc_lsb - 1)
229- }
230- })
231- }
232-
233- /// §8.3.2 — apply the reference-picture-set marking for the current
234- /// picture.
235- ///
236- /// `is_irap_no_rasl` is `true` for an IRAP picture with
237- /// `NoRaslOutputFlag == 1` (all current references become "unused");
238- /// `layer_id` is the current picture's `nuh_layer_id`; `lists` is the
239- /// output of [`build_rps_poc_lists`]; `max_poc_lsb` is
240- /// `MaxPicOrderCntLsb`.
241- ///
242- /// Returns the five resolved RPS reference-picture lists as index
243- /// vectors into [`Dpb::entries`]; a `None` entry is the §8.3.2 "no
244- /// reference picture". After this call every DPB picture carries its
245- /// updated [`Marking`].
246- pub fn apply_rps(
247- &mut self,
248- is_irap_no_rasl: bool,
249- layer_id: u8,
250- lists: &RpsPocLists,
251- max_poc_lsb: u32,
252- ) -> ResolvedRps {
253- // §8.3.2 — an IRAP with NoRaslOutputFlag == 1 marks every current
254- // reference of this layer "unused for reference" up front.
255- if is_irap_no_rasl {
256- for e in &mut self.entries {
257- if e.layer_id == layer_id {
258- e.marking = Marking::Unused;
259- }
260- }
261- }
262-
263- let mut resolved = ResolvedRps::default();
264-
265- // Step 1 — resolve the long-term RPS sets (LSB or full POC).
266- for (i, &poc_lt) in lists.lt_curr.iter().enumerate() {
267- resolved.lt_curr.push(self.find_long_term(
268- poc_lt,
269- lists.curr_delta_poc_msb_present[i],
270- max_poc_lsb,
271- layer_id,
272- ));
273- }
274- for (i, &poc_lt) in lists.lt_foll.iter().enumerate() {
275- resolved.lt_foll.push(self.find_long_term(
276- poc_lt,
277- lists.foll_delta_poc_msb_present[i],
278- max_poc_lsb,
279- layer_id,
280- ));
281- }
282-
283- // Step 2 — mark the long-term picks "used for long-term reference".
284- for idx in resolved
285- .lt_curr
286- .iter()
287- .chain(resolved.lt_foll.iter())
288- .flatten()
289- {
290- self.entries[*idx].marking = Marking::LongTerm;
291- }
292-
293- // Step 3 — resolve the short-term RPS sets (exact POC).
294- for &poc in &lists.st_curr_before {
295- resolved
296- .st_curr_before
297- .push(self.find_short_term(poc, layer_id));
298- }
299- for &poc in &lists.st_curr_after {
300- resolved
301- .st_curr_after
302- .push(self.find_short_term(poc, layer_id));
303- }
304- for &poc in &lists.st_foll {
305- resolved.st_foll.push(self.find_short_term(poc, layer_id));
306- }
307-
308- // Step 4 — any picture of this layer not in any RPS set is
309- // "unused for reference".
310- let mut keep = vec![false; self.entries.len()];
311- for idx in resolved
312- .lt_curr
313- .iter()
314- .chain(resolved.lt_foll.iter())
315- .chain(resolved.st_curr_before.iter())
316- .chain(resolved.st_curr_after.iter())
317- .chain(resolved.st_foll.iter())
318- .flatten()
319- {
320- keep[*idx] = true;
321- }
322- for (i, e) in self.entries.iter_mut().enumerate() {
323- if e.layer_id == layer_id && !keep[i] {
324- e.marking = Marking::Unused;
325- }
326- }
327-
328- resolved
329- }
330-
331- /// §8.3.4 — construct `RefPicList0` (and, for a B slice,
332- /// `RefPicList1`) as index vectors into [`Dpb::entries`].
333- ///
334- /// `rps` is the [`apply_rps`](Dpb::apply_rps) output; `params` carries
335- /// the §8.3.4 sizing + modification inputs. With
336- /// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) the
337- /// equation 8-8 / 8-10 wrap appends the current picture — the
338- /// [`CURR_PIC`] sentinel — after `RefPicSetLtCurr` on every pass,
339- /// and the equation 8-9 closing clause overrides the last active
340- /// `RefPicList0` slot when the temp list was longer than the
341- /// active count and no explicit modification was signalled.
342- #[must_use]
343- pub fn build_ref_pic_lists(
344- &self,
345- rps: &ResolvedRps,
346- params: &RefPicListParams<'_>,
347- ) -> RefPicLists {
348- // RefPicListTemp0 (equation 8-8): StCurrBefore, StCurrAfter, LtCurr,
349- // (+ currPic with pps_curr_pic_ref_enabled_flag), repeated until
350- // NumRpsCurrTempList0 entries are produced.
351- let active0 = (params.num_ref_idx_l0_active_minus1 + 1) as usize;
352- let num_temp0 = active0.max(params.num_pic_total_curr as usize);
353- let temp0 = build_temp_list(
354- num_temp0,
355- &[&rps.st_curr_before, &rps.st_curr_after, &rps.lt_curr],
356- params.curr_pic_ref_enabled,
357- );
358- let mut list0 = apply_list_modification(&temp0, active0, params.list_entry_l0);
359- // Equation 8-9 closing clause.
360- if params.curr_pic_ref_enabled && params.list_entry_l0.is_none() && num_temp0 > active0 {
361- if let Some(last) = list0.last_mut() {
362- *last = Some(CURR_PIC);
363- }
364- }
365-
366- let list1 = if params.is_b {
367- // RefPicListTemp1 (equation 8-10): StCurrAfter, StCurrBefore,
368- // LtCurr (note the swapped first two sets).
369- let active1 = (params.num_ref_idx_l1_active_minus1 + 1) as usize;
370- let num_temp1 = active1.max(params.num_pic_total_curr as usize);
371- let temp1 = build_temp_list(
372- num_temp1,
373- &[&rps.st_curr_after, &rps.st_curr_before, &rps.lt_curr],
374- params.curr_pic_ref_enabled,
375- );
376- Some(apply_list_modification(
377- &temp1,
378- active1,
379- params.list_entry_l1,
380- ))
381- } else {
382- None
383- };
384-
385- RefPicLists { list0, list1 }
386- }
387-}
388-
389-/// The [`RefPicLists`] sentinel index standing for the CURRENT decoded
390-/// picture (before in-loop filtering) — the §8.3.4 `currPic` appended
391-/// when `pps_curr_pic_ref_enabled_flag` is 1. It is deliberately out of
392-/// range for every real DPB entry vector; consumers must test for it
393-/// before indexing.
394-pub const CURR_PIC: usize = usize::MAX;
395-
396-/// §8.3.4 sizing + modification inputs for
397-/// [`Dpb::build_ref_pic_lists`].
398-#[derive(Debug, Clone, Copy, Default)]
399-pub struct RefPicListParams<'a> {
400- /// `num_ref_idx_l0_active_minus1`.
401- pub num_ref_idx_l0_active_minus1: u32,
402- /// `num_ref_idx_l1_active_minus1`.
403- pub num_ref_idx_l1_active_minus1: u32,
404- /// `NumPicTotalCurr` (§7.4.7.2).
405- pub num_pic_total_curr: u32,
406- /// `true` for a B slice (builds `RefPicList1`).
407- pub is_b: bool,
408- /// `list_entry_l0[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp0`.
409- pub list_entry_l0: Option<&'a [u32]>,
410- /// `list_entry_l1[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp1`.
411- pub list_entry_l1: Option<&'a [u32]>,
412- /// `pps_curr_pic_ref_enabled_flag` — appends the [`CURR_PIC`]
413- /// sentinel per equations 8-8 / 8-9 / 8-10.
414- pub curr_pic_ref_enabled: bool,
415-}
416-
417-/// The §8.3.2 RPS resolved to DPB entry indices. A `None` is the spec's
418-/// "no reference picture".
419-#[derive(Debug, Clone, Default, PartialEq, Eq)]
420-pub struct ResolvedRps {
421- /// `RefPicSetStCurrBefore`.
422- pub st_curr_before: Vec<Option<usize>>,
423- /// `RefPicSetStCurrAfter`.
424- pub st_curr_after: Vec<Option<usize>>,
425- /// `RefPicSetStFoll`.
426- pub st_foll: Vec<Option<usize>>,
427- /// `RefPicSetLtCurr`.
428- pub lt_curr: Vec<Option<usize>>,
429- /// `RefPicSetLtFoll`.
430- pub lt_foll: Vec<Option<usize>>,
431-}
432-
433-/// The §8.3.4 reference picture lists, as DPB entry indices. A `None`
434-/// entry is a "no reference picture" carried through from the RPS.
435-#[derive(Debug, Clone, PartialEq, Eq)]
436-pub struct RefPicLists {
437- /// `RefPicList0`.
438- pub list0: Vec<Option<usize>>,
439- /// `RefPicList1` (only for B slices).
440- pub list1: Option<Vec<Option<usize>>>,
441-}
442-
443-/// §8.3.5 — select the collocated picture `ColPic` for temporal MV
444-/// prediction, returning its DPB entry index.
445-///
446-/// `slice_type_is_b` + `collocated_from_l0_flag` choose the list per
447-/// §8.3.5; `collocated_ref_idx` indexes it. Returns `None` when the
448-/// chosen entry is "no reference picture" or the index is out of range.
449-#[must_use]
450-pub fn select_col_pic(
451- lists: &RefPicLists,
452- slice_type_is_b: bool,
453- collocated_from_l0_flag: bool,
454- collocated_ref_idx: u32,
455-) -> Option<usize> {
456- let idx = collocated_ref_idx as usize;
457- let picked = if slice_type_is_b && !collocated_from_l0_flag {
458- lists.list1.as_ref()?.get(idx).copied().flatten()
459- } else {
460- lists.list0.get(idx).copied().flatten()
461- };
462- // §7.4.7.1: collocated_ref_idx shall not refer to the current
463- // picture — treat a malformed selection as "no collocated picture".
464- picked.filter(|&i| i != CURR_PIC)
465-}
466-
467-/// §8.3.5 — `NoBackwardPredFlag`: true iff every reference picture in
468-/// `RefPicList0` / `RefPicList1` has `DiffPicOrderCnt( aPic, CurrPic )
469-/// <= 0`. `curr_poc` is the current picture's `PicOrderCntVal`; the
470-/// closure resolves a DPB index to its POC.
471-#[must_use]
472-pub fn no_backward_pred_flag(dpb: &Dpb, lists: &RefPicLists, curr_poc: i32) -> bool {
473- let mut all_le = true;
474- let check = |idx: &Option<usize>, all_le: &mut bool| {
475- if let Some(i) = idx {
476- // The current picture (CURR_PIC) has DiffPicOrderCnt == 0.
477- if *i != CURR_PIC && diff_pic_order_cnt(dpb.entries[*i].poc, curr_poc) > 0 {
478- *all_le = false;
479- }
480- }
481- };
482- for idx in &lists.list0 {
483- check(idx, &mut all_le);
484- }
485- if let Some(l1) = &lists.list1 {
486- for idx in l1 {
487- check(idx, &mut all_le);
488- }
489- }
490- all_le
491-}
492-
493-/// Build a §8.3.4 `RefPicListTempX` by concatenating the given RPS sets
494-/// in order — appending the [`CURR_PIC`] sentinel after each pass when
495-/// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) — and
496-/// wrapping around until `len` entries are produced (equations
497-/// 8-8 / 8-10).
498-fn build_temp_list(
499- len: usize,
500- sets: &[&[Option<usize>]],
501- curr_pic_ref_enabled: bool,
502-) -> Vec<Option<usize>> {
503- let mut temp = Vec::with_capacity(len);
504- if sets.iter().all(|s| s.is_empty()) && !curr_pic_ref_enabled {
505- return temp;
506- }
507- while temp.len() < len {
508- for set in sets {
509- for &e in *set {
510- if temp.len() >= len {
511- break;
512- }
513- temp.push(e);
514- }
515- }
516- if curr_pic_ref_enabled {
517- // The equation 8-8 / 8-10 currPic append carries no
518- // `rIdx < NumRpsCurrTempListX` guard — the temp list may
519- // end one entry longer than `len` (reachable through
520- // `list_entry_lX`).
521- temp.push(Some(CURR_PIC));
522- }
523- }
524- temp
525-}
526-
527-/// Apply the §8.3.4 `RefPicListX` selection (equation 8-9 / 8-11): take
528-/// the first `active` entries of `temp`, reordered through `list_entry`
529-/// when present.
530-fn apply_list_modification(
531- temp: &[Option<usize>],
532- active: usize,
533- list_entry: Option<&[u32]>,
534-) -> Vec<Option<usize>> {
535- (0..active)
536- .map(|r_idx| match list_entry {
537- Some(le) => temp.get(le[r_idx] as usize).copied().flatten(),
538- None => temp.get(r_idx).copied().flatten(),
539- })
540- .collect()
541-}
542-
543-#[cfg(test)]
544-mod tests {
545- use super::*;
546- use crate::picture::Picture;
547-
548- fn entry(poc: i32, marking: Marking) -> DpbEntry {
549- DpbEntry {
550- poc,
551- layer_id: 0,
552- marking,
553- picture: Picture::new(16, 16, 1, 8, 8),
554- motion: MotionField::new(16, 16),
555- }
556- }
557-
558- fn empty_st_rps() -> MaterializedShortTermRefPicSet {
559- MaterializedShortTermRefPicSet {
560- delta_poc_s0: vec![],
561- used_by_curr_pic_s0: vec![],
562- delta_poc_s1: vec![],
563- used_by_curr_pic_s1: vec![],
564- }
565- }
566-
567- #[test]
568- fn idr_rps_lists_are_empty() {
569- let st = empty_st_rps();
570- let lists = build_rps_poc_lists(true, 0, 256, &st, &[]);
571- assert!(lists.st_curr_before.is_empty());
572- assert!(lists.st_curr_after.is_empty());
573- assert!(lists.lt_curr.is_empty());
574- }
575-
576- #[test]
577- fn p_frame_short_term_before_resolves_idr() {
578- // One negative pic at delta −1, used by curr ⇒ PocStCurrBefore
579- // = [poc 1 + (−1)] = [0], which resolves to the IDR in the DPB.
580- let st = MaterializedShortTermRefPicSet {
581- delta_poc_s0: vec![-1],
582- used_by_curr_pic_s0: vec![true],
583- delta_poc_s1: vec![],
584- used_by_curr_pic_s1: vec![],
585- };
586- let lists = build_rps_poc_lists(false, 1, 256, &st, &[]);
587- assert_eq!(lists.st_curr_before, vec![0]);
588-
589- let mut dpb = Dpb::new();
590- dpb.insert(entry(0, Marking::ShortTerm));
591- let rps = dpb.apply_rps(false, 0, &lists, 256);
592- assert_eq!(rps.st_curr_before, vec![Some(0)]);
593- // The IDR stays short-term (it is in the RPS).
594- assert_eq!(dpb.entries[0].marking, Marking::ShortTerm);
595- }
596-
597- #[test]
598- fn picture_not_in_rps_becomes_unused() {
599- let st = empty_st_rps();
600- let lists = build_rps_poc_lists(false, 5, 256, &st, &[]);
601- let mut dpb = Dpb::new();
602- dpb.insert(entry(0, Marking::ShortTerm));
603- dpb.apply_rps(false, 0, &lists, 256);
604- // poc 0 is in no RPS list ⇒ unused for reference.
605- assert_eq!(dpb.entries[0].marking, Marking::Unused);
606- }
607-
608- #[test]
609- fn irap_no_rasl_unmarks_all_references() {
610- let st = empty_st_rps();
611- let lists = build_rps_poc_lists(true, 0, 256, &st, &[]);
612- let mut dpb = Dpb::new();
613- dpb.insert(entry(0, Marking::ShortTerm));
614- dpb.insert(entry(2, Marking::LongTerm));
615- dpb.apply_rps(true, 0, &lists, 256);
616- assert!(dpb.entries.iter().all(|e| e.marking == Marking::Unused));
617- }
618-
619- #[test]
620- fn p_ref_pic_list0_takes_curr_before() {
621- // DPB holds POC 0 (IDR). Current P-frame POC 1 with one
622- // short-term-before pic at POC 0.
623- let st = MaterializedShortTermRefPicSet {
624- delta_poc_s0: vec![-1],
625- used_by_curr_pic_s0: vec![true],
626- delta_poc_s1: vec![],
627- used_by_curr_pic_s1: vec![],
628- };
629- let lists = build_rps_poc_lists(false, 1, 256, &st, &[]);
630- let mut dpb = Dpb::new();
631- dpb.insert(entry(0, Marking::ShortTerm));
632- let rps = dpb.apply_rps(false, 0, &lists, 256);
633- let rpl = dpb.build_ref_pic_lists(
634- &rps,
635- &RefPicListParams {
636- num_pic_total_curr: 1,
637- ..Default::default()
638- },
639- );
640- assert_eq!(rpl.list0, vec![Some(0)]);
641- assert!(rpl.list1.is_none());
642- }
643-
644- /// §8.3.4 with `pps_curr_pic_ref_enabled_flag`: the current picture
645- /// (CURR_PIC) is appended after the RPS sets (eq. 8-8) — a P slice
646- /// with one short-term reference and two active entries lists
647- /// [ref, currPic].
648- #[test]
649- fn curr_pic_ref_appends_current_picture() {
650- let st = MaterializedShortTermRefPicSet {
651- delta_poc_s0: vec![-1],
652- used_by_curr_pic_s0: vec![true],
653- delta_poc_s1: vec![],
654- used_by_curr_pic_s1: vec![],
655- };
656- let lists = build_rps_poc_lists(false, 1, 256, &st, &[]);
657- let mut dpb = Dpb::new();
658- dpb.insert(entry(0, Marking::ShortTerm));
659- let rps = dpb.apply_rps(false, 0, &lists, 256);
660- let rpl = dpb.build_ref_pic_lists(
661- &rps,
662- &RefPicListParams {
663- num_ref_idx_l0_active_minus1: 1,
664- num_pic_total_curr: 2,
665- curr_pic_ref_enabled: true,
666- ..Default::default()
667- },
668- );
669- assert_eq!(rpl.list0, vec![Some(0), Some(CURR_PIC)]);
670- }
671-
672- /// An IRAP-only stream (empty RPS) with current-picture referencing
673- /// still builds a list: [currPic] (the intra-block-copy-only case).
674- #[test]
675- fn curr_pic_ref_fills_empty_rps_list() {
676- let dpb = Dpb::new();
677- let rps = ResolvedRps::default();
678- let rpl = dpb.build_ref_pic_lists(
679- &rps,
680- &RefPicListParams {
681- num_ref_idx_l0_active_minus1: 0,
682- num_pic_total_curr: 1,
683- curr_pic_ref_enabled: true,
684- ..Default::default()
685- },
686- );
687- assert_eq!(rpl.list0, vec![Some(CURR_PIC)]);
688- }
689-
690- /// The eq. 8-9 closing clause: with the temp list longer than the
691- /// active count and no explicit modification, the LAST active slot
692- /// is overridden to currPic — one short-term ref, one active entry,
693- /// NumPicTotalCurr 2 ⇒ list0 = [currPic].
694- #[test]
695- fn curr_pic_ref_overrides_last_active_slot() {
696- let st = MaterializedShortTermRefPicSet {
697- delta_poc_s0: vec![-1],
698- used_by_curr_pic_s0: vec![true],
699- delta_poc_s1: vec![],
700- used_by_curr_pic_s1: vec![],
701- };
702- let lists = build_rps_poc_lists(false, 1, 256, &st, &[]);
703- let mut dpb = Dpb::new();
704- dpb.insert(entry(0, Marking::ShortTerm));
705- let rps = dpb.apply_rps(false, 0, &lists, 256);
706- let rpl = dpb.build_ref_pic_lists(
707- &rps,
708- &RefPicListParams {
709- num_ref_idx_l0_active_minus1: 0,
710- num_pic_total_curr: 2,
711- curr_pic_ref_enabled: true,
712- ..Default::default()
713- },
714- );
715- assert_eq!(rpl.list0, vec![Some(CURR_PIC)]);
716- }
717-
718- /// select_col_pic never yields the CURR_PIC sentinel (§7.4.7.1
719- /// forbids collocated_ref_idx referring to the current picture).
720- #[test]
721- fn col_pic_selection_rejects_curr_pic() {
722- let lists = RefPicLists {
723- list0: vec![Some(CURR_PIC)],
724- list1: None,
725- };
726- assert_eq!(select_col_pic(&lists, false, true, 0), None);
727- }
728-
729- /// no_backward_pred_flag treats currPic as DiffPicOrderCnt == 0
730- /// (not a future reference).
731- #[test]
732- fn no_backward_pred_ignores_curr_pic() {
733- let dpb = Dpb::new();
734- let lists = RefPicLists {
735- list0: vec![Some(CURR_PIC)],
736- list1: None,
737- };
738- assert!(no_backward_pred_flag(&dpb, &lists, 5));
739- }
740-
741- #[test]
742- fn b_ref_pic_lists_swap_before_after() {
743- // Current B POC 1, with a before-pic at POC 0 and an after-pic at
744- // POC 2. RefPicList0 = [before, after]; RefPicList1 = [after,
745- // before].
746- let st = MaterializedShortTermRefPicSet {
747- delta_poc_s0: vec![-1],
748- used_by_curr_pic_s0: vec![true],
749- delta_poc_s1: vec![1],
750- used_by_curr_pic_s1: vec![true],
751- };
752- let lists = build_rps_poc_lists(false, 1, 256, &st, &[]);
753- assert_eq!(lists.st_curr_before, vec![0]);
754- assert_eq!(lists.st_curr_after, vec![2]);
755- let mut dpb = Dpb::new();
756- dpb.insert(entry(0, Marking::ShortTerm)); // index 0 = POC 0
757- dpb.insert(entry(2, Marking::ShortTerm)); // index 1 = POC 2
758- let rps = dpb.apply_rps(false, 0, &lists, 256);
759- let rpl = dpb.build_ref_pic_lists(
760- &rps,
761- &RefPicListParams {
762- num_ref_idx_l0_active_minus1: 1,
763- num_ref_idx_l1_active_minus1: 1,
764- num_pic_total_curr: 2,
765- is_b: true,
766- ..Default::default()
767- },
768- );
769- assert_eq!(rpl.list0, vec![Some(0), Some(1)]);
770- assert_eq!(rpl.list1, Some(vec![Some(1), Some(0)]));
771- }
772-
773- #[test]
774- fn col_pic_selection_picks_list0_for_p() {
775- let lists = RefPicLists {
776- list0: vec![Some(3)],
777- list1: None,
778- };
779- // P slice ⇒ list0[collocated_ref_idx 0].
780- assert_eq!(select_col_pic(&lists, false, true, 0), Some(3));
781- }
782-
783- #[test]
784- fn col_pic_selection_picks_list1_when_b_and_not_from_l0() {
785- let lists = RefPicLists {
786- list0: vec![Some(3)],
787- list1: Some(vec![Some(7)]),
788- };
789- assert_eq!(select_col_pic(&lists, true, false, 0), Some(7));
790- // collocated_from_l0_flag true falls back to list0.
791- assert_eq!(select_col_pic(&lists, true, true, 0), Some(3));
792- }
793-
794- #[test]
795- fn no_backward_pred_flag_detects_future_ref() {
796- let mut dpb = Dpb::new();
797- dpb.insert(entry(0, Marking::ShortTerm)); // index 0 (past)
798- dpb.insert(entry(4, Marking::ShortTerm)); // index 1 (future)
799- // Current POC 2; list0 references the past pic only ⇒ no backward.
800- let past_only = RefPicLists {
801- list0: vec![Some(0)],
802- list1: None,
803- };
804- assert!(no_backward_pred_flag(&dpb, &past_only, 2));
805- // list1 references the future pic ⇒ backward prediction present.
806- let with_future = RefPicLists {
807- list0: vec![Some(0)],
808- list1: Some(vec![Some(1)]),
809- };
810- assert!(!no_backward_pred_flag(&dpb, &with_future, 2));
811- }
812-
813- #[test]
814- fn long_term_lsb_lookup_marks_long_term() {
815- // A long-term entry referencing POC 100 by LSB only (msb not
816- // present). MaxPicOrderCntLsb 256 ⇒ lsb 100. The DPB picture at
817- // POC 100 is found by its LSB and marked long-term.
818- let lt = LongTermEntry {
819- poc_lsb_lt: 100,
820- used_by_curr_pic_lt: true,
821- delta_poc_msb_present: false,
822- delta_poc_msb_cycle_lt: 0,
823- };
824- let st = empty_st_rps();
825- let lists = build_rps_poc_lists(false, 300, 256, &st, &[lt]);
826- assert_eq!(lists.lt_curr, vec![100]);
827- let mut dpb = Dpb::new();
828- dpb.insert(entry(100, Marking::ShortTerm));
829- let rps = dpb.apply_rps(false, 0, &lists, 256);
830- assert_eq!(rps.lt_curr, vec![Some(0)]);
831- assert_eq!(dpb.entries[0].marking, Marking::LongTerm);
832- }
833-}
vendor/oxideav-h265/src/encoder.rsdeleted+0 -440
@@ -1,440 +0,0 @@
1-//! H.265 / HEVC encoder — write-side building blocks.
2-//!
3-//! The encode stack mirrors the decode stack bottom-up:
4-//!
5-//! * [`bitwriter::BitWriter`] — the MSB-first RBSP bit sink (`u(n)`,
6-//! `ue(v)` / `se(v)`, `rbsp_trailing_bits()`).
7-//! * [`nal`] — §7.4.1.1 emulation-prevention escaping, the §7.3.1.2
8-//! NAL header, and Annex B framing.
9-//! * [`cabac::CabacEncoder`] — the §9.3.5 arithmetic encoding engine
10-//! (the spec's informative encoder that "matches the arithmetic
11-//! decoding engine described in clause 9.3.4.3").
12-//!
13-//! Every layer is pinned against the crate's own decode side: bit
14-//! fields re-read through [`crate::bitreader::BitReader`], NAL units
15-//! re-walked through [`crate::nal`], and CABAC bin streams re-decoded
16-//! through [`crate::cabac::CabacEngine`].
17-
18-// internal — exposed for tests/fuzz; not part of the stable API
19-#[doc(hidden)]
20-pub mod bitwriter;
21-// internal — exposed for tests/fuzz; not part of the stable API
22-#[doc(hidden)]
23-pub mod cabac;
24-pub mod inter;
25-pub mod intra;
26-pub mod loopfilter;
27-pub mod pyramid;
28-// internal — exposed for tests/fuzz; not part of the stable API
29-#[cfg(test)]
30-mod ccp_streams;
31-#[doc(hidden)]
32-pub mod nal;
33-#[cfg(test)]
34-mod palette_streams;
35-pub mod pcm;
36-#[cfg(test)]
37-mod rdpcm_streams;
38-#[cfg(test)]
39-mod scc_streams;
40-// internal — exposed for tests/fuzz; not part of the stable API
41-#[doc(hidden)]
42-pub mod residual;
43-
44-/// Registry-encoder coding mode, selected by the `mode` codec option.
45-#[derive(Debug)]
46-enum EncodeMode {
47- /// PCM-only IDR bootstrap: bit-exact lossless, every CU a
48- /// §7.3.8.7 PCM block. The default (`mode` absent or `"pcm"`).
49- Pcm,
50- /// Real CABAC intra coding ([`intra::encode_idr_intra_au`]) at
51- /// the carried `SliceQpY` (`mode = "intra"`, `qp` option, default
52- /// 26) with the carried §8.7 in-loop filters (`deblock` / `sao`
53- /// options).
54- Intra(i32, loopfilter::LoopFilterCfg),
55- /// Low-delay inter coding (`mode = "inter"`): `IDR, P, P, …`
56- /// GOPs through [`inter::LowDelayPEncoder`] (`qp` option, default
57- /// 26; `gop` option = GOP length in frames, default 0 = a single
58- /// leading IDR).
59- Inter(inter::LowDelayPEncoder),
60- /// Hierarchical-B coding (`mode = "inter"` + `pyramid = <gop>`):
61- /// dyadic B pyramids through [`pyramid::PyramidEncoder`] —
62- /// out-of-order coding, so packets arrive in bursts per mini-GOP
63- /// and [`Encoder::flush`] emits the low-delay tail.
64- Pyramid {
65- /// The buffering pyramid encoder.
66- enc: pyramid::PyramidEncoder,
67- /// `log2(gop)` — the dts-behind-pts reorder delay in frames.
68- delay: i64,
69- /// The caller-supplied pts of each pushed frame, by display
70- /// index (`None` ⇒ the display index itself).
71- pts_by_display: Vec<Option<i64>>,
72- /// Decode-order packet counter (drives dts).
73- decode_count: i64,
74- },
75-}
76-
77-use std::collections::VecDeque;
78-
79-use oxideav_core::{
80- CodecId, CodecParameters, Encoder, Error, Frame, Packet, PixelFormat, Result, TimeBase,
81-};
82-
83-/// H.265 registry encoder behind the [`oxideav_core::Encoder`]
84-/// contract. Every input frame becomes one Annex B access unit — a
85-/// self-contained IDR (`VPS + SPS + PPS + IDR_N_LP`) in the two intra
86-/// modes and at inter-mode GOP starts, or a `TRAIL_R` P slice inside
87-/// an inter-mode GOP. Three coding modes, selected by the `mode`
88-/// codec option:
89-///
90-/// * `"pcm"` (default) — the PCM-only bootstrap: every coding unit a
91-/// §7.3.8.7 PCM block, bit-exact lossless.
92-/// * `"intra"` — real CABAC intra coding (§8.4 prediction + forward
93-/// transform/quant + §7.3.8 syntax) at the `qp` option's
94-/// `SliceQpY` (0..=51, default 26).
95-/// * `"inter"` — low-delay `IDR, P, P, …` coding (§8.5 inter
96-/// prediction with per-CTU skip / merge / AMVP / intra decisions)
97-/// at the `qp` option's `SliceQpY`; the `gop` option sets the IDR
98-/// period in frames (default 0 = a single leading IDR); the
99-/// `bslices` option (`"1"` / `"true"`) codes the non-IDR frames as
100-/// low-delay B slices; the `amp` option switches to the AMP stream
101-/// configuration (`MinCbSizeY == 8`, `amp_enabled_flag == 1`, the
102-/// four asymmetric PART_2NxnU/2NxnD/nLx2N/nRx2N shapes competing in
103-/// the inter CU ladder); the `pyramid` option (a power of two in
104-/// 2..=16) switches to hierarchical-B coding — dyadic mini-GOPs
105-/// coded out of display order with per-layer QP offsets; packets
106-/// then arrive in bursts per mini-GOP (dts trails pts by
107-/// `log2(pyramid)` frames) and `flush()` emits the tail. `pyramid`
108-/// excludes the `gop` / `bslices` options.
109-///
110-/// The `"intra"` and `"inter"` modes accept the §8.7 in-loop filter
111-/// options `deblock` and `sao` (`"1"` / `"true"` to enable): the
112-/// encoder then signals the filters, elects them per slice / CTB
113-/// against distortion, and reconstructs through them (the reference
114-/// path a conforming decoder holds).
115-///
116-/// 4:2:0 8-bit, dimensions multiples of 16.
117-pub struct H265Encoder {
118- codec_id: CodecId,
119- output_params: CodecParameters,
120- width: usize,
121- height: usize,
122- mode: EncodeMode,
123- ready: VecDeque<Packet>,
124- frame_index: i64,
125-}
126-
127-/// Former name of [`H265Encoder`] (from when the registry encoder was
128-/// PCM-only).
129-pub type H265PcmEncoder = H265Encoder;
130-
131-impl std::fmt::Debug for H265Encoder {
132- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133- f.debug_struct("H265Encoder")
134- .field("width", &self.width)
135- .field("height", &self.height)
136- .field("mode", &self.mode)
137- .field("ready", &self.ready.len())
138- .finish()
139- }
140-}
141-
142-/// Direct factory endpoint: construct the software H.265 encoder.
143-/// Codec options: `mode` (`"pcm"` lossless bootstrap, the default,
144-/// `"intra"` real CABAC intra coding, or `"inter"` low-delay P GOPs),
145-/// `qp` (`SliceQpY` 0..=51 for the intra / inter modes, default 26),
146-/// `gop` (inter mode IDR period, default 0 = single leading IDR),
147-/// `amp` (inter mode: asymmetric motion partitions), and the in-loop
148-/// filter switches `deblock` / `sao` (intra / inter modes; default
149-/// off).
150-///
151-/// # Errors
152-/// [`Error::InvalidData`] when width / height are missing or not
153-/// nonzero multiples of 16, the pixel format is declared and is not
154-/// 4:2:0 8-bit planar, or a codec option is malformed.
155-pub fn make_encoder(params: &CodecParameters) -> Result<Box<dyn Encoder>> {
156- let width = params
157- .width
158- .ok_or_else(|| Error::InvalidData("h265 encode: width is required".into()))?
159- as usize;
160- let height = params
161- .height
162- .ok_or_else(|| Error::InvalidData("h265 encode: height is required".into()))?
163- as usize;
164- if width == 0 || height == 0 || width % 16 != 0 || height % 16 != 0 {
165- return Err(Error::InvalidData(format!(
166- "h265 encode: dimensions must be nonzero multiples of 16, got {width}x{height}"
167- )));
168- }
169- if let Some(pf) = params.pixel_format {
170- if pf != PixelFormat::Yuv420P {
171- return Err(Error::InvalidData(format!(
172- "h265 encode: only yuv420p input is supported, got {pf:?}"
173- )));
174- }
175- }
176- let parse_qp = |params: &CodecParameters| -> Result<i32> {
177- match params.options.get("qp") {
178- None => Ok(26),
179- Some(v) => v
180- .parse::<i32>()
181- .ok()
182- .filter(|q| (0..=51).contains(q))
183- .ok_or_else(|| {
184- Error::InvalidData(format!("h265 encode: qp must be 0..=51, got {v:?}"))
185- }),
186- }
187- };
188- let parse_flag = |params: &CodecParameters, key: &str| -> Result<bool> {
189- match params.options.get(key) {
190- None | Some("0") | Some("false") => Ok(false),
191- Some("1") | Some("true") => Ok(true),
192- Some(v) => Err(Error::InvalidData(format!(
193- "h265 encode: {key} must be 0/1/true/false, got {v:?}"
194- ))),
195- }
196- };
197- let parse_lf = |params: &CodecParameters| -> Result<loopfilter::LoopFilterCfg> {
198- let sao = parse_flag(params, "sao")?;
199- Ok(loopfilter::LoopFilterCfg {
200- deblocking: parse_flag(params, "deblock")?,
201- sao_luma: sao,
202- sao_chroma: sao,
203- })
204- };
205- let mode = match params.options.get("mode") {
206- None | Some("pcm") => {
207- if parse_lf(params)?.any() {
208- return Err(Error::InvalidData(
209- "h265 encode: deblock/sao options require mode \"intra\" or \"inter\"".into(),
210- ));
211- }
212- if parse_flag(params, "amp")? {
213- return Err(Error::InvalidData(
214- "h265 encode: the amp option requires mode \"inter\"".into(),
215- ));
216- }
217- EncodeMode::Pcm
218- }
219- Some("intra") => {
220- if parse_flag(params, "amp")? {
221- return Err(Error::InvalidData(
222- "h265 encode: the amp option requires mode \"inter\"".into(),
223- ));
224- }
225- EncodeMode::Intra(parse_qp(params)?, parse_lf(params)?)
226- }
227- Some("inter") => {
228- let qp = parse_qp(params)?;
229- if let Some(v) = params.options.get("pyramid") {
230- if params.options.get("gop").is_some() || params.options.get("bslices").is_some() {
231- return Err(Error::InvalidData(
232- "h265 encode: pyramid excludes the gop / bslices options".into(),
233- ));
234- }
235- let g = v
236- .parse::<usize>()
237- .ok()
238- .filter(|g| g.is_power_of_two() && (2..=16).contains(g))
239- .ok_or_else(|| {
240- Error::InvalidData(format!(
241- "h265 encode: pyramid must be a power of two in 2..=16, got {v:?}"
242- ))
243- })?;
244- let enc = pyramid::PyramidEncoder::new(width, height, qp, g)
245- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?
246- .with_amp(parse_flag(params, "amp")?)
247- .with_loop_filters(parse_lf(params)?);
248- EncodeMode::Pyramid {
249- enc,
250- delay: i64::from(g.trailing_zeros()),
251- pts_by_display: Vec::new(),
252- decode_count: 0,
253- }
254- } else {
255- let gop = match params.options.get("gop") {
256- None => 0usize,
257- Some(v) => v.parse::<usize>().map_err(|_| {
258- Error::InvalidData(format!(
259- "h265 encode: gop must be a non-negative integer, got {v:?}"
260- ))
261- })?,
262- };
263- let b_slices = parse_flag(params, "bslices")?;
264- let enc = inter::LowDelayPEncoder::new(width, height, qp, gop)
265- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?
266- .with_b_slices(b_slices)
267- .with_amp(parse_flag(params, "amp")?)
268- .with_loop_filters(parse_lf(params)?);
269- EncodeMode::Inter(enc)
270- }
271- }
272- Some(other) => {
273- return Err(Error::InvalidData(format!(
274- "h265 encode: unknown mode {other:?} (expected \"pcm\", \"intra\" or \"inter\")"
275- )))
276- }
277- };
278- let mut output_params = params.clone();
279- output_params.media_type = oxideav_core::MediaType::Video;
280- output_params.pixel_format = Some(PixelFormat::Yuv420P);
281- // Parameter sets ride in band in every access unit; no extradata.
282- output_params.extradata.clear();
283- Ok(Box::new(H265Encoder {
284- codec_id: params.codec_id.clone(),
285- output_params,
286- width,
287- height,
288- mode,
289- ready: VecDeque::new(),
290- frame_index: 0,
291- }))
292-}
293-
294-impl Encoder for H265Encoder {
295- fn codec_id(&self) -> &CodecId {
296- &self.codec_id
297- }
298-
299- fn output_params(&self) -> &CodecParameters {
300- &self.output_params
301- }
302-
303- fn send_frame(&mut self, frame: &Frame) -> Result<()> {
304- let v = match frame {
305- Frame::Video(v) => v,
306- _ => return Err(Error::InvalidData("h265 encode: video frames only".into())),
307- };
308- if v.planes.len() != 3 {
309- return Err(Error::InvalidData(format!(
310- "h265 encode: expected 3 planes (yuv420p), got {}",
311- v.planes.len()
312- )));
313- }
314- // Repack each plane row-by-row (strides may exceed the width).
315- let pack = |idx: usize, w: usize, h: usize| -> Result<Vec<u8>> {
316- let plane = &v.planes[idx];
317- if plane.stride < w || plane.data.len() < plane.stride * h {
318- return Err(Error::InvalidData(format!(
319- "h265 encode: plane {idx} too small (stride {}, len {})",
320- plane.stride,
321- plane.data.len()
322- )));
323- }
324- let mut out = Vec::with_capacity(w * h);
325- for row in 0..h {
326- out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + w]);
327- }
328- Ok(out)
329- };
330- let y = pack(0, self.width, self.height)?;
331- let cb = pack(1, self.width / 2, self.height / 2)?;
332- let cr = pack(2, self.width / 2, self.height / 2)?;
333-
334- let (au, keyframe) = match &mut self.mode {
335- EncodeMode::Pcm => (
336- pcm::encode_idr_pcm_au(&y, &cb, &cr, self.width, self.height)
337- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?,
338- true,
339- ),
340- EncodeMode::Intra(qp, lf) => (
341- intra::encode_idr_intra_au_lf(&y, &cb, &cr, self.width, self.height, *qp, lf)
342- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?
343- .au,
344- true,
345- ),
346- EncodeMode::Inter(enc) => {
347- let f = enc
348- .encode_frame(&inter::YuvFrame {
349- y: &y,
350- cb: &cb,
351- cr: &cr,
352- })
353- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?;
354- (f.au, f.keyframe)
355- }
356- EncodeMode::Pyramid {
357- enc,
358- delay,
359- pts_by_display,
360- decode_count,
361- } => {
362- pts_by_display.push(v.pts);
363- let aus = enc
364- .encode_frame(&inter::YuvFrame {
365- y: &y,
366- cb: &cb,
367- cr: &cr,
368- })
369- .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?;
370- self.frame_index += 1;
371- let (delay, decode_count) = (*delay, decode_count);
372- let mut packets = Self::pyramid_packets(aus, pts_by_display, delay, decode_count);
373- for pkt in packets.drain(..) {
374- self.ready.push_back(pkt);
375- }
376- return Ok(());
377- }
378- };
379- let mut pkt = Packet::new(0, TimeBase::new(1, 25), au);
380- pkt.pts = v.pts.or(Some(self.frame_index));
381- pkt.dts = pkt.pts;
382- pkt.flags.keyframe = keyframe;
383- self.frame_index += 1;
384- self.ready.push_back(pkt);
385- Ok(())
386- }
387-
388- fn receive_packet(&mut self) -> Result<Packet> {
389- self.ready.pop_front().ok_or(Error::NeedMore)
390- }
391-
392- fn flush(&mut self) -> Result<()> {
393- // Only the pyramid mode buffers: emit its low-delay tail.
394- if let EncodeMode::Pyramid {
395- enc,
396- delay,
397- pts_by_display,
398- decode_count,
399- } = &mut self.mode
400- {
401- let aus = enc.flush();
402- let (delay, decode_count) = (*delay, decode_count);
403- let mut packets = Self::pyramid_packets(aus, pts_by_display, delay, decode_count);
404- for pkt in packets.drain(..) {
405- self.ready.push_back(pkt);
406- }
407- }
408- Ok(())
409- }
410-}
411-
412-impl H265Encoder {
413- /// Turn a burst of decode-ordered pyramid access units into
414- /// packets: pts = the pushed frame's pts (default: its display
415- /// index), dts = the decode counter minus the reorder delay (a
416- /// dts never after its pts on the dyadic schedule).
417- fn pyramid_packets(
418- aus: Vec<pyramid::PyramidAu>,
419- pts_by_display: &[Option<i64>],
420- delay: i64,
421- decode_count: &mut i64,
422- ) -> Vec<Packet> {
423- aus.into_iter()
424- .map(|au| {
425- let mut pkt = Packet::new(0, TimeBase::new(1, 25), au.au);
426- pkt.pts = Some(
427- pts_by_display
428- .get(au.display_order)
429- .copied()
430- .flatten()
431- .unwrap_or(au.display_order as i64),
432- );
433- pkt.dts = Some(*decode_count - delay);
434- *decode_count += 1;
435- pkt.flags.keyframe = au.keyframe;
436- pkt
437- })
438- .collect()
439- }
440-}
vendor/oxideav-h265/src/encoder/bitwriter.rsdeleted+0 -190
@@ -1,190 +0,0 @@
1-//! MSB-first RBSP bit writer — the write-side dual of
2-//! [`crate::bitreader::BitReader`].
3-//!
4-//! Produces raw RBSP bytes: fixed-width `u(n)` fields, the §9.2
5-//! Exp-Golomb `ue(v)` / `se(v)` encodings, the §7.3.2 `rbsp_trailing_
6-//! bits()` terminator, and byte alignment. Emulation prevention
7-//! (§7.4.1.1) is NOT applied here — it belongs to the NAL encapsulation
8-//! ([`super::nal::escape_rbsp`]), which turns an RBSP into the on-wire
9-//! escaped payload.
10-
11-/// MSB-first bit accumulator over a growable byte buffer.
12-#[derive(Debug, Default, Clone)]
13-pub struct BitWriter {
14- buf: Vec<u8>,
15- /// Bits already used in the trailing partial byte (0..=7). When 0,
16- /// the writer is byte-aligned and `buf` holds only complete bytes.
17- partial_bits: u8,
18-}
19-
20-impl BitWriter {
21- /// A fresh, empty, byte-aligned writer.
22- #[must_use]
23- pub fn new() -> Self {
24- Self::default()
25- }
26-
27- /// Total bits written so far.
28- #[must_use]
29- pub fn bit_len(&self) -> usize {
30- if self.partial_bits == 0 {
31- self.buf.len() * 8
32- } else {
33- (self.buf.len() - 1) * 8 + self.partial_bits as usize
34- }
35- }
36-
37- /// `byte_aligned()` per §7.2.
38- #[must_use]
39- pub fn byte_aligned(&self) -> bool {
40- self.partial_bits == 0
41- }
42-
43- /// Append a single bit (the low bit of `bit`).
44- pub fn put_bit(&mut self, bit: u8) {
45- if self.partial_bits == 0 {
46- self.buf.push(0);
47- }
48- let last = self.buf.last_mut().expect("partial byte exists");
49- *last |= (bit & 1) << (7 - self.partial_bits);
50- self.partial_bits = (self.partial_bits + 1) & 7;
51- }
52-
53- /// Append the `n` low bits of `value`, most significant first
54- /// (`u(n)` / `f(n)`). `n == 0` writes nothing; `n <= 32`.
55- pub fn put_bits(&mut self, value: u32, n: u8) {
56- debug_assert!(n <= 32);
57- for i in (0..n).rev() {
58- self.put_bit(((value >> i) & 1) as u8);
59- }
60- }
61-
62- /// §9.2 — 0-th order Exp-Golomb, unsigned (`ue(v)`).
63- pub fn ue(&mut self, value: u32) {
64- // codeNum = value; the codeword is `leadingZeroBits` zeros, a
65- // one, then `leadingZeroBits` LSBs of (codeNum + 1).
66- let code_num = value as u64 + 1;
67- let bits = 64 - code_num.leading_zeros() as u8; // >= 1
68- self.put_bits(0, bits - 1);
69- for i in (0..bits).rev() {
70- self.put_bit(((code_num >> i) & 1) as u8);
71- }
72- }
73-
74- /// §9.2.2 — 0-th order Exp-Golomb, signed (`se(v)`):
75- /// `codeNum = value > 0 ? 2*value − 1 : −2*value`.
76- pub fn se(&mut self, value: i32) {
77- let code_num = if value > 0 {
78- 2 * value as u32 - 1
79- } else {
80- 2 * value.unsigned_abs()
81- };
82- self.ue(code_num);
83- }
84-
85- /// §7.3.2 `rbsp_trailing_bits()`: `rbsp_stop_one_bit` then zero
86- /// bits to the byte boundary.
87- pub fn rbsp_trailing_bits(&mut self) {
88- self.put_bit(1);
89- self.align_zero();
90- }
91-
92- /// Append zero bits until byte-aligned (`pcm_alignment_zero_bit` /
93- /// `rbsp_alignment_zero_bit` runs).
94- pub fn align_zero(&mut self) {
95- while self.partial_bits != 0 {
96- self.put_bit(0);
97- }
98- }
99-
100- /// Consume the writer and return the accumulated bytes. Any
101- /// trailing partial byte is zero-padded (callers producing RBSPs
102- /// terminate with [`Self::rbsp_trailing_bits`] first, so a
103- /// conforming RBSP is already aligned).
104- #[must_use]
105- pub fn finish(self) -> Vec<u8> {
106- self.buf
107- }
108-
109- /// Borrow the bytes written so far (trailing partial byte included,
110- /// zero-padded).
111- #[must_use]
112- pub fn as_bytes(&self) -> &[u8] {
113- &self.buf
114- }
115-}
116-
117-#[cfg(test)]
118-mod tests {
119- use super::*;
120- use crate::bitreader::BitReader;
121-
122- #[test]
123- fn bits_pack_msb_first() {
124- let mut w = BitWriter::new();
125- w.put_bit(1);
126- w.put_bits(0b0110, 4);
127- w.put_bits(0b101, 3);
128- assert_eq!(w.finish(), vec![0b1011_0101]);
129- }
130-
131- #[test]
132- fn ue_matches_reader_for_first_values() {
133- for v in 0..200u32 {
134- let mut w = BitWriter::new();
135- w.ue(v);
136- w.align_zero();
137- let bytes = w.finish();
138- let mut r = BitReader::new(&bytes);
139- assert_eq!(r.ue().unwrap(), v, "ue({v})");
140- }
141- }
142-
143- #[test]
144- fn se_matches_reader() {
145- for v in -100..=100i32 {
146- let mut w = BitWriter::new();
147- w.se(v);
148- w.align_zero();
149- let bytes = w.finish();
150- let mut r = BitReader::new(&bytes);
151- assert_eq!(r.se().unwrap(), v, "se({v})");
152- }
153- }
154-
155- #[test]
156- fn u_fields_roundtrip() {
157- let mut w = BitWriter::new();
158- w.put_bits(0x2A, 6);
159- w.put_bits(0x1FFFF, 17);
160- w.put_bits(1, 1);
161- w.align_zero();
162- let bytes = w.finish();
163- let mut r = BitReader::new(&bytes);
164- assert_eq!(r.u(6).unwrap(), 0x2A);
165- assert_eq!(r.u(17).unwrap(), 0x1FFFF);
166- assert_eq!(r.u1().unwrap(), 1);
167- }
168-
169- #[test]
170- fn trailing_bits_terminate_and_align() {
171- let mut w = BitWriter::new();
172- w.put_bits(0b101, 3);
173- w.rbsp_trailing_bits();
174- assert!(w.byte_aligned());
175- assert_eq!(w.finish(), vec![0b1011_0000]);
176- }
177-
178- #[test]
179- fn bit_len_tracks_partial_bytes() {
180- let mut w = BitWriter::new();
181- assert_eq!(w.bit_len(), 0);
182- w.put_bit(0);
183- assert_eq!(w.bit_len(), 1);
184- w.put_bits(0, 7);
185- assert_eq!(w.bit_len(), 8);
186- assert!(w.byte_aligned());
187- w.put_bits(0, 3);
188- assert_eq!(w.bit_len(), 11);
189- }
190-}
vendor/oxideav-h265/src/encoder/cabac.rsdeleted+0 -323
@@ -1,323 +0,0 @@
1-//! §9.3.5 CABAC arithmetic *encoding* engine (the spec's informative
2-//! encoder, which "matches the arithmetic decoding engine described in
3-//! clause 9.3.4.3").
4-//!
5-//! The engine state is `ivlLow` / `ivlCurrRange` plus the
6-//! `firstBitFlag` / `bitsOutstanding` carry-control of the §9.3.5.4
7-//! renormalization (Figure 9-11) and its PutBit procedure
8-//! (Figure 9-12). The four entry points mirror the decoder:
9-//!
10-//! * §9.3.5.2 [`CabacEncoder::new`] — `ivlLow = 0`,
11-//! `ivlCurrRange = 510`, `firstBitFlag = 1`, `bitsOutstanding = 0`.
12-//! The same initialization re-arms the engine after PCM sample data
13-//! ([`CabacEncoder::reinit`]).
14-//! * §9.3.5.3 [`CabacEncoder::encode_decision`] (EncodeDecision) — the
15-//! Table 9-52 `rangeTabLps` interval split, the §9.3.4.3.2.2 state
16-//! transition (Table 9-53), then renormalization.
17-//! * §9.3.5.5 [`CabacEncoder::encode_bypass`] (EncodeBypass).
18-//! * §9.3.5.6 [`CabacEncoder::encode_terminate`] (EncodeTerminate) —
19-//! `end_of_slice_segment_flag` / `end_of_subset_one_bit` /
20-//! `pcm_flag`; a `binVal == 1` runs the Figure 9-15 flush whose last
21-//! written bit is the `rbsp_stop_one_bit` /
22-//! `alignment_bit_equal_to_one`.
23-//!
24-//! Bits go into the caller's [`BitWriter`]; the encoder is constructed
25-//! at a byte-aligned position (the start of `slice_segment_data()`)
26-//! and, via the first-bit suppression, produces exactly the byte
27-//! sequence whose 9-bit preload the §9.3.2.6 decoder init consumes.
28-//!
29-//! Correctness contract: any bin sequence encoded through this engine
30-//! and decoded through [`crate::cabac::CabacEngine`] (with identically
31-//! initialized context models) reproduces the original bins — pinned
32-//! by the roundtrip tests below.
33-
34-use crate::cabac::{ContextModel, RANGE_TAB_LPS, TRANS_IDX_LPS, TRANS_IDX_MPS};
35-use crate::encoder::bitwriter::BitWriter;
36-
37-/// §9.3.5 arithmetic encoding engine over a borrowed [`BitWriter`].
38-#[derive(Debug)]
39-pub struct CabacEncoder {
40- /// `ivlLow` — low end of the current sub-interval (10-bit register
41- /// per the §9.3.5.2 NOTE; `u32` gives headroom).
42- low: u32,
43- /// `ivlCurrRange` — width of the current sub-interval (9 bits).
44- range: u32,
45- /// `firstBitFlag` — suppresses the very first PutBit output (the
46- /// decoder's 9-bit preload supplies it implicitly).
47- first_bit: bool,
48- /// `bitsOutstanding` — pending carry-propagation bits.
49- outstanding: u64,
50-}
51-
52-impl Default for CabacEncoder {
53- fn default() -> Self {
54- Self::new()
55- }
56-}
57-
58-impl CabacEncoder {
59- /// §9.3.5.2 InitEncoder.
60- #[must_use]
61- pub fn new() -> Self {
62- Self {
63- low: 0,
64- range: 510,
65- first_bit: true,
66- outstanding: 0,
67- }
68- }
69-
70- /// §9.3.5.2 — re-initialize after PCM sample data (`pcm_flag == 1`
71- /// coding units re-arm the engine exactly like a slice start).
72- pub fn reinit(&mut self) {
73- *self = Self::new();
74- }
75-
76- /// Figure 9-12 PutBit(B): carry-over control. The first bit of a
77- /// slice segment's arithmetic codeword is not written.
78- fn put_bit(&mut self, w: &mut BitWriter, b: u8) {
79- if self.first_bit {
80- self.first_bit = false;
81- } else {
82- w.put_bit(b);
83- }
84- while self.outstanding > 0 {
85- w.put_bit(1 - b);
86- self.outstanding -= 1;
87- }
88- }
89-
90- /// Figure 9-11 RenormE.
91- fn renorm(&mut self, w: &mut BitWriter) {
92- while self.range < 256 {
93- if self.low >= 512 {
94- self.low -= 512;
95- self.put_bit(w, 1);
96- } else if self.low < 256 {
97- self.put_bit(w, 0);
98- } else {
99- self.low -= 256;
100- self.outstanding += 1;
101- }
102- self.range <<= 1;
103- self.low <<= 1;
104- }
105- }
106-
107- /// §9.3.5.3 EncodeDecision: one context-coded bin. Updates the
108- /// context model exactly as the decoder's §9.3.4.3.2.2 transition.
109- pub fn encode_decision(&mut self, w: &mut BitWriter, ctx: &mut ContextModel, bin: u8) {
110- // Equation 9-64: qRangeIdx = ( ivlCurrRange >> 6 ) & 3.
111- let q_range_idx = ((self.range >> 6) & 3) as usize;
112- let lps = u32::from(RANGE_TAB_LPS[ctx.p_state_idx as usize][q_range_idx]);
113- self.range -= lps;
114- if bin != ctx.val_mps {
115- // LPS path: the LPS sub-interval sits above the MPS one.
116- self.low += self.range;
117- self.range = lps;
118- if ctx.p_state_idx == 0 {
119- ctx.val_mps = 1 - ctx.val_mps;
120- }
121- ctx.p_state_idx = TRANS_IDX_LPS[ctx.p_state_idx as usize];
122- } else {
123- ctx.p_state_idx = TRANS_IDX_MPS[ctx.p_state_idx as usize];
124- }
125- self.renorm(w);
126- }
127-
128- /// §9.3.5.5 EncodeBypass: one equal-probability bin (renorm
129- /// inlined per Figure 9-13).
130- pub fn encode_bypass(&mut self, w: &mut BitWriter, bin: u8) {
131- self.low <<= 1;
132- if bin != 0 {
133- self.low += self.range;
134- }
135- if self.low >= 1024 {
136- self.low -= 1024;
137- self.put_bit(w, 1);
138- } else if self.low < 512 {
139- self.put_bit(w, 0);
140- } else {
141- self.low -= 512;
142- self.outstanding += 1;
143- }
144- }
145-
146- /// MSB-first multi-bit bypass helper (the dual of
147- /// [`crate::cabac::CabacEngine::decode_bypass_bits`]).
148- pub fn encode_bypass_bits(&mut self, w: &mut BitWriter, value: u32, n: u8) {
149- for i in (0..n).rev() {
150- self.encode_bypass(w, ((value >> i) & 1) as u8);
151- }
152- }
153-
154- /// §9.3.5.6 EncodeTerminate: `end_of_slice_segment_flag` /
155- /// `end_of_subset_one_bit` / `pcm_flag`. `bin == 1` terminates the
156- /// arithmetic codeword and flushes (Figure 9-15) — the last written
157- /// bit is the `rbsp_stop_one_bit` / `alignment_bit_equal_to_one`;
158- /// the writer is then ready for byte-aligned raw data (PCM) or the
159- /// slice end.
160- pub fn encode_terminate(&mut self, w: &mut BitWriter, bin: u8) {
161- self.range -= 2;
162- if bin != 0 {
163- self.low += self.range;
164- self.flush(w);
165- } else {
166- self.renorm(w);
167- }
168- }
169-
170- /// Figure 9-15 EncodeFlush.
171- fn flush(&mut self, w: &mut BitWriter) {
172- self.range = 2;
173- self.renorm(w);
174- self.put_bit(w, ((self.low >> 9) & 1) as u8);
175- // WriteBits( ( ivlLow >> 7 ) & 3 | 1, 2 ) — the trailing 1 is
176- // the terminating one bit the decoder sees as the last bit
177- // inserted into ivlOffset.
178- w.put_bits(((self.low >> 7) & 3) | 1, 2);
179- }
180-}
181-
182-#[cfg(test)]
183-mod tests {
184- use super::*;
185- use crate::bitreader::BitReader;
186- use crate::cabac::CabacEngine;
187-
188- /// Encode `bins` as context-coded decisions with a single shared
189- /// context (encoder and decoder start from the same init), append a
190- /// terminate-1, and decode back.
191- fn roundtrip_decisions(init_value: u8, qp: i32, bins: &[u8]) {
192- let mut w = BitWriter::new();
193- let mut enc = CabacEncoder::new();
194- let mut ectx = ContextModel::init(init_value, qp);
195- for &b in bins {
196- enc.encode_decision(&mut w, &mut ectx, b);
197- }
198- enc.encode_terminate(&mut w, 1);
199- w.align_zero();
200- let bytes = w.finish();
201-
202- let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init");
203- let mut dctx = ContextModel::init(init_value, qp);
204- for (i, &b) in bins.iter().enumerate() {
205- assert_eq!(dec.decode_decision(&mut dctx).unwrap(), b, "bin {i}");
206- }
207- assert_eq!(dec.decode_terminate().unwrap(), 1, "terminator");
208- // The context models must have walked the same state path.
209- assert_eq!(ectx, dctx, "context state after roundtrip");
210- }
211-
212- #[test]
213- fn decision_roundtrip_simple_patterns() {
214- roundtrip_decisions(154, 26, &[0]);
215- roundtrip_decisions(154, 26, &[1]);
216- roundtrip_decisions(154, 26, &[1, 0, 1, 1, 0, 0, 1, 0]);
217- roundtrip_decisions(200, 37, &[1; 64]);
218- roundtrip_decisions(63, 0, &[0; 64]);
219- }
220-
221- #[test]
222- fn decision_roundtrip_pseudorandom_long() {
223- // Deterministic LCG bins over several init values / QPs.
224- let mut x = 0x1234_5678u32;
225- let mut bins = Vec::new();
226- for _ in 0..4096 {
227- x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345);
228- bins.push(((x >> 16) & 1) as u8);
229- }
230- for (iv, qp) in [(154u8, 26), (79, 12), (227, 51), (16, 0)] {
231- roundtrip_decisions(iv, qp, &bins);
232- }
233- }
234-
235- #[test]
236- fn bypass_roundtrip() {
237- let mut w = BitWriter::new();
238- let mut enc = CabacEncoder::new();
239- let pattern = 0xDEAD_BEEFu32;
240- enc.encode_bypass_bits(&mut w, pattern, 32);
241- enc.encode_terminate(&mut w, 1);
242- w.align_zero();
243- let bytes = w.finish();
244-
245- let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init");
246- assert_eq!(dec.decode_bypass_bits(32).unwrap(), pattern);
247- assert_eq!(dec.decode_terminate().unwrap(), 1);
248- }
249-
250- #[test]
251- fn mixed_decision_bypass_terminate_roundtrip() {
252- let mut w = BitWriter::new();
253- let mut enc = CabacEncoder::new();
254- let mut ectx = [ContextModel::init(154, 26), ContextModel::init(31, 40)];
255- // Interleave: ctx0, bypass, ctx1, terminate-0 (continue), repeat.
256- for round in 0..50u32 {
257- enc.encode_decision(&mut w, &mut ectx[0], (round & 1) as u8);
258- enc.encode_bypass(&mut w, ((round >> 1) & 1) as u8);
259- enc.encode_decision(&mut w, &mut ectx[1], ((round >> 2) & 1) as u8);
260- enc.encode_terminate(&mut w, 0);
261- }
262- enc.encode_terminate(&mut w, 1);
263- w.align_zero();
264- let bytes = w.finish();
265-
266- let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init");
267- let mut dctx = [ContextModel::init(154, 26), ContextModel::init(31, 40)];
268- for round in 0..50u32 {
269- assert_eq!(
270- dec.decode_decision(&mut dctx[0]).unwrap(),
271- (round & 1) as u8
272- );
273- assert_eq!(dec.decode_bypass().unwrap(), ((round >> 1) & 1) as u8);
274- assert_eq!(
275- dec.decode_decision(&mut dctx[1]).unwrap(),
276- ((round >> 2) & 1) as u8
277- );
278- assert_eq!(dec.decode_terminate().unwrap(), 0, "round {round}");
279- }
280- assert_eq!(dec.decode_terminate().unwrap(), 1);
281- assert_eq!(ectx[0], dctx[0]);
282- assert_eq!(ectx[1], dctx[1]);
283- }
284-
285- /// The PCM shape: terminate-1 mid-stream, byte-align, raw bits,
286- /// engine re-init on both sides, then more coded bins.
287- #[test]
288- fn pcm_style_flush_align_raw_reinit_roundtrip() {
289- let raw: [u8; 5] = [0x11, 0x22, 0x33, 0xFE, 0x00];
290-
291- let mut w = BitWriter::new();
292- let mut enc = CabacEncoder::new();
293- let mut ectx = ContextModel::init(154, 26);
294- enc.encode_decision(&mut w, &mut ectx, 1);
295- enc.encode_decision(&mut w, &mut ectx, 0);
296- // pcm_flag == 1: terminate + flush, then alignment zeros + raw.
297- enc.encode_terminate(&mut w, 1);
298- w.align_zero();
299- for &b in &raw {
300- w.put_bits(u32::from(b), 8);
301- }
302- // §9.3.5.2: re-init after the PCM data, keep encoding.
303- enc.reinit();
304- enc.encode_decision(&mut w, &mut ectx, 1);
305- enc.encode_terminate(&mut w, 1);
306- w.align_zero();
307- let bytes = w.finish();
308-
309- let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init");
310- let mut dctx = ContextModel::init(154, 26);
311- assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 1);
312- assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 0);
313- assert_eq!(dec.decode_terminate().unwrap(), 1);
314- // pcm_alignment_zero_bit run, raw PCM reads, §9.3.2.6 re-init.
315- dec.pcm_align().unwrap();
316- for &b in &raw {
317- assert_eq!(dec.read_raw_bits(8).unwrap(), u32::from(b));
318- }
319- dec.init_engine().expect("reinit");
320- assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 1);
321- assert_eq!(dec.decode_terminate().unwrap(), 1);
322- }
323-}
vendor/oxideav-h265/src/encoder/ccp_streams.rsdeleted+0 -540
@@ -1,540 +0,0 @@
1-//! Self-built §8.6.6 cross-component-prediction conformance stream
2-//! (test-only).
3-//!
4-//! No black-box encoder binary exposes the range-extension
5-//! cross-component prediction tool, so this module assembles a tiny
6-//! 4:4:4 lossless (transquant-bypass) all-intra Annex B bitstream from
7-//! this crate's own header writers and CABAC encoder. Every coding
8-//! unit signals derived (DM) chroma so the §7.3.8.10 `cross_comp_pred`
9-//! gate holds, and the per-CTB `ResScaleVal` plan cycles through every
10-//! legal magnitude and both signs for Cb and Cr independently —
11-//! including a CTB whose chroma residual is exactly the scaled luma
12-//! residual (cbf clear, CCP still signalled) and zero-scale controls.
13-//!
14-//! The stream reconstructs losslessly: the encoder codes the chroma
15-//! residual as `( orig − pred ) − ( ResScaleVal * rY ) >> 3` so the
16-//! decoder's eq. 8-324 modification restores `orig` exactly. The
17-//! checked-in copy under `tests/fixture_bytes/` was validated against
18-//! a black-box reference decoder (byte-exact; SHA-256 sums in
19-//! `tests/fixture_bytes/r416-generation-notes.md`); the tests here pin
20-//! (a) that the builder still produces those exact bytes and (b) that
21-//! this crate's decoder reconstructs the procedural source planes.
22-
23-use crate::binarization::{
24- cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, intra_luma_cand_mode_list,
25- log2_res_scale_abs_plus1_ctx_inc, res_scale_sign_flag_ctx_inc,
26-};
27-use crate::cabac::init_type;
28-use crate::ctx_init::SliceContexts;
29-use crate::encoder::bitwriter::BitWriter;
30-use crate::encoder::cabac::CabacEncoder;
31-use crate::encoder::intra::{gather_refs, zscan_avail};
32-use crate::encoder::nal::{annexb, nal_unit};
33-use crate::encoder::residual::encode_residual_coding;
34-use crate::intra_mode_field::{IntraModeField, Neighbour};
35-use crate::intra_pred::{
36- intra_predict_with_substitution, Component as PredComponent, IntraPredParams,
37-};
38-use crate::residual::{residual_coding_scan_idx, ResidualCodingParams};
39-
40-/// One picture's `(Y, Cb, Cr)` planes (all full-resolution — 4:4:4).
41-pub(super) type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
42-
43-/// CTB / coding-block log2 size (16x16, `MinCbSizeY == CtbSizeY`).
44-const CTB_LOG2: u32 = 4;
45-const CTB: usize = 1 << CTB_LOG2;
46-/// SliceQpY (immaterial — every CU is transquant-bypassed).
47-const SLICE_QP: i32 = 26;
48-
49-/// Deterministic 4:4:4 source planes: smooth gradients plus a coarse
50-/// checker texture (full-resolution chroma).
51-pub(super) fn source_planes_444(w: usize, h: usize) -> Planes {
52- let lum = |x: i32, y: i32| -> u8 {
53- let g = (x * 3 + y * 5) % 197;
54- let t = ((x / 4 + y / 4) % 3) * 23;
55- (16 + g + t).clamp(0, 255) as u8
56- };
57- let chr = |x: i32, y: i32, ph: i32| -> u8 {
58- let g = (x * 7 + y * 2 + ph) % 151;
59- let t = ((x / 4 + y / 8) % 2) * 31;
60- (40 + g + t).clamp(0, 255) as u8
61- };
62- let mut y_p = Vec::with_capacity(w * h);
63- let mut cb_p = Vec::with_capacity(w * h);
64- let mut cr_p = Vec::with_capacity(w * h);
65- for yy in 0..h as i32 {
66- for xx in 0..w as i32 {
67- y_p.push(lum(xx, yy));
68- cb_p.push(chr(xx, yy, 0));
69- cr_p.push(chr(xx, yy, 61));
70- }
71- }
72- (y_p, cb_p, cr_p)
73-}
74-
75-/// §7.3.3 — profile tier level for Format Range Extensions
76-/// (`general_profile_idc == 4`) with the 4:4:4 8-bit constraint-flag
77-/// pattern (`max_422chroma` / `max_420chroma` clear).
78-fn write_ptl_rext_444(w: &mut BitWriter, level_idc: u8) {
79- w.put_bits(0, 2); // general_profile_space
80- w.put_bit(0); // general_tier_flag
81- w.put_bits(4, 5); // general_profile_idc = 4 (Range Extensions)
82- let mut compat: u32 = 0;
83- compat |= 1 << (31 - 4); // flag[4] — Range Extensions
84- w.put_bits(compat, 32);
85- w.put_bit(1); // general_progressive_source_flag
86- w.put_bit(0); // general_interlaced_source_flag
87- w.put_bit(1); // general_non_packed_constraint_flag
88- w.put_bit(1); // general_frame_only_constraint_flag
89- w.put_bit(1); // general_max_12bit_constraint_flag
90- w.put_bit(1); // general_max_10bit_constraint_flag
91- w.put_bit(1); // general_max_8bit_constraint_flag
92- w.put_bit(0); // general_max_422chroma_constraint_flag
93- w.put_bit(0); // general_max_420chroma_constraint_flag
94- w.put_bit(0); // general_max_monochrome_constraint_flag
95- w.put_bit(0); // general_intra_constraint_flag
96- w.put_bit(0); // general_one_picture_only_constraint_flag
97- w.put_bit(0); // general_lower_bit_rate_constraint_flag
98- // general_reserved_zero_34bits
99- w.put_bits(0, 32);
100- w.put_bits(0, 2);
101- w.put_bit(0); // general_inbld_flag (reserved zero)
102- w.put_bits(level_idc as u32, 8); // general_level_idc
103- // sps_max_sub_layers_minus1 == 0: no sub-layer flags, no bytes.
104-}
105-
106-/// §7.3.2.1 — minimal single-layer VPS carrying the 4:4:4 Rext PTL.
107-fn write_vps_rext_444(level_idc: u8) -> Vec<u8> {
108- let mut w = BitWriter::new();
109- w.put_bits(0, 4); // vps_video_parameter_set_id
110- w.put_bit(1); // vps_base_layer_internal_flag
111- w.put_bit(1); // vps_base_layer_available_flag
112- w.put_bits(0, 6); // vps_max_layers_minus1
113- w.put_bits(0, 3); // vps_max_sub_layers_minus1
114- w.put_bit(1); // vps_temporal_id_nesting_flag
115- w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits
116- write_ptl_rext_444(&mut w, level_idc);
117- w.put_bit(1); // vps_sub_layer_ordering_info_present_flag
118- w.ue(1); // vps_max_dec_pic_buffering_minus1[0]
119- w.ue(0); // vps_max_num_reorder_pics[0]
120- w.ue(0); // vps_max_latency_increase_plus1[0]
121- w.put_bits(0, 6); // vps_max_layer_id
122- w.ue(0); // vps_num_layer_sets_minus1
123- w.put_bit(0); // vps_timing_info_present_flag
124- w.put_bit(0); // vps_extension_flag
125- w.rbsp_trailing_bits();
126- w.finish()
127-}
128-
129-/// §7.3.2.2 — 4:4:4 8-bit SPS (CTB 16, no PCM, SAO off, no
130-/// extensions).
131-fn write_sps_444(width: usize, height: usize, level_idc: u8) -> Vec<u8> {
132- let mut w = BitWriter::new();
133- w.put_bits(0, 4); // sps_video_parameter_set_id
134- w.put_bits(0, 3); // sps_max_sub_layers_minus1
135- w.put_bit(1); // sps_temporal_id_nesting_flag
136- write_ptl_rext_444(&mut w, level_idc);
137- w.ue(0); // sps_seq_parameter_set_id
138- w.ue(3); // chroma_format_idc = 4:4:4
139- w.put_bit(0); // separate_colour_plane_flag
140- w.ue(width as u32); // pic_width_in_luma_samples
141- w.ue(height as u32); // pic_height_in_luma_samples
142- w.put_bit(0); // conformance_window_flag
143- w.ue(0); // bit_depth_luma_minus8
144- w.ue(0); // bit_depth_chroma_minus8
145- w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
146- w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
147- w.ue(1); // sps_max_dec_pic_buffering_minus1[0]
148- w.ue(0); // sps_max_num_reorder_pics[0]
149- w.ue(0); // sps_max_latency_increase_plus1[0]
150- w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16)
151- w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16)
152- w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
153- w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
154- w.ue(0); // max_transform_hierarchy_depth_inter
155- w.ue(0); // max_transform_hierarchy_depth_intra
156- w.put_bit(0); // scaling_list_enabled_flag
157- w.put_bit(0); // amp_enabled_flag
158- w.put_bit(0); // sample_adaptive_offset_enabled_flag
159- w.put_bit(0); // pcm_enabled_flag
160- w.ue(0); // num_short_term_ref_pic_sets
161- w.put_bit(0); // long_term_ref_pics_present_flag
162- w.put_bit(0); // sps_temporal_mvp_enabled_flag
163- w.put_bit(0); // strong_intra_smoothing_enabled_flag
164- w.put_bit(0); // vui_parameters_present_flag
165- w.put_bit(0); // sps_extension_present_flag
166- w.rbsp_trailing_bits();
167- w.finish()
168-}
169-
170-/// §7.3.2.3 — PPS with `transquant_bypass_enabled_flag == 1` and a
171-/// `pps_range_extension()` whose
172-/// `cross_component_prediction_enabled_flag` is 1.
173-fn write_pps_ccp() -> Vec<u8> {
174- let mut w = BitWriter::new();
175- w.ue(0); // pps_pic_parameter_set_id
176- w.ue(0); // pps_seq_parameter_set_id
177- w.put_bit(0); // dependent_slice_segments_enabled_flag
178- w.put_bit(0); // output_flag_present_flag
179- w.put_bits(0, 3); // num_extra_slice_header_bits
180- w.put_bit(0); // sign_data_hiding_enabled_flag
181- w.put_bit(0); // cabac_init_present_flag
182- w.ue(0); // num_ref_idx_l0_default_active_minus1
183- w.ue(0); // num_ref_idx_l1_default_active_minus1
184- w.se(SLICE_QP - 26); // init_qp_minus26
185- w.put_bit(0); // constrained_intra_pred_flag
186- w.put_bit(0); // transform_skip_enabled_flag
187- w.put_bit(0); // cu_qp_delta_enabled_flag
188- w.se(0); // pps_cb_qp_offset
189- w.se(0); // pps_cr_qp_offset
190- w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag
191- w.put_bit(0); // weighted_pred_flag
192- w.put_bit(0); // weighted_bipred_flag
193- w.put_bit(1); // transquant_bypass_enabled_flag
194- w.put_bit(0); // tiles_enabled_flag
195- w.put_bit(0); // entropy_coding_sync_enabled_flag
196- w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag
197- w.put_bit(1); // deblocking_filter_control_present_flag
198- w.put_bit(0); // deblocking_filter_override_enabled_flag
199- w.put_bit(1); // pps_deblocking_filter_disabled_flag
200- w.put_bit(0); // pps_scaling_list_data_present_flag
201- w.put_bit(0); // lists_modification_present_flag
202- w.ue(0); // log2_parallel_merge_level_minus2
203- w.put_bit(0); // slice_segment_header_extension_present_flag
204- w.put_bit(1); // pps_extension_present_flag
205- w.put_bit(1); // pps_range_extension_flag
206- w.put_bit(0); // pps_multilayer_extension_flag
207- w.put_bit(0); // pps_3d_extension_flag
208- w.put_bit(0); // pps_scc_extension_flag
209- w.put_bits(0, 4); // pps_extension_4bits
210- // pps_range_extension() — §7.3.2.3.2 (transform_skip disabled ⇒ no
211- // log2_max_transform_skip_block_size_minus2).
212- w.put_bit(1); // cross_component_prediction_enabled_flag
213- w.put_bit(0); // chroma_qp_offset_list_enabled_flag
214- w.ue(0); // log2_sao_offset_scale_luma
215- w.ue(0); // log2_sao_offset_scale_chroma
216- w.rbsp_trailing_bits();
217- w.finish()
218-}
219-
220-pub(super) fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec<i32> {
221- let mut out = Vec::with_capacity(n * n);
222- for j in 0..n {
223- for i in 0..n {
224- out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
225- }
226- }
227- out
228-}
229-
230-/// The intra prediction params mirroring the stream's SPS: 4:4:4,
231-/// default smoothing, no strong smoothing, boundary filters active
232-/// (no implicit RDPCM in this stream).
233-pub(super) fn ip_params_444(mode: u8, cidx: PredComponent) -> IntraPredParams {
234- IntraPredParams {
235- pred_mode_intra: mode,
236- cidx,
237- bit_depth: 8,
238- bit_depth_luma: 8,
239- intra_smoothing_disabled: false,
240- strong_intra_smoothing_enabled: false,
241- chroma_array_type_3: true,
242- disable_boundary_filter: false,
243- }
244-}
245-
246-/// Per-CTB plan: `(luma_mode, cb_scale, cr_scale)`. Chroma is always
247-/// DM (`intra_chroma_pred_mode == 4`) so the §7.3.8.10
248-/// `cross_comp_pred` gate holds for every CU with a coded luma
249-/// residual. The ResScaleVal plan sweeps every legal magnitude and
250-/// both signs across the picture, with zero-scale controls.
251-fn ccp_plan(ctb: usize) -> (u8, i32, i32) {
252- const MODES: [u8; 6] = [0, 1, 26, 10, 18, 34];
253- const SCALES: [i32; 9] = [1, -1, 2, -2, 4, -4, 8, -8, 0];
254- let mode = MODES[ctb % MODES.len()];
255- let cb = SCALES[ctb % SCALES.len()];
256- let cr = SCALES[(ctb + 4) % SCALES.len()];
257- (mode, cb, cr)
258-}
259-
260-/// The CTB index whose chroma source is rewritten so the coded chroma
261-/// residual is exactly zero while `cross_comp_pred` still fires — the
262-/// cbf-clear + CCP pin.
263-const ZERO_RESIDUAL_CTB: usize = 5;
264-
265-/// Encode the §9.3.3.8 TR(cMax = 4) `log2_res_scale_abs_plus1[ c ]`
266-/// prefix plus the `res_scale_sign_flag[ c ]` for one component.
267-pub(super) fn encode_cross_comp_pred(
268- w: &mut BitWriter,
269- cabac: &mut CabacEncoder,
270- ctxs: &mut SliceContexts,
271- c: u32,
272- res_scale_val: i32,
273-) {
274- let (prefix, sign) = if res_scale_val == 0 {
275- (0u32, None)
276- } else {
277- let mag = res_scale_val.unsigned_abs();
278- debug_assert!(mag.is_power_of_two() && mag <= 8);
279- (mag.trailing_zeros() + 1, Some(u8::from(res_scale_val < 0)))
280- };
281- // TR cMax = 4: `prefix` ones then a terminating zero unless the
282- // prefix equals cMax; each bin has ctxInc = 4*c + binIdx.
283- for bin_idx in 0..prefix {
284- let ctx = log2_res_scale_abs_plus1_ctx_inc(bin_idx, c) as usize;
285- cabac.encode_decision(w, &mut ctxs.log2_res_scale_abs_plus1[ctx], 1);
286- }
287- if prefix < 4 {
288- let ctx = log2_res_scale_abs_plus1_ctx_inc(prefix, c) as usize;
289- cabac.encode_decision(w, &mut ctxs.log2_res_scale_abs_plus1[ctx], 0);
290- }
291- if let Some(s) = sign {
292- let ctx = res_scale_sign_flag_ctx_inc(c) as usize;
293- cabac.encode_decision(w, &mut ctxs.res_scale_sign_flag[ctx], s);
294- }
295-}
296-
297-/// Encode the all-intra 4:4:4 bypass slice: one 16x16 `PART_2Nx2N` CU
298-/// per CTB, DM chroma, per-CTB `cross_comp_pred` scales from
299-/// [`ccp_plan`]. Lossless: the reconstruction equals the source, so
300-/// reference samples read the (possibly rewritten) source planes.
301-///
302-/// `cb` / `cr` are mutated for [`ZERO_RESIDUAL_CTB`]: its chroma
303-/// source becomes exactly `pred + ( ResScaleVal * rY ) >> 3`, so the
304-/// coded chroma residual is zero while CCP still applies.
305-fn encode_ccp_idr_slice(
306- y: &[u8],
307- cb: &mut [u8],
308- cr: &mut [u8],
309- width: usize,
310- height: usize,
311-) -> Vec<u8> {
312- let ctbs_x = width / CTB;
313- let ctbs_y = height / CTB;
314- let mut modes = IntraModeField::new(width, height, CTB_LOG2);
315-
316- let mut w = BitWriter::new();
317- // ---- slice_segment_header( ) ----
318- w.put_bit(1); // first_slice_segment_in_pic_flag
319- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
320- w.ue(0); // slice_pic_parameter_set_id
321- w.ue(2); // slice_type = I
322- w.se(0); // slice_qp_delta
323- w.rbsp_trailing_bits(); // byte_alignment()
324-
325- // ---- slice_segment_data( ) ----
326- let mut cabac = CabacEncoder::new();
327- let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
328-
329- for ctb in 0..ctbs_x * ctbs_y {
330- let x0 = (ctb % ctbs_x) * CTB;
331- let y0 = (ctb / ctbs_x) * CTB;
332- let (mode, cb_scale, cr_scale) = ccp_plan(ctb);
333-
334- // Luma prediction + residual (lossless recon == source).
335- let read_y = |x: usize, yy: usize| i32::from(y[yy * width + x]);
336- let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
337- let marked = gather_refs(&read_y, &avail, x0, y0, CTB);
338- let pred =
339- intra_predict_with_substitution(&marked, &ip_params_444(mode, PredComponent::Luma))
340- .expect("legal prediction");
341- let src = extract(y, width, x0, y0, CTB);
342- let res_l: Vec<i32> = src.iter().zip(&pred).map(|(s, p)| s - p).collect();
343- let cbf_luma = res_l.iter().any(|&v| v != 0);
344- // §7.3.8.10: cross_comp_pred needs cbf_luma; without it the
345- // decoder infers ResScaleVal 0.
346- let (cb_scale, cr_scale) = if cbf_luma {
347- (cb_scale, cr_scale)
348- } else {
349- (0, 0)
350- };
351-
352- // Chroma 16x16 TBs at (x0, y0) — 4:4:4, DM mode.
353- let code_chroma = |plane: &mut [u8], pc: PredComponent, scale: i32| -> Vec<i32> {
354- let pred = {
355- let read = |x: usize, yy: usize| i32::from(plane[yy * width + x]);
356- let avail =
357- |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
358- let marked = gather_refs(&read, &avail, x0, y0, CTB);
359- intra_predict_with_substitution(&marked, &ip_params_444(mode, pc))
360- .expect("legal prediction")
361- };
362- if ctb == ZERO_RESIDUAL_CTB {
363- // Rewrite the source so orig == pred + ccp_term
364- // (clamped to 8-bit: pick a value that stays exact).
365- for j in 0..CTB {
366- for i in 0..CTB {
367- let term = (scale * res_l[j * CTB + i]) >> 3;
368- let v = (pred[j * CTB + i] + term).clamp(0, 255);
369- plane[(y0 + j) * width + x0 + i] = v as u8;
370- }
371- }
372- }
373- let src = extract(plane, width, x0, y0, CTB);
374- src.iter()
375- .zip(&pred)
376- .enumerate()
377- .map(|(k, (s, p))| {
378- let term = (scale * res_l[k]) >> 3;
379- s - p - term
380- })
381- .collect()
382- };
383- let res_cb = code_chroma(cb, PredComponent::Cb, cb_scale);
384- let res_cr = code_chroma(cr, PredComponent::Cr, cr_scale);
385-
386- // ---- §7.3.8.5 coding_unit( ) ----
387- cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1);
388- cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N
389- let avail_l = zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0);
390- let avail_a = zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0);
391- let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l);
392- let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a);
393- let list = intra_luma_cand_mode_list(cand_a, cand_b);
394- let sel = list.iter().position(|&m| m == mode);
395- cabac.encode_decision(
396- &mut w,
397- &mut ctxs.prev_intra_luma_pred_flag[0],
398- u8::from(sel.is_some()),
399- );
400- modes.record_intra_pb(x0, y0, CTB, mode, false);
401- match sel {
402- Some(0) => cabac.encode_bypass(&mut w, 0),
403- Some(1) => {
404- cabac.encode_bypass(&mut w, 1);
405- cabac.encode_bypass(&mut w, 0);
406- }
407- Some(_) => {
408- cabac.encode_bypass(&mut w, 1);
409- cabac.encode_bypass(&mut w, 1);
410- }
411- None => {
412- let mut rem = u32::from(mode);
413- for &c in &list {
414- if u32::from(mode) > u32::from(c) {
415- rem -= 1;
416- }
417- }
418- cabac.encode_bypass_bits(&mut w, rem, 5);
419- }
420- }
421- // intra_chroma_pred_mode = 4 (derived / DM): single ctx bin 0.
422- cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0);
423-
424- // ---- transform_tree / transform_unit ----
425- let cbf_cb_f = res_cb.iter().any(|&v| v != 0);
426- let cbf_cr_f = res_cr.iter().any(|&v| v != 0);
427- cabac.encode_decision(
428- &mut w,
429- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
430- u8::from(cbf_cb_f),
431- );
432- cabac.encode_decision(
433- &mut w,
434- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
435- u8::from(cbf_cr_f),
436- );
437- cabac.encode_decision(
438- &mut w,
439- &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize],
440- u8::from(cbf_luma),
441- );
442- let rc = |is_chroma: bool| ResidualCodingParams {
443- log2_trafo_size: 4,
444- is_chroma,
445- scan_idx: residual_coding_scan_idx(true, 4, u8::from(is_chroma), 3, u32::from(mode)),
446- sign_data_hiding_enabled_flag: false,
447- sign_hidden_suppressed: false,
448- transform_skip_sig_ctx: false,
449- persistent_rice_adaptation_enabled_flag: false,
450- cabac_bypass_alignment_enabled_flag: false,
451- extended_precision_processing_flag: false,
452- bit_depth: 8,
453- rice_stat_transform_skip: false,
454- };
455- if cbf_luma {
456- encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(false), &res_l)
457- .expect("valid luma levels");
458- }
459- // §7.3.8.10 in-place chroma: cross_comp_pred( x0, y0, 0 ),
460- // Cb residual, cross_comp_pred( x0, y0, 1 ), Cr residual. The
461- // gate is cross_component_prediction_enabled_flag && cbf_luma
462- // && intra_chroma_pred_mode == 4.
463- if cbf_luma {
464- encode_cross_comp_pred(&mut w, &mut cabac, &mut ctxs, 0, cb_scale);
465- }
466- if cbf_cb_f {
467- encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cb)
468- .expect("valid cb levels");
469- }
470- if cbf_luma {
471- encode_cross_comp_pred(&mut w, &mut cabac, &mut ctxs, 1, cr_scale);
472- }
473- if cbf_cr_f {
474- encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cr)
475- .expect("valid cr levels");
476- }
477-
478- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
479- }
480- w.align_zero();
481- w.finish()
482-}
483-
484-/// The cross-component-prediction conformance stream: VPS + SPS(4:4:4)
485-/// + PPS(rext, CCP) + one all-intra bypass IDR picture (64x48).
486-///
487-/// Returns the Annex B bytes and the expected (lossless) planes.
488-pub(crate) fn build_ccp_stream() -> (Vec<u8>, Planes) {
489- let (w, h) = (64usize, 48usize);
490- let (y, mut cb, mut cr) = source_planes_444(w, h);
491- let slice = encode_ccp_idr_slice(&y, &mut cb, &mut cr, w, h);
492- let units = vec![
493- nal_unit(32, 0, 0, &write_vps_rext_444(30)),
494- nal_unit(33, 0, 0, &write_sps_444(w, h, 30)),
495- nal_unit(34, 0, 0, &write_pps_ccp()),
496- nal_unit(20, 0, 0, &slice), // IDR_N_LP
497- ];
498- (annexb(&units), (y, cb, cr))
499-}
500-
501-#[cfg(test)]
502-mod tests {
503- use super::*;
504- use crate::sequence::decode_annexb_sequence;
505-
506- /// The checked-in stream bytes (black-box-reference-validated; see
507- /// `tests/fixture_bytes/r416-generation-notes.md`) are exactly
508- /// what the builder produces, and this crate's decoder
509- /// reconstructs the procedural source losslessly through the
510- /// §8.6.6 cross-component-prediction path — every legal
511- /// ResScaleVal magnitude, both signs, both components, plus the
512- /// cbf-clear-with-CCP and zero-scale controls.
513- #[test]
514- fn ccp_stream_decodes_lossless() {
515- let (stream, (y, cb, cr)) = build_ccp_stream();
516- let pinned: &[u8] = include_bytes!(concat!(
517- env!("CARGO_MANIFEST_DIR"),
518- "/tests/fixture_bytes/r416-ccp.hevc"
519- ));
520- assert_eq!(stream, pinned, "builder must reproduce the validated bytes");
521- let frames = decode_annexb_sequence(&stream).expect("decode");
522- assert_eq!(frames.len(), 1);
523- let mut expected = y;
524- expected.extend(cb);
525- expected.extend(cr);
526- let got = frames[0].picture.to_planar_u8().expect("8-bit planes");
527- assert_eq!(got, expected, "lossless CCP decode");
528- }
529-
530- /// The plan exercises the cbf-clear + CCP coding unit: the
531- /// designated CTB codes NO chroma residual yet carries non-zero
532- /// ResScaleVal (its chroma reconstruction is purely the scaled
533- /// luma residual on top of the prediction).
534- #[test]
535- fn ccp_stream_covers_cbf_clear_ccp_block() {
536- let (mode, cb_s, cr_s) = ccp_plan(ZERO_RESIDUAL_CTB);
537- let _ = mode;
538- assert!(cb_s != 0 || cr_s != 0, "zero-residual CTB must scale");
539- }
540-}
vendor/oxideav-h265/src/encoder/inter.rsdeleted+0 -3156

Diff too large; view file

@@ -1,3156 +0,0 @@
1-//! Low-delay GOP encoder — §8.5 inter prediction on the encode side.
2-//!
3-//! The sequence shape is `IDR, P, P, …` (or `IDR, B, B, …` with
4-//! [`LowDelayPEncoder::with_b_slices`]): the first frame goes through
5-//! the real CABAC intra encoder ([`crate::encoder::intra`]), every
6-//! following frame is one P / low-delay-B slice (TRAIL_R) whose
7-//! active reference(s) — `RefPicList0[0]`, and `RefPicList1[0]` on B
8-//! slices — resolve to the previous frame's reconstruction, signalled
9-//! with an inline §7.4.8 short-term RPS (`num_negative_pics == 1`,
10-//! `delta_poc == −1`). Low-delay B keeps decode order == display
11-//! order while enabling the bi-predictive §8.5.3.2.2 merge candidates
12-//! (zero-merge and combined candidates are bi on B slices) and the
13-//! B-side syntax (`inter_pred_idc`, `mvd_l1_zero_flag`, initType 2
14-//! contexts).
15-//!
16-//! Geometry mirrors the intra bootstrap: `CtbSizeY == MinCbSizeY ==
17-//! 16`, so every CTB is one unsplit CU; inter CUs are `PART_2Nx2N`
18-//! (one 16x16 PU, one depth-0 TU). Per CTU three coding modes compete
19-//! under an SSD + λ·rate heuristic:
20-//!
21-//! * **skip** (`cu_skip_flag == 1`) — the SAD-best §8.5.3.2.2 merge
22-//! candidate with no residual;
23-//! * **merge + residual** (`merge_flag == 1`) — the same candidate
24-//! with the transform-coded residual (`rqt_root_cbf` is inferred 1
25-//! for a 2Nx2N merge CU, so an all-zero residual falls back to
26-//! skip);
27-//! * **AMVP** — motion-estimated `mvL0` (greedy integer diamond over
28-//! seeded predictors, then half- then quarter-pel refinement
29-//! against the crate's own §8.5.3.3.3 interpolation), signalled as
30-//! `mvp_l0_flag` + §7.3.8.9 `mvd_coding`, with `rqt_root_cbf`
31-//! electing the residual.
32-//!
33-//! Every candidate's motion is resolved through the DECODE-side
34-//! §8.5.3.2 derivation ([`crate::pu_mv::resolve_pu_motion`] against
35-//! the picture's in-progress [`MotionField`] and the §6.4.2
36-//! availability of [`crate::availability::PictureTiling`]), its
37-//! prediction through the decode-side §8.5.3.3 driver
38-//! ([`predict_inter_pu`]), and its reconstruction through the
39-//! decode-side §8.6 scaling/transform — so the encoder's reference
40-//! buffer is bit-identical to a conforming decoder's output (in-loop
41-//! filters are off), which the roundtrip tests pin frame by frame.
42-
43-use crate::availability::{PictureTiling, TilingParams, MODE_INTRA};
44-use crate::binarization::{
45- cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, cu_skip_flag_ctx_inc,
46- intra_luma_cand_mode_list, CuPredMode, InterPredIdc, MvdComponent,
47-};
48-use crate::cabac::init_type;
49-use crate::ctx_init::SliceContexts;
50-use crate::encoder::bitwriter::BitWriter;
51-use crate::encoder::cabac::CabacEncoder;
52-use crate::encoder::intra::{
53- chroma_qp_420, code_tb, encode_idr_intra_au_full, gather_refs, pred_params, search_best_mode,
54- ssd, zscan_avail, IntraEncodeError, SpsCfg,
55-};
56-use crate::encoder::loopfilter::{
57- encode_sao_ctb, filter_frame, CtbShape, FilterInput, LoopFilterCfg,
58-};
59-use crate::encoder::nal::{annexb, nal_unit};
60-use crate::encoder::residual::encode_residual_coding;
61-use crate::inter_pred::{
62- predict_inter_pu, InterPredGeometry, InterPrediction, ListPrediction, RefPlane,
63-};
64-use crate::intra_mode_field::{IntraModeField, Neighbour};
65-use crate::intra_pred::{intra_predict_with_substitution, Component as PredComponent};
66-use crate::motion::{derive_chroma_mv, MotionCell, MotionField, Mv};
67-use crate::pu_mv::{resolve_pu_motion, PartMode, PuGeometry, PuMotion, PuMvContext};
68-use crate::residual::{residual_coding_scan_idx, ResidualCodingParams};
69-use crate::slice_data::PredictionUnit;
70-use crate::transform::{Component, PredMode};
71-
72-/// The fixed CTB / coding-block log2 size (16x16).
73-const CTB_LOG2: u32 = 4;
74-/// The fixed CTB size.
75-const CTB: usize = 1 << CTB_LOG2;
76-/// Fixed 8-bit depth.
77-const BIT_DEPTH: u8 = 8;
78-/// `MaxNumMergeCand` (§7.4.7.1) — `five_minus_max_num_merge_cand = 0`.
79-const MAX_MERGE: usize = 5;
80-/// The greedy integer-search iteration cap (diamond steps).
81-const ME_MAX_STEPS: usize = 24;
82-/// The z-order offsets of the four depth-1 transform units within a
83-/// CTB (§6.5.2 z-scan of the four halves).
84-const Z_OFFSETS: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
85-
86-/// One 4:2:0 8-bit input frame (borrowed planes).
87-#[derive(Debug, Clone, Copy)]
88-pub struct YuvFrame<'a> {
89- /// Luma plane, `width * height` samples.
90- pub y: &'a [u8],
91- /// Cb plane, `width/2 * height/2` samples.
92- pub cb: &'a [u8],
93- /// Cr plane.
94- pub cr: &'a [u8],
95-}
96-
97-/// One frame's reconstruction (what a conforming decoder outputs).
98-#[derive(Debug, Clone, Default)]
99-pub struct FrameRecon {
100- /// Reconstructed luma plane.
101- pub y: Vec<u8>,
102- /// Reconstructed Cb plane.
103- pub cb: Vec<u8>,
104- /// Reconstructed Cr plane.
105- pub cr: Vec<u8>,
106-}
107-
108-/// The encoded low-delay sequence: the Annex B stream (`VPS + SPS +
109-/// PPS + IDR, TRAIL_R, TRAIL_R, …`) plus the per-frame encoder
110-/// reconstructions in output order.
111-#[derive(Debug, Clone)]
112-pub struct LowDelayPEncoded {
113- /// The whole Annex B byte stream.
114- pub stream: Vec<u8>,
115- /// Per-frame reconstruction, `frames.len()` entries.
116- pub recon: Vec<FrameRecon>,
117- /// Per-frame CU mode decisions, `frames.len()` entries (frame 0 —
118- /// the IDR — counts every CTB as intra).
119- pub stats: Vec<FrameStats>,
120-}
121-
122-/// Per-frame CU mode-decision counters (one CU per CTB).
123-#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
124-pub struct FrameStats {
125- /// `cu_skip_flag == 1` CUs.
126- pub skip: usize,
127- /// Merge-with-residual CUs.
128- pub merge: usize,
129- /// AMVP (explicit-MV) CUs.
130- pub amvp: usize,
131- /// Intra CUs (`pred_mode_flag == 1`, or every CU of the IDR).
132- pub intra: usize,
133- /// Bi-predicted CUs (both `predFlagLX` set on some PU — B slices
134- /// only; an overlay of the mode classes above).
135- pub bi: usize,
136- /// Rectangular-partition CUs (`PART_2NxN` / `PART_Nx2N` — an
137- /// overlay counted in `merge` / `amvp` too).
138- pub rect: usize,
139- /// Asymmetric-partition CUs (`PART_2NxnU` / `PART_2NxnD` /
140- /// `PART_nLx2N` / `PART_nRx2N` — an overlay counted in `merge` /
141- /// `amvp` too; AMP streams only).
142- pub amp: usize,
143- /// CUs referencing the second reference picture (POC − 2) on some
144- /// PU / list (an overlay of the mode classes above).
145- pub ref1: usize,
146-}
147-
148-/// A resolved-and-coded CU candidate.
149-struct CuCandidate {
150- /// How the CU is signalled.
151- kind: CuKind,
152- /// The §8.5.3.2.1-resolved per-PU motion in §7.3.8.6 order (what
153- /// the decoder will derive); empty for an intra CU.
154- motions: Vec<PuMotion>,
155- /// The coded transform tree; `None` ⇔ no tree (skip, or
156- /// `rqt_root_cbf == 0`).
157- levels: Option<CuLevels>,
158- /// The CTB reconstruction (y 16x16, cb 8x8, cr 8x8).
159- recon: [Vec<u8>; 3],
160- /// SSD + λ·rate cost.
161- cost: u64,
162-}
163-
164-/// The quantized levels of a CU candidate's transform tree.
165-enum CuLevels {
166- /// One depth-0 TU: luma 16x16, cb 8x8, cr 8x8.
167- Depth0([Vec<i32>; 3]),
168- /// The §7.4.9.8 `interSplitFlag` forced depth-1 tree (rectangular
169- /// inter partitions at `max_transform_hierarchy_depth_inter == 0`):
170- /// four z-order 8x8 luma and 4x4 chroma TBs per plane (boxed to
171- /// keep the variant sizes comparable).
172- Depth1(Box<Depth1Levels>),
173-}
174-
175-/// The four z-order leaves of a forced depth-1 transform tree.
176-struct Depth1Levels {
177- luma: [Vec<i32>; 4],
178- cb: [Vec<i32>; 4],
179- cr: [Vec<i32>; 4],
180-}
181-
182-/// One list's non-merge (AMVP) signalling group: `ref_idx_lX` (when
183-/// that list has more than one active reference), the §7.3.8.9
184-/// `mvd_coding( )` pair, and `mvp_lX_flag`.
185-#[derive(Clone, Copy)]
186-struct AmvpGroup {
187- ref_idx: u8,
188- mvd: Mv,
189- mvp_flag: u8,
190-}
191-
192-/// One prediction unit's §7.3.8.6 signalling (merge or AMVP).
193-#[derive(Clone, Copy)]
194-enum PuSyntax {
195- /// `merge_flag == 1`, `merge_idx`.
196- Merge { merge_idx: usize },
197- /// `merge_flag == 0`: `inter_pred_idc` (on B slices) selects the
198- /// used list(s) — `PRED_L0`, `PRED_L1` or `PRED_BI` — and each
199- /// used list carries its [`AmvpGroup`].
200- Amvp {
201- l0: Option<AmvpGroup>,
202- l1: Option<AmvpGroup>,
203- },
204-}
205-
206-/// The signalling class of a chosen CU.
207-enum CuKind {
208- /// `cu_skip_flag == 1`, `merge_idx`.
209- Skip { merge_idx: usize },
210- /// `merge_flag == 1`, `merge_idx`, transform tree follows
211- /// (`rqt_root_cbf` inferred 1).
212- Merge { merge_idx: usize },
213- /// AMVP (one 2Nx2N PU): the carried [`PuSyntax::Amvp`] group;
214- /// `rqt_root_cbf` signalled.
215- Amvp { pu: PuSyntax },
216- /// Two-PU inter partition (`PART_2NxN` / `PART_Nx2N`, or one of
217- /// the four AMP shapes on an AMP stream): two prediction units,
218- /// the forced depth-1 RQT, `rqt_root_cbf` signalled.
219- TwoPu { part: PartMode, pus: [PuSyntax; 2] },
220- /// Intra fallback (`pred_mode_flag == 1`, `PART_2Nx2N`): §8.4
221- /// prediction with luma mode `mode`, chroma derived-from-luma.
222- Intra { mode: u8 },
223-}
224-
225-/// One frame's output from the streaming [`LowDelayPEncoder`].
226-#[derive(Debug, Clone)]
227-pub struct EncodedPFrame {
228- /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP` for a
229- /// keyframe, one `TRAIL_R` slice otherwise).
230- pub au: Vec<u8>,
231- /// `true` for an IDR access unit (a random access point).
232- pub keyframe: bool,
233- /// The frame's reconstruction (== a conforming decoder's output).
234- pub recon: FrameRecon,
235- /// The frame's CU mode-decision counters.
236- pub stats: FrameStats,
237-}
238-
239-/// The streaming low-delay encoder: one frame in, one access unit
240-/// out. The first frame (and every `gop`-th frame when `gop > 0`)
241-/// becomes a self-contained IDR access unit; every other frame is a
242-/// P slice referencing the previous frame's reconstruction.
243-#[derive(Debug)]
244-pub struct LowDelayPEncoder {
245- width: usize,
246- height: usize,
247- qp: i32,
248- /// GOP length in frames (`0` = a single leading IDR, endless P).
249- gop: usize,
250- /// Code the non-IDR frames as (low-delay) B slices: both
251- /// reference lists resolve to the previous picture, enabling
252- /// bi-predictive merge candidates and the B-slice syntax.
253- b_slices: bool,
254- /// The §8.7 in-loop filters this stream signals and applies on
255- /// its reconstruction path.
256- filters: LoopFilterCfg,
257- /// AMP stream configuration: `MinCbSizeY == 8` with every CTB an
258- /// unsplit 16x16 CU, `amp_enabled_flag == 1`, and the asymmetric
259- /// PART_2NxnU/2NxnD/nLx2N/nRx2N shapes competing in the inter CU
260- /// ladder.
261- amp: bool,
262- /// POC of the NEXT frame within the current GOP (0 ⇒ IDR next).
263- poc: i32,
264- /// The most recent reconstructions, newest first (up to two — the
265- /// active references POC − 1 and POC − 2).
266- prevs: Vec<FrameRecon>,
267-}
268-
269-impl LowDelayPEncoder {
270- /// Construct a streaming encoder for `width`x`height` 4:2:0 8-bit
271- /// content at constant `SliceQpY == qp`. `gop == 0` emits a
272- /// single leading IDR; `gop == n` re-emits an IDR every `n`
273- /// frames.
274- ///
275- /// # Errors
276- /// [`IntraEncodeError`] on bad dimensions / QP.
277- pub fn new(width: usize, height: usize, qp: i32, gop: usize) -> Result<Self, IntraEncodeError> {
278- if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 {
279- return Err(IntraEncodeError::BadDimensions { width, height });
280- }
281- if !(0..=51).contains(&qp) {
282- return Err(IntraEncodeError::BadQp(qp));
283- }
284- Ok(Self {
285- width,
286- height,
287- qp,
288- gop,
289- b_slices: false,
290- filters: LoopFilterCfg::off(),
291- amp: false,
292- poc: 0,
293- prevs: Vec::new(),
294- })
295- }
296-
297- /// Code non-IDR frames as low-delay B slices (both reference
298- /// lists resolving to the previous picture) instead of P slices.
299- #[must_use]
300- pub fn with_b_slices(mut self, on: bool) -> Self {
301- self.b_slices = on;
302- self
303- }
304-
305- /// Switch the stream to the AMP configuration: the SPS signals
306- /// `MinCbSizeY == 8` + `amp_enabled_flag == 1` (every CTB still
307- /// one unsplit 16x16 CU, now with an explicit `split_cu_flag`),
308- /// and the inter CU ladder elects the asymmetric
309- /// `PART_2NxnU / PART_2NxnD / PART_nLx2N / PART_nRx2N` motion
310- /// partitions alongside the symmetric shapes.
311- #[must_use]
312- pub fn with_amp(mut self, on: bool) -> Self {
313- self.amp = on;
314- self
315- }
316-
317- /// Enable the §8.7 in-loop filters (deblocking / SAO) on the
318- /// encoder's reconstruction path: every frame's reference — and
319- /// the [`EncodedPFrame::recon`] a conforming decoder reproduces —
320- /// becomes the FILTERED picture, with the filter elections
321- /// signalled in the parameter sets and slice headers.
322- #[must_use]
323- pub fn with_loop_filters(mut self, filters: LoopFilterCfg) -> Self {
324- self.filters = filters;
325- self
326- }
327-
328- /// Encode the next frame in display order.
329- ///
330- /// # Errors
331- /// [`IntraEncodeError::PlaneSize`] when a plane length does not
332- /// match the 4:2:0 geometry.
333- pub fn encode_frame(
334- &mut self,
335- frame: &YuvFrame<'_>,
336- ) -> Result<EncodedPFrame, IntraEncodeError> {
337- let (cw, ch) = (self.width / 2, self.height / 2);
338- for (plane, buf, expected) in [
339- ("y", frame.y, self.width * self.height),
340- ("cb", frame.cb, cw * ch),
341- ("cr", frame.cr, cw * ch),
342- ] {
343- if buf.len() != expected {
344- return Err(IntraEncodeError::PlaneSize {
345- plane,
346- expected,
347- got: buf.len(),
348- });
349- }
350- }
351- let idr_now = self.prevs.is_empty() || self.poc == 0;
352- let out = if idr_now {
353- // sps_max_dec_pic_buffering_minus1 = 2: the current picture
354- // plus the two short-term references the P/B slices keep.
355- let idr = encode_idr_intra_au_full(
356- frame.y,
357- frame.cb,
358- frame.cr,
359- self.width,
360- self.height,
361- self.qp,
362- &SpsCfg {
363- max_dec_pic_buffering_minus1: 2,
364- max_num_reorder_pics: 0,
365- min_cb_log2: if self.amp { 3 } else { 4 },
366- amp: self.amp,
367- // edith patch: no crop and no VUI on the inter paths
368- conf_win: (0, 0),
369- signal: None,
370- },
371- &self.filters,
372- )?;
373- let recon = FrameRecon {
374- y: idr.recon_y,
375- cb: idr.recon_cb,
376- cr: idr.recon_cr,
377- };
378- self.prevs = vec![recon.clone()];
379- self.poc = 1;
380- EncodedPFrame {
381- au: idr.au,
382- keyframe: true,
383- recon,
384- stats: FrameStats {
385- intra: (self.width / CTB) * (self.height / CTB),
386- ..FrameStats::default()
387- },
388- }
389- } else {
390- // The active references: RefPicListX[i] = the
391- // reconstruction of POC − 1 − i (newest first, up to two),
392- // and a low-delay B slice holds the same set on both lists.
393- let l0: Vec<(i32, &FrameRecon)> = self
394- .prevs
395- .iter()
396- .take(2)
397- .enumerate()
398- .map(|(i, rec)| (self.poc - 1 - i as i32, rec))
399- .collect();
400- let spec = SliceSpec {
401- poc: self.poc,
402- qp: self.qp,
403- b_slice: self.b_slices,
404- rps_neg: (1..=l0.len() as u32).map(|d| (d, true)).collect(),
405- rps_pos: Vec::new(),
406- l1: if self.b_slices {
407- l0.clone()
408- } else {
409- Vec::new()
410- },
411- l0,
412- lf: &self.filters,
413- big_cu: self.amp,
414- };
415- let (rbsp, recon, stats) = encode_inter_slice(frame, &spec, self.width, self.height);
416- let au = annexb(&[nal_unit(1, 0, 0, &rbsp)]); // TRAIL_R
417- self.prevs.insert(0, recon.clone());
418- self.prevs.truncate(2);
419- self.poc += 1;
420- EncodedPFrame {
421- au,
422- keyframe: false,
423- recon,
424- stats,
425- }
426- };
427- // GOP wrap: schedule the next IDR.
428- if self.gop > 0 && self.poc >= self.gop as i32 {
429- self.poc = 0;
430- }
431- Ok(out)
432- }
433-}
434-
435-/// Encode a low-delay `IDR, P, P, …` sequence at a constant
436-/// `SliceQpY == qp` and return the Annex B stream plus the per-frame
437-/// reconstructions a conforming decoder reproduces exactly.
438-///
439-/// # Errors
440-/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP (the
441-/// validation contract is shared with the intra encoder).
442-pub fn encode_low_delay_p(
443- frames: &[YuvFrame<'_>],
444- width: usize,
445- height: usize,
446- qp: i32,
447-) -> Result<LowDelayPEncoded, IntraEncodeError> {
448- let mut enc = LowDelayPEncoder::new(width, height, qp, 0)?;
449- let mut out = LowDelayPEncoded {
450- stream: Vec::new(),
451- recon: Vec::new(),
452- stats: Vec::new(),
453- };
454- for frame in frames {
455- let f = enc.encode_frame(frame)?;
456- out.stream.extend_from_slice(&f.au);
457- out.recon.push(f.recon);
458- out.stats.push(f.stats);
459- }
460- Ok(out)
461-}
462-
463-/// The slice header's in-loop-filter fields (§7.3.6.1): the enabled
464-/// filter set plus this slice's elections.
465-struct SliceLfSignalling<'a> {
466- /// The stream's filter configuration (drives field presence: the
467- /// SAO gates exist iff the SPS enables SAO, the deblocking
468- /// override group iff the PPS enables the override).
469- cfg: &'a LoopFilterCfg,
470- /// This slice's deblocking election
471- /// (`slice_deblocking_filter_disabled_flag == !deblock_on`).
472- deblock_on: bool,
473- /// Elected `slice_beta_offset_div2`.
474- beta_offset_div2: i32,
475- /// Elected `slice_tc_offset_div2`.
476- tc_offset_div2: i32,
477- /// Elected `slice_sao_luma_flag`.
478- sao_luma: bool,
479- /// Elected `slice_sao_chroma_flag`.
480- sao_chroma: bool,
481-}
482-
483-/// Everything one P / B slice's coding depends on beyond the frame
484-/// samples: POC, QP, slice type, the inline §7.4.8 short-term RPS
485-/// content, and the two active reference lists (POC + reconstruction
486-/// each, in `RefPicListX` order). The low-delay GOP passes past
487-/// pictures on both lists; the hierarchical-B GOP passes past
488-/// pictures on L0 and future pictures on L1.
489-pub(crate) struct SliceSpec<'a> {
490- /// `PicOrderCntVal` (== `slice_pic_order_cnt_lsb`, 8 bits).
491- pub poc: i32,
492- /// `SliceQpY`.
493- pub qp: i32,
494- /// B slice (`slice_type == 0`)?
495- pub b_slice: bool,
496- /// Negative RPS entries closest-first: `(PocDelta, used_by_curr)`
497- /// with `PocDelta = poc − entry POC > 0`, strictly increasing.
498- pub rps_neg: Vec<(u32, bool)>,
499- /// Positive RPS entries closest-first: `(entry POC − poc, used)`.
500- pub rps_pos: Vec<(u32, bool)>,
501- /// `RefPicList0`: active references, `(POC, reconstruction)`.
502- pub l0: Vec<(i32, &'a FrameRecon)>,
503- /// `RefPicList1` (B slices; empty on P slices).
504- pub l1: Vec<(i32, &'a FrameRecon)>,
505- /// The stream's §8.7 in-loop filter configuration.
506- pub lf: &'a LoopFilterCfg,
507- /// Stream geometry: `log2CbSize > MinCbLog2SizeY` (MinCb 8, one
508- /// explicit `split_cu_flag == 0` per CTB, the Table 9-45 big-CU
509- /// `part_mode` column, no intra `part_mode`). Implied by the AMP
510- /// stream configuration.
511- pub big_cu: bool,
512-}
513-
514-/// §7.3.6.1 — the P / B slice-segment header: an inline §7.4.8
515-/// short-term RPS (negative + positive pictures with per-entry used
516-/// flags), the `num_ref_idx` override when a list keeps more than one
517-/// active reference, `MaxNumMergeCand == 5`, `slice_qp_delta` against
518-/// `init_qp == 26`, then the in-loop-filter block (`slice_sao_*`
519-/// gates when the SPS enables SAO, the deblocking override group when
520-/// the PPS enables the override, the across-slices flag when any
521-/// filter is active).
522-fn write_inter_slice_header(w: &mut BitWriter, spec: &SliceSpec<'_>, lf: &SliceLfSignalling<'_>) {
523- w.put_bit(1); // first_slice_segment_in_pic_flag
524- w.ue(0); // slice_pic_parameter_set_id
525- w.ue(u32::from(!spec.b_slice)); // slice_type (0 = B, 1 = P)
526- w.put_bits((spec.poc & 0xFF) as u32, 8); // slice_pic_order_cnt_lsb
527- w.put_bit(0); // short_term_ref_pic_set_sps_flag
528- // st_ref_pic_set( 0 ) — idx 0 has no
529- // inter_ref_pic_set_prediction_flag (§7.3.7).
530- w.ue(spec.rps_neg.len() as u32); // num_negative_pics
531- w.ue(spec.rps_pos.len() as u32); // num_positive_pics
532- let mut prev = 0u32;
533- for &(delta, used) in &spec.rps_neg {
534- // §7.4.8: DeltaPocS0[i] = DeltaPocS0[i−1] − (minus1 + 1).
535- w.ue(delta - prev - 1); // delta_poc_s0_minus1[i]
536- w.put_bit(u8::from(used)); // used_by_curr_pic_s0_flag[i]
537- prev = delta;
538- }
539- let mut prev = 0u32;
540- for &(delta, used) in &spec.rps_pos {
541- // §7.4.8: DeltaPocS1[i] = DeltaPocS1[i−1] + (minus1 + 1).
542- w.ue(delta - prev - 1); // delta_poc_s1_minus1[i]
543- w.put_bit(u8::from(used)); // used_by_curr_pic_s1_flag[i]
544- prev = delta;
545- }
546- // sps_temporal_mvp_enabled_flag == 0: nothing.
547- if lf.cfg.sao() {
548- // SPS SAO enabled: the per-slice component gates are present.
549- w.put_bit(u8::from(lf.sao_luma)); // slice_sao_luma_flag
550- w.put_bit(u8::from(lf.sao_chroma)); // slice_sao_chroma_flag
551- }
552- let n_l0 = spec.l0.len() as u32;
553- let n_l1 = spec.l1.len() as u32;
554- if n_l0 != 1 || (spec.b_slice && n_l1 != 1) {
555- // PPS defaults are one active reference per list.
556- w.put_bit(1); // num_ref_idx_active_override_flag
557- w.ue(n_l0 - 1); // num_ref_idx_l0_active_minus1
558- if spec.b_slice {
559- w.ue(n_l1 - 1); // num_ref_idx_l1_active_minus1
560- }
561- } else {
562- w.put_bit(0); // num_ref_idx_active_override_flag (default: 1)
563- }
564- // lists_modification_present_flag == 0.
565- if spec.b_slice {
566- w.put_bit(0); // mvd_l1_zero_flag
567- }
568- // cabac_init_present_flag == 0; TMVP off; WP off.
569- w.ue((5 - MAX_MERGE) as u32); // five_minus_max_num_merge_cand
570- w.se(spec.qp - 26); // slice_qp_delta
571- if lf.cfg.deblocking {
572- // §7.3.6.1 deblocking override group (the PPS signals
573- // override-enabled + deblocking disabled; an electing slice
574- // overrides to enabled with zero β/tC offsets).
575- w.put_bit(u8::from(lf.deblock_on)); // deblocking_filter_override_flag
576- if lf.deblock_on {
577- w.put_bit(0); // slice_deblocking_filter_disabled_flag
578- w.se(lf.beta_offset_div2); // slice_beta_offset_div2
579- w.se(lf.tc_offset_div2); // slice_tc_offset_div2
580- }
581- }
582- if lf.sao_luma || lf.sao_chroma || lf.deblock_on {
583- // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and
584- // some in-loop filter is active for this slice.
585- w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag
586- }
587- // No tiles / WPP: no entry points.
588- w.rbsp_trailing_bits(); // byte_alignment()
589-}
590-
591-/// Extract an `n`x`n` block of `plane` at `(x0, y0)` as `i32`s.
592-fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec<i32> {
593- let mut out = Vec::with_capacity(n * n);
594- for j in 0..n {
595- for i in 0..n {
596- out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
597- }
598- }
599- out
600-}
601-
602-/// Store an `n`x`n` block back into `plane` at `(x0, y0)`.
603-fn store(plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]) {
604- for j in 0..n {
605- plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n].copy_from_slice(&s[j * n..(j + 1) * n]);
606- }
607-}
608-
609-/// The [`crate::binarization::PartMode`] twin of a [`PartMode`] (the
610-/// loop-filter descriptors speak the binarization enum).
611-fn bin_part_mode(p: PartMode) -> crate::binarization::PartMode {
612- use crate::binarization::PartMode as B;
613- match p {
614- PartMode::Part2Nx2N => B::Part2Nx2N,
615- PartMode::Part2NxN => B::Part2NxN,
616- PartMode::PartNx2N => B::PartNx2N,
617- PartMode::PartNxN => B::PartNxN,
618- PartMode::Part2NxnU => B::Part2NxnU,
619- PartMode::Part2NxnD => B::Part2NxnD,
620- PartMode::PartNLx2N => B::PartNLx2N,
621- PartMode::PartNRx2N => B::PartNRx2N,
622- }
623-}
624-
625-/// `true` for the horizontal-split two-PU shapes (`PART_2NxN` /
626-/// `PART_2NxnU` / `PART_2NxnD`) — Table 9-45 bin 1.
627-fn part_is_horizontal(p: PartMode) -> bool {
628- matches!(
629- p,
630- PartMode::Part2NxN | PartMode::Part2NxnU | PartMode::Part2NxnD
631- )
632-}
633-
634-/// `true` for the four asymmetric shapes.
635-fn part_is_amp(p: PartMode) -> bool {
636- matches!(
637- p,
638- PartMode::Part2NxnU | PartMode::Part2NxnD | PartMode::PartNLx2N | PartMode::PartNRx2N
639- )
640-}
641-
642-/// The merge / skip PU syntax for candidate `merge_idx` (the §7.3.8.6
643-/// fields the §8.5.3.2.2 derivation reads).
644-fn merge_pu(merge_idx: usize) -> PredictionUnit {
645- PredictionUnit {
646- merge_flag: true,
647- merge_idx: Some(merge_idx as u8),
648- inter_pred_idc: None,
649- ref_idx_l0: None,
650- mvd_l0: None,
651- mvp_l0_flag: None,
652- ref_idx_l1: None,
653- mvd_l1: None,
654- mvp_l1_flag: None,
655- }
656-}
657-
658-/// An AMVP PU carrying the given per-list signalling groups (the
659-/// §7.3.8.6 fields the §8.5.3.2 derivation reads). At least one list
660-/// must be used; `inter_pred_idc` follows from which are.
661-fn amvp_pu(l0: Option<AmvpGroup>, l1: Option<AmvpGroup>) -> PredictionUnit {
662- let comp = |v: i32| MvdComponent {
663- greater0_flag: u8::from(v != 0),
664- greater1_flag: None,
665- minus2: None,
666- sign_flag: None,
667- value: v,
668- };
669- let idc = match (l0.is_some(), l1.is_some()) {
670- (true, true) => InterPredIdc::PredBi,
671- (false, true) => InterPredIdc::PredL1,
672- // An AMVP PU uses at least one list; default to L0.
673- _ => InterPredIdc::PredL0,
674- };
675- PredictionUnit {
676- merge_flag: false,
677- merge_idx: None,
678- inter_pred_idc: Some(idc),
679- ref_idx_l0: l0.map(|g| g.ref_idx),
680- mvd_l0: l0.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]),
681- mvp_l0_flag: l0.map(|g| g.mvp_flag),
682- ref_idx_l1: l1.map(|g| g.ref_idx),
683- mvd_l1: l1.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]),
684- mvp_l1_flag: l1.map(|g| g.mvp_flag),
685- }
686-}
687-
688-/// A single-list [`amvp_pu`] probe (zero or explicit mvd) for the
689-/// §8.5.3.2.6 predictor derivation and the ME resolution step.
690-fn amvp_pu_list(list: usize, ref_idx: u8, mvd: Mv, mvp_flag: u8) -> PredictionUnit {
691- let g = Some(AmvpGroup {
692- ref_idx,
693- mvd,
694- mvp_flag,
695- });
696- if list == 0 {
697- amvp_pu(g, None)
698- } else {
699- amvp_pu(None, g)
700- }
701-}
702-
703-/// Select the plane set a list prediction reads: the used list's
704-/// `refs[refIdxLX]`, or (for an unused list, whose planes are never
705-/// read) any legal plane set from either list.
706-fn pick_ref<'r>(
707- refs: &'r [RefPlanes],
708- other: &'r [RefPlanes],
709- pred_flag: bool,
710- ref_idx: i32,
711-) -> &'r RefPlanes {
712- if pred_flag {
713- &refs[ref_idx.max(0) as usize]
714- } else {
715- refs.first().unwrap_or_else(|| &other[0])
716- }
717-}
718-
719-/// §8.5.3.3 — the final clipped prediction for a `w`x`h` PU at
720-/// `(x0, y0)` with the resolved motion (uni-L0, uni-L1 or bi). Each
721-/// used list reads `refs_lX[ refIdxLX ]`; the low-delay GOP passes the
722-/// same past reconstructions on both lists, the hierarchical-B GOP
723-/// passes past pictures on L0 and future pictures on L1. `chroma`
724-/// selects whether the Cb / Cr planes are predicted too (the SAD
725-/// search runs luma-only).
726-#[allow(clippy::too_many_arguments)]
727-fn predict_block(
728- refs_l0: &[RefPlanes],
729- refs_l1: &[RefPlanes],
730- x0: usize,
731- y0: usize,
732- w: usize,
733- h: usize,
734- motion: &PuMotion,
735- chroma: bool,
736-) -> InterPrediction {
737- fn list(refp: &RefPlanes, pred_flag: bool, mv: Mv, chroma: bool) -> ListPrediction<'_> {
738- let luma = RefPlane::new(&refp.y, refp.width, refp.height).expect("legal ref plane");
739- let (cb, cr) = if chroma {
740- (
741- Some(
742- RefPlane::new(&refp.cb, refp.width / 2, refp.height / 2).expect("legal plane"),
743- ),
744- Some(
745- RefPlane::new(&refp.cr, refp.width / 2, refp.height / 2).expect("legal plane"),
746- ),
747- )
748- } else {
749- (None, None)
750- };
751- ListPrediction {
752- pred_flag,
753- luma,
754- cb,
755- cr,
756- mv_l: mv,
757- // §8.5.3.2.10: 4:2:0 chroma MV = luma MV (eighth-pel units).
758- mv_c: derive_chroma_mv(mv, 2, 2),
759- }
760- }
761- let l0 = list(
762- pick_ref(refs_l0, refs_l1, motion.pred_flag_l0, motion.ref_idx_l0),
763- motion.pred_flag_l0,
764- motion.mv_l0,
765- chroma,
766- );
767- let l1 = list(
768- pick_ref(refs_l1, refs_l0, motion.pred_flag_l1, motion.ref_idx_l1),
769- motion.pred_flag_l1,
770- motion.mv_l1,
771- chroma,
772- );
773- let geom = InterPredGeometry {
774- x_pb: x0 as i32,
775- y_pb: y0 as i32,
776- n_pb_w: w,
777- n_pb_h: h,
778- chroma_array_type: if chroma { 1 } else { 0 },
779- bit_depth_luma: BIT_DEPTH,
780- bit_depth_chroma: BIT_DEPTH,
781- };
782- predict_inter_pu(&l0, &l1, &geom).expect("legal prediction geometry")
783-}
784-
785-/// Copy a `w`x`h` block into a `bw`-wide buffer at `(bx, by)`.
786-fn blit(dst: &mut [i32], bw: usize, bx: usize, by: usize, src: &[i32], w: usize, h: usize) {
787- for j in 0..h {
788- dst[(by + j) * bw + bx..(by + j) * bw + bx + w].copy_from_slice(&src[j * w..(j + 1) * w]);
789- }
790-}
791-
792-/// Extract an `n`x`n` sub-block of a `bw`-wide buffer at `(bx, by)`.
793-fn sub_block(buf: &[i32], bw: usize, bx: usize, by: usize, n: usize) -> Vec<i32> {
794- let mut out = Vec::with_capacity(n * n);
795- for j in 0..n {
796- out.extend_from_slice(&buf[(by + j) * bw + bx..(by + j) * bw + bx + n]);
797- }
798- out
799-}
800-
801-/// A uni-L0 [`PuMotion`] for motion-search probes (list-0 reference
802-/// index 0 — the probe caller passes the searched reference's planes
803-/// as the single-entry `refs` slice).
804-fn uni_l0(mv: Mv) -> PuMotion {
805- PuMotion {
806- pred_flag_l0: true,
807- pred_flag_l1: false,
808- ref_idx_l0: 0,
809- ref_idx_l1: -1,
810- mv_l0: mv,
811- mv_l1: [0, 0],
812- }
813-}
814-
815-/// The previous frame's reconstruction as `i32` planes (the
816-/// §8.5.3.3.3 interpolation input).
817-struct RefPlanes {
818- y: Vec<i32>,
819- cb: Vec<i32>,
820- cr: Vec<i32>,
821- width: usize,
822- height: usize,
823-}
824-
825-/// Luma SAD between a prediction and the source block.
826-fn sad(pred: &[i32], src: &[i32]) -> u64 {
827- pred.iter()
828- .zip(src.iter())
829- .map(|(&p, &s)| u64::from(p.abs_diff(s)))
830- .sum()
831-}
832-
833-/// Rate proxy (bins) for one signed mvd component.
834-fn mvd_component_bits(v: i32) -> u64 {
835- match v.unsigned_abs() {
836- 0 => 1,
837- 1 => 3,
838- a => 5 + 2 * u64::from(32 - (a - 1).leading_zeros()),
839- }
840-}
841-
842-/// Rate proxy for a full mvd pair.
843-fn mvd_bits(mvd: Mv) -> u64 {
844- mvd_component_bits(mvd[0]) + mvd_component_bits(mvd[1])
845-}
846-
847-/// Crude bit-cost proxy for one TB's quantized levels (mirrors the
848-/// intra encoder's heuristic).
849-fn levels_rate(levels: &[i32]) -> u64 {
850- let bits: u64 = levels
851- .iter()
852- .filter(|&&l| l != 0)
853- .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros()))
854- .sum();
855- if bits == 0 {
856- 1
857- } else {
858- bits + 8
859- }
860-}
861-
862-/// Transform-code the three components of a CTB against `pred`,
863-/// reconstructing through the decode-side path. Returns
864-/// `(levels, recon, ssd_total, rate)`.
865-fn code_ctb_residual(
866- pred: &InterPrediction,
867- src: &[Vec<i32>; 3],
868- qp_y: u32,
869- qp_c: u32,
870-) -> ([Vec<i32>; 3], [Vec<u8>; 3], u64, u64) {
871- let (ly, ry) = code_tb(
872- &src[0],
873- &pred.luma,
874- CTB,
875- qp_y,
876- Component::Luma,
877- PredMode::Inter,
878- );
879- let (lcb, rcb) = code_tb(&src[1], &pred.cb, 8, qp_c, Component::Cb, PredMode::Inter);
880- let (lcr, rcr) = code_tb(&src[2], &pred.cr, 8, qp_c, Component::Cr, PredMode::Inter);
881- let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]);
882- let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr);
883- ([ly, lcb, lcr], [ry, rcb, rcr], dist, rate)
884-}
885-
886-/// The prediction-only reconstruction (clip to 8-bit) and its SSD.
887-fn pred_recon(pred: &InterPrediction, src: &[Vec<i32>; 3]) -> ([Vec<u8>; 3], u64) {
888- let clip = |v: &Vec<i32>| -> Vec<u8> { v.iter().map(|&p| p.clamp(0, 255) as u8).collect() };
889- let recon = [clip(&pred.luma), clip(&pred.cb), clip(&pred.cr)];
890- let dist = ssd(&recon[0], &src[0]) + ssd(&recon[1], &src[1]) + ssd(&recon[2], &src[2]);
891- (recon, dist)
892-}
893-
894-/// Greedy integer-pel motion search on luma SAD: seeds, then a
895-/// small-diamond descent (capped). Returns the best full-pel MV in
896-/// luma samples.
897-#[allow(clippy::too_many_arguments)]
898-fn integer_me(
899- refp: &RefPlanes,
900- src_y: &[i32],
901- x0: usize,
902- y0: usize,
903- w: usize,
904- h: usize,
905- seeds: &[[i32; 2]],
906- lambda_me: u64,
907- mvp_q: &[Mv],
908-) -> [i32; 2] {
909- // Full-pel prediction == direct (clamped) reference samples.
910- let sad_at = |mx: i32, my: i32| -> u64 {
911- let mut acc = 0u64;
912- for j in 0..h {
913- for i in 0..w {
914- let rx = (x0 as i32 + i as i32 + mx).clamp(0, refp.width as i32 - 1);
915- let ry = (y0 as i32 + j as i32 + my).clamp(0, refp.height as i32 - 1);
916- let r = refp.y[ry as usize * refp.width + rx as usize];
917- acc += u64::from(r.abs_diff(src_y[j * w + i]));
918- }
919- }
920- acc
921- };
922- // Motion-cost proxy at full-pel: cheapest mvd against either MVP.
923- let mv_cost = |mx: i32, my: i32| -> u64 {
924- mvp_q
925- .iter()
926- .map(|p| mvd_bits([mx * 4 - p[0], my * 4 - p[1]]))
927- .min()
928- .unwrap_or(0)
929- * lambda_me
930- };
931- let mut best = seeds[0];
932- let mut best_cost = u64::MAX;
933- for &s in seeds {
934- let c = sad_at(s[0], s[1]) + mv_cost(s[0], s[1]);
935- if c < best_cost {
936- best_cost = c;
937- best = s;
938- }
939- }
940- for _ in 0..ME_MAX_STEPS {
941- let mut improved = false;
942- for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
943- let (mx, my) = (best[0] + dx, best[1] + dy);
944- let c = sad_at(mx, my) + mv_cost(mx, my);
945- if c < best_cost {
946- best_cost = c;
947- best = [mx, my];
948- improved = true;
949- }
950- }
951- if !improved {
952- break;
953- }
954- }
955- best
956-}
957-
958-/// Half- then quarter-pel refinement around `best` (quarter-pel
959-/// units), scoring with the real §8.5.3.3.3 interpolation.
960-#[allow(clippy::too_many_arguments)]
961-fn fractional_me(
962- refp: &RefPlanes,
963- src_y: &[i32],
964- x0: usize,
965- y0: usize,
966- w: usize,
967- h: usize,
968- start: Mv,
969- lambda_me: u64,
970- mvp_q: &[Mv],
971-) -> Mv {
972- let cost_at = |mv: Mv| -> u64 {
973- let one = std::slice::from_ref(refp);
974- let pred = predict_block(one, one, x0, y0, w, h, &uni_l0(mv), false);
975- let mv_rate = mvp_q
976- .iter()
977- .map(|p| mvd_bits([mv[0] - p[0], mv[1] - p[1]]))
978- .min()
979- .unwrap_or(0);
980- sad(&pred.luma, src_y) + lambda_me * mv_rate
981- };
982- let mut best = start;
983- let mut best_cost = cost_at(best);
984- for step in [2i32, 1] {
985- let mut improved = true;
986- while improved {
987- improved = false;
988- for (dx, dy) in [
989- (step, 0),
990- (-step, 0),
991- (0, step),
992- (0, -step),
993- (step, step),
994- (step, -step),
995- (-step, step),
996- (-step, -step),
997- ] {
998- let mv = [best[0] + dx, best[1] + dy];
999- let c = cost_at(mv);
1000- if c < best_cost {
1001- best_cost = c;
1002- best = mv;
1003- improved = true;
1004- }
1005- }
1006- }
1007- }
1008- best
1009-}
1010-
1011-/// Inputs shared by every per-PU decision of one slice.
1012-struct PuChooseCtx<'a> {
1013- refs_l0: &'a [RefPlanes],
1014- refs_l1: &'a [RefPlanes],
1015- mv_ctx: &'a PuMvContext<'a>,
1016- lambda_me: u64,
1017- b_slice: bool,
1018- /// B slice whose two reference lists differ (hierarchical B): the
1019- /// AMVP election searches L1 and the bi combination too. A
1020- /// low-delay B (both lists the same pictures) keeps the L0-only
1021- /// search — L1 would duplicate it bin for bin at a higher rate.
1022- two_sided: bool,
1023-}
1024-
1025-/// Choose merge-vs-AMVP for one prediction unit against `field` (the
1026-/// motion state the decoder will have when resolving this PU), by
1027-/// luma SAD + λ·signalling-bins. Returns the syntax, the resolved
1028-/// motion, and the motion-rate proxy.
1029-fn choose_pu(
1030- field: &MotionField,
1031- geom: &PuGeometry,
1032- available: &dyn Fn(i32, i32) -> bool,
1033- src_y: &[i32],
1034- ctx: &PuChooseCtx<'_>,
1035-) -> (PuSyntax, PuMotion, u64) {
1036- let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1037- // ---- merge candidates (§8.5.3.2.2) ----
1038- let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE);
1039- for idx in 0..MAX_MERGE {
1040- let m = resolve_pu_motion(field, geom, &merge_pu(idx), ctx.mv_ctx, available);
1041- // A later duplicate can never beat the earlier index.
1042- if !merge_cands.iter().any(|(_, prev)| *prev == m) {
1043- merge_cands.push((idx, m));
1044- }
1045- }
1046- let (merge_cost, merge_idx, merge_motion) = merge_cands
1047- .iter()
1048- .map(|&(idx, m)| {
1049- let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &m, false);
1050- (
1051- sad(&pred.luma, src_y) + ctx.lambda_me * (idx as u64 + 2),
1052- idx,
1053- m,
1054- )
1055- })
1056- .min_by_key(|&(cost, idx, _)| (cost, idx))
1057- .expect("merge list is never empty");
1058-
1059- let (amvp_syntax, amvp_motion, best_amvp_rate, best_amvp_cost) =
1060- amvp_search(field, geom, available, src_y, ctx, &merge_cands);
1061-
1062- if merge_cost <= best_amvp_cost {
1063- (
1064- PuSyntax::Merge { merge_idx },
1065- merge_motion,
1066- merge_idx as u64 + 2,
1067- )
1068- } else {
1069- (amvp_syntax, amvp_motion, best_amvp_rate)
1070- }
1071-}
1072-
1073-/// §8.5.3.2.6 + motion estimation over every active reference of ONE
1074-/// list: the SAD + λ·bins-best single-list AMVP signalling for one
1075-/// PU. Returns the group, the resolved motion, the rate proxy and the
1076-/// search cost; `None` when the list has no active reference.
1077-#[allow(clippy::too_many_arguments)]
1078-fn amvp_search_list(
1079- field: &MotionField,
1080- geom: &PuGeometry,
1081- available: &dyn Fn(i32, i32) -> bool,
1082- src_y: &[i32],
1083- ctx: &PuChooseCtx<'_>,
1084- merge_cands: &[(usize, PuMotion)],
1085- list: usize,
1086-) -> Option<(AmvpGroup, PuMotion, u64, u64)> {
1087- let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1088- let refs = if list == 0 { ctx.refs_l0 } else { ctx.refs_l1 };
1089- let mv_of = |m: &PuMotion| if list == 0 { m.mv_l0 } else { m.mv_l1 };
1090- let mut best: Option<(AmvpGroup, PuMotion, u64, u64)> = None;
1091- for (r, refp) in refs.iter().enumerate() {
1092- let mvp = [
1093- mv_of(&resolve_pu_motion(
1094- field,
1095- geom,
1096- &amvp_pu_list(list, r as u8, [0, 0], 0),
1097- ctx.mv_ctx,
1098- available,
1099- )),
1100- mv_of(&resolve_pu_motion(
1101- field,
1102- geom,
1103- &amvp_pu_list(list, r as u8, [0, 0], 1),
1104- ctx.mv_ctx,
1105- available,
1106- )),
1107- ];
1108- let mut seeds: Vec<[i32; 2]> = vec![[0, 0]];
1109- for p in &mvp {
1110- seeds.push([p[0] >> 2, p[1] >> 2]);
1111- }
1112- for (_, m) in merge_cands {
1113- let mv = mv_of(m);
1114- seeds.push([mv[0] >> 2, mv[1] >> 2]);
1115- }
1116- seeds.dedup();
1117- let int_mv = integer_me(refp, src_y, x, y, w, h, &seeds, ctx.lambda_me, &mvp);
1118- let me_mv = fractional_me(
1119- refp,
1120- src_y,
1121- x,
1122- y,
1123- w,
1124- h,
1125- [int_mv[0] * 4, int_mv[1] * 4],
1126- ctx.lambda_me,
1127- &mvp,
1128- );
1129- // Choose the cheaper predictor for the found MV.
1130- let (mvp_flag, mvd) = (0u8..2)
1131- .map(|f| {
1132- let p = mvp[f as usize];
1133- (f, [me_mv[0] - p[0], me_mv[1] - p[1]])
1134- })
1135- .min_by_key(|&(_, d)| mvd_bits(d))
1136- .expect("two predictors");
1137- // Resolve through the decoder's derivation (mv wrap etc.).
1138- let motion = resolve_pu_motion(
1139- field,
1140- geom,
1141- &amvp_pu_list(list, r as u8, mvd, mvp_flag),
1142- ctx.mv_ctx,
1143- available,
1144- );
1145- // merge_flag + mvp_flag + ref_idx bin (2 refs) + idc (B) + mvd.
1146- let rate = 2 + mvd_bits(mvd) + u64::from(refs.len() > 1) + u64::from(ctx.b_slice) * 2;
1147- let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false);
1148- let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate;
1149- let improved = match &best {
1150- None => true,
1151- Some((_, _, _, c)) => cost < *c,
1152- };
1153- if improved {
1154- let group = AmvpGroup {
1155- ref_idx: r as u8,
1156- mvd,
1157- mvp_flag,
1158- };
1159- best = Some((group, motion, rate, cost));
1160- }
1161- }
1162- best
1163-}
1164-
1165-/// The full AMVP election for one PU: the best single-list search on
1166-/// L0 — and, on a two-sided B slice, on L1 plus the bi-predictive
1167-/// combination of the two winners. Returns the syntax, the resolved
1168-/// motion, the rate proxy and the search cost.
1169-fn amvp_search(
1170- field: &MotionField,
1171- geom: &PuGeometry,
1172- available: &dyn Fn(i32, i32) -> bool,
1173- src_y: &[i32],
1174- ctx: &PuChooseCtx<'_>,
1175- merge_cands: &[(usize, PuMotion)],
1176-) -> (PuSyntax, PuMotion, u64, u64) {
1177- let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1178- let l0 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 0);
1179- if !ctx.two_sided {
1180- let (g, motion, rate, cost) = l0.expect("at least one L0 reference");
1181- return (
1182- PuSyntax::Amvp {
1183- l0: Some(g),
1184- l1: None,
1185- },
1186- motion,
1187- rate,
1188- cost,
1189- );
1190- }
1191- let l1 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 1);
1192- let mut cands: Vec<(PuSyntax, PuMotion, u64, u64)> = Vec::with_capacity(3);
1193- if let Some((g, motion, rate, cost)) = l0 {
1194- cands.push((
1195- PuSyntax::Amvp {
1196- l0: Some(g),
1197- l1: None,
1198- },
1199- motion,
1200- rate,
1201- cost,
1202- ));
1203- }
1204- if let Some((g, motion, rate, cost)) = l1 {
1205- cands.push((
1206- PuSyntax::Amvp {
1207- l0: None,
1208- l1: Some(g),
1209- },
1210- motion,
1211- rate,
1212- cost,
1213- ));
1214- }
1215- if let (Some((g0, _, _, _)), Some((g1, _, _, _))) = (&l0, &l1) {
1216- // Bi combination of the two single-list winners: the AMVP
1217- // predictor derivation of each list is independent of the
1218- // other, so the resolved per-list MVs match the uni winners.
1219- let motion = resolve_pu_motion(
1220- field,
1221- geom,
1222- &amvp_pu(Some(*g0), Some(*g1)),
1223- ctx.mv_ctx,
1224- available,
1225- );
1226- // merge_flag + inter_pred_idc ("1") + per-list mvd/mvp/ref bins.
1227- let rate = 2
1228- + (mvd_bits(g0.mvd) + 1 + u64::from(ctx.refs_l0.len() > 1))
1229- + (mvd_bits(g1.mvd) + 1 + u64::from(ctx.refs_l1.len() > 1));
1230- let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false);
1231- let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate;
1232- cands.push((
1233- PuSyntax::Amvp {
1234- l0: Some(*g0),
1235- l1: Some(*g1),
1236- },
1237- motion,
1238- rate,
1239- cost,
1240- ));
1241- }
1242- cands
1243- .into_iter()
1244- .min_by_key(|&(_, _, _, cost)| cost)
1245- .expect("at least one active reference across the lists")
1246-}
1247-
1248-/// Encode `merge_idx` (§9.3.3.10 TR with `cMax = MaxNumMergeCand − 1`:
1249-/// bin 0 context-coded, the rest bypass).
1250-fn encode_merge_idx(
1251- w: &mut BitWriter,
1252- cabac: &mut CabacEncoder,
1253- ctxs: &mut SliceContexts,
1254- idx: usize,
1255-) {
1256- let c_max = MAX_MERGE - 1;
1257- cabac.encode_decision(w, &mut ctxs.merge_idx[0], u8::from(idx > 0));
1258- if idx > 0 {
1259- for _ in 1..idx {
1260- cabac.encode_bypass(w, 1);
1261- }
1262- if idx < c_max {
1263- cabac.encode_bypass(w, 0);
1264- }
1265- }
1266-}
1267-
1268-/// §9.3.3.3 — encode an EGk-coded value (the dual of the decoder's
1269-/// `read_eg_k_with`): a run of `1` prefix bins, a `0`, then
1270-/// `prefix_ones + k` MSB-first suffix bins.
1271-fn encode_eg_k(w: &mut BitWriter, cabac: &mut CabacEncoder, value: u32, k: u32) {
1272- let mut prefix_ones = 0u32;
1273- while ((1u64 << (prefix_ones + 1)) - 1) << k <= u64::from(value) {
1274- prefix_ones += 1;
1275- }
1276- for _ in 0..prefix_ones {
1277- cabac.encode_bypass(w, 1);
1278- }
1279- cabac.encode_bypass(w, 0);
1280- let base = ((1u64 << prefix_ones) - 1) << k;
1281- let suffix = (u64::from(value) - base) as u32;
1282- cabac.encode_bypass_bits(w, suffix, (prefix_ones + k) as u8);
1283-}
1284-
1285-/// §7.3.8.9 `mvd_coding( )` — the interleaved bin order the decoder's
1286-/// `decode_mvd_pair` reads: both `abs_mvd_greater0_flag`s, both
1287-/// `abs_mvd_greater1_flag`s, then per component the EG1
1288-/// `abs_mvd_minus2` escape and `mvd_sign_flag`.
1289-fn encode_mvd_pair(w: &mut BitWriter, cabac: &mut CabacEncoder, ctxs: &mut SliceContexts, mvd: Mv) {
1290- let g0 = [mvd[0] != 0, mvd[1] != 0];
1291- for &g in &g0 {
1292- cabac.encode_decision(w, &mut ctxs.abs_mvd_greater0_flag[0], u8::from(g));
1293- }
1294- for (&g, &v) in g0.iter().zip(mvd.iter()) {
1295- if g {
1296- cabac.encode_decision(
1297- w,
1298- &mut ctxs.abs_mvd_greater1_flag[0],
1299- u8::from(v.unsigned_abs() > 1),
1300- );
1301- }
1302- }
1303- for (&g, &v) in g0.iter().zip(mvd.iter()) {
1304- if g {
1305- let a = v.unsigned_abs();
1306- if a > 1 {
1307- encode_eg_k(w, cabac, a - 2, 1);
1308- }
1309- cabac.encode_bypass(w, u8::from(v < 0));
1310- }
1311- }
1312-}
1313-
1314-/// §7.3.8.6 — emit one prediction unit's syntax (merge_flag +
1315-/// merge_idx, or the AMVP groups). On B slices `inter_pred_idc` is
1316-/// coded per Table 9-47 (`PRED_BI` = "1", `PRED_L0` = "00", `PRED_L1`
1317-/// = "01"; bin 0 ctxInc = CtDepth = 0, bin 1 ctxInc = 4 — `nPbW +
1318-/// nPbH != 12` for every PU shape this encoder emits). Each used
1319-/// list codes `ref_idx_lX` (a single context bin — at most two active
1320-/// references per list), `mvd_coding` (`mvd_l1_zero_flag == 0`) and
1321-/// `mvp_lX_flag`.
1322-fn encode_pu_syntax(
1323- w: &mut BitWriter,
1324- cabac: &mut CabacEncoder,
1325- ctxs: &mut SliceContexts,
1326- pu: &PuSyntax,
1327- b_slice: bool,
1328- n_l0: usize,
1329- n_l1: usize,
1330-) {
1331- match pu {
1332- PuSyntax::Merge { merge_idx } => {
1333- cabac.encode_decision(w, &mut ctxs.merge_flag[0], 1);
1334- encode_merge_idx(w, cabac, ctxs, *merge_idx);
1335- }
1336- PuSyntax::Amvp { l0, l1 } => {
1337- cabac.encode_decision(w, &mut ctxs.merge_flag[0], 0);
1338- if b_slice {
1339- let (head, tail) = ctxs.inter_pred_idc.split_at_mut(4);
1340- if l0.is_some() && l1.is_some() {
1341- cabac.encode_decision(w, &mut head[0], 1); // PRED_BI
1342- } else {
1343- cabac.encode_decision(w, &mut head[0], 0);
1344- cabac.encode_decision(w, &mut tail[0], u8::from(l1.is_some()));
1345- }
1346- }
1347- for (group, n_active) in [(l0, n_l0), (l1, n_l1)] {
1348- let Some(g) = group else { continue };
1349- if n_active > 1 {
1350- // §9.3.3 TR cMax = num_ref_idx_lX_active_minus1 ==
1351- // 1: a single context-coded bin (ctxInc 0).
1352- debug_assert!(n_active == 2, "at most two active references per list");
1353- cabac.encode_decision(w, &mut ctxs.ref_idx[0], g.ref_idx);
1354- }
1355- encode_mvd_pair(w, cabac, ctxs, g.mvd);
1356- cabac.encode_decision(w, &mut ctxs.mvp_flag[0], g.mvp_flag);
1357- }
1358- }
1359- }
1360-}
1361-
1362-/// Encode one P / B frame as a single TRAIL_R slice against the
1363-/// reference lists of `spec`: pass 1 makes the per-CTB mode decisions
1364-/// and builds the pre-filter reconstruction, the §8.7 filter stage
1365-/// elects and applies deblocking + SAO, pass 2 emits the slice header
1366-/// and syntax. Returns the slice RBSP, the frame's (filtered)
1367-/// reconstruction, and its CU mode-decision counters.
1368-#[allow(clippy::too_many_lines)]
1369-pub(crate) fn encode_inter_slice(
1370- frame: &YuvFrame<'_>,
1371- spec: &SliceSpec<'_>,
1372- width: usize,
1373- height: usize,
1374-) -> (Vec<u8>, FrameRecon, FrameStats) {
1375- let (poc, qp, b_slice, lf) = (spec.poc, spec.qp, spec.b_slice, spec.lf);
1376- let (cw, ch) = (width / 2, height / 2);
1377- let ctbs_x = width / CTB;
1378- let ctbs_y = height / CTB;
1379- let qp_y = qp as u32;
1380- let qp_c = chroma_qp_420(qp);
1381- // SSD-per-bit tradeoff, doubling every 3 QP (as the intra path);
1382- // the SAD-domain motion-search λ uses the same scale.
1383- let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3);
1384- let lambda_me: u64 = lambda;
1385-
1386- let to_i32 = |p: &[u8]| -> Vec<i32> { p.iter().map(|&v| i32::from(v)).collect() };
1387- let to_planes = |list: &[(i32, &FrameRecon)]| -> Vec<RefPlanes> {
1388- list.iter()
1389- .map(|&(_, rec)| RefPlanes {
1390- y: to_i32(&rec.y),
1391- cb: to_i32(&rec.cb),
1392- cr: to_i32(&rec.cr),
1393- width,
1394- height,
1395- })
1396- .collect()
1397- };
1398- let refs_l0: Vec<RefPlanes> = to_planes(&spec.l0);
1399- let refs_l1: Vec<RefPlanes> = to_planes(&spec.l1);
1400- let l0_pocs: Vec<i32> = spec.l0.iter().map(|&(p, _)| p).collect();
1401- let l1_pocs: Vec<i32> = spec.l1.iter().map(|&(p, _)| p).collect();
1402- let n_l0 = l0_pocs.len() as i32;
1403- let n_l1 = l1_pocs.len() as i32;
1404- // Hierarchical B: the two lists differ, so the AMVP election
1405- // searches L1 / bi as well; a low-delay B keeps the L0-only
1406- // search (L1 duplicates it at a higher signalling rate).
1407- let two_sided = b_slice && l0_pocs != l1_pocs;
1408-
1409- let mut recon = FrameRecon {
1410- y: vec![0u8; width * height],
1411- cb: vec![0u8; cw * ch],
1412- cr: vec![0u8; cw * ch],
1413- };
1414- let mut field = MotionField::new(width, height);
1415- // §8.4.2 luma-mode records for the intra-fallback MPM lists (an
1416- // inter / skip CU records as "not intra" ⇒ candidate INTRA_DC).
1417- let mut modes = IntraModeField::new(width, height, CTB_LOG2);
1418- // Per-CTB cu_skip_flag values (CU == CTB) for the §9.3.4.2.2 ctxInc.
1419- let mut skip_grid = vec![false; ctbs_x * ctbs_y];
1420- let mut stats = FrameStats::default();
1421-
1422- // §6.4.2 availability plumbing (single slice, single tile).
1423- let tiling = PictureTiling::new(
1424- ctbs_x as u32,
1425- ctbs_y as u32,
1426- width as u32,
1427- height as u32,
1428- CTB_LOG2,
1429- 2,
1430- &TilingParams::single_tile(),
1431- )
1432- .expect("legal single-tile geometry");
1433-
1434- // §8.5.3.2 reference resolvers over the spec's explicit lists.
1435- let list_pocs = |list: usize| -> &Vec<i32> {
1436- if list == 0 {
1437- &l0_pocs
1438- } else {
1439- &l1_pocs
1440- }
1441- };
1442- let ref_poc = |list: usize, ref_idx: i32| -> i32 {
1443- usize::try_from(ref_idx)
1444- .ok()
1445- .and_then(|i| list_pocs(list).get(i).copied())
1446- .unwrap_or(i32::MIN)
1447- };
1448- // The decoder's motion-field cells store the REFERENCED
1449- // picture's POC per used list (pu_mv fill: `ref_poc(list, idx)`);
1450- // an unused list's value is ignored by `to_cell`.
1451- let cell_pocs =
1452- |m: &PuMotion| -> (i32, i32) { (ref_poc(0, m.ref_idx_l0), ref_poc(1, m.ref_idx_l1)) };
1453- let ref_long_term = |_list: usize, _ref_idx: i32| false;
1454- let ref_short_term = |list: usize, ref_idx: i32| {
1455- usize::try_from(ref_idx).is_ok_and(|i| i < list_pocs(list).len())
1456- };
1457- let col_ref_long_term = |_poc: i32| false;
1458- // §8.5.3.2.2 NoBackwardPredFlag: 1 iff every active reference of
1459- // both lists precedes the current picture in output order.
1460- let no_backward_pred = !l0_pocs.iter().chain(l1_pocs.iter()).any(|&p| p > poc);
1461- let mv_ctx = PuMvContext {
1462- curr_poc: poc,
1463- slice_is_b: b_slice,
1464- ctb_log2_size_y: CTB_LOG2,
1465- pic_width_luma: width as u32,
1466- pic_height_luma: height as u32,
1467- max_num_merge_cand: MAX_MERGE,
1468- num_ref_idx_l0_active: n_l0,
1469- num_ref_idx_l1_active: if b_slice { n_l1 } else { 0 },
1470- log2_par_mrg_level: 2,
1471- temporal_mvp_enabled: false,
1472- collocated_from_l0_flag: true,
1473- col_poc: 0,
1474- no_backward_pred,
1475- ref_poc: &ref_poc,
1476- ref_long_term: &ref_long_term,
1477- ref_short_term: &ref_short_term,
1478- col_field: None,
1479- col_ref_long_term: &col_ref_long_term,
1480- use_integer_mv: false,
1481- two_versions_curr_pic: false,
1482- is_curr_pic: &|_, _| false,
1483- };
1484-
1485- // ---- pass 1: per-CTB mode decisions + reconstruction ----
1486- let mut plans: Vec<CuCandidate> = Vec::with_capacity(ctbs_x * ctbs_y);
1487- // `ctb` also drives the x0/y0 arithmetic, not just the grid index.
1488- #[allow(clippy::needless_range_loop)]
1489- for ctb in 0..ctbs_x * ctbs_y {
1490- let x0 = (ctb % ctbs_x) * CTB;
1491- let y0 = (ctb / ctbs_x) * CTB;
1492- let (cx0, cy0) = (x0 / 2, y0 / 2);
1493- let src = [
1494- extract(frame.y, width, x0, y0, CTB),
1495- extract(frame.cb, cw, cx0, cy0, 8),
1496- extract(frame.cr, cw, cx0, cy0, 8),
1497- ];
1498-
1499- let geom = PuGeometry {
1500- x_cb: x0,
1501- y_cb: y0,
1502- n_cb_s: CTB,
1503- x_pb: x0,
1504- y_pb: y0,
1505- n_pb_w: CTB,
1506- n_pb_h: CTB,
1507- part_mode: PartMode::Part2Nx2N,
1508- part_idx: 0,
1509- };
1510-
1511- let chosen = {
1512- // §6.4.2 prediction-block availability against the
1513- // in-progress motion field (identical to the decoder's
1514- // closure in the picture-level inter driver).
1515- let available = |x_nb: i32, y_nb: i32| -> bool {
1516- tiling.prediction_block_availability(
1517- x0 as u32,
1518- y0 as u32,
1519- CTB as u32,
1520- x0 as u32,
1521- y0 as u32,
1522- CTB as u32,
1523- CTB as u32,
1524- 0,
1525- x_nb,
1526- y_nb,
1527- |_ctb_rs| 0,
1528- |x, y| {
1529- if field.cell_at(x as usize, y as usize).is_intra {
1530- MODE_INTRA
1531- } else {
1532- 0
1533- }
1534- },
1535- )
1536- };
1537-
1538- // ---- merge / skip candidates (§8.5.3.2.2) ----
1539- let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE);
1540- for idx in 0..MAX_MERGE {
1541- let m = resolve_pu_motion(&field, &geom, &merge_pu(idx), &mv_ctx, &available);
1542- // A later duplicate can never beat the earlier index
1543- // (same samples, more merge_idx bins).
1544- if !merge_cands.iter().any(|(_, prev)| *prev == m) {
1545- merge_cands.push((idx, m));
1546- }
1547- }
1548- let (best_merge_idx, best_merge_motion) = merge_cands
1549- .iter()
1550- .map(|&(idx, m)| {
1551- let pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &m, false);
1552- (
1553- sad(&pred.luma, &src[0]) + lambda_me * (idx as u64 + 1),
1554- idx,
1555- m,
1556- )
1557- })
1558- .min_by_key(|&(cost, idx, _)| (cost, idx))
1559- .map(|(_, idx, m)| (idx, m))
1560- .expect("merge list is never empty");
1561-
1562- // ---- AMVP: §8.5.3.2.6 predictors + per-reference ME ----
1563- let choose_ctx = PuChooseCtx {
1564- refs_l0: &refs_l0,
1565- refs_l1: &refs_l1,
1566- mv_ctx: &mv_ctx,
1567- lambda_me,
1568- b_slice,
1569- two_sided,
1570- };
1571- let (amvp_syntax, amvp_motion, amvp_rate, _) = amvp_search(
1572- &field,
1573- &geom,
1574- &available,
1575- &src[0],
1576- &choose_ctx,
1577- &merge_cands,
1578- );
1579-
1580- // ---- fully code the finalists ----
1581- let mut cands: Vec<CuCandidate> = Vec::with_capacity(6);
1582-
1583- // Skip: best merge candidate, prediction only.
1584- let merge_pred = predict_block(
1585- &refs_l0,
1586- &refs_l1,
1587- x0,
1588- y0,
1589- CTB,
1590- CTB,
1591- &best_merge_motion,
1592- true,
1593- );
1594- let (skip_recon, skip_dist) = pred_recon(&merge_pred, &src);
1595- cands.push(CuCandidate {
1596- kind: CuKind::Skip {
1597- merge_idx: best_merge_idx,
1598- },
1599- motions: vec![best_merge_motion],
1600- levels: None,
1601- recon: skip_recon,
1602- cost: skip_dist + lambda * (best_merge_idx as u64 + 2),
1603- });
1604-
1605- // Merge + residual (only legal when some level is nonzero:
1606- // a 2Nx2N merge CU has rqt_root_cbf inferred 1).
1607- let (m_levels, m_recon, m_dist, m_rate) =
1608- code_ctb_residual(&merge_pred, &src, qp_y, qp_c);
1609- if m_levels.iter().any(|l| l.iter().any(|&v| v != 0)) {
1610- cands.push(CuCandidate {
1611- kind: CuKind::Merge {
1612- merge_idx: best_merge_idx,
1613- },
1614- motions: vec![best_merge_motion],
1615- levels: Some(CuLevels::Depth0(m_levels)),
1616- recon: m_recon,
1617- cost: m_dist + lambda * (m_rate + best_merge_idx as u64 + 3),
1618- });
1619- }
1620-
1621- // AMVP (with or without residual).
1622- let amvp_pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &amvp_motion, true);
1623- let (a_levels, a_recon, a_dist, a_rate) =
1624- code_ctb_residual(&amvp_pred, &src, qp_y, qp_c);
1625- let motion_rate = amvp_rate + 2; // + skip / rqt flags
1626- if a_levels.iter().any(|l| l.iter().any(|&v| v != 0)) {
1627- cands.push(CuCandidate {
1628- kind: CuKind::Amvp { pu: amvp_syntax },
1629- motions: vec![amvp_motion],
1630- levels: Some(CuLevels::Depth0(a_levels)),
1631- recon: a_recon,
1632- cost: a_dist + lambda * (a_rate + motion_rate),
1633- });
1634- } else {
1635- // All-zero residual: rqt_root_cbf == 0.
1636- let (pr, pd) = pred_recon(&amvp_pred, &src);
1637- cands.push(CuCandidate {
1638- kind: CuKind::Amvp { pu: amvp_syntax },
1639- motions: vec![amvp_motion],
1640- levels: None,
1641- recon: pr,
1642- cost: pd + lambda * motion_rate,
1643- });
1644- }
1645-
1646- // ---- two-PU partitions: the symmetric rectangles, plus
1647- // the four asymmetric shapes on an AMP stream ----
1648- let mut two_pu_parts = vec![PartMode::Part2NxN, PartMode::PartNx2N];
1649- if spec.big_cu {
1650- two_pu_parts.extend([
1651- PartMode::Part2NxnU,
1652- PartMode::Part2NxnD,
1653- PartMode::PartNLx2N,
1654- PartMode::PartNRx2N,
1655- ]);
1656- }
1657- for part in two_pu_parts {
1658- let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part);
1659- // The decoder resolves PU1 with PU0's motion already in
1660- // the field (§8.5.3.2 order): stage the writes on a copy.
1661- let mut tmp = field.clone();
1662- let mut pus = [PuSyntax::Merge { merge_idx: 0 }; 2];
1663- let mut motions_r = Vec::with_capacity(2);
1664- let mut pred_y = vec![0i32; CTB * CTB];
1665- let mut pred_cb = vec![0i32; 64];
1666- let mut pred_cr = vec![0i32; 64];
1667- // pred_mode + part_mode bins (the AMP forms carry two
1668- // extra part_mode bins).
1669- let mut motion_rate_r = if part_is_amp(part) { 5u64 } else { 3u64 };
1670- for (k, r) in rects.iter().enumerate() {
1671- let g = PuGeometry {
1672- x_cb: x0,
1673- y_cb: y0,
1674- n_cb_s: CTB,
1675- x_pb: r.x_pb,
1676- y_pb: r.y_pb,
1677- n_pb_w: r.n_pb_w,
1678- n_pb_h: r.n_pb_h,
1679- part_mode: part,
1680- part_idx: k as u32,
1681- };
1682- // §6.4.2 availability against the staged field. The
1683- // decoder's closure passes the CU as the PU geometry
1684- // (the sameCb NxN clause never fires for 2-PU
1685- // shapes) and treats the current CU as MODE_INTER.
1686- let avail_k = |x_nb: i32, y_nb: i32| -> bool {
1687- tiling.prediction_block_availability(
1688- x0 as u32,
1689- y0 as u32,
1690- CTB as u32,
1691- x0 as u32,
1692- y0 as u32,
1693- CTB as u32,
1694- CTB as u32,
1695- 0,
1696- x_nb,
1697- y_nb,
1698- |_ctb_rs| 0,
1699- |x, y| {
1700- let (xu, yu) = (x as usize, y as usize);
1701- let inside_cu =
1702- (x0..x0 + CTB).contains(&xu) && (y0..y0 + CTB).contains(&yu);
1703- if !inside_cu && tmp.cell_at(xu, yu).is_intra {
1704- MODE_INTRA
1705- } else {
1706- 0
1707- }
1708- },
1709- )
1710- };
1711- let mut src_pu = Vec::with_capacity(r.n_pb_w * r.n_pb_h);
1712- for j in 0..r.n_pb_h {
1713- for i in 0..r.n_pb_w {
1714- src_pu.push(i32::from(frame.y[(r.y_pb + j) * width + r.x_pb + i]));
1715- }
1716- }
1717- let (pu_syntax, motion, rate_k) =
1718- choose_pu(&tmp, &g, &avail_k, &src_pu, &choose_ctx);
1719- // eqs 8-80..8-85: PU1's derivation sees PU0's motion.
1720- tmp.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, {
1721- let (p0, p1) = cell_pocs(&motion);
1722- motion.to_cell(p0, p1)
1723- });
1724- let p = predict_block(
1725- &refs_l0, &refs_l1, r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, &motion, true,
1726- );
1727- blit(
1728- &mut pred_y,
1729- CTB,
1730- r.x_pb - x0,
1731- r.y_pb - y0,
1732- &p.luma,
1733- r.n_pb_w,
1734- r.n_pb_h,
1735- );
1736- blit(
1737- &mut pred_cb,
1738- 8,
1739- (r.x_pb - x0) / 2,
1740- (r.y_pb - y0) / 2,
1741- &p.cb,
1742- r.n_pb_w / 2,
1743- r.n_pb_h / 2,
1744- );
1745- blit(
1746- &mut pred_cr,
1747- 8,
1748- (r.x_pb - x0) / 2,
1749- (r.y_pb - y0) / 2,
1750- &p.cr,
1751- r.n_pb_w / 2,
1752- r.n_pb_h / 2,
1753- );
1754- pus[k] = pu_syntax;
1755- motions_r.push(motion);
1756- motion_rate_r += rate_k;
1757- }
1758- // §7.4.9.8 interSplitFlag: forced depth-1 tree — four
1759- // z-order 8x8 luma + 4x4 chroma TBs.
1760- let mut luma_l: [Vec<i32>; 4] = Default::default();
1761- let mut cb_l: [Vec<i32>; 4] = Default::default();
1762- let mut cr_l: [Vec<i32>; 4] = Default::default();
1763- let mut recon_r = [vec![0u8; CTB * CTB], vec![0u8; 64], vec![0u8; 64]];
1764- let mut rate_r = 0u64;
1765- for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
1766- let (lx, ly8) = (zx * 8, zy * 8);
1767- let s_y = sub_block(&src[0], CTB, lx, ly8, 8);
1768- let p_y = sub_block(&pred_y, CTB, lx, ly8, 8);
1769- let (lv, rc) = code_tb(&s_y, &p_y, 8, qp_y, Component::Luma, PredMode::Inter);
1770- for j in 0..8 {
1771- recon_r[0][(ly8 + j) * CTB + lx..(ly8 + j) * CTB + lx + 8]
1772- .copy_from_slice(&rc[j * 8..(j + 1) * 8]);
1773- }
1774- rate_r += levels_rate(&lv);
1775- luma_l[k] = lv;
1776- for (plane, src_c, pred_c, out) in [
1777- (1usize, &src[1], &pred_cb, &mut cb_l),
1778- (2usize, &src[2], &pred_cr, &mut cr_l),
1779- ] {
1780- let s_c = sub_block(src_c, 8, zx * 4, zy * 4, 4);
1781- let p_c = sub_block(pred_c, 8, zx * 4, zy * 4, 4);
1782- let comp = if plane == 1 {
1783- Component::Cb
1784- } else {
1785- Component::Cr
1786- };
1787- let (lv_c, rc_c) = code_tb(&s_c, &p_c, 4, qp_c, comp, PredMode::Inter);
1788- for j in 0..4 {
1789- recon_r[plane]
1790- [(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4]
1791- .copy_from_slice(&rc_c[j * 4..(j + 1) * 4]);
1792- }
1793- rate_r += levels_rate(&lv_c);
1794- out[k] = lv_c;
1795- }
1796- }
1797- let any_nonzero = luma_l
1798- .iter()
1799- .chain(cb_l.iter())
1800- .chain(cr_l.iter())
1801- .any(|l| l.iter().any(|&v| v != 0));
1802- let (levels_r, recon_final, dist_r) = if any_nonzero {
1803- let d = ssd(&recon_r[0], &src[0])
1804- + ssd(&recon_r[1], &src[1])
1805- + ssd(&recon_r[2], &src[2]);
1806- (
1807- Some(CuLevels::Depth1(Box::new(Depth1Levels {
1808- luma: luma_l,
1809- cb: cb_l,
1810- cr: cr_l,
1811- }))),
1812- recon_r,
1813- d + lambda * rate_r,
1814- )
1815- } else {
1816- // rqt_root_cbf == 0: prediction-only reconstruction.
1817- let clip = |v: &[i32]| -> Vec<u8> {
1818- v.iter().map(|&p| p.clamp(0, 255) as u8).collect()
1819- };
1820- let rec = [clip(&pred_y), clip(&pred_cb), clip(&pred_cr)];
1821- let d = ssd(&rec[0], &src[0]) + ssd(&rec[1], &src[1]) + ssd(&rec[2], &src[2]);
1822- (None, rec, d)
1823- };
1824- cands.push(CuCandidate {
1825- kind: CuKind::TwoPu { part, pus },
1826- motions: motions_r,
1827- levels: levels_r,
1828- recon: recon_final,
1829- cost: dist_r + lambda * (motion_rate_r + 1),
1830- });
1831- }
1832-
1833- // ---- intra 2Nx2N fallback (§8.4 against our own recon) ----
1834- {
1835- let read_y = |x: usize, yy: usize| i32::from(recon.y[yy * width + x]);
1836- let avail_y =
1837- |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
1838- let marked = gather_refs(&read_y, &avail_y, x0, y0, CTB);
1839- let (mode, pred_y) = search_best_mode(&marked, &src[0]);
1840- let (ly, ry) = code_tb(
1841- &src[0],
1842- &pred_y,
1843- CTB,
1844- qp_y,
1845- Component::Luma,
1846- PredMode::Intra,
1847- );
1848- let code_c = |plane: &[u8], comp: Component, pc: PredComponent| {
1849- let read = |x: usize, yy: usize| i32::from(plane[yy * cw + x]);
1850- let avail =
1851- |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0);
1852- let marked_c = gather_refs(&read, &avail, cx0, cy0, 8);
1853- let pred = intra_predict_with_substitution(&marked_c, &pred_params(mode, pc))
1854- .expect("legal prediction params");
1855- let src_c = match comp {
1856- Component::Cb => &src[1],
1857- _ => &src[2],
1858- };
1859- code_tb(src_c, &pred, 8, qp_c, comp, PredMode::Intra)
1860- };
1861- let (lcb, rcb) = code_c(&recon.cb, Component::Cb, PredComponent::Cb);
1862- let (lcr, rcr) = code_c(&recon.cr, Component::Cr, PredComponent::Cr);
1863- let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]);
1864- let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr) + 8;
1865- cands.push(CuCandidate {
1866- kind: CuKind::Intra { mode },
1867- motions: Vec::new(),
1868- levels: Some(CuLevels::Depth0([ly, lcb, lcr])),
1869- recon: [ry, rcb, rcr],
1870- cost: dist + lambda * rate,
1871- });
1872- }
1873-
1874- cands
1875- .into_iter()
1876- .min_by_key(|c| c.cost)
1877- .expect("at least the skip candidate")
1878- };
1879-
1880- // ---- state update (eqs 8-80..8-85 + mode fields + recon) ----
1881- let is_skip = matches!(chosen.kind, CuKind::Skip { .. });
1882- skip_grid[ctb] = is_skip;
1883- match &chosen.kind {
1884- CuKind::Intra { mode } => {
1885- stats.intra += 1;
1886- // The decoder stamps intra CUs into the motion field so
1887- // a later CU's §6.4.2 availability denies them.
1888- field.fill_rect(
1889- x0,
1890- y0,
1891- CTB,
1892- CTB,
1893- MotionCell {
1894- is_intra: true,
1895- ..MotionCell::default()
1896- },
1897- );
1898- modes.record_intra_pb(x0, y0, CTB, *mode, false);
1899- }
1900- kind => {
1901- match kind {
1902- CuKind::Skip { .. } => stats.skip += 1,
1903- CuKind::Merge { .. } => stats.merge += 1,
1904- CuKind::TwoPu { part, pus } => {
1905- if pus.iter().any(|p| matches!(p, PuSyntax::Amvp { .. })) {
1906- stats.amvp += 1;
1907- } else {
1908- stats.merge += 1;
1909- }
1910- if part_is_amp(*part) {
1911- stats.amp += 1;
1912- } else {
1913- stats.rect += 1;
1914- }
1915- }
1916- _ => stats.amvp += 1,
1917- }
1918- if chosen
1919- .motions
1920- .iter()
1921- .any(|m| m.pred_flag_l0 && m.pred_flag_l1)
1922- {
1923- stats.bi += 1;
1924- }
1925- if chosen.motions.iter().any(|m| {
1926- (m.pred_flag_l0 && m.ref_idx_l0 > 0) || (m.pred_flag_l1 && m.ref_idx_l1 > 0)
1927- }) {
1928- stats.ref1 += 1;
1929- }
1930- // eqs 8-80..8-85: one motion cell per PU rectangle, the
1931- // stored identity being the referenced picture's POC.
1932- let part = match kind {
1933- CuKind::TwoPu { part, .. } => *part,
1934- _ => PartMode::Part2Nx2N,
1935- };
1936- let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part);
1937- for (r, m) in rects.iter().zip(chosen.motions.iter()) {
1938- field.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, {
1939- let (p0, p1) = cell_pocs(m);
1940- m.to_cell(p0, p1)
1941- });
1942- }
1943- let cu_mode = if is_skip {
1944- CuPredMode::Skip
1945- } else {
1946- CuPredMode::Inter
1947- };
1948- modes.record_non_intra_cu(x0, y0, CTB, cu_mode);
1949- // §8.7.2.4 — mark each luma TRANSFORM BLOCK carrying a
1950- // coded coefficient (the decoder marks per tree leaf,
1951- // not per CU; intra CUs are never marked — their edges
1952- // are bS 2 regardless).
1953- match &chosen.levels {
1954- Some(CuLevels::Depth0(l)) if l[0].iter().any(|&v| v != 0) => {
1955- field.mark_nonzero_coeff(x0, y0, CTB, CTB);
1956- }
1957- Some(CuLevels::Depth1(d)) => {
1958- for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
1959- if d.luma[k].iter().any(|&v| v != 0) {
1960- field.mark_nonzero_coeff(x0 + zx * 8, y0 + zy * 8, 8, 8);
1961- }
1962- }
1963- }
1964- _ => {}
1965- }
1966- }
1967- }
1968- store(&mut recon.y, width, x0, y0, CTB, &chosen.recon[0]);
1969- store(&mut recon.cb, cw, cx0, cy0, 8, &chosen.recon[1]);
1970- store(&mut recon.cr, cw, cx0, cy0, 8, &chosen.recon[2]);
1971- plans.push(chosen);
1972- }
1973-
1974- // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ----
1975- let mut lf_sig = SliceLfSignalling {
1976- cfg: lf,
1977- deblock_on: false,
1978- beta_offset_div2: 0,
1979- tc_offset_div2: 0,
1980- sao_luma: false,
1981- sao_chroma: false,
1982- };
1983- let mut sao_ctbs: Vec<crate::slice_data::SaoCtbParams> = Vec::new();
1984- if lf.any() {
1985- let shapes: Vec<CtbShape> = plans
1986- .iter()
1987- .map(|c| CtbShape {
1988- part_mode: match &c.kind {
1989- CuKind::TwoPu { part, .. } => bin_part_mode(*part),
1990- _ => crate::binarization::PartMode::Part2Nx2N,
1991- },
1992- split_depth1: matches!(c.levels, Some(CuLevels::Depth1(_))),
1993- })
1994- .collect();
1995- let out = filter_frame(
1996- &FilterInput {
1997- width,
1998- height,
1999- qp,
2000- lambda,
vendor/oxideav-h265/src/encoder/intra.rsdeleted+0 -1559
@@ -1,1559 +0,0 @@
1-//! Real CABAC intra encoder — I-slice IDR access units with §8.4
2-//! intra prediction, forward transform + quantization, and full
3-//! §7.3.8 CABAC syntax emission (no PCM).
4-//!
5-//! Geometry (this bootstrap's fixed shape, mirroring the PCM
6-//! encoder): `CtbSizeY == MinCbSizeY == 16`, so every CTB is one
7-//! unsplit intra CU. Two partition modes compete per CU
8-//! (rate-distortion heuristic):
9-//!
10-//! * `PART_2Nx2N` — one 16x16 luma PB/TB + two 8x8 chroma TBs;
11-//! * `PART_NxN` — four 8x8 luma PBs, each its own mode; the §7.4.9.8
12-//! `IntraSplitFlag` forces the transform tree to depth 1 (four
13-//! 8x8 luma TBs + four 4x4 chroma TBs per plane), the 8x8 luma and
14-//! 4x4 chroma TBs picking their §7.4.9.11 mode-dependent scans.
15-//!
16-//! Per CTU the encoder:
17-//!
18-//! 1. gathers the §8.4.4.2.1 reference samples from its own
19-//! reconstruction buffer, marking availability per the §6.4.1
20-//! z-scan decode order (CTB raster + TU z-order within the CTB),
21-//! and runs the decode-side [`crate::intra_pred`] pipeline
22-//! (§8.4.4.2.2 substitution + §8.4.4.2.3 filtering + planar / DC /
23-//! angular prediction) for every candidate mode, picking the
24-//! SAD-best per PB;
25-//! 2. forward-transforms the prediction residual (the transpose of
26-//! the §8.6.4.2 DCT-II basis) and quantizes against the §8.6.3
27-//! `levelScale`-derived reciprocal at the slice QP (chroma via the
28-//! Table 8-10 QP mapping);
29-//! 3. reconstructs through the crate's own DECODE-side §8.6.2
30-//! scaling/transform ([`crate::transform::residual_block`]) so the
31-//! encoder's reference buffer is bit-identical to what a
32-//! conforming decoder reconstructs, and picks the partition with
33-//! the smaller SSD + partition-cost heuristic;
34-//! 4. emits the §7.3.8.5 coding-unit syntax (`part_mode`, the
35-//! §7.3.8.5 two-loop `prev_intra_luma_pred_flag[]` then
36-//! `mpm_idx` / `rem_intra_luma_pred_mode` group against the
37-//! §8.4.2 candidate lists, `intra_chroma_pred_mode` =
38-//! derived-from-luma), the §7.3.8.8 transform tree with its cbf
39-//! inheritance, and the §7.3.8.11 residual blocks through
40-//! [`crate::encoder::residual::encode_residual_coding`].
41-//!
42-//! In-loop filters are off (SAO off in the SPS, deblocking disabled
43-//! in the PPS), so a conforming decoder's output equals the encoder's
44-//! reconstruction exactly — pinned by the roundtrip tests.
45-
46-use crate::binarization::intra_luma_cand_mode_list;
47-use crate::binarization::PartMode;
48-use crate::binarization::{cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc};
49-use crate::cabac::init_type;
50-use crate::ctx_init::SliceContexts;
51-use crate::encoder::bitwriter::BitWriter;
52-use crate::encoder::cabac::CabacEncoder;
53-use crate::encoder::loopfilter::{
54- encode_sao_ctb, filter_frame, CtbShape, FilterInput, LoopFilterCfg,
55-};
56-use crate::encoder::nal::{annexb, nal_unit};
57-// --- edith patch: the SPS's colour signalling reuses the parser's types ---
58-use crate::vui::VideoSignalType;
59-use crate::encoder::pcm::{level_idc_for, write_pps_lf, write_ptl, write_vps, write_vps_cfg};
60-use crate::encoder::residual::encode_residual_coding;
61-use crate::intra_mode_field::{IntraModeField, Neighbour};
62-use crate::intra_pred::{
63- intra_predict_with_substitution, Component as PredComponent, IntraPredParams,
64- MarkedReferenceSamples,
65-};
66-use crate::motion::MotionField;
67-use crate::residual::{residual_coding_scan_idx, ResidualCodingParams};
68-use crate::slice_data::SaoCtbParams;
69-use crate::transform::{forward_dct_1d, residual_block, BlockParams, Component, PredMode};
70-
71-/// The fixed CTB / coding-block log2 size (16x16).
72-const CTB_LOG2: u32 = 4;
73-/// The fixed CTB size.
74-const CTB: usize = 1 << CTB_LOG2;
75-/// Fixed 8-bit depth.
76-const BIT_DEPTH: u32 = 8;
77-/// The z-order offsets of the four NxN prediction blocks / depth-1
78-/// transform units within a CTB (§6.5.2 z-scan of the four halves).
79-const Z_OFFSETS: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
80-
81-/// Errors from the intra encoder.
82-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
83-pub enum IntraEncodeError {
84- /// Width or height is zero or not a multiple of the 16-sample CTB.
85- BadDimensions {
86- /// Requested luma width.
87- width: usize,
88- /// Requested luma height.
89- height: usize,
90- },
91- /// A supplied plane's length does not match the 4:2:0 geometry.
92- PlaneSize {
93- /// Which plane (`"y"`, `"cb"`, `"cr"`).
94- plane: &'static str,
95- /// Required sample count.
96- expected: usize,
97- /// Supplied sample count.
98- got: usize,
99- },
100- /// `SliceQpY` outside 0..=51.
101- BadQp(i32),
102-}
103-
104-impl core::fmt::Display for IntraEncodeError {
105- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
106- match self {
107- Self::BadDimensions { width, height } => write!(
108- f,
109- "intra encoder requires nonzero dimensions that are multiples of 16, got {width}x{height}"
110- ),
111- Self::PlaneSize {
112- plane,
113- expected,
114- got,
115- } => write!(f, "{plane} plane has {got} samples, expected {expected}"),
116- Self::BadQp(qp) => write!(f, "slice QP {qp} outside 0..=51"),
117- }
118- }
119-}
120-
121-impl std::error::Error for IntraEncodeError {}
122-
123-/// The encoded access unit plus the encoder's own reconstruction
124-/// (what a conforming decoder outputs — in-loop filters are off).
125-#[derive(Debug, Clone)]
126-pub struct IntraEncodedAu {
127- /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP`).
128- pub au: Vec<u8>,
129- /// Reconstructed luma plane (`width * height`).
130- pub recon_y: Vec<u8>,
131- /// Reconstructed Cb plane (`width/2 * height/2`).
132- pub recon_cb: Vec<u8>,
133- /// Reconstructed Cr plane.
134- pub recon_cr: Vec<u8>,
135-}
136-
137-/// The stream-level geometry / buffering knobs of the shared SPS
138-/// (everything the intra, low-delay and hierarchical-B encoders vary
139-/// between them; the rest of the SPS is fixed 4:2:0 8-bit CTB-16).
140-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
141-pub(crate) struct SpsCfg {
142- /// `sps_max_dec_pic_buffering_minus1[0]`.
143- pub max_dec_pic_buffering_minus1: u32,
144- /// `sps_max_num_reorder_pics[0]` (nonzero for the out-of-order
145- /// hierarchical-B GOPs).
146- pub max_num_reorder_pics: u32,
147- /// `MinCbLog2SizeY` (4 for the legacy CTB == CU geometry; 3 for
148- /// the AMP-enabled geometry, where every CTB is an UNSPLIT 16x16
149- /// CU with `log2CbSize > MinCbLog2SizeY`).
150- pub min_cb_log2: u32,
151- /// `amp_enabled_flag` (requires `min_cb_log2 == 3` — Table 9-45
152- /// only reaches the AMP bin strings when `log2CbSize >
153- /// MinCbLog2SizeY`).
154- pub amp: bool,
155- // --- edith patch (see the crate-level note in vendor/) ---
156- /// `conf_win_right_offset` / `conf_win_bottom_offset`, in
157- /// **chroma** units (§7.4.3.2.1: the luma crop is these times
158- /// `SubWidthC`/`SubHeightC`, i.e. 2 at 4:2:0). `(0, 0)` writes
159- /// `conformance_window_flag = 0`, which is what upstream always
160- /// wrote.
161- pub conf_win: (u32, u32),
162- /// §E.2.1 `video_signal_type_present_flag` block, written into a
163- /// VUI of its own. `None` writes `vui_parameters_present_flag = 0`,
164- /// which is what upstream always wrote — and which makes a decoder
165- /// infer "unspecified" and render the picture BT.601 whatever the
166- /// container said.
167- pub signal: Option<VideoSignalType>,
168- // --- end edith patch ---
169-}
170-
171-impl SpsCfg {
172- /// The legacy fixed geometry: `MinCbSizeY == CtbSizeY == 16`, no
173- /// AMP, no output reordering.
174- pub(crate) fn legacy(max_dec_pic_buffering_minus1: u32) -> Self {
175- Self {
176- max_dec_pic_buffering_minus1,
177- max_num_reorder_pics: 0,
178- min_cb_log2: CTB_LOG2,
179- amp: false,
180- conf_win: (0, 0),
181- signal: None,
182- }
183- }
184-}
185-
186-/// §7.3.2.2 — the fixed-geometry SPS (4:2:0, 8-bit, CTB 16, PCM off,
187-/// SAO per `sao_enabled`) with the [`SpsCfg`] knob set (coding-block
188-/// geometry, `amp_enabled_flag`, DPB / reorder bounds). Shared by the
189-/// intra, low-delay and hierarchical-B encoders (nothing in it is
190-/// slice-type specific: the P / B slices code their §7.4.8 short-term
191-/// RPS inline and `sps_temporal_mvp_enabled_flag` is 0).
192-pub(crate) fn write_sps_cfg(
193- width: usize,
194- height: usize,
195- level_idc: u8,
196- cfg: &SpsCfg,
197- sao_enabled: bool,
198-) -> Vec<u8> {
199- debug_assert!(
200- !cfg.amp || cfg.min_cb_log2 < CTB_LOG2,
201- "AMP requires log2CbSize > MinCbLog2SizeY (Table 9-45)"
202- );
203- let mut w = BitWriter::new();
204- w.put_bits(0, 4); // sps_video_parameter_set_id
205- w.put_bits(0, 3); // sps_max_sub_layers_minus1
206- w.put_bit(1); // sps_temporal_id_nesting_flag
207- write_ptl(&mut w, level_idc);
208- w.ue(0); // sps_seq_parameter_set_id
209- w.ue(1); // chroma_format_idc = 4:2:0
210- w.ue(width as u32); // pic_width_in_luma_samples
211- w.ue(height as u32); // pic_height_in_luma_samples
212- // --- edith patch: conformance window (upstream always wrote 0) ---
213- match cfg.conf_win {
214- (0, 0) => w.put_bit(0), // conformance_window_flag
215- (right, bottom) => {
216- w.put_bit(1); // conformance_window_flag
217- w.ue(0); // conf_win_left_offset
218- w.ue(right); // conf_win_right_offset
219- w.ue(0); // conf_win_top_offset
220- w.ue(bottom); // conf_win_bottom_offset
221- }
222- }
223- // --- end edith patch ---
224- w.ue(0); // bit_depth_luma_minus8
225- w.ue(0); // bit_depth_chroma_minus8
226- w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
227- w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
228- w.ue(cfg.max_dec_pic_buffering_minus1); // sps_max_dec_pic_buffering_minus1[0]
229- w.ue(cfg.max_num_reorder_pics); // sps_max_num_reorder_pics[0]
230- w.ue(0); // sps_max_latency_increase_plus1[0]
231- w.ue(cfg.min_cb_log2 - 3); // log2_min_luma_coding_block_size_minus3
232- w.ue(CTB_LOG2 - cfg.min_cb_log2); // log2_diff_max_min_luma_coding_block_size (CTB 16)
233- w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
234- w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
235- w.ue(0); // max_transform_hierarchy_depth_inter
236- w.ue(0); // max_transform_hierarchy_depth_intra
237- w.put_bit(0); // scaling_list_enabled_flag
238- w.put_bit(u8::from(cfg.amp)); // amp_enabled_flag
239- w.put_bit(u8::from(sao_enabled)); // sample_adaptive_offset_enabled_flag
240- w.put_bit(0); // pcm_enabled_flag
241- w.ue(0); // num_short_term_ref_pic_sets
242- w.put_bit(0); // long_term_ref_pics_present_flag
243- w.put_bit(0); // sps_temporal_mvp_enabled_flag
244- w.put_bit(0); // strong_intra_smoothing_enabled_flag
245- // --- edith patch: §E.2.1 VUI, colour signalling only (upstream
246- // always wrote 0). Everything else in the VUI stays absent, which
247- // §E.3.1 infers to exactly the values upstream's silence did.
248- match cfg.signal {
249- None => w.put_bit(0), // vui_parameters_present_flag
250- Some(signal) => {
251- w.put_bit(1); // vui_parameters_present_flag
252- w.put_bit(0); // aspect_ratio_info_present_flag
253- w.put_bit(0); // overscan_info_present_flag
254- w.put_bit(1); // video_signal_type_present_flag
255- w.put_bits(u32::from(signal.video_format), 3);
256- w.put_bit(u8::from(signal.video_full_range_flag));
257- match signal.colour_description {
258- None => w.put_bit(0), // colour_description_present_flag
259- Some(colour) => {
260- w.put_bit(1); // colour_description_present_flag
261- w.put_bits(u32::from(colour.colour_primaries), 8);
262- w.put_bits(u32::from(colour.transfer_characteristics), 8);
263- w.put_bits(u32::from(colour.matrix_coeffs), 8);
264- }
265- }
266- w.put_bit(0); // chroma_loc_info_present_flag
267- w.put_bit(0); // neutral_chroma_indication_flag
268- w.put_bit(0); // field_seq_flag
269- w.put_bit(0); // frame_field_info_present_flag
270- w.put_bit(0); // default_display_window_flag
271- w.put_bit(0); // vui_timing_info_present_flag
272- w.put_bit(0); // bitstream_restriction_flag
273- }
274- }
275- // --- end edith patch ---
276- w.put_bit(0); // sps_extension_present_flag
277- w.rbsp_trailing_bits();
278- w.finish()
279-}
280-
281-/// Table 8-10 — the `ChromaArrayType == 1` chroma QP mapping
282-/// `qPC = f(qPi)` (§8.6.1; `QpBdOffsetC == 0` at 8-bit).
283-pub(crate) fn chroma_qp_420(qp_y: i32) -> u32 {
284- let qpi = qp_y.clamp(0, 57);
285- (match qpi {
286- x if x < 30 => x,
287- 30..=33 => qpi - 1, // 30..=33 -> 29, 30, 31, 32
288- 34..=43 => 33 + (qpi - 34) / 2, // 34..=43 -> 33, 33, 34, 34 .. 37, 37
289- x => x - 6,
290- }) as u32
291-}
292-
293-/// §8.6.3-derived reciprocal quantizer scale: `levelScale[qP % 6]` is
294-/// `{40, 45, 51, 57, 64, 72}`; the forward reciprocal is
295-/// `round(2^20 / levelScale)` so `quant ∘ dequant` has unity gain.
296-fn quant_scale(qp_rem: u32) -> i64 {
297- let ls = i64::from(crate::transform::LEVEL_SCALE[qp_rem as usize]);
298- ((1i64 << 20) + ls / 2) / ls
299-}
300-
301-/// Forward 2-D DCT-II (the transpose of the §8.6.4 inverse): stage 1
302-/// over rows with `shift1 = log2TbS + BitDepth − 9`, stage 2 over
303-/// columns with `shift2 = log2TbS + 6` — the normalization that makes
304-/// the §8.6.3 dequant + §8.6.4 inverse reproduce the residual.
305-fn forward_transform(res: &[i32], n: usize) -> Vec<i32> {
306- let log2 = n.trailing_zeros();
307- let shift1 = log2 + BIT_DEPTH - 9;
308- let shift2 = log2 + 6;
309- let r1 = 1i64 << (shift1 - 1);
310- let r2 = 1i64 << (shift2 - 1);
311- // Stage 1: horizontal analysis per row y -> a[y][u].
312- let mut a = vec![0i64; n * n];
313- for y in 0..n {
314- let row: Vec<i64> = (0..n).map(|x| i64::from(res[y * n + x])).collect();
315- let t = forward_dct_1d(&row, n);
316- for (u, &v) in t.iter().enumerate() {
317- a[y * n + u] = (v + r1) >> shift1;
318- }
319- }
320- // Stage 2: vertical analysis per column u -> coef[v][u].
321- let mut coef = vec![0i32; n * n];
322- for u in 0..n {
323- let col: Vec<i64> = (0..n).map(|y| a[y * n + u]).collect();
324- let t = forward_dct_1d(&col, n);
325- for (v, &val) in t.iter().enumerate() {
326- coef[v * n + u] = ((val + r2) >> shift2) as i32;
327- }
328- }
329- coef
330-}
331-
332-/// Scalar quantization to `TransCoeffLevel`: `level = sign ·
333-/// (|coef| · quantScale + offset) >> qBits` with `qBits = 14 + qP/6 +
334-/// (15 − BitDepth − log2TbS)` (the inverse of the §8.6.3 eq. 8-309
335-/// scaling chain) and a one-third rounding offset; clamped to the
336-/// §7.4.9.11 CoeffMax.
337-fn quantize(coef: &[i32], n: usize, qp: u32) -> Vec<i32> {
338- let log2 = n.trailing_zeros();
339- let qbits = 14 + qp / 6 + (15 - BIT_DEPTH - log2);
340- let scale = quant_scale(qp % 6);
341- let offset = (1i64 << qbits) / 3;
342- coef.iter()
343- .map(|&c| {
344- let level = ((i64::from(c.unsigned_abs()) * scale + offset) >> qbits).min(0x7FFF);
345- (level as i32) * c.signum()
346- })
347- .collect()
348-}
349-
350-/// §6.4.1-shaped z-scan availability of the sample at `(nx, ny)`
351-/// relative to the block being decoded: available iff inside the
352-/// plane AND its covering coding block precedes in decode order —
353-/// an earlier CTB (raster), or the same CTB with a smaller depth-1
354-/// z-order quadrant index (`cur_z`; pass 0 when the current TB is the
355-/// whole CTB, making every same-CTB neighbour unavailable).
356-#[allow(clippy::too_many_arguments)]
357-pub(crate) fn zscan_avail(
358- nx: i64,
359- ny: i64,
360- plane_w: usize,
361- plane_h: usize,
362- blk: usize,
363- ctbs_x: usize,
364- cur_ctb: usize,
365- cur_z: u32,
366-) -> bool {
367- if nx < 0 || ny < 0 || nx >= plane_w as i64 || ny >= plane_h as i64 {
368- return false;
369- }
370- let (nx, ny) = (nx as usize, ny as usize);
371- let nctb = (ny / blk) * ctbs_x + nx / blk;
372- match nctb.cmp(&cur_ctb) {
373- core::cmp::Ordering::Less => true,
374- core::cmp::Ordering::Greater => false,
375- core::cmp::Ordering::Equal => {
376- let half = blk / 2;
377- let z = ((ny % blk) / half) * 2 + ((nx % blk) / half);
378- (z as u32) < cur_z
379- }
380- }
381-}
382-
383-/// Gather the §8.4.4.2.1 marked reference array for an `n`-sample TB
384-/// at `(x0, y0)`: values through `read`, availability through `avail`.
385-pub(crate) fn gather_refs(
386- read: &dyn Fn(usize, usize) -> i32,
387- avail: &dyn Fn(i64, i64) -> bool,
388- x0: usize,
389- y0: usize,
390- n: usize,
391-) -> MarkedReferenceSamples {
392- let get = |x: i64, y: i64| -> (i32, bool) {
393- if avail(x, y) {
394- (read(x as usize, y as usize), true)
395- } else {
396- (0, false)
397- }
398- };
399- let corner = get(x0 as i64 - 1, y0 as i64 - 1);
400- let left: Vec<(i32, bool)> = (0..2 * n)
401- .map(|k| get(x0 as i64 - 1, (y0 + k) as i64))
402- .collect();
403- let top: Vec<(i32, bool)> = (0..2 * n)
404- .map(|k| get((x0 + k) as i64, y0 as i64 - 1))
405- .collect();
406- MarkedReferenceSamples::new(n, corner, left, top).expect("legal TB geometry")
407-}
408-
409-pub(crate) fn pred_params(mode: u8, cidx: PredComponent) -> IntraPredParams {
410- IntraPredParams {
411- pred_mode_intra: mode,
412- cidx,
413- bit_depth: BIT_DEPTH as u8,
414- bit_depth_luma: BIT_DEPTH as u8,
415- intra_smoothing_disabled: false,
416- strong_intra_smoothing_enabled: false,
417- chroma_array_type_3: false,
418- disable_boundary_filter: false,
419- }
420-}
421-
422-/// SAD-search all 35 §8.4.2 modes; returns `(mode, prediction)`.
423-pub(crate) fn search_best_mode(marked: &MarkedReferenceSamples, src: &[i32]) -> (u8, Vec<i32>) {
424- let mut best = (0u8, Vec::new());
425- let mut best_cost = u64::MAX;
426- for mode in 0..=34u8 {
427- let pred = intra_predict_with_substitution(marked, &pred_params(mode, PredComponent::Luma))
428- .expect("legal prediction params");
429- let cost: u64 = src
430- .iter()
431- .zip(pred.iter())
432- .map(|(&s, &p)| u64::from(s.abs_diff(p)))
433- .sum();
434- if cost < best_cost {
435- best_cost = cost;
436- best = (mode, pred);
437- }
438- }
439- best
440-}
441-
442-/// Transform + quantize one component TB and reconstruct it through
443-/// the DECODE-side §8.6.2 path. Returns `(levels, recon_samples)`;
444-/// `levels` all-zero ⇔ cbf 0 (recon = clipped prediction).
445-///
446-/// `pred_mode` selects the §8.6.4 transform family exactly as the
447-/// decoder does (the intra-luma 4x4 DST case; every TB the intra and
448-/// low-delay-P encoders emit at other geometries is DCT either way).
449-pub(crate) fn code_tb(
450- src: &[i32],
451- pred: &[i32],
452- n: usize,
453- qp: u32,
454- component: Component,
455- pred_mode: PredMode,
456-) -> (Vec<i32>, Vec<u8>) {
457- let res: Vec<i32> = src.iter().zip(pred.iter()).map(|(&s, &p)| s - p).collect();
458- let coef = forward_transform(&res, n);
459- let levels = quantize(&coef, n, qp);
460- let recon: Vec<u8> = if levels.iter().all(|&v| v == 0) {
461- pred.iter().map(|&p| p.clamp(0, 255) as u8).collect()
462- } else {
463- let r = residual_block(
464- &levels,
465- None,
466- BlockParams {
467- n_tbs: n,
468- q_p: qp,
469- component,
470- pred_mode,
471- bit_depth: BIT_DEPTH as u8,
472- extended_precision: false,
473- transquant_bypass: false,
474- transform_skip: false,
475- transform_skip_rotation_enabled: false,
476- },
477- )
478- .expect("legal block params");
479- pred.iter()
480- .zip(r.iter())
481- .map(|(&p, &d)| (p + d).clamp(0, 255) as u8)
482- .collect()
483- };
484- (levels, recon)
485-}
486-
487-pub(crate) fn ssd(a: &[u8], b: &[i32]) -> u64 {
488- a.iter()
489- .zip(b.iter())
490- .map(|(&x, &y)| {
491- let d = i64::from(x) - i64::from(y);
492- (d * d) as u64
493- })
494- .sum()
495-}
496-
497-/// Crude bit-cost proxy for one TB's quantized levels: each nonzero
498-/// coefficient costs roughly its magnitude's bit length (sig flag +
499-/// sign + level bins); a coded-but-empty TB is nearly free, a coded
500-/// TB pays a small last-sig overhead.
501-fn rate_proxy(levels: &[i32]) -> u64 {
502- let bits: u64 = levels
503- .iter()
504- .filter(|&&l| l != 0)
505- .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros()))
506- .sum();
507- if bits == 0 {
508- 1
509- } else {
510- bits + 8
511- }
512-}
513-
514-/// One coded luma partition candidate for a CTB.
515-struct LumaPlan {
516- /// `PART_NxN`?
517- nxn: bool,
518- /// PB modes (1 used for 2Nx2N, 4 for NxN, z-order).
519- modes: [u8; 4],
520- /// TB level arrays (1 x 16x16 or 4 x 8x8, z-order).
521- levels: Vec<Vec<i32>>,
522- /// The CTB's 16x16 luma reconstruction, row-major.
523- recon: Vec<u8>,
524-}
525-
526-/// One CTB's pass-1 coding decisions (pass 2 emits the syntax after
527-/// the in-loop filter elections are known).
528-struct CtbPlan {
529- /// The elected luma partition + levels.
530- plan: LumaPlan,
531- /// Chroma Cb TB levels (1 x 8x8 or 4 x 4x4, z-order).
532- cb_levels: Vec<Vec<i32>>,
533- /// Chroma Cr TB levels.
534- cr_levels: Vec<Vec<i32>>,
535-}
536-
537-/// Encode one 4:2:0 8-bit frame as a self-contained intra IDR access
538-/// unit at `SliceQpY == qp` and return it with the reconstruction a
539-/// conforming decoder produces.
540-///
541-/// # Errors
542-/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP.
543-#[allow(clippy::too_many_lines)]
544-pub fn encode_idr_intra_au(
545- y: &[u8],
546- cb: &[u8],
547- cr: &[u8],
548- width: usize,
549- height: usize,
550- qp: i32,
551-) -> Result<IntraEncodedAu, IntraEncodeError> {
552- // A standalone intra AU needs one reference slot beyond the
553- // current picture (`sps_max_dec_pic_buffering_minus1 == 1`).
554- encode_idr_intra_au_cfg(y, cb, cr, width, height, qp, 1)
555-}
556-
557-// --- edith patch ---
558-/// [`encode_idr_intra_au`] for a picture whose display size is not a
559-/// multiple of the 16-sample CTB: the planes handed over are the
560-/// **padded** ones (`width`/`height`, both multiples of 16) and the SPS
561-/// carries a §7.4.3.2.1 conformance window cropping `crop_right` /
562-/// `crop_bottom` **luma** samples off, so a decoder outputs the display
563-/// size. Both crops must be even (4:2:0 addresses the window in chroma
564-/// units) and smaller than 16.
565-///
566-/// `signal` is the §E.2.1 colour signalling the SPS carries: a decoder
567-/// reads the bitstream before it reads the container, so `None` renders
568-/// as "unspecified" — BT.601 in libavcodec — however the file is tagged.
569-///
570-/// # Errors
571-/// [`IntraEncodeError`] as [`encode_idr_intra_au`], plus
572-/// [`IntraEncodeError::BadDimensions`] for an odd or oversized crop.
573-pub fn encode_idr_intra_au_cropped(
574- y: &[u8],
575- cb: &[u8],
576- cr: &[u8],
577- width: usize,
578- height: usize,
579- qp: i32,
580- crop_right: usize,
581- crop_bottom: usize,
582- signal: Option<VideoSignalType>,
583-) -> Result<IntraEncodedAu, IntraEncodeError> {
584- if crop_right % 2 != 0 || crop_bottom % 2 != 0 || crop_right >= CTB || crop_bottom >= CTB {
585- return Err(IntraEncodeError::BadDimensions {
586- width: width - crop_right,
587- height: height - crop_bottom,
588- });
589- }
590- let mut cfg = SpsCfg::legacy(1);
591- cfg.conf_win = ((crop_right / 2) as u32, (crop_bottom / 2) as u32);
592- cfg.signal = signal;
593- encode_idr_intra_au_full(y, cb, cr, width, height, qp, &cfg, &LoopFilterCfg::off())
594-}
595-// --- end edith patch ---
596-
597-/// [`encode_idr_intra_au`] with the §8.7 in-loop filters enabled per
598-/// `lf`: the reconstruction runs through the crate's decode-side
599-/// deblocking (per-slice on/off elected against distortion) and SAO
600-/// (per-CTB §7.3.8.3 parameters from statistics-driven offset
601-/// estimation), and the returned `recon_*` planes are the *filtered*
602-/// picture — still exactly what a conforming decoder outputs.
603-///
604-/// # Errors
605-/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP.
606-pub fn encode_idr_intra_au_lf(
607- y: &[u8],
608- cb: &[u8],
609- cr: &[u8],
610- width: usize,
611- height: usize,
612- qp: i32,
613- lf: &LoopFilterCfg,
614-) -> Result<IntraEncodedAu, IntraEncodeError> {
615- encode_idr_intra_au_full(y, cb, cr, width, height, qp, &SpsCfg::legacy(1), lf)
616-}
617-
618-/// [`encode_idr_intra_au`] with an explicit
619-/// `sps_max_dec_pic_buffering_minus1` — the low-delay GOP encoder
620-/// passes 2 so a conforming decoder keeps BOTH short-term references
621-/// alive alongside the current picture.
622-pub(crate) fn encode_idr_intra_au_cfg(
623- y: &[u8],
624- cb: &[u8],
625- cr: &[u8],
626- width: usize,
627- height: usize,
628- qp: i32,
629- max_dec_pic_buffering_minus1: u32,
630-) -> Result<IntraEncodedAu, IntraEncodeError> {
631- encode_idr_intra_au_full(
632- y,
633- cb,
634- cr,
635- width,
636- height,
637- qp,
638- &SpsCfg::legacy(max_dec_pic_buffering_minus1),
639- &LoopFilterCfg::off(),
640- )
641-}
642-
643-/// The full-configuration intra encode: two passes (per-CTB mode
644-/// decision + reconstruction, then syntax emission) around the §8.7
645-/// in-loop filter stage, so the per-CTB §7.3.8.3 SAO parameters and
646-/// the slice-header filter elections are known before the slice is
647-/// written.
648-#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
649-pub(crate) fn encode_idr_intra_au_full(
650- y: &[u8],
651- cb: &[u8],
652- cr: &[u8],
653- width: usize,
654- height: usize,
655- qp: i32,
656- cfg: &SpsCfg,
657- lf: &LoopFilterCfg,
658-) -> Result<IntraEncodedAu, IntraEncodeError> {
659- if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 {
660- return Err(IntraEncodeError::BadDimensions { width, height });
661- }
662- if !(0..=51).contains(&qp) {
663- return Err(IntraEncodeError::BadQp(qp));
664- }
665- let check = |plane: &'static str, buf: &[u8], expected: usize| {
666- if buf.len() != expected {
667- Err(IntraEncodeError::PlaneSize {
668- plane,
669- expected,
670- got: buf.len(),
671- })
672- } else {
673- Ok(())
674- }
675- };
676- check("y", y, width * height)?;
677- check("cb", cb, width * height / 4)?;
678- check("cr", cr, width * height / 4)?;
679-
680- let (cw, ch) = (width / 2, height / 2);
681- let ctbs_x = width / CTB;
682- let ctbs_y = height / CTB;
683- let qp_y = qp as u32;
684- let qp_c = chroma_qp_420(qp);
685- // Rate-distortion tradeoff for the partition decision: SSD per
686- // estimated bit, doubling every 3 QP (integer, deterministic).
687- let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3);
688-
689- let mut recon_y = vec![0u8; width * height];
690- let mut recon_cb = vec![0u8; cw * ch];
691- let mut recon_cr = vec![0u8; cw * ch];
692- let mut modes = IntraModeField::new(width, height, CTB_LOG2);
693- let mut plans: Vec<CtbPlan> = Vec::with_capacity(ctbs_x * ctbs_y);
694-
695- let extract = |plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize| -> Vec<i32> {
696- let mut out = Vec::with_capacity(n * n);
697- for j in 0..n {
698- for i in 0..n {
699- out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
700- }
701- }
702- out
703- };
704- let store = |plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]| {
705- for j in 0..n {
706- plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n]
707- .copy_from_slice(&s[j * n..(j + 1) * n]);
708- }
709- };
710-
711- for ctb in 0..ctbs_x * ctbs_y {
712- let x0 = (ctb % ctbs_x) * CTB;
713- let y0 = (ctb / ctbs_x) * CTB;
714- let src16 = extract(y, width, x0, y0, CTB);
715-
716- // ---- candidate PART_2Nx2N: one 16x16 PB/TB ----
717- let plan_2n = {
718- let read = |x: usize, yy: usize| i32::from(recon_y[yy * width + x]);
719- let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
720- let marked = gather_refs(&read, &avail, x0, y0, CTB);
721- let (mode, pred) = search_best_mode(&marked, &src16);
722- let (levels, recon) =
723- code_tb(&src16, &pred, CTB, qp_y, Component::Luma, PredMode::Intra);
724- LumaPlan {
725- nxn: false,
726- modes: [mode; 4],
727- levels: vec![levels],
728- recon,
729- }
730- };
731-
732- // ---- candidate PART_NxN: four 8x8 PBs/TBs, z-order ----
733- // Only at the legacy MinCb geometry: at `log2CbSize >
734- // MinCbLog2SizeY` an intra CU's `part_mode` is not present
735- // (§7.3.8.5), so PART_NxN cannot be signalled.
736- let plan_nxn = if cfg.min_cb_log2 < CTB_LOG2 {
737- None
738- } else {
739- let mut scratch = vec![0u8; CTB * CTB]; // in-progress CTB recon
740- let mut pb_modes = [0u8; 4];
741- let mut pb_levels: Vec<Vec<i32>> = Vec::with_capacity(4);
742- for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
743- let (px, py) = (x0 + zx * 8, y0 + zy * 8);
744- let read = |x: usize, yy: usize| -> i32 {
745- if (x0..x0 + CTB).contains(&x) && (y0..y0 + CTB).contains(&yy) {
746- i32::from(scratch[(yy - y0) * CTB + (x - x0)])
747- } else {
748- i32::from(recon_y[yy * width + x])
749- }
750- };
751- let avail = |nx: i64, ny: i64| {
752- zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, k as u32)
753- };
754- let marked = gather_refs(&read, &avail, px, py, 8);
755- let src8 = extract(y, width, px, py, 8);
756- let (mode, pred) = search_best_mode(&marked, &src8);
757- let (levels, recon8) =
758- code_tb(&src8, &pred, 8, qp_y, Component::Luma, PredMode::Intra);
759- for j in 0..8 {
760- scratch[(zy * 8 + j) * CTB + zx * 8..(zy * 8 + j) * CTB + zx * 8 + 8]
761- .copy_from_slice(&recon8[j * 8..(j + 1) * 8]);
762- }
763- pb_modes[k] = mode;
764- pb_levels.push(levels);
765- }
766- Some(LumaPlan {
767- nxn: true,
768- modes: pb_modes,
769- levels: pb_levels,
770- recon: scratch,
771- })
772- };
773-
774- // Luma-only rate-distortion comparison: SSD of the coded
775- // reconstruction + lambda times a bit proxy (residual levels +
776- // mode signalling: ~6 bits per PB).
777- let cost = |plan: &LumaPlan| -> u64 {
778- let rate: u64 = plan.levels.iter().map(|lv| rate_proxy(lv)).sum::<u64>()
779- + plan.levels.len() as u64 * 6;
780- ssd(&plan.recon, &src16) + lambda * rate
781- };
782- let plan = match plan_nxn {
783- Some(nxn) if cost(&nxn) < cost(&plan_2n) => nxn,
784- _ => plan_2n,
785- };
786- store(&mut recon_y, width, x0, y0, CTB, &plan.recon);
787- // §8.4.3: IntraPredModeC derives from the CU's first PB.
788- let mode_c = plan.modes[0];
789-
790- // ---- chroma: 8x8 TBs (2Nx2N) or four 4x4 TBs (NxN) ----
791- let (cx0, cy0) = (x0 / 2, y0 / 2);
792- let code_chroma = |plane: &[u8],
793- recon: &mut Vec<u8>,
794- comp: Component,
795- pc: PredComponent|
796- -> Vec<Vec<i32>> {
797- if !plan.nxn {
798- let read = |x: usize, yy: usize| i32::from(recon[yy * cw + x]);
799- let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0);
800- let marked = gather_refs(&read, &avail, cx0, cy0, 8);
801- let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc))
802- .expect("legal prediction params");
803- let src = extract(plane, cw, cx0, cy0, 8);
804- let (levels, rec) = code_tb(&src, &pred, 8, qp_c, comp, PredMode::Intra);
805- store(recon, cw, cx0, cy0, 8, &rec);
806- vec![levels]
807- } else {
808- let mut out = Vec::with_capacity(4);
809- let mut scratch = vec![0u8; 64]; // 8x8 chroma CTB recon
810- for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
811- let (px, py) = (cx0 + zx * 4, cy0 + zy * 4);
812- let read = |x: usize, yy: usize| -> i32 {
813- if (cx0..cx0 + 8).contains(&x) && (cy0..cy0 + 8).contains(&yy) {
814- i32::from(scratch[(yy - cy0) * 8 + (x - cx0)])
815- } else {
816- i32::from(recon[yy * cw + x])
817- }
818- };
819- let avail = |nx: i64, ny: i64| {
820- zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, k as u32)
821- };
822- let marked = gather_refs(&read, &avail, px, py, 4);
823- let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc))
824- .expect("legal prediction params");
825- let src = extract(plane, cw, px, py, 4);
826- let (levels, rec) = code_tb(&src, &pred, 4, qp_c, comp, PredMode::Intra);
827- for j in 0..4 {
828- scratch[(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4]
829- .copy_from_slice(&rec[j * 4..(j + 1) * 4]);
830- }
831- out.push(levels);
832- }
833- store(recon, cw, cx0, cy0, 8, &scratch);
834- out
835- }
836- };
837- let cb_levels = code_chroma(cb, &mut recon_cb, Component::Cb, PredComponent::Cb);
838- let cr_levels = code_chroma(cr, &mut recon_cr, Component::Cr, PredComponent::Cr);
839-
840- plans.push(CtbPlan {
841- plan,
842- cb_levels,
843- cr_levels,
844- });
845- }
846-
847- // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ----
848- let mut deblock_on = false;
849- let mut beta_offset_div2 = 0i32;
850- let mut tc_offset_div2 = 0i32;
851- let mut slice_sao_luma = false;
852- let mut slice_sao_chroma = false;
853- let mut sao_ctbs: Vec<SaoCtbParams> = Vec::new();
854- if lf.any() {
855- let shapes: Vec<CtbShape> = plans
856- .iter()
857- .map(|p| CtbShape {
858- part_mode: if p.plan.nxn {
859- PartMode::PartNxN
860- } else {
861- PartMode::Part2Nx2N
862- },
863- split_depth1: p.plan.nxn,
864- })
865- .collect();
866- // Every CU is intra: the fresh motion field's all-intra
867- // background is exactly the decoder's state (bS == 2 at every
868- // filtered edge).
869- let field = MotionField::new(width, height);
870- let out = filter_frame(
871- &FilterInput {
872- width,
873- height,
874- qp,
875- lambda,
876- recon: [&recon_y, &recon_cb, &recon_cr],
877- src: [y, cb, cr],
878- field: &field,
879- shapes: &shapes,
880- },
881- lf,
882- );
883- deblock_on = out.deblock_on;
884- beta_offset_div2 = out.beta_offset_div2;
885- tc_offset_div2 = out.tc_offset_div2;
886- slice_sao_luma = out.slice_sao_luma;
887- slice_sao_chroma = out.slice_sao_chroma;
888- sao_ctbs = out.sao_ctbs;
889- recon_y = out.y;
890- recon_cb = out.cb;
891- recon_cr = out.cr;
892- }
893-
894- // ---- slice_segment_header( ) ----
895- let mut w = BitWriter::new();
896- w.put_bit(1); // first_slice_segment_in_pic_flag
897- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
898- w.ue(0); // slice_pic_parameter_set_id
899- w.ue(2); // slice_type = I
900- if lf.sao() {
901- // SPS SAO enabled: the per-slice component gates are present.
902- w.put_bit(u8::from(slice_sao_luma)); // slice_sao_luma_flag
903- w.put_bit(u8::from(slice_sao_chroma)); // slice_sao_chroma_flag
904- }
905- w.se(qp - 26); // slice_qp_delta (init_qp_minus26 == 0)
906- if lf.deblocking {
907- // §7.3.6.1 deblocking override group (the PPS signals
908- // override-enabled + deblocking disabled; an electing slice
909- // overrides to enabled with zero β/tC offsets).
910- w.put_bit(u8::from(deblock_on)); // deblocking_filter_override_flag
911- if deblock_on {
912- w.put_bit(0); // slice_deblocking_filter_disabled_flag
913- w.se(beta_offset_div2); // slice_beta_offset_div2
914- w.se(tc_offset_div2); // slice_tc_offset_div2
915- }
916- }
917- if slice_sao_luma || slice_sao_chroma || deblock_on {
918- // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and
919- // some in-loop filter is active for this slice.
920- w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag
921- }
922- w.rbsp_trailing_bits(); // byte_alignment()
923-
924- // ---- slice_segment_data( ) — pass 2: syntax emission ----
925- let mut cabac = CabacEncoder::new();
926- // Table 9-4: I slice => initType 0 (raw slice_type 2).
927- let mut ctxs = SliceContexts::init(init_type(2, false), qp);
928- for (ctb, ctb_plan) in plans.iter().enumerate() {
929- let x0 = (ctb % ctbs_x) * CTB;
930- let y0 = (ctb / ctbs_x) * CTB;
931- if slice_sao_luma || slice_sao_chroma {
932- // §7.3.8.3 sao( rx, ry ) ahead of the coding quadtree.
933- encode_sao_ctb(
934- &mut w,
935- &mut cabac,
936- &mut ctxs,
937- &sao_ctbs[ctb],
938- ctb % ctbs_x,
939- ctb / ctbs_x,
940- slice_sao_luma,
941- slice_sao_chroma,
942- );
943- }
944- let plan = &ctb_plan.plan;
945- let cb_levels = &ctb_plan.cb_levels;
946- let cr_levels = &ctb_plan.cr_levels;
947- // §8.4.3: IntraPredModeC derives from the CU's first PB.
948- let mode_c = plan.modes[0];
949-
950- // ---- §7.3.8.5 coding_unit( ) syntax ----
951- if cfg.min_cb_log2 < CTB_LOG2 {
952- // §7.3.8.4: log2CbSize (4) > MinCbLog2SizeY — split_cu_flag
953- // is coded, and every CTB stays one UNSPLIT 16x16 CU. All
954- // CtDepth values are 0, so both §9.3.4.2.2 conds are 0 and
955- // the ctxInc is 0. part_mode is then NOT present for an
956- // intra CU at log2CbSize > MinCbLog2SizeY (§7.3.8.5;
957- // inferred PART_2Nx2N).
958- cabac.encode_decision(&mut w, &mut ctxs.split_cu_flag[0], 0);
959- debug_assert!(!plan.nxn, "PART_NxN cannot be signalled above MinCb");
960- } else {
961- // part_mode: §9.3.3.7 intra at MinCb — "1" = PART_2Nx2N,
962- // "0" = PART_NxN.
963- cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], u8::from(!plan.nxn));
964- }
965- // §7.3.8.5 two-loop luma mode group: all
966- // prev_intra_luma_pred_flag bins first, then the mpm_idx /
967- // rem_intra_luma_pred_mode group. The §8.4.2 candidate list of
968- // PB k sees the recorded modes of PBs < k, so record as we go
969- // through the SECOND loop (derivation order).
970- let n_pb = if plan.nxn { 4 } else { 1 };
971- let pb_size = if plan.nxn { 8 } else { CTB };
972- let pb_pos = |k: usize| (x0 + Z_OFFSETS[k].0 * 8, y0 + Z_OFFSETS[k].1 * 8);
973- let mut selections: Vec<Option<usize>> = Vec::with_capacity(n_pb);
974- {
975- // The candidate list depends only on ALREADY-decoded PBs,
976- // which are identical in both loop passes; precompute the
977- // per-PB MPM position by simulating the record order.
978- for k in 0..n_pb {
979- let (px, py) = pb_pos(k);
980- let avail_l = zscan_avail(
981- px as i64 - 1,
982- py as i64,
983- width,
984- height,
985- CTB,
986- ctbs_x,
987- ctb,
988- k as u32,
989- );
990- let avail_a = zscan_avail(
991- px as i64,
992- py as i64 - 1,
993- width,
994- height,
995- CTB,
996- ctbs_x,
997- ctb,
998- k as u32,
999- );
1000- let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l);
1001- let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a);
1002- let list = intra_luma_cand_mode_list(cand_a, cand_b);
1003- selections.push(list.iter().position(|&m| m == plan.modes[k]));
1004- // Loop 1: prev_intra_luma_pred_flag[k].
1005- cabac.encode_decision(
1006- &mut w,
1007- &mut ctxs.prev_intra_luma_pred_flag[0],
1008- u8::from(selections[k].is_some()),
1009- );
1010- // Record now: the next PB's candidates must see this
1011- // one (§8.4.2 derivation order).
1012- modes.record_intra_pb(px, py, pb_size, plan.modes[k], false);
1013- }
1014- // Loop 2: mpm_idx / rem_intra_luma_pred_mode.
1015- for (k, sel) in selections.iter().enumerate() {
1016- match *sel {
1017- Some(0) => cabac.encode_bypass(&mut w, 0),
1018- Some(1) => {
1019- cabac.encode_bypass(&mut w, 1);
1020- cabac.encode_bypass(&mut w, 0);
1021- }
1022- Some(_) => {
1023- cabac.encode_bypass(&mut w, 1);
1024- cabac.encode_bypass(&mut w, 1);
1025- }
1026- None => {
1027- // §8.4.2: rem = mode with each smaller
1028- // candidate removed. Recompute the list the
1029- // same way the decoder will (earlier PBs
1030- // recorded).
1031- let (px, py) = pb_pos(k);
1032- let avail_l = zscan_avail(
1033- px as i64 - 1,
1034- py as i64,
1035- width,
1036- height,
1037- CTB,
1038- ctbs_x,
1039- ctb,
1040- k as u32,
1041- );
1042- let avail_a = zscan_avail(
1043- px as i64,
1044- py as i64 - 1,
1045- width,
1046- height,
1047- CTB,
1048- ctbs_x,
1049- ctb,
1050- k as u32,
1051- );
1052- let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l);
1053- let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a);
1054- let list = intra_luma_cand_mode_list(cand_a, cand_b);
1055- let mut rem = u32::from(plan.modes[k]);
1056- for &c in &list {
1057- if u32::from(plan.modes[k]) > u32::from(c) {
1058- rem -= 1;
1059- }
1060- }
1061- cabac.encode_bypass_bits(&mut w, rem, 5); // FL cMax 31
1062- }
1063- }
1064- }
1065- }
1066- // intra_chroma_pred_mode = 4 (derived from luma): bin "0".
1067- cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0);
1068-
1069- // ---- §7.3.8.8 transform_tree + §7.3.8.10 transform_unit ----
1070- let rc_params = |log2: u32, is_chroma: bool, mode: u8| ResidualCodingParams {
1071- log2_trafo_size: log2,
1072- is_chroma,
1073- // §7.4.9.11 mode-dependent scan (only 4x4 / 8x8-luma TBs
1074- // are eligible; larger TBs come back Diagonal).
1075- scan_idx: residual_coding_scan_idx(true, log2, u8::from(is_chroma), 1, u32::from(mode)),
1076- sign_data_hiding_enabled_flag: false,
1077- sign_hidden_suppressed: false,
1078- transform_skip_sig_ctx: false,
1079- persistent_rice_adaptation_enabled_flag: false,
1080- cabac_bypass_alignment_enabled_flag: false,
1081- extended_precision_processing_flag: false,
1082- bit_depth: 8,
1083- rice_stat_transform_skip: false,
1084- };
1085- if !plan.nxn {
1086- // Single 16x16 TU at depth 0.
1087- let cbf_cb = cb_levels[0].iter().any(|&v| v != 0);
1088- let cbf_cr = cr_levels[0].iter().any(|&v| v != 0);
1089- let cbf_luma = plan.levels[0].iter().any(|&v| v != 0);
1090- cabac.encode_decision(
1091- &mut w,
1092- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
1093- u8::from(cbf_cb),
1094- );
1095- cabac.encode_decision(
1096- &mut w,
1097- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
1098- u8::from(cbf_cr),
1099- );
1100- cabac.encode_decision(
1101- &mut w,
1102- &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize],
1103- u8::from(cbf_luma),
1104- );
1105- if cbf_luma {
1106- encode_residual_coding(
1107- &mut w,
1108- &mut cabac,
1109- &mut ctxs.residual,
1110- &rc_params(4, false, plan.modes[0]),
1111- &plan.levels[0],
1112- )
1113- .expect("validated luma levels");
1114- }
1115- if cbf_cb {
1116- encode_residual_coding(
1117- &mut w,
1118- &mut cabac,
1119- &mut ctxs.residual,
1120- &rc_params(3, true, mode_c),
1121- &cb_levels[0],
1122- )
1123- .expect("validated cb levels");
1124- }
1125- if cbf_cr {
1126- encode_residual_coding(
1127- &mut w,
1128- &mut cabac,
1129- &mut ctxs.residual,
1130- &rc_params(3, true, mode_c),
1131- &cr_levels[0],
1132- )
1133- .expect("validated cr levels");
1134- }
1135- } else {
1136- // IntraSplitFlag == 1: split_transform_flag inferred 1 at
1137- // depth 0 (§7.4.9.8); four 8x8 leaves at depth 1. Root
1138- // cbf_cb / cbf_cr gate the per-leaf chroma flags
1139- // (§7.3.8.8 inheritance).
1140- let leaf_cbf = |lv: &Vec<i32>| lv.iter().any(|&v| v != 0);
1141- let root_cb = cb_levels.iter().any(&leaf_cbf);
1142- let root_cr = cr_levels.iter().any(&leaf_cbf);
1143- cabac.encode_decision(
1144- &mut w,
1145- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
1146- u8::from(root_cb),
1147- );
1148- cabac.encode_decision(
1149- &mut w,
1150- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
1151- u8::from(root_cr),
1152- );
1153- for k in 0..4 {
1154- let cbf_cb_k = leaf_cbf(&cb_levels[k]);
1155- let cbf_cr_k = leaf_cbf(&cr_levels[k]);
1156- let cbf_luma_k = leaf_cbf(&plan.levels[k]);
1157- if root_cb {
1158- cabac.encode_decision(
1159- &mut w,
1160- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(1) as usize],
1161- u8::from(cbf_cb_k),
1162- );
1163- }
1164- if root_cr {
1165- cabac.encode_decision(
1166- &mut w,
1167- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(1) as usize],
1168- u8::from(cbf_cr_k),
1169- );
1170- }
1171- cabac.encode_decision(
1172- &mut w,
1173- &mut ctxs.cbf_luma[cbf_luma_ctx_inc(1) as usize],
1174- u8::from(cbf_luma_k),
1175- );
1176- if cbf_luma_k {
1177- encode_residual_coding(
1178- &mut w,
1179- &mut cabac,
1180- &mut ctxs.residual,
1181- &rc_params(3, false, plan.modes[k]),
1182- &plan.levels[k],
1183- )
1184- .expect("validated luma levels");
1185- }
1186- if root_cb && cbf_cb_k {
1187- encode_residual_coding(
1188- &mut w,
1189- &mut cabac,
1190- &mut ctxs.residual,
1191- &rc_params(2, true, mode_c),
1192- &cb_levels[k],
1193- )
1194- .expect("validated cb levels");
1195- }
1196- if root_cr && cbf_cr_k {
1197- encode_residual_coding(
1198- &mut w,
1199- &mut cabac,
1200- &mut ctxs.residual,
1201- &rc_params(2, true, mode_c),
1202- &cr_levels[k],
1203- )
1204- .expect("validated cr levels");
1205- }
1206- }
1207- }
1208-
1209- // end_of_slice_segment_flag.
1210- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
1211- }
1212- // The final terminate-1 flush wrote the rbsp_stop_one_bit;
1213- // rbsp_slice_segment_trailing_bits() is alignment zeros from here.
1214- w.align_zero();
1215- let slice_rbsp = w.finish();
1216-
1217- let level_idc = level_idc_for(width * height);
1218- // The reorder-free streams keep the historical VPS bounds (1, 0)
1219- // so every golden pin stays byte-stable; a reordering
1220- // (hierarchical-B) stream signals its honest DPB bounds.
1221- let vps = if cfg.max_num_reorder_pics == 0 {
1222- write_vps(level_idc)
1223- } else {
1224- write_vps_cfg(
1225- level_idc,
1226- cfg.max_dec_pic_buffering_minus1,
1227- cfg.max_num_reorder_pics,
1228- )
1229- };
1230- let units = vec![
1231- nal_unit(32, 0, 0, &vps), // VPS_NUT
1232- nal_unit(
1233- 33,
1234- 0,
1235- 0,
1236- &write_sps_cfg(width, height, level_idc, cfg, lf.sao()),
1237- ), // SPS_NUT
1238- nal_unit(34, 0, 0, &write_pps_lf(false, false, lf.deblocking, None)), // PPS_NUT
1239- nal_unit(20, 0, 0, &slice_rbsp), // IDR_N_LP
1240- ];
1241- Ok(IntraEncodedAu {
1242- au: annexb(&units),
1243- recon_y,
1244- recon_cb,
1245- recon_cr,
1246- })
1247-}
1248-
1249-#[cfg(test)]
1250-mod tests {
1251- use super::*;
1252- use crate::binarization::PartMode;
1253- use crate::sequence::{decode_annexb_sequence, decode_annexb_sequence_debug};
1254- use crate::slice_data::CodingQuadtree;
1255-
1256- /// Deterministic test content: smooth gradients + a diagonal
1257- /// texture component so directional modes and residuals both work.
1258- fn planes(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1259- let y: Vec<u8> = (0..w * h)
1260- .map(|i| {
1261- let (x, yy) = (i % w, i / w);
1262- ((x * 3 + yy * 2 + (x * yy / 7) % 31) % 256) as u8
1263- })
1264- .collect();
1265- let cb: Vec<u8> = (0..w * h / 4)
1266- .map(|i| ((i % (w / 2)) * 4 % 200 + 20) as u8)
1267- .collect();
1268- let cr: Vec<u8> = (0..w * h / 4)
1269- .map(|i| (240 - (i / (w / 2)) * 3 % 200) as u8)
1270- .collect();
1271- (y, cb, cr)
1272- }
1273-
1274- /// Content with per-8x8 alternating strong directions: drives the
1275- /// partition decision toward PART_NxN.
1276- fn blocky_planes(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1277- let y: Vec<u8> = (0..w * h)
1278- .map(|i| {
1279- let (x, yy) = (i % w, i / w);
1280- let (bx, by) = (x / 8, yy / 8);
1281- match (bx + by) % 3 {
1282- 0 => ((x % 8) * 30) as u8,
1283- 1 => ((yy % 8) * 30) as u8,
1284- _ => (((x + yy) % 16) * 15) as u8,
1285- }
1286- })
1287- .collect();
1288- let cb = vec![100u8; w * h / 4];
1289- let cr = vec![160u8; w * h / 4];
1290- (y, cb, cr)
1291- }
1292-
1293- fn psnr(a: &[u8], b: &[u8]) -> f64 {
1294- let mse: f64 = a
1295- .iter()
1296- .zip(b.iter())
1297- .map(|(&x, &y)| {
1298- let d = f64::from(x) - f64::from(y);
1299- d * d
1300- })
1301- .sum::<f64>()
1302- / a.len() as f64;
1303- if mse == 0.0 {
1304- f64::INFINITY
1305- } else {
1306- 10.0 * (255.0f64 * 255.0 / mse).log10()
1307- }
1308- }
1309-
1310- fn assert_roundtrip_exact(y: &[u8], cb: &[u8], cr: &[u8], w: usize, h: usize, qp: i32) {
1311- let enc = encode_idr_intra_au(y, cb, cr, w, h, qp).expect("encode");
1312- let frames = decode_annexb_sequence(&enc.au).expect("decode");
1313- assert_eq!(frames.len(), 1, "{w}x{h} qp{qp}");
1314- let mut recon = Vec::new();
1315- recon.extend_from_slice(&enc.recon_y);
1316- recon.extend_from_slice(&enc.recon_cb);
1317- recon.extend_from_slice(&enc.recon_cr);
1318- assert_eq!(
1319- frames[0].picture.to_planar_u8().expect("8-bit"),
1320- recon,
1321- "{w}x{h} qp{qp}: decoder output == encoder reconstruction"
1322- );
1323- }
1324-
1325- /// The core contract: the crate's own decoder reproduces the
1326- /// encoder's reconstruction EXACTLY (dual-decoder bit-exactness),
1327- /// on both smooth and NxN-inducing content.
1328- #[test]
1329- fn intra_au_decodes_to_encoder_recon_exactly() {
1330- for (w, h) in [(16usize, 16usize), (64, 48), (48, 80)] {
1331- let (y, cb, cr) = planes(w, h);
1332- for qp in [4i32, 22, 32, 45] {
1333- assert_roundtrip_exact(&y, &cb, &cr, w, h, qp);
1334- }
1335- let (y, cb, cr) = blocky_planes(w, h);
1336- for qp in [10i32, 27, 38] {
1337- assert_roundtrip_exact(&y, &cb, &cr, w, h, qp);
1338- }
1339- }
1340- }
1341-
1342- /// The partition decision really selects PART_NxN on content with
1343- /// per-8x8 directional structure (and the stream decodes exactly).
1344- #[test]
1345- fn nxn_partition_is_selected_and_decodes() {
1346- let (w, h) = (64usize, 64usize);
1347- let (y, cb, cr) = blocky_planes(w, h);
1348- let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 27).expect("encode");
1349- let ctus = decode_annexb_sequence_debug(&enc.au).expect("walk");
1350- let mut nxn = 0usize;
1351- let mut two_n = 0usize;
1352- for (_, _, ctu) in &ctus {
1353- if let CodingQuadtree::Leaf(cu) = &ctu.quadtree {
1354- match cu.part_mode {
1355- PartMode::PartNxN => nxn += 1,
1356- PartMode::Part2Nx2N => two_n += 1,
1357- other => panic!("unexpected part mode {other:?}"),
1358- }
1359- }
1360- }
1361- assert!(nxn > 0, "no PART_NxN CU selected ({two_n} 2Nx2N)");
1362- }
1363-
1364- /// Rate/distortion sanity: low QP is near-transparent, and
1365- /// quality degrades monotonically-ish while staying decodable.
1366- #[test]
1367- fn intra_quality_tracks_qp() {
1368- let (w, h) = (64usize, 64usize);
1369- let (y, cb, cr) = planes(w, h);
1370- let at = |qp: i32| {
1371- let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("encode");
1372- (psnr(&enc.recon_y, &y), enc.au.len())
1373- };
1374- let (p4, s4) = at(4);
1375- let (p22, s22) = at(22);
1376- let (p40, s40) = at(40);
1377- assert!(p4 > 45.0, "qp4 luma PSNR {p4:.1} dB");
1378- assert!(p22 > 33.0, "qp22 luma PSNR {p22:.1} dB");
1379- assert!(p40 > 22.0, "qp40 luma PSNR {p40:.1} dB");
1380- assert!(p4 > p22 && p22 > p40, "PSNR decreases with QP");
1381- assert!(
1382- s4 > s22 && s22 > s40,
1383- "bytes decrease with QP ({s4} > {s22} > {s40})"
1384- );
1385- }
1386-
1387- /// QP 22 on this content should be visually transparent while far
1388- /// smaller than the PCM (raw) coding — i.e. the transform path
1389- /// actually compresses.
1390- #[test]
1391- fn intra_beats_pcm_size_at_high_quality() {
1392- let (w, h) = (64usize, 64usize);
1393- let (y, cb, cr) = planes(w, h);
1394- let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 22).expect("encode");
1395- let raw = w * h * 3 / 2;
1396- assert!(
1397- enc.au.len() < raw / 2,
1398- "compressed {} bytes vs raw {raw}",
1399- enc.au.len()
1400- );
1401- }
1402-
1403- #[test]
1404- fn rejects_bad_inputs() {
1405- let (y, cb, cr) = planes(16, 16);
1406- assert!(matches!(
1407- encode_idr_intra_au(&y, &cb, &cr, 20, 16, 26),
1408- Err(IntraEncodeError::BadDimensions { .. })
1409- ));
1410- assert!(matches!(
1411- encode_idr_intra_au(&y, &cb, &cr, 16, 16, 52),
1412- Err(IntraEncodeError::BadQp(52))
1413- ));
1414- assert!(matches!(
1415- encode_idr_intra_au(&y, &cb, &cr, 32, 16, 26),
1416- Err(IntraEncodeError::PlaneSize { .. })
1417- ));
1418- }
1419-
1420- /// Filtered intra AUs (§8.7.2 deblocking / §8.7.3 SAO, alone and
1421- /// combined) decode bit-exactly to the encoder's filtered
1422- /// reconstruction through the crate's own decoder, across
1423- /// geometries and QPs.
1424- #[test]
1425- fn filtered_intra_au_decodes_to_encoder_recon_exactly() {
1426- let cfgs = [
1427- LoopFilterCfg {
1428- deblocking: true,
1429- sao_luma: false,
1430- sao_chroma: false,
1431- },
1432- LoopFilterCfg {
1433- deblocking: false,
1434- sao_luma: true,
1435- sao_chroma: true,
1436- },
1437- LoopFilterCfg {
1438- deblocking: false,
1439- sao_luma: true,
1440- sao_chroma: false,
1441- },
1442- LoopFilterCfg::all(),
1443- ];
1444- for (w, h) in [(32usize, 32usize), (64, 48)] {
1445- for planes_fn in [planes, blocky_planes] {
1446- let (y, cb, cr) = planes_fn(w, h);
1447- for qp in [27i32, 38] {
1448- for cfg in &cfgs {
1449- let enc =
1450- encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, cfg).expect("encode");
1451- let frames = decode_annexb_sequence(&enc.au).expect("decode");
1452- assert_eq!(frames.len(), 1, "{w}x{h} qp{qp} {cfg:?}");
1453- let mut recon = enc.recon_y.clone();
1454- recon.extend_from_slice(&enc.recon_cb);
1455- recon.extend_from_slice(&enc.recon_cr);
1456- assert_eq!(
1457- frames[0].picture.to_planar_u8().expect("8-bit"),
1458- recon,
1459- "{w}x{h} qp{qp} {cfg:?}: decoder output == filtered recon"
1460- );
1461- }
1462- }
1463- }
1464- }
1465- }
1466-
1467- /// The filter elections are distortion-driven, so a filtered
1468- /// encode is never further from the source than the unfiltered
1469- /// one — and on smooth content at high QP (where quantization
1470- /// manufactures block edges the source never had) the filters
1471- /// actually engage (the reconstruction changes and the slice
1472- /// header signals them).
1473- #[test]
1474- fn filters_never_hurt_and_engage_on_smooth_content() {
1475- let (w, h) = (64usize, 64usize);
1476- let (y, cb, cr) = planes(w, h);
1477- let qp = 40;
1478- let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("plain");
1479- let filtered =
1480- encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, &LoopFilterCfg::all()).expect("lf");
1481- let ssd = |a: &[u8], b: &[u8]| -> u64 {
1482- a.iter()
1483- .zip(b.iter())
1484- .map(|(&p, &q)| {
1485- let d = i64::from(p) - i64::from(q);
1486- (d * d) as u64
1487- })
1488- .sum()
1489- };
1490- let d_plain =
1491- ssd(&plain.recon_y, &y) + ssd(&plain.recon_cb, &cb) + ssd(&plain.recon_cr, &cr);
1492- let d_filt = ssd(&filtered.recon_y, &y)
1493- + ssd(&filtered.recon_cb, &cb)
1494- + ssd(&filtered.recon_cr, &cr);
1495- assert!(
1496- d_filt <= d_plain,
1497- "filters must not hurt: filtered {d_filt} vs plain {d_plain}"
1498- );
1499- assert_ne!(
1500- filtered.recon_y, plain.recon_y,
1501- "high-QP blocky content should engage the loop filters"
1502- );
1503-
1504- // The written headers carry the filter signalling: SAO enabled
1505- // in the SPS, the deblocking override chain in the PPS, and
1506- // the elected per-slice flags in the slice header.
1507- let units = crate::nal::collect_nal_units(&filtered.au).expect("walk");
1508- let sps = crate::sps::SeqParameterSet::parse(&units[1].rbsp).expect("sps");
1509- assert!(sps.sample_adaptive_offset_enabled_flag);
1510- let pps = crate::pps::PicParameterSet::parse(&units[2].rbsp).expect("pps");
1511- assert!(pps.deblocking_filter_control_present_flag);
1512- assert!(pps.deblocking.override_enabled_flag);
1513- assert!(pps.deblocking.disabled_flag, "PPS default stays disabled");
1514- let header = crate::slice::SliceSegmentHeader::parse(
1515- &units[3].rbsp,
1516- units[3].header.nal_unit_type,
1517- &sps,
1518- &pps,
1519- )
1520- .expect("slice header");
1521- assert!(
1522- header.slice_sao_luma_flag
1523- || header.slice_sao_chroma_flag
1524- || header.deblocking.is_some_and(|d| !d.disabled_flag),
1525- "some in-loop filter is elected in the slice header"
1526- );
1527- }
1528-
1529- /// `LoopFilterCfg::off()` reproduces the legacy unfiltered stream
1530- /// byte for byte (headers included) — the golden interop pins stay
1531- /// valid.
1532- #[test]
1533- fn lf_off_is_byte_identical_to_legacy_encode() {
1534- let (w, h) = (48usize, 32usize);
1535- let (y, cb, cr) = planes(w, h);
1536- let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, 24).expect("plain");
1537- let off =
1538- encode_idr_intra_au_lf(&y, &cb, &cr, w, h, 24, &LoopFilterCfg::off()).expect("off");
1539- assert_eq!(plain.au, off.au);
1540- assert_eq!(plain.recon_y, off.recon_y);
1541- }
1542-
1543- /// Table 8-10 spot pins.
1544- #[test]
1545- fn chroma_qp_mapping_matches_table_8_10() {
1546- assert_eq!(chroma_qp_420(0), 0);
1547- assert_eq!(chroma_qp_420(29), 29);
1548- assert_eq!(chroma_qp_420(30), 29);
1549- assert_eq!(chroma_qp_420(33), 32);
1550- assert_eq!(chroma_qp_420(34), 33);
1551- assert_eq!(chroma_qp_420(35), 33);
1552- assert_eq!(chroma_qp_420(36), 34);
1553- assert_eq!(chroma_qp_420(37), 34);
1554- assert_eq!(chroma_qp_420(38), 35);
1555- assert_eq!(chroma_qp_420(43), 37);
1556- assert_eq!(chroma_qp_420(44), 38);
1557- assert_eq!(chroma_qp_420(51), 45);
1558- }
1559-}
vendor/oxideav-h265/src/encoder/loopfilter.rsdeleted+0 -1308
@@ -1,1308 +0,0 @@
1-//! Encoder-side §8.7 in-loop filters — deblocking + SAO on the
2-//! encoder's reconstruction path.
3-//!
4-//! A conforming decoder's reference pictures are the *filtered*
5-//! reconstructions, so an encoder that signals the loop filters must
6-//! run the very same §8.7.2 deblocking and §8.7.3 SAO over its own
7-//! reconstruction before using it as a reference (and before claiming
8-//! it as "what the decoder outputs"). This module drives the crate's
9-//! DECODE-side filter implementations ([`crate::deblock`] /
10-//! [`crate::sao`]) over an encoder frame:
11-//!
12-//! * **Deblocking** (§8.7.2) — applied through
13-//! [`crate::deblock::deblock_picture_full`] with per-CTB
14-//! [`DeblockCuDesc`]s built from the encoder's coding decisions
15-//! (partition mode + transform-split topology) and the same
16-//! [`MotionField`] the mode decisions maintained. The per-frame
17-//! election is distortion-driven over off + a 3x3
18-//! `slice_beta_offset_div2` / `slice_tc_offset_div2` sweep
19-//! ({−2, 0, 2}²): the slice signals
20-//! `deblocking_filter_override_flag == 1` /
21-//! `slice_deblocking_filter_disabled_flag == 0` with the winning
22-//! offsets only when some filtered picture is closer to the source.
23-//! * **SAO** (§8.7.3) — per-CTB statistics-driven offset estimation
24-//! (the derivation of the offsets is encoder freedom; the *applied*
25-//! modification is the decoder's own
26-//! [`crate::sao::apply_sao_ctb_full`], so every candidate's
27-//! distortion is measured with the exact decode-side arithmetic).
28-//! Candidates per component: off, band offset (best
29-//! `sao_band_position` by per-band gain), and the four edge-offset
30-//! classes; chroma obeys the §7.4.9.3 shared-type rule (`SaoTypeIdx
31-//! [2]` / `SaoEoClass[2]` inherit cIdx 1). Whole-CTB
32-//! `sao_merge_left_flag` / `sao_merge_up_flag` candidates are priced
33-//! too. The elected parameters are applied with
34-//! [`crate::sao::apply_sao_picture_full`] — the same picture-level
35-//! driver the decoder runs.
36-//! * **Syntax** — [`encode_sao_ctb`] is the bin-exact §7.3.8.3
37-//! `sao( rx, ry )` dual of [`crate::slice_data::decode_sao`].
38-//!
39-//! Geometry contract (shared with the intra / low-delay encoders):
40-//! `CtbSizeY == 16`, one coding unit per CTB, 4:2:0 8-bit, a single
41-//! slice and tile per picture, constant QP (no `cu_qp_delta`), no PCM
42-//! / transquant-bypass CUs (so the §8.7 `NoFilterMap` is empty).
43-
44-use crate::binarization::PartMode;
45-use crate::ctx_init::SliceContexts;
46-use crate::deblock::{deblock_picture_full, DeblockCu, DeblockCuDesc, DeblockCuParams};
47-use crate::encoder::bitwriter::BitWriter;
48-use crate::encoder::cabac::CabacEncoder;
49-use crate::motion::MotionField;
50-use crate::picture::{Picture, Plane};
51-use crate::sao::{apply_sao_ctb_full, apply_sao_picture_full, ResolvedSao, ResolvedSaoComponent};
52-use crate::slice_data::{SaoComponent, SaoCtbParams};
53-
54-/// The fixed CTB log2 size of the bootstrap encoders (16x16).
55-const CTB_LOG2: u32 = 4;
56-/// The fixed CTB size.
57-const CTB: usize = 1 << CTB_LOG2;
58-/// §7.3.8.3 `sao_offset_abs` cMax at 8-bit:
59-/// `(1 << (Min(bitDepth, 10) − 5)) − 1`.
60-const SAO_OFFSET_MAX: i32 = 7;
61-
62-/// Which in-loop filters the encoder signals and applies.
63-#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
64-pub struct LoopFilterCfg {
65- /// Enable the §8.7.2 deblocking filter (PPS
66- /// `deblocking_filter_override_enabled_flag == 1`; each slice
67- /// elects on/off against distortion).
68- pub deblocking: bool,
69- /// Enable luma SAO (SPS `sample_adaptive_offset_enabled_flag == 1`
70- /// + per-slice `slice_sao_luma_flag` election).
71- pub sao_luma: bool,
72- /// Enable chroma SAO (`slice_sao_chroma_flag` election).
73- pub sao_chroma: bool,
74-}
75-
76-impl LoopFilterCfg {
77- /// No in-loop filters (the pre-round-429 encoder behaviour).
78- #[must_use]
79- pub fn off() -> Self {
80- Self::default()
81- }
82-
83- /// Deblocking + luma and chroma SAO.
84- #[must_use]
85- pub fn all() -> Self {
86- Self {
87- deblocking: true,
88- sao_luma: true,
89- sao_chroma: true,
90- }
91- }
92-
93- /// `true` when SAO is enabled for any component (drives the SPS
94- /// `sample_adaptive_offset_enabled_flag`).
95- #[must_use]
96- pub fn sao(&self) -> bool {
97- self.sao_luma || self.sao_chroma
98- }
99-
100- /// `true` when any filter is enabled.
101- #[must_use]
102- pub fn any(&self) -> bool {
103- self.deblocking || self.sao()
104- }
105-}
106-
107-/// One CTB-sized coding unit's deblocking shape (the encoder-side
108-/// counterpart of what the decoder reads off the parsed CU).
109-#[derive(Debug, Clone, Copy)]
110-pub struct CtbShape {
111- /// The CU's prediction partition mode.
112- pub part_mode: PartMode,
113- /// `true` when the CU's transform tree is the single-level split
114- /// (four depth-1 leaves: the §7.4.9.8 `IntraSplitFlag` /
115- /// `interSplitFlag` forced split); `false` for a whole-CB leaf
116- /// (depth-0 TU, skip, or `rqt_root_cbf == 0`).
117- pub split_depth1: bool,
118-}
119-
120-/// Build the per-CTB [`DeblockCuDesc`] list for a fixed-geometry
121-/// encoder picture (CTB == CU == 16, raster order, single slice /
122-/// tile, constant QP) at the given slice β/tC offsets.
123-#[must_use]
124-pub(crate) fn ctb_deblock_descs(
125- shapes: &[CtbShape],
126- width: usize,
127- height: usize,
128- qp: i32,
129- beta_offset_div2: i32,
130- tc_offset_div2: i32,
131-) -> Vec<DeblockCuDesc> {
132- let ctbs_x = width / CTB;
133- let ctbs_y = height / CTB;
134- debug_assert_eq!(shapes.len(), ctbs_x * ctbs_y);
135- let params = DeblockCuParams {
136- qp_y: qp,
137- beta_offset_div2,
138- tc_offset_div2,
139- cb_qp_offset: 0,
140- cr_qp_offset: 0,
141- bit_depth_luma: 8,
142- bit_depth_chroma: 8,
143- chroma_array_type: 1,
144- };
145- shapes
146- .iter()
147- .enumerate()
148- .map(|(ctb, shape)| {
149- let x0 = (ctb % ctbs_x) * CTB;
150- let y0 = (ctb / ctbs_x) * CTB;
151- DeblockCuDesc {
152- cu: DeblockCu {
153- x_cb: x0,
154- y_cb: y0,
155- log2_cb_size: CTB_LOG2,
156- params,
157- // Constant QP: the p-side scalars equal the CU QP.
158- qp_y_p_left: qp,
159- qp_y_p_top: qp,
160- },
161- transform_split: if shape.split_depth1 {
162- crate::deblock::TransformSplit::split_once()
163- } else {
164- crate::deblock::TransformSplit::leaf()
165- },
166- part_mode: shape.part_mode,
167- // §8.7.2.1: picture-boundary edges are never filtered;
168- // single slice / tile, so no other exclusions.
169- filter_left: x0 > 0,
170- filter_top: y0 > 0,
171- }
172- })
173- .collect()
174-}
175-
176-/// The borrowed inputs of one frame's filter pass.
177-pub(crate) struct FilterInput<'a> {
178- /// Picture width in luma samples (multiple of 16).
179- pub width: usize,
180- /// Picture height in luma samples.
181- pub height: usize,
182- /// `SliceQpY`.
183- pub qp: i32,
184- /// The SSD-per-bin λ of the slice's mode decisions.
185- pub lambda: u64,
186- /// Pre-filter reconstruction planes `[y, cb, cr]`.
187- pub recon: [&'a [u8]; 3],
188- /// Source planes `[y, cb, cr]`.
189- pub src: [&'a [u8]; 3],
190- /// The picture's motion / mode field (§8.7.2.4 bS input).
191- pub field: &'a MotionField,
192- /// Per-CTB coding shapes (raster order).
193- pub shapes: &'a [CtbShape],
194-}
195-
196-/// One frame's elected filter signalling + the filtered reconstruction.
197-pub(crate) struct FilteredFrame {
198- /// The slice's deblocking election
199- /// (`slice_deblocking_filter_disabled_flag == !deblock_on`).
200- pub deblock_on: bool,
201- /// Elected `slice_beta_offset_div2` (meaningful iff
202- /// [`Self::deblock_on`]).
203- pub beta_offset_div2: i32,
204- /// Elected `slice_tc_offset_div2`.
205- pub tc_offset_div2: i32,
206- /// Elected `slice_sao_luma_flag`.
207- pub slice_sao_luma: bool,
208- /// Elected `slice_sao_chroma_flag`.
209- pub slice_sao_chroma: bool,
210- /// Per-CTB §7.3.8.3 syntax values (raster order; empty when both
211- /// slice SAO flags are 0).
212- pub sao_ctbs: Vec<SaoCtbParams>,
213- /// The filtered reconstruction (what a conforming decoder outputs
214- /// and stores as a reference).
215- pub y: Vec<u8>,
216- /// Filtered Cb plane.
217- pub cb: Vec<u8>,
218- /// Filtered Cr plane.
219- pub cr: Vec<u8>,
220-}
221-
222-/// Pack three u8 planes into a [`Picture`].
223-fn planes_to_picture(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Picture {
224- let mut pic = Picture::new(width, height, 1, 8, 8);
225- for (plane, data) in [(Plane::Luma, y), (Plane::Cb, cb), (Plane::Cr, cr)] {
226- let (buf, _stride) = pic.plane_mut(plane);
227- debug_assert_eq!(buf.len(), data.len());
228- for (dst, &src) in buf.iter_mut().zip(data.iter()) {
229- *dst = i32::from(src);
230- }
231- }
232- pic
233-}
234-
235-/// SSD of one whole plane against a u8 source plane.
236-fn plane_ssd(pic: &Picture, plane: Plane, src: &[u8]) -> u64 {
237- pic.plane(plane)
238- .iter()
239- .zip(src.iter())
240- .map(|(&a, &b)| {
241- let d = a - i32::from(b);
242- (d * d) as u64
243- })
244- .sum()
245-}
246-
247-/// SSD of a `w`x`h` region of a picture plane against the matching
248-/// region of a u8 source plane (`plane_w` wide).
249-#[allow(clippy::too_many_arguments)]
250-fn region_ssd(
251- pic: &Picture,
252- plane: Plane,
253- src: &[u8],
254- plane_w: usize,
255- x0: usize,
256- y0: usize,
257- w: usize,
258- h: usize,
259-) -> u64 {
260- let mut acc = 0u64;
261- for j in 0..h {
262- for i in 0..w {
263- let d = pic.sample(plane, x0 + i, y0 + j) - i32::from(src[(y0 + j) * plane_w + x0 + i]);
264- acc += (d * d) as u64;
265- }
266- }
267- acc
268-}
269-
270-/// Copy a `w`x`h` region of `from` into `to` (same plane geometry).
271-fn restore_region(
272- to: &mut Picture,
273- from: &Picture,
274- plane: Plane,
275- x0: usize,
276- y0: usize,
277- w: usize,
278- h: usize,
279-) {
280- for j in 0..h {
281- for i in 0..w {
282- to.set_sample(plane, x0 + i, y0 + j, from.sample(plane, x0 + i, y0 + j));
283- }
284- }
285-}
286-
287-/// Round-half-away-from-zero integer division for the offset means.
288-fn round_div(sum: i64, cnt: i64) -> i32 {
289- if cnt == 0 {
290- 0
291- } else {
292- let bias = if sum >= 0 { cnt } else { -cnt };
293- ((2 * sum + bias) / (2 * cnt)) as i32
294- }
295-}
296-
297-/// §9.3.3 TR (cMax 7, bypass) bin count of one `sao_offset_abs` value.
298-fn tr7_bins(v: u32) -> u64 {
299- if v as i32 >= SAO_OFFSET_MAX {
300- SAO_OFFSET_MAX as u64
301- } else {
302- u64::from(v) + 1
303- }
304-}
305-
306-/// Rate proxy (bins) of one component's §7.3.8.3 fields. `with_shared`
307-/// counts the `sao_type_idx_*` (and, for edge offset, `sao_eo_class_*`)
308-/// bins — true for cIdx 0 / 1, false for cIdx 2 (which inherits both
309-/// per §7.4.9.3).
310-fn component_rate(comp: &SaoComponent, with_shared: bool) -> u64 {
311- match comp.sao_type_idx {
312- 0 => u64::from(with_shared),
313- 1 => {
314- let offs: u64 = comp.offset_abs.iter().map(|&a| tr7_bins(a)).sum();
315- let signs = comp.offset_abs.iter().filter(|&&a| a != 0).count() as u64;
316- u64::from(with_shared) * 2 + offs + signs + 5
317- }
318- _ => {
319- let offs: u64 = comp.offset_abs.iter().map(|&a| tr7_bins(a)).sum();
320- u64::from(with_shared) * 2 + offs + u64::from(with_shared) * 2
321- }
322- }
323-}
324-
325-/// Exact distortion of applying `comp` (already §7.4.9.3-resolved) to
326-/// one CTB region of one plane: runs the decoder's own
327-/// [`apply_sao_ctb_full`] into `scratch` (which must equal `base`
328-/// outside the region on entry) and restores the region afterwards.
329-#[allow(clippy::too_many_arguments)]
330-fn eval_component(
331- base: &Picture,
332- scratch: &mut Picture,
333- plane: Plane,
334- comp: &ResolvedSaoComponent,
335- src: &[u8],
336- plane_w: usize,
337- x0: usize,
338- y0: usize,
339- n: usize,
340-) -> u64 {
341- if comp.sao_type_idx == 0 {
342- return region_ssd(base, plane, src, plane_w, x0, y0, n, n);
343- }
344- apply_sao_ctb_full(base, scratch, plane, comp, x0, y0, n, n, None, None);
345- let d = region_ssd(scratch, plane, src, plane_w, x0, y0, n, n);
346- restore_region(scratch, base, plane, x0, y0, n, n);
347- d
348-}
349-
350-/// Statistics-driven §8.7.3.2 edge-offset candidate for one component
351-/// region: classify every sample against the pre-SAO picture (the
352-/// §8.7.3.2 picture-boundary guard included), then derive the four
353-/// per-category offsets from the src−rec means (categories 0/1
354-/// non-negative, 2/3 non-positive per the §7.4.9.3 inferred signs).
355-#[allow(clippy::too_many_arguments)]
356-fn edge_candidate(
357- base: &Picture,
358- plane: Plane,
359- src: &[u8],
360- plane_w: usize,
361- x0: usize,
362- y0: usize,
363- n: usize,
364- eo_class: u8,
365-) -> SaoComponent {
366- let (h0, v0, h1, v1) = crate::sao::eo_pos(eo_class);
367- let (pw, ph) = base.plane_dims(plane);
368- let mut cnt = [0i64; 5];
369- let mut sum = [0i64; 5];
370- for j in 0..n {
371- for i in 0..n {
372- let (x, y) = ((x0 + i) as i32, (y0 + j) as i32);
373- let in_pic =
374- |xx: i32, yy: i32| xx >= 0 && yy >= 0 && (xx as usize) < pw && (yy as usize) < ph;
375- if !in_pic(x + h0, y + v0) || !in_pic(x + h1, y + v1) {
376- continue;
377- }
378- let cur = base.sample(plane, x as usize, y as usize);
379- let s0 = base.sample(plane, (x + h0) as usize, (y + v0) as usize);
380- let s1 = base.sample(plane, (x + h1) as usize, (y + v1) as usize);
381- let sign = |v: i32| -> i32 {
382- match v.cmp(&0) {
383- core::cmp::Ordering::Greater => 1,
384- core::cmp::Ordering::Equal => 0,
385- core::cmp::Ordering::Less => -1,
386- }
387- };
388- let mut edge_idx = 2 + sign(cur - s0) + sign(cur - s1);
389- if edge_idx <= 2 {
390- edge_idx = if edge_idx == 2 { 0 } else { edge_idx + 1 };
391- }
392- if edge_idx == 0 {
393- continue;
394- }
395- cnt[edge_idx as usize] += 1;
396- sum[edge_idx as usize] +=
397- i64::from(src[(y as usize) * plane_w + x as usize]) - i64::from(cur);
398- }
399- }
400- let mut offset_abs = [0u32; 4];
401- for i in 0..4 {
402- let raw = round_div(sum[i + 1], cnt[i + 1]);
403- // §7.4.9.3 inferred signs: categories 1/2 add, 3/4 subtract.
404- let clamped = if i < 2 {
405- raw.clamp(0, SAO_OFFSET_MAX)
406- } else {
407- raw.clamp(-SAO_OFFSET_MAX, 0)
408- };
409- offset_abs[i] = clamped.unsigned_abs();
410- }
411- SaoComponent {
412- sao_type_idx: 2,
413- offset_abs,
414- offset_sign: [0; 4],
415- band_position: 0,
416- eo_class,
417- }
418-}
419-
420-/// Statistics-driven §8.7.3.2 band-offset candidate: per-band src−rec
421-/// means, then the `sao_band_position` whose four consecutive bands
422-/// carry the largest estimated SSD gain.
423-#[allow(clippy::too_many_arguments)]
424-fn band_candidate(
425- base: &Picture,
426- plane: Plane,
427- src: &[u8],
428- plane_w: usize,
429- x0: usize,
430- y0: usize,
431- n: usize,
432-) -> SaoComponent {
433- let mut cnt = [0i64; 32];
434- let mut sum = [0i64; 32];
435- for j in 0..n {
436- for i in 0..n {
437- let cur = base.sample(plane, x0 + i, y0 + j);
438- let band = (cur >> 3) as usize & 31;
439- cnt[band] += 1;
440- sum[band] += i64::from(src[(y0 + j) * plane_w + x0 + i]) - i64::from(cur);
441- }
442- }
443- let mut offset = [0i32; 32];
444- let mut gain = [0i64; 32];
445- for b in 0..32 {
446- let o = round_div(sum[b], cnt[b]).clamp(-SAO_OFFSET_MAX, SAO_OFFSET_MAX);
447- // Estimated SSD reduction: 2·o·Σdiff − o²·N (clipping ignored —
448- // the exact election re-measures with the decode-side apply).
449- let g = 2 * i64::from(o) * sum[b] - i64::from(o) * i64::from(o) * cnt[b];
450- if g > 0 {
451- offset[b] = o;
452- gain[b] = g;
453- }
454- }
455- let best_pos = (0..32u8)
456- .max_by_key(|&p| (0..4).map(|k| gain[(p as usize + k) & 31]).sum::<i64>())
457- .unwrap_or(0);
458- let mut offset_abs = [0u32; 4];
459- let mut offset_sign = [0u8; 4];
460- for k in 0..4 {
461- let o = offset[(best_pos as usize + k) & 31];
462- offset_abs[k] = o.unsigned_abs();
463- offset_sign[k] = u8::from(o < 0);
464- }
465- SaoComponent {
466- sao_type_idx: 1,
467- offset_abs,
468- offset_sign,
469- band_position: best_pos,
470- eo_class: 0,
471- }
472-}
473-
474-/// Resolve a syntax component into the applied form (8-bit: no
475-/// range-extension offset scale).
476-fn resolved(comp: &SaoComponent) -> ResolvedSaoComponent {
477- ResolvedSaoComponent::from_decoded(comp, 0)
478-}
479-
480-/// Elect one CTB's luma SAO parameters: off vs band vs the four edge
481-/// classes, each measured with the decode-side apply. Returns the
482-/// syntax component and its `dist + λ·rate` cost (rate including the
483-/// component's own §7.3.8.3 bins).
484-#[allow(clippy::too_many_arguments)]
485-fn choose_luma(
486- base: &Picture,
487- scratch: &mut Picture,
488- src: &[u8],
489- width: usize,
490- x0: usize,
491- y0: usize,
492- lambda: u64,
493-) -> (SaoComponent, u64) {
494- let off = SaoComponent::default();
495- let mut best = (
496- off,
497- region_ssd(base, Plane::Luma, src, width, x0, y0, CTB, CTB) + lambda,
498- );
499- let mut consider = |comp: SaoComponent, scratch: &mut Picture| {
500- let d = eval_component(
501- base,
502- scratch,
503- Plane::Luma,
504- &resolved(&comp),
505- src,
506- width,
507- x0,
508- y0,
509- CTB,
510- );
511- let cost = d + lambda * component_rate(&comp, true);
512- if cost < best.1 {
513- best = (comp, cost);
514- }
515- };
516- consider(
517- band_candidate(base, Plane::Luma, src, width, x0, y0, CTB),
518- scratch,
519- );
520- for eo_class in 0..4u8 {
521- consider(
522- edge_candidate(base, Plane::Luma, src, width, x0, y0, CTB, eo_class),
523- scratch,
524- );
525- }
526- best
527-}
528-
529-/// Elect one CTB's chroma SAO parameters under the §7.4.9.3 shared
530-/// type / eo-class rule: one `SaoTypeIdx` (and edge class) for both
531-/// Cb and Cr, per-component offsets / band positions.
532-#[allow(clippy::too_many_arguments)]
533-fn choose_chroma(
534- base: &Picture,
535- scratch: &mut Picture,
536- src_cb: &[u8],
537- src_cr: &[u8],
538- cw: usize,
539- cx0: usize,
540- cy0: usize,
541- lambda: u64,
542-) -> ([SaoComponent; 2], u64) {
543- let n = CTB / 2;
544- let dist_pair = |cb: &SaoComponent, cr: &SaoComponent, scratch: &mut Picture| -> u64 {
545- eval_component(
546- base,
547- scratch,
548- Plane::Cb,
549- &resolved(cb),
550- src_cb,
551- cw,
552- cx0,
553- cy0,
554- n,
555- ) + eval_component(
556- base,
557- scratch,
558- Plane::Cr,
559- &resolved(cr),
560- src_cr,
561- cw,
562- cx0,
563- cy0,
564- n,
565- )
566- };
567- let off = SaoComponent::default();
568- let mut best = ([off, off], dist_pair(&off, &off, scratch) + lambda);
569- let mut consider = |cb: SaoComponent, cr: SaoComponent, scratch: &mut Picture| {
570- let d = dist_pair(&cb, &cr, scratch);
571- let rate = component_rate(&cb, true) + component_rate(&cr, false);
572- let cost = d + lambda * rate;
573- if cost < best.1 {
574- best = ([cb, cr], cost);
575- }
576- };
577- consider(
578- band_candidate(base, Plane::Cb, src_cb, cw, cx0, cy0, n),
579- band_candidate(base, Plane::Cr, src_cr, cw, cx0, cy0, n),
580- scratch,
581- );
582- for eo_class in 0..4u8 {
583- consider(
584- edge_candidate(base, Plane::Cb, src_cb, cw, cx0, cy0, n, eo_class),
585- edge_candidate(base, Plane::Cr, src_cr, cw, cx0, cy0, n, eo_class),
586- scratch,
587- );
588- }
589- best
590-}
591-
592-/// Distortion of applying a fully-resolved CTB parameter set (all
593-/// three components) — the merge-candidate measurement.
594-#[allow(clippy::too_many_arguments)]
595-fn resolved_ctb_dist(
596- base: &Picture,
597- scratch: &mut Picture,
598- r: &ResolvedSao,
599- input: &FilterInput<'_>,
600- x0: usize,
601- y0: usize,
602- sao_luma: bool,
603- sao_chroma: bool,
604-) -> u64 {
605- let (cw, cx0, cy0, n) = (input.width / 2, x0 / 2, y0 / 2, CTB / 2);
606- let mut d = 0u64;
607- let luma = if sao_luma {
608- &r.components[0]
609- } else {
610- &ResolvedSaoComponent::off()
611- };
612- d += eval_component(
613- base,
614- scratch,
615- Plane::Luma,
616- luma,
617- input.src[0],
618- input.width,
619- x0,
620- y0,
621- CTB,
622- );
623- let (cbc, crc) = if sao_chroma {
624- (&r.components[1], &r.components[2])
625- } else {
626- (&ResolvedSaoComponent::off(), &ResolvedSaoComponent::off())
627- };
628- d += eval_component(base, scratch, Plane::Cb, cbc, input.src[1], cw, cx0, cy0, n);
629- d += eval_component(base, scratch, Plane::Cr, crc, input.src[2], cw, cx0, cy0, n);
630- d
631-}
632-
633-/// Run the elected in-loop filters over one encoder frame.
634-///
635-/// Returns the filter signalling (per-slice deblocking election, the
636-/// slice SAO flags, per-CTB SAO syntax) and the filtered
637-/// reconstruction — exactly what a conforming decoder reconstructs
638-/// from that signalling.
639-pub(crate) fn filter_frame(input: &FilterInput<'_>, cfg: &LoopFilterCfg) -> FilteredFrame {
640- let (width, height) = (input.width, input.height);
641- let pre = planes_to_picture(
642- input.recon[0],
643- input.recon[1],
644- input.recon[2],
645- width,
646- height,
647- );
648-
649- // ---- §8.7.2 deblocking: per-slice on/off + β/tC election ----
650- let mut deblock_on = false;
651- let mut beta_offset_div2 = 0i32;
652- let mut tc_offset_div2 = 0i32;
653- let base = if cfg.deblocking {
654- let ssd = |p: &Picture| {
655- plane_ssd(p, Plane::Luma, input.src[0])
656- + plane_ssd(p, Plane::Cb, input.src[1])
657- + plane_ssd(p, Plane::Cr, input.src[2])
658- };
659- // se(v) bin-length proxy of one slice offset field.
660- let se_bits = |v: i32| -> u64 {
661- match v.unsigned_abs() {
662- 0 => 1,
663- n => 2 * u64::from(32 - n.leading_zeros()) + 1,
664- }
665- };
666- // Off (override_flag 0: one bit) vs each (β, tC) offset pair
667- // (override group: ~3 bits + the two se(v) fields).
668- let mut best_pic = pre.clone();
669- let mut best_cost = ssd(&pre) + input.lambda;
670- for beta in [-2i32, 0, 2] {
671- for tc in [-2i32, 0, 2] {
672- let mut filtered = pre.clone();
673- let descs = ctb_deblock_descs(input.shapes, width, height, input.qp, beta, tc);
674- deblock_picture_full(&mut filtered, input.field, &descs, None, None);
675- let cost = ssd(&filtered) + input.lambda * (3 + se_bits(beta) + se_bits(tc));
676- if cost < best_cost {
677- best_cost = cost;
678- best_pic = filtered;
679- deblock_on = true;
680- beta_offset_div2 = beta;
681- tc_offset_div2 = tc;
682- }
683- }
684- }
685- best_pic
686- } else {
687- pre
688- };
689-
690- // ---- §8.7.3 SAO estimation (per CTB, on the deblocked picture) ----
691- let ctbs_x = width / CTB;
692- let ctbs_y = height / CTB;
693- let mut sao_ctbs: Vec<SaoCtbParams> = Vec::new();
694- let mut grid: Vec<ResolvedSao> = Vec::new();
695- if cfg.sao() {
696- let mut scratch = base.clone();
697- sao_ctbs.reserve(ctbs_x * ctbs_y);
698- grid.reserve(ctbs_x * ctbs_y);
699- for ctb in 0..ctbs_x * ctbs_y {
700- let (rx, ry) = (ctb % ctbs_x, ctb / ctbs_x);
701- let (x0, y0) = (rx * CTB, ry * CTB);
702- let (cx0, cy0) = (x0 / 2, y0 / 2);
703-
704- // Explicit candidate: per-component election.
705- let mut comps = [SaoComponent::default(); 3];
706- let mut explicit_cost = 0u64;
707- if cfg.sao_luma {
708- let (c, cost) = choose_luma(
709- &base,
710- &mut scratch,
711- input.src[0],
712- width,
713- x0,
714- y0,
715- input.lambda,
716- );
717- comps[0] = c;
718- explicit_cost += cost;
719- } else {
720- explicit_cost +=
721- region_ssd(&base, Plane::Luma, input.src[0], width, x0, y0, CTB, CTB);
722- }
723- if cfg.sao_chroma {
724- let ([cb, cr], cost) = choose_chroma(
725- &base,
726- &mut scratch,
727- input.src[1],
728- input.src[2],
729- width / 2,
730- cx0,
731- cy0,
732- input.lambda,
733- );
734- comps[1] = cb;
735- comps[2] = cr;
736- explicit_cost += cost;
737- } else {
738- let (cw, n) = (width / 2, CTB / 2);
739- explicit_cost += region_ssd(&base, Plane::Cb, input.src[1], cw, cx0, cy0, n, n)
740- + region_ssd(&base, Plane::Cr, input.src[2], cw, cx0, cy0, n, n);
741- }
742- // Declining the available merges costs one bin each.
743- let decline_bins = u64::from(rx > 0) + u64::from(ry > 0);
744- explicit_cost += input.lambda * decline_bins;
745-
746- let explicit_params = SaoCtbParams {
747- merge_left: false,
748- merge_up: false,
749- components: comps,
750- };
751- let explicit_resolved = ResolvedSao::resolve(&explicit_params, None, None, 0, 0);
752-
753- // Whole-CTB merge candidates (inherit ALL components).
754- let mut best = (explicit_params, explicit_resolved, explicit_cost);
755- if rx > 0 {
756- let left = grid[ctb - 1];
757- let d = resolved_ctb_dist(
758- &base,
759- &mut scratch,
760- &left,
761- input,
762- x0,
763- y0,
764- cfg.sao_luma,
765- cfg.sao_chroma,
766- );
767- let cost = d + input.lambda;
768- if cost < best.2 {
769- best = (
770- SaoCtbParams {
771- merge_left: true,
772- merge_up: false,
773- components: [SaoComponent::default(); 3],
774- },
775- left,
776- cost,
777- );
778- }
779- }
780- if ry > 0 {
781- let above = grid[ctb - ctbs_x];
782- let d = resolved_ctb_dist(
783- &base,
784- &mut scratch,
785- &above,
786- input,
787- x0,
788- y0,
789- cfg.sao_luma,
790- cfg.sao_chroma,
791- );
792- let cost = d + input.lambda * (1 + u64::from(rx > 0));
793- if cost < best.2 {
794- best = (
795- SaoCtbParams {
796- merge_left: false,
797- merge_up: true,
798- components: [SaoComponent::default(); 3],
799- },
800- above,
801- cost,
802- );
803- }
804- }
805-
806- sao_ctbs.push(best.0);
807- grid.push(best.1);
808- }
809- }
810-
811- // ---- slice-flag election + the decode-side picture apply ----
812- let slice_sao_luma = cfg.sao_luma && grid.iter().any(|r| r.components[0].sao_type_idx != 0);
813- let slice_sao_chroma = cfg.sao_chroma && grid.iter().any(|r| r.components[1].sao_type_idx != 0);
814- let out = if slice_sao_luma || slice_sao_chroma {
815- apply_sao_picture_full(
816- &base,
817- &grid,
818- CTB_LOG2,
819- 1,
820- slice_sao_luma,
821- slice_sao_chroma,
822- None,
823- None,
824- )
825- } else {
826- sao_ctbs.clear();
827- base
828- };
829-
830- let planar = out.to_planar_u8().expect("8-bit planes");
831- let (cw, ch) = (width / 2, height / 2);
832- let y = planar[..width * height].to_vec();
833- let cb = planar[width * height..width * height + cw * ch].to_vec();
834- let cr = planar[width * height + cw * ch..].to_vec();
835- FilteredFrame {
836- deblock_on,
837- beta_offset_div2,
838- tc_offset_div2,
839- slice_sao_luma,
840- slice_sao_chroma,
841- sao_ctbs,
842- y,
843- cb,
844- cr,
845- }
846-}
847-
848-/// §7.3.8.3 `sao( rx, ry )` — the bin-exact dual of
849-/// [`crate::slice_data::decode_sao`] for a single-slice, single-tile
850-/// picture (merge-left available iff `rx > 0`, merge-up iff `ry > 0`).
851-#[allow(clippy::too_many_arguments)]
852-pub(crate) fn encode_sao_ctb(
853- w: &mut BitWriter,
854- cabac: &mut CabacEncoder,
855- ctxs: &mut SliceContexts,
856- params: &SaoCtbParams,
857- rx: usize,
858- ry: usize,
859- slice_sao_luma: bool,
860- slice_sao_chroma: bool,
861-) {
862- if rx > 0 {
863- cabac.encode_decision(w, &mut ctxs.sao_merge_flag[0], u8::from(params.merge_left));
864- if params.merge_left {
865- return;
866- }
867- }
868- if ry > 0 {
869- cabac.encode_decision(w, &mut ctxs.sao_merge_flag[0], u8::from(params.merge_up));
870- if params.merge_up {
871- return;
872- }
873- }
874- for c_idx in 0..3usize {
875- let read = (slice_sao_luma && c_idx == 0) || (slice_sao_chroma && c_idx > 0);
876- if !read {
877- continue;
878- }
879- let comp = &params.components[c_idx];
880- if c_idx < 2 {
881- // sao_type_idx_luma / _chroma: TR cMax 2 — bin 0
882- // context-coded, bin 1 bypass.
883- cabac.encode_decision(
884- w,
885- &mut ctxs.sao_type_idx[0],
886- u8::from(comp.sao_type_idx > 0),
887- );
888- if comp.sao_type_idx > 0 {
889- cabac.encode_bypass(w, u8::from(comp.sao_type_idx == 2));
890- }
891- } else {
892- debug_assert_eq!(
893- comp.sao_type_idx, params.components[1].sao_type_idx,
894- "SaoTypeIdx[2] inherits cIdx 1 (§7.4.9.3)"
895- );
896- }
897- if comp.sao_type_idx != 0 {
898- for &abs in &comp.offset_abs {
899- // sao_offset_abs: TR cMax 7 (8-bit), all bypass.
900- for _ in 0..abs.min(SAO_OFFSET_MAX as u32) {
901- cabac.encode_bypass(w, 1);
902- }
903- if (abs as i32) < SAO_OFFSET_MAX {
904- cabac.encode_bypass(w, 0);
905- }
906- }
907- if comp.sao_type_idx == 1 {
908- for i in 0..4 {
909- if comp.offset_abs[i] != 0 {
910- cabac.encode_bypass(w, comp.offset_sign[i]);
911- }
912- }
913- cabac.encode_bypass_bits(w, u32::from(comp.band_position), 5);
914- } else if c_idx < 2 {
915- cabac.encode_bypass_bits(w, u32::from(comp.eo_class), 2);
916- }
917- }
918- }
919-}
920-
921-#[cfg(test)]
922-mod tests {
923- use super::*;
924- use crate::bitreader::BitReader;
925- use crate::cabac::CabacEngine;
926- use crate::slice_data::{decode_sao, SliceDataParams};
927-
928- fn sao_params(sao_luma: bool, sao_chroma: bool) -> SliceDataParams {
929- SliceDataParams {
930- ctb_log2_size_y: 4,
931- min_cb_log2_size_y: 4,
932- max_tb_log2_size_y: 4,
933- min_tb_log2_size_y: 2,
934- pic_width_in_luma_samples: 64,
935- pic_height_in_luma_samples: 64,
936- chroma_array_type: 1,
937- bit_depth_luma: 8,
938- bit_depth_chroma: 8,
939- slice_type_is_i: true,
940- slice_type_is_b: false,
941- slice_sao_luma_flag: sao_luma,
942- slice_sao_chroma_flag: sao_chroma,
943- transquant_bypass_enabled_flag: false,
944- cu_qp_delta_enabled_flag: false,
945- log2_min_cu_qp_delta_size: 4,
946- cu_chroma_qp_offset_enabled_flag: false,
947- log2_min_cu_chroma_qp_offset_size: 4,
948- chroma_qp_offset_list_len_minus1: 0,
949- amp_enabled_flag: false,
950- pcm_enabled_flag: false,
951- log2_min_ipcm_cb_size_y: 3,
952- log2_max_ipcm_cb_size_y: 5,
953- pcm_bit_depth_luma: 8,
954- pcm_bit_depth_chroma: 8,
955- max_transform_hierarchy_depth_intra: 0,
956- max_transform_hierarchy_depth_inter: 0,
957- max_num_merge_cand: 5,
958- num_ref_idx_l0_active_minus1: 0,
959- num_ref_idx_l1_active_minus1: 0,
960- mvd_l1_zero_flag: false,
961- sign_data_hiding_enabled_flag: false,
962- cross_component_prediction_enabled_flag: false,
963- residual_adaptive_colour_transform_enabled_flag: false,
964- transform_skip_enabled_flag: false,
965- log2_max_transform_skip_size: 2,
966- implicit_rdpcm_enabled_flag: false,
967- explicit_rdpcm_enabled_flag: false,
968- transform_skip_context_enabled_flag: false,
969- persistent_rice_adaptation_enabled_flag: false,
970- cabac_bypass_alignment_enabled_flag: false,
971- extended_precision_processing_flag: false,
972- palette_mode_enabled_flag: false,
973- palette_max_size: 0,
974- palette_max_predictor_size: 0,
975- }
976- }
977-
978- fn band(pos: u8, abs: [u32; 4], sign: [u8; 4]) -> SaoComponent {
979- SaoComponent {
980- sao_type_idx: 1,
981- offset_abs: abs,
982- offset_sign: sign,
983- band_position: pos,
984- eo_class: 0,
985- }
986- }
987-
988- fn edge(class: u8, abs: [u32; 4]) -> SaoComponent {
989- SaoComponent {
990- sao_type_idx: 2,
991- offset_abs: abs,
992- offset_sign: [0; 4],
993- band_position: 0,
994- eo_class: class,
995- }
996- }
997-
998- /// Round-trip one CTB's syntax through the write-side dual and the
999- /// decode-side `decode_sao`, comparing the decoded fields.
1000- fn assert_sao_roundtrip(
1001- params: &SaoCtbParams,
1002- rx: usize,
1003- ry: usize,
1004- sao_luma: bool,
1005- sao_chroma: bool,
1006- ) {
1007- let mut w = BitWriter::new();
1008- let mut enc = CabacEncoder::new();
1009- let mut ectx = SliceContexts::init(0, 26);
1010- encode_sao_ctb(
1011- &mut w, &mut enc, &mut ectx, params, rx, ry, sao_luma, sao_chroma,
1012- );
1013- enc.encode_terminate(&mut w, 1);
1014- let bytes = w.finish();
1015-
1016- let mut engine = CabacEngine::new(BitReader::new(&bytes)).expect("engine");
1017- let mut dctx = SliceContexts::init(0, 26);
1018- let got = decode_sao(
1019- &mut engine,
1020- &mut dctx,
1021- &sao_params(sao_luma, sao_chroma),
1022- rx > 0,
1023- ry > 0,
1024- )
1025- .expect("decode_sao");
1026-
1027- assert_eq!(got.merge_left, params.merge_left, "merge_left");
1028- assert_eq!(got.merge_up, params.merge_up, "merge_up");
1029- if params.merge_left || params.merge_up {
1030- return;
1031- }
1032- for c in 0..3 {
1033- let read = (sao_luma && c == 0) || (sao_chroma && c > 0);
1034- if !read {
1035- continue;
1036- }
1037- assert_eq!(got.components[c], params.components[c], "component {c}");
1038- }
1039- }
1040-
1041- /// The §7.3.8.3 writer is the exact dual of `decode_sao` across
1042- /// off / band / edge / merge shapes, all flag combinations, and
1043- /// the offset extremes (incl. the TR cMax 7 no-terminator case).
1044- #[test]
1045- fn sao_syntax_roundtrips_through_decode_sao() {
1046- let shapes: Vec<[SaoComponent; 3]> = vec![
1047- [SaoComponent::default(); 3],
1048- [
1049- band(8, [1, 2, 3, 4], [0, 1, 0, 1]),
1050- SaoComponent::default(),
1051- SaoComponent::default(),
1052- ],
1053- [
1054- edge(1, [7, 0, 2, 7]),
1055- edge(3, [1, 1, 1, 1]),
1056- edge(3, [0, 7, 3, 0]),
1057- ],
1058- [
1059- band(31, [7, 7, 7, 7], [1, 1, 1, 1]),
1060- band(0, [0, 0, 0, 0], [0, 0, 0, 0]),
1061- band(29, [4, 0, 1, 7], [0, 0, 1, 1]),
1062- ],
1063- [
1064- SaoComponent::default(),
1065- edge(0, [2, 1, 0, 3]),
1066- edge(0, [5, 4, 3, 2]),
1067- ],
1068- ];
1069- for comps in &shapes {
1070- for (sao_luma, sao_chroma) in [(true, true), (true, false), (false, true)] {
1071- for (rx, ry) in [(0usize, 0usize), (1, 0), (0, 1), (2, 3)] {
1072- let params = SaoCtbParams {
1073- merge_left: false,
1074- merge_up: false,
1075- components: *comps,
1076- };
1077- assert_sao_roundtrip(&params, rx, ry, sao_luma, sao_chroma);
1078- }
1079- }
1080- }
1081- // Merge shapes.
1082- for (ml, mu, rx, ry) in [
1083- (true, false, 1, 1),
1084- (false, true, 1, 1),
1085- (false, true, 0, 1),
1086- ] {
1087- let params = SaoCtbParams {
1088- merge_left: ml,
1089- merge_up: mu,
1090- components: [SaoComponent::default(); 3],
1091- };
1092- assert_sao_roundtrip(&params, rx, ry, true, true);
1093- }
1094- }
1095-
1096- /// Band estimation on a constant-shift region recovers the shift
1097- /// (a flat +4 error in one band ⇒ offset +4 in that band).
1098- #[test]
1099- fn band_candidate_recovers_flat_shift() {
1100- let mut pic = Picture::new(16, 16, 1, 8, 8);
1101- for y in 0..16 {
1102- for x in 0..16 {
1103- pic.set_sample(Plane::Luma, x, y, 100); // band 12
1104- }
1105- }
1106- let src = vec![104u8; 256];
1107- let cand = band_candidate(&pic, Plane::Luma, &src, 16, 0, 0, 16);
1108- assert_eq!(cand.sao_type_idx, 1);
1109- // Band 12 must be one of the four covered bands, with offset +4.
1110- let covered: Vec<usize> = (0..4)
1111- .map(|k| (cand.band_position as usize + k) & 31)
1112- .collect();
1113- let pos = covered
1114- .iter()
1115- .position(|&b| b == 12)
1116- .expect("band 12 covered");
1117- assert_eq!(cand.offset_abs[pos], 4);
1118- assert_eq!(cand.offset_sign[pos], 0);
1119- }
1120-
1121- /// Edge estimation classifies against the pre-SAO neighbours and
1122- /// clamps to the §7.4.9.3 inferred signs (categories 3/4 never
1123- /// positive).
1124- #[test]
1125- fn edge_candidate_derives_clamped_offsets() {
1126- let mut pic = Picture::new(16, 16, 1, 8, 8);
1127- // A horizontal comb: odd columns are local minima (category 1
1128- // for eo_class 0), even columns local maxima (category 4).
1129- for y in 0..16 {
1130- for x in 0..16 {
1131- pic.set_sample(Plane::Luma, x, y, if x % 2 == 0 { 110 } else { 90 });
1132- }
1133- }
1134- // Source: flatten toward 100 ⇒ minima want +10 (clamped 7),
1135- // maxima want −10 (clamped −7 ⇒ abs 7).
1136- let src = vec![100u8; 256];
1137- let cand = edge_candidate(&pic, Plane::Luma, &src, 16, 0, 0, 16, 0);
1138- assert_eq!(cand.sao_type_idx, 2);
1139- assert_eq!(cand.eo_class, 0);
1140- assert_eq!(cand.offset_abs[0], 7, "category 1 (local min) clamped +7");
1141- assert_eq!(cand.offset_abs[3], 7, "category 4 (local max) clamped −7");
1142- }
1143-
1144- /// The whole-frame SAO election never worsens the reconstruction:
1145- /// on content with a systematic band error the filtered output is
1146- /// strictly closer to the source, and re-applying the elected
1147- /// parameters through the decode-side picture driver reproduces
1148- /// the returned planes exactly.
1149- #[test]
1150- fn filter_frame_sao_improves_and_matches_decoder_apply() {
1151- let (w, h) = (32usize, 32usize);
1152- // Recon: gradient. Source: recon + 3 (a flat band-offset-able
1153- // error), chroma constant.
1154- let recon_y: Vec<u8> = (0..w * h).map(|i| ((i % w) * 4) as u8).collect();
1155- let src_y: Vec<u8> = recon_y.iter().map(|&v| v.saturating_add(3)).collect();
1156- let recon_c = vec![100u8; w * h / 4];
1157- let src_c: Vec<u8> = vec![102u8; w * h / 4];
1158- let field = MotionField::new(w, h);
1159- let shapes = vec![
1160- CtbShape {
1161- part_mode: PartMode::Part2Nx2N,
1162- split_depth1: false,
1163- };
1164- (w / 16) * (h / 16)
1165- ];
1166- let input = FilterInput {
1167- width: w,
1168- height: h,
1169- qp: 30,
1170- lambda: 4,
1171- recon: [&recon_y, &recon_c, &recon_c],
1172- src: [&src_y, &src_c, &src_c],
1173- field: &field,
1174- shapes: &shapes,
1175- };
1176- let out = filter_frame(&input, &LoopFilterCfg::all());
1177- assert!(out.slice_sao_luma || out.slice_sao_chroma, "SAO elected");
1178-
1179- let ssd = |a: &[u8], b: &[u8]| -> u64 {
1180- a.iter()
1181- .zip(b.iter())
1182- .map(|(&x, &y)| {
1183- let d = i64::from(x) - i64::from(y);
1184- (d * d) as u64
1185- })
1186- .sum()
1187- };
1188- let before = ssd(&recon_y, &src_y) + 2 * ssd(&recon_c, &src_c);
1189- let after = ssd(&out.y, &src_y) + ssd(&out.cb, &src_c) + ssd(&out.cr, &src_c);
1190- assert!(after < before, "SAO improves SSD ({after} < {before})");
1191-
1192- // Decoder-side re-application: resolve the emitted syntax with
1193- // merge inheritance and run the picture driver — byte-exact
1194- // against the returned planes.
1195- let ctbs_x = w / 16;
1196- let mut grid = vec![ResolvedSao::off(); out.sao_ctbs.len()];
1197- for (i, p) in out.sao_ctbs.iter().enumerate() {
1198- let left = (i % ctbs_x > 0).then(|| grid[i - 1]);
1199- let above = (i / ctbs_x > 0).then(|| grid[i - ctbs_x]);
1200- grid[i] = ResolvedSao::resolve(p, left.as_ref(), above.as_ref(), 0, 0);
1201- }
1202- let pre = planes_to_picture(&recon_y, &recon_c, &recon_c, w, h);
1203- let applied = apply_sao_picture_full(
1204- &pre,
1205- &grid,
1206- 4,
1207- 1,
1208- out.slice_sao_luma,
1209- out.slice_sao_chroma,
1210- None,
1211- None,
1212- );
1213- let planar = applied.to_planar_u8().expect("8-bit");
1214- let mut expect = out.y.clone();
1215- expect.extend_from_slice(&out.cb);
1216- expect.extend_from_slice(&out.cr);
1217- assert_eq!(planar, expect, "decode-side apply reproduces filter_frame");
1218- }
1219-
1220- /// Deblocking election: on a blocky reconstruction of smooth
1221- /// source content the filter is elected (and the output differs);
1222- /// on a perfect reconstruction it is declined.
1223- #[test]
1224- fn deblock_election_is_distortion_driven() {
1225- let (w, h) = (32usize, 32usize);
1226- // Source: smooth horizontal ramp.
1227- let src_y: Vec<u8> = (0..w * h).map(|i| ((i % w) * 3 + 40) as u8).collect();
1228- // Recon: the ramp quantized to per-16 blocks (strong blocking).
1229- let recon_y: Vec<u8> = (0..w * h)
1230- .map(|i| {
1231- let x = (i % w) / 16 * 16 + 8;
1232- (x * 3 + 40) as u8
1233- })
1234- .collect();
1235- let cpl = vec![128u8; w * h / 4];
1236- let field = MotionField::new(w, h); // all intra ⇒ bS 2 at CB edges
1237- let shapes = vec![
1238- CtbShape {
1239- part_mode: PartMode::Part2Nx2N,
1240- split_depth1: false,
1241- };
1242- (w / 16) * (h / 16)
1243- ];
1244- let input = FilterInput {
1245- width: w,
1246- height: h,
1247- qp: 37,
1248- lambda: 1,
1249- recon: [&recon_y, &cpl, &cpl],
1250- src: [&src_y, &cpl, &cpl],
1251- field: &field,
1252- shapes: &shapes,
1253- };
1254- let cfg = LoopFilterCfg {
1255- deblocking: true,
1256- sao_luma: false,
1257- sao_chroma: false,
1258- };
1259- let out = filter_frame(&input, &cfg);
1260- assert!(out.deblock_on, "blocky recon elects deblocking");
1261- assert_ne!(out.y, recon_y, "deblocking modified the luma plane");
1262- assert!(
1263- (-2..=2).contains(&out.beta_offset_div2) && (-2..=2).contains(&out.tc_offset_div2),
1264- "elected offsets stay in the swept range"
1265- );
1266-
1267- // The election is optimal over its candidate set: brute-force
1268- // every (β, tC) pair through the decode-side driver and check
1269- // the elected pair's distortion is the minimum.
1270- let ssd = |a: &[u8], b: &[u8]| -> u64 {
1271- a.iter()
1272- .zip(b.iter())
1273- .map(|(&x, &y)| {
1274- let d = i64::from(x) - i64::from(y);
1275- (d * d) as u64
1276- })
1277- .sum()
1278- };
1279- let dist_at = |beta: i32, tc: i32| -> u64 {
1280- let mut pic = planes_to_picture(&recon_y, &cpl, &cpl, w, h);
1281- let descs = ctb_deblock_descs(&shapes, w, h, 37, beta, tc);
1282- deblock_picture_full(&mut pic, &field, &descs, None, None);
1283- let planar = pic.to_planar_u8().expect("8-bit");
1284- ssd(&planar[..w * h], &src_y)
1285- };
1286- let elected = dist_at(out.beta_offset_div2, out.tc_offset_div2);
1287- for beta in [-2i32, 0, 2] {
1288- for tc in [-2i32, 0, 2] {
1289- // λ == 1 makes the rate term negligible against the
1290- // luma SSD scale of this content.
1291- assert!(
1292- elected <= dist_at(beta, tc) + 16,
1293- "({beta},{tc}) beats the elected pair"
1294- );
1295- }
1296- }
1297-
1298- // Perfect reconstruction: filtering can only hurt ⇒ declined.
1299- let input2 = FilterInput {
1300- recon: [&src_y, &cpl, &cpl],
1301- src: [&src_y, &cpl, &cpl],
1302- ..input
1303- };
1304- let out2 = filter_frame(&input2, &cfg);
1305- assert!(!out2.deblock_on, "perfect recon declines deblocking");
1306- assert_eq!(out2.y, src_y);
1307- }
1308-}
vendor/oxideav-h265/src/encoder/nal.rsdeleted+0 -114
@@ -1,114 +0,0 @@
1-//! NAL-unit encapsulation — the write-side dual of [`crate::nal`].
2-//!
3-//! Wraps an RBSP into a complete NAL unit (the two-byte §7.3.1.2
4-//! header + the §7.4.1.1 emulation-prevention escaped payload) and
5-//! frames NAL units into an Annex B byte stream.
6-
7-/// §7.4.1.1 — insert `emulation_prevention_three_byte`s: within the
8-/// payload, any `00 00` followed by a byte `<= 0x03` becomes
9-/// `00 00 03 xx` so no start-code prefix can appear inside a NAL unit.
10-#[must_use]
11-pub fn escape_rbsp(rbsp: &[u8]) -> Vec<u8> {
12- let mut out = Vec::with_capacity(rbsp.len() + rbsp.len() / 64 + 4);
13- let mut zero_run = 0usize;
14- for &b in rbsp {
15- if zero_run >= 2 && b <= 0x03 {
16- out.push(0x03);
17- zero_run = 0;
18- }
19- out.push(b);
20- if b == 0 {
21- zero_run += 1;
22- } else {
23- zero_run = 0;
24- }
25- }
26- out
27-}
28-
29-/// Build a complete coded NAL unit: the §7.3.1.2 two-byte header
30-/// (`forbidden_zero_bit == 0`, `nal_unit_type`, `nuh_layer_id`,
31-/// `nuh_temporal_id_plus1 = temporal_id + 1`) followed by the escaped
32-/// RBSP.
33-#[must_use]
34-pub fn nal_unit(nal_unit_type: u8, nuh_layer_id: u8, temporal_id: u8, rbsp: &[u8]) -> Vec<u8> {
35- debug_assert!(nal_unit_type < 64 && nuh_layer_id < 64 && temporal_id < 7);
36- let b0 = (nal_unit_type << 1) | (nuh_layer_id >> 5);
37- let b1 = ((nuh_layer_id & 0x1F) << 3) | (temporal_id + 1);
38- let mut out = vec![b0, b1];
39- out.extend(escape_rbsp(rbsp));
40- out
41-}
42-
43-/// Frame complete coded NAL units into an Annex B byte stream: a
44-/// four-byte start code (`00 00 00 01`) before parameter-set /
45-/// first-of-AU units keeps players happy; this writer simply uses the
46-/// four-byte form everywhere (§B.1.2 permits leading zeros).
47-#[must_use]
48-pub fn annexb(units: &[Vec<u8>]) -> Vec<u8> {
49- let mut out = Vec::new();
50- for u in units {
51- out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]);
52- out.extend_from_slice(u);
53- }
54- out
55-}
56-
57-#[cfg(test)]
58-mod tests {
59- use super::*;
60- use crate::nal::{collect_nal_units, strip_emulation_prevention};
61-
62- #[test]
63- fn escape_inserts_before_low_bytes() {
64- // 00 00 00 -> 00 00 03 00; 00 00 01 -> 00 00 03 01; 00 00 04 stays.
65- assert_eq!(
66- escape_rbsp(&[0, 0, 0, 0, 1]),
67- vec![0, 0, 3, 0, 0, 3, 1],
68- "double escape over a zero run"
69- );
70- assert_eq!(escape_rbsp(&[0, 0, 4]), vec![0, 0, 4]);
71- assert_eq!(escape_rbsp(&[0, 0, 2]), vec![0, 0, 3, 2]);
72- }
73-
74- #[test]
75- fn escape_roundtrips_through_reader_strip() {
76- let payloads: [&[u8]; 5] = [
77- &[],
78- &[0, 0, 0, 0, 0, 0],
79- &[0, 0, 1, 0, 0, 2, 0, 0, 3],
80- &[0xFF, 0, 0, 0, 0xFF],
81- &[0, 0],
82- ];
83- for p in payloads {
84- let escaped = escape_rbsp(p);
85- assert_eq!(strip_emulation_prevention(&escaped), p, "{p:02x?}");
86- // No start code may survive inside the escaped payload.
87- assert!(!escaped.windows(3).any(|w| w == [0, 0, 1] || w == [0, 0, 0]));
88- }
89- }
90-
91- #[test]
92- fn nal_unit_header_roundtrips_through_walker() {
93- let rbsp = vec![0xAA, 0x00, 0x00, 0x00, 0xBB];
94- let unit = nal_unit(19, 0, 0, &rbsp); // IDR_W_RADL
95- let stream = annexb(&[unit]);
96- let units = collect_nal_units(&stream).expect("walk");
97- assert_eq!(units.len(), 1);
98- assert_eq!(units[0].header.nal_unit_type, 19);
99- assert_eq!(units[0].header.nuh_layer_id, 0);
100- assert_eq!(units[0].header.temporal_id, 0);
101- assert_eq!(units[0].rbsp, rbsp);
102- }
103-
104- #[test]
105- fn annexb_frames_multiple_units() {
106- let a = nal_unit(32, 0, 0, &[0x01]);
107- let b = nal_unit(33, 0, 0, &[0x02]);
108- let stream = annexb(&[a, b]);
109- let units = collect_nal_units(&stream).expect("walk");
110- assert_eq!(units.len(), 2);
111- assert_eq!(units[0].header.nal_unit_type, 32);
112- assert_eq!(units[1].header.nal_unit_type, 33);
113- }
114-}
vendor/oxideav-h265/src/encoder/palette_streams.rsdeleted+0 -1130
@@ -1,1130 +0,0 @@
1-//! Self-built §7.3.8.13 palette-mode conformance stream (test-only).
2-//!
3-//! No black-box encoder binary exposes the Screen Content Coding
4-//! tools, so this module assembles a tiny all-palette Annex B
5-//! bitstream from this crate's own header writers and CABAC encoder:
6-//! every 16x16 CTB is one `palette_mode_flag == 1` coding unit, and
7-//! the per-CTB plans exercise new-entry signalling, predictor reuse
8-//! (`palette_predictor_run`), explicit-index and copy-above runs, the
9-//! run-to-end inference, `MaxPaletteIndex == 0` degenerate blocks,
10-//! `palette_transpose_flag`, and escape samples in BOTH forms —
11-//! transquant-bypass (FL) and quantized (EG3, at `SliceQpY == 4`
12-//! where the eq. 8-77 dequantization is exact, keeping the whole
13-//! stream lossless).
14-//!
15-//! The checked-in copy under `tests/fixture_bytes/` is pinned by the
16-//! tests here: the builder must reproduce its exact bytes and this
17-//! crate's decoder must reconstruct the planned source planes
18-//! losslessly (reference-decoder validation notes live in
19-//! `tests/fixture_bytes/r413-generation-notes.md`).
20-
21-use crate::cabac::init_type;
22-use crate::ctx_init::SliceContexts;
23-use crate::encoder::bitwriter::BitWriter;
24-use crate::encoder::cabac::CabacEncoder;
25-use crate::encoder::nal::{annexb, nal_unit};
26-use crate::encoder::rdpcm_streams::{write_pps_bypass, write_ptl_rext};
27-use crate::palette::{PaletteCu, PalettePredictor};
28-
29-/// One picture's `(Y, Cb, Cr)` planes.
30-type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
31-use crate::scan::traverse;
32-
33-/// CTB / coding-block size (16x16, `MinCbSizeY == CtbSizeY`).
34-const CTB: usize = 16;
35-/// `SliceQpY` — 4, where escape dequantization (eq. 8-77) is exact:
36-/// `levelScale[4 % 6] = 64`, shift `4 / 6 = 0`, so
37-/// `((v * 64) + 32) >> 6 == v`.
38-const SLICE_QP: i32 = 4;
39-/// `palette_max_size` signalled in the SPS SCC extension.
40-const PALETTE_MAX_SIZE: u32 = 7;
41-/// `delta_palette_max_predictor_size`.
42-const DELTA_MAX_PREDICTOR: u32 = 9;
43-
44-/// §7.3.2.2 — 4:2:0 8-bit SPS (CTB 16, no PCM, SAO off) with an
45-/// `sps_scc_extension()` enabling palette mode.
46-fn write_sps_scc(width: usize, height: usize, level_idc: u8, initializers: &[[u16; 3]]) -> Vec<u8> {
47- let mut w = BitWriter::new();
48- w.put_bits(0, 4); // sps_video_parameter_set_id
49- w.put_bits(0, 3); // sps_max_sub_layers_minus1
50- w.put_bit(1); // sps_temporal_id_nesting_flag
51- write_ptl_rext(&mut w, level_idc);
52- w.ue(0); // sps_seq_parameter_set_id
53- w.ue(1); // chroma_format_idc = 4:2:0
54- w.ue(width as u32); // pic_width_in_luma_samples
55- w.ue(height as u32); // pic_height_in_luma_samples
56- w.put_bit(0); // conformance_window_flag
57- w.ue(0); // bit_depth_luma_minus8
58- w.ue(0); // bit_depth_chroma_minus8
59- w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
60- w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
61- w.ue(1); // sps_max_dec_pic_buffering_minus1[0]
62- w.ue(0); // sps_max_num_reorder_pics[0]
63- w.ue(0); // sps_max_latency_increase_plus1[0]
64- w.ue(1); // log2_min_luma_coding_block_size_minus3 (16)
65- w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16)
66- w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
67- w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
68- w.ue(0); // max_transform_hierarchy_depth_inter
69- w.ue(0); // max_transform_hierarchy_depth_intra
70- w.put_bit(0); // scaling_list_enabled_flag
71- w.put_bit(0); // amp_enabled_flag
72- w.put_bit(0); // sample_adaptive_offset_enabled_flag
73- w.put_bit(0); // pcm_enabled_flag
74- w.ue(0); // num_short_term_ref_pic_sets
75- w.put_bit(0); // long_term_ref_pics_present_flag
76- w.put_bit(0); // sps_temporal_mvp_enabled_flag
77- w.put_bit(0); // strong_intra_smoothing_enabled_flag
78- w.put_bit(0); // vui_parameters_present_flag
79- w.put_bit(1); // sps_extension_present_flag
80- w.put_bit(0); // sps_range_extension_flag
81- w.put_bit(0); // sps_multilayer_extension_flag
82- w.put_bit(0); // sps_3d_extension_flag
83- w.put_bit(1); // sps_scc_extension_flag
84- w.put_bits(0, 4); // sps_extension_4bits
85- // sps_scc_extension() — §7.3.2.2.3.
86- w.put_bit(0); // sps_curr_pic_ref_enabled_flag
87- w.put_bit(1); // palette_mode_enabled_flag
88- w.ue(PALETTE_MAX_SIZE); // palette_max_size
89- w.ue(DELTA_MAX_PREDICTOR); // delta_palette_max_predictor_size
90- if initializers.is_empty() {
91- w.put_bit(0); // sps_palette_predictor_initializers_present_flag
92- } else {
93- w.put_bit(1); // sps_palette_predictor_initializers_present_flag
94- w.ue(initializers.len() as u32 - 1); // sps_num_..._minus1
95- // §7.3.2.2.3: component-major, u(BitDepth) each (8 bits here).
96- for c in 0..3 {
97- for e in initializers {
98- w.put_bits(u32::from(e[c]), 8);
99- }
100- }
101- }
102- w.put_bits(0, 2); // motion_vector_resolution_control_idc
103- w.put_bit(0); // intra_boundary_filtering_disabled_flag
104- w.rbsp_trailing_bits();
105- w.finish()
106-}
107-
108-/// One planned palette CU: the palette (per component), the target
109-/// index map (coded coordinates), transpose, bypass and the escape
110-/// samples (`Some(values per component)` at positions whose index is
111-/// `MaxPaletteIndex`).
112-struct CuPlan {
113- /// Reuse flags into the CURRENT predictor (length =
114- /// `PredictorPaletteSize` at this CU).
115- reuse: Vec<bool>,
116- /// Explicitly signalled new entries (per component).
117- new_entries: [Vec<u16>; 3],
118- /// Escape samples present.
119- escape_present: bool,
120- /// `palette_transpose_flag`.
121- transpose: bool,
122- /// `cu_transquant_bypass_flag`.
123- bypass: bool,
124- /// Target `PaletteIndexMap` (coded coords, `CTB * CTB`).
125- index_map: Vec<u8>,
126- /// Escape values per component at coded luma coords (only
127- /// positions whose index equals `MaxPaletteIndex` and pass the
128- /// §7.3.8.13 4:2:0 phase gate are consulted).
129- escape_vals: [Vec<u16>; 3],
130-}
131-
132-/// Bypass-encode an EG0 value.
133-fn encode_eg0(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32) {
134- encode_eg_k(cabac, w, v, 0);
135-}
136-
137-/// §9.3.3.3 dual of `decode_eg_k`.
138-fn encode_eg_k(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32, k: u32) {
139- let mut prefix_ones = 0u32;
140- while (((1u64 << (prefix_ones + 1)) - 1) << k) <= u64::from(v) {
141- prefix_ones += 1;
142- }
143- for _ in 0..prefix_ones {
144- cabac.encode_bypass(w, 1);
145- }
146- cabac.encode_bypass(w, 0);
147- let base = ((1u64 << prefix_ones) - 1) << k;
148- let suffix = u64::from(v) - base;
149- let bits = prefix_ones + k;
150- for i in (0..bits).rev() {
151- cabac.encode_bypass(w, ((suffix >> i) & 1) as u8);
152- }
153-}
154-
155-/// §9.3.3.6 dual of `decode_tb`.
156-fn encode_tb(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32, c_max: u32) {
157- if c_max == 0 {
158- return;
159- }
160- let n = c_max + 1;
161- let k = 31 - n.leading_zeros();
162- let u = (1u32 << (k + 1)) - n;
163- if v < u {
164- for i in (0..k).rev() {
165- cabac.encode_bypass(w, ((v >> i) & 1) as u8);
166- }
167- } else {
168- let val = v + u;
169- for i in (0..=k).rev() {
170- cabac.encode_bypass(w, ((val >> i) & 1) as u8);
171- }
172- }
173-}
174-
175-/// §9.3.3.14 dual.
176-fn encode_num_palette_indices_minus1(
177- cabac: &mut CabacEncoder,
178- w: &mut BitWriter,
179- v: u32,
180- max_palette_index: u32,
181-) {
182- let k = 3 + ((max_palette_index + 1) >> 3);
183- let c_max = 4u32 << k;
184- if v < c_max {
185- let q = v >> k;
186- for _ in 0..q {
187- cabac.encode_bypass(w, 1);
188- }
189- cabac.encode_bypass(w, 0);
190- for i in (0..k).rev() {
191- cabac.encode_bypass(w, ((v >> i) & 1) as u8);
192- }
193- } else {
194- for _ in 0..4 {
195- cabac.encode_bypass(w, 1);
196- }
197- encode_eg_k(cabac, w, v - c_max, k + 1);
198- }
199-}
200-
201-/// The run segmentation of a target index map: `(copy_above, explicit
202-/// index or 0, run_minus1)` per run, in scan order.
203-struct Run {
204- copy: bool,
205- index: u8,
206- len: usize, // PaletteRunMinus1 + 1
207-}
208-
209-/// Greedy §7.3.8.13-compatible segmentation: maximal runs, preferring
210-/// copy-above when it is at least as long as the explicit run (and
211-/// syntactically expressible).
212-fn segment_runs(index_map: &[u8], n: usize) -> Vec<Run> {
213- let scan = traverse(n);
214- let area = n * n;
215- let mut runs: Vec<Run> = Vec::new();
216- let mut pos = 0usize;
217- while pos < area {
218- let at = |p: usize| {
219- let s = &scan[p];
220- index_map[s.y as usize * n + s.x as usize]
221- };
222- let above = |p: usize| {
223- let s = &scan[p];
224- debug_assert!(s.y > 0);
225- index_map[(s.y as usize - 1) * n + s.x as usize]
226- };
227- let prev_copy = runs.last().is_some_and(|r| r.copy);
228- // Maximal explicit run of the current index.
229- let idx = at(pos);
230- let mut exp_len = 1usize;
231- while pos + exp_len < area && at(pos + exp_len) == idx {
232- exp_len += 1;
233- }
234- // Maximal copy-above run (when expressible here).
235- let mut copy_len = 0usize;
236- if pos >= n && !prev_copy {
237- while pos + copy_len < area
238- && scan[pos + copy_len].y > 0
239- && at(pos + copy_len) == above(pos + copy_len)
240- {
241- copy_len += 1;
242- }
243- }
244- if copy_len >= exp_len && copy_len > 0 {
245- runs.push(Run {
246- copy: true,
247- index: 0,
248- len: copy_len,
249- });
250- pos += copy_len;
251- } else {
252- runs.push(Run {
253- copy: false,
254- index: idx,
255- len: exp_len,
256- });
257- pos += exp_len;
258- }
259- }
260- runs
261-}
262-
263-/// Encode one `palette_coding( )` body for `plan`, mirroring the
264-/// §7.3.8.13 parse gate-for-gate (panicking if the plan is not
265-/// syntactically representable), and apply the eq. 8-79 predictor
266-/// update to `predictor`.
267-#[allow(clippy::too_many_lines)]
268-fn encode_palette_cu(
269- cabac: &mut CabacEncoder,
270- w: &mut BitWriter,
271- ctx: &mut SliceContexts,
272- predictor: &mut PalettePredictor,
273- plan: &CuPlan,
274-) -> PaletteCu {
275- let n = CTB;
276- let area = n * n;
277- let predictor_size = predictor.size();
278- assert_eq!(plan.reuse.len(), predictor_size);
279-
280- // ---- palette_predictor_run ----
281- let num_predicted = plan.reuse.iter().filter(|&&r| r).count();
282- {
283- let mut last = -1i64;
284- let mut emitted = 0usize;
285- for (i, &r) in plan.reuse.iter().enumerate() {
286- if !r {
287- continue;
288- }
289- let run = if emitted == 0 {
290- i as u32
291- } else {
292- (i as i64 - last) as u32
293- };
294- // run semantics: 0 = reuse at current cursor; >1 = skip
295- // run-1 then reuse; the value 1 is the terminator, so a
296- // gap of exactly one entry is encoded as run = 2, etc.
297- let wire = if emitted == 0 {
298- if i == 0 {
299- 0
300- } else {
301- i as u32 + 1
302- }
303- } else {
304- let gap = (i as i64 - last - 1) as u32;
305- if gap == 0 {
306- 0
307- } else {
308- gap + 1
309- }
310- };
311- let _ = run;
312- encode_eg0(cabac, w, wire);
313- emitted += 1;
314- last = i as i64;
315- }
316- // Terminator when the loop would otherwise continue.
317- if predictor_size > 0
318- && num_predicted < PALETTE_MAX_SIZE as usize
319- && (emitted == 0 || (last as usize) < predictor_size - 1)
320- {
321- encode_eg0(cabac, w, 1);
322- }
323- }
324-
325- // ---- num_signalled_palette_entries + new entries ----
326- let num_signalled = plan.new_entries[0].len();
327- if num_predicted < PALETTE_MAX_SIZE as usize {
328- encode_eg0(cabac, w, num_signalled as u32);
329- } else {
330- assert_eq!(num_signalled, 0);
331- }
332- for c in 0..3 {
333- for &v in &plan.new_entries[c] {
334- cabac.encode_bypass_bits(w, u32::from(v), 8);
335- }
336- }
337-
338- // ---- CurrentPaletteEntries (eq. 7-82) ----
339- let mut palette: [Vec<u16>; 3] = Default::default();
340- for (c, pal) in palette.iter_mut().enumerate() {
341- for (i, &r) in plan.reuse.iter().enumerate() {
342- if r {
343- pal.push(predictor.entries[c][i]);
344- }
345- }
346- pal.extend_from_slice(&plan.new_entries[c]);
347- }
348- let current_size = palette[0].len();
349-
350- // ---- palette_escape_val_present_flag ----
351- if current_size != 0 {
352- cabac.encode_bypass(w, u8::from(plan.escape_present));
353- } else {
354- assert!(plan.escape_present, "empty palette requires escapes");
355- }
356- let max_index = current_size as u32 + u32::from(plan.escape_present) - 1;
357-
358- // ---- run segmentation, explicit index list ----
359- let runs = segment_runs(&plan.index_map, n);
360- let explicit: Vec<&Run> = runs.iter().filter(|r| !r.copy).collect();
361- let num_indices = explicit.len();
362- let final_copy = runs.last().map(|r| r.copy).unwrap_or(false);
363- // Per-run RAW `palette_idx_idc` values (0 for copy-above runs):
364- // §9.3.4.2.8 derives the `palette_run_prefix` ctxInc from the
365- // signalled syntax element, so the run loop below needs the
366- // pre-eq.-7-84 value, not the plan's final index.
367- let mut idc_by_run: Vec<u32> = vec![0; runs.len()];
368-
369- if max_index > 0 {
370- encode_num_palette_indices_minus1(cabac, w, num_indices as u32 - 1, max_index);
371- // The idc list needs the eq. 7-83/7-84 INVERSE adjustment,
372- // which depends on scan state; walk the runs to derive each
373- // adjusted idc.
374- let scan = traverse(n);
375- let mut adjust = 0u32;
376- let mut pos = 0usize;
377- let mut prev_copy = false;
378- for (run_i, r) in runs.iter().enumerate() {
379- if !r.copy {
380- let adjusted_ref = if pos > 0 {
381- let p = &scan[pos - 1];
382- if !prev_copy {
383- u32::from(plan.index_map[p.y as usize * n + p.x as usize])
384- } else {
385- let c = &scan[pos];
386- u32::from(plan.index_map[(c.y as usize - 1) * n + c.x as usize])
387- }
388- } else {
389- max_index + 1
390- };
391- let target = u32::from(r.index);
392- assert_ne!(
393- target, adjusted_ref,
394- "explicit index equal to adjustedRefPaletteIndex is not encodable"
395- );
396- let idc = if target > adjusted_ref {
397- target - 1
398- } else {
399- target
400- };
401- idc_by_run[run_i] = idc;
402- let c_max = max_index - adjust;
403- if c_max > 0 {
404- encode_tb(cabac, w, idc, c_max);
405- } else {
406- assert_eq!(idc, 0);
407- }
408- adjust = 1;
409- }
410- prev_copy = r.copy;
411- pos += r.len;
412- }
413- // copy_above_indices_for_final_run_flag + transpose.
414- let ctxm = &mut ctx.palette_copy_above_flag[0];
415- cabac.encode_decision(w, ctxm, u8::from(final_copy));
416- cabac.encode_decision(
417- w,
418- &mut ctx.palette_transpose_flag[0],
419- u8::from(plan.transpose),
420- );
421- } else {
422- assert_eq!(num_indices, 1, "MaxPaletteIndex 0 has one inferred index");
423- assert!(!plan.transpose);
424- }
425-
426- // (delta_qp: cu_qp_delta_enabled == 0 in this stream ⇒ no bins.)
427-
428- // ---- run loop ----
429- let mut remaining = num_indices;
430- let mut pos = 0usize;
431- let mut prev_copy = false;
432- for (run_i, r) in runs.iter().enumerate() {
433- // Mirror the parse-side flag presence gates.
434- if max_index > 0 && pos >= n && !prev_copy {
435- if remaining > 0 && pos < area - 1 {
436- cabac.encode_decision(w, &mut ctx.palette_copy_above_flag[0], u8::from(r.copy));
437- } else {
438- let inferred = !(pos == area - 1 && remaining > 0);
439- assert_eq!(r.copy, inferred, "inferred copy flag must match the plan");
440- }
441- } else {
442- assert!(!r.copy, "copy-above not expressible at pos {pos}");
443- }
444- // §9.3.4.2.8: the run-prefix ctxInc consumes the RAW
445- // signalled `palette_idx_idc`, not the final palette index.
446- let idc_for_ctx = if r.copy { 0 } else { idc_by_run[run_i] };
447- if max_index > 0 {
448- if !r.copy {
449- remaining -= 1;
450- }
451- if remaining > 0 || r.copy != final_copy {
452- let max_run_minus1 =
453- area as i64 - pos as i64 - 1 - remaining as i64 - i64::from(final_copy);
454- assert!(max_run_minus1 >= 0);
455- let run_minus1 = (r.len - 1) as u32;
456- assert!(i64::from(run_minus1) <= max_run_minus1);
457- if max_run_minus1 > 0 {
458- // palette_run_prefix / suffix.
459- let c_max =
460- crate::binarization::palette_run_prefix_tr_cmax(max_run_minus1 as u32);
461- let (prefix, suffix) = if run_minus1 < 2 {
462- (run_minus1, None)
463- } else {
464- let p = 32 - run_minus1.leading_zeros(); // floor(log2(v)) + 1
465- let prefix_offset = 1u32 << (p - 1);
466- debug_assert!(prefix_offset <= run_minus1);
467- (p, Some(run_minus1 - prefix_offset))
468- };
469- // TR prefix: `prefix` ones then a terminating zero
470- // (omitted at cMax).
471- for bin_idx in 0..prefix {
472- emit_run_prefix_bin(cabac, w, ctx, bin_idx, r.copy, idc_for_ctx, 1);
473- }
474- if prefix < c_max {
475- emit_run_prefix_bin(cabac, w, ctx, prefix, r.copy, idc_for_ctx, 0);
476- }
477- if let Some(sfx) = suffix {
478- let prefix_offset = 1u32 << (prefix - 1);
479- if max_run_minus1 as u32 != prefix_offset {
480- let c_max_tb = if (prefix_offset << 1) > max_run_minus1 as u32 {
481- max_run_minus1 as u32 - prefix_offset
482- } else {
483- prefix_offset - 1
484- };
485- encode_tb(cabac, w, sfx, c_max_tb);
486- } else {
487- assert_eq!(sfx, 0);
488- }
489- }
490- } else {
491- assert_eq!(run_minus1, 0);
492- }
493- } else {
494- // RunToEnd inference: the run must actually reach the
495- // block end.
496- assert_eq!(pos + r.len, area, "final run must cover the tail");
497- }
498- }
499- prev_copy = r.copy;
500- pos += r.len;
501- }
502-
503- // ---- escape values ----
504- if plan.escape_present {
505- let scan = traverse(n);
506- for c in 0..3usize {
507- for p in &scan {
508- let (x, y) = (p.x as usize, p.y as usize);
509- if u32::from(plan.index_map[y * n + x]) != max_index {
510- continue;
511- }
512- let present = c == 0 || (x % 2 == 0 && y % 2 == 0);
513- if !present {
514- continue;
515- }
516- let v = u32::from(plan.escape_vals[c][y * n + x]);
517- if plan.bypass {
518- cabac.encode_bypass_bits(w, v, 8);
519- } else {
520- encode_eg_k(cabac, w, v, 3);
521- }
522- }
523- }
524- }
525-
526- // ---- eq. 8-79 predictor update ----
527- let max_pred = (PALETTE_MAX_SIZE + DELTA_MAX_PREDICTOR) as usize;
528- let mut new_pred: [Vec<u16>; 3] = palette.clone();
529- let mut new_size = current_size;
530- for (i, &r) in plan.reuse.iter().enumerate() {
531- if new_size >= max_pred {
532- break;
533- }
534- if !r {
535- for (c, np) in new_pred.iter_mut().enumerate() {
536- np.push(predictor.entries[c][i]);
537- }
538- new_size += 1;
539- }
540- }
541- *predictor = PalettePredictor { entries: new_pred };
542-
543- PaletteCu {
544- n_cbs: n,
545- palette,
546- escape_present: plan.escape_present,
547- transpose: plan.transpose,
548- index_map: plan.index_map.clone(),
549- escape_vals: plan.escape_vals.clone(),
550- cu_qp_delta: None,
551- cu_chroma_qp_offset: None,
552- }
553-}
554-
555-fn emit_run_prefix_bin(
556- cabac: &mut CabacEncoder,
557- w: &mut BitWriter,
558- ctx: &mut SliceContexts,
559- bin_idx: u32,
560- copy: bool,
561- idc: u32,
562- bin: u8,
563-) {
564- match crate::binarization::palette_run_prefix_ctx_inc(bin_idx, copy, idc) {
565- Some(inc) => cabac.encode_decision(w, &mut ctx.palette_run_prefix[inc as usize], bin),
566- None => cabac.encode_bypass(w, bin),
567- }
568-}
569-
570-/// The per-CTB plans for a 64x48 picture (4x3 CTBs).
571-fn cu_plans(predictor_snapshots: &mut Vec<PalettePredictor>) -> Vec<CuPlan> {
572- let n = CTB;
573- let _ = predictor_snapshots;
574- let mut plans = Vec::new();
575-
576- // CTB 0: four new colours, horizontal bands (explicit runs only).
577- plans.push(CuPlan {
578- reuse: vec![],
579- new_entries: [
580- vec![30, 90, 160, 220],
581- vec![60, 100, 150, 200],
582- vec![200, 150, 100, 50],
583- ],
584- escape_present: false,
585- transpose: false,
586- bypass: true,
587- index_map: {
588- let mut m = vec![0u8; n * n];
589- for y in 0..n {
590- for x in 0..n {
591- m[y * n + x] = (y / 4) as u8;
592- }
593- }
594- m
595- },
596- escape_vals: Default::default(),
597- });
598-
599- // CTB 1: reuse predictor entries 0 and 2, one new colour;
600- // vertical stripes (row 0 explicit, the rest copy-above runs).
601- plans.push(CuPlan {
602- reuse: vec![true, false, true, false],
603- new_entries: [vec![120], vec![130], vec![140]],
604- escape_present: false,
605- transpose: false,
606- bypass: true,
607- index_map: {
608- let mut m = vec![0u8; n * n];
609- for y in 0..n {
610- for x in 0..n {
611- m[y * n + x] = ((x / 2) % 3) as u8;
612- }
613- }
614- m
615- },
616- escape_vals: Default::default(),
617- });
618-
619- // CTB 2: single colour (MaxPaletteIndex == 0 degenerate: no index
620- // list, no run coding).
621- plans.push(CuPlan {
622- reuse: vec![false, false, true, false, false],
623- new_entries: [vec![], vec![], vec![]],
624- escape_present: false,
625- transpose: false,
626- bypass: true,
627- index_map: vec![0u8; n * n],
628- escape_vals: Default::default(),
629- });
630-
631- // CTB 3: two colours + BYPASS escapes on a sparse grid.
632- plans.push(CuPlan {
633- reuse: vec![true, true, false, false, false],
634- new_entries: [vec![], vec![], vec![]],
635- escape_present: true,
636- transpose: false,
637- bypass: true,
638- index_map: {
639- let mut m = vec![0u8; n * n];
640- for y in 0..n {
641- for x in 0..n {
642- m[y * n + x] = u8::from(y >= 8);
643- }
644- }
645- // Escape index = MaxPaletteIndex = 2, at even positions.
646- m[2 * n + 2] = 2;
647- m[2 * n + 3] = 2; // odd x: luma escape only (4:2:0 gate)
648- m[10 * n + 6] = 2;
649- m
650- },
651- escape_vals: {
652- let mut y_v = vec![0u16; n * n];
653- let mut cb_v = vec![0u16; n * n];
654- let mut cr_v = vec![0u16; n * n];
655- y_v[2 * n + 2] = 250;
656- y_v[2 * n + 3] = 17;
657- y_v[10 * n + 6] = 3;
658- cb_v[2 * n + 2] = 77;
659- cr_v[2 * n + 2] = 99;
660- cb_v[10 * n + 6] = 5;
661- cr_v[10 * n + 6] = 240;
662- [y_v, cb_v, cr_v]
663- },
664- });
665-
666- // CTB 4: transpose stripes (coded rows become picture columns).
667- plans.push(CuPlan {
668- reuse: vec![true, true, true, false, false],
669- new_entries: [vec![], vec![], vec![]],
670- escape_present: false,
671- transpose: true,
672- bypass: true,
673- index_map: {
674- let mut m = vec![0u8; n * n];
675- for y in 0..n {
676- for x in 0..n {
677- m[y * n + x] = ((y / 3) % 3) as u8;
678- }
679- }
680- m
681- },
682- escape_vals: Default::default(),
683- });
684-
685- // CTB 5: QUANTIZED escapes (non-bypass CU at SliceQpY 4 — exact).
686- plans.push(CuPlan {
687- reuse: vec![true, false, false, false, false],
688- new_entries: [vec![10], vec![20], vec![30]],
689- escape_present: true,
690- transpose: false,
691- bypass: false,
692- index_map: {
693- let mut m = vec![0u8; n * n];
694- for y in 0..n {
695- for x in 0..n {
696- m[y * n + x] = u8::from((x + y) % 4 == 0);
697- }
698- }
699- // A 2x2-aligned escape block.
700- m[4 * n + 4] = 2;
701- m[12 * n + 8] = 2;
702- m
703- },
704- escape_vals: {
705- let mut y_v = vec![0u16; n * n];
706- let mut cb_v = vec![0u16; n * n];
707- let mut cr_v = vec![0u16; n * n];
708- y_v[4 * n + 4] = 133;
709- y_v[12 * n + 8] = 255;
710- cb_v[4 * n + 4] = 44;
711- cr_v[4 * n + 4] = 211;
712- cb_v[12 * n + 8] = 0;
713- cr_v[12 * n + 8] = 128;
714- [y_v, cb_v, cr_v]
715- },
716- });
717-
718- // CTBs 6..11: diagonal two-colour texture cycling reuse patterns
719- // (keeps the predictor evolving).
720- for k in 0..6usize {
721- plans.push(CuPlan {
722- reuse: vec![], // filled at build time (reuse first two)
723- new_entries: Default::default(),
724- escape_present: false,
725- transpose: k % 2 == 1,
726- bypass: true,
727- index_map: {
728- let mut m = vec![0u8; n * n];
729- for y in 0..n {
730- for x in 0..n {
731- m[y * n + x] = u8::from((x + y + k) % 8 < 4);
732- }
733- }
734- m
735- },
736- escape_vals: Default::default(),
737- });
738- }
739-
740- plans
741-}
742-
743-/// Build the palette conformance stream: VPS + SPS(SCC) + PPS + one
744-/// all-palette IDR picture (64x48). Returns the Annex B bytes and the
745-/// expected (lossless) decoded planes.
746-pub(crate) fn build_palette_stream() -> (Vec<u8>, Planes) {
747- let (width, height) = (64usize, 48usize);
748- let (cw, ch) = (width / 2, height / 2);
749- let ctbs_x = width / CTB;
750-
751- let mut w = BitWriter::new();
752- // ---- slice_segment_header( ) ----
753- w.put_bit(1); // first_slice_segment_in_pic_flag
754- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
755- w.ue(0); // slice_pic_parameter_set_id
756- w.ue(2); // slice_type = I
757- w.se(SLICE_QP - 26); // slice_qp_delta
758- w.rbsp_trailing_bits();
759-
760- let mut cabac = CabacEncoder::new();
761- let mut ctx = SliceContexts::init(init_type(2, false), SLICE_QP);
762- let mut predictor = PalettePredictor::default();
763-
764- let mut y_plane = vec![0u8; width * height];
765- let mut cb_plane = vec![0u8; cw * ch];
766- let mut cr_plane = vec![0u8; cw * ch];
767-
768- let mut snapshots = Vec::new();
769- let mut plans = cu_plans(&mut snapshots);
770- for (ctb, plan) in plans.iter_mut().enumerate() {
771- let x0 = (ctb % ctbs_x) * CTB;
772- let y0 = (ctb / ctbs_x) * CTB;
773-
774- // Late-bound reuse vectors for the tail CTBs: reuse the first
775- // two predictor entries.
776- if ctb >= 6 {
777- let mut reuse = vec![false; predictor.size()];
778- if reuse.len() >= 2 {
779- reuse[0] = true;
780- reuse[1] = true;
781- }
782- plan.reuse = reuse;
783- }
784-
785- // ---- coding_unit( ) prelude ----
786- cabac.encode_decision(
787- &mut w,
788- &mut ctx.cu_transquant_bypass_flag[0],
789- u8::from(plan.bypass),
790- );
791- // palette_mode_flag = 1.
792- cabac.encode_decision(&mut w, &mut ctx.palette_mode_flag[0], 1);
793-
794- let cu = encode_palette_cu(&mut cabac, &mut w, &mut ctx, &mut predictor, plan);
795-
796- // Reference reconstruction into the expected planes (§8.4.4.2.7
797- // with the exact-at-QP-4 escape dequantization).
798- crate::palette::reconstruct_palette_component(
799- &cu,
800- 0,
801- 1,
802- 1,
803- SLICE_QP,
804- 8,
805- plan.bypass,
806- |x, y, v| {
807- y_plane[(y0 + y) * width + x0 + x] = v as u8;
808- },
809- );
810- crate::palette::reconstruct_palette_component(
811- &cu,
812- 1,
813- 2,
814- 2,
815- SLICE_QP,
816- 8,
817- plan.bypass,
818- |x, y, v| {
819- cb_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8;
820- },
821- );
822- crate::palette::reconstruct_palette_component(
823- &cu,
824- 2,
825- 2,
826- 2,
827- SLICE_QP,
828- 8,
829- plan.bypass,
830- |x, y, v| {
831- cr_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8;
832- },
833- );
834-
835- cabac.encode_terminate(&mut w, u8::from(ctb == 11));
836- }
837- w.align_zero();
838- let slice = w.finish();
839-
840- let units = vec![
841- nal_unit(32, 0, 0, &{
842- // Reuse the Rext VPS shape (PTL profile bits are opaque to
843- // the decode path).
844- let mut vw = BitWriter::new();
845- vw.put_bits(0, 4);
846- vw.put_bit(1);
847- vw.put_bit(1);
848- vw.put_bits(0, 6);
849- vw.put_bits(0, 3);
850- vw.put_bit(1);
851- vw.put_bits(0xFFFF, 16);
852- write_ptl_rext(&mut vw, 30);
853- vw.put_bit(1);
854- vw.ue(1);
855- vw.ue(0);
856- vw.ue(0);
857- vw.put_bits(0, 6);
858- vw.ue(0);
859- vw.put_bit(0);
860- vw.put_bit(0);
861- vw.rbsp_trailing_bits();
862- vw.finish()
863- }),
864- nal_unit(33, 0, 0, &write_sps_scc(width, height, 30, &[])),
865- nal_unit(34, 0, 0, &write_pps_bypass()),
866- nal_unit(20, 0, 0, &slice), // IDR_N_LP
867- ];
868- (annexb(&units), (y_plane, cb_plane, cr_plane))
869-}
870-
871-/// Second pin: §9.3.2.3 SPS palette predictor INITIALIZERS + per-
872-/// independent-slice predictor re-initialization. A 32x32 picture
873-/// (2x2 CTBs) in TWO independent slices; the SPS carries four
874-/// predictor initializer entries, so every slice starts with a
875-/// four-entry predictor. CU plans: reuse-only palettes from the
876-/// initializers, a MaxPaletteIndex-0 block at the second slice's
877-/// start (proving the re-init), and a 256-run diagonal block whose
878-/// index count exercises the §9.3.3.14 all-ones escape suffix.
879-pub(crate) fn build_palette_init_stream() -> (Vec<u8>, Planes) {
880- const INIT: [[u16; 3]; 4] = [[25, 60, 190], [80, 90, 100], [140, 120, 70], [200, 180, 40]];
881- let (width, height) = (32usize, 32usize);
882- let (cw, ch) = (width / 2, height / 2);
883- let ctbs_x = width / CTB;
884- let n = CTB;
885-
886- let base_predictor = PalettePredictor {
887- entries: [
888- INIT.iter().map(|e| e[0]).collect(),
889- INIT.iter().map(|e| e[1]).collect(),
890- INIT.iter().map(|e| e[2]).collect(),
891- ],
892- };
893-
894- let plans: Vec<CuPlan> = vec![
895- // CTB 0 (slice 1): reuse initializer entries 0 and 2; stripes.
896- CuPlan {
897- reuse: vec![true, false, true, false],
898- new_entries: Default::default(),
899- escape_present: false,
900- transpose: false,
901- bypass: true,
902- index_map: {
903- let mut m = vec![0u8; n * n];
904- for y in 0..n {
905- for x in 0..n {
906- m[y * n + x] = u8::from((x / 4) % 2 == 1);
907- }
908- }
909- m
910- },
911- escape_vals: Default::default(),
912- },
913- // CTB 1 (slice 1): predictor evolved to [i0, i2, i1, i3];
914- // reuse the outer two; horizontal bands.
915- CuPlan {
916- reuse: vec![true, false, false, true],
917- new_entries: Default::default(),
918- escape_present: false,
919- transpose: false,
920- bypass: true,
921- index_map: {
922- let mut m = vec![0u8; n * n];
923- for y in 0..n {
924- for x in 0..n {
925- m[y * n + x] = u8::from(y >= 8);
926- }
927- }
928- m
929- },
930- escape_vals: Default::default(),
931- },
932- // CTB 2 (slice 2, FIRST CU): the predictor must be the
933- // re-initialized four initializer entries again — reuse entry
934- // 1 only (MaxPaletteIndex == 0 degenerate block).
935- CuPlan {
936- reuse: vec![false, true, false, false],
937- new_entries: Default::default(),
938- escape_present: false,
939- transpose: false,
940- bypass: true,
941- index_map: vec![0u8; n * n],
942- escape_vals: Default::default(),
943- },
944- // CTB 3 (slice 2): reuse all four evolved entries; diagonal
945- // (x + y) % 4 texture — 256 single-sample explicit runs, so
946- // num_palette_indices_minus1 = 255 takes the §9.3.3.14
947- // all-ones prefix + EGk escape.
948- CuPlan {
949- reuse: vec![true, true, true, true],
950- new_entries: Default::default(),
951- escape_present: false,
952- transpose: false,
953- bypass: true,
954- index_map: {
955- let mut m = vec![0u8; n * n];
956- for y in 0..n {
957- for x in 0..n {
958- m[y * n + x] = ((x + y) % 4) as u8;
959- }
960- }
961- m
962- },
963- escape_vals: Default::default(),
964- },
965- ];
966-
967- let mut y_plane = vec![0u8; width * height];
968- let mut cb_plane = vec![0u8; cw * ch];
969- let mut cr_plane = vec![0u8; cw * ch];
970-
971- // Two independent slices: CTBs [0, 1] and [2, 3].
972- let mut slice_rbsps: Vec<Vec<u8>> = Vec::new();
973- for (slice_idx, ctbs) in [[0usize, 1], [2, 3]].iter().enumerate() {
974- let mut w = BitWriter::new();
975- let first = slice_idx == 0;
976- w.put_bit(u8::from(first)); // first_slice_segment_in_pic_flag
977- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
978- w.ue(0); // slice_pic_parameter_set_id
979- if !first {
980- // slice_segment_address: Ceil(Log2(4)) = 2 bits.
981- w.put_bits(ctbs[0] as u32, 2);
982- }
983- w.ue(2); // slice_type = I
984- w.se(SLICE_QP - 26); // slice_qp_delta
985- w.rbsp_trailing_bits();
986-
987- let mut cabac = CabacEncoder::new();
988- let mut ctx = SliceContexts::init(init_type(2, false), SLICE_QP);
989- // §9.3.2.3 — every independent slice re-initializes the
990- // predictor from the SPS initializers.
991- let mut predictor = base_predictor.clone();
992-
993- for &ctb in ctbs {
994- let x0 = (ctb % ctbs_x) * CTB;
995- let y0 = (ctb / ctbs_x) * CTB;
996- let plan = &plans[ctb];
997- cabac.encode_decision(
998- &mut w,
999- &mut ctx.cu_transquant_bypass_flag[0],
1000- u8::from(plan.bypass),
1001- );
1002- cabac.encode_decision(&mut w, &mut ctx.palette_mode_flag[0], 1);
1003- let cu = encode_palette_cu(&mut cabac, &mut w, &mut ctx, &mut predictor, plan);
1004- crate::palette::reconstruct_palette_component(
1005- &cu,
1006- 0,
1007- 1,
1008- 1,
1009- SLICE_QP,
1010- 8,
1011- plan.bypass,
1012- |x, y, v| {
1013- y_plane[(y0 + y) * width + x0 + x] = v as u8;
1014- },
1015- );
1016- crate::palette::reconstruct_palette_component(
1017- &cu,
1018- 1,
1019- 2,
1020- 2,
1021- SLICE_QP,
1022- 8,
1023- plan.bypass,
1024- |x, y, v| {
1025- cb_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8;
1026- },
1027- );
1028- crate::palette::reconstruct_palette_component(
1029- &cu,
1030- 2,
1031- 2,
1032- 2,
1033- SLICE_QP,
1034- 8,
1035- plan.bypass,
1036- |x, y, v| {
1037- cr_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8;
1038- },
1039- );
1040- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs[1]));
1041- }
1042- w.align_zero();
1043- slice_rbsps.push(w.finish());
1044- }
1045-
1046- let mut units = vec![
1047- nal_unit(32, 0, 0, &{
1048- let mut vw = BitWriter::new();
1049- vw.put_bits(0, 4);
1050- vw.put_bit(1);
1051- vw.put_bit(1);
1052- vw.put_bits(0, 6);
1053- vw.put_bits(0, 3);
1054- vw.put_bit(1);
1055- vw.put_bits(0xFFFF, 16);
1056- write_ptl_rext(&mut vw, 30);
1057- vw.put_bit(1);
1058- vw.ue(1);
1059- vw.ue(0);
1060- vw.ue(0);
1061- vw.put_bits(0, 6);
1062- vw.ue(0);
1063- vw.put_bit(0);
1064- vw.put_bit(0);
1065- vw.rbsp_trailing_bits();
1066- vw.finish()
1067- }),
1068- nal_unit(33, 0, 0, &write_sps_scc(width, height, 30, &INIT)),
1069- nal_unit(34, 0, 0, &write_pps_bypass()),
1070- ];
1071- for rbsp in &slice_rbsps {
1072- units.push(nal_unit(20, 0, 0, rbsp)); // IDR_N_LP
1073- }
1074- (annexb(&units), (y_plane, cb_plane, cr_plane))
1075-}
1076-
1077-#[cfg(test)]
1078-mod tests {
1079- use super::*;
1080- use crate::sequence::decode_annexb_sequence;
1081-
1082- /// SPS predictor initializers + two independent slices: the
1083- /// second slice's first CU must see the re-initialized
1084- /// four-entry predictor (§9.3.2.3), not the first slice's
1085- /// evolved one.
1086- #[test]
1087- fn palette_initializer_stream_decodes_lossless() {
1088- let (stream, (y, cb, cr)) = build_palette_init_stream();
1089- let pinned: &[u8] = include_bytes!(concat!(
1090- env!("CARGO_MANIFEST_DIR"),
1091- "/tests/fixture_bytes/r413-palette-init.hevc"
1092- ));
1093- assert_eq!(stream, pinned, "builder must reproduce the validated bytes");
1094- let frames = decode_annexb_sequence(&stream).expect("decode");
1095- assert_eq!(frames.len(), 1);
1096- let mut expected = y;
1097- expected.extend(cb);
1098- expected.extend(cr);
1099- assert_eq!(
1100- frames[0].picture.to_planar_u8().expect("8-bit planes"),
1101- expected,
1102- "lossless palette decode with SPS initializers"
1103- );
1104- }
1105-
1106- /// The checked-in stream bytes are exactly what the builder
1107- /// produces, and this crate's decoder reconstructs the planned
1108- /// palette content losslessly (predictor reuse, explicit /
1109- /// copy-above runs, run-to-end, MaxPaletteIndex 0, transpose, and
1110- /// bypass + quantized escapes).
1111- #[test]
1112- fn palette_stream_decodes_lossless() {
1113- let (stream, (y, cb, cr)) = build_palette_stream();
1114- let pinned: &[u8] = include_bytes!(concat!(
1115- env!("CARGO_MANIFEST_DIR"),
1116- "/tests/fixture_bytes/r413-palette.hevc"
1117- ));
1118- assert_eq!(stream, pinned, "builder must reproduce the validated bytes");
1119- let frames = decode_annexb_sequence(&stream).expect("decode");
1120- assert_eq!(frames.len(), 1);
1121- let mut expected = y;
1122- expected.extend(cb);
1123- expected.extend(cr);
1124- assert_eq!(
1125- frames[0].picture.to_planar_u8().expect("8-bit planes"),
1126- expected,
1127- "lossless palette decode"
1128- );
1129- }
1130-}
vendor/oxideav-h265/src/encoder/pcm.rsdeleted+0 -1150
@@ -1,1150 +0,0 @@
1-//! PCM-only IDR encoder — the crate's encoder bootstrap.
2-//!
3-//! Emits fully conformant Main-profile Annex B access units in which
4-//! every coding unit is a `pcm_flag == 1` PCM block (§7.3.8.7): the
5-//! samples ride uncompressed inside the slice data, so the decode is
6-//! exactly lossless. The geometry is fixed at the simplest legal
7-//! shape: `CtbSizeY == MinCbSizeY == 16` with the PCM size range
8-//! pinned to 16 (`Log2MinIpcmCbSizeY == Log2MaxIpcmCbSizeY == 4`), so
9-//! every CTB is one unsplit coding unit and the whole §7.3.8 syntax
10-//! walk per CTB is: `part_mode` (one context-coded bin, `PART_2Nx2N`),
11-//! `pcm_flag` (a §9.3.5.6 terminate bin), the `pcm_alignment_zero_bit`
12-//! run, the raw §7.3.8.7 sample payload, the §9.3.5.2 engine re-init,
13-//! and `end_of_slice_segment_flag`.
14-//!
15-//! Every picture is an IDR (`IDR_N_LP`) with in-band VPS/SPS/PPS, so
16-//! the stream is seekable anywhere and decoder-stateless. 4:2:0 8-bit
17-//! only; picture dimensions must be multiples of 16 (the CTB size —
18-//! this bootstrap writes no conformance-window cropping).
19-//!
20-//! In-loop filters are neutralized the conformant way: SAO off in the
21-//! SPS, deblocking disabled in the PPS, and
22-//! `pcm_loop_filter_disabled_flag == 1` — a PCM-only picture
23-//! reconstructs to the raw samples bit for bit.
24-
25-use crate::availability::{PictureTiling, TilingParams};
26-use crate::cabac::init_type;
27-use crate::ctx_init::SliceContexts;
28-use crate::encoder::bitwriter::BitWriter;
29-use crate::encoder::cabac::CabacEncoder;
30-use crate::encoder::nal::{annexb, nal_unit};
31-
32-/// The fixed CTB / coding-block / PCM-block log2 size of this encoder.
33-const CTB_LOG2: u32 = 4;
34-/// The fixed CTB size (16).
35-const CTB: usize = 1 << CTB_LOG2;
36-/// `SliceQpY` written in every slice header (`slice_qp_delta == 0`
37-/// over `init_qp_minus26 == 0`). PCM blocks carry no residual, so the
38-/// QP only seeds context initialization.
39-const SLICE_QP: i32 = 26;
40-
41-/// Per-AU shape options for the PCM encoder.
42-#[derive(Debug, Clone)]
43-pub struct PcmAuOptions {
44- /// Number of slice segments (1 = a single independent segment;
45- /// more = one independent + N−1 dependent segments). Ignored when
46- /// [`Self::independent_slices`] is non-empty.
47- pub segments: usize,
48- /// Independent slices as `(start_ctb, slice_loop_filter_across_
49- /// slices_enabled_flag)` pairs (sorted, first start 0). Empty =
50- /// the [`Self::segments`] split. Heterogeneous per-slice flags
51- /// exercise the §8.7.2.1 / §8.7.3.2 per-slice boundary gates.
52- pub independent_slices: Vec<(usize, bool)>,
53- /// Enable the §8.7.2 deblocking filter (PPS
54- /// `pps_deblocking_filter_disabled_flag == 0`). With every CU a
55- /// PCM block and `pcm_loop_filter_disabled_flag == 1`, a
56- /// conforming decoder must leave all samples untouched — this
57- /// exercises the §8.7.2.5.4 `nDp`/`nDq` PCM suppression.
58- pub deblocking: bool,
59- /// Enable luma band-offset SAO (SPS SAO on,
60- /// `slice_sao_luma_flag == 1`, per-CTB §7.3.8.3 band parameters
61- /// with non-zero offsets).
62- pub sao_luma_band: bool,
63- /// Enable luma vertical-class edge-offset SAO (`sao_type_idx_luma
64- /// == 2`, `sao_eo_class_luma == 1`): the classification reads
65- /// above / below neighbours, exercising the §8.7.3.2 cross-slice
66- /// availability at horizontal slice boundaries. Mutually exclusive
67- /// with [`Self::sao_luma_band`].
68- pub sao_luma_eo_vertical: bool,
69- /// `pcm_loop_filter_disabled_flag` (§7.4.3.2.1). `false` lets the
70- /// enabled loop filters modify the PCM samples like any other CU's.
71- pub pcm_loop_filter_disabled: bool,
72- /// Tile grid as `(columns, rows)` — `tiles_enabled_flag == 1` with
73- /// `uniform_spacing_flag == 1` and
74- /// `loop_filter_across_tiles_enabled_flag == 0`. The picture is
75- /// coded as ONE slice segment whose CTBs walk the §6.5.1 tile scan:
76- /// every tile is its own §7.3.8.1 subset (`end_of_subset_one_bit` +
77- /// byte alignment between tiles, §9.3.2.2 context re-initialization
78- /// at each tile start) and the slice header carries the §7.4.7.1
79- /// `entry_point_offset_minus1[]` block. Requires `columns * rows >=
80- /// 2`; incompatible with multi-segment / SAO options.
81- pub tiles: Option<(u32, u32)>,
82-}
83-
84-impl Default for PcmAuOptions {
85- fn default() -> Self {
86- Self {
87- segments: 1,
88- independent_slices: Vec::new(),
89- deblocking: false,
90- sao_luma_band: false,
91- sao_luma_eo_vertical: false,
92- pcm_loop_filter_disabled: true,
93- tiles: None,
94- }
95- }
96-}
97-
98-/// Errors from the PCM encoder.
99-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
100-pub enum PcmEncodeError {
101- /// Width or height is zero or not a multiple of the 16-sample CTB.
102- BadDimensions {
103- /// Requested luma width.
104- width: usize,
105- /// Requested luma height.
106- height: usize,
107- },
108- /// A supplied plane's length does not match the 4:2:0 geometry.
109- PlaneSize {
110- /// Which plane (`"y"`, `"cb"`, `"cr"`).
111- plane: &'static str,
112- /// Required sample count.
113- expected: usize,
114- /// Supplied sample count.
115- got: usize,
116- },
117-}
118-
119-impl core::fmt::Display for PcmEncodeError {
120- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
121- match self {
122- Self::BadDimensions { width, height } => write!(
123- f,
124- "PCM encoder requires nonzero dimensions that are multiples of 16, got {width}x{height}"
125- ),
126- Self::PlaneSize {
127- plane,
128- expected,
129- got,
130- } => write!(f, "{plane} plane has {got} samples, expected {expected}"),
131- }
132- }
133-}
134-
135-impl std::error::Error for PcmEncodeError {}
136-
137-/// Table A.8 — pick the smallest `general_level_idc` whose `MaxLumaPs`
138-/// covers the picture. (A PCM payload can exceed a level's bit-rate
139-/// ceilings for large / high-rate content; this bootstrap levels by
140-/// luma picture size, the binding constraint for its intended
141-/// small-picture use.)
142-pub(crate) fn level_idc_for(luma_ps: usize) -> u8 {
143- const LEVELS: [(usize, u8); 9] = [
144- (36_864, 30), // 1
145- (122_880, 60), // 2
146- (245_760, 63), // 2.1
147- (552_960, 90), // 3
148- (983_040, 93), // 3.1
149- (2_228_224, 120), // 4
150- (8_912_896, 150), // 5
151- (35_651_584, 180), // 6
152- (usize::MAX, 186), // 6.2
153- ];
154- LEVELS
155- .iter()
156- .find(|(max_ps, _)| luma_ps <= *max_ps)
157- .map(|&(_, idc)| idc)
158- .unwrap_or(186)
159-}
160-
161-/// Table A.8 — the smallest `general_level_idc` whose `MaxTileCols` /
162-/// `MaxTileRows` cover the requested tile grid (§A.4.2 item f:
163-/// `num_tile_columns_minus1 < MaxTileCols`, `num_tile_rows_minus1 <
164-/// MaxTileRows`). This bootstrap's tiny tiles can undercut the
165-/// 256-sample minimum tile-column width; the level is chosen by tile
166-/// count, the constraint a decoder actually dispatches on.
167-fn level_idc_for_tiles(cols: u32, rows: u32) -> u8 {
168- const LEVELS: [(u32, u32, u8); 6] = [
169- (1, 1, 30), // 1 .. 2.1
170- (2, 2, 90), // 3
171- (3, 3, 93), // 3.1
172- (5, 5, 120), // 4 / 4.1
173- (10, 11, 150), // 5 .. 5.2
174- (20, 22, 180), // 6 .. 6.2
175- ];
176- LEVELS
177- .iter()
178- .find(|&&(c, r, _)| cols <= c && rows <= r)
179- .map(|&(_, _, idc)| idc)
180- .unwrap_or(180)
181-}
182-
183-/// §7.3.3 `profile_tier_level( 1, 0 )` — Main profile, Main tier.
184-pub(crate) fn write_ptl(w: &mut BitWriter, level_idc: u8) {
185- w.put_bits(0, 2); // general_profile_space
186- w.put_bit(0); // general_tier_flag
187- w.put_bits(1, 5); // general_profile_idc = 1 (Main)
188- // general_profile_compatibility_flag[0..32]: Main (1) is also
189- // decodable by Main 10 (2) decoders.
190- let mut compat: u32 = 0;
191- compat |= 1 << (31 - 1); // flag[1] — Main
192- compat |= 1 << (31 - 2); // flag[2] — Main 10
193- w.put_bits(compat, 32);
194- w.put_bit(1); // general_progressive_source_flag
195- w.put_bit(0); // general_interlaced_source_flag
196- w.put_bit(1); // general_non_packed_constraint_flag
197- w.put_bit(1); // general_frame_only_constraint_flag
198- // Main profile: general_reserved_zero_43bits.
199- w.put_bits(0, 32);
200- w.put_bits(0, 11);
201- // Profile 1: general_inbld_flag = 0.
202- w.put_bit(0);
203- w.put_bits(u32::from(level_idc), 8); // general_level_idc
204- // max_sub_layers_minus1 == 0: no sub-layer PTL syntax.
205-}
206-
207-/// §7.3.2.1 — the minimal single-layer VPS.
208-pub(crate) fn write_vps(level_idc: u8) -> Vec<u8> {
209- write_vps_cfg(level_idc, 1, 0)
210-}
211-
212-/// [`write_vps`] with explicit `vps_max_dec_pic_buffering_minus1[0]` /
213-/// `vps_max_num_reorder_pics[0]` (the hierarchical-B encoder holds
214-/// more references and reorders output).
215-pub(crate) fn write_vps_cfg(
216- level_idc: u8,
217- max_dec_pic_buffering_minus1: u32,
218- max_num_reorder_pics: u32,
219-) -> Vec<u8> {
220- let mut w = BitWriter::new();
221- w.put_bits(0, 4); // vps_video_parameter_set_id
222- w.put_bit(1); // vps_base_layer_internal_flag
223- w.put_bit(1); // vps_base_layer_available_flag
224- w.put_bits(0, 6); // vps_max_layers_minus1
225- w.put_bits(0, 3); // vps_max_sub_layers_minus1
226- w.put_bit(1); // vps_temporal_id_nesting_flag
227- w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits
228- write_ptl(&mut w, level_idc);
229- w.put_bit(1); // vps_sub_layer_ordering_info_present_flag
230- w.ue(max_dec_pic_buffering_minus1); // vps_max_dec_pic_buffering_minus1[0]
231- w.ue(max_num_reorder_pics); // vps_max_num_reorder_pics[0]
232- w.ue(0); // vps_max_latency_increase_plus1[0]
233- w.put_bits(0, 6); // vps_max_layer_id
234- w.ue(0); // vps_num_layer_sets_minus1
235- w.put_bit(0); // vps_timing_info_present_flag
236- w.put_bit(0); // vps_extension_flag
237- w.rbsp_trailing_bits();
238- w.finish()
239-}
240-
241-/// §7.3.2.2 — the fixed-geometry SPS (4:2:0, 8-bit, CTB 16, PCM on).
242-fn write_sps(
243- width: usize,
244- height: usize,
245- level_idc: u8,
246- sao_enabled: bool,
247- pcm_loop_filter_disabled: bool,
248-) -> Vec<u8> {
249- let mut w = BitWriter::new();
250- w.put_bits(0, 4); // sps_video_parameter_set_id
251- w.put_bits(0, 3); // sps_max_sub_layers_minus1
252- w.put_bit(1); // sps_temporal_id_nesting_flag
253- write_ptl(&mut w, level_idc);
254- w.ue(0); // sps_seq_parameter_set_id
255- w.ue(1); // chroma_format_idc = 4:2:0
256- w.ue(width as u32); // pic_width_in_luma_samples
257- w.ue(height as u32); // pic_height_in_luma_samples
258- w.put_bit(0); // conformance_window_flag
259- w.ue(0); // bit_depth_luma_minus8
260- w.ue(0); // bit_depth_chroma_minus8
261- w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
262- w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
263- w.ue(1); // sps_max_dec_pic_buffering_minus1[0]
264- w.ue(0); // sps_max_num_reorder_pics[0]
265- w.ue(0); // sps_max_latency_increase_plus1[0]
266- w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16)
267- w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16)
268- w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
269- w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
270- w.ue(0); // max_transform_hierarchy_depth_inter
271- w.ue(0); // max_transform_hierarchy_depth_intra
272- w.put_bit(0); // scaling_list_enabled_flag
273- w.put_bit(0); // amp_enabled_flag
274- w.put_bit(u8::from(sao_enabled)); // sample_adaptive_offset_enabled_flag
275- w.put_bit(1); // pcm_enabled_flag
276- w.put_bits(7, 4); // pcm_sample_bit_depth_luma_minus1 (8-bit)
277- w.put_bits(7, 4); // pcm_sample_bit_depth_chroma_minus1
278- w.ue(CTB_LOG2 - 3); // log2_min_pcm_luma_coding_block_size_minus3 (16)
279- w.ue(0); // log2_diff_max_min_pcm_luma_coding_block_size
280- w.put_bit(u8::from(pcm_loop_filter_disabled)); // pcm_loop_filter_disabled_flag
281- w.ue(0); // num_short_term_ref_pic_sets
282- w.put_bit(0); // long_term_ref_pics_present_flag
283- w.put_bit(0); // sps_temporal_mvp_enabled_flag
284- w.put_bit(0); // strong_intra_smoothing_enabled_flag
285- w.put_bit(0); // vui_parameters_present_flag
286- w.put_bit(0); // sps_extension_present_flag
287- w.rbsp_trailing_bits();
288- w.finish()
289-}
290-
291-/// §7.3.2.3 — the all-defaults PPS (deblocking disabled), optionally
292-/// with a uniform tile grid (`tiles_enabled_flag == 1`,
293-/// `uniform_spacing_flag == 1`,
294-/// `loop_filter_across_tiles_enabled_flag == 0`).
295-pub(crate) fn write_pps(
296- dependent_slice_segments_enabled: bool,
297- deblocking_enabled: bool,
298- tiles: Option<(u32, u32)>,
299-) -> Vec<u8> {
300- write_pps_lf(
301- dependent_slice_segments_enabled,
302- deblocking_enabled,
303- false,
304- tiles,
305- )
306-}
307-
308-/// [`write_pps`] with `deblocking_filter_override_enabled_flag`
309-/// control: the loop-filter encoders write the PPS with
310-/// `pps_deblocking_filter_disabled_flag == 1` +
311-/// `deblocking_filter_override_enabled_flag == 1` so every slice
312-/// elects deblocking on/off itself (§7.3.6.1 override group).
313-pub(crate) fn write_pps_lf(
314- dependent_slice_segments_enabled: bool,
315- deblocking_enabled: bool,
316- deblocking_override_enabled: bool,
317- tiles: Option<(u32, u32)>,
318-) -> Vec<u8> {
319- let mut w = BitWriter::new();
320- w.ue(0); // pps_pic_parameter_set_id
321- w.ue(0); // pps_seq_parameter_set_id
322- w.put_bit(u8::from(dependent_slice_segments_enabled)); // dependent_slice_segments_enabled_flag
323- w.put_bit(0); // output_flag_present_flag
324- w.put_bits(0, 3); // num_extra_slice_header_bits
325- w.put_bit(0); // sign_data_hiding_enabled_flag
326- w.put_bit(0); // cabac_init_present_flag
327- w.ue(0); // num_ref_idx_l0_default_active_minus1
328- w.ue(0); // num_ref_idx_l1_default_active_minus1
329- w.se(SLICE_QP - 26); // init_qp_minus26
330- w.put_bit(0); // constrained_intra_pred_flag
331- w.put_bit(0); // transform_skip_enabled_flag
332- w.put_bit(0); // cu_qp_delta_enabled_flag
333- w.se(0); // pps_cb_qp_offset
334- w.se(0); // pps_cr_qp_offset
335- w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag
336- w.put_bit(0); // weighted_pred_flag
337- w.put_bit(0); // weighted_bipred_flag
338- w.put_bit(0); // transquant_bypass_enabled_flag
339- w.put_bit(u8::from(tiles.is_some())); // tiles_enabled_flag
340- w.put_bit(0); // entropy_coding_sync_enabled_flag
341- if let Some((cols, rows)) = tiles {
342- w.ue(cols - 1); // num_tile_columns_minus1
343- w.ue(rows - 1); // num_tile_rows_minus1
344- w.put_bit(1); // uniform_spacing_flag
345- w.put_bit(0); // loop_filter_across_tiles_enabled_flag
346- }
347- w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag
348- w.put_bit(1); // deblocking_filter_control_present_flag
349- w.put_bit(u8::from(deblocking_override_enabled)); // deblocking_filter_override_enabled_flag
350- w.put_bit(u8::from(!deblocking_enabled)); // pps_deblocking_filter_disabled_flag
351- if deblocking_enabled {
352- w.se(0); // pps_beta_offset_div2
353- w.se(0); // pps_tc_offset_div2
354- }
355- w.put_bit(0); // pps_scaling_list_data_present_flag
356- w.put_bit(0); // lists_modification_present_flag
357- w.ue(0); // log2_parallel_merge_level_minus2
358- w.put_bit(0); // slice_segment_header_extension_present_flag
359- w.put_bit(0); // pps_extension_present_flag
360- w.rbsp_trailing_bits();
361- w.finish()
362-}
363-
364-/// §7.3.6.1 + §7.3.8.1 — the picture's slice segments: one
365-/// independent I-slice segment followed by `segments − 1` dependent
366-/// slice segments (§7.4.7.1 inheritance), every CTB a PCM coding
367-/// unit. Returns one RBSP per segment.
368-///
369-/// The CABAC context variables carry across the segment boundary per
370-/// §9.3.1 / §9.3.2.4 (`TableStateIdxDs` storage at each segment's
371-/// `end_of_slice_segment_flag == 1`, §9.3.2.5 synchronization at the
372-/// next dependent segment's start) — each segment gets a fresh
373-/// §9.3.5.2 arithmetic engine over the shared context state.
374-fn write_idr_slice_segments(
375- y: &[u8],
376- cb: &[u8],
377- cr: &[u8],
378- width: usize,
379- height: usize,
380- opts: &PcmAuOptions,
381-) -> Vec<Vec<u8>> {
382- let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical;
383- let ctbs_x = width / CTB;
384- let ctbs_y = height / CTB;
385- let total = ctbs_x * ctbs_y;
386- // Ceil(Log2(PicSizeInCtbsY)) — the slice_segment_address width.
387- let addr_bits = (usize::BITS - (total - 1).leading_zeros()).max(1) as u8;
388-
389- // Segment plan: (start_ctb, Some(across_flag) for an independent
390- // slice header / None for a dependent segment).
391- let plan: Vec<(usize, Option<bool>)> = if opts.independent_slices.is_empty() {
392- // Even split; segment 0 independent, the rest dependent.
393- let seg_len = total.div_ceil(opts.segments);
394- (0..opts.segments)
395- .map(|i| (i * seg_len, (i == 0).then_some(true)))
396- .collect()
397- } else {
398- opts.independent_slices
399- .iter()
400- .map(|&(start, across)| (start, Some(across)))
401- .collect()
402- };
403- let dependent_mode = opts.independent_slices.is_empty() && opts.segments > 1;
404-
405- // initType 0 (I slice, equation 9-7), SliceQpY = 26. Carried across
406- // dependent segments (§9.3.2.4 / §9.3.2.5); re-initialized at each
407- // independent slice.
408- let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
409- // Start CTB of the current independent slice (SAO merge / left
410- // availability is denied across independent slices).
411- let mut cur_slice_start = 0usize;
412-
413- let mut out = Vec::with_capacity(plan.len());
414- for (seg_idx, &(start, indep)) in plan.iter().enumerate() {
415- let end = plan.get(seg_idx + 1).map_or(total, |&(next, _)| next);
416- let mut w = BitWriter::new();
417-
418- // ---- slice_segment_header() ----
419- let first = seg_idx == 0;
420- w.put_bit(u8::from(first)); // first_slice_segment_in_pic_flag
421- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
422- w.ue(0); // slice_pic_parameter_set_id
423- if !first {
424- if dependent_mode {
425- w.put_bit(1); // dependent_slice_segment_flag
426- }
427- w.put_bits(start as u32, addr_bits); // slice_segment_address
428- }
429- if let Some(across) = indep {
430- // Independent slice: fresh CABAC contexts (§9.3.2.2) and a
431- // full slice-level header.
432- ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
433- cur_slice_start = start;
434- w.ue(2); // slice_type = I
435- if sao {
436- // SPS SAO enabled: the slice SAO flags are present.
437- w.put_bit(1); // slice_sao_luma_flag
438- w.put_bit(0); // slice_sao_chroma_flag (4:2:0 present)
439- }
440- w.se(SLICE_QP - 26); // slice_qp_delta
441- if opts.deblocking || sao {
442- // §7.3.6.1 gate: pps_loop_filter_across_slices == 1 and
443- // (SAO on or deblocking not disabled).
444- w.put_bit(u8::from(across)); // slice_loop_filter_across_slices_enabled_flag
445- }
446- }
447- // No tiles / WPP: no entry points. No header extension.
448- w.rbsp_trailing_bits(); // byte_alignment() before slice data
449-
450- // ---- slice_segment_data() ----
451- let mut cabac = CabacEncoder::new();
452- for addr in start..end {
453- let x0 = (addr % ctbs_x) * CTB;
454- let y0 = (addr / ctbs_x) * CTB;
455- if sao {
456- // §7.3.8.3 sao( rx, ry ): decline the available merges
457- // (left / above must lie in the same slice + tile),
458- // then explicit luma parameters.
459- let (rx, ry) = (addr % ctbs_x, addr / ctbs_x);
460- if rx > 0 && addr > cur_slice_start {
461- cabac.encode_decision(&mut w, &mut ctxs.sao_merge_flag[0], 0);
462- }
463- if ry > 0 && addr - ctbs_x >= cur_slice_start {
464- cabac.encode_decision(&mut w, &mut ctxs.sao_merge_flag[0], 0);
465- }
466- if opts.sao_luma_band {
467- // sao_type_idx_luma = 1 (band): TR bins "1" (ctx),
468- // "0" (bypass).
469- cabac.encode_decision(&mut w, &mut ctxs.sao_type_idx[0], 1);
470- cabac.encode_bypass(&mut w, 0);
471- // sao_offset_abs[0][i] — TR(cMax 7, bypass): values
472- // 1, 2, 3, 4.
473- for v in 1..=4u32 {
474- for _ in 0..v {
475- cabac.encode_bypass(&mut w, 1);
476- }
477- cabac.encode_bypass(&mut w, 0); // v < cMax terminator
478- }
479- // sao_offset_sign[0][i]: +, −, +, −.
480- for sign in [0u8, 1, 0, 1] {
481- cabac.encode_bypass(&mut w, sign);
482- }
483- // sao_band_position[0]: FL(5) = 8.
484- cabac.encode_bypass_bits(&mut w, 8, 5);
485- } else {
486- // sao_type_idx_luma = 2 (edge): TR bins "1" (ctx),
487- // "1" (bypass).
488- cabac.encode_decision(&mut w, &mut ctxs.sao_type_idx[0], 1);
489- cabac.encode_bypass(&mut w, 1);
490- // sao_offset_abs[0][i]: 1, 2, 1, 2 (edge offsets
491- // carry implicit signs per §7.4.9.3).
492- for v in [1u32, 2, 1, 2] {
493- for _ in 0..v {
494- cabac.encode_bypass(&mut w, 1);
495- }
496- cabac.encode_bypass(&mut w, 0);
497- }
498- // sao_eo_class_luma: FL(2) = 1 (vertical — reads
499- // the above / below neighbours).
500- cabac.encode_bypass_bits(&mut w, 1, 2);
501- }
502- }
503- write_pcm_ctu(&mut w, &mut cabac, &mut ctxs, y, cb, cr, width, x0, y0);
504- // end_of_slice_segment_flag: 1 only at the segment's last CTB.
505- cabac.encode_terminate(&mut w, u8::from(addr == end - 1));
506- }
507- // The final terminate-1 flush wrote the rbsp_stop_one_bit;
508- // rbsp_slice_segment_trailing_bits() is alignment zeros from here.
509- w.align_zero();
510- out.push(w.finish());
511- }
512- out
513-}
514-
515-/// §7.3.8.2 + §7.3.8.5 — one all-PCM CTB (`CtbLog2SizeY ==
516-/// MinCbLog2SizeY`, so the coding quadtree is the single unsplit CU):
517-/// `part_mode` (§9.3.3.7 bin "1" = `PART_2Nx2N`), `pcm_flag` (a
518-/// §9.3.5.6 terminate bin — value 1 flushes the codeword), the
519-/// `pcm_alignment_zero_bit` run, the raw §7.3.8.7 samples (luma then
520-/// Cb, Cr), and the §9.3.5.2 engine re-initialization.
521-#[allow(clippy::too_many_arguments)]
522-fn write_pcm_ctu(
523- w: &mut BitWriter,
524- cabac: &mut CabacEncoder,
525- ctxs: &mut SliceContexts,
526- y: &[u8],
527- cb: &[u8],
528- cr: &[u8],
529- width: usize,
530- x0: usize,
531- y0: usize,
532-) {
533- let cw = width / 2;
534- cabac.encode_decision(w, &mut ctxs.part_mode[0], 1);
535- cabac.encode_terminate(w, 1);
536- w.align_zero();
537- for j in 0..CTB {
538- for i in 0..CTB {
539- w.put_bits(u32::from(y[(y0 + j) * width + x0 + i]), 8);
540- }
541- }
542- let (cx, cy) = (x0 / 2, y0 / 2);
543- for plane in [cb, cr] {
544- for j in 0..CTB / 2 {
545- for i in 0..CTB / 2 {
546- w.put_bits(u32::from(plane[(cy + j) * cw + cx + i]), 8);
547- }
548- }
549- }
550- cabac.reinit();
551-}
552-
553-/// §7.4.1.1 — the coded (emulation-prevention-escaped) byte length of
554-/// `bytes`, given the zero-run carried in from the preceding coded
555-/// bytes. Returns the length and the carry-out zero run. The dual of
556-/// the counting the §7.4.7.1 `entry_point_offset_minus1[i]` values
557-/// perform over the coded slice-segment data.
558-fn escaped_len(bytes: &[u8], mut zero_run: u32) -> (usize, u32) {
559- let mut len = 0usize;
560- for &b in bytes {
561- if zero_run >= 2 && b <= 0x03 {
562- len += 1; // emulation_prevention_three_byte
563- zero_run = 0;
564- }
565- len += 1;
566- if b == 0 {
567- zero_run += 1;
568- } else {
569- zero_run = 0;
570- }
571- }
572- (len, zero_run)
573-}
574-
575-/// §7.3.6.1 + §7.3.8.1 — the tiled picture as ONE independent I-slice
576-/// segment whose CTBs walk the §6.5.1 tile scan. Every tile is its own
577-/// subset: fresh §9.3.2.2 contexts and a fresh §9.3.5.2 arithmetic
578-/// engine at each tile start, `end_of_subset_one_bit` + byte alignment
579-/// after every tile but the last, and the §7.4.7.1
580-/// `entry_point_offset_minus1[]` block (offsets in CODED bytes,
581-/// emulation-prevention included) in the slice header.
582-fn write_tiled_idr_slice(
583- y: &[u8],
584- cb: &[u8],
585- cr: &[u8],
586- width: usize,
587- height: usize,
588- opts: &PcmAuOptions,
589-) -> Vec<u8> {
590- let (cols, rows) = opts.tiles.expect("caller checked the tile grid");
591- let ctbs_x = width / CTB;
592- let ctbs_y = height / CTB;
593- let total = ctbs_x * ctbs_y;
594- let tiling = PictureTiling::new(
595- ctbs_x as u32,
596- ctbs_y as u32,
597- width as u32,
598- height as u32,
599- CTB_LOG2,
600- 2, // MinTbLog2SizeY (SPS: log2_min_luma_transform_block_size = 4)
601- &TilingParams {
602- num_tile_columns_minus1: cols - 1,
603- num_tile_rows_minus1: rows - 1,
604- uniform_spacing_flag: true,
605- column_width_minus1: Vec::new(),
606- row_height_minus1: Vec::new(),
607- },
608- )
609- .expect("validated tile geometry");
610-
611- // ---- slice_segment_data( ), one coded subset per tile ----
612- let mut subsets: Vec<Vec<u8>> = Vec::new();
613- let mut w = BitWriter::new();
614- let mut cabac = CabacEncoder::new();
615- let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
616- for ts in 0..total as u32 {
617- let rs = tiling.ctb_addr_ts_to_rs(ts) as usize;
618- let x0 = (rs % ctbs_x) * CTB;
619- let y0 = (rs / ctbs_x) * CTB;
620- write_pcm_ctu(&mut w, &mut cabac, &mut ctxs, y, cb, cr, width, x0, y0);
621- let last_of_pic = ts == total as u32 - 1;
622- // end_of_slice_segment_flag: 1 only at the picture's last CTB.
623- cabac.encode_terminate(&mut w, u8::from(last_of_pic));
624- let last_of_tile = last_of_pic || tiling.tile_id(ts + 1) != tiling.tile_id(ts);
625- if last_of_tile {
626- if !last_of_pic {
627- // §7.3.8.1 end_of_subset_one_bit (terminate-1 flush).
628- cabac.encode_terminate(&mut w, 1);
629- }
630- // byte_alignment( ) — the flush wrote the trailing one bit.
631- w.align_zero();
632- subsets.push(std::mem::take(&mut w).finish());
633- // §9.3.2.2 — fresh contexts + engine at the next tile start.
634- cabac = CabacEncoder::new();
635- ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
636- }
637- }
638-
639- // §7.4.7.1 — entry_point_offset_minus1[i] counts CODED bytes; the
640- // emulation-prevention zero-run threads across subset boundaries
641- // (the slice header's byte_alignment one-bit makes its last byte
642- // nonzero, so the first subset starts with a zero run of 0).
643- let mut offsets: Vec<u32> = Vec::new();
644- let mut zero_run = 0u32;
645- for s in &subsets[..subsets.len() - 1] {
646- let (len, zr) = escaped_len(s, zero_run);
647- zero_run = zr;
648- offsets.push(len as u32 - 1);
649- }
650- let offset_len = offsets
651- .iter()
652- .map(|&o| 32 - o.leading_zeros())
653- .max()
654- .unwrap_or(1)
655- .max(1) as u8;
656-
657- // ---- slice_segment_header( ) ----
658- let mut h = BitWriter::new();
659- h.put_bit(1); // first_slice_segment_in_pic_flag
660- h.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
661- h.ue(0); // slice_pic_parameter_set_id
662- h.ue(2); // slice_type = I
663- h.se(SLICE_QP - 26); // slice_qp_delta
664- if opts.deblocking {
665- // §7.3.6.1 gate: pps_loop_filter_across_slices == 1 and
666- // deblocking not disabled.
667- h.put_bit(1); // slice_loop_filter_across_slices_enabled_flag
668- }
669- // tiles_enabled_flag == 1: the entry-point block is present.
670- h.ue(offsets.len() as u32); // num_entry_point_offsets
671- if !offsets.is_empty() {
672- h.ue(u32::from(offset_len) - 1); // offset_len_minus1
673- for &o in &offsets {
674- h.put_bits(o, offset_len); // entry_point_offset_minus1[i]
675- }
676- }
677- h.rbsp_trailing_bits(); // byte_alignment() before slice data
678- debug_assert_ne!(h.as_bytes().last(), Some(&0), "aligned header byte");
679- for s in &subsets {
680- for &b in s {
681- h.put_bits(u32::from(b), 8);
682- }
683- }
684- h.finish()
685-}
686-
687-/// Encode one 4:2:0 8-bit frame as a self-contained IDR access unit
688-/// (`VPS + SPS + PPS + IDR_N_LP` in Annex B form). The decode is
689-/// bit-exact lossless: every coding unit is a §7.3.8.7 PCM block.
690-///
691-/// # Errors
692-/// [`PcmEncodeError`] when the dimensions are not nonzero multiples of
693-/// 16 or a plane buffer has the wrong length.
694-pub fn encode_idr_pcm_au(
695- y: &[u8],
696- cb: &[u8],
697- cr: &[u8],
698- width: usize,
699- height: usize,
700-) -> Result<Vec<u8>, PcmEncodeError> {
701- encode_au(y, cb, cr, width, height, PcmAuOptions::default())
702-}
703-
704-/// As [`encode_idr_pcm_au`], with the picture split into `segments`
705-/// slice segments: the first independent, the rest §7.3.6.1
706-/// *dependent* slice segments (`dependent_slice_segment_flag == 1`,
707-/// header inherited per §7.4.7.1, CABAC contexts carried across the
708-/// boundary per §9.3.2.4 / §9.3.2.5).
709-///
710-/// # Errors
711-/// [`PcmEncodeError`] as for [`encode_idr_pcm_au`], or
712-/// [`PcmEncodeError::BadDimensions`] when `segments` is 0 or exceeds
713-/// the picture's CTB count.
714-pub fn encode_idr_pcm_au_segmented(
715- y: &[u8],
716- cb: &[u8],
717- cr: &[u8],
718- width: usize,
719- height: usize,
720- segments: usize,
721-) -> Result<Vec<u8>, PcmEncodeError> {
722- encode_au(
723- y,
724- cb,
725- cr,
726- width,
727- height,
728- PcmAuOptions {
729- segments,
730- ..PcmAuOptions::default()
731- },
732- )
733-}
734-
735-/// As [`encode_idr_pcm_au`], with the full [`PcmAuOptions`] shape
736-/// control (slice segmentation, deblocking on, luma band-offset SAO).
737-///
738-/// # Errors
739-/// [`PcmEncodeError`] as for [`encode_idr_pcm_au_segmented`].
740-pub fn encode_idr_pcm_au_opts(
741- y: &[u8],
742- cb: &[u8],
743- cr: &[u8],
744- width: usize,
745- height: usize,
746- opts: PcmAuOptions,
747-) -> Result<Vec<u8>, PcmEncodeError> {
748- encode_au(y, cb, cr, width, height, opts)
749-}
750-
751-fn encode_au(
752- y: &[u8],
753- cb: &[u8],
754- cr: &[u8],
755- width: usize,
756- height: usize,
757- opts: PcmAuOptions,
758-) -> Result<Vec<u8>, PcmEncodeError> {
759- let segments = opts.segments;
760- if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 {
761- return Err(PcmEncodeError::BadDimensions { width, height });
762- }
763- let total_ctbs = (width / CTB) * (height / CTB);
764- if segments == 0 || segments > total_ctbs {
765- return Err(PcmEncodeError::BadDimensions { width, height });
766- }
767- // Independent-slice plans must be sorted, start at CTB 0 and stay
768- // in range; band and edge SAO are mutually exclusive.
769- if !opts.independent_slices.is_empty() {
770- let starts: Vec<usize> = opts.independent_slices.iter().map(|&(s, _)| s).collect();
771- if starts[0] != 0
772- || starts.windows(2).any(|w| w[1] <= w[0])
773- || starts.iter().any(|&s| s >= total_ctbs)
774- {
775- return Err(PcmEncodeError::BadDimensions { width, height });
776- }
777- }
778- if opts.sao_luma_band && opts.sao_luma_eo_vertical {
779- return Err(PcmEncodeError::BadDimensions { width, height });
780- }
781- // Tile grid: at least two tiles, each column/row at least one CTB
782- // wide/tall; the tiled picture is a single slice segment with SAO
783- // off (the tile-scan SAO merge availability is out of this
784- // bootstrap's scope).
785- if let Some((cols, rows)) = opts.tiles {
786- let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical;
787- if cols == 0
788- || rows == 0
789- || cols * rows < 2
790- || cols as usize > width / CTB
791- || rows as usize > height / CTB
792- || segments != 1
793- || !opts.independent_slices.is_empty()
794- || sao
795- {
796- return Err(PcmEncodeError::BadDimensions { width, height });
797- }
798- }
799- let check = |plane: &'static str, buf: &[u8], expected: usize| {
800- if buf.len() != expected {
801- Err(PcmEncodeError::PlaneSize {
802- plane,
803- expected,
804- got: buf.len(),
805- })
806- } else {
807- Ok(())
808- }
809- };
810- check("y", y, width * height)?;
811- check("cb", cb, width * height / 4)?;
812- check("cr", cr, width * height / 4)?;
813-
814- let level_idc = opts.tiles.map_or_else(
815- || level_idc_for(width * height),
816- |(c, r)| level_idc_for(width * height).max(level_idc_for_tiles(c, r)),
817- );
818- let dependent_mode = opts.independent_slices.is_empty() && segments > 1;
819- let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical;
820- let mut units = vec![
821- nal_unit(32, 0, 0, &write_vps(level_idc)), // VPS_NUT
822- nal_unit(
823- 33,
824- 0,
825- 0,
826- &write_sps(width, height, level_idc, sao, opts.pcm_loop_filter_disabled),
827- ), // SPS_NUT
828- nal_unit(
829- 34,
830- 0,
831- 0,
832- &write_pps(dependent_mode, opts.deblocking, opts.tiles),
833- ), // PPS_NUT
834- ];
835- if opts.tiles.is_some() {
836- let rbsp = write_tiled_idr_slice(y, cb, cr, width, height, &opts);
837- units.push(nal_unit(20, 0, 0, &rbsp)); // IDR_N_LP
838- } else {
839- for rbsp in write_idr_slice_segments(y, cb, cr, width, height, &opts) {
840- units.push(nal_unit(20, 0, 0, &rbsp)); // IDR_N_LP
841- }
842- }
843- Ok(annexb(&units))
844-}
845-
846-#[cfg(test)]
847-mod tests {
848- use super::*;
849- use crate::pps::PicParameterSet;
850- use crate::sps::SeqParameterSet;
851-
852- fn gradient_planes(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
853- let y: Vec<u8> = (0..w * h).map(|i| (i * 7 % 251) as u8).collect();
854- let cb: Vec<u8> = (0..w * h / 4).map(|i| (i * 3 % 240 + 8) as u8).collect();
855- let cr: Vec<u8> = (0..w * h / 4).map(|i| (255 - i * 5 % 250) as u8).collect();
856- (y, cb, cr)
857- }
858-
859- #[test]
860- fn rejects_bad_geometry() {
861- let (y, cb, cr) = gradient_planes(16, 16);
862- assert!(matches!(
863- encode_idr_pcm_au(&y, &cb, &cr, 20, 16),
864- Err(PcmEncodeError::BadDimensions { .. })
865- ));
866- assert!(matches!(
867- encode_idr_pcm_au(&y, &cb, &cr, 32, 16),
868- Err(PcmEncodeError::PlaneSize { .. })
869- ));
870- }
871-
872- /// The whole bootstrap contract: encode → decode with the crate's
873- /// own end-to-end driver → bit-exact planes (PCM is lossless).
874- #[test]
875- fn pcm_au_roundtrips_losslessly_through_the_decoder() {
876- for (w, h) in [(16usize, 16usize), (48, 32), (32, 64)] {
877- let (y, cb, cr) = gradient_planes(w, h);
878- let au = encode_idr_pcm_au(&y, &cb, &cr, w, h).expect("encode");
879- let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode");
880- assert_eq!(frames.len(), 1, "{w}x{h}: one IDR frame");
881- let mut expected = Vec::new();
882- expected.extend_from_slice(&y);
883- expected.extend_from_slice(&cb);
884- expected.extend_from_slice(&cr);
885- assert_eq!(
886- frames[0].picture.to_planar_u8().expect("8-bit"),
887- expected,
888- "{w}x{h}: lossless PCM roundtrip"
889- );
890- }
891- }
892-
893- /// Two frames form two self-contained IDR AUs; both decode losslessly
894- /// and in order.
895- #[test]
896- fn multi_frame_pcm_stream_decodes_in_order() {
897- let (y0, cb0, cr0) = gradient_planes(32, 32);
898- let y1: Vec<u8> = y0.iter().map(|&v| v ^ 0x5A).collect();
899- let mut stream = encode_idr_pcm_au(&y0, &cb0, &cr0, 32, 32).expect("au0");
900- stream.extend(encode_idr_pcm_au(&y1, &cb0, &cr0, 32, 32).expect("au1"));
901- let frames = crate::sequence::decode_annexb_sequence(&stream).expect("decode");
902- assert_eq!(frames.len(), 2);
903- let p0 = frames[0].picture.to_planar_u8().unwrap();
904- let p1 = frames[1].picture.to_planar_u8().unwrap();
905- assert_eq!(&p0[..y0.len()], &y0[..]);
906- assert_eq!(&p1[..y1.len()], &y1[..]);
907- assert_ne!(p0, p1);
908- }
909-
910- /// Dependent slice segments: the picture splits into an independent
911- /// segment + dependent segments whose CABAC contexts continue
912- /// across the NAL boundary (§9.3.2.4 / §9.3.2.5) and whose header
913- /// values inherit per §7.4.7.1 — still bit-exact lossless.
914- #[test]
915- fn dependent_slice_segments_roundtrip_losslessly() {
916- let (w, h) = (48usize, 48usize); // 9 CTBs
917- let (y, cb, cr) = gradient_planes(w, h);
918- for segments in [2usize, 3, 9] {
919- let au = encode_idr_pcm_au_segmented(&y, &cb, &cr, w, h, segments).expect("encode");
920- // One IDR NAL per segment behind the parameter sets.
921- let units = crate::nal::collect_nal_units(&au).expect("walk");
922- assert_eq!(units.len(), 3 + segments, "{segments} segments");
923- assert!(units[4..].iter().all(|u| u.header.nal_unit_type == 20));
924- let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode");
925- assert_eq!(frames.len(), 1);
926- let mut expected = Vec::new();
927- expected.extend_from_slice(&y);
928- expected.extend_from_slice(&cb);
929- expected.extend_from_slice(&cr);
930- assert_eq!(
931- frames[0].picture.to_planar_u8().expect("8-bit"),
932- expected,
933- "{segments}-segment lossless roundtrip"
934- );
935- }
936- }
937-
938- /// A dependent segment decoded WITHOUT the preceding segment's
939- /// stored context state is rejected, not misdecoded.
940- #[test]
941- fn dependent_segment_without_predecessor_is_rejected() {
942- let (y, cb, cr) = gradient_planes(32, 32);
943- let au = encode_idr_pcm_au_segmented(&y, &cb, &cr, 32, 32, 2).expect("encode");
944- let units = crate::nal::collect_nal_units(&au).expect("walk");
945- // Drop the independent slice segment (unit 3), keep the
946- // dependent one: the driver must refuse.
947- let mut broken = Vec::new();
948- for (i, u) in units.iter().enumerate() {
949- if i == 3 {
950- continue;
951- }
952- let mut coded = vec![0, 0, 0, 1];
953- coded.extend(crate::encoder::nal::nal_unit(
954- u.header.nal_unit_type,
955- u.header.nuh_layer_id,
956- u.header.temporal_id,
957- &u.rbsp,
958- ));
959- broken.extend(coded);
960- }
961- assert!(crate::sequence::decode_annexb_sequence(&broken).is_err());
962- }
963-
964- /// §8.7.2.5.4 / §8.7.3.1 — with deblocking and luma band-offset
965- /// SAO ENABLED over an all-PCM picture and
966- /// `pcm_loop_filter_disabled_flag == 1`, a conforming decoder must
967- /// leave every reconstructed sample untouched. This pins the
968- /// per-CU loop-filter suppression map end to end (a decoder that
969- /// filtered the PCM samples would corrupt the smooth gradient).
970- #[test]
971- fn pcm_loop_filter_suppression_keeps_samples_exact() {
972- let (w, h) = (48usize, 32usize);
973- let (y, cb, cr) = gradient_planes(w, h);
974- for (deblocking, sao_luma_band) in [(true, false), (false, true), (true, true)] {
975- let opts = PcmAuOptions {
976- segments: 1,
977- deblocking,
978- sao_luma_band,
979- ..PcmAuOptions::default()
980- };
981- let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode");
982- let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode");
983- assert_eq!(frames.len(), 1);
984- let mut expected = Vec::new();
985- expected.extend_from_slice(&y);
986- expected.extend_from_slice(&cb);
987- expected.extend_from_slice(&cr);
988- assert_eq!(
989- frames[0].picture.to_planar_u8().expect("8-bit"),
990- expected,
991- "deblocking={deblocking} sao={sao_luma_band}: PCM samples survive the loop filters"
992- );
993- }
994- }
995-
996- /// Independent multi-slice pictures with heterogeneous per-slice
997- /// `slice_loop_filter_across_slices_enabled_flag` values roundtrip
998- /// through the crate's own decoder (which implements the §8.7.2.1
999- /// per-slice gate), and the opposite flag layouts produce
1000- /// different pictures (the boundary edge filters on exactly one
1001- /// side of the pair).
1002- #[test]
1003- fn independent_slices_with_heterogeneous_across_flags() {
1004- let (w, h) = (48usize, 32usize);
1005- let (y, cb, cr) = gradient_planes(w, h);
1006- let mut decoded = Vec::new();
1007- for flags in [(true, false), (false, true)] {
1008- let opts = PcmAuOptions {
1009- independent_slices: vec![(0, flags.0), (3, flags.1)],
1010- deblocking: true,
1011- pcm_loop_filter_disabled: false,
1012- ..PcmAuOptions::default()
1013- };
1014- let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode");
1015- let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode");
1016- assert_eq!(frames.len(), 1);
1017- decoded.push(frames[0].picture.to_planar_u8().expect("8-bit"));
1018- }
1019- assert_ne!(
1020- decoded[0], decoded[1],
1021- "opposite per-slice flags gate the boundary deblocking differently"
1022- );
1023- }
1024-
1025- /// True multi-tile single-slice streams: the picture walks the
1026- /// §6.5.1 tile scan inside ONE slice segment, every tile its own
1027- /// §7.3.8.1 subset behind a §7.4.7.1 entry-point offset, with the
1028- /// §9.3.2.2 per-tile CABAC context re-initialization on both the
1029- /// encode and decode sides — bit-exact lossless through the
1030- /// crate's own decoder.
1031- #[test]
1032- fn tiled_pcm_au_roundtrips_losslessly() {
1033- for (w, h, cols, rows) in [
1034- (64usize, 48usize, 2u32, 2u32), // uneven rows: 4x3 CTBs / 2x2
1035- (96, 64, 3, 2), // 6x4 CTBs / 3x2
1036- (32, 16, 2, 1), // single tile row
1037- (80, 80, 5, 5), // one CTB per tile
1038- ] {
1039- let (y, cb, cr) = gradient_planes(w, h);
1040- let opts = PcmAuOptions {
1041- tiles: Some((cols, rows)),
1042- ..PcmAuOptions::default()
1043- };
1044- let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode");
1045- let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode");
1046- assert_eq!(frames.len(), 1, "{cols}x{rows}: one IDR frame");
1047- let mut expected = Vec::new();
1048- expected.extend_from_slice(&y);
1049- expected.extend_from_slice(&cb);
1050- expected.extend_from_slice(&cr);
1051- assert_eq!(
1052- frames[0].picture.to_planar_u8().expect("8-bit"),
1053- expected,
1054- "{w}x{h} {cols}x{rows} tiles: lossless roundtrip"
1055- );
1056- }
1057- }
1058-
1059- /// The tiled stream's parameter sets and slice header really carry
1060- /// the tile syntax: `tiles_enabled_flag == 1`, the uniform 2x2
1061- /// grid, and `num_entry_point_offsets == 3` with offsets that
1062- /// partition the coded slice data.
1063- #[test]
1064- fn tiled_pcm_au_signals_tiles_and_entry_points() {
1065- let (w, h) = (64usize, 64usize);
1066- let (y, cb, cr) = gradient_planes(w, h);
1067- let opts = PcmAuOptions {
1068- tiles: Some((2, 2)),
1069- ..PcmAuOptions::default()
1070- };
1071- let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode");
1072- let units = crate::nal::collect_nal_units(&au).expect("walk");
1073- assert_eq!(units.len(), 4);
1074- let sps = SeqParameterSet::parse(&units[1].rbsp).expect("sps");
1075- let pps = PicParameterSet::parse(&units[2].rbsp).expect("pps");
1076- assert!(pps.tiles_enabled_flag);
1077- assert_eq!(pps.tiles.num_tile_columns_minus1, 1);
1078- assert_eq!(pps.tiles.num_tile_rows_minus1, 1);
1079- assert!(pps.tiles.uniform_spacing_flag);
1080- assert!(!pps.loop_filter_across_tiles_enabled_flag);
1081- let header = crate::slice::SliceSegmentHeader::parse(
1082- &units[3].rbsp,
1083- units[3].header.nal_unit_type,
1084- &sps,
1085- &pps,
1086- )
1087- .expect("slice header");
1088- let eps = header.entry_point_offsets.expect("entry points present");
1089- assert_eq!(eps.num_entry_point_offsets, 3);
1090- assert_eq!(eps.entry_point_offset_minus1.len(), 3);
1091- }
1092-
1093- /// Tile-option validation: zero-sized grids, single-tile grids,
1094- /// grids finer than the CTB grid, and combinations with
1095- /// multi-segment or SAO options are rejected.
1096- #[test]
1097- fn tiled_pcm_au_rejects_bad_grids() {
1098- let (y, cb, cr) = gradient_planes(32, 32);
1099- for opts in [
1100- PcmAuOptions {
1101- tiles: Some((1, 1)),
1102- ..PcmAuOptions::default()
1103- },
1104- PcmAuOptions {
1105- tiles: Some((0, 2)),
1106- ..PcmAuOptions::default()
1107- },
1108- PcmAuOptions {
1109- tiles: Some((3, 1)), // 2x2 CTBs: only 2 columns exist
1110- ..PcmAuOptions::default()
1111- },
1112- PcmAuOptions {
1113- tiles: Some((2, 2)),
1114- segments: 2,
1115- ..PcmAuOptions::default()
1116- },
1117- PcmAuOptions {
1118- tiles: Some((2, 2)),
1119- sao_luma_band: true,
1120- ..PcmAuOptions::default()
1121- },
1122- ] {
1123- assert!(
1124- matches!(
1125- encode_idr_pcm_au_opts(&y, &cb, &cr, 32, 32, opts.clone()),
1126- Err(PcmEncodeError::BadDimensions { .. })
1127- ),
1128- "{opts:?}"
1129- );
1130- }
1131- }
1132-
1133- #[test]
1134- fn written_sps_pps_parse_back() {
1135- let (y, cb, cr) = gradient_planes(48, 32);
1136- let au = encode_idr_pcm_au(&y, &cb, &cr, 48, 32).expect("encode");
1137- let units = crate::nal::collect_nal_units(&au).expect("walk");
1138- assert_eq!(units.len(), 4);
1139- let sps = SeqParameterSet::parse(&units[1].rbsp).expect("sps parses");
1140- assert_eq!(sps.pic_width_in_luma_samples, 48);
1141- assert_eq!(sps.pic_height_in_luma_samples, 32);
1142- assert_eq!(sps.chroma_format_idc, 1);
1143- let pcm = sps.pcm.as_ref().expect("pcm block present");
1144- assert_eq!(pcm.bit_depth_luma_minus1, 7);
1145- assert!(pcm.loop_filter_disabled_flag);
1146- let pps = PicParameterSet::parse(&units[2].rbsp).expect("pps parses");
1147- assert!(pps.deblocking_filter_control_present_flag);
1148- assert!(pps.deblocking.disabled_flag);
1149- }
1150-}
vendor/oxideav-h265/src/encoder/pyramid.rsdeleted+0 -720
@@ -1,720 +0,0 @@
1-//! Hierarchical-B GOP encoder — dyadic B pyramids over the §8.5
2-//! inter machinery of [`crate::encoder::inter`].
3-//!
4-//! The sequence shape is one leading IDR followed by dyadic mini-GOPs
5-//! of `gop` frames (a power of two). Within a mini-GOP anchored at
6-//! POC `a`:
7-//!
8-//! * the next anchor `a + gop` is coded FIRST as a P slice (layer 0)
9-//! referencing `a`;
10-//! * every interval `(lo, hi)` then codes its midpoint as a B slice
11-//! whose `RefPicList0` holds the past boundary `lo` and whose
12-//! `RefPicList1` holds the FUTURE boundary `hi` (out-of-order
13-//! coding, decode order ≠ output order), recursing into the two
14-//! halves one pyramid layer deeper.
15-//!
16-//! Every B slice's AMVP election therefore searches L0, L1 and the
17-//! bi combination (see [`crate::encoder::inter`]'s two-sided search),
18-//! and the §8.5.3.2.2 merge candidates carry genuinely bi-directional
19-//! motion. Deeper layers ride a per-layer QP offset (`qp + layer`
20-//! by default) — the classic pyramid rate allocation: the pictures
21-//! referenced most are coded best.
22-//!
23-//! Stream-level signalling:
24-//!
25-//! * `slice_pic_order_cnt_lsb` carries the DISPLAY order; the SPS
26-//! signals `sps_max_num_reorder_pics = log2(gop)` and a DPB bound
27-//! of `log2(gop) + 2` pictures so a conforming decoder reorders
28-//! output correctly;
29-//! * each slice's inline §7.4.8 short-term RPS lists every picture a
30-//! later slice (in decode order) still references — negative AND
31-//! positive pictures — with `used_by_curr_pic` flags marking this
32-//! slice's own active references;
33-//! * reference-list sizes stay 1/1 (the PPS defaults), so no
34-//! `num_ref_idx` override is signalled on the pyramid slices.
35-//!
36-//! Reconstruction stays the decode-side truth: every slice
37-//! reconstructs through the shared [`encode_inter_slice`] pass
38-//! (decode-side prediction, transform and §8.7 in-loop filters), so
39-//! a conforming decoder's output is bit-identical to the encoder's
40-//! per-frame reconstruction — pinned by the roundtrip tests in
41-//! DISPLAY order against [`crate::sequence::decode_annexb_sequence`]
42-//! (which itself outputs §C.5.2.2 output order).
43-//!
44-//! The trailing frames that do not fill a final mini-GOP are coded at
45-//! [`PyramidEncoder::flush`] as a low-delay P chain from the last
46-//! anchor (decode order == display order again).
47-
48-use std::collections::BTreeMap;
49-
50-use crate::encoder::inter::{encode_inter_slice, FrameRecon, FrameStats, SliceSpec, YuvFrame};
51-use crate::encoder::intra::{encode_idr_intra_au_full, IntraEncodeError, SpsCfg};
52-use crate::encoder::loopfilter::LoopFilterCfg;
53-use crate::encoder::nal::{annexb, nal_unit};
54-
55-/// The fixed CTB size shared with the intra / low-delay encoders.
56-const CTB: usize = 16;
57-
58-/// One encoded access unit of the pyramid stream, in DECODE order.
59-#[derive(Debug, Clone)]
60-pub struct PyramidAu {
61- /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP` for the
62- /// leading IDR, one `TRAIL_R` slice otherwise).
63- pub au: Vec<u8>,
64- /// `true` for the leading IDR.
65- pub keyframe: bool,
66- /// The frame's DISPLAY index (== its `PicOrderCntVal`).
67- pub display_order: usize,
68- /// The pyramid layer (0 = the IDR / anchors, deeper B layers up
69- /// to `log2(gop)`).
70- pub layer: u8,
71- /// The frame's reconstruction (== a conforming decoder's output).
72- pub recon: FrameRecon,
73- /// The frame's CU mode-decision counters.
74- pub stats: FrameStats,
75-}
76-
77-/// An owned 4:2:0 frame buffered until its mini-GOP completes.
78-#[derive(Debug)]
79-struct OwnedFrame {
80- y: Vec<u8>,
81- cb: Vec<u8>,
82- cr: Vec<u8>,
83-}
84-
85-impl OwnedFrame {
86- fn as_yuv(&self) -> YuvFrame<'_> {
87- YuvFrame {
88- y: &self.y,
89- cb: &self.cb,
90- cr: &self.cr,
91- }
92- }
93-}
94-
95-/// One scheduled slice of a mini-GOP, in decode order.
96-struct Sched {
97- poc: i32,
98- /// `RefPicList0[0]` (the past boundary).
99- l0: i32,
100- /// `RefPicList1[0]` (the future boundary) — `None` for the anchor
101- /// P slice.
102- l1: Option<i32>,
103- layer: u8,
104-}
105-
106-/// The dyadic decode-order schedule of one mini-GOP `(a, a + g]`:
107-/// the anchor P first, then the midpoint recursion.
108-fn build_schedule(a: i32, g: i32) -> Vec<Sched> {
109- fn rec(v: &mut Vec<Sched>, lo: i32, hi: i32, layer: u8) {
110- if hi - lo < 2 {
111- return;
112- }
113- let mid = (lo + hi) / 2;
114- v.push(Sched {
115- poc: mid,
116- l0: lo,
117- l1: Some(hi),
118- layer,
119- });
120- rec(v, lo, mid, layer + 1);
121- rec(v, mid, hi, layer + 1);
122- }
123- let mut v = vec![Sched {
124- poc: a + g,
125- l0: a,
126- l1: None,
127- layer: 0,
128- }];
129- rec(&mut v, a, a + g, 1);
130- v
131-}
132-
133-/// The streaming hierarchical-B encoder: display-order frames in,
134-/// decode-order access units out (buffered per mini-GOP).
135-#[derive(Debug)]
136-pub struct PyramidEncoder {
137- width: usize,
138- height: usize,
139- qp: i32,
140- /// Mini-GOP length (a power of two, 2..=16).
141- gop: usize,
142- /// Per-layer QP step (`SliceQpY = qp + layer * step`, clamped).
143- layer_qp_step: i32,
144- filters: LoopFilterCfg,
145- amp: bool,
146- /// Display index of the next frame pushed.
147- next_display: usize,
148- /// Frames after the last anchor, awaiting their mini-GOP.
149- pending: Vec<OwnedFrame>,
150- /// The retained reference reconstructions, keyed by POC.
151- refs: BTreeMap<i32, FrameRecon>,
152- /// POC of the last coded anchor (`None` before the IDR).
153- anchor: Option<i32>,
154-}
155-
156-impl PyramidEncoder {
157- /// Construct a hierarchical-B encoder for `width`x`height` 4:2:0
158- /// 8-bit content at base `SliceQpY == qp` with dyadic mini-GOPs
159- /// of `gop` frames (a power of two in 2..=16).
160- ///
161- /// # Errors
162- /// [`PyramidError::Encode`] on bad dimensions / QP,
163- /// [`PyramidError::BadGop`] on a non-power-of-two or out-of-range
164- /// `gop`.
165- pub fn new(width: usize, height: usize, qp: i32, gop: usize) -> Result<Self, PyramidError> {
166- if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 {
167- return Err(PyramidError::Encode(IntraEncodeError::BadDimensions {
168- width,
169- height,
170- }));
171- }
172- if !(0..=51).contains(&qp) {
173- return Err(PyramidError::Encode(IntraEncodeError::BadQp(qp)));
174- }
175- if !(2..=16).contains(&gop) || !gop.is_power_of_two() {
176- return Err(PyramidError::BadGop(gop));
177- }
178- Ok(Self {
179- width,
180- height,
181- qp,
182- gop,
183- layer_qp_step: 1,
184- filters: LoopFilterCfg::off(),
185- amp: false,
186- next_display: 0,
187- pending: Vec::new(),
188- refs: BTreeMap::new(),
189- anchor: None,
190- })
191- }
192-
193- /// Set the per-layer QP step (default 1): a slice on pyramid
194- /// layer `l` codes at `SliceQpY = clamp(qp + l * step, 0, 51)`.
195- #[must_use]
196- pub fn with_layer_qp_step(mut self, step: i32) -> Self {
197- self.layer_qp_step = step;
198- self
199- }
200-
201- /// Enable the §8.7 in-loop filters on every slice's
202- /// reconstruction path (see
203- /// [`crate::encoder::inter::LowDelayPEncoder::with_loop_filters`]).
204- #[must_use]
205- pub fn with_loop_filters(mut self, filters: LoopFilterCfg) -> Self {
206- self.filters = filters;
207- self
208- }
209-
210- /// Switch the stream to the AMP configuration (see
211- /// [`crate::encoder::inter::LowDelayPEncoder::with_amp`]).
212- #[must_use]
213- pub fn with_amp(mut self, on: bool) -> Self {
214- self.amp = on;
215- self
216- }
217-
218- /// The number of pyramid layers below the anchors
219- /// (`log2(gop)`).
220- fn depth(&self) -> u32 {
221- self.gop.trailing_zeros()
222- }
223-
224- /// The stream's [`SpsCfg`]: DPB bound `log2(gop) + 2` pictures
225- /// (the deepest recursion retains `log2(gop) + 1` references
226- /// beside the current picture), reorder bound `log2(gop)`.
227- fn sps_cfg(&self) -> SpsCfg {
228- SpsCfg {
229- max_dec_pic_buffering_minus1: self.depth() + 1,
230- max_num_reorder_pics: self.depth(),
231- min_cb_log2: if self.amp { 3 } else { 4 },
232- amp: self.amp,
233- // edith patch: no crop and no VUI on the inter paths
234- conf_win: (0, 0),
235- signal: None,
236- }
237- }
238-
239- /// The layer-`l` slice QP.
240- fn layer_qp(&self, layer: u8) -> i32 {
241- (self.qp + i32::from(layer) * self.layer_qp_step).clamp(0, 51)
242- }
243-
244- /// Push the next DISPLAY-order frame; returns every access unit
245- /// that became codable (none until the current mini-GOP fills,
246- /// then the whole mini-GOP in decode order).
247- ///
248- /// # Errors
249- /// [`PyramidError::Encode`] on plane-size mismatches.
250- pub fn encode_frame(&mut self, frame: &YuvFrame<'_>) -> Result<Vec<PyramidAu>, PyramidError> {
251- let (cw, ch) = (self.width / 2, self.height / 2);
252- for (plane, buf, expected) in [
253- ("y", frame.y, self.width * self.height),
254- ("cb", frame.cb, cw * ch),
255- ("cr", frame.cr, cw * ch),
256- ] {
257- if buf.len() != expected {
258- return Err(PyramidError::Encode(IntraEncodeError::PlaneSize {
259- plane,
260- expected,
261- got: buf.len(),
262- }));
263- }
264- }
265-
266- if self.anchor.is_none() {
267- // The leading IDR (POC 0, layer 0).
268- let idr = encode_idr_intra_au_full(
269- frame.y,
270- frame.cb,
271- frame.cr,
272- self.width,
273- self.height,
274- self.qp,
275- &self.sps_cfg(),
276- &self.filters,
277- )?;
278- let recon = FrameRecon {
279- y: idr.recon_y,
280- cb: idr.recon_cb,
281- cr: idr.recon_cr,
282- };
283- self.refs.insert(0, recon.clone());
284- self.anchor = Some(0);
285- self.next_display = 1;
286- return Ok(vec![PyramidAu {
287- au: idr.au,
288- keyframe: true,
289- display_order: 0,
290- layer: 0,
291- recon,
292- stats: FrameStats {
293- intra: (self.width / CTB) * (self.height / CTB),
294- ..FrameStats::default()
295- },
296- }]);
297- }
298-
299- self.pending.push(OwnedFrame {
300- y: frame.y.to_vec(),
301- cb: frame.cb.to_vec(),
302- cr: frame.cr.to_vec(),
303- });
304- self.next_display += 1;
305- if self.pending.len() == self.gop {
306- Ok(self.code_mini_gop())
307- } else {
308- Ok(Vec::new())
309- }
310- }
311-
312- /// Code the buffered complete mini-GOP in decode order and drain
313- /// it. The pending buffer holds displays `a+1 ..= a+gop`.
314- fn code_mini_gop(&mut self) -> Vec<PyramidAu> {
315- let a = self.anchor.expect("mini-GOP needs an anchor");
316- let g = self.gop as i32;
317- let sched = build_schedule(a, g);
318- let mut out = Vec::with_capacity(sched.len());
319- for (i, s) in sched.iter().enumerate() {
320- // Retained set for THIS slice's RPS: every already-coded
321- // picture that this or a LATER slice of the schedule
322- // still references.
323- let retained: Vec<i32> = {
324- let mut keep: Vec<i32> = self
325- .refs
326- .keys()
327- .copied()
328- .filter(|&p| {
329- sched[i..].iter().any(|t| {
330- t.l0 == p || t.l1 == Some(p) // still referenced
331- })
332- })
333- .collect();
334- keep.sort_unstable();
335- keep
336- };
337- // Drop reconstructions nothing references any more.
338- self.refs.retain(|p, _| retained.contains(p));
339-
340- let frame = &self.pending[(s.poc - a - 1) as usize];
341- let au = self.code_slice(frame.as_yuv(), s, &retained);
342- self.refs.insert(s.poc, au.recon.clone());
343- out.push(au);
344- }
345- // Only the new anchor survives into the next mini-GOP.
346- let new_anchor = a + g;
347- self.refs.retain(|&p, _| p == new_anchor);
348- self.anchor = Some(new_anchor);
349- self.pending.clear();
350- out
351- }
352-
353- /// Encode one scheduled P / B slice against the retained
354- /// reconstructions.
355- fn code_slice(&self, frame: YuvFrame<'_>, s: &Sched, retained: &[i32]) -> PyramidAu {
356- let b_slice = s.l1.is_some();
357- let rec_of = |p: i32| -> &FrameRecon { self.refs.get(&p).expect("retained recon") };
358- let l0 = vec![(s.l0, rec_of(s.l0))];
359- let l1: Vec<(i32, &FrameRecon)> = s.l1.map(|p| (p, rec_of(p))).into_iter().collect();
360- // Inline §7.4.8 RPS: negative pics closest-first, positive
361- // pics closest-first; used flags mark the active references.
362- let rps_neg: Vec<(u32, bool)> = retained
363- .iter()
364- .rev()
365- .filter(|&&p| p < s.poc)
366- .map(|&p| ((s.poc - p) as u32, p == s.l0))
367- .collect();
368- let rps_pos: Vec<(u32, bool)> = retained
369- .iter()
370- .filter(|&&p| p > s.poc)
371- .map(|&p| ((p - s.poc) as u32, Some(p) == s.l1))
372- .collect();
373- let spec = SliceSpec {
374- poc: s.poc,
375- qp: self.layer_qp(s.layer),
376- b_slice,
377- rps_neg,
378- rps_pos,
379- l0,
380- l1,
381- lf: &self.filters,
382- big_cu: self.amp,
383- };
384- let (rbsp, recon, stats) = encode_inter_slice(&frame, &spec, self.width, self.height);
385- PyramidAu {
386- au: annexb(&[nal_unit(1, 0, 0, &rbsp)]), // TRAIL_R
387- keyframe: false,
388- display_order: s.poc as usize,
389- layer: s.layer,
390- recon,
391- stats,
392- }
393- }
394-
395- /// Flush the trailing frames that never filled a mini-GOP: a
396- /// low-delay P chain from the last anchor (decode order ==
397- /// display order). Returns their access units; the encoder is
398- /// ready for more input afterwards (the last tail frame becomes
399- /// the new anchor).
400- pub fn flush(&mut self) -> Vec<PyramidAu> {
401- let Some(a) = self.anchor else {
402- return Vec::new();
403- };
404- let mut out = Vec::with_capacity(self.pending.len());
405- let pending = std::mem::take(&mut self.pending);
406- for (k, frame) in pending.iter().enumerate() {
407- let poc = a + 1 + k as i32;
408- let s = Sched {
409- poc,
410- l0: poc - 1,
411- l1: None,
412- layer: 0,
413- };
414- let retained = vec![poc - 1];
415- self.refs.retain(|&p, _| p == poc - 1);
416- let au = self.code_slice(frame.as_yuv(), &s, &retained);
417- self.refs.insert(poc, au.recon.clone());
418- out.push(au);
419- }
420- if let Some(last) = out.last() {
421- let new_anchor = last.display_order as i32;
422- self.refs.retain(|&p, _| p == new_anchor);
423- self.anchor = Some(new_anchor);
424- }
425- out
426- }
427-}
428-
429-/// Errors from the pyramid encoder.
430-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
431-pub enum PyramidError {
432- /// The shared input-validation contract (dimensions, planes, QP).
433- Encode(IntraEncodeError),
434- /// `gop` is not a power of two in 2..=16.
435- BadGop(usize),
436-}
437-
438-impl From<IntraEncodeError> for PyramidError {
439- fn from(e: IntraEncodeError) -> Self {
440- Self::Encode(e)
441- }
442-}
443-
444-impl core::fmt::Display for PyramidError {
445- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
446- match self {
447- Self::Encode(e) => e.fmt(f),
448- Self::BadGop(g) => write!(f, "pyramid gop must be a power of two in 2..=16, got {g}"),
449- }
450- }
451-}
452-
453-impl std::error::Error for PyramidError {}
454-
455-/// The encoded hierarchical-B sequence, with the per-frame outputs in
456-/// DISPLAY order (the stream itself is decode-ordered).
457-#[derive(Debug, Clone)]
458-pub struct PyramidEncoded {
459- /// The whole Annex B byte stream (decode order).
460- pub stream: Vec<u8>,
461- /// Per-frame reconstruction, display order.
462- pub recon: Vec<FrameRecon>,
463- /// Per-frame CU mode-decision counters, display order.
464- pub stats: Vec<FrameStats>,
465- /// Per-frame pyramid layer, display order.
466- pub layers: Vec<u8>,
467- /// The display order of each access unit of `stream`, in decode
468- /// order (the coding schedule, for inspection).
469- pub decode_order: Vec<usize>,
470-}
471-
472-/// Encode a whole sequence through a [`PyramidEncoder`] (leading IDR,
473-/// dyadic mini-GOPs, low-delay tail) and return the stream plus the
474-/// display-ordered per-frame outputs.
475-///
476-/// # Errors
477-/// [`PyramidError`] on bad dimensions / planes / QP / GOP length.
478-pub fn encode_pyramid(
479- frames: &[YuvFrame<'_>],
480- width: usize,
481- height: usize,
482- qp: i32,
483- gop: usize,
484-) -> Result<PyramidEncoded, PyramidError> {
485- encode_pyramid_with(PyramidEncoder::new(width, height, qp, gop)?, frames)
486-}
487-
488-/// [`encode_pyramid`] over a pre-configured encoder (filters, AMP,
489-/// layer QP step).
490-///
491-/// # Errors
492-/// [`PyramidError`] on bad plane geometry.
493-pub fn encode_pyramid_with(
494- mut enc: PyramidEncoder,
495- frames: &[YuvFrame<'_>],
496-) -> Result<PyramidEncoded, PyramidError> {
497- let n = frames.len();
498- let mut out = PyramidEncoded {
499- stream: Vec::new(),
500- recon: vec![FrameRecon::default(); n],
501- stats: vec![FrameStats::default(); n],
502- layers: vec![0; n],
503- decode_order: Vec::with_capacity(n),
504- };
505- let push = |out: &mut PyramidEncoded, aus: Vec<PyramidAu>| {
506- for au in aus {
507- out.stream.extend_from_slice(&au.au);
508- out.decode_order.push(au.display_order);
509- out.recon[au.display_order] = au.recon;
510- out.stats[au.display_order] = au.stats;
511- out.layers[au.display_order] = au.layer;
512- }
513- };
514- for f in frames {
515- let aus = enc.encode_frame(f)?;
516- push(&mut out, aus);
517- }
518- push(&mut out, enc.flush());
519- Ok(out)
520-}
521-
522-#[cfg(test)]
523-mod tests {
524- use super::*;
525- use crate::encoder::inter::encode_low_delay_p;
526- use crate::sequence::decode_annexb_sequence;
527-
528- /// A deterministic "camera-noise" scene: a static textured
529- /// background under small temporally-independent sensor noise,
530- /// with a small bright square drifting 1 px per frame. Motion
531- /// prediction cancels everything except the noise — the content
532- /// class where the pyramid's per-layer QP allocation wins (the
533- /// top layers spend fewer bits on noise nobody references).
534- fn pan_scene(w: usize, h: usize, n: usize) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
535- let tex = |u: usize, v: usize| -> i32 { ((u * 3 + v * 5 + (u / 9) * 7) % 200) as i32 };
536- let noise = |x: usize, yy: usize, t: usize| -> i32 {
537- let h32 = (x
538- .wrapping_mul(73_856_093)
539- .wrapping_add(yy.wrapping_mul(19_349_663))
540- .wrapping_add(t.wrapping_mul(83_492_791))) as u32;
541- ((h32 >> 13) % 9) as i32 - 4
542- };
543- (0..n)
544- .map(|t| {
545- let y: Vec<u8> = (0..w * h)
546- .map(|i| {
547- let (x, yy) = (i % w, i / w);
548- let (sx, sy) = (10 + t, 24);
549- let obj = x >= sx && x < sx + 8 && yy >= sy && yy < sy + 8;
550- let base = tex(x, yy) + if obj { 45 } else { 0 };
551- (base + 8 + noise(x, yy, t)).clamp(0, 255) as u8
552- })
553- .collect();
554- let cb: Vec<u8> = (0..w * h / 4)
555- .map(|i| (90 + (i % (w / 2)) % 70) as u8)
556- .collect();
557- let cr: Vec<u8> = (0..w * h / 4)
558- .map(|i| (180 - (i / (w / 2)) % 60) as u8)
559- .collect();
560- (y, cb, cr)
561- })
562- .collect()
563- }
564-
565- fn as_frames(planes: &[(Vec<u8>, Vec<u8>, Vec<u8>)]) -> Vec<YuvFrame<'_>> {
566- planes
567- .iter()
568- .map(|(y, cb, cr)| YuvFrame { y, cb, cr })
569- .collect()
570- }
571-
572- fn assert_display_order_exact(stream: &[u8], recons: &[FrameRecon], label: &str) {
573- let decoded = decode_annexb_sequence(stream).expect("decode");
574- assert_eq!(decoded.len(), recons.len(), "{label}: frame count");
575- for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() {
576- assert_eq!(dec.poc, i as i32, "{label}: display order POC {i}");
577- let mut expect = rec.y.clone();
578- expect.extend_from_slice(&rec.cb);
579- expect.extend_from_slice(&rec.cr);
580- assert_eq!(
581- dec.picture.to_planar_u8().expect("8-bit"),
582- expect,
583- "{label} frame {i}: decoder output == encoder recon"
584- );
585- }
586- }
587-
588- /// The core contract across GOP shapes: out-of-order coded
589- /// pyramids decode (through the crate's own §C.5.2.2
590- /// output-ordering) bit-exactly to the encoder's display-order
591- /// reconstructions — including a non-filling low-delay tail.
592- #[test]
593- fn pyramid_gops_decode_to_encoder_recon_exactly() {
594- let planes = pan_scene(64, 64, 10);
595- let frames = as_frames(&planes);
596- for (gop, qp) in [(2usize, 24i32), (4, 30), (8, 27)] {
597- let enc = encode_pyramid(&frames, 64, 64, qp, gop).expect("encode");
598- assert_display_order_exact(&enc.stream, &enc.recon, &format!("gop{gop} qp{qp}"));
599- }
600- }
601-
602- /// The decode-order schedule is the dyadic pyramid, the layers
603- /// are the recursion depths, and the mid slices really code
604- /// bi-predictively (past L0 + future L1).
605- #[test]
606- fn pyramid_schedule_layers_and_bi_usage() {
607- let planes = pan_scene(64, 64, 9);
608- let frames = as_frames(&planes);
609- let enc = encode_pyramid(&frames, 64, 64, 26, 8).expect("encode");
610- // IDR, then the mini-GOP in dyadic decode order.
611- assert_eq!(enc.decode_order, vec![0, 8, 4, 2, 1, 3, 6, 5, 7]);
612- assert_eq!(
613- enc.layers,
614- vec![0, 3, 2, 3, 1, 3, 2, 3, 0],
615- "display-order layers of a GOP-8 pyramid"
616- );
617- // Every B layer >= 1 frame elects some bi-predicted CUs on
618- // smooth translation.
619- let bi_frames = (0..9)
620- .filter(|&i| enc.layers[i] >= 1 && enc.stats[i].bi > 0)
621- .count();
622- assert!(
623- bi_frames >= 4,
624- "expected widespread bi-prediction, stats: {:?}",
625- enc.stats
626- );
627- }
628-
629- /// Pyramid coding beats the low-delay chain on smooth motion at
630- /// the same base QP: fewer bytes for comparable quality.
631- #[test]
632- fn pyramid_beats_low_delay_on_smooth_motion() {
633- let (w, h, n) = (64usize, 64usize, 9usize);
634- let planes = pan_scene(w, h, n);
635- let frames = as_frames(&planes);
636- let qp = 30;
637- let low = encode_low_delay_p(&frames, w, h, qp).expect("low-delay");
638- let pyr = encode_pyramid(&frames, w, h, qp, 8).expect("pyramid");
639- assert!(
640- pyr.stream.len() < low.stream.len(),
641- "pyramid ({} B) should undercut low-delay ({} B) on smooth motion",
642- pyr.stream.len(),
643- low.stream.len()
644- );
645- // Quality stays in the same class (the per-layer QP offsets
646- // trade a little PSNR on the top layers for the rate win).
647- let psnr = |rec: &FrameRecon, t: usize| -> f64 {
648- let mse: f64 = rec
649- .y
650- .iter()
651- .zip(planes[t].0.iter())
652- .map(|(&a, &b)| {
653- let d = f64::from(a) - f64::from(b);
654- d * d
655- })
656- .sum::<f64>()
657- / rec.y.len() as f64;
658- 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10()
659- };
660- for t in 0..n {
661- assert!(
662- psnr(&pyr.recon[t], t) > 30.0,
663- "frame {t}: pyramid luma PSNR too low"
664- );
665- }
666- }
667-
668- /// Pyramids compose with the AMP configuration and the §8.7
669- /// in-loop filters — everything still decodes bit-exactly.
670- #[test]
671- fn pyramid_composes_with_amp_and_filters() {
672- let planes = pan_scene(64, 48, 9);
673- let frames = as_frames(&planes);
674- for (amp, lf) in [
675- (true, LoopFilterCfg::off()),
676- (false, LoopFilterCfg::all()),
677- (true, LoopFilterCfg::all()),
678- ] {
679- let enc = PyramidEncoder::new(64, 48, 32, 4)
680- .expect("encoder")
681- .with_amp(amp)
682- .with_loop_filters(lf);
683- let out = encode_pyramid_with(enc, &frames).expect("encode");
684- assert_display_order_exact(&out.stream, &out.recon, &format!("amp={amp} {lf:?}"));
685- }
686- }
687-
688- /// Successive mini-GOPs chain across anchors, and flushing midway
689- /// (a 6-frame sequence at GOP 4: IDR + one mini-GOP + 1-frame
690- /// tail) stays bit-exact.
691- #[test]
692- fn pyramid_multi_gop_and_tail_roundtrip() {
693- let planes = pan_scene(48, 32, 6);
694- let frames = as_frames(&planes);
695- let enc = encode_pyramid(&frames, 48, 32, 22, 4).expect("encode");
696- assert_eq!(enc.decode_order, vec![0, 4, 2, 1, 3, 5]);
697- assert_display_order_exact(&enc.stream, &enc.recon, "gop4 tail");
698- }
699-
700- /// Input validation.
701- #[test]
702- fn rejects_bad_configs() {
703- assert!(matches!(
704- PyramidEncoder::new(64, 64, 26, 3),
705- Err(PyramidError::BadGop(3))
706- ));
707- assert!(matches!(
708- PyramidEncoder::new(64, 64, 26, 32),
709- Err(PyramidError::BadGop(32))
710- ));
711- assert!(matches!(
712- PyramidEncoder::new(20, 64, 26, 4),
713- Err(PyramidError::Encode(IntraEncodeError::BadDimensions { .. }))
714- ));
715- assert!(matches!(
716- PyramidEncoder::new(64, 64, 99, 4),
717- Err(PyramidError::Encode(IntraEncodeError::BadQp(99)))
718- ));
719- }
720-}
vendor/oxideav-h265/src/encoder/rdpcm_streams.rsdeleted+0 -772
@@ -1,772 +0,0 @@
1-//! Self-built §8.6.5 RDPCM conformance streams (test-only).
2-//!
3-//! No black-box encoder binary exposes the range-extension RDPCM
4-//! tools, so these tests assemble tiny lossless (transquant-bypass)
5-//! Annex B bitstreams from this crate's own header writers and CABAC
6-//! encoder:
7-//!
8-//! * an all-intra stream whose SPS signals
9-//! `implicit_rdpcm_enabled_flag == 1` and whose bypass CUs cycle
10-//! through predModeIntra 26 / 10 / DC / PLANAR — the mode-26/10 CUs
11-//! carry §8.6.5-DPCM-differenced residuals (and their DM chroma
12-//! blocks likewise), the DC / PLANAR CUs raw residuals;
13-//! * an IDR + P stream whose P-slice merge CUs signal
14-//! `explicit_rdpcm_flag` per component (§7.3.8.11) with both
15-//! directions, plus flag-0 control CUs and an all-skip CU.
16-//!
17-//! Both reconstruct losslessly, so a conforming decoder must emit the
18-//! procedural source planes exactly. The checked-in copies under
19-//! `tests/fixture_bytes/` were validated against a black-box reference
20-//! decoder (byte-exact; SHA-256 sums in
21-//! `tests/fixture_bytes/r413-generation-notes.md`), and the tests here
22-//! pin (a) that the builder still produces those exact bytes and
23-//! (b) that this crate's decoder reconstructs them losslessly.
24-
25-use crate::binarization::{
26- cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, intra_luma_cand_mode_list,
27-};
28-use crate::cabac::init_type;
29-use crate::ctx_init::SliceContexts;
30-use crate::encoder::bitwriter::BitWriter;
31-use crate::encoder::cabac::CabacEncoder;
32-use crate::encoder::intra::{gather_refs, zscan_avail};
33-use crate::encoder::nal::{annexb, nal_unit};
34-use crate::encoder::residual::encode_residual_coding;
35-use crate::intra_mode_field::{IntraModeField, Neighbour};
36-use crate::intra_pred::{
37- intra_predict_with_substitution, Component as PredComponent, IntraPredParams,
38-};
39-use crate::residual::{residual_coding_scan_idx, ResidualCodingParams};
40-
41-/// One picture's `(Y, Cb, Cr)` planes.
42-type Planes = (Vec<u8>, Vec<u8>, Vec<u8>);
43-
44-/// CTB / coding-block log2 size (16x16, `MinCbSizeY == CtbSizeY`).
45-const CTB_LOG2: u32 = 4;
46-const CTB: usize = 1 << CTB_LOG2;
47-/// SliceQpY (immaterial — every CU is transquant-bypassed).
48-const SLICE_QP: i32 = 26;
49-
50-/// Deterministic 4:2:0 source planes: smooth gradients plus a coarse
51-/// checker texture, phase-shifted per frame.
52-fn source_planes(w: usize, h: usize, frame: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
53- // The bottom-right CTB is static across frames so the P slice
54- // exercises a genuine skip CU.
55- let static_corner =
56- |x: i32, y: i32, pw: i32, ph: i32, blk: i32| -> bool { x >= pw - blk && y >= ph - blk };
57- let lum = |x: i32, y: i32, f: i32| -> u8 {
58- let g = (x * 3 + y * 5 + f * 17) % 197;
59- let t = ((x / 4 + y / 4 + f) % 3) * 23;
60- (16 + g + t).clamp(0, 255) as u8
61- };
62- let chr = |x: i32, y: i32, ph: i32, f: i32| -> u8 {
63- let g = (x * 7 + y * 2 + f * 29 + ph) % 151;
64- let t = ((x / 4 + y / 8) % 2) * 31;
65- (40 + g + t).clamp(0, 255) as u8
66- };
67- let f = frame as i32;
68- let mut y_p = Vec::with_capacity(w * h);
69- for yy in 0..h as i32 {
70- for xx in 0..w as i32 {
71- let ef = if static_corner(xx, yy, w as i32, h as i32, 16) {
72- 0
73- } else {
74- f
75- };
76- y_p.push(lum(xx, yy, ef));
77- }
78- }
79- let (cw, ch) = (w / 2, h / 2);
80- let mut cb_p = Vec::with_capacity(cw * ch);
81- let mut cr_p = Vec::with_capacity(cw * ch);
82- for yy in 0..ch as i32 {
83- for xx in 0..cw as i32 {
84- let ef = if static_corner(xx, yy, cw as i32, ch as i32, 8) {
85- 0
86- } else {
87- f
88- };
89- cb_p.push(chr(xx, yy, 0, ef));
90- cr_p.push(chr(xx, yy, 61, ef));
91- }
92- }
93- (y_p, cb_p, cr_p)
94-}
95-
96-/// §7.3.3 — profile tier level for Format Range Extensions
97-/// (`general_profile_idc == 4`) at the given level.
98-pub(crate) fn write_ptl_rext(w: &mut BitWriter, level_idc: u8) {
99- w.put_bits(0, 2); // general_profile_space
100- w.put_bit(0); // general_tier_flag
101- w.put_bits(4, 5); // general_profile_idc = 4 (Range Extensions)
102- let mut compat: u32 = 0;
103- compat |= 1 << (31 - 4); // flag[4] — Range Extensions
104- w.put_bits(compat, 32);
105- w.put_bit(1); // general_progressive_source_flag
106- w.put_bit(0); // general_interlaced_source_flag
107- w.put_bit(1); // general_non_packed_constraint_flag
108- w.put_bit(1); // general_frame_only_constraint_flag
109- // profile_idc 4: max_12bit / max_10bit / max_8bit /
110- // max_422chroma / max_420chroma constraint flags set
111- // (4:2:0 8-bit), then max_monochrome / intra /
112- // one_picture_only / lossless 0 + 34 reserved bits.
113- w.put_bit(1); // general_max_12bit_constraint_flag
114- w.put_bit(1); // general_max_10bit_constraint_flag
115- w.put_bit(1); // general_max_8bit_constraint_flag
116- w.put_bit(1); // general_max_422chroma_constraint_flag
117- w.put_bit(1); // general_max_420chroma_constraint_flag
118- w.put_bit(0); // general_max_monochrome_constraint_flag
119- w.put_bit(0); // general_intra_constraint_flag
120- w.put_bit(0); // general_one_picture_only_constraint_flag
121- w.put_bit(0); // general_lossless_constraint_flag
122- w.put_bits(0, 32); // general_reserved_zero_34bits...
123- w.put_bits(0, 2);
124- w.put_bit(0); // general_inbld_flag
125- w.put_bits(u32::from(level_idc), 8); // general_level_idc
126-}
127-
128-/// §7.3.2.1 — single-layer VPS with the Range-Extensions PTL.
129-fn write_vps_rext(level_idc: u8) -> Vec<u8> {
130- let mut w = BitWriter::new();
131- w.put_bits(0, 4); // vps_video_parameter_set_id
132- w.put_bit(1); // vps_base_layer_internal_flag
133- w.put_bit(1); // vps_base_layer_available_flag
134- w.put_bits(0, 6); // vps_max_layers_minus1
135- w.put_bits(0, 3); // vps_max_sub_layers_minus1
136- w.put_bit(1); // vps_temporal_id_nesting_flag
137- w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits
138- write_ptl_rext(&mut w, level_idc);
139- w.put_bit(1); // vps_sub_layer_ordering_info_present_flag
140- w.ue(1); // vps_max_dec_pic_buffering_minus1[0]
141- w.ue(0); // vps_max_num_reorder_pics[0]
142- w.ue(0); // vps_max_latency_increase_plus1[0]
143- w.put_bits(0, 6); // vps_max_layer_id
144- w.ue(0); // vps_num_layer_sets_minus1
145- w.put_bit(0); // vps_timing_info_present_flag
146- w.put_bit(0); // vps_extension_flag
147- w.rbsp_trailing_bits();
148- w.finish()
149-}
150-
151-/// §7.3.2.2 — 4:2:0 8-bit SPS (CTB 16, no PCM, SAO off) carrying an
152-/// `sps_range_extension()` with `implicit_rdpcm_enabled_flag` and
153-/// `explicit_rdpcm_enabled_flag` both set.
154-fn write_sps_rext(width: usize, height: usize, level_idc: u8) -> Vec<u8> {
155- let mut w = BitWriter::new();
156- w.put_bits(0, 4); // sps_video_parameter_set_id
157- w.put_bits(0, 3); // sps_max_sub_layers_minus1
158- w.put_bit(1); // sps_temporal_id_nesting_flag
159- write_ptl_rext(&mut w, level_idc);
160- w.ue(0); // sps_seq_parameter_set_id
161- w.ue(1); // chroma_format_idc = 4:2:0
162- w.ue(width as u32); // pic_width_in_luma_samples
163- w.ue(height as u32); // pic_height_in_luma_samples
164- w.put_bit(0); // conformance_window_flag
165- w.ue(0); // bit_depth_luma_minus8
166- w.ue(0); // bit_depth_chroma_minus8
167- w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
168- w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
169- w.ue(1); // sps_max_dec_pic_buffering_minus1[0]
170- w.ue(0); // sps_max_num_reorder_pics[0]
171- w.ue(0); // sps_max_latency_increase_plus1[0]
172- w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16)
173- w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16)
174- w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
175- w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
176- w.ue(0); // max_transform_hierarchy_depth_inter
177- w.ue(0); // max_transform_hierarchy_depth_intra
178- w.put_bit(0); // scaling_list_enabled_flag
179- w.put_bit(0); // amp_enabled_flag
180- w.put_bit(0); // sample_adaptive_offset_enabled_flag
181- w.put_bit(0); // pcm_enabled_flag
182- w.ue(0); // num_short_term_ref_pic_sets
183- w.put_bit(0); // long_term_ref_pics_present_flag
184- w.put_bit(0); // sps_temporal_mvp_enabled_flag
185- w.put_bit(0); // strong_intra_smoothing_enabled_flag
186- w.put_bit(0); // vui_parameters_present_flag
187- w.put_bit(1); // sps_extension_present_flag
188- w.put_bit(1); // sps_range_extension_flag
189- w.put_bit(0); // sps_multilayer_extension_flag
190- w.put_bit(0); // sps_3d_extension_flag
191- w.put_bit(0); // sps_scc_extension_flag
192- w.put_bits(0, 4); // sps_extension_4bits
193- // sps_range_extension() — §7.3.2.2.2.
194- w.put_bit(0); // transform_skip_rotation_enabled_flag
195- w.put_bit(0); // transform_skip_context_enabled_flag
196- w.put_bit(1); // implicit_rdpcm_enabled_flag
197- w.put_bit(1); // explicit_rdpcm_enabled_flag
198- w.put_bit(0); // extended_precision_processing_flag
199- w.put_bit(0); // intra_smoothing_disabled_flag
200- w.put_bit(0); // high_precision_offsets_enabled_flag
201- w.put_bit(0); // persistent_rice_adaptation_enabled_flag
202- w.put_bit(0); // cabac_bypass_alignment_enabled_flag
203- w.rbsp_trailing_bits();
204- w.finish()
205-}
206-
207-/// §7.3.2.3 — PPS with `transquant_bypass_enabled_flag == 1`,
208-/// deblocking disabled, sign hiding off.
209-pub(crate) fn write_pps_bypass() -> Vec<u8> {
210- let mut w = BitWriter::new();
211- w.ue(0); // pps_pic_parameter_set_id
212- w.ue(0); // pps_seq_parameter_set_id
213- w.put_bit(0); // dependent_slice_segments_enabled_flag
214- w.put_bit(0); // output_flag_present_flag
215- w.put_bits(0, 3); // num_extra_slice_header_bits
216- w.put_bit(0); // sign_data_hiding_enabled_flag
217- w.put_bit(0); // cabac_init_present_flag
218- w.ue(0); // num_ref_idx_l0_default_active_minus1
219- w.ue(0); // num_ref_idx_l1_default_active_minus1
220- w.se(SLICE_QP - 26); // init_qp_minus26
221- w.put_bit(0); // constrained_intra_pred_flag
222- w.put_bit(0); // transform_skip_enabled_flag
223- w.put_bit(0); // cu_qp_delta_enabled_flag
224- w.se(0); // pps_cb_qp_offset
225- w.se(0); // pps_cr_qp_offset
226- w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag
227- w.put_bit(0); // weighted_pred_flag
228- w.put_bit(0); // weighted_bipred_flag
229- w.put_bit(1); // transquant_bypass_enabled_flag
230- w.put_bit(0); // tiles_enabled_flag
231- w.put_bit(0); // entropy_coding_sync_enabled_flag
232- w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag
233- w.put_bit(1); // deblocking_filter_control_present_flag
234- w.put_bit(0); // deblocking_filter_override_enabled_flag
235- w.put_bit(1); // pps_deblocking_filter_disabled_flag
236- w.put_bit(0); // pps_scaling_list_data_present_flag
237- w.put_bit(0); // lists_modification_present_flag
238- w.ue(0); // log2_parallel_merge_level_minus2
239- w.put_bit(0); // slice_segment_header_extension_present_flag
240- w.put_bit(0); // pps_extension_present_flag
241- w.rbsp_trailing_bits();
242- w.finish()
243-}
244-
245-/// §8.6.5 in the ENCODE direction: difference the residual along the
246-/// DPCM direction so the decoder's accumulation restores it exactly.
247-fn dpcm_difference(res: &[i32], n: usize, vertical: bool) -> Vec<i32> {
248- let mut out = res.to_vec();
249- if vertical {
250- for y in (1..n).rev() {
251- for x in 0..n {
252- out[y * n + x] -= res[(y - 1) * n + x];
253- }
254- }
255- } else {
256- for y in 0..n {
257- for x in (1..n).rev() {
258- out[y * n + x] -= res[y * n + x - 1];
259- }
260- }
261- }
262- out
263-}
264-
265-fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec<i32> {
266- let mut out = Vec::with_capacity(n * n);
267- for j in 0..n {
268- for i in 0..n {
269- out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
270- }
271- }
272- out
273-}
274-
275-/// The intra prediction params mirroring the stream's SPS: smoothing
276-/// on (no rext disable), no strong smoothing, and — because every CU
277-/// is transquant-bypassed under `implicit_rdpcm_enabled_flag == 1` —
278-/// the §8.4.4.2.6 `disableIntraBoundaryFilter` (angular 10/26 filters
279-/// only; the §8.4.4.2.5 DC gate is the SCC flag, which is 0).
280-fn ip_params(mode: u8, cidx: PredComponent) -> IntraPredParams {
281- IntraPredParams {
282- pred_mode_intra: mode,
283- cidx,
284- bit_depth: 8,
285- bit_depth_luma: 8,
286- intra_smoothing_disabled: false,
287- strong_intra_smoothing_enabled: false,
288- chroma_array_type_3: false,
289- disable_boundary_filter: mode != crate::intra_pred::INTRA_DC,
290- }
291-}
292-
293-/// Per-CTB intra plan: `(luma_mode, intra_chroma_pred_mode_raw)`.
294-///
295-/// The §8.4.4.2.6 mode-26 (left-column) / mode-10 (top-row) boundary
296-/// filters are disabled by `disableIntraBoundaryFilter` under implicit
297-/// RDPCM with transquant bypass; a surveyed black-box reference
298-/// decoder applies them regardless, so luma DPCM modes are placed
299-/// where the relevant reference edge is a picture boundary (the
300-/// §8.4.4.2.2 substitution makes the filter a no-op there): mode 10
301-/// on the top CTB row, mode 26 down the left CTB column. Interior CUs
302-/// carry DC / PLANAR luma (non-DPCM controls) while their CHROMA
303-/// blocks — never boundary-filtered — take mode 26 / 10 through
304-/// `intra_chroma_pred_mode` 1 / 2 (Table 8-3), keeping implicit RDPCM
305-/// dense across the picture.
306-fn intra_plan(col: usize, row: usize, ctb: usize) -> (u8, u8) {
307- if row == 0 {
308- if col == 0 {
309- (26, 4) // both edges are picture boundaries
310- } else {
311- (10, 4) // DM ⇒ chroma 10
312- }
313- } else if col == 0 {
314- (26, 4) // DM ⇒ chroma 26
315- } else {
316- // Interior: luma control mode (no DPCM), chroma 26 / 10.
317- let luma = if ctb % 2 == 0 { 1 } else { 0 };
318- let chroma_raw = if ctb % 4 < 2 { 1 } else { 2 };
319- (luma, chroma_raw)
320- }
321-}
322-
323-/// Table 8-3 — `IntraPredModeC` from `intra_chroma_pred_mode` and the
324-/// luma mode (the collision row maps to 34; the plan never collides).
325-fn mode_c_of(raw: u8, luma: u8) -> u8 {
326- let base = match raw {
327- 0 => 0u8,
328- 1 => 26,
329- 2 => 10,
330- 3 => 1,
331- _ => return luma,
332- };
333- if base == luma {
334- 34
335- } else {
336- base
337- }
338-}
339-
340-/// Encode the all-intra bypass slice: one 16x16 `PART_2Nx2N` CU per
341-/// CTB, `cu_transquant_bypass_flag == 1`, modes per [`intra_plan`].
342-/// Lossless: the reconstruction equals the source, so reference
343-/// samples read the source planes directly.
344-fn encode_bypass_idr_slice(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Vec<u8> {
345- let (cw, ch) = (width / 2, height / 2);
346- let ctbs_x = width / CTB;
347- let ctbs_y = height / CTB;
348- let mut modes = IntraModeField::new(width, height, CTB_LOG2);
349-
350- let mut w = BitWriter::new();
351- // ---- slice_segment_header( ) ----
352- w.put_bit(1); // first_slice_segment_in_pic_flag
353- w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
354- w.ue(0); // slice_pic_parameter_set_id
355- w.ue(2); // slice_type = I
356- w.se(0); // slice_qp_delta
357- w.rbsp_trailing_bits(); // byte_alignment()
358-
359- // ---- slice_segment_data( ) ----
360- let mut cabac = CabacEncoder::new();
361- let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP);
362-
363- for ctb in 0..ctbs_x * ctbs_y {
364- let x0 = (ctb % ctbs_x) * CTB;
365- let y0 = (ctb / ctbs_x) * CTB;
366- let (mode, chroma_raw) = intra_plan(ctb % ctbs_x, ctb / ctbs_x, ctb);
367- let mode_c = mode_c_of(chroma_raw, mode);
368-
369- // Luma prediction + residual (lossless recon == source).
370- let read_y = |x: usize, yy: usize| i32::from(y[yy * width + x]);
371- let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
372- let marked = gather_refs(&read_y, &avail, x0, y0, CTB);
373- let pred = intra_predict_with_substitution(&marked, &ip_params(mode, PredComponent::Luma))
374- .expect("legal prediction");
375- let src = extract(y, width, x0, y0, CTB);
376- let mut res_l: Vec<i32> = src.iter().zip(&pred).map(|(s, p)| s - p).collect();
377- if mode == 26 || mode == 10 {
378- res_l = dpcm_difference(&res_l, CTB, mode == 26);
379- }
380-
381- // Chroma 8x8 TBs at (x0/2, y0/2), mode `mode_c`.
382- let (cx0, cy0) = (x0 / 2, y0 / 2);
383- let code_chroma = |plane: &[u8], pc: PredComponent| -> Vec<i32> {
384- let read = |x: usize, yy: usize| i32::from(plane[yy * cw + x]);
385- let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0);
386- let marked = gather_refs(&read, &avail, cx0, cy0, 8);
387- let pred = intra_predict_with_substitution(&marked, &ip_params(mode_c, pc))
388- .expect("legal prediction");
389- let src = extract(plane, cw, cx0, cy0, 8);
390- let mut res: Vec<i32> = src.iter().zip(&pred).map(|(s, p)| s - p).collect();
391- if mode_c == 26 || mode_c == 10 {
392- res = dpcm_difference(&res, 8, mode_c == 26);
393- }
394- res
395- };
396- let res_cb = code_chroma(cb, PredComponent::Cb);
397- let res_cr = code_chroma(cr, PredComponent::Cr);
398-
399- // ---- §7.3.8.5 coding_unit( ) ----
400- cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1);
401- // part_mode (intra at MinCb): "1" = PART_2Nx2N.
402- cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1);
403- // Luma mode signalling against the §8.4.2 candidate list.
404- let avail_l = zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0);
405- let avail_a = zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0);
406- let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l);
407- let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a);
408- let list = intra_luma_cand_mode_list(cand_a, cand_b);
409- let sel = list.iter().position(|&m| m == mode);
410- cabac.encode_decision(
411- &mut w,
412- &mut ctxs.prev_intra_luma_pred_flag[0],
413- u8::from(sel.is_some()),
414- );
415- modes.record_intra_pb(x0, y0, CTB, mode, false);
416- match sel {
417- Some(0) => cabac.encode_bypass(&mut w, 0),
418- Some(1) => {
419- cabac.encode_bypass(&mut w, 1);
420- cabac.encode_bypass(&mut w, 0);
421- }
422- Some(_) => {
423- cabac.encode_bypass(&mut w, 1);
424- cabac.encode_bypass(&mut w, 1);
425- }
426- None => {
427- let mut rem = u32::from(mode);
428- for &c in &list {
429- if u32::from(mode) > u32::from(c) {
430- rem -= 1;
431- }
432- }
433- cabac.encode_bypass_bits(&mut w, rem, 5);
434- }
435- }
436- // intra_chroma_pred_mode: 4 (derived) is the single ctx bin
437- // "0"; values 0..3 are ctx bin "1" plus two FL bypass bits.
438- if chroma_raw == 4 {
439- cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0);
440- } else {
441- cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 1);
442- cabac.encode_bypass_bits(&mut w, u32::from(chroma_raw), 2);
443- }
444-
445- // ---- transform_tree / transform_unit ----
446- let cbf_cb_f = res_cb.iter().any(|&v| v != 0);
447- let cbf_cr_f = res_cr.iter().any(|&v| v != 0);
448- let cbf_luma = res_l.iter().any(|&v| v != 0);
449- cabac.encode_decision(
450- &mut w,
451- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
452- u8::from(cbf_cb_f),
453- );
454- cabac.encode_decision(
455- &mut w,
456- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
457- u8::from(cbf_cr_f),
458- );
459- cabac.encode_decision(
460- &mut w,
461- &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize],
462- u8::from(cbf_luma),
463- );
464- let rc = |log2: u32, is_chroma: bool| ResidualCodingParams {
465- log2_trafo_size: log2,
466- is_chroma,
467- scan_idx: residual_coding_scan_idx(
468- true,
469- log2,
470- u8::from(is_chroma),
471- 1,
472- u32::from(if is_chroma { mode_c } else { mode }),
473- ),
474- sign_data_hiding_enabled_flag: false,
475- sign_hidden_suppressed: false,
476- transform_skip_sig_ctx: false,
477- persistent_rice_adaptation_enabled_flag: false,
478- cabac_bypass_alignment_enabled_flag: false,
479- extended_precision_processing_flag: false,
480- bit_depth: 8,
481- rice_stat_transform_skip: false,
482- };
483- if cbf_luma {
484- encode_residual_coding(
485- &mut w,
486- &mut cabac,
487- &mut ctxs.residual,
488- &rc(4, false),
489- &res_l,
490- )
491- .expect("valid luma levels");
492- }
493- if cbf_cb_f {
494- encode_residual_coding(
495- &mut w,
496- &mut cabac,
497- &mut ctxs.residual,
498- &rc(3, true),
499- &res_cb,
500- )
501- .expect("valid cb levels");
502- }
503- if cbf_cr_f {
504- encode_residual_coding(
505- &mut w,
506- &mut cabac,
507- &mut ctxs.residual,
508- &rc(3, true),
509- &res_cr,
510- )
511- .expect("valid cr levels");
512- }
513-
514- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
515- }
516- w.align_zero();
517- w.finish()
518-}
519-
520-/// Encode the P slice: every CTB one 16x16 CU predicting from the
521-/// previous picture at MV (0, 0) — `MaxNumMergeCand == 1`, so both
522-/// merge and skip resolve to the zero candidate. CUs with residual are
523-/// bypass merge CUs whose per-component `residual_coding( )` signals
524-/// `explicit_rdpcm_flag` (cycling direction, with flag-0 controls);
525-/// all-zero CTBs are skip CUs.
526-#[allow(clippy::too_many_arguments)]
527-fn encode_bypass_p_slice(
528- y: &[u8],
529- cb: &[u8],
530- cr: &[u8],
531- ry: &[u8],
532- rcb: &[u8],
533- rcr: &[u8],
534- width: usize,
535- height: usize,
536-) -> Vec<u8> {
537- let (cw, _ch) = (width / 2, height / 2);
538- let ctbs_x = width / CTB;
539- let ctbs_y = height / CTB;
540-
541- let mut w = BitWriter::new();
542- // ---- slice_segment_header( ) ----
543- w.put_bit(1); // first_slice_segment_in_pic_flag
544- w.ue(0); // slice_pic_parameter_set_id
545- w.ue(1); // slice_type = P
546- w.put_bits(1, 8); // slice_pic_order_cnt_lsb (log2 max = 8 bits)
547- w.put_bit(0); // short_term_ref_pic_set_sps_flag
548- // st_ref_pic_set( 0 ): one negative reference at −1.
549- w.ue(1); // num_negative_pics
550- w.ue(0); // num_positive_pics
551- w.ue(0); // delta_poc_s0_minus1[0]
552- w.put_bit(1); // used_by_curr_pic_s0_flag[0]
553- w.put_bit(0); // num_ref_idx_active_override_flag
554- w.ue(4); // five_minus_max_num_merge_cand (MaxNumMergeCand = 1)
555- w.se(0); // slice_qp_delta
556- w.rbsp_trailing_bits(); // byte_alignment()
557-
558- // ---- slice_segment_data( ) ----
559- let mut cabac = CabacEncoder::new();
560- let mut ctxs = SliceContexts::init(init_type(1, false), SLICE_QP);
561- let mut skip_flags = vec![false; ctbs_x * ctbs_y];
562-
563- for ctb in 0..ctbs_x * ctbs_y {
564- let x0 = (ctb % ctbs_x) * CTB;
565- let y0 = (ctb / ctbs_x) * CTB;
566- let col = ctb % ctbs_x;
567- let row = ctb / ctbs_x;
568-
569- // MV (0, 0) prediction from the reference picture: the
570- // residual is the plane difference.
571- let diff = |cur: &[u8], refp: &[u8], pw: usize, bx: usize, by: usize, n: usize| {
572- let mut out = Vec::with_capacity(n * n);
573- for j in 0..n {
574- for i in 0..n {
575- let idx = (by + j) * pw + bx + i;
576- out.push(i32::from(cur[idx]) - i32::from(refp[idx]));
577- }
578- }
579- out
580- };
581- let res_l = diff(y, ry, width, x0, y0, CTB);
582- let res_cb = diff(cb, rcb, cw, x0 / 2, y0 / 2, 8);
583- let res_cr = diff(cr, rcr, cw, x0 / 2, y0 / 2, 8);
584- let all_zero = res_l.iter().all(|&v| v == 0)
585- && res_cb.iter().all(|&v| v == 0)
586- && res_cr.iter().all(|&v| v == 0);
587-
588- // §7.3.8.5: cu_transquant_bypass_flag precedes cu_skip_flag.
589- cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1);
590- // cu_skip_flag with the §9.3.4.2.2 neighbour ctxInc.
591- let ctx_inc = usize::from(col > 0 && skip_flags[ctb - 1])
592- + usize::from(row > 0 && skip_flags[ctb - ctbs_x]);
593- cabac.encode_decision(&mut w, &mut ctxs.cu_skip_flag[ctx_inc], u8::from(all_zero));
594- skip_flags[ctb] = all_zero;
595- if all_zero {
596- // Skip CU: MaxNumMergeCand == 1 ⇒ no merge_idx bins.
597- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
598- continue;
599- }
600-
601- cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); // MODE_INTER
602- cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N
603- cabac.encode_decision(&mut w, &mut ctxs.merge_flag[0], 1); // merge_flag
604- // merge_idx absent (MaxNumMergeCand == 1);
605- // rqt_root_cbf inferred 1 (2Nx2N merge).
606-
607- // Per-CTB explicit-RDPCM plan: two of three CUs signal the
608- // flag (alternating direction), the third is a flag-0 control.
609- let flag = ctb % 3 != 2;
610- let vertical = ctb % 2 == 0;
611-
612- let cbf_cb_f = res_cb.iter().any(|&v| v != 0);
613- let cbf_cr_f = res_cr.iter().any(|&v| v != 0);
614- let cbf_luma = res_l.iter().any(|&v| v != 0);
615- cabac.encode_decision(
616- &mut w,
617- &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
618- u8::from(cbf_cb_f),
619- );
620- cabac.encode_decision(
621- &mut w,
622- &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
623- u8::from(cbf_cr_f),
624- );
625- // §7.3.8.10: inter at depth 0 with no chroma cbf ⇒ cbf_luma
626- // inferred 1; otherwise signalled.
627- if cbf_cb_f || cbf_cr_f {
628- cabac.encode_decision(
629- &mut w,
630- &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize],
631- u8::from(cbf_luma),
632- );
633- } else {
634- assert!(cbf_luma, "all-zero CU must have been a skip CU");
635- }
636-
637- let emit = |cabac: &mut CabacEncoder,
638- wtr: &mut BitWriter,
639- ctxs: &mut SliceContexts,
640- res: &[i32],
641- log2: u32,
642- is_chroma: bool| {
643- // §7.3.8.11 prelude: explicit_rdpcm_flag / dir (inter +
644- // enabled + bypass; Table 9-32 / 9-33 slot by component).
645- let slot = usize::from(is_chroma);
646- cabac.encode_decision(wtr, &mut ctxs.explicit_rdpcm_flag[slot], u8::from(flag));
647- let levels = if flag {
648- cabac.encode_decision(
649- wtr,
650- &mut ctxs.explicit_rdpcm_dir_flag[slot],
651- u8::from(vertical),
652- );
653- dpcm_difference(res, 1 << log2, vertical)
654- } else {
655- res.to_vec()
656- };
657- let rc = ResidualCodingParams {
658- log2_trafo_size: log2,
659- is_chroma,
660- scan_idx: residual_coding_scan_idx(false, log2, u8::from(is_chroma), 1, 0),
661- sign_data_hiding_enabled_flag: false,
662- sign_hidden_suppressed: false,
663- transform_skip_sig_ctx: false,
664- persistent_rice_adaptation_enabled_flag: false,
665- cabac_bypass_alignment_enabled_flag: false,
666- extended_precision_processing_flag: false,
667- bit_depth: 8,
668- rice_stat_transform_skip: false,
669- };
670- encode_residual_coding(wtr, cabac, &mut ctxs.residual, &rc, &levels)
671- .expect("valid inter levels");
672- };
673- if cbf_luma {
674- emit(&mut cabac, &mut w, &mut ctxs, &res_l, 4, false);
675- }
676- if cbf_cb_f {
677- emit(&mut cabac, &mut w, &mut ctxs, &res_cb, 3, true);
678- }
679- if cbf_cr_f {
680- emit(&mut cabac, &mut w, &mut ctxs, &res_cr, 3, true);
681- }
682-
683- cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
684- }
685- w.align_zero();
686- w.finish()
687-}
688-
689-/// The implicit-RDPCM conformance stream: VPS + SPS(rext) + PPS +
690-/// one all-intra bypass IDR picture (64x48).
691-pub(crate) fn build_implicit_stream() -> (Vec<u8>, Planes) {
692- let (w, h) = (64usize, 48usize);
693- let (y, cb, cr) = source_planes(w, h, 0);
694- let slice = encode_bypass_idr_slice(&y, &cb, &cr, w, h);
695- let units = vec![
696- nal_unit(32, 0, 0, &write_vps_rext(30)),
697- nal_unit(33, 0, 0, &write_sps_rext(w, h, 30)),
698- nal_unit(34, 0, 0, &write_pps_bypass()),
699- nal_unit(20, 0, 0, &slice), // IDR_N_LP
700- ];
701- (annexb(&units), (y, cb, cr))
702-}
703-
704-/// The explicit-RDPCM conformance stream: the implicit IDR picture
705-/// followed by a P picture whose merge CUs carry per-component
706-/// explicit-RDPCM residuals (64x48, 2 frames).
707-pub(crate) fn build_explicit_stream() -> (Vec<u8>, Planes, Planes) {
708- let (w, h) = (64usize, 48usize);
709- let (y0, cb0, cr0) = source_planes(w, h, 0);
710- let (y1, cb1, cr1) = source_planes(w, h, 1);
711- let idr = encode_bypass_idr_slice(&y0, &cb0, &cr0, w, h);
712- let p = encode_bypass_p_slice(&y1, &cb1, &cr1, &y0, &cb0, &cr0, w, h);
713- let units = vec![
714- nal_unit(32, 0, 0, &write_vps_rext(30)),
715- nal_unit(33, 0, 0, &write_sps_rext(w, h, 30)),
716- nal_unit(34, 0, 0, &write_pps_bypass()),
717- nal_unit(20, 0, 0, &idr), // IDR_N_LP
718- nal_unit(1, 0, 0, &p), // TRAIL_R
719- ];
720- (annexb(&units), (y0, cb0, cr0), (y1, cb1, cr1))
721-}
722-
723-#[cfg(test)]
724-mod tests {
725- use super::*;
726- use crate::sequence::decode_annexb_sequence;
727-
728- fn planes_of(frame: &crate::sequence::DecodedFrame) -> Vec<u8> {
729- frame.picture.to_planar_u8().expect("8-bit planes")
730- }
731-
732- /// The checked-in stream bytes (black-box-reference-validated;
733- /// see `tests/fixture_bytes/r413-generation-notes.md`) are exactly
734- /// what the builder produces, and this crate's decoder
735- /// reconstructs the procedural source losslessly through the
736- /// §8.4.4.1 implicit-RDPCM path.
737- #[test]
738- fn implicit_rdpcm_stream_decodes_lossless() {
739- let (stream, (y, cb, cr)) = build_implicit_stream();
740- let pinned: &[u8] = include_bytes!(concat!(
741- env!("CARGO_MANIFEST_DIR"),
742- "/tests/fixture_bytes/r413-rdpcm-implicit.hevc"
743- ));
744- assert_eq!(stream, pinned, "builder must reproduce the validated bytes");
745- let frames = decode_annexb_sequence(&stream).expect("decode");
746- assert_eq!(frames.len(), 1);
747- let mut expected = y;
748- expected.extend(cb);
749- expected.extend(cr);
750- assert_eq!(planes_of(&frames[0]), expected, "lossless implicit RDPCM");
751- }
752-
753- /// Same pin for the explicit-RDPCM P picture (§8.5.4.2 step 3 /
754- /// §8.5.4.3 step 4 with both mDir values plus flag-0 controls).
755- #[test]
756- fn explicit_rdpcm_stream_decodes_lossless() {
757- let (stream, f0, f1) = build_explicit_stream();
758- let pinned: &[u8] = include_bytes!(concat!(
759- env!("CARGO_MANIFEST_DIR"),
760- "/tests/fixture_bytes/r413-rdpcm-explicit.hevc"
761- ));
762- assert_eq!(stream, pinned, "builder must reproduce the validated bytes");
763- let frames = decode_annexb_sequence(&stream).expect("decode");
764- assert_eq!(frames.len(), 2);
765- for (frame, (y, cb, cr)) in frames.iter().zip([f0, f1]) {
766- let mut expected = y;
767- expected.extend(cb);
768- expected.extend(cr);
769- assert_eq!(planes_of(frame), expected, "lossless explicit RDPCM");
770- }
771- }
772-}
vendor/oxideav-h265/src/encoder/residual.rsdeleted+0 -641

Diff too large; view file

@@ -1,641 +0,0 @@
1-//! §7.3.8.11 `residual_coding( )` *encoding* — the bin-exact dual of
2-//! [`crate::residual::decode_residual_coding_with`].
3-//!
4-//! Walks the coefficient array in the same reverse §6.5 scan the
5-//! decoder uses, emitting `last_sig_coeff_{x,y}_{prefix,suffix}`,
6-//! `coded_sub_block_flag`, `sig_coeff_flag`,
7-//! `coeff_abs_level_greater1_flag`, `coeff_abs_level_greater2_flag`,
8-//! `coeff_sign_flag` and `coeff_abs_level_remaining` through the
9-//! §9.3.5 arithmetic encoding engine, using the *same* §9.3.4.2
10-//! ctxInc derivation helpers as the decoder — so any block this
11-//! module emits decodes back to the identical `TransCoeffLevel`
12-//! array with identical context-state evolution (pinned by the
13-//! differential tests below).
14-//!
15-//! Scope bounds (the emitting encoder's fixed configuration, not
16-//! §7.3.8.11 limits): `sign_data_hiding_enabled_flag == 0` (a hidden
17-//! sign would require parity-forcing the quantized levels) and no
18-//! transform-skip / transquant-bypass residual rewrites.
19-
20-use crate::binarization::{
21- coded_sub_block_flag_ctx_inc_with_edge, coeff_abs_level_greater2_flag_ctx_inc,
22- coeff_abs_level_remaining_c_max_eq_9_26, coeff_abs_level_remaining_c_rice_param_eq_9_24,
23- last_sig_coeff_position, last_sig_coeff_prefix_cmax, last_sig_coeff_prefix_ctx_inc,
24- last_sig_coeff_prefix_ctx_offset_shift, last_sig_coeff_suffix_n_bits,
25- sig_coeff_flag_ctx_inc_from_sig_ctx, sig_coeff_flag_sig_ctx_dc, sig_coeff_flag_sig_ctx_general,
26- sig_coeff_flag_sig_ctx_log2_2, sig_coeff_flag_sig_ctx_transform_skip, Greater1State,
27-};
28-use crate::cabac::ContextModel;
29-use crate::encoder::bitwriter::BitWriter;
30-use crate::encoder::cabac::CabacEncoder;
31-use crate::residual::{ResidualCodingParams, ResidualContexts, ResidualElement};
32-use crate::scan::{scan_order, ScanIdx};
33-
34-/// Errors from [`encode_residual_coding`].
35-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36-pub enum ResidualEncodeError {
37- /// `log2TrafoSize` outside 2..=5.
38- UnsupportedLog2TrafoSize(u32),
39- /// A scan §7.4.9.11 never selects.
40- UnsupportedScanIdx(ScanIdx),
41- /// `levels.len() != (1 << log2TrafoSize)²`.
42- LengthMismatch {
43- /// Required level count.
44- expected: usize,
45- /// Supplied level count.
46- got: usize,
47- },
48- /// Every level is zero — the caller must signal `cbf == 0`
49- /// instead of invoking `residual_coding( )`.
50- AllZero,
51- /// A |level| exceeds the §7.4.9.11 CoeffMax bound for the
52- /// non-extended-precision profiles (`2^15 − 1`).
53- LevelOutOfRange(i32),
54- /// `sign_data_hiding_enabled_flag == 1` — this encoder does not
55- /// parity-force levels for hidden signs.
56- SignHidingUnsupported,
57-}
58-
59-impl core::fmt::Display for ResidualEncodeError {
60- fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
61- match self {
62- Self::UnsupportedLog2TrafoSize(v) => {
63- write!(f, "residual encode: log2TrafoSize {v} outside 2..=5")
64- }
65- Self::UnsupportedScanIdx(s) => {
66- write!(f, "residual encode: scanIdx {s:?} not reachable")
67- }
68- Self::LengthMismatch { expected, got } => {
69- write!(f, "residual encode: {got} levels, expected {expected}")
70- }
71- Self::AllZero => write!(f, "residual encode: all-zero block (cbf must be 0)"),
72- Self::LevelOutOfRange(v) => write!(f, "residual encode: level {v} out of range"),
73- Self::SignHidingUnsupported => {
74- write!(f, "residual encode: sign data hiding not supported")
75- }
76- }
77- }
78-}
79-
80-impl std::error::Error for ResidualEncodeError {}
81-
82-/// Bank dispatch — the encode dual of the decoder's
83-/// `EngineResidualBinSource` element→bank mapping.
84-fn bank(contexts: &mut ResidualContexts, element: ResidualElement) -> &mut [ContextModel] {
85- match element {
86- ResidualElement::LastSigCoeffXPrefix => &mut contexts.last_sig_coeff_x_prefix,
87- ResidualElement::LastSigCoeffYPrefix => &mut contexts.last_sig_coeff_y_prefix,
88- ResidualElement::CodedSubBlockFlag => &mut contexts.coded_sub_block_flag,
89- ResidualElement::SigCoeffFlag => &mut contexts.sig_coeff_flag,
90- ResidualElement::CoeffAbsLevelGreater1Flag => &mut contexts.coeff_abs_level_greater1_flag,
91- ResidualElement::CoeffAbsLevelGreater2Flag => &mut contexts.coeff_abs_level_greater2_flag,
92- }
93-}
94-
95-/// Invert §7.4.9.11 eqs. 7-74..7-77: split a `LastSignificantCoeff*`
96-/// position into its `(prefix, suffix)` wire pair.
97-fn split_last_sig_position(v: u32, c_max: u32) -> (u32, Option<(u32, u32)>) {
98- for prefix in 0..=c_max {
99- let n_bits = last_sig_coeff_suffix_n_bits(prefix);
100- if n_bits == 0 {
101- if last_sig_coeff_position(prefix, None) == v {
102- return (prefix, None);
103- }
104- } else {
105- let base = last_sig_coeff_position(prefix, Some(0));
106- if v >= base && v < base + (1u32 << n_bits) {
107- return (prefix, Some((v - base, n_bits)));
108- }
109- }
110- }
111- unreachable!("last-sig position exceeds the TB (caller bounds it)")
112-}
113-
114-/// Emit one `last_sig_coeff_*_prefix` as its §9.3.3.2 TR bin string
115-/// (unary ones, a terminating zero unless `prefix == cMax`), each bin
116-/// context-coded with the §9.3.4.2.3 ctxInc.
117-fn encode_last_sig_prefix(
118- w: &mut BitWriter,
119- cabac: &mut CabacEncoder,
120- contexts: &mut ResidualContexts,
121- element: ResidualElement,
122- log2_trafo_size: u32,
123- is_chroma: bool,
124- prefix: u32,
125-) {
126- let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size);
127- let (ctx_offset, ctx_shift) =
128- last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma);
129- for bin_idx in 0..prefix {
130- let inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift);
131- cabac.encode_decision(w, &mut bank(contexts, element)[inc as usize], 1);
132- }
133- if prefix < c_max {
134- let inc = last_sig_coeff_prefix_ctx_inc(prefix, ctx_offset, ctx_shift);
135- cabac.encode_decision(w, &mut bank(contexts, element)[inc as usize], 0);
136- }
137-}
138-
139-/// §9.3.3.11 — emit one `coeff_abs_level_remaining` value as the TR
140-/// prefix (escape at 4 ones) + conditional EGk(`cRiceParam + 1`)
141-/// suffix, all bypass-coded. The bin-exact dual of
142-/// [`crate::binarization::decode_coeff_abs_level_remaining_with`].
143-fn encode_coeff_abs_level_remaining(
144- w: &mut BitWriter,
145- cabac: &mut CabacEncoder,
146- c_rice_param: u32,
147- value: u32,
148-) {
149- let c_max = coeff_abs_level_remaining_c_max_eq_9_26(c_rice_param);
150- if value < c_max {
151- // TR shape: `value >> cRiceParam` ones + terminating zero +
152- // `cRiceParam` suffix bits.
153- let prefix_len = value >> c_rice_param;
154- for _ in 0..prefix_len {
155- cabac.encode_bypass(w, 1);
156- }
157- cabac.encode_bypass(w, 0);
158- if c_rice_param > 0 {
159- cabac.encode_bypass_bits(w, value & ((1 << c_rice_param) - 1), c_rice_param as u8);
160- }
161- return;
162- }
163- // Escape: 4 ones (no terminator), then EGk with k = cRiceParam+1
164- // over `value − cMax`: `prefix_ones` ones + one zero +
165- // `prefix_ones + k` suffix bits of `v' − ((1 << prefix_ones) − 1)
166- // << k`.
167- for _ in 0..4 {
168- cabac.encode_bypass(w, 1);
169- }
170- let k = c_rice_param + 1;
171- let v = value - c_max;
172- let mut prefix_ones = 0u32;
173- while (((1u64 << (prefix_ones + 1)) - 1) << k) <= u64::from(v) {
174- prefix_ones += 1;
175- }
176- let base = ((1u64 << prefix_ones) - 1) << k;
177- let suffix = u64::from(v) - base;
178- for _ in 0..prefix_ones {
179- cabac.encode_bypass(w, 1);
180- }
181- cabac.encode_bypass(w, 0);
182- let n_bits = prefix_ones + k;
183- for i in (0..n_bits).rev() {
184- cabac.encode_bypass(w, ((suffix >> i) & 1) as u8);
185- }
186-}
187-
188-/// §7.3.8.11 — encode one `residual_coding( )` body from the
189-/// row-major `TransCoeffLevel` array (`levels[yC * size + xC]`),
190-/// following the decoder's control flow exactly (same inference
191-/// rules, same ctxInc derivations, same §9.3.4.2.6 greater-1 state
192-/// machine).
193-///
194-/// # Errors
195-/// [`ResidualEncodeError`] on out-of-scope parameters or an all-zero
196-/// / out-of-range level array.
197-pub fn encode_residual_coding(
198- w: &mut BitWriter,
199- cabac: &mut CabacEncoder,
200- contexts: &mut ResidualContexts,
201- params: &ResidualCodingParams,
202- levels: &[i32],
203-) -> Result<(), ResidualEncodeError> {
204- let log2 = params.log2_trafo_size;
205- if !(2..=5).contains(&log2) {
206- return Err(ResidualEncodeError::UnsupportedLog2TrafoSize(log2));
207- }
208- let scan_idx_num = u32::from(params.scan_idx.index());
209- if scan_idx_num > 2 {
210- return Err(ResidualEncodeError::UnsupportedScanIdx(params.scan_idx));
211- }
212- if params.sign_data_hiding_enabled_flag {
213- return Err(ResidualEncodeError::SignHidingUnsupported);
214- }
215- let size = 1usize << log2;
216- if levels.len() != size * size {
217- return Err(ResidualEncodeError::LengthMismatch {
218- expected: size * size,
219- got: levels.len(),
220- });
221- }
222- if let Some(&bad) = levels.iter().find(|&&v| v.unsigned_abs() > 0x7FFF) {
223- return Err(ResidualEncodeError::LevelOutOfRange(bad));
224- }
225- let is_chroma = params.is_chroma;
226-
227- let pos_scan = scan_order(2, params.scan_idx)
228- .map_err(|_| ResidualEncodeError::UnsupportedScanIdx(params.scan_idx))?;
229- let sub_scan = scan_order((log2 - 2) as u8, params.scan_idx)
230- .map_err(|_| ResidualEncodeError::UnsupportedScanIdx(params.scan_idx))?;
231- let num_sb_1d = 1usize << (log2 - 2);
232-
233- // Locate the last significant coefficient in scan order.
234- let coeff_at = |sb_i: usize, n: usize| -> i32 {
235- let sb = sub_scan[sb_i];
236- let xc = ((sb.x as usize) << 2) + pos_scan[n].x as usize;
237- let yc = ((sb.y as usize) << 2) + pos_scan[n].y as usize;
238- levels[yc * size + xc]
239- };
240- let mut last_sub_block: i32 = -1;
241- let mut last_scan_pos: i32 = -1;
242- for i in 0..num_sb_1d * num_sb_1d {
243- for n in 0..16 {
244- if coeff_at(i, n) != 0 {
245- last_sub_block = i as i32;
246- last_scan_pos = n as i32;
247- }
248- }
249- }
250- if last_sub_block < 0 {
251- return Err(ResidualEncodeError::AllZero);
252- }
253-
254- // §7.4.9.11 LastSignificantCoeff{X,Y} (+ the eq.-7-78 swap for the
255- // vertical scan), split into prefix/suffix wire pairs.
256- let sb = sub_scan[last_sub_block as usize];
257- let last_x = ((sb.x as u32) << 2) + u32::from(pos_scan[last_scan_pos as usize].x);
258- let last_y = ((sb.y as u32) << 2) + u32::from(pos_scan[last_scan_pos as usize].y);
259- let (wire_x, wire_y) = if params.scan_idx == ScanIdx::Vertical {
260- (last_y, last_x)
261- } else {
262- (last_x, last_y)
263- };
264- let c_max = last_sig_coeff_prefix_cmax(log2);
265- let (prefix_x, suffix_x) = split_last_sig_position(wire_x, c_max);
266- let (prefix_y, suffix_y) = split_last_sig_position(wire_y, c_max);
267- // §7.3.8.11 bin order: both context-coded prefixes, then both
268- // bypass suffixes.
269- encode_last_sig_prefix(
270- w,
271- cabac,
272- contexts,
273- ResidualElement::LastSigCoeffXPrefix,
274- log2,
275- is_chroma,
276- prefix_x,
277- );
278- encode_last_sig_prefix(
279- w,
280- cabac,
281- contexts,
282- ResidualElement::LastSigCoeffYPrefix,
283- log2,
284- is_chroma,
285- prefix_y,
286- );
287- if let Some((suffix, n_bits)) = suffix_x {
288- cabac.encode_bypass_bits(w, suffix, n_bits as u8);
289- }
290- if let Some((suffix, n_bits)) = suffix_y {
291- cabac.encode_bypass_bits(w, suffix, n_bits as u8);
292- }
293-
294- // coded_sub_block_flag grid, filled progressively in reverse scan
295- // order exactly as the decoder builds it.
296- let mut csbf = vec![0u8; num_sb_1d * num_sb_1d];
297- let csbf_at = |grid: &[u8], xs: usize, ys: usize| -> u8 {
298- if xs < num_sb_1d && ys < num_sb_1d {
299- grid[ys * num_sb_1d + xs]
300- } else {
301- 0
302- }
303- };
304-
305- let mut g1_state = Greater1State::new();
306- let mut last_g1_bin: u8 = 0;
307-
308- for i in (0..=last_sub_block).rev() {
309- let sb = sub_scan[i as usize];
310- let (xs, ys) = (u32::from(sb.x), u32::from(sb.y));
311- let is_last_sb = i == last_sub_block;
312- let any_nonzero = (0..16).any(|n| coeff_at(i as usize, n) != 0);
313-
314- // coded_sub_block_flag: coded for 0 < i < lastSubBlock,
315- // inferred 1 otherwise.
316- let mut infer_sb_dc_sig = false;
317- let sb_coded: u8 = if i < last_sub_block && i > 0 {
318- let right = csbf_at(&csbf, xs as usize + 1, ys as usize);
319- let below = csbf_at(&csbf, xs as usize, ys as usize + 1);
320- let ctx_inc =
321- coded_sub_block_flag_ctx_inc_with_edge(is_chroma, xs, ys, log2, right, below);
322- let bin = u8::from(any_nonzero);
323- cabac.encode_decision(
324- w,
325- &mut bank(contexts, ResidualElement::CodedSubBlockFlag)[ctx_inc as usize],
326- bin,
327- );
328- infer_sb_dc_sig = true;
329- bin
330- } else {
331- 1
332- };
333- csbf[ys as usize * num_sb_1d + xs as usize] = sb_coded;
334- if sb_coded == 0 {
335- continue;
336- }
337-
338- // sig_coeff_flag pass (same coding/inference split as decode).
339- let mut sig = [0u8; 16];
340- if is_last_sb {
341- sig[last_scan_pos as usize] = 1;
342- }
343- let start_n: i32 = if is_last_sb { last_scan_pos - 1 } else { 15 };
344- for n in (0..=start_n).rev() {
345- let significant = u8::from(coeff_at(i as usize, n as usize) != 0);
346- let xc = (xs << 2) + u32::from(pos_scan[n as usize].x);
347- let yc = (ys << 2) + u32::from(pos_scan[n as usize].y);
348- if n > 0 || !infer_sb_dc_sig {
349- let sig_ctx = if params.transform_skip_sig_ctx {
350- sig_coeff_flag_sig_ctx_transform_skip(is_chroma)
351- } else if log2 == 2 {
352- sig_coeff_flag_sig_ctx_log2_2(xc & 3, yc & 3)
353- } else if xc + yc == 0 {
354- sig_coeff_flag_sig_ctx_dc(is_chroma, log2, scan_idx_num)
355- } else {
356- let right = csbf_at(&csbf, xs as usize + 1, ys as usize);
357- let below = csbf_at(&csbf, xs as usize, ys as usize + 1);
358- sig_coeff_flag_sig_ctx_general(
359- is_chroma,
360- log2,
361- xc,
362- yc,
363- xs,
364- ys,
365- right,
366- below,
367- scan_idx_num,
368- )
369- };
370- let ctx_inc = sig_coeff_flag_ctx_inc_from_sig_ctx(sig_ctx, is_chroma);
371- cabac.encode_decision(
372- w,
373- &mut bank(contexts, ResidualElement::SigCoeffFlag)[ctx_inc as usize],
374- significant,
375- );
376- sig[n as usize] = significant;
377- if significant == 1 {
378- infer_sb_dc_sig = false;
379- }
380- } else {
381- // n == 0 with the DC inference alive: the decoder
382- // infers sig[0] = 1; a conforming encoder only reaches
383- // here when the DC coefficient IS significant (a coded
384- // sub-block cannot be all-zero).
385- debug_assert_eq!(significant, 1, "coded sub-block with only a zero DC");
386- sig[0] = 1;
387- }
388- }
389-
390- // greater-1 pass: the first 8 significant positions carry a
391- // coded flag; the §9.3.4.2.6 state machine advances on the
392- // encoder's own bins.
393- let mut first_sig_scan_pos: i32 = 16;
394- let mut last_sig_scan_pos: i32 = -1;
395- let mut num_greater1: u32 = 0;
396- let mut last_greater1_scan_pos: i32 = -1;
397- let mut g1 = [0u8; 16];
398- let mut entered_subblock = false;
399- for n in (0..16usize).rev() {
400- if sig[n] == 1 {
401- let abs = coeff_at(i as usize, n).unsigned_abs();
402- if num_greater1 < 8 {
403- if !entered_subblock {
404- g1_state.on_subblock_entry(i as u32, is_chroma, last_g1_bin);
405- entered_subblock = true;
406- }
407- let ctx_inc = g1_state.current_ctx_inc(is_chroma);
408- let bin = u8::from(abs > 1);
409- cabac.encode_decision(
410- w,
411- &mut bank(contexts, ResidualElement::CoeffAbsLevelGreater1Flag)
412- [ctx_inc as usize],
413- bin,
414- );
415- g1_state.on_coeff_abs_level_greater1_flag(bin);
416- last_g1_bin = bin;
417- g1[n] = bin;
418- num_greater1 += 1;
419- if bin == 1 && last_greater1_scan_pos == -1 {
420- last_greater1_scan_pos = n as i32;
421- }
422- }
423- if last_sig_scan_pos == -1 {
424- last_sig_scan_pos = n as i32;
425- }
426- first_sig_scan_pos = n as i32;
427- }
428- }
429- let _ = (first_sig_scan_pos, last_sig_scan_pos); // sign hiding off
430-
431- // greater-2 flag — at most once per sub-block.
432- let mut g2 = [0u8; 16];
433- if last_greater1_scan_pos != -1 {
434- let ctx_inc = coeff_abs_level_greater2_flag_ctx_inc(g1_state.ctx_set(), is_chroma);
435- let abs = coeff_at(i as usize, last_greater1_scan_pos as usize).unsigned_abs();
436- let bin = u8::from(abs > 2);
437- cabac.encode_decision(
438- w,
439- &mut bank(contexts, ResidualElement::CoeffAbsLevelGreater2Flag)[ctx_inc as usize],
440- bin,
441- );
442- g2[last_greater1_scan_pos as usize] = bin;
443- }
444-
445- // coeff_sign_flag pass (bypass; sign hiding disabled).
446- for n in (0..16usize).rev() {
447- if sig[n] == 1 {
448- let sign = u8::from(coeff_at(i as usize, n) < 0);
449- cabac.encode_bypass(w, sign);
450- }
vendor/oxideav-h265/src/encoder/scc_streams.rsdeleted+0 -936

Diff too large; view file

vendor/oxideav-h265/src/hrd.rsdeleted+0 -1044

Diff too large; view file

vendor/oxideav-h265/src/hvcc.rsdeleted+0 -408

Diff too large; view file

vendor/oxideav-h265/src/inter_pred.rsdeleted+0 -1385

Diff too large; view file

vendor/oxideav-h265/src/inter_recon.rsdeleted+0 -1933

Diff too large; view file

vendor/oxideav-h265/src/intra_mode_field.rsdeleted+0 -371

Diff too large; view file

vendor/oxideav-h265/src/intra_pred.rsdeleted+0 -1230

Diff too large; view file

vendor/oxideav-h265/src/lib.rsdeleted+0 -616

Diff too large; view file

vendor/oxideav-h265/src/motion.rsdeleted+0 -1826

Diff too large; view file

vendor/oxideav-h265/src/nal.rsdeleted+0 -342

Diff too large; view file

vendor/oxideav-h265/src/palette.rsdeleted+0 -981

Diff too large; view file

vendor/oxideav-h265/src/picture.rsdeleted+0 -327

Diff too large; view file

vendor/oxideav-h265/src/poc.rsdeleted+0 -403

Diff too large; view file

vendor/oxideav-h265/src/pps.rsdeleted+0 -1880

Diff too large; view file

vendor/oxideav-h265/src/pu_mv.rsdeleted+0 -1228

Diff too large; view file

vendor/oxideav-h265/src/recon.rsdeleted+0 -3899

Diff too large; view file

vendor/oxideav-h265/src/residual.rsdeleted+0 -1588

Diff too large; view file

vendor/oxideav-h265/src/sao.rsdeleted+0 -762

Diff too large; view file

vendor/oxideav-h265/src/scaling_list.rsdeleted+0 -1011

Diff too large; view file

vendor/oxideav-h265/src/scan.rsdeleted+0 -552

Diff too large; view file

vendor/oxideav-h265/src/sei.rsdeleted+0 -607

Diff too large; view file

vendor/oxideav-h265/src/sei/tests.rsdeleted+0 -478

Diff too large; view file

vendor/oxideav-h265/src/sequence.rsdeleted+0 -1620

Diff too large; view file

vendor/oxideav-h265/src/slice.rsdeleted+0 -5567

Diff too large; view file

vendor/oxideav-h265/src/slice_data.rsdeleted+0 -1527

Diff too large; view file

vendor/oxideav-h265/src/slice_data/tests.rsdeleted+0 -165

Diff too large; view file

vendor/oxideav-h265/src/sps.rsdeleted+0 -3501

Diff too large; view file

vendor/oxideav-h265/src/transform.rsdeleted+0 -1152

Diff too large; view file

vendor/oxideav-h265/src/transform_tree.rsdeleted+0 -347

Diff too large; view file

vendor/oxideav-h265/src/transform_tree/tests.rsdeleted+0 -227

Diff too large; view file

vendor/oxideav-h265/src/transform_unit.rsdeleted+0 -672

Diff too large; view file

vendor/oxideav-h265/src/vps.rsdeleted+0 -1231

Diff too large; view file

vendor/oxideav-h265/src/vui.rsdeleted+0 -1017

Diff too large; view file