forge
Explore
Log in

Don't you dare go Hollow

✨ merge(T2): HEVC intra export — both containers, cropped 1080p

Browse files at this commit

303919e6701eb56cc284ed0887533df1123145ddAhmet Kaan GümüşParent: 59c74e812f8cb7

68 changed files +69062 -97

Cargo.lockmodified+8 -0
@@ -1637,6 +1637,7 @@ dependencies = [
1637 "mp4",1637 "mp4",
1638 "oxideav-ac3",1638 "oxideav-ac3",
1639 "oxideav-core",1639 "oxideav-core",
1640+ "oxideav-h265",
1640 "rav1e",1641 "rav1e",
1641 "rusty_aac",1642 "rusty_aac",
1642 "rusty_h264",1643 "rusty_h264",
@@ -3950,6 +3951,13 @@ dependencies = [
3950 "thiserror 2.0.20",3951 "thiserror 2.0.20",
3951 ]3952 ]
3952 3953
3954+[[package]]
3955+name = "oxideav-h265"
3956+version = "0.0.9"
3957+dependencies = [
3958+ "oxideav-core",
3959+]
3960+
3953 [[package]]3961 [[package]]
3954 name = "parking"3962 name = "parking"
3955 version = "2.2.1"3963 version = "2.2.1"
Cargo.tomlmodified+21 -4
@@ -2,14 +2,20 @@
2 resolver = "3"2 resolver = "3"
3 members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"]3 members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"]
4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.4 # Vendored third-party (see [patch.crates-io]); not ours to build or test.
5-exclude = ["vendor/cros-libva", "vendor/cros-codecs", "vendor/rusty_aac"]5+exclude = [
6+ "vendor/cros-libva",
7+ "vendor/cros-codecs",
8+ "vendor/rusty_aac",
9+ "vendor/oxideav-h265",
10+]
6 11
7 [workspace.package]12 [workspace.package]
8 version = "0.1.0"13 version = "0.1.0"
9 edition = "2024"14 edition = "2024"
10 15
11-# Three upstream crates vendored verbatim except for one clearly marked fix each,16+# Four upstream crates vendored verbatim except for one clearly marked fix each,
12-# all blockers on this machine and all still unfixed upstream as of 0.0.6/0.0.13/0.5.0:17+# all blockers on this machine and all still unfixed upstream as of
18+# 0.0.6/0.0.13/0.5.0/0.0.9:
13 # cros-libva - fails to build against libva >= 1.23 headers19 # cros-libva - fails to build against libva >= 1.23 headers
14 # 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;
15 # 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
@@ -18,7 +24,18 @@ edition = "2024"
18 # term (the fast path in the same file serves the encoder only),24 # term (the fast path in the same file serves the encoder only),
19 # which is 4x slower than real time for 5.1 and therefore not25 # which is 4x slower than real time for 5.1 and therefore not
20 # playable at all; the patch caches the cosine matrix26 # playable at all; the patch caches the cosine matrix
21-# Drop `vendor/` entirely once released versions handle all three.27+# oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and
28+# refuses any dimension that is not a multiple of the 16-sample
29+# CTB, so 1920x1080 could not be written at all; the patch adds
30+# the §7.4.3.2.1 conformance window (`SpsCfg::conf_win`, one
31+# marked block in `encoder/intra.rs`) so the picture is coded
32+# padded to 1920x1088 and *displayed* at 1920x1080. Taken from
33+# git master rather than the registry -- crates.io 0.0.9 is the
34+# pre-encoder release -- at rev d35963a02c872d12e6878b4ed3cf17a
35+# 69bde5a6e, and it is a plain path dependency (no
36+# `[patch.crates-io]` line) because nothing else in the tree
37+# asks for it.
38+# Drop `vendor/` entirely once released versions handle all four.
22 [patch.crates-io]39 [patch.crates-io]
23 cros-libva = { path = "vendor/cros-libva" }40 cros-libva = { path = "vendor/cros-libva" }
24 cros-codecs = { path = "vendor/cros-codecs" }41 cros-codecs = { path = "vendor/cros-codecs" }
crates/app/src/keymap.rsmodified+3 -2
@@ -337,8 +337,9 @@ pub const FIXED: [Fixed; 16] = [
337 category: Category::File,337 category: Category::File,
338 },338 },
339 Fixed {339 Fixed {
340- chord: "m / a / v / w / f / p",340+ chord: "m / a / v / h / x / w / f / p",
341- label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, WAV, FLAC or MP3",341+ label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, HEVC in MKV, \
342+ HEVC in MP4, WAV, FLAC or MP3",
342 category: Category::File,343 category: Category::File,
343 },344 },
344 Fixed {345 Fixed {
crates/app/src/main.rsmodified+59 -22
@@ -117,7 +117,7 @@ const KEYS_ROW_H: f32 = HIT_MIN;
117 /// editor grows -- ten rows fit here, and the eleventh is a scroll away.117 /// editor grows -- ten rows fit here, and the eleventh is a scroll away.
118 const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;118 const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
119 /// The same for the export card, which carries a fixed-format line and a button119 /// The same for the export card, which carries a fixed-format line and a button
120-/// under its list and so has less room: destination, nine formats and five120+/// under its list and so has less room: destination, ten formats and five
121 /// qualities are fifteen rows, eight of them on screen.121 /// qualities are fifteen rows, eight of them on screen.
122 const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;122 const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
123 /// The menu a right-click on a clip opens: wide enough for the longest label123 /// The menu a right-click on a clip opens: wide enough for the longest label
@@ -4802,11 +4802,12 @@ impl Player {
4802 .text_size(px(11.))4802 .text_size(px(11.))
4803 .text_color(rgb(INK_DIM))4803 .text_color(rgb(INK_DIM))
4804 .child(self.notice.clone().unwrap_or_else(|| {4804 .child(self.notice.clone().unwrap_or_else(|| {
4805- "pick a format (m/a/v/w/f/p), then Export — esc closes".into()4805+ "pick a format (m/a/v/h/x/w/f/p), then Export — esc closes"
4806+ .into()
4806 })),4807 })),
4807 )4808 )
4808 // Capped and scrolling like the keybindings list: the4809 // Capped and scrolling like the keybindings list: the
4809- // destination, nine formats and five qualities are more4810+ // destination, ten formats and five qualities are more
4810 // rows than a 360 px window has room for, and it is the4811 // rows than a 360 px window has room for, and it is the
4811 // list that scrolls, never the card that grows.4812 // list that scrolls, never the card that grows.
4812 .child(4813 .child(
@@ -6941,20 +6942,23 @@ impl Quality {
6941 /// as a claim that nothing else exists -- so the refusals are rows too, dimmed6942 /// as a claim that nothing else exists -- so the refusals are rows too, dimmed
6942 /// and unclickable.6943 /// and unclickable.
6943 ///6944 ///
6944-/// `None` is exactly that kind of row, and there are three left. MP3 stopped6945+/// `None` is exactly that kind of row, and there are two left. MP3 stopped
6945 /// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL6946 /// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
6946 /// `shine-rs` was the licence question, and it is not the only encoder any6947 /// `shine-rs` was the licence question, and it is not the only encoder any
6947-/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the6948+/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an
6948-/// plugin decodes both and there is no encoder for either here -- so they are6949+/// encoder — an *intra-only* one, which the rows say rather than let a user
6949-/// rows for the same reason: a codec that opens but never comes back out is6950+/// find out from the size of the file. VP9 is the one this program still only
6950-/// exactly the gap a user would otherwise go looking for. AAC is not a row at6951+/// *reads*: the plugin decodes it and there is no encoder for it here, so it is
6951-/// all: it is what both containers' sound *is*, never a file of its own.6952+/// a row for the reason the refusals are rows at all — a codec that opens but
6953+/// never comes back out is exactly the gap a user would otherwise go looking
6954+/// for. AAC is not a row at all: it is what both containers' sound *is*, never a
6955+/// file of its own.
6952 ///6956 ///
6953 /// AV1 is two rows because a codec and a container are two choices: the same6957 /// AV1 is two rows because a codec and a container are two choices: the same
6954 /// picture and the same AAC track go into a Matroska file or into an mp4, and6958 /// picture and the same AAC track go into a Matroska file or into an mp4, and
6955 /// which one a user needs is about what has to play the file, not about the6959 /// which one a user needs is about what has to play the file, not about the
6956-/// encode.6960+/// encode. HEVC is two rows for the same reason.
6957-const FORMATS: [(Option<Format>, &str, &str, &str); 9] = [6961+const FORMATS: [(Option<Format>, &str, &str, &str); 10] = [
6958 (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"),6962 (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"),
6959 (6963 (
6960 Some(Format::Av1),6964 Some(Format::Av1),
@@ -6968,6 +6972,18 @@ const FORMATS: [(Option<Format>, &str, &str, &str); 9] = [
6968 "AV1 · MP4",6972 "AV1 · MP4",
6969 "the same AV1 picture and sound in .mp4",6973 "the same AV1 picture and sound in .mp4",
6970 ),6974 ),
6975+ (
6976+ Some(Format::Hevc),
6977+ "h",
6978+ "HEVC · MKV",
6979+ "intra-only HEVC + AAC in .mkv — large files",
6980+ ),
6981+ (
6982+ Some(Format::HevcMp4),
6983+ "x",
6984+ "HEVC · MP4",
6985+ "the same intra-only HEVC and sound in .mp4",
6986+ ),
6971 (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"),6987 (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"),
6972 (Some(Format::Flac), "f", "FLAC", "lossless — audio only"),6988 (Some(Format::Flac), "f", "FLAC", "lossless — audio only"),
6973 (6989 (
@@ -6977,12 +6993,6 @@ const FORMATS: [(Option<Format>, &str, &str, &str); 9] = [
6977 "MPEG-1 Layer III, 256 kbps — audio only",6993 "MPEG-1 Layer III, 256 kbps — audio only",
6978 ),6994 ),
6979 (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"),6995 (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"),
6980- (
6981- None,
6982- "",
6983- "HEVC",
6984- "no encoder in this stack, and patent-encumbered",
6985- ),
6986 (None, "", "VP9", "superseded by AV1, which is the row above"),6996 (None, "", "VP9", "superseded by AV1, which is the row above"),
6987 ];6997 ];
6988 6998
@@ -7167,6 +7177,8 @@ fn format_line(format: Format) -> &'static str {
7167 Format::Mp4 => "H.264 · MP4 · moov at end",7177 Format::Mp4 => "H.264 · MP4 · moov at end",
7168 Format::Av1 => "AV1 · Matroska · picture and sound",7178 Format::Av1 => "AV1 · Matroska · picture and sound",
7169 Format::Av1Mp4 => "AV1 · MP4 · picture and sound",7179 Format::Av1Mp4 => "AV1 · MP4 · picture and sound",
7180+ Format::Hevc => "HEVC intra · Matroska · picture and sound",
7181+ Format::HevcMp4 => "HEVC intra · MP4 · picture and sound",
7170 Format::Wav => "16-bit PCM · WAV · timeline audio only",7182 Format::Wav => "16-bit PCM · WAV · timeline audio only",
7171 Format::Flac => "FLAC · lossless · timeline audio only",7183 Format::Flac => "FLAC · lossless · timeline audio only",
7172 Format::Mp3 => "MP3 · 256 kbps · timeline audio only",7184 Format::Mp3 => "MP3 · 256 kbps · timeline audio only",
@@ -10254,6 +10266,8 @@ mod tests {
10254 Format::Mp4,10266 Format::Mp4,
10255 Format::Av1,10267 Format::Av1,
10256 Format::Av1Mp4,10268 Format::Av1Mp4,
10269+ Format::Hevc,
10270+ Format::HevcMp4,
10257 Format::Wav,10271 Format::Wav,
10258 Format::Flac,10272 Format::Flac,
10259 Format::Mp310273 Format::Mp3
@@ -10261,10 +10275,14 @@ mod tests {
10261 );10275 );
10262 assert_eq!(Format::Av1.ext(), "mkv");10276 assert_eq!(Format::Av1.ext(), "mkv");
10263 assert_eq!(Format::Av1Mp4.ext(), "mp4");10277 assert_eq!(Format::Av1Mp4.ext(), "mp4");
10278+ assert_eq!(Format::Hevc.ext(), "mkv");
10279+ assert_eq!(Format::HevcMp4.ext(), "mp4");
10264 for (format, _, label, _) in FORMATS {10280 for (format, _, label, _) in FORMATS {
10265 match format {10281 match format {
10266 Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"),10282 Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"),
10267 Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"),10283 Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"),
10284+ Some(Format::Hevc) => assert_eq!(label, "HEVC · MKV"),
10285+ Some(Format::HevcMp4) => assert_eq!(label, "HEVC · MP4"),
10268 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),10286 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
10269 // A refused format is a row with a reason, never a hidden one:10287 // A refused format is a row with a reason, never a hidden one:
10270 // an empty detail column would read as an oversight.10288 // an empty detail column would read as an oversight.
@@ -10277,7 +10295,12 @@ mod tests {
10277 // dims them off exactly this.10295 // dims them off exactly this.
10278 assert_eq!(10296 assert_eq!(
10279 format.is_some_and(Format::has_video),10297 format.is_some_and(Format::has_video),
10280- matches!(format, Some(Format::Mp4 | Format::Av1 | Format::Av1Mp4))10298+ matches!(
10299+ format,
10300+ Some(
10301+ Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4
10302+ )
10303+ )
10281 );10304 );
10282 // Every row that can be picked has a key of its own, and no two10305 // Every row that can be picked has a key of its own, and no two
10283 // share one: the card is drivable without a pointer.10306 // share one: the card is drivable without a pointer.
@@ -10290,10 +10313,11 @@ mod tests {
10290 );10313 );
10291 }10314 }
10292 }10315 }
10293- // The two codecs this program reads and cannot write are rows of their10316+ // The codec this program reads and cannot write is a row of its own,
10294- // own, refused by name rather than absent -- HEVC for want of an encoder10317+ // refused by name rather than absent: VP9, because AV1 is the row that
10295- // (and for its patents), VP9 because AV1 is the row that replaced it.10318+ // replaced it. HEVC used to be one beside it and is now two rows that
10296- for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] {10319+ // pick -- an intra-only encoder is still an encoder.
10320+ for (label, word) in [("VP9", "superseded")] {
10297 let (format, _, _, detail) = FORMATS10321 let (format, _, _, detail) = FORMATS
10298 .into_iter()10322 .into_iter()
10299 .find(|(_, _, row, _)| *row == label)10323 .find(|(_, _, row, _)| *row == label)
@@ -10312,8 +10336,21 @@ mod tests {
10312 assert!(detail.contains("sound"), "{detail}");10336 assert!(detail.contains("sound"), "{detail}");
10313 assert!(format_line(format).contains("picture and sound"));10337 assert!(format_line(format).contains("picture and sound"));
10314 }10338 }
10339+ // ...and both HEVC rows say what they are before a user waits on one:
10340+ // intra-only, which is a file several times the size of the AV1 above
10341+ // it. A row that hid that would be found out by the disk.
10342+ for format in [Format::Hevc, Format::HevcMp4] {
10343+ let (_, _, _, detail) = FORMATS
10344+ .into_iter()
10345+ .find(|(f, ..)| *f == Some(format))
10346+ .expect("an HEVC row");
10347+ assert!(detail.contains("intra-only"), "{detail}");
10348+ assert!(format_line(format).contains("picture and sound"));
10349+ }
10315 assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one");10350 assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one");
10316 assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one");10351 assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one");
10352+ assert_eq!(format_key("h"), Some(Format::Hevc), "HEVC's Matroska");
10353+ assert_eq!(format_key("x"), Some(Format::HevcMp4), "and its mp4");
10317 assert_eq!(format_key("p"), Some(Format::Mp3));10354 assert_eq!(format_key("p"), Some(Format::Mp3));
10318 assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p");10355 assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p");
10319 // The destination follows the format and keeps the stem, mp4 included.10356 // The destination follows the format and keeps the stem, mp4 included.
crates/engine/Cargo.tomlmodified+8 -0
@@ -74,6 +74,14 @@ oxideav-core = "0.1.34"
74 # inside rav1e itself and is what keeps an export minutes rather than tens of74 # inside rav1e itself and is what keeps an export minutes rather than tens of
75 # minutes; the cost of no assembly is measured in `export::Enc::open_av1`.75 # minutes; the cost of no assembly is measured in `export::Enc::open_av1`.
76 rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }76 rav1e = { version = "0.8.1", default-features = false, features = ["threading"] }
77+# The software HEVC encoder, intra-only: OxideAV's pure-Rust H.265, MIT, no C
78+# and no FFI like everything else here. Its *inter* modes run at 0.81 fps on
79+# 1080p across 12 cores (measured 2026-08-11) and are therefore not an export
80+# anyone would wait for; its intra AU is a stateless free function that fans out
81+# across cores at 4.30 fps for the same picture, which is the export this
82+# project offers -- an intraframe master, ProRes-shaped, large files and all.
83+# Built from `vendor/oxideav-h265`; see the note in the workspace manifest.
84+oxideav-h265 = { path = "../../vendor/oxideav-h265" }
77 85
78 [dev-dependencies]86 [dev-dependencies]
79 # The still-image suite compares what the timeline shows against the file's own87 # The still-image suite compares what the timeline shows against the file's own
crates/engine/src/export.rsmodified+431 -24
@@ -1,6 +1,13 @@
1-//! Export: the edit list rendered back out as one mp4 (H.264 or AV1) or one1+//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or
2-//! AV1-in-Matroska — or, picture left behind, as one WAV, FLAC or MP3 of the2+//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC
3-//! timeline's audio alone.3+//! or MP3 of the timeline's audio alone.
4+//!
5+//! 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 the
7+//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter
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 — large
10+//! files, every frame a cut point — and not a delivery codec.
4 //!11 //!
5 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it12 //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it
6 //! is impossible — while audio is copied packet for packet wherever a copy can13 //! is impossible — while audio is copied packet for packet wherever a copy can
@@ -55,7 +62,7 @@ use flacenc::error::Verify;
55 use crate::audio::{AudioMeta, AudioSession};62 use crate::audio::{AudioMeta, AudioSession};
56 use crate::demux::{Demuxer, VideoMeta};63 use crate::demux::{Demuxer, VideoMeta};
57 use crate::hw::{HwEncoder, HwSession};64 use crate::hw::{HwEncoder, HwSession};
58-use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams};65+use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams};
59 use crate::project::{LaneKind, Project, Rate};66 use crate::project::{LaneKind, Project, Rate};
60 use crate::scale::Composer;67 use crate::scale::Composer;
61 68
@@ -73,15 +80,30 @@ const MAX_BITRATE: u64 = 20_000_000;
73 /// on a build with no assembly, which is what this one is.80 /// on a build with no assembly, which is what this one is.
74 const AV1_SPEED: u8 = 10;81 const AV1_SPEED: u8 = 10;
75 82
76-/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the83+/// The HEVC coding tree block this encoder is fixed at: the coded picture is a
77-/// user's pick of container -- are the only *video* pairs with both an encoder84+/// whole number of them, which is what the conformance window crops back.
78-/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are85+const CTB: usize = 16;
79-/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and86+/// How many frames the intra HEVC encoder codes at once. Twelve is where the
80-/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is87+/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes
81-/// what a re-encoded video track's sound leaves through -- but AAC is a88+/// only holds more decoded frames in memory.
82-/// container's own audio, never a file of its own here.) HEVC and VP9 have no89+const HEVC_LANES: usize = 12;
83-/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there).90+/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench:
84-/// A front-end says so rather than hiding the rows.91+/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through.
92+const HEVC_BPP_AT_27: f64 = 0.6;
93+/// The band [`hevc_qp`] is clamped into, for the reason stated there.
94+const HEVC_QP_MIN: i32 = 22;
95+const HEVC_QP_MAX: i32 = 40;
96+
97+/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in
98+/// Matroska or in mp4, the user's pick of container -- are the *video* pairs
99+/// with both an encoder and a decoder under this project's no-install rule, and
100+/// WAV, FLAC and MP3 are the standalone audio formats with a pure-Rust encoder:
101+/// `hound`, `flacenc` and `rusty_mp3`. Vorbis and Opus have none. (AAC does --
102+/// `rusty_aac`, which is what a re-encoded video track's sound leaves through --
103+/// but AAC is a container's own audio, never a file of its own here.) VP9 is the
104+/// one codec left that comes in through the plugin and stops there, HEVC having
105+/// gained an encoder (an intra-only one, which the rows say). A front-end says
106+/// so rather than hiding the row.
85 ///107 ///
86 /// **Every video format carries sound.** Which way it carries it is the only108 /// **Every video format carries sound.** Which way it carries it is the only
87 /// difference: copied packet for packet where a copy can say what the timeline109 /// difference: copied packet for packet where a copy can say what the timeline
@@ -103,6 +125,14 @@ pub enum Format {
103 /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,125 /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own,
104 /// unchanged.126 /// unchanged.
105 Av1Mp4,127 Av1Mp4,
128+ /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR
129+ /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC
130+ /// encoder fast enough to be an export at all. An intraframe master, like
131+ /// ProRes or DNxHD -- large files, and every frame a cut point.
132+ Hevc,
133+ /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4
134+ /// and not Matroska -- the AV1 pair's split, for the same reason.
135+ HevcMp4,
106 /// The audio lanes alone, 16-bit PCM.136 /// The audio lanes alone, 16-bit PCM.
107 Wav,137 Wav,
108 /// The audio lanes alone, losslessly compressed.138 /// The audio lanes alone, losslessly compressed.
@@ -116,8 +146,8 @@ impl Format {
116 /// the destination path from it, so the name never disagrees with the bytes.146 /// the destination path from it, so the name never disagrees with the bytes.
117 pub fn ext(self) -> &'static str {147 pub fn ext(self) -> &'static str {
118 match self {148 match self {
119- Self::Mp4 | Self::Av1Mp4 => "mp4",149+ Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4",
120- Self::Av1 => "mkv",150+ Self::Av1 | Self::Hevc => "mkv",
121 Self::Wav => "wav",151 Self::Wav => "wav",
122 Self::Flac => "flac",152 Self::Flac => "flac",
123 Self::Mp3 => "mp3",153 Self::Mp3 => "mp3",
@@ -127,7 +157,10 @@ impl Format {
127 /// Whether this format carries the picture. The bitrate settings are video157 /// Whether this format carries the picture. The bitrate settings are video
128 /// settings and mean nothing to the audio-only ones.158 /// settings and mean nothing to the audio-only ones.
129 pub fn has_video(self) -> bool {159 pub fn has_video(self) -> bool {
130- matches!(self, Self::Mp4 | Self::Av1 | Self::Av1Mp4)160+ matches!(
161+ self,
162+ Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4
163+ )
131 }164 }
132 165
133 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs166 /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs
@@ -137,12 +170,20 @@ impl Format {
137 matches!(self, Self::Av1 | Self::Av1Mp4)170 matches!(self, Self::Av1 | Self::Av1Mp4)
138 }171 }
139 172
173+ /// The same question for HEVC, and the same answer for both its containers:
174+ /// one encoder, two boxes to put its stream in.
175+ fn is_hevc(self) -> bool {
176+ matches!(self, Self::Hevc | Self::HevcMp4)
177+ }
178+
140 /// What the format is called where a refusal names it.179 /// What the format is called where a refusal names it.
141 pub fn name(self) -> &'static str {180 pub fn name(self) -> &'static str {
142 match self {181 match self {
143 Self::Mp4 => "an mp4",182 Self::Mp4 => "an mp4",
144 Self::Av1 => "an AV1 Matroska",183 Self::Av1 => "an AV1 Matroska",
145 Self::Av1Mp4 => "an AV1 mp4",184 Self::Av1Mp4 => "an AV1 mp4",
185+ Self::Hevc => "an HEVC Matroska",
186+ Self::HevcMp4 => "an HEVC mp4",
146 Self::Wav => "a WAV",187 Self::Wav => "a WAV",
147 Self::Flac => "a FLAC",188 Self::Flac => "a FLAC",
148 Self::Mp3 => "an MP3",189 Self::Mp3 => "an MP3",
@@ -339,6 +380,11 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
339 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;380 let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?;
340 let bitrate = bitrate_of(meta, settings);381 let bitrate = bitrate_of(meta, settings);
341 match settings.format {382 match settings.format {
383+ // The HEVC pair is software only, and not for want of a GPU: the plugin
384+ // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264
385+ // and AV1), so there is no seat to probe. Said here rather than left to
386+ // a failed open, which would read as a driver refusal.
387+ format if format.is_hevc() => None,
342 // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both388 // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both
343 // AV1 formats sit on it: the container is not the encoder's business.389 // AV1 formats sit on it: the container is not the encoder's business.
344 format if format.is_av1() && !forced("VE_HW_AV1") => None,390 format if format.is_av1() && !forced("VE_HW_AV1") => None,
@@ -355,10 +401,11 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option<HwEncoder> {
355 /// place, so what a card says before an export and what its progress line says401 /// place, so what a card says before an export and what its progress line says
356 /// during one cannot drift apart.402 /// during one cannot drift apart.
357 fn video_label(format: Format, hw: bool) -> &'static str {403 fn video_label(format: Format, hw: bool) -> &'static str {
358- match (format.is_av1(), hw) {404+ match (format, hw) {
359 (_, true) => "HW encode (VA-API)",405 (_, true) => "HW encode (VA-API)",
360- (true, false) => "SW encode (rav1e)",406+ (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)",
361- (false, false) => "SW encode (rusty_h264)",407+ (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)",
408+ (_, false) => "SW encode (rusty_h264)",
362 }409 }
363 }410 }
364 411
@@ -936,9 +983,7 @@ fn run_audio(
936 Format::Wav => write_wav(out, &samples, &audio)?,983 Format::Wav => write_wav(out, &samples, &audio)?,
937 Format::Flac => write_flac(out, &samples, &audio)?,984 Format::Flac => write_flac(out, &samples, &audio)?,
938 Format::Mp3 => write_mp3(out, &samples, &audio)?,985 Format::Mp3 => write_mp3(out, &samples, &audio)?,
939- Format::Mp4 | Format::Av1 | Format::Av1Mp4 => {986+ _ => unreachable!("the picture formats are `run`"),
940- unreachable!("the picture formats are `run`")
941- }
942 }987 }
943 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);988 shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed);
944 Ok(())989 Ok(())
@@ -1105,6 +1150,60 @@ fn write_video(
1105 au: &[u8],1150 au: &[u8],
1106 key: bool,1151 key: bool,
1107 ) -> crate::Result<()> {1152 ) -> crate::Result<()> {
1153+ if settings.format.is_hevc() {
1154+ // The parameter sets are in the access unit -- every intra AU carries
1155+ // VPS, SPS and PPS -- and the record built from them is what *both*
1156+ // containers declare the track with: an mp4's `hvcC` box and a
1157+ // Matroska `CodecPrivate` are the same bytes, so the two files are one
1158+ // stream written twice rather than two.
1159+ let sample =
1160+ crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?;
1161+ if settings.format == Format::Hevc {
1162+ let muxer = match muxer {
1163+ Some(Muxer::Mkv(mkv)) => mkv,
1164+ Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"),
1165+ none => {
1166+ let hvcc = hevc_params(au)?;
1167+ let sound = audio.zip(packets.take());
1168+ let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc(
1169+ out,
1170+ &HevcParams {
1171+ width: meta.width,
1172+ height: meta.height,
1173+ frame_rate: meta.frame_rate,
1174+ hvcc: &hvcc,
1175+ },
1176+ sound,
1177+ )?)) else {
1178+ unreachable!("just inserted a Matroska muxer")
1179+ };
1180+ mkv
1181+ }
1182+ };
1183+ return muxer.write_frame(&sample, key);
1184+ }
1185+ let muxer = match muxer {
1186+ Some(Muxer::Mp4(mp4)) => mp4,
1187+ Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"),
1188+ none => {
1189+ let hvcc = hevc_params(au)?;
1190+ let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc(
1191+ out,
1192+ &HevcParams {
1193+ width: meta.width,
1194+ height: meta.height,
1195+ frame_rate: meta.frame_rate,
1196+ hvcc: &hvcc,
1197+ },
1198+ audio,
1199+ )?)) else {
1200+ unreachable!("just inserted an mp4 muxer")
1201+ };
1202+ mp4
1203+ }
1204+ };
1205+ return muxer.write_coded_sample(&sample, key);
1206+ }
1108 if settings.format.is_av1() {1207 if settings.format.is_av1() {
1109 // Every AV1 stream opens on a keyframe, and a keyframe carries the1208 // Every AV1 stream opens on a keyframe, and a keyframe carries the
1110 // sequence header the track has to declare: an encoder that handed back1209 // sequence header the track has to declare: an encoder that handed back
@@ -1153,7 +1252,7 @@ fn write_video(
1153 mp41252 mp4
1154 }1253 }
1155 };1254 };
1156- return muxer.write_av1_frame(au, key);1255+ return muxer.write_coded_sample(au, key);
1157 }1256 }
1158 if !crate::mux::has_coded_slice(au) {1257 if !crate::mux::has_coded_slice(au) {
1159 return Ok(());1258 return Ok(());
@@ -1183,6 +1282,13 @@ fn write_video(
1183 muxer.write_video_au(au)1282 muxer.write_video_au(au)
1184 }1283 }
1185 1284
1285+/// The `hvcC` record of the first coded unit, or the refusal by name. Split out
1286+/// because both HEVC containers ask it in the same words.
1287+fn hevc_params(au: &[u8]) -> crate::Result<Vec<u8>> {
1288+ crate::mux::hvcc_record(au)
1289+ .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS"))
1290+}
1291+
1186 fn bitrate_for(meta: &VideoMeta) -> u64 {1292 fn bitrate_for(meta: &VideoMeta) -> u64 {
1187 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;1293 let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL;
1188 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)1294 (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE)
@@ -1219,6 +1325,38 @@ enum Enc {
1219 au: Vec<u8>,1325 au: Vec<u8>,
1220 flushed: bool,1326 flushed: bool,
1221 },1327 },
1328+ /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a
1329+ /// *stateless* function of one picture, so a batch of frames is coded on as
1330+ /// many cores as there are lanes and collected back in order.
1331+ Hevc(HevcEnc),
1332+}
1333+
1334+/// The intra HEVC seat. Frames arrive one at a time (the export walk is one
1335+/// picture per timeline frame) and are held until there are [`lanes`] of them,
1336+/// then coded in parallel and queued in **display order** -- fanning out is the
1337+/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on
1338+/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose
1339+/// frames came back shuffled would be no export at all.
1340+///
1341+/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p,
1342+/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes
1343+/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a
1344+/// decoder running ahead of the encoder rather than a batch barrier.
1345+struct HevcEnc {
1346+ /// Padded I420 planes waiting for a lane, in display order.
1347+ pending: Vec<(Vec<u8>, Vec<u8>, Vec<u8>)>,
1348+ /// Coded access units not yet collected, in the same order.
1349+ ready: std::collections::VecDeque<Vec<u8>>,
1350+ /// The unit currently lent out, for the reason `Sw` owns one.
1351+ au: Vec<u8>,
1352+ /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid.
1353+ width: usize,
1354+ height: usize,
1355+ /// Luma samples the conformance window crops off the right and the bottom,
1356+ /// so a decoder outputs the picture's own size ([`pad_to_ctb`]).
1357+ crop: (usize, usize),
1358+ qp: i32,
1359+ lanes: usize,
1222 }1360 }
1223 1361
1224 impl Enc {1362 impl Enc {
@@ -1231,15 +1369,19 @@ impl Enc {
1231 Self::Sw { .. } => video_label(Format::Mp4, false),1369 Self::Sw { .. } => video_label(Format::Mp4, false),
1232 Self::Av1Hw(_) => video_label(Format::Av1, true),1370 Self::Av1Hw(_) => video_label(Format::Av1, true),
1233 Self::Av1Sw { .. } => video_label(Format::Av1, false),1371 Self::Av1Sw { .. } => video_label(Format::Av1, false),
1372+ Self::Hevc(_) => video_label(Format::Hevc, false),
1234 }1373 }
1235 }1374 }
1236 1375
1237 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {1376 fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1238 // Which *codec* the picture is, not which container it goes in: both AV11377 // Which *codec* the picture is, not which container it goes in: both AV1
1239- // formats run the same encoder.1378+ // formats run the same encoder, and so do both HEVC ones.
1240 if settings.format.is_av1() {1379 if settings.format.is_av1() {
1241 return Self::open_av1(meta, settings);1380 return Self::open_av1(meta, settings);
1242 }1381 }
1382+ if settings.format.is_hevc() {
1383+ return Self::open_hevc(meta, settings);
1384+ }
1243 // A caller's number goes through the same clamp as the computed one: a1385 // A caller's number goes through the same clamp as the computed one: a
1244 // zero bitrate switches the software encoder's lookahead on, which would1386 // zero bitrate switches the software encoder's lookahead on, which would
1245 // break the one-picture-per-call contract `encode` documents below.1387 // break the one-picture-per-call contract `encode` documents below.
@@ -1331,6 +1473,53 @@ impl Enc {
1331 })1473 })
1332 }1474 }
1333 1475
1476+ /// The intra HEVC seat, software and frame-parallel. There is no hardware
1477+ /// half: the plugin encodes H.264 and AV1 and nothing else, which
1478+ /// [`hw_seat`] says by refusing to probe one.
1479+ ///
1480+ /// **Intra-only, deliberately.** The vendored encoder's inter modes code
1481+ /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of
1482+ /// timeline in half an hour, which is not an export anybody waits for --
1483+ /// while the intra path does 4.30 fps on the same picture and the same
1484+ /// cores. So every frame is an IDR, the file is an intraframe master in the
1485+ /// shape of ProRes or DNxHD, and the card says so where a user picks it.
1486+ ///
1487+ /// The picture is coded **padded** to the 16-sample CTB grid and the SPS
1488+ /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so
1489+ /// 1920x1080 is a legal export rather than a refusal.
1490+ fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result<Self> {
1491+ // The muxers time by it and the mp4 one wants an exact rational: asked
1492+ // here so an impossible rate fails before a frame is coded.
1493+ crate::mux::frame_timing(meta.frame_rate)?;
1494+ // 4:2:0 addresses its conformance window in *chroma* samples, so an odd
1495+ // picture cannot be cropped back to itself -- and an odd dimension has
1496+ // no chroma plane of its own to begin with. Named rather than padded to
1497+ // something a decoder would then show a column of.
1498+ if meta.width % 2 != 0 || meta.height % 2 != 0 {
1499+ return Err(format!(
1500+ "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions",
1501+ meta.width, meta.height
1502+ )
1503+ .into());
1504+ }
1505+ let (width, height) = (
1506+ (meta.width as usize).next_multiple_of(CTB),
1507+ (meta.height as usize).next_multiple_of(CTB),
1508+ );
1509+ let lanes = std::thread::available_parallelism().map_or(1, |n| n.get());
1510+ eprintln!("export encoder: software HEVC intra (oxideav-h265)");
1511+ Ok(Self::Hevc(HevcEnc {
1512+ pending: Vec::new(),
1513+ ready: std::collections::VecDeque::new(),
1514+ au: Vec::new(),
1515+ width,
1516+ height,
1517+ crop: (width - meta.width as usize, height - meta.height as usize),
1518+ qp: hevc_qp(meta, settings),
1519+ lanes: lanes.min(HEVC_LANES),
1520+ }))
1521+ }
1522+
1334 /// One picture in, at most one access unit out, and whether that unit is one1523 /// One picture in, at most one access unit out, and whether that unit is one
1335 /// a decoder may be started from -- which only the Matroska muxer asks, the1524 /// a decoder may be started from -- which only the Matroska muxer asks, the
1336 /// mp4 one reading its own sync flag off the IDR slice.1525 /// mp4 one reading its own sync flag off the IDR slice.
@@ -1373,6 +1562,23 @@ impl Enc {
1373 collect_av1(context, ready)?;1562 collect_av1(context, ready)?;
1374 Ok(pop_av1(ready, au))1563 Ok(pop_av1(ready, au))
1375 }1564 }
1565+ Self::Hevc(hevc) => {
1566+ hevc.pending.push(pad_to_ctb(
1567+ y,
1568+ u,
1569+ v,
1570+ width as usize,
1571+ height as usize,
1572+ hevc.width,
1573+ hevc.height,
1574+ ));
1575+ if hevc.pending.len() >= hevc.lanes {
1576+ hevc.code_batch()?;
1577+ }
1578+ // Every intra AU is an IDR, so every one of them is a key
1579+ // frame -- which is what an intraframe master means.
1580+ Ok(pop_hevc(hevc))
1581+ }
1376 Self::Hw(hw) => Ok(hw1582 Self::Hw(hw) => Ok(hw
1377 .encode(y, u, v, width, height, false)?1583 .encode(y, u, v, width, height, false)?
1378 .map(|au| (au, false))),1584 .map(|au| (au, false))),
@@ -1412,6 +1618,14 @@ impl Enc {
1412 }1618 }
1413 Ok(pop_av1(ready, au))1619 Ok(pop_av1(ready, au))
1414 }1620 }
1621+ Self::Hevc(hevc) => {
1622+ // The tail batch: fewer frames than lanes, coded on as many
1623+ // cores as there are frames left.
1624+ if !hevc.pending.is_empty() {
1625+ hevc.code_batch()?;
1626+ }
1627+ Ok(pop_hevc(hevc))
1628+ }
1415 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),1629 Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))),
1416 Self::Sw {1630 Self::Sw {
1417 encoder,1631 encoder,
@@ -1431,6 +1645,103 @@ impl Enc {
1431 }1645 }
1432 }1646 }
1433 1647
1648+impl HevcEnc {
1649+ /// The whole pending batch, one frame per lane, collected back in the order
1650+ /// it went out -- `std::thread::scope`, because the encode borrows the
1651+ /// planes rather than copying them again. A panic inside a lane comes back
1652+ /// as an error rather than unwinding the export thread.
1653+ fn code_batch(&mut self) -> crate::Result<()> {
1654+ let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop);
1655+ let coded: Vec<crate::Result<Vec<u8>>> = std::thread::scope(|scope| {
1656+ let lanes: Vec<_> = self
1657+ .pending
1658+ .iter()
1659+ .map(|(y, cb, cr)| {
1660+ scope.spawn(move || {
1661+ oxideav_h265::encoder::intra::encode_idr_intra_au_cropped(
1662+ y, cb, cr, width, height, qp, crop.0, crop.1,
1663+ )
1664+ .map(|coded| coded.au)
1665+ .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}")))
1666+ })
1667+ })
1668+ .collect();
1669+ lanes
1670+ .into_iter()
1671+ .map(|lane| {
1672+ lane.join()
1673+ .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into()))
1674+ })
1675+ .collect()
1676+ });
1677+ for au in coded {
1678+ self.ready.push_back(au?);
1679+ }
1680+ self.pending.clear();
1681+ Ok(())
1682+ }
1683+}
1684+
1685+/// The oldest coded intra AU, lent out under the same "valid until the next
1686+/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag
1687+/// is not a guess.
1688+fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> {
1689+ hevc.au = hevc.ready.pop_front()?;
1690+ Some((&hevc.au[..], true))
1691+}
1692+
1693+/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the
1694+/// added rows and columns filled by **replicating the edge** rather than with
1695+/// black: the padding is coded and then cropped away, and a black border would
1696+/// bleed into the last real column through the intra prediction and the
1697+/// transform that straddles it.
1698+fn pad_to_ctb(
1699+ y: &[u8],
1700+ u: &[u8],
1701+ v: &[u8],
1702+ width: usize,
1703+ height: usize,
1704+ padded_w: usize,
1705+ padded_h: usize,
1706+) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1707+ let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| {
1708+ let mut out = vec![0u8; pw * ph];
1709+ for row in 0..ph {
1710+ let src_row = &src[row.min(h - 1) * w..][..w];
1711+ let dst = &mut out[row * pw..][..pw];
1712+ dst[..w].copy_from_slice(src_row);
1713+ dst[w..].fill(src_row[w - 1]);
1714+ }
1715+ out
1716+ };
1717+ (
1718+ plane(y, width, height, padded_w, padded_h),
1719+ plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2),
1720+ plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2),
1721+ )
1722+}
1723+
1724+/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a
1725+/// user picked -- the card has no QP control and this codec has no rate control,
1726+/// so the two are joined by measurement rather than promised to each other.
1727+///
1728+/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured
1729+/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP
1730+/// is a factor of two in rate, which is the classic HEVC relation. So the QP
1731+/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is
1732+/// clamped, because this is a *quality* dial and not a rate controller: below QP
1733+/// 22 the file grows without a picture to show for it, and past QP 40 an
1734+/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30
1735+/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out
1736+/// bigger than that, which is what "intra-only, large files" on the format row
1737+/// means: the row buys quality, not a size.
1738+fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 {
1739+ let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate;
1740+ let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0);
1741+ let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2();
1742+ (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX)
1743+}
1744+
1434 /// Every temporal unit `rav1e` has finished, moved into the queue in display1745 /// Every temporal unit `rav1e` has finished, moved into the queue in display
1435 /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is1746 /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is
1436 /// through) are the two ways it says there is nothing more; `Encoded` means a1747 /// through) are the two ways it says there is nothing more; `Encoded` means a
@@ -1587,4 +1898,100 @@ mod tests {
1587 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");1898 assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny");
1588 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");1899 assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge");
1589 }1900 }
1901+
1902+ fn meta(width: u32, height: u32) -> VideoMeta {
1903+ VideoMeta {
1904+ width,
1905+ height,
1906+ frame_rate: 30.0,
1907+ frame_count: 1,
1908+ codec: crate::demux::Codec::H264,
1909+ }
1910+ }
1911+
1912+ /// The bitrate row a user picked, read as the quality tier it is: a higher
1913+ /// row is a lower QP, the band is honoured at both ends, and the same
1914+ /// picture at the same rate gets the same number whatever its size (the
1915+ /// mapping is bits per *pixel*, which is what makes 720p and 1080p one
1916+ /// table).
1917+ #[test]
1918+ fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() {
1919+ let at = |width, height, mbps: Option<u64>| {
1920+ hevc_qp(
1921+ &meta(width, height),
1922+ &ExportSettings {
1923+ bitrate: mbps.map(|m| m * 1_000_000),
1924+ ..Default::default()
1925+ },
1926+ )
1927+ };
1928+ // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at
1929+ // QP 27, which is just over half: five QP up, and QP is not an
1930+ // arithmetic scale, so this is the number the formula gives.
1931+ assert_eq!(at(1920, 1080, Some(20)), 32);
1932+ // Every step down the card is a step up in QP, never sideways.
1933+ let rows: Vec<i32> = [20, 12, 8, 4, 2, 1]
1934+ .into_iter()
1935+ .map(|mbps| at(1920, 1080, Some(mbps)))
1936+ .collect();
1937+ assert!(
1938+ rows.windows(2).all(|w| w[0] <= w[1]),
1939+ "a lower bitrate row must never code at a lower QP: {rows:?}"
1940+ );
1941+ assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped");
1942+ // ...and the top of the range is the clamp, not an unbounded number: 20
1943+ // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs.
1944+ assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN);
1945+ // The same bits per pixel is the same quantiser at any size: 1080p at
1946+ // 20 Mbps and 720p at 8.9 Mbps are one picture quality.
1947+ assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9)));
1948+ // The automatic bitrate is 0.1 bpp at every size, so it is one QP
1949+ // everywhere -- the honest end of "intra-only, large files": the file
1950+ // will be bigger than the row says, and the row buys quality.
1951+ assert_eq!(at(1920, 1080, None), at(1280, 720, None));
1952+ }
1953+
1954+ /// The padding a non-%16 picture is coded with replicates the edge instead
1955+ /// of filling black: the coded rows past the picture carry its last row, so
1956+ /// nothing bleeds into the last real line through the intra prediction.
1957+ #[test]
1958+ fn the_ctb_padding_replicates_the_edge() {
1959+ // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the
1960+ // copy itself with numbers small enough to read).
1961+ let y: Vec<u8> = (1..=12).collect();
1962+ let u: Vec<u8> = vec![40, 41, 42];
1963+ let v: Vec<u8> = vec![50, 51, 52];
1964+ let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4);
1965+ assert_eq!(
1966+ py,
1967+ vec![
1968+ 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice
1969+ 7, 8, 9, 10, 11, 12, 12, 12, //
1970+ 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated
1971+ 7, 8, 9, 10, 11, 12, 12, 12,
1972+ ]
1973+ );
1974+ // Chroma is half of everything, padded the same way.
1975+ assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]);
1976+ assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]);
1977+ }
1978+
1979+ /// An odd picture cannot be cropped back to itself in 4:2:0 -- the
1980+ /// conformance window is stated in chroma samples -- so it is refused by
1981+ /// name rather than written a column wider than the timeline.
1982+ #[test]
1983+ fn an_odd_picture_is_refused_an_hevc_export_by_name() {
1984+ let settings = ExportSettings {
1985+ format: Format::Hevc,
1986+ ..Default::default()
1987+ };
1988+ let refused = Enc::open(&meta(1919, 1080), &settings)
1989+ .err()
1990+ .expect("an odd width has no chroma plane")
1991+ .to_string();
1992+ assert!(refused.contains("1919x1080"), "{refused}");
1993+ assert!(refused.contains("even"), "{refused}");
1994+ // ...and the even one it neighbours opens.
1995+ assert!(Enc::open(&meta(1920, 1080), &settings).is_ok());
1996+ }
1590 }1997 }
crates/engine/src/mux.rsmodified+237 -45
@@ -66,10 +66,11 @@ pub struct Mp4Muxer {
66 writer: Mp4Writer<BufWriter<File>>,66 writer: Mp4Writer<BufWriter<File>>,
67 frame_duration: u32,67 frame_duration: u32,
68 has_audio: bool,68 has_audio: bool,
69- /// The `av1C` record an AV1 file's sample entry is patched to carry at69+ /// The sample entry an AV1 or HEVC file's is patched into at
70- /// [`finish`](Mp4Muxer::finish); `None` for H.264, which the crate spells70+ /// [`finish`](Mp4Muxer::finish) -- entry type, configuration box type and
71- /// itself. See [`create_av1`](Mp4Muxer::create_av1).71+ /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the
72- av1c: Option<Vec<u8>>,72+ /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1).
73+ entry: Option<([u8; 4], [u8; 4], Vec<u8>)>,
73 /// Where the file is, for that patch: the writer owns the handle it wrote74 /// Where the file is, for that patch: the writer owns the handle it wrote
74 /// through and the patch reopens the finished file.75 /// through and the patch reopens the finished file.
75 path: PathBuf,76 path: PathBuf,
@@ -129,7 +130,37 @@ impl Mp4Muxer {
129 pps: &[0x68, 0xCE, 0x3C, 0x80],130 pps: &[0x68, 0xCE, 0x3C, 0x80],
130 },131 },
131 audio,132 audio,
132- Some(av1c),133+ Some((*b"av01", *b"av1C", av1c)),
134+ )
135+ }
136+
137+ /// ...and the same trick for HEVC, which `mp4 0.14` cannot spell either:
138+ /// the file is written with an `avc1` entry and that entry is rewritten at
139+ /// [`finish`](Mp4Muxer::finish) into the `hvc1` + `hvcC` pair ISO/IEC
140+ /// 14496-15 §8.4.1 asks for -- the record being the very bytes the Matroska
141+ /// file puts in `CodecPrivate`, so the two containers carry one stream.
142+ /// `hvc1` rather than `hev1`: the samples this writes carry no parameter
143+ /// sets (they are dropped into `hvcC`), which is exactly what the `hvc1`
144+ /// name promises a reader.
145+ pub fn create_hevc(
146+ path: &Path,
147+ video: &HevcParams,
148+ audio: Option<&AudioParams>,
149+ ) -> crate::Result<Self> {
150+ if video.hvcc.is_empty() {
151+ return Err("no hvcC record for the track's sample entry".into());
152+ }
153+ Self::open(
154+ path,
155+ &VideoParams {
156+ width: video.width,
157+ height: video.height,
158+ frame_rate: video.frame_rate,
159+ sps: &[0x67, 0x42, 0x00, 0x1E],
160+ pps: &[0x68, 0xCE, 0x3C, 0x80],
161+ },
162+ audio,
163+ Some((*b"hvc1", *b"hvcC", video.hvcc.to_vec())),
133 )164 )
134 }165 }
135 166
@@ -137,7 +168,7 @@ impl Mp4Muxer {
137 path: &Path,168 path: &Path,
138 video: &VideoParams,169 video: &VideoParams,
139 audio: Option<&AudioParams>,170 audio: Option<&AudioParams>,
140- av1c: Option<Vec<u8>>,171+ entry: Option<([u8; 4], [u8; 4], Vec<u8>)>,
141 ) -> crate::Result<Self> {172 ) -> crate::Result<Self> {
142 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {173 if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {
143 return Err(format!("bad frame rate {}", video.frame_rate).into());174 return Err(format!("bad frame rate {}", video.frame_rate).into());
@@ -166,8 +197,8 @@ impl Mp4Muxer {
166 compatible_brands: vec![197 compatible_brands: vec![
167 FourCC::from(*b"isom"),198 FourCC::from(*b"isom"),
168 FourCC::from(*b"iso2"),199 FourCC::from(*b"iso2"),
169- FourCC::from(match av1c {200+ FourCC::from(match &entry {
170- Some(_) => *b"av01",201+ Some((kind, ..)) => *kind,
171 None => *b"avc1",202 None => *b"avc1",
172 }),203 }),
173 FourCC::from(*b"mp41"),204 FourCC::from(*b"mp41"),
@@ -215,7 +246,7 @@ impl Mp4Muxer {
215 writer,246 writer,
216 frame_duration,247 frame_duration,
217 has_audio: audio.is_some(),248 has_audio: audio.is_some(),
218- av1c,249+ entry,
219 path: path.to_path_buf(),250 path: path.to_path_buf(),
220 })251 })
221 }252 }
@@ -237,14 +268,15 @@ impl Mp4Muxer {
237 Ok(())268 Ok(())
238 }269 }
239 270
240- /// One coded picture as an AV1 temporal unit, written verbatim: an mp4 AV1271+ /// One coded picture already framed the way its sample carries it: an AV1
241- /// sample is the low-overhead OBU stream the encoder handed over, exactly as272+ /// temporal unit is the low-overhead OBU stream the encoder handed over
242- /// a Matroska block is, so there is nothing to reframe. `key` is the273+ /// (nothing to reframe, exactly as a Matroska block holds it), and an HEVC
274+ /// sample is the length-prefixed NALs [`annex_b_to_hvcc`] made. `key` is the
243 /// encoder's own word for a unit a decoder may start on -- an mp4 says it in275 /// encoder's own word for a unit a decoder may start on -- an mp4 says it in
244 /// `stss` where Matroska says it in the block flags.276 /// `stss` where Matroska says it in the block flags.
245- pub fn write_av1_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {277+ pub fn write_coded_sample(&mut self, obus: &[u8], key: bool) -> crate::Result<()> {
246 if obus.is_empty() {278 if obus.is_empty() {
247- return Err("an empty AV1 temporal unit".into());279+ return Err("an empty coded picture".into());
248 }280 }
249 self.writer.write_sample(281 self.writer.write_sample(
250 VIDEO_TRACK,282 VIDEO_TRACK,
@@ -284,32 +316,42 @@ impl Mp4Muxer {
284 pub fn finish(mut self) -> crate::Result<()> {316 pub fn finish(mut self) -> crate::Result<()> {
285 self.writer.write_end()?;317 self.writer.write_end()?;
286 let Self {318 let Self {
287- writer, av1c, path, ..319+ writer,
320+ entry,
321+ path,
322+ ..
288 } = self;323 } = self;
289 // Not a `drop`: the buffered tail of `moov` has to be on disk before the324 // Not a `drop`: the buffered tail of `moov` has to be on disk before the
290 // patch below reads it back, and a `BufWriter` swallows the error of325 // patch below reads it back, and a `BufWriter` swallows the error of
291 // flushing it on drop.326 // flushing it on drop.
292 writer.into_writer().flush()?;327 writer.into_writer().flush()?;
293- match av1c {328+ match entry {
294- Some(av1c) => patch_av01(&path, &av1c),329+ Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config),
295 None => Ok(()),330 None => Ok(()),
296 }331 }
297 }332 }
298 }333 }
299 334
300 /// Rewrites the finished file's one video sample entry from the `avc1` the crate335 /// Rewrites the finished file's one video sample entry from the `avc1` the crate
301-/// wrote into the `av01` + `av1C` an AV1 track declares. Called once, on a336+/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` +
302-/// complete file, and only for a file [`Mp4Muxer::create_av1`] opened.337+/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file
338+/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened.
303 ///339 ///
304 /// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only340 /// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only
305 /// ever rewrites the tail of the file: no sample moves and no chunk offset in341 /// ever rewrites the tail of the file: no sample moves and no chunk offset in
306 /// `co64` changes. The box tree is rebuilt rather than patched in place, which342 /// `co64` changes. The box tree is rebuilt rather than patched in place, which
307 /// is what keeps every ancestor's size right by construction.343 /// is what keeps every ancestor's size right by construction.
308-fn patch_av01(path: &Path, av1c: &[u8]) -> crate::Result<()> {344+fn patch_entry(
345+ path: &Path,
346+ kind: &[u8; 4],
347+ config_kind: &[u8; 4],
348+ config: &[u8],
349+) -> crate::Result<()> {
309 let mut file = OpenOptions::new().read(true).write(true).open(path)?;350 let mut file = OpenOptions::new().read(true).write(true).open(path)?;
310 let end = file.metadata()?.len();351 let end = file.metadata()?.len();
311 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;352 let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?;
312- let patched = swap_av01(&payload, 0, av1c).ok_or("no avc1 sample entry to rewrite as av01")?;353+ let patched = swap_entry(&payload, 0, kind, config_kind, config)
354+ .ok_or("no avc1 sample entry to rewrite")?;
313 let mut out = Vec::with_capacity(patched.len() + 8);355 let mut out = Vec::with_capacity(patched.len() + 8);
314 push_box(&mut out, b"moov", &patched);356 push_box(&mut out, b"moov", &patched);
315 file.seek(SeekFrom::Start(at))?;357 file.seek(SeekFrom::Start(at))?;
@@ -355,7 +397,13 @@ const STSD_PATH: [&[u8; 4]; 5] = [b"trak", b"mdia", b"minf", b"stbl", b"stsd"];
355 /// `None` where this branch holds no such entry -- an audio `trak` is walked397 /// `None` where this branch holds no such entry -- an audio `trak` is walked
356 /// into and comes back untouched, which is how the *video* track is found398 /// into and comes back untouched, which is how the *video* track is found
357 /// without being told which id it has.399 /// without being told which id it has.
358-fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option<Vec<u8>> {400+fn swap_entry(
401+ payload: &[u8],
402+ depth: usize,
403+ want: &[u8; 4],
404+ config_kind: &[u8; 4],
405+ config: &[u8],
406+) -> Option<Vec<u8>> {
359 if depth == STSD_PATH.len() {407 if depth == STSD_PATH.len() {
360 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.408 // stsd is a FullBox (4) plus entry_count (4), then the sample entries.
361 let mut out = payload.get(..8)?.to_vec();409 let mut out = payload.get(..8)?.to_vec();
@@ -364,18 +412,19 @@ fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option<Vec<u8>> {
364 return None;412 return None;
365 }413 }
366 // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all)414 // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all)
367- // before its codec box, and `av01` carries exactly the same ones -- so415+ // before its codec box, and `av01` and `hvc1` carry exactly the same
368- // the header is kept and only the configuration box is swapped.416+ // ones -- so the header is kept and only the configuration box is
417+ // swapped.
369 let mut swapped = entry.get(..78)?.to_vec();418 let mut swapped = entry.get(..78)?.to_vec();
370- push_box(&mut swapped, b"av1C", av1c);419+ push_box(&mut swapped, config_kind, config);
371- push_box(&mut out, b"av01", &swapped);420+ push_box(&mut out, want, &swapped);
372 return Some(out);421 return Some(out);
373 }422 }
374 let mut out = Vec::with_capacity(payload.len());423 let mut out = Vec::with_capacity(payload.len());
375 let mut done = false;424 let mut done = false;
376 for (kind, child) in crate::demux::boxes(payload) {425 for (kind, child) in crate::demux::boxes(payload) {
377 let patched = match !done && kind == STSD_PATH[depth] {426 let patched = match !done && kind == STSD_PATH[depth] {
378- true => swap_av01(child, depth + 1, av1c),427+ true => swap_entry(child, depth + 1, want, config_kind, config),
379 false => None,428 false => None,
380 };429 };
381 match patched {430 match patched {
@@ -471,6 +520,18 @@ pub struct Av1Params<'a> {
471 pub config: &'a [u8],520 pub config: &'a [u8],
472 }521 }
473 522
523+/// What an HEVC track declares in either container: the `hvcC` record
524+/// [`hvcc_record`] built out of the encoder's own VPS/SPS/PPS. The dimensions
525+/// are the *displayed* ones -- the coded picture is padded up to the 16-sample
526+/// CTB grid and the SPS crops it back with a conformance window, which is the
527+/// size a decoder outputs and therefore the size the container states.
528+pub struct HevcParams<'a> {
529+ pub width: u32,
530+ pub height: u32,
531+ pub frame_rate: f64,
532+ pub hvcc: &'a [u8],
533+}
534+
474 /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC535 /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC
475 /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the536 /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the
476 /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what537 /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what
@@ -528,18 +589,66 @@ impl MkvMuxer {
528 video: &Av1Params,589 video: &Av1Params,
529 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,590 audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
530 ) -> crate::Result<Self> {591 ) -> crate::Result<Self> {
531- if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 {592+ if video.config.is_empty() {
532- return Err(format!("bad frame rate {}", video.frame_rate).into());593+ return Err("no AV1 sequence header for the track's CodecPrivate".into());
533 }594 }
534- if video.width == 0 || video.height == 0 {595+ let mut av1c = AV1C_HEAD.to_vec();
535- return Err(format!("bad dimensions {}x{}", video.width, video.height).into());596+ av1c.extend_from_slice(video.config);
597+ Self::open(
598+ path,
599+ video.width,
600+ video.height,
601+ video.frame_rate,
602+ b"V_AV1",
603+ &av1c,
604+ audio,
605+ )
606+ }
607+
608+ /// The same file with an HEVC track in it: `V_MPEGH/ISO/HEVC`, whose
609+ /// `CodecPrivate` is the very `hvcC` record an mp4 puts in its sample entry
610+ /// ([`hvcc_record`]) -- and whose blocks are therefore length-prefixed NALs
611+ /// like an mp4 sample's, not Annex B. That is what this engine's own reader
612+ /// expects back (`demux`'s Matroska branch parses `CodecPrivate` as `hvcC`
613+ /// and reframes the blocks by the length it states), and what every other
614+ /// Matroska reader expects too.
615+ pub fn create_hevc(
616+ path: &Path,
617+ video: &HevcParams,
618+ audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
619+ ) -> crate::Result<Self> {
620+ if video.hvcc.is_empty() {
621+ return Err("no hvcC record for the track's CodecPrivate".into());
536 }622 }
537- let frame_ns = (1e9 / video.frame_rate).round() as u64;623+ Self::open(
538- if frame_ns == 0 {624+ path,
539- return Err(format!("frame rate {} is too fast to time", video.frame_rate).into());625+ video.width,
626+ video.height,
627+ video.frame_rate,
628+ b"V_MPEGH/ISO/HEVC",
629+ video.hvcc,
630+ audio,
631+ )
632+ }
633+
634+ fn open(
635+ path: &Path,
636+ width: u32,
637+ height: u32,
638+ frame_rate: f64,
639+ codec_id: &[u8],
640+ codec_private: &[u8],
641+ audio: Option<(&AudioParams, Vec<crate::AacPacket>)>,
642+ ) -> crate::Result<Self> {
643+ if !frame_rate.is_finite() || frame_rate <= 0.0 {
644+ return Err(format!("bad frame rate {frame_rate}").into());
540 }645 }
541- if video.config.is_empty() {646+ if width == 0 || height == 0 {
542- return Err("no AV1 sequence header for the track's CodecPrivate".into());647+ return Err(format!("bad dimensions {width}x{height}").into());
648+ }
649+ let frame_ns = (1e9 / frame_rate).round() as u64;
650+ if frame_ns == 0 {
651+ return Err(format!("frame rate {frame_rate} is too fast to time").into());
543 }652 }
544 653
545 let mut head = Vec::new();654 let mut head = Vec::new();
@@ -576,14 +685,12 @@ impl MkvMuxer {
576 uint(&mut entry, TRACK_UID, 1);685 uint(&mut entry, TRACK_UID, 1);
577 uint(&mut entry, TRACK_TYPE, 1); // video686 uint(&mut entry, TRACK_TYPE, 1); // video
578 uint(&mut entry, FLAG_LACING, 0);687 uint(&mut entry, FLAG_LACING, 0);
579- elem(&mut entry, CODEC_ID, b"V_AV1");688+ elem(&mut entry, CODEC_ID, codec_id);
580- let mut av1c = AV1C_HEAD.to_vec();689+ elem(&mut entry, CODEC_PRIVATE, codec_private);
581- av1c.extend_from_slice(video.config);
582- elem(&mut entry, CODEC_PRIVATE, &av1c);
583 uint(&mut entry, DEFAULT_DURATION, frame_ns);690 uint(&mut entry, DEFAULT_DURATION, frame_ns);
584 let mut dims = Vec::new();691 let mut dims = Vec::new();
585- uint(&mut dims, PIXEL_WIDTH, u64::from(video.width));692+ uint(&mut dims, PIXEL_WIDTH, u64::from(width));
586- uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height));693+ uint(&mut dims, PIXEL_HEIGHT, u64::from(height));
587 elem(&mut entry, VIDEO, &dims);694 elem(&mut entry, VIDEO, &dims);
588 let mut tracks = Vec::new();695 let mut tracks = Vec::new();
589 elem(&mut tracks, TRACK_ENTRY, &entry);696 elem(&mut tracks, TRACK_ENTRY, &entry);
@@ -882,6 +989,91 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> {
882 Some((sps, pps))989 Some((sps, pps))
883 }990 }
884 991
992+/// The `HEVCDecoderConfigurationRecord` an HEVC track declares, built out of the
993+/// parameter sets the encoder put in its first access unit -- the exact record
994+/// `demux::parse_hvcc` reads back, which is what makes an export of this
995+/// project's own something it can re-open.
996+///
997+/// The 22 fixed bytes before the arrays: the 12-byte `profile_tier_level` is
998+/// copied straight out of the SPS (its first 12 bytes after the two-byte NAL
999+/// header and the four `sps_video_parameter_set_id`/`sps_max_sub_layers_minus1`
1000+/// /`sps_temporal_id_nesting_flag` bits -- §7.3.2.2 puts the PTL there and the
1001+/// hvcC header states the same fields in the same order), and the rest is what
1002+/// this encoder is: 4:2:0, 8-bit, one temporal layer, 4-byte NAL lengths. Only
1003+/// the *arrays* are read by anything here, but a record whose header lied about
1004+/// the profile would be a file `ffprobe` disagrees with.
1005+///
1006+/// `None` where the unit carries no VPS, SPS or PPS -- the first coded intra AU
1007+/// always carries all three.
1008+pub fn hvcc_record(annex_b: &[u8]) -> Option<Vec<u8>> {
1009+ let nals = split_annex_b(annex_b);
1010+ let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind);
1011+ let (vps, sps, pps) = (of(HEVC_VPS)?, of(HEVC_SPS)?, of(HEVC_PPS)?);
1012+ // The SPS as a decoder reads it: the emulation-prevention bytes the encoder
1013+ // escaped it with are not part of the syntax, and a run of zeros in the
1014+ // constraint flags is exactly where one lands.
1015+ let rbsp = unescape(sps.get(2..)?);
1016+ let mut rec = vec![1u8]; // configurationVersion
1017+ rec.extend_from_slice(rbsp.get(1..13)?); // profile_tier_level, verbatim
1018+ rec.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc = 0
1019+ rec.push(0xFC); // parallelismType = 0 (unknown)
1020+ rec.push(0xFC | 1); // chroma_format_idc = 1 (4:2:0)
1021+ rec.push(0xF8); // bit_depth_luma_minus8 = 0
1022+ rec.push(0xF8); // bit_depth_chroma_minus8 = 0
1023+ rec.extend_from_slice(&0u16.to_be_bytes()); // avgFrameRate: unstated
1024+ // constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1,
1025+ // lengthSizeMinusOne 3 -- the same 4-byte prefix `annex_b_to_hvcc` writes.
1026+ rec.push(0b00_001_1_11);
1027+ rec.push(3); // numOfArrays
1028+ for (kind, nal) in [(HEVC_VPS, vps), (HEVC_SPS, sps), (HEVC_PPS, pps)] {
1029+ rec.push(0x80 | kind); // array_completeness = 1, NAL_unit_type
1030+ rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus
1031+ rec.extend_from_slice(&(nal.len() as u16).to_be_bytes());
1032+ rec.extend_from_slice(nal);
1033+ }
1034+ Some(rec)
1035+}
1036+
1037+/// One HEVC access unit as a sample of both containers: 4-byte length prefixes,
1038+/// parameter sets dropped (they are in the `hvcC`, which is what `hvc1` and a
1039+/// Matroska `CodecPrivate` both promise). `None` where the unit holds no coded
1040+/// slice at all.
1041+pub(crate) fn annex_b_to_hvcc(annex_b: &[u8]) -> Option<Vec<u8>> {
1042+ let mut out = Vec::with_capacity(annex_b.len());
1043+ for nal in split_annex_b(annex_b) {
1044+ // 32 VPS, 33 SPS, 34 PPS, 35 AUD -- and everything from 40 up is
1045+ // non-VCL padding no decoder needs to start.
1046+ if matches!(hevc_nal_type(nal), HEVC_VPS | HEVC_SPS | HEVC_PPS | 35) {
1047+ continue;
1048+ }
1049+ out.extend_from_slice(&(nal.len() as u32).to_be_bytes());
1050+ out.extend_from_slice(nal);
1051+ }
1052+ (!out.is_empty()).then_some(out)
1053+}
1054+
1055+/// §7.3.1.2 `nal_unit_type`, the six bits after the forbidden_zero_bit.
1056+fn hevc_nal_type(nal: &[u8]) -> u8 {
1057+ nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F)
1058+}
1059+
1060+const HEVC_VPS: u8 = 32;
1061+const HEVC_SPS: u8 = 33;
1062+const HEVC_PPS: u8 = 34;
1063+
1064+/// A coded NAL payload back to its RBSP: every `00 00 03` loses the `03`
1065+/// (§7.3.1.1). Only ever asked of an SPS, which is short.
1066+fn unescape(nal: &[u8]) -> Vec<u8> {
1067+ let mut out = Vec::with_capacity(nal.len());
1068+ for (i, &byte) in nal.iter().enumerate() {
1069+ if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 {
1070+ continue;
1071+ }
1072+ out.push(byte);
1073+ }
1074+ out
1075+}
1076+
885 /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that1077 /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that
886 /// buffered instead of coding hands back an empty buffer, and one that emitted1078 /// buffered instead of coding hands back an empty buffer, and one that emitted
887 /// only parameter sets has no sample to write -- both are for the caller to skip1079 /// only parameter sets has no sample to write -- both are for the caller to skip
@@ -1322,9 +1514,9 @@ mod tests {
1322 }),1514 }),
1323 )1515 )
1324 .unwrap();1516 .unwrap();
1325- muxer.write_av1_frame(&key, true).unwrap();1517+ muxer.write_coded_sample(&key, true).unwrap();
1326- muxer.write_av1_frame(&inter, false).unwrap();1518+ muxer.write_coded_sample(&inter, false).unwrap();
1327- muxer.write_av1_frame(&inter, false).unwrap();1519+ muxer.write_coded_sample(&inter, false).unwrap();
1328 for packet in &packets {1520 for packet in &packets {
1329 muxer.write_audio_packet(&packet.bytes).unwrap();1521 muxer.write_audio_packet(&packet.bytes).unwrap();
1330 }1522 }
crates/engine/tests/backends.rsmodified+11 -0
@@ -106,6 +106,11 @@ fn the_planned_encoders_are_the_ones_the_job_opens() {
106 (Format::Mp4, "mp4"),106 (Format::Mp4, "mp4"),
107 (Format::Av1, "mkv"),107 (Format::Av1, "mkv"),
108 (Format::Av1Mp4, "mp4"),108 (Format::Av1Mp4, "mp4"),
109+ // Both HEVC containers, whose seat is software whatever the box has:
110+ // the plugin encodes H.264 and AV1 and no HEVC, so a card that offered
111+ // a hardware seat here would be promising one that cannot exist.
112+ (Format::Hevc, "mkv"),
113+ (Format::HevcMp4, "mp4"),
109 ] {114 ] {
110 let settings = ExportSettings {115 let settings = ExportSettings {
111 format,116 format,
@@ -145,6 +150,12 @@ fn the_planned_encoders_are_the_ones_the_job_opens() {
145 // carries the timeline's audio now, so a line that said nothing about150 // carries the timeline's audio now, so a line that said nothing about
146 // it would be the old picture-only lie in a new place.151 // it would be the old picture-only lie in a new place.
147 assert!(planned.contains("AAC"), "{ext}: {planned}");152 assert!(planned.contains("AAC"), "{ext}: {planned}");
153+ if matches!(format, Format::Hevc | Format::HevcMp4) {
154+ assert!(
155+ planned.contains("oxideav-h265 intra"),
156+ "{ext}: an HEVC job names the intra encoder that writes it: {planned}"
157+ );
158+ }
148 }159 }
149 }160 }
150 161
crates/engine/tests/hevc_export.rsadded+298 -0
@@ -0,0 +1,298 @@
1+//! HEVC export: the codec this project could read and not write until OxideAV's
2+//! pure-Rust H.265 gave it an encoder -- an **intra-only** one, every frame a
3+//! self-contained IDR, which is the only shape of it fast enough to wait for
4+//! (the inter modes code 1080p at 0.81 fps across 12 cores; the intra path does
5+//! 4.30 fps on the same picture).
6+//!
7+//! Two things are under test here and neither of them is the encoder's picture
8+//! quality: that the *containers* say HEVC in the words their readers expect
9+//! (this project's own demuxer, and ffprobe where it is installed), and that a
10+//! picture whose height is not a multiple of the 16-sample coding tree block --
11+//! 1080, the resolution -- comes back out at its own size, coded padded to 1088
12+//! and cropped by the SPS conformance window.
13+//!
14+//! ```text
15+//! cargo test -p engine --release --test hevc_export -- --test-threads=1
16+//! ```
17+//!
18+//! Release, always: a debug intra encode is minutes a frame. The 1080p twin
19+//! needs the `ffmpeg` CLI to make its source and `ffprobe` to read the coded
20+//! size back; without them it says so and passes, exactly as the hardware tests
21+//! here do.
22+
23+use std::path::{Path, PathBuf};
24+use std::process::Command;
25+use std::time::{Duration, Instant};
26+
27+use engine::demux::{Codec, Demuxer};
28+use engine::export::{ExportSettings, Format};
29+use engine::{AudioSession, PlaybackSession};
30+
31+fn asset(name: &str) -> PathBuf {
32+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
33+ .join("../../assets")
34+ .join(name)
35+}
36+
37+fn out_path(name: &str, ext: &str) -> PathBuf {
38+ let path = std::env::temp_dir().join(format!("ve_hevc_{name}_{}.{ext}", std::process::id()));
39+ let _ = std::fs::remove_file(&path);
40+ let _ = std::fs::remove_file(format!("{}.part", path.display()));
41+ path
42+}
43+
44+/// Runs an export to completion, failing on the deadline rather than hanging.
45+fn export(session: &PlaybackSession, out: &Path, format: Format) {
46+ let settings = ExportSettings {
47+ format,
48+ ..Default::default()
49+ };
50+ let handle = session.export_to_with(out, &settings);
51+ let started = Instant::now();
52+ while !handle.is_finished() {
53+ assert!(
54+ started.elapsed() < Duration::from_secs(300),
55+ "the export did not finish in 300 s"
56+ );
57+ std::thread::sleep(Duration::from_millis(20));
58+ }
59+ handle
60+ .result()
61+ .expect("an outcome")
62+ .expect("an HEVC export");
63+ assert_eq!(handle.progress(), 1.0, "finished at full progress");
64+}
65+
66+/// Two frames of the A/V fixture: what is under test is the wiring from the
67+/// format to the muxer, not how long an encoder takes.
68+fn two_frames() -> PlaybackSession {
69+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
70+ assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front");
71+ assert!(session.delete_clip(engine::project::Lane::V1, 1));
72+ session
73+}
74+
75+/// The container half, in both boxes: an HEVC export is read back as HEVC, at
76+/// the size and the count it was written at, with the timeline's sound beside
77+/// it. The `hvcC` record this writes is the one `demux` parses -- Matroska in
78+/// `CodecPrivate`, mp4 in the sample entry -- so this is where the writer and
79+/// the reader either agree or do not.
80+#[test]
81+fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() {
82+ for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
83+ let session = two_frames();
84+ let out = out_path("container", ext);
85+ export(&session, &out, format);
86+
87+ let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export");
88+ assert_eq!(meta.codec, Codec::Hevc, "{ext}: an HEVC export is HEVC");
89+ assert_eq!((meta.width, meta.height), (1280, 720), "{ext}");
90+ assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there");
91+ // Every access unit comes back, and every one of them is a sync point:
92+ // that is what intra-only means, and it is what makes any frame of the
93+ // file a cut point.
94+ let mut count = 0;
95+ while demuxer.next_access_unit().expect("read").is_some() {
96+ count += 1;
97+ }
98+ assert_eq!(count, 2, "{ext}: every coded picture comes back out");
99+ assert_eq!(
100+ demuxer.seek_to_sync_at_or_before(1),
101+ 1,
102+ "{ext}: an intra-only file syncs on every frame"
103+ );
104+
105+ // ...and the sound with it, through the reader an import opens it by.
106+ let (audio, chunks) = AudioSession::open(&out)
107+ .expect("reopen for its sound")
108+ .expect("an HEVC export has an audio track");
109+ let samples: Vec<f32> = chunks.into_iter().flat_map(|c| c.samples).collect();
110+ let rms = (samples.iter().map(|s| s * s).sum::<f32>() / samples.len().max(1) as f32).sqrt();
111+ eprintln!(
112+ "{ext}: {} Hz x{}, rms {rms:.4}, {} bytes",
113+ audio.sample_rate,
114+ audio.channels,
115+ std::fs::metadata(&out).unwrap().len()
116+ );
117+ assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})");
118+ std::fs::remove_file(&out).unwrap();
119+ }
120+}
121+
122+/// The %16 half, and the reason the vendored encoder carries a patch at all:
123+/// 1080 is not a multiple of the 16-sample CTB, so the picture is coded at
124+/// 1920x1088 and the SPS crops it back with a §7.4.3.2.1 conformance window.
125+/// ffprobe is what says whether that worked -- it reads the *bitstream*, not
126+/// the container's own claim -- and ffmpeg decoding the file without a
127+/// complaint is what says the stream is legal.
128+#[test]
129+fn a_1080p_export_states_1920x1080_through_the_conformance_window() {
130+ let Some(source) = fixture_1080p() else {
131+ eprintln!("no ffmpeg: skipping the 1080p conformance-window twin");
132+ return;
133+ };
134+ for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
135+ let mut session = PlaybackSession::open(&source).expect("open the 1080p fixture");
136+ assert!(session.cut_at(2.0 / 30.0));
137+ assert!(session.delete_clip(engine::project::Lane::V1, 1));
138+ let out = out_path("1080p", ext);
139+ export(&session, &out, format);
140+
141+ // The container's own claim first: this project's reader.
142+ let (meta, _) = Demuxer::open(&out).expect("reopen the 1080p export");
143+ assert_eq!((meta.width, meta.height), (1920, 1080), "{ext}");
144+
145+ // ...and the coded size, out of the SPS, by a reader that is not ours.
146+ let probed = probe(&out);
147+ assert_eq!(
148+ probed.as_deref(),
149+ Some("hevc,1920,1080"),
150+ "{ext}: ffprobe reads the cropped size out of the bitstream"
151+ );
152+ // ...and the whole file decoded, with ffmpeg's own stderr as the test:
153+ // a stream a decoder complains about is not an export.
154+ let decoded = Command::new("ffmpeg")
155+ .args(["-v", "error", "-i"])
156+ .arg(&out)
157+ .args(["-f", "null", "-"])
158+ .output()
159+ .expect("run ffmpeg");
160+ let complaints = String::from_utf8_lossy(&decoded.stderr);
161+ assert!(
162+ decoded.status.success() && complaints.is_empty(),
163+ "{ext}: ffmpeg complained: {complaints}"
164+ );
165+ std::fs::remove_file(&out).unwrap();
166+ }
167+ let _ = std::fs::remove_file(&source);
168+}
169+
170+/// The loop closed where it matters to a user: the file this wrote is opened
171+/// again *by edith*, picture and all. HEVC has no software decoder here at all,
172+/// so the way back in is the plugin -- which is what makes this the twin that
173+/// needs one, and what makes the test above (the containers, read by the
174+/// demuxer) the one that does not.
175+#[test]
176+#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"]
177+fn an_hevc_export_decodes_back_into_pictures_through_edith() {
178+ for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] {
179+ let session = two_frames();
180+ let out = out_path("roundtrip", ext);
181+ export(&session, &out, format);
182+
183+ let (meta, frames) = engine::DecodeSession::open(&out).expect("decode the export");
184+ assert_eq!(meta.codec, Codec::Hevc, "{ext}");
185+ let frames: Vec<_> = frames.into_iter().collect();
186+ assert_eq!(frames.len(), 2, "{ext}: every written frame decodes back");
187+ // The picture is the fixture's colour pattern, not black: a conformance
188+ // window read wrong would show as a shifted or empty picture.
189+ for (i, frame) in frames.iter().enumerate() {
190+ assert_eq!((frame.width, frame.height), (1280, 720), "{ext} frame {i}");
191+ assert!(
192+ frame.bgra.iter().any(|&p| p > 32),
193+ "{ext} frame {i} carries picture"
194+ );
195+ }
196+ std::fs::remove_file(&out).unwrap();
197+ }
198+}
199+
200+/// An audio-only timeline has no picture to code, and an HEVC export says so by
201+/// name exactly as the mp4 and AV1 ones do -- and writes nothing.
202+#[test]
203+fn an_audio_only_timeline_is_refused_an_hevc_export_by_name() {
204+ let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone");
205+ let out = out_path("refused", "mkv");
206+ let settings = ExportSettings {
207+ format: Format::Hevc,
208+ ..Default::default()
209+ };
210+ let handle = session.export_to_with(&out, &settings);
211+ while !handle.is_finished() {
212+ std::thread::sleep(Duration::from_millis(10));
213+ }
214+ let refused = handle
215+ .result()
216+ .expect("an outcome")
217+ .expect_err("an audio-only timeline has no picture to code")
218+ .to_string();
219+ assert!(refused.contains("no picture"), "{refused}");
220+ assert!(refused.contains("HEVC"), "{refused}");
221+ assert!(!out.exists(), "nothing is written for a refusal");
222+}
223+
224+/// A cancelled HEVC export leaves nothing behind -- not the file and not the
225+/// `.part` the worker was writing. An intra-only export of a whole fixture is
226+/// long enough to catch mid-flight, and the frame loop checks for a cancel
227+/// every picture, so this stops in a frame or two rather than at the end.
228+#[test]
229+fn a_cancelled_hevc_export_leaves_no_file_behind() {
230+ let session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4");
231+ let out = out_path("cancelled", "mkv");
232+ let settings = ExportSettings {
233+ format: Format::Hevc,
234+ ..Default::default()
235+ };
236+ let handle = session.export_to_with(&out, &settings);
237+ handle.cancel();
238+ let started = Instant::now();
239+ while !handle.is_finished() {
240+ assert!(started.elapsed() < Duration::from_secs(60), "cancel hung");
241+ std::thread::sleep(Duration::from_millis(20));
242+ }
243+ let stopped = handle
244+ .result()
245+ .expect("an outcome")
246+ .expect_err("a cancelled export is an error");
247+ assert!(stopped.to_string().contains("cancelled"), "{stopped}");
248+ assert!(!out.exists(), "no output for a cancelled export");
249+ assert!(
250+ !PathBuf::from(format!("{}.part", out.display())).exists(),
251+ "no partial file either"
252+ );
253+}
254+
255+/// `codec,width,height` of the file's video stream as ffprobe reads it, or
256+/// `None` where ffprobe is not installed.
257+fn probe(path: &Path) -> Option<String> {
258+ let out = Command::new("ffprobe")
259+ .args([
260+ "-v",
261+ "error",
262+ "-select_streams",
263+ "v:0",
264+ "-show_entries",
265+ "stream=codec_name,width,height",
266+ "-of",
267+ "csv=p=0",
268+ ])
269+ .arg(path)
270+ .output()
271+ .ok()?;
272+ Some(String::from_utf8_lossy(&out.stdout).trim().to_string())
273+}
274+
275+/// A two-second 1920x1080 H.264 fixture in the temp directory -- the assets are
276+/// all 720p, which is a multiple of 16 in both directions and would leave the
277+/// crop path untested. `None` where ffmpeg is not installed.
278+fn fixture_1080p() -> Option<PathBuf> {
279+ let path = out_path("source1080", "mp4");
280+ let made = Command::new("ffmpeg")
281+ .args([
282+ "-y",
283+ "-f",
284+ "lavfi",
285+ "-i",
286+ "testsrc2=size=1920x1080:rate=30:duration=1",
287+ "-c:v",
288+ "libx264",
289+ "-profile:v",
290+ "baseline",
291+ "-pix_fmt",
292+ "yuv420p",
293+ ])
294+ .arg(&path)
295+ .output()
296+ .ok()?;
297+ made.status.success().then_some(path)
298+}
vendor/oxideav-h265/Cargo.tomladded+17 -0
@@ -0,0 +1,17 @@
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/LICENSEadded+21 -0
@@ -0,0 +1,21 @@
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.mdadded+243 -0
@@ -0,0 +1,243 @@
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.rsadded+569 -0
@@ -0,0 +1,569 @@
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.rsadded+315 -0
@@ -0,0 +1,315 @@
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.rsadded+8000 -0

Diff too large; view file

@@ -0,0 +1,8000 @@
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.rsadded+300 -0
@@ -0,0 +1,300 @@
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.rsadded+820 -0
@@ -0,0 +1,820 @@
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.rsadded+994 -0
@@ -0,0 +1,994 @@
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.rsadded+2484 -0

Diff too large; view file

@@ -0,0 +1,2484 @@
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.rsadded+349 -0
@@ -0,0 +1,349 @@
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.rsadded+214 -0
@@ -0,0 +1,214 @@
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.rsadded+833 -0
@@ -0,0 +1,833 @@
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.rsadded+440 -0
@@ -0,0 +1,440 @@
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.rsadded+190 -0
@@ -0,0 +1,190 @@
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.rsadded+323 -0
@@ -0,0 +1,323 @@
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.rsadded+540 -0
@@ -0,0 +1,540 @@
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.rsadded+3154 -0

Diff too large; view file

@@ -0,0 +1,3154 @@
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+ conf_win: (0, 0), // edith patch: no crop on the inter paths
368+ },
369+ &self.filters,
370+ )?;
371+ let recon = FrameRecon {
372+ y: idr.recon_y,
373+ cb: idr.recon_cb,
374+ cr: idr.recon_cr,
375+ };
376+ self.prevs = vec![recon.clone()];
377+ self.poc = 1;
378+ EncodedPFrame {
379+ au: idr.au,
380+ keyframe: true,
381+ recon,
382+ stats: FrameStats {
383+ intra: (self.width / CTB) * (self.height / CTB),
384+ ..FrameStats::default()
385+ },
386+ }
387+ } else {
388+ // The active references: RefPicListX[i] = the
389+ // reconstruction of POC − 1 − i (newest first, up to two),
390+ // and a low-delay B slice holds the same set on both lists.
391+ let l0: Vec<(i32, &FrameRecon)> = self
392+ .prevs
393+ .iter()
394+ .take(2)
395+ .enumerate()
396+ .map(|(i, rec)| (self.poc - 1 - i as i32, rec))
397+ .collect();
398+ let spec = SliceSpec {
399+ poc: self.poc,
400+ qp: self.qp,
401+ b_slice: self.b_slices,
402+ rps_neg: (1..=l0.len() as u32).map(|d| (d, true)).collect(),
403+ rps_pos: Vec::new(),
404+ l1: if self.b_slices {
405+ l0.clone()
406+ } else {
407+ Vec::new()
408+ },
409+ l0,
410+ lf: &self.filters,
411+ big_cu: self.amp,
412+ };
413+ let (rbsp, recon, stats) = encode_inter_slice(frame, &spec, self.width, self.height);
414+ let au = annexb(&[nal_unit(1, 0, 0, &rbsp)]); // TRAIL_R
415+ self.prevs.insert(0, recon.clone());
416+ self.prevs.truncate(2);
417+ self.poc += 1;
418+ EncodedPFrame {
419+ au,
420+ keyframe: false,
421+ recon,
422+ stats,
423+ }
424+ };
425+ // GOP wrap: schedule the next IDR.
426+ if self.gop > 0 && self.poc >= self.gop as i32 {
427+ self.poc = 0;
428+ }
429+ Ok(out)
430+ }
431+}
432+
433+/// Encode a low-delay `IDR, P, P, …` sequence at a constant
434+/// `SliceQpY == qp` and return the Annex B stream plus the per-frame
435+/// reconstructions a conforming decoder reproduces exactly.
436+///
437+/// # Errors
438+/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP (the
439+/// validation contract is shared with the intra encoder).
440+pub fn encode_low_delay_p(
441+ frames: &[YuvFrame<'_>],
442+ width: usize,
443+ height: usize,
444+ qp: i32,
445+) -> Result<LowDelayPEncoded, IntraEncodeError> {
446+ let mut enc = LowDelayPEncoder::new(width, height, qp, 0)?;
447+ let mut out = LowDelayPEncoded {
448+ stream: Vec::new(),
449+ recon: Vec::new(),
450+ stats: Vec::new(),
451+ };
452+ for frame in frames {
453+ let f = enc.encode_frame(frame)?;
454+ out.stream.extend_from_slice(&f.au);
455+ out.recon.push(f.recon);
456+ out.stats.push(f.stats);
457+ }
458+ Ok(out)
459+}
460+
461+/// The slice header's in-loop-filter fields (§7.3.6.1): the enabled
462+/// filter set plus this slice's elections.
463+struct SliceLfSignalling<'a> {
464+ /// The stream's filter configuration (drives field presence: the
465+ /// SAO gates exist iff the SPS enables SAO, the deblocking
466+ /// override group iff the PPS enables the override).
467+ cfg: &'a LoopFilterCfg,
468+ /// This slice's deblocking election
469+ /// (`slice_deblocking_filter_disabled_flag == !deblock_on`).
470+ deblock_on: bool,
471+ /// Elected `slice_beta_offset_div2`.
472+ beta_offset_div2: i32,
473+ /// Elected `slice_tc_offset_div2`.
474+ tc_offset_div2: i32,
475+ /// Elected `slice_sao_luma_flag`.
476+ sao_luma: bool,
477+ /// Elected `slice_sao_chroma_flag`.
478+ sao_chroma: bool,
479+}
480+
481+/// Everything one P / B slice's coding depends on beyond the frame
482+/// samples: POC, QP, slice type, the inline §7.4.8 short-term RPS
483+/// content, and the two active reference lists (POC + reconstruction
484+/// each, in `RefPicListX` order). The low-delay GOP passes past
485+/// pictures on both lists; the hierarchical-B GOP passes past
486+/// pictures on L0 and future pictures on L1.
487+pub(crate) struct SliceSpec<'a> {
488+ /// `PicOrderCntVal` (== `slice_pic_order_cnt_lsb`, 8 bits).
489+ pub poc: i32,
490+ /// `SliceQpY`.
491+ pub qp: i32,
492+ /// B slice (`slice_type == 0`)?
493+ pub b_slice: bool,
494+ /// Negative RPS entries closest-first: `(PocDelta, used_by_curr)`
495+ /// with `PocDelta = poc − entry POC > 0`, strictly increasing.
496+ pub rps_neg: Vec<(u32, bool)>,
497+ /// Positive RPS entries closest-first: `(entry POC − poc, used)`.
498+ pub rps_pos: Vec<(u32, bool)>,
499+ /// `RefPicList0`: active references, `(POC, reconstruction)`.
500+ pub l0: Vec<(i32, &'a FrameRecon)>,
501+ /// `RefPicList1` (B slices; empty on P slices).
502+ pub l1: Vec<(i32, &'a FrameRecon)>,
503+ /// The stream's §8.7 in-loop filter configuration.
504+ pub lf: &'a LoopFilterCfg,
505+ /// Stream geometry: `log2CbSize > MinCbLog2SizeY` (MinCb 8, one
506+ /// explicit `split_cu_flag == 0` per CTB, the Table 9-45 big-CU
507+ /// `part_mode` column, no intra `part_mode`). Implied by the AMP
508+ /// stream configuration.
509+ pub big_cu: bool,
510+}
511+
512+/// §7.3.6.1 — the P / B slice-segment header: an inline §7.4.8
513+/// short-term RPS (negative + positive pictures with per-entry used
514+/// flags), the `num_ref_idx` override when a list keeps more than one
515+/// active reference, `MaxNumMergeCand == 5`, `slice_qp_delta` against
516+/// `init_qp == 26`, then the in-loop-filter block (`slice_sao_*`
517+/// gates when the SPS enables SAO, the deblocking override group when
518+/// the PPS enables the override, the across-slices flag when any
519+/// filter is active).
520+fn write_inter_slice_header(w: &mut BitWriter, spec: &SliceSpec<'_>, lf: &SliceLfSignalling<'_>) {
521+ w.put_bit(1); // first_slice_segment_in_pic_flag
522+ w.ue(0); // slice_pic_parameter_set_id
523+ w.ue(u32::from(!spec.b_slice)); // slice_type (0 = B, 1 = P)
524+ w.put_bits((spec.poc & 0xFF) as u32, 8); // slice_pic_order_cnt_lsb
525+ w.put_bit(0); // short_term_ref_pic_set_sps_flag
526+ // st_ref_pic_set( 0 ) — idx 0 has no
527+ // inter_ref_pic_set_prediction_flag (§7.3.7).
528+ w.ue(spec.rps_neg.len() as u32); // num_negative_pics
529+ w.ue(spec.rps_pos.len() as u32); // num_positive_pics
530+ let mut prev = 0u32;
531+ for &(delta, used) in &spec.rps_neg {
532+ // §7.4.8: DeltaPocS0[i] = DeltaPocS0[i−1] − (minus1 + 1).
533+ w.ue(delta - prev - 1); // delta_poc_s0_minus1[i]
534+ w.put_bit(u8::from(used)); // used_by_curr_pic_s0_flag[i]
535+ prev = delta;
536+ }
537+ let mut prev = 0u32;
538+ for &(delta, used) in &spec.rps_pos {
539+ // §7.4.8: DeltaPocS1[i] = DeltaPocS1[i−1] + (minus1 + 1).
540+ w.ue(delta - prev - 1); // delta_poc_s1_minus1[i]
541+ w.put_bit(u8::from(used)); // used_by_curr_pic_s1_flag[i]
542+ prev = delta;
543+ }
544+ // sps_temporal_mvp_enabled_flag == 0: nothing.
545+ if lf.cfg.sao() {
546+ // SPS SAO enabled: the per-slice component gates are present.
547+ w.put_bit(u8::from(lf.sao_luma)); // slice_sao_luma_flag
548+ w.put_bit(u8::from(lf.sao_chroma)); // slice_sao_chroma_flag
549+ }
550+ let n_l0 = spec.l0.len() as u32;
551+ let n_l1 = spec.l1.len() as u32;
552+ if n_l0 != 1 || (spec.b_slice && n_l1 != 1) {
553+ // PPS defaults are one active reference per list.
554+ w.put_bit(1); // num_ref_idx_active_override_flag
555+ w.ue(n_l0 - 1); // num_ref_idx_l0_active_minus1
556+ if spec.b_slice {
557+ w.ue(n_l1 - 1); // num_ref_idx_l1_active_minus1
558+ }
559+ } else {
560+ w.put_bit(0); // num_ref_idx_active_override_flag (default: 1)
561+ }
562+ // lists_modification_present_flag == 0.
563+ if spec.b_slice {
564+ w.put_bit(0); // mvd_l1_zero_flag
565+ }
566+ // cabac_init_present_flag == 0; TMVP off; WP off.
567+ w.ue((5 - MAX_MERGE) as u32); // five_minus_max_num_merge_cand
568+ w.se(spec.qp - 26); // slice_qp_delta
569+ if lf.cfg.deblocking {
570+ // §7.3.6.1 deblocking override group (the PPS signals
571+ // override-enabled + deblocking disabled; an electing slice
572+ // overrides to enabled with zero β/tC offsets).
573+ w.put_bit(u8::from(lf.deblock_on)); // deblocking_filter_override_flag
574+ if lf.deblock_on {
575+ w.put_bit(0); // slice_deblocking_filter_disabled_flag
576+ w.se(lf.beta_offset_div2); // slice_beta_offset_div2
577+ w.se(lf.tc_offset_div2); // slice_tc_offset_div2
578+ }
579+ }
580+ if lf.sao_luma || lf.sao_chroma || lf.deblock_on {
581+ // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and
582+ // some in-loop filter is active for this slice.
583+ w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag
584+ }
585+ // No tiles / WPP: no entry points.
586+ w.rbsp_trailing_bits(); // byte_alignment()
587+}
588+
589+/// Extract an `n`x`n` block of `plane` at `(x0, y0)` as `i32`s.
590+fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec<i32> {
591+ let mut out = Vec::with_capacity(n * n);
592+ for j in 0..n {
593+ for i in 0..n {
594+ out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
595+ }
596+ }
597+ out
598+}
599+
600+/// Store an `n`x`n` block back into `plane` at `(x0, y0)`.
601+fn store(plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]) {
602+ for j in 0..n {
603+ plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n].copy_from_slice(&s[j * n..(j + 1) * n]);
604+ }
605+}
606+
607+/// The [`crate::binarization::PartMode`] twin of a [`PartMode`] (the
608+/// loop-filter descriptors speak the binarization enum).
609+fn bin_part_mode(p: PartMode) -> crate::binarization::PartMode {
610+ use crate::binarization::PartMode as B;
611+ match p {
612+ PartMode::Part2Nx2N => B::Part2Nx2N,
613+ PartMode::Part2NxN => B::Part2NxN,
614+ PartMode::PartNx2N => B::PartNx2N,
615+ PartMode::PartNxN => B::PartNxN,
616+ PartMode::Part2NxnU => B::Part2NxnU,
617+ PartMode::Part2NxnD => B::Part2NxnD,
618+ PartMode::PartNLx2N => B::PartNLx2N,
619+ PartMode::PartNRx2N => B::PartNRx2N,
620+ }
621+}
622+
623+/// `true` for the horizontal-split two-PU shapes (`PART_2NxN` /
624+/// `PART_2NxnU` / `PART_2NxnD`) — Table 9-45 bin 1.
625+fn part_is_horizontal(p: PartMode) -> bool {
626+ matches!(
627+ p,
628+ PartMode::Part2NxN | PartMode::Part2NxnU | PartMode::Part2NxnD
629+ )
630+}
631+
632+/// `true` for the four asymmetric shapes.
633+fn part_is_amp(p: PartMode) -> bool {
634+ matches!(
635+ p,
636+ PartMode::Part2NxnU | PartMode::Part2NxnD | PartMode::PartNLx2N | PartMode::PartNRx2N
637+ )
638+}
639+
640+/// The merge / skip PU syntax for candidate `merge_idx` (the §7.3.8.6
641+/// fields the §8.5.3.2.2 derivation reads).
642+fn merge_pu(merge_idx: usize) -> PredictionUnit {
643+ PredictionUnit {
644+ merge_flag: true,
645+ merge_idx: Some(merge_idx as u8),
646+ inter_pred_idc: None,
647+ ref_idx_l0: None,
648+ mvd_l0: None,
649+ mvp_l0_flag: None,
650+ ref_idx_l1: None,
651+ mvd_l1: None,
652+ mvp_l1_flag: None,
653+ }
654+}
655+
656+/// An AMVP PU carrying the given per-list signalling groups (the
657+/// §7.3.8.6 fields the §8.5.3.2 derivation reads). At least one list
658+/// must be used; `inter_pred_idc` follows from which are.
659+fn amvp_pu(l0: Option<AmvpGroup>, l1: Option<AmvpGroup>) -> PredictionUnit {
660+ let comp = |v: i32| MvdComponent {
661+ greater0_flag: u8::from(v != 0),
662+ greater1_flag: None,
663+ minus2: None,
664+ sign_flag: None,
665+ value: v,
666+ };
667+ let idc = match (l0.is_some(), l1.is_some()) {
668+ (true, true) => InterPredIdc::PredBi,
669+ (false, true) => InterPredIdc::PredL1,
670+ // An AMVP PU uses at least one list; default to L0.
671+ _ => InterPredIdc::PredL0,
672+ };
673+ PredictionUnit {
674+ merge_flag: false,
675+ merge_idx: None,
676+ inter_pred_idc: Some(idc),
677+ ref_idx_l0: l0.map(|g| g.ref_idx),
678+ mvd_l0: l0.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]),
679+ mvp_l0_flag: l0.map(|g| g.mvp_flag),
680+ ref_idx_l1: l1.map(|g| g.ref_idx),
681+ mvd_l1: l1.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]),
682+ mvp_l1_flag: l1.map(|g| g.mvp_flag),
683+ }
684+}
685+
686+/// A single-list [`amvp_pu`] probe (zero or explicit mvd) for the
687+/// §8.5.3.2.6 predictor derivation and the ME resolution step.
688+fn amvp_pu_list(list: usize, ref_idx: u8, mvd: Mv, mvp_flag: u8) -> PredictionUnit {
689+ let g = Some(AmvpGroup {
690+ ref_idx,
691+ mvd,
692+ mvp_flag,
693+ });
694+ if list == 0 {
695+ amvp_pu(g, None)
696+ } else {
697+ amvp_pu(None, g)
698+ }
699+}
700+
701+/// Select the plane set a list prediction reads: the used list's
702+/// `refs[refIdxLX]`, or (for an unused list, whose planes are never
703+/// read) any legal plane set from either list.
704+fn pick_ref<'r>(
705+ refs: &'r [RefPlanes],
706+ other: &'r [RefPlanes],
707+ pred_flag: bool,
708+ ref_idx: i32,
709+) -> &'r RefPlanes {
710+ if pred_flag {
711+ &refs[ref_idx.max(0) as usize]
712+ } else {
713+ refs.first().unwrap_or_else(|| &other[0])
714+ }
715+}
716+
717+/// §8.5.3.3 — the final clipped prediction for a `w`x`h` PU at
718+/// `(x0, y0)` with the resolved motion (uni-L0, uni-L1 or bi). Each
719+/// used list reads `refs_lX[ refIdxLX ]`; the low-delay GOP passes the
720+/// same past reconstructions on both lists, the hierarchical-B GOP
721+/// passes past pictures on L0 and future pictures on L1. `chroma`
722+/// selects whether the Cb / Cr planes are predicted too (the SAD
723+/// search runs luma-only).
724+#[allow(clippy::too_many_arguments)]
725+fn predict_block(
726+ refs_l0: &[RefPlanes],
727+ refs_l1: &[RefPlanes],
728+ x0: usize,
729+ y0: usize,
730+ w: usize,
731+ h: usize,
732+ motion: &PuMotion,
733+ chroma: bool,
734+) -> InterPrediction {
735+ fn list(refp: &RefPlanes, pred_flag: bool, mv: Mv, chroma: bool) -> ListPrediction<'_> {
736+ let luma = RefPlane::new(&refp.y, refp.width, refp.height).expect("legal ref plane");
737+ let (cb, cr) = if chroma {
738+ (
739+ Some(
740+ RefPlane::new(&refp.cb, refp.width / 2, refp.height / 2).expect("legal plane"),
741+ ),
742+ Some(
743+ RefPlane::new(&refp.cr, refp.width / 2, refp.height / 2).expect("legal plane"),
744+ ),
745+ )
746+ } else {
747+ (None, None)
748+ };
749+ ListPrediction {
750+ pred_flag,
751+ luma,
752+ cb,
753+ cr,
754+ mv_l: mv,
755+ // §8.5.3.2.10: 4:2:0 chroma MV = luma MV (eighth-pel units).
756+ mv_c: derive_chroma_mv(mv, 2, 2),
757+ }
758+ }
759+ let l0 = list(
760+ pick_ref(refs_l0, refs_l1, motion.pred_flag_l0, motion.ref_idx_l0),
761+ motion.pred_flag_l0,
762+ motion.mv_l0,
763+ chroma,
764+ );
765+ let l1 = list(
766+ pick_ref(refs_l1, refs_l0, motion.pred_flag_l1, motion.ref_idx_l1),
767+ motion.pred_flag_l1,
768+ motion.mv_l1,
769+ chroma,
770+ );
771+ let geom = InterPredGeometry {
772+ x_pb: x0 as i32,
773+ y_pb: y0 as i32,
774+ n_pb_w: w,
775+ n_pb_h: h,
776+ chroma_array_type: if chroma { 1 } else { 0 },
777+ bit_depth_luma: BIT_DEPTH,
778+ bit_depth_chroma: BIT_DEPTH,
779+ };
780+ predict_inter_pu(&l0, &l1, &geom).expect("legal prediction geometry")
781+}
782+
783+/// Copy a `w`x`h` block into a `bw`-wide buffer at `(bx, by)`.
784+fn blit(dst: &mut [i32], bw: usize, bx: usize, by: usize, src: &[i32], w: usize, h: usize) {
785+ for j in 0..h {
786+ dst[(by + j) * bw + bx..(by + j) * bw + bx + w].copy_from_slice(&src[j * w..(j + 1) * w]);
787+ }
788+}
789+
790+/// Extract an `n`x`n` sub-block of a `bw`-wide buffer at `(bx, by)`.
791+fn sub_block(buf: &[i32], bw: usize, bx: usize, by: usize, n: usize) -> Vec<i32> {
792+ let mut out = Vec::with_capacity(n * n);
793+ for j in 0..n {
794+ out.extend_from_slice(&buf[(by + j) * bw + bx..(by + j) * bw + bx + n]);
795+ }
796+ out
797+}
798+
799+/// A uni-L0 [`PuMotion`] for motion-search probes (list-0 reference
800+/// index 0 — the probe caller passes the searched reference's planes
801+/// as the single-entry `refs` slice).
802+fn uni_l0(mv: Mv) -> PuMotion {
803+ PuMotion {
804+ pred_flag_l0: true,
805+ pred_flag_l1: false,
806+ ref_idx_l0: 0,
807+ ref_idx_l1: -1,
808+ mv_l0: mv,
809+ mv_l1: [0, 0],
810+ }
811+}
812+
813+/// The previous frame's reconstruction as `i32` planes (the
814+/// §8.5.3.3.3 interpolation input).
815+struct RefPlanes {
816+ y: Vec<i32>,
817+ cb: Vec<i32>,
818+ cr: Vec<i32>,
819+ width: usize,
820+ height: usize,
821+}
822+
823+/// Luma SAD between a prediction and the source block.
824+fn sad(pred: &[i32], src: &[i32]) -> u64 {
825+ pred.iter()
826+ .zip(src.iter())
827+ .map(|(&p, &s)| u64::from(p.abs_diff(s)))
828+ .sum()
829+}
830+
831+/// Rate proxy (bins) for one signed mvd component.
832+fn mvd_component_bits(v: i32) -> u64 {
833+ match v.unsigned_abs() {
834+ 0 => 1,
835+ 1 => 3,
836+ a => 5 + 2 * u64::from(32 - (a - 1).leading_zeros()),
837+ }
838+}
839+
840+/// Rate proxy for a full mvd pair.
841+fn mvd_bits(mvd: Mv) -> u64 {
842+ mvd_component_bits(mvd[0]) + mvd_component_bits(mvd[1])
843+}
844+
845+/// Crude bit-cost proxy for one TB's quantized levels (mirrors the
846+/// intra encoder's heuristic).
847+fn levels_rate(levels: &[i32]) -> u64 {
848+ let bits: u64 = levels
849+ .iter()
850+ .filter(|&&l| l != 0)
851+ .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros()))
852+ .sum();
853+ if bits == 0 {
854+ 1
855+ } else {
856+ bits + 8
857+ }
858+}
859+
860+/// Transform-code the three components of a CTB against `pred`,
861+/// reconstructing through the decode-side path. Returns
862+/// `(levels, recon, ssd_total, rate)`.
863+fn code_ctb_residual(
864+ pred: &InterPrediction,
865+ src: &[Vec<i32>; 3],
866+ qp_y: u32,
867+ qp_c: u32,
868+) -> ([Vec<i32>; 3], [Vec<u8>; 3], u64, u64) {
869+ let (ly, ry) = code_tb(
870+ &src[0],
871+ &pred.luma,
872+ CTB,
873+ qp_y,
874+ Component::Luma,
875+ PredMode::Inter,
876+ );
877+ let (lcb, rcb) = code_tb(&src[1], &pred.cb, 8, qp_c, Component::Cb, PredMode::Inter);
878+ let (lcr, rcr) = code_tb(&src[2], &pred.cr, 8, qp_c, Component::Cr, PredMode::Inter);
879+ let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]);
880+ let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr);
881+ ([ly, lcb, lcr], [ry, rcb, rcr], dist, rate)
882+}
883+
884+/// The prediction-only reconstruction (clip to 8-bit) and its SSD.
885+fn pred_recon(pred: &InterPrediction, src: &[Vec<i32>; 3]) -> ([Vec<u8>; 3], u64) {
886+ let clip = |v: &Vec<i32>| -> Vec<u8> { v.iter().map(|&p| p.clamp(0, 255) as u8).collect() };
887+ let recon = [clip(&pred.luma), clip(&pred.cb), clip(&pred.cr)];
888+ let dist = ssd(&recon[0], &src[0]) + ssd(&recon[1], &src[1]) + ssd(&recon[2], &src[2]);
889+ (recon, dist)
890+}
891+
892+/// Greedy integer-pel motion search on luma SAD: seeds, then a
893+/// small-diamond descent (capped). Returns the best full-pel MV in
894+/// luma samples.
895+#[allow(clippy::too_many_arguments)]
896+fn integer_me(
897+ refp: &RefPlanes,
898+ src_y: &[i32],
899+ x0: usize,
900+ y0: usize,
901+ w: usize,
902+ h: usize,
903+ seeds: &[[i32; 2]],
904+ lambda_me: u64,
905+ mvp_q: &[Mv],
906+) -> [i32; 2] {
907+ // Full-pel prediction == direct (clamped) reference samples.
908+ let sad_at = |mx: i32, my: i32| -> u64 {
909+ let mut acc = 0u64;
910+ for j in 0..h {
911+ for i in 0..w {
912+ let rx = (x0 as i32 + i as i32 + mx).clamp(0, refp.width as i32 - 1);
913+ let ry = (y0 as i32 + j as i32 + my).clamp(0, refp.height as i32 - 1);
914+ let r = refp.y[ry as usize * refp.width + rx as usize];
915+ acc += u64::from(r.abs_diff(src_y[j * w + i]));
916+ }
917+ }
918+ acc
919+ };
920+ // Motion-cost proxy at full-pel: cheapest mvd against either MVP.
921+ let mv_cost = |mx: i32, my: i32| -> u64 {
922+ mvp_q
923+ .iter()
924+ .map(|p| mvd_bits([mx * 4 - p[0], my * 4 - p[1]]))
925+ .min()
926+ .unwrap_or(0)
927+ * lambda_me
928+ };
929+ let mut best = seeds[0];
930+ let mut best_cost = u64::MAX;
931+ for &s in seeds {
932+ let c = sad_at(s[0], s[1]) + mv_cost(s[0], s[1]);
933+ if c < best_cost {
934+ best_cost = c;
935+ best = s;
936+ }
937+ }
938+ for _ in 0..ME_MAX_STEPS {
939+ let mut improved = false;
940+ for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] {
941+ let (mx, my) = (best[0] + dx, best[1] + dy);
942+ let c = sad_at(mx, my) + mv_cost(mx, my);
943+ if c < best_cost {
944+ best_cost = c;
945+ best = [mx, my];
946+ improved = true;
947+ }
948+ }
949+ if !improved {
950+ break;
951+ }
952+ }
953+ best
954+}
955+
956+/// Half- then quarter-pel refinement around `best` (quarter-pel
957+/// units), scoring with the real §8.5.3.3.3 interpolation.
958+#[allow(clippy::too_many_arguments)]
959+fn fractional_me(
960+ refp: &RefPlanes,
961+ src_y: &[i32],
962+ x0: usize,
963+ y0: usize,
964+ w: usize,
965+ h: usize,
966+ start: Mv,
967+ lambda_me: u64,
968+ mvp_q: &[Mv],
969+) -> Mv {
970+ let cost_at = |mv: Mv| -> u64 {
971+ let one = std::slice::from_ref(refp);
972+ let pred = predict_block(one, one, x0, y0, w, h, &uni_l0(mv), false);
973+ let mv_rate = mvp_q
974+ .iter()
975+ .map(|p| mvd_bits([mv[0] - p[0], mv[1] - p[1]]))
976+ .min()
977+ .unwrap_or(0);
978+ sad(&pred.luma, src_y) + lambda_me * mv_rate
979+ };
980+ let mut best = start;
981+ let mut best_cost = cost_at(best);
982+ for step in [2i32, 1] {
983+ let mut improved = true;
984+ while improved {
985+ improved = false;
986+ for (dx, dy) in [
987+ (step, 0),
988+ (-step, 0),
989+ (0, step),
990+ (0, -step),
991+ (step, step),
992+ (step, -step),
993+ (-step, step),
994+ (-step, -step),
995+ ] {
996+ let mv = [best[0] + dx, best[1] + dy];
997+ let c = cost_at(mv);
998+ if c < best_cost {
999+ best_cost = c;
1000+ best = mv;
1001+ improved = true;
1002+ }
1003+ }
1004+ }
1005+ }
1006+ best
1007+}
1008+
1009+/// Inputs shared by every per-PU decision of one slice.
1010+struct PuChooseCtx<'a> {
1011+ refs_l0: &'a [RefPlanes],
1012+ refs_l1: &'a [RefPlanes],
1013+ mv_ctx: &'a PuMvContext<'a>,
1014+ lambda_me: u64,
1015+ b_slice: bool,
1016+ /// B slice whose two reference lists differ (hierarchical B): the
1017+ /// AMVP election searches L1 and the bi combination too. A
1018+ /// low-delay B (both lists the same pictures) keeps the L0-only
1019+ /// search — L1 would duplicate it bin for bin at a higher rate.
1020+ two_sided: bool,
1021+}
1022+
1023+/// Choose merge-vs-AMVP for one prediction unit against `field` (the
1024+/// motion state the decoder will have when resolving this PU), by
1025+/// luma SAD + λ·signalling-bins. Returns the syntax, the resolved
1026+/// motion, and the motion-rate proxy.
1027+fn choose_pu(
1028+ field: &MotionField,
1029+ geom: &PuGeometry,
1030+ available: &dyn Fn(i32, i32) -> bool,
1031+ src_y: &[i32],
1032+ ctx: &PuChooseCtx<'_>,
1033+) -> (PuSyntax, PuMotion, u64) {
1034+ let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1035+ // ---- merge candidates (§8.5.3.2.2) ----
1036+ let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE);
1037+ for idx in 0..MAX_MERGE {
1038+ let m = resolve_pu_motion(field, geom, &merge_pu(idx), ctx.mv_ctx, available);
1039+ // A later duplicate can never beat the earlier index.
1040+ if !merge_cands.iter().any(|(_, prev)| *prev == m) {
1041+ merge_cands.push((idx, m));
1042+ }
1043+ }
1044+ let (merge_cost, merge_idx, merge_motion) = merge_cands
1045+ .iter()
1046+ .map(|&(idx, m)| {
1047+ let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &m, false);
1048+ (
1049+ sad(&pred.luma, src_y) + ctx.lambda_me * (idx as u64 + 2),
1050+ idx,
1051+ m,
1052+ )
1053+ })
1054+ .min_by_key(|&(cost, idx, _)| (cost, idx))
1055+ .expect("merge list is never empty");
1056+
1057+ let (amvp_syntax, amvp_motion, best_amvp_rate, best_amvp_cost) =
1058+ amvp_search(field, geom, available, src_y, ctx, &merge_cands);
1059+
1060+ if merge_cost <= best_amvp_cost {
1061+ (
1062+ PuSyntax::Merge { merge_idx },
1063+ merge_motion,
1064+ merge_idx as u64 + 2,
1065+ )
1066+ } else {
1067+ (amvp_syntax, amvp_motion, best_amvp_rate)
1068+ }
1069+}
1070+
1071+/// §8.5.3.2.6 + motion estimation over every active reference of ONE
1072+/// list: the SAD + λ·bins-best single-list AMVP signalling for one
1073+/// PU. Returns the group, the resolved motion, the rate proxy and the
1074+/// search cost; `None` when the list has no active reference.
1075+#[allow(clippy::too_many_arguments)]
1076+fn amvp_search_list(
1077+ field: &MotionField,
1078+ geom: &PuGeometry,
1079+ available: &dyn Fn(i32, i32) -> bool,
1080+ src_y: &[i32],
1081+ ctx: &PuChooseCtx<'_>,
1082+ merge_cands: &[(usize, PuMotion)],
1083+ list: usize,
1084+) -> Option<(AmvpGroup, PuMotion, u64, u64)> {
1085+ let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1086+ let refs = if list == 0 { ctx.refs_l0 } else { ctx.refs_l1 };
1087+ let mv_of = |m: &PuMotion| if list == 0 { m.mv_l0 } else { m.mv_l1 };
1088+ let mut best: Option<(AmvpGroup, PuMotion, u64, u64)> = None;
1089+ for (r, refp) in refs.iter().enumerate() {
1090+ let mvp = [
1091+ mv_of(&resolve_pu_motion(
1092+ field,
1093+ geom,
1094+ &amvp_pu_list(list, r as u8, [0, 0], 0),
1095+ ctx.mv_ctx,
1096+ available,
1097+ )),
1098+ mv_of(&resolve_pu_motion(
1099+ field,
1100+ geom,
1101+ &amvp_pu_list(list, r as u8, [0, 0], 1),
1102+ ctx.mv_ctx,
1103+ available,
1104+ )),
1105+ ];
1106+ let mut seeds: Vec<[i32; 2]> = vec![[0, 0]];
1107+ for p in &mvp {
1108+ seeds.push([p[0] >> 2, p[1] >> 2]);
1109+ }
1110+ for (_, m) in merge_cands {
1111+ let mv = mv_of(m);
1112+ seeds.push([mv[0] >> 2, mv[1] >> 2]);
1113+ }
1114+ seeds.dedup();
1115+ let int_mv = integer_me(refp, src_y, x, y, w, h, &seeds, ctx.lambda_me, &mvp);
1116+ let me_mv = fractional_me(
1117+ refp,
1118+ src_y,
1119+ x,
1120+ y,
1121+ w,
1122+ h,
1123+ [int_mv[0] * 4, int_mv[1] * 4],
1124+ ctx.lambda_me,
1125+ &mvp,
1126+ );
1127+ // Choose the cheaper predictor for the found MV.
1128+ let (mvp_flag, mvd) = (0u8..2)
1129+ .map(|f| {
1130+ let p = mvp[f as usize];
1131+ (f, [me_mv[0] - p[0], me_mv[1] - p[1]])
1132+ })
1133+ .min_by_key(|&(_, d)| mvd_bits(d))
1134+ .expect("two predictors");
1135+ // Resolve through the decoder's derivation (mv wrap etc.).
1136+ let motion = resolve_pu_motion(
1137+ field,
1138+ geom,
1139+ &amvp_pu_list(list, r as u8, mvd, mvp_flag),
1140+ ctx.mv_ctx,
1141+ available,
1142+ );
1143+ // merge_flag + mvp_flag + ref_idx bin (2 refs) + idc (B) + mvd.
1144+ let rate = 2 + mvd_bits(mvd) + u64::from(refs.len() > 1) + u64::from(ctx.b_slice) * 2;
1145+ let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false);
1146+ let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate;
1147+ let improved = match &best {
1148+ None => true,
1149+ Some((_, _, _, c)) => cost < *c,
1150+ };
1151+ if improved {
1152+ let group = AmvpGroup {
1153+ ref_idx: r as u8,
1154+ mvd,
1155+ mvp_flag,
1156+ };
1157+ best = Some((group, motion, rate, cost));
1158+ }
1159+ }
1160+ best
1161+}
1162+
1163+/// The full AMVP election for one PU: the best single-list search on
1164+/// L0 — and, on a two-sided B slice, on L1 plus the bi-predictive
1165+/// combination of the two winners. Returns the syntax, the resolved
1166+/// motion, the rate proxy and the search cost.
1167+fn amvp_search(
1168+ field: &MotionField,
1169+ geom: &PuGeometry,
1170+ available: &dyn Fn(i32, i32) -> bool,
1171+ src_y: &[i32],
1172+ ctx: &PuChooseCtx<'_>,
1173+ merge_cands: &[(usize, PuMotion)],
1174+) -> (PuSyntax, PuMotion, u64, u64) {
1175+ let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h);
1176+ let l0 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 0);
1177+ if !ctx.two_sided {
1178+ let (g, motion, rate, cost) = l0.expect("at least one L0 reference");
1179+ return (
1180+ PuSyntax::Amvp {
1181+ l0: Some(g),
1182+ l1: None,
1183+ },
1184+ motion,
1185+ rate,
1186+ cost,
1187+ );
1188+ }
1189+ let l1 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 1);
1190+ let mut cands: Vec<(PuSyntax, PuMotion, u64, u64)> = Vec::with_capacity(3);
1191+ if let Some((g, motion, rate, cost)) = l0 {
1192+ cands.push((
1193+ PuSyntax::Amvp {
1194+ l0: Some(g),
1195+ l1: None,
1196+ },
1197+ motion,
1198+ rate,
1199+ cost,
1200+ ));
1201+ }
1202+ if let Some((g, motion, rate, cost)) = l1 {
1203+ cands.push((
1204+ PuSyntax::Amvp {
1205+ l0: None,
1206+ l1: Some(g),
1207+ },
1208+ motion,
1209+ rate,
1210+ cost,
1211+ ));
1212+ }
1213+ if let (Some((g0, _, _, _)), Some((g1, _, _, _))) = (&l0, &l1) {
1214+ // Bi combination of the two single-list winners: the AMVP
1215+ // predictor derivation of each list is independent of the
1216+ // other, so the resolved per-list MVs match the uni winners.
1217+ let motion = resolve_pu_motion(
1218+ field,
1219+ geom,
1220+ &amvp_pu(Some(*g0), Some(*g1)),
1221+ ctx.mv_ctx,
1222+ available,
1223+ );
1224+ // merge_flag + inter_pred_idc ("1") + per-list mvd/mvp/ref bins.
1225+ let rate = 2
1226+ + (mvd_bits(g0.mvd) + 1 + u64::from(ctx.refs_l0.len() > 1))
1227+ + (mvd_bits(g1.mvd) + 1 + u64::from(ctx.refs_l1.len() > 1));
1228+ let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false);
1229+ let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate;
1230+ cands.push((
1231+ PuSyntax::Amvp {
1232+ l0: Some(*g0),
1233+ l1: Some(*g1),
1234+ },
1235+ motion,
1236+ rate,
1237+ cost,
1238+ ));
1239+ }
1240+ cands
1241+ .into_iter()
1242+ .min_by_key(|&(_, _, _, cost)| cost)
1243+ .expect("at least one active reference across the lists")
1244+}
1245+
1246+/// Encode `merge_idx` (§9.3.3.10 TR with `cMax = MaxNumMergeCand − 1`:
1247+/// bin 0 context-coded, the rest bypass).
1248+fn encode_merge_idx(
1249+ w: &mut BitWriter,
1250+ cabac: &mut CabacEncoder,
1251+ ctxs: &mut SliceContexts,
1252+ idx: usize,
1253+) {
1254+ let c_max = MAX_MERGE - 1;
1255+ cabac.encode_decision(w, &mut ctxs.merge_idx[0], u8::from(idx > 0));
1256+ if idx > 0 {
1257+ for _ in 1..idx {
1258+ cabac.encode_bypass(w, 1);
1259+ }
1260+ if idx < c_max {
1261+ cabac.encode_bypass(w, 0);
1262+ }
1263+ }
1264+}
1265+
1266+/// §9.3.3.3 — encode an EGk-coded value (the dual of the decoder's
1267+/// `read_eg_k_with`): a run of `1` prefix bins, a `0`, then
1268+/// `prefix_ones + k` MSB-first suffix bins.
1269+fn encode_eg_k(w: &mut BitWriter, cabac: &mut CabacEncoder, value: u32, k: u32) {
1270+ let mut prefix_ones = 0u32;
1271+ while ((1u64 << (prefix_ones + 1)) - 1) << k <= u64::from(value) {
1272+ prefix_ones += 1;
1273+ }
1274+ for _ in 0..prefix_ones {
1275+ cabac.encode_bypass(w, 1);
1276+ }
1277+ cabac.encode_bypass(w, 0);
1278+ let base = ((1u64 << prefix_ones) - 1) << k;
1279+ let suffix = (u64::from(value) - base) as u32;
1280+ cabac.encode_bypass_bits(w, suffix, (prefix_ones + k) as u8);
1281+}
1282+
1283+/// §7.3.8.9 `mvd_coding( )` — the interleaved bin order the decoder's
1284+/// `decode_mvd_pair` reads: both `abs_mvd_greater0_flag`s, both
1285+/// `abs_mvd_greater1_flag`s, then per component the EG1
1286+/// `abs_mvd_minus2` escape and `mvd_sign_flag`.
1287+fn encode_mvd_pair(w: &mut BitWriter, cabac: &mut CabacEncoder, ctxs: &mut SliceContexts, mvd: Mv) {
1288+ let g0 = [mvd[0] != 0, mvd[1] != 0];
1289+ for &g in &g0 {
1290+ cabac.encode_decision(w, &mut ctxs.abs_mvd_greater0_flag[0], u8::from(g));
1291+ }
1292+ for (&g, &v) in g0.iter().zip(mvd.iter()) {
1293+ if g {
1294+ cabac.encode_decision(
1295+ w,
1296+ &mut ctxs.abs_mvd_greater1_flag[0],
1297+ u8::from(v.unsigned_abs() > 1),
1298+ );
1299+ }
1300+ }
1301+ for (&g, &v) in g0.iter().zip(mvd.iter()) {
1302+ if g {
1303+ let a = v.unsigned_abs();
1304+ if a > 1 {
1305+ encode_eg_k(w, cabac, a - 2, 1);
1306+ }
1307+ cabac.encode_bypass(w, u8::from(v < 0));
1308+ }
1309+ }
1310+}
1311+
1312+/// §7.3.8.6 — emit one prediction unit's syntax (merge_flag +
1313+/// merge_idx, or the AMVP groups). On B slices `inter_pred_idc` is
1314+/// coded per Table 9-47 (`PRED_BI` = "1", `PRED_L0` = "00", `PRED_L1`
1315+/// = "01"; bin 0 ctxInc = CtDepth = 0, bin 1 ctxInc = 4 — `nPbW +
1316+/// nPbH != 12` for every PU shape this encoder emits). Each used
1317+/// list codes `ref_idx_lX` (a single context bin — at most two active
1318+/// references per list), `mvd_coding` (`mvd_l1_zero_flag == 0`) and
1319+/// `mvp_lX_flag`.
1320+fn encode_pu_syntax(
1321+ w: &mut BitWriter,
1322+ cabac: &mut CabacEncoder,
1323+ ctxs: &mut SliceContexts,
1324+ pu: &PuSyntax,
1325+ b_slice: bool,
1326+ n_l0: usize,
1327+ n_l1: usize,
1328+) {
1329+ match pu {
1330+ PuSyntax::Merge { merge_idx } => {
1331+ cabac.encode_decision(w, &mut ctxs.merge_flag[0], 1);
1332+ encode_merge_idx(w, cabac, ctxs, *merge_idx);
1333+ }
1334+ PuSyntax::Amvp { l0, l1 } => {
1335+ cabac.encode_decision(w, &mut ctxs.merge_flag[0], 0);
1336+ if b_slice {
1337+ let (head, tail) = ctxs.inter_pred_idc.split_at_mut(4);
1338+ if l0.is_some() && l1.is_some() {
1339+ cabac.encode_decision(w, &mut head[0], 1); // PRED_BI
1340+ } else {
1341+ cabac.encode_decision(w, &mut head[0], 0);
1342+ cabac.encode_decision(w, &mut tail[0], u8::from(l1.is_some()));
1343+ }
1344+ }
1345+ for (group, n_active) in [(l0, n_l0), (l1, n_l1)] {
1346+ let Some(g) = group else { continue };
1347+ if n_active > 1 {
1348+ // §9.3.3 TR cMax = num_ref_idx_lX_active_minus1 ==
1349+ // 1: a single context-coded bin (ctxInc 0).
1350+ debug_assert!(n_active == 2, "at most two active references per list");
1351+ cabac.encode_decision(w, &mut ctxs.ref_idx[0], g.ref_idx);
1352+ }
1353+ encode_mvd_pair(w, cabac, ctxs, g.mvd);
1354+ cabac.encode_decision(w, &mut ctxs.mvp_flag[0], g.mvp_flag);
1355+ }
1356+ }
1357+ }
1358+}
1359+
1360+/// Encode one P / B frame as a single TRAIL_R slice against the
1361+/// reference lists of `spec`: pass 1 makes the per-CTB mode decisions
1362+/// and builds the pre-filter reconstruction, the §8.7 filter stage
1363+/// elects and applies deblocking + SAO, pass 2 emits the slice header
1364+/// and syntax. Returns the slice RBSP, the frame's (filtered)
1365+/// reconstruction, and its CU mode-decision counters.
1366+#[allow(clippy::too_many_lines)]
1367+pub(crate) fn encode_inter_slice(
1368+ frame: &YuvFrame<'_>,
1369+ spec: &SliceSpec<'_>,
1370+ width: usize,
1371+ height: usize,
1372+) -> (Vec<u8>, FrameRecon, FrameStats) {
1373+ let (poc, qp, b_slice, lf) = (spec.poc, spec.qp, spec.b_slice, spec.lf);
1374+ let (cw, ch) = (width / 2, height / 2);
1375+ let ctbs_x = width / CTB;
1376+ let ctbs_y = height / CTB;
1377+ let qp_y = qp as u32;
1378+ let qp_c = chroma_qp_420(qp);
1379+ // SSD-per-bit tradeoff, doubling every 3 QP (as the intra path);
1380+ // the SAD-domain motion-search λ uses the same scale.
1381+ let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3);
1382+ let lambda_me: u64 = lambda;
1383+
1384+ let to_i32 = |p: &[u8]| -> Vec<i32> { p.iter().map(|&v| i32::from(v)).collect() };
1385+ let to_planes = |list: &[(i32, &FrameRecon)]| -> Vec<RefPlanes> {
1386+ list.iter()
1387+ .map(|&(_, rec)| RefPlanes {
1388+ y: to_i32(&rec.y),
1389+ cb: to_i32(&rec.cb),
1390+ cr: to_i32(&rec.cr),
1391+ width,
1392+ height,
1393+ })
1394+ .collect()
1395+ };
1396+ let refs_l0: Vec<RefPlanes> = to_planes(&spec.l0);
1397+ let refs_l1: Vec<RefPlanes> = to_planes(&spec.l1);
1398+ let l0_pocs: Vec<i32> = spec.l0.iter().map(|&(p, _)| p).collect();
1399+ let l1_pocs: Vec<i32> = spec.l1.iter().map(|&(p, _)| p).collect();
1400+ let n_l0 = l0_pocs.len() as i32;
1401+ let n_l1 = l1_pocs.len() as i32;
1402+ // Hierarchical B: the two lists differ, so the AMVP election
1403+ // searches L1 / bi as well; a low-delay B keeps the L0-only
1404+ // search (L1 duplicates it at a higher signalling rate).
1405+ let two_sided = b_slice && l0_pocs != l1_pocs;
1406+
1407+ let mut recon = FrameRecon {
1408+ y: vec![0u8; width * height],
1409+ cb: vec![0u8; cw * ch],
1410+ cr: vec![0u8; cw * ch],
1411+ };
1412+ let mut field = MotionField::new(width, height);
1413+ // §8.4.2 luma-mode records for the intra-fallback MPM lists (an
1414+ // inter / skip CU records as "not intra" ⇒ candidate INTRA_DC).
1415+ let mut modes = IntraModeField::new(width, height, CTB_LOG2);
1416+ // Per-CTB cu_skip_flag values (CU == CTB) for the §9.3.4.2.2 ctxInc.
1417+ let mut skip_grid = vec![false; ctbs_x * ctbs_y];
1418+ let mut stats = FrameStats::default();
1419+
1420+ // §6.4.2 availability plumbing (single slice, single tile).
1421+ let tiling = PictureTiling::new(
1422+ ctbs_x as u32,
1423+ ctbs_y as u32,
1424+ width as u32,
1425+ height as u32,
1426+ CTB_LOG2,
1427+ 2,
1428+ &TilingParams::single_tile(),
1429+ )
1430+ .expect("legal single-tile geometry");
1431+
1432+ // §8.5.3.2 reference resolvers over the spec's explicit lists.
1433+ let list_pocs = |list: usize| -> &Vec<i32> {
1434+ if list == 0 {
1435+ &l0_pocs
1436+ } else {
1437+ &l1_pocs
1438+ }
1439+ };
1440+ let ref_poc = |list: usize, ref_idx: i32| -> i32 {
1441+ usize::try_from(ref_idx)
1442+ .ok()
1443+ .and_then(|i| list_pocs(list).get(i).copied())
1444+ .unwrap_or(i32::MIN)
1445+ };
1446+ // The decoder's motion-field cells store the REFERENCED
1447+ // picture's POC per used list (pu_mv fill: `ref_poc(list, idx)`);
1448+ // an unused list's value is ignored by `to_cell`.
1449+ let cell_pocs =
1450+ |m: &PuMotion| -> (i32, i32) { (ref_poc(0, m.ref_idx_l0), ref_poc(1, m.ref_idx_l1)) };
1451+ let ref_long_term = |_list: usize, _ref_idx: i32| false;
1452+ let ref_short_term = |list: usize, ref_idx: i32| {
1453+ usize::try_from(ref_idx).is_ok_and(|i| i < list_pocs(list).len())
1454+ };
1455+ let col_ref_long_term = |_poc: i32| false;
1456+ // §8.5.3.2.2 NoBackwardPredFlag: 1 iff every active reference of
1457+ // both lists precedes the current picture in output order.
1458+ let no_backward_pred = !l0_pocs.iter().chain(l1_pocs.iter()).any(|&p| p > poc);
1459+ let mv_ctx = PuMvContext {
1460+ curr_poc: poc,
1461+ slice_is_b: b_slice,
1462+ ctb_log2_size_y: CTB_LOG2,
1463+ pic_width_luma: width as u32,
1464+ pic_height_luma: height as u32,
1465+ max_num_merge_cand: MAX_MERGE,
1466+ num_ref_idx_l0_active: n_l0,
1467+ num_ref_idx_l1_active: if b_slice { n_l1 } else { 0 },
1468+ log2_par_mrg_level: 2,
1469+ temporal_mvp_enabled: false,
1470+ collocated_from_l0_flag: true,
1471+ col_poc: 0,
1472+ no_backward_pred,
1473+ ref_poc: &ref_poc,
1474+ ref_long_term: &ref_long_term,
1475+ ref_short_term: &ref_short_term,
1476+ col_field: None,
1477+ col_ref_long_term: &col_ref_long_term,
1478+ use_integer_mv: false,
1479+ two_versions_curr_pic: false,
1480+ is_curr_pic: &|_, _| false,
1481+ };
1482+
1483+ // ---- pass 1: per-CTB mode decisions + reconstruction ----
1484+ let mut plans: Vec<CuCandidate> = Vec::with_capacity(ctbs_x * ctbs_y);
1485+ // `ctb` also drives the x0/y0 arithmetic, not just the grid index.
1486+ #[allow(clippy::needless_range_loop)]
1487+ for ctb in 0..ctbs_x * ctbs_y {
1488+ let x0 = (ctb % ctbs_x) * CTB;
1489+ let y0 = (ctb / ctbs_x) * CTB;
1490+ let (cx0, cy0) = (x0 / 2, y0 / 2);
1491+ let src = [
1492+ extract(frame.y, width, x0, y0, CTB),
1493+ extract(frame.cb, cw, cx0, cy0, 8),
1494+ extract(frame.cr, cw, cx0, cy0, 8),
1495+ ];
1496+
1497+ let geom = PuGeometry {
1498+ x_cb: x0,
1499+ y_cb: y0,
1500+ n_cb_s: CTB,
1501+ x_pb: x0,
1502+ y_pb: y0,
1503+ n_pb_w: CTB,
1504+ n_pb_h: CTB,
1505+ part_mode: PartMode::Part2Nx2N,
1506+ part_idx: 0,
1507+ };
1508+
1509+ let chosen = {
1510+ // §6.4.2 prediction-block availability against the
1511+ // in-progress motion field (identical to the decoder's
1512+ // closure in the picture-level inter driver).
1513+ let available = |x_nb: i32, y_nb: i32| -> bool {
1514+ tiling.prediction_block_availability(
1515+ x0 as u32,
1516+ y0 as u32,
1517+ CTB as u32,
1518+ x0 as u32,
1519+ y0 as u32,
1520+ CTB as u32,
1521+ CTB as u32,
1522+ 0,
1523+ x_nb,
1524+ y_nb,
1525+ |_ctb_rs| 0,
1526+ |x, y| {
1527+ if field.cell_at(x as usize, y as usize).is_intra {
1528+ MODE_INTRA
1529+ } else {
1530+ 0
1531+ }
1532+ },
1533+ )
1534+ };
1535+
1536+ // ---- merge / skip candidates (§8.5.3.2.2) ----
1537+ let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE);
1538+ for idx in 0..MAX_MERGE {
1539+ let m = resolve_pu_motion(&field, &geom, &merge_pu(idx), &mv_ctx, &available);
1540+ // A later duplicate can never beat the earlier index
1541+ // (same samples, more merge_idx bins).
1542+ if !merge_cands.iter().any(|(_, prev)| *prev == m) {
1543+ merge_cands.push((idx, m));
1544+ }
1545+ }
1546+ let (best_merge_idx, best_merge_motion) = merge_cands
1547+ .iter()
1548+ .map(|&(idx, m)| {
1549+ let pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &m, false);
1550+ (
1551+ sad(&pred.luma, &src[0]) + lambda_me * (idx as u64 + 1),
1552+ idx,
1553+ m,
1554+ )
1555+ })
1556+ .min_by_key(|&(cost, idx, _)| (cost, idx))
1557+ .map(|(_, idx, m)| (idx, m))
1558+ .expect("merge list is never empty");
1559+
1560+ // ---- AMVP: §8.5.3.2.6 predictors + per-reference ME ----
1561+ let choose_ctx = PuChooseCtx {
1562+ refs_l0: &refs_l0,
1563+ refs_l1: &refs_l1,
1564+ mv_ctx: &mv_ctx,
1565+ lambda_me,
1566+ b_slice,
1567+ two_sided,
1568+ };
1569+ let (amvp_syntax, amvp_motion, amvp_rate, _) = amvp_search(
1570+ &field,
1571+ &geom,
1572+ &available,
1573+ &src[0],
1574+ &choose_ctx,
1575+ &merge_cands,
1576+ );
1577+
1578+ // ---- fully code the finalists ----
1579+ let mut cands: Vec<CuCandidate> = Vec::with_capacity(6);
1580+
1581+ // Skip: best merge candidate, prediction only.
1582+ let merge_pred = predict_block(
1583+ &refs_l0,
1584+ &refs_l1,
1585+ x0,
1586+ y0,
1587+ CTB,
1588+ CTB,
1589+ &best_merge_motion,
1590+ true,
1591+ );
1592+ let (skip_recon, skip_dist) = pred_recon(&merge_pred, &src);
1593+ cands.push(CuCandidate {
1594+ kind: CuKind::Skip {
1595+ merge_idx: best_merge_idx,
1596+ },
1597+ motions: vec![best_merge_motion],
1598+ levels: None,
1599+ recon: skip_recon,
1600+ cost: skip_dist + lambda * (best_merge_idx as u64 + 2),
1601+ });
1602+
1603+ // Merge + residual (only legal when some level is nonzero:
1604+ // a 2Nx2N merge CU has rqt_root_cbf inferred 1).
1605+ let (m_levels, m_recon, m_dist, m_rate) =
1606+ code_ctb_residual(&merge_pred, &src, qp_y, qp_c);
1607+ if m_levels.iter().any(|l| l.iter().any(|&v| v != 0)) {
1608+ cands.push(CuCandidate {
1609+ kind: CuKind::Merge {
1610+ merge_idx: best_merge_idx,
1611+ },
1612+ motions: vec![best_merge_motion],
1613+ levels: Some(CuLevels::Depth0(m_levels)),
1614+ recon: m_recon,
1615+ cost: m_dist + lambda * (m_rate + best_merge_idx as u64 + 3),
1616+ });
1617+ }
1618+
1619+ // AMVP (with or without residual).
1620+ let amvp_pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &amvp_motion, true);
1621+ let (a_levels, a_recon, a_dist, a_rate) =
1622+ code_ctb_residual(&amvp_pred, &src, qp_y, qp_c);
1623+ let motion_rate = amvp_rate + 2; // + skip / rqt flags
1624+ if a_levels.iter().any(|l| l.iter().any(|&v| v != 0)) {
1625+ cands.push(CuCandidate {
1626+ kind: CuKind::Amvp { pu: amvp_syntax },
1627+ motions: vec![amvp_motion],
1628+ levels: Some(CuLevels::Depth0(a_levels)),
1629+ recon: a_recon,
1630+ cost: a_dist + lambda * (a_rate + motion_rate),
1631+ });
1632+ } else {
1633+ // All-zero residual: rqt_root_cbf == 0.
1634+ let (pr, pd) = pred_recon(&amvp_pred, &src);
1635+ cands.push(CuCandidate {
1636+ kind: CuKind::Amvp { pu: amvp_syntax },
1637+ motions: vec![amvp_motion],
1638+ levels: None,
1639+ recon: pr,
1640+ cost: pd + lambda * motion_rate,
1641+ });
1642+ }
1643+
1644+ // ---- two-PU partitions: the symmetric rectangles, plus
1645+ // the four asymmetric shapes on an AMP stream ----
1646+ let mut two_pu_parts = vec![PartMode::Part2NxN, PartMode::PartNx2N];
1647+ if spec.big_cu {
1648+ two_pu_parts.extend([
1649+ PartMode::Part2NxnU,
1650+ PartMode::Part2NxnD,
1651+ PartMode::PartNLx2N,
1652+ PartMode::PartNRx2N,
1653+ ]);
1654+ }
1655+ for part in two_pu_parts {
1656+ let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part);
1657+ // The decoder resolves PU1 with PU0's motion already in
1658+ // the field (§8.5.3.2 order): stage the writes on a copy.
1659+ let mut tmp = field.clone();
1660+ let mut pus = [PuSyntax::Merge { merge_idx: 0 }; 2];
1661+ let mut motions_r = Vec::with_capacity(2);
1662+ let mut pred_y = vec![0i32; CTB * CTB];
1663+ let mut pred_cb = vec![0i32; 64];
1664+ let mut pred_cr = vec![0i32; 64];
1665+ // pred_mode + part_mode bins (the AMP forms carry two
1666+ // extra part_mode bins).
1667+ let mut motion_rate_r = if part_is_amp(part) { 5u64 } else { 3u64 };
1668+ for (k, r) in rects.iter().enumerate() {
1669+ let g = PuGeometry {
1670+ x_cb: x0,
1671+ y_cb: y0,
1672+ n_cb_s: CTB,
1673+ x_pb: r.x_pb,
1674+ y_pb: r.y_pb,
1675+ n_pb_w: r.n_pb_w,
1676+ n_pb_h: r.n_pb_h,
1677+ part_mode: part,
1678+ part_idx: k as u32,
1679+ };
1680+ // §6.4.2 availability against the staged field. The
1681+ // decoder's closure passes the CU as the PU geometry
1682+ // (the sameCb NxN clause never fires for 2-PU
1683+ // shapes) and treats the current CU as MODE_INTER.
1684+ let avail_k = |x_nb: i32, y_nb: i32| -> bool {
1685+ tiling.prediction_block_availability(
1686+ x0 as u32,
1687+ y0 as u32,
1688+ CTB as u32,
1689+ x0 as u32,
1690+ y0 as u32,
1691+ CTB as u32,
1692+ CTB as u32,
1693+ 0,
1694+ x_nb,
1695+ y_nb,
1696+ |_ctb_rs| 0,
1697+ |x, y| {
1698+ let (xu, yu) = (x as usize, y as usize);
1699+ let inside_cu =
1700+ (x0..x0 + CTB).contains(&xu) && (y0..y0 + CTB).contains(&yu);
1701+ if !inside_cu && tmp.cell_at(xu, yu).is_intra {
1702+ MODE_INTRA
1703+ } else {
1704+ 0
1705+ }
1706+ },
1707+ )
1708+ };
1709+ let mut src_pu = Vec::with_capacity(r.n_pb_w * r.n_pb_h);
1710+ for j in 0..r.n_pb_h {
1711+ for i in 0..r.n_pb_w {
1712+ src_pu.push(i32::from(frame.y[(r.y_pb + j) * width + r.x_pb + i]));
1713+ }
1714+ }
1715+ let (pu_syntax, motion, rate_k) =
1716+ choose_pu(&tmp, &g, &avail_k, &src_pu, &choose_ctx);
1717+ // eqs 8-80..8-85: PU1's derivation sees PU0's motion.
1718+ tmp.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, {
1719+ let (p0, p1) = cell_pocs(&motion);
1720+ motion.to_cell(p0, p1)
1721+ });
1722+ let p = predict_block(
1723+ &refs_l0, &refs_l1, r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, &motion, true,
1724+ );
1725+ blit(
1726+ &mut pred_y,
1727+ CTB,
1728+ r.x_pb - x0,
1729+ r.y_pb - y0,
1730+ &p.luma,
1731+ r.n_pb_w,
1732+ r.n_pb_h,
1733+ );
1734+ blit(
1735+ &mut pred_cb,
1736+ 8,
1737+ (r.x_pb - x0) / 2,
1738+ (r.y_pb - y0) / 2,
1739+ &p.cb,
1740+ r.n_pb_w / 2,
1741+ r.n_pb_h / 2,
1742+ );
1743+ blit(
1744+ &mut pred_cr,
1745+ 8,
1746+ (r.x_pb - x0) / 2,
1747+ (r.y_pb - y0) / 2,
1748+ &p.cr,
1749+ r.n_pb_w / 2,
1750+ r.n_pb_h / 2,
1751+ );
1752+ pus[k] = pu_syntax;
1753+ motions_r.push(motion);
1754+ motion_rate_r += rate_k;
1755+ }
1756+ // §7.4.9.8 interSplitFlag: forced depth-1 tree — four
1757+ // z-order 8x8 luma + 4x4 chroma TBs.
1758+ let mut luma_l: [Vec<i32>; 4] = Default::default();
1759+ let mut cb_l: [Vec<i32>; 4] = Default::default();
1760+ let mut cr_l: [Vec<i32>; 4] = Default::default();
1761+ let mut recon_r = [vec![0u8; CTB * CTB], vec![0u8; 64], vec![0u8; 64]];
1762+ let mut rate_r = 0u64;
1763+ for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
1764+ let (lx, ly8) = (zx * 8, zy * 8);
1765+ let s_y = sub_block(&src[0], CTB, lx, ly8, 8);
1766+ let p_y = sub_block(&pred_y, CTB, lx, ly8, 8);
1767+ let (lv, rc) = code_tb(&s_y, &p_y, 8, qp_y, Component::Luma, PredMode::Inter);
1768+ for j in 0..8 {
1769+ recon_r[0][(ly8 + j) * CTB + lx..(ly8 + j) * CTB + lx + 8]
1770+ .copy_from_slice(&rc[j * 8..(j + 1) * 8]);
1771+ }
1772+ rate_r += levels_rate(&lv);
1773+ luma_l[k] = lv;
1774+ for (plane, src_c, pred_c, out) in [
1775+ (1usize, &src[1], &pred_cb, &mut cb_l),
1776+ (2usize, &src[2], &pred_cr, &mut cr_l),
1777+ ] {
1778+ let s_c = sub_block(src_c, 8, zx * 4, zy * 4, 4);
1779+ let p_c = sub_block(pred_c, 8, zx * 4, zy * 4, 4);
1780+ let comp = if plane == 1 {
1781+ Component::Cb
1782+ } else {
1783+ Component::Cr
1784+ };
1785+ let (lv_c, rc_c) = code_tb(&s_c, &p_c, 4, qp_c, comp, PredMode::Inter);
1786+ for j in 0..4 {
1787+ recon_r[plane]
1788+ [(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4]
1789+ .copy_from_slice(&rc_c[j * 4..(j + 1) * 4]);
1790+ }
1791+ rate_r += levels_rate(&lv_c);
1792+ out[k] = lv_c;
1793+ }
1794+ }
1795+ let any_nonzero = luma_l
1796+ .iter()
1797+ .chain(cb_l.iter())
1798+ .chain(cr_l.iter())
1799+ .any(|l| l.iter().any(|&v| v != 0));
1800+ let (levels_r, recon_final, dist_r) = if any_nonzero {
1801+ let d = ssd(&recon_r[0], &src[0])
1802+ + ssd(&recon_r[1], &src[1])
1803+ + ssd(&recon_r[2], &src[2]);
1804+ (
1805+ Some(CuLevels::Depth1(Box::new(Depth1Levels {
1806+ luma: luma_l,
1807+ cb: cb_l,
1808+ cr: cr_l,
1809+ }))),
1810+ recon_r,
1811+ d + lambda * rate_r,
1812+ )
1813+ } else {
1814+ // rqt_root_cbf == 0: prediction-only reconstruction.
1815+ let clip = |v: &[i32]| -> Vec<u8> {
1816+ v.iter().map(|&p| p.clamp(0, 255) as u8).collect()
1817+ };
1818+ let rec = [clip(&pred_y), clip(&pred_cb), clip(&pred_cr)];
1819+ let d = ssd(&rec[0], &src[0]) + ssd(&rec[1], &src[1]) + ssd(&rec[2], &src[2]);
1820+ (None, rec, d)
1821+ };
1822+ cands.push(CuCandidate {
1823+ kind: CuKind::TwoPu { part, pus },
1824+ motions: motions_r,
1825+ levels: levels_r,
1826+ recon: recon_final,
1827+ cost: dist_r + lambda * (motion_rate_r + 1),
1828+ });
1829+ }
1830+
1831+ // ---- intra 2Nx2N fallback (§8.4 against our own recon) ----
1832+ {
1833+ let read_y = |x: usize, yy: usize| i32::from(recon.y[yy * width + x]);
1834+ let avail_y =
1835+ |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
1836+ let marked = gather_refs(&read_y, &avail_y, x0, y0, CTB);
1837+ let (mode, pred_y) = search_best_mode(&marked, &src[0]);
1838+ let (ly, ry) = code_tb(
1839+ &src[0],
1840+ &pred_y,
1841+ CTB,
1842+ qp_y,
1843+ Component::Luma,
1844+ PredMode::Intra,
1845+ );
1846+ let code_c = |plane: &[u8], comp: Component, pc: PredComponent| {
1847+ let read = |x: usize, yy: usize| i32::from(plane[yy * cw + x]);
1848+ let avail =
1849+ |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0);
1850+ let marked_c = gather_refs(&read, &avail, cx0, cy0, 8);
1851+ let pred = intra_predict_with_substitution(&marked_c, &pred_params(mode, pc))
1852+ .expect("legal prediction params");
1853+ let src_c = match comp {
1854+ Component::Cb => &src[1],
1855+ _ => &src[2],
1856+ };
1857+ code_tb(src_c, &pred, 8, qp_c, comp, PredMode::Intra)
1858+ };
1859+ let (lcb, rcb) = code_c(&recon.cb, Component::Cb, PredComponent::Cb);
1860+ let (lcr, rcr) = code_c(&recon.cr, Component::Cr, PredComponent::Cr);
1861+ let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]);
1862+ let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr) + 8;
1863+ cands.push(CuCandidate {
1864+ kind: CuKind::Intra { mode },
1865+ motions: Vec::new(),
1866+ levels: Some(CuLevels::Depth0([ly, lcb, lcr])),
1867+ recon: [ry, rcb, rcr],
1868+ cost: dist + lambda * rate,
1869+ });
1870+ }
1871+
1872+ cands
1873+ .into_iter()
1874+ .min_by_key(|c| c.cost)
1875+ .expect("at least the skip candidate")
1876+ };
1877+
1878+ // ---- state update (eqs 8-80..8-85 + mode fields + recon) ----
1879+ let is_skip = matches!(chosen.kind, CuKind::Skip { .. });
1880+ skip_grid[ctb] = is_skip;
1881+ match &chosen.kind {
1882+ CuKind::Intra { mode } => {
1883+ stats.intra += 1;
1884+ // The decoder stamps intra CUs into the motion field so
1885+ // a later CU's §6.4.2 availability denies them.
1886+ field.fill_rect(
1887+ x0,
1888+ y0,
1889+ CTB,
1890+ CTB,
1891+ MotionCell {
1892+ is_intra: true,
1893+ ..MotionCell::default()
1894+ },
1895+ );
1896+ modes.record_intra_pb(x0, y0, CTB, *mode, false);
1897+ }
1898+ kind => {
1899+ match kind {
1900+ CuKind::Skip { .. } => stats.skip += 1,
1901+ CuKind::Merge { .. } => stats.merge += 1,
1902+ CuKind::TwoPu { part, pus } => {
1903+ if pus.iter().any(|p| matches!(p, PuSyntax::Amvp { .. })) {
1904+ stats.amvp += 1;
1905+ } else {
1906+ stats.merge += 1;
1907+ }
1908+ if part_is_amp(*part) {
1909+ stats.amp += 1;
1910+ } else {
1911+ stats.rect += 1;
1912+ }
1913+ }
1914+ _ => stats.amvp += 1,
1915+ }
1916+ if chosen
1917+ .motions
1918+ .iter()
1919+ .any(|m| m.pred_flag_l0 && m.pred_flag_l1)
1920+ {
1921+ stats.bi += 1;
1922+ }
1923+ if chosen.motions.iter().any(|m| {
1924+ (m.pred_flag_l0 && m.ref_idx_l0 > 0) || (m.pred_flag_l1 && m.ref_idx_l1 > 0)
1925+ }) {
1926+ stats.ref1 += 1;
1927+ }
1928+ // eqs 8-80..8-85: one motion cell per PU rectangle, the
1929+ // stored identity being the referenced picture's POC.
1930+ let part = match kind {
1931+ CuKind::TwoPu { part, .. } => *part,
1932+ _ => PartMode::Part2Nx2N,
1933+ };
1934+ let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part);
1935+ for (r, m) in rects.iter().zip(chosen.motions.iter()) {
1936+ field.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, {
1937+ let (p0, p1) = cell_pocs(m);
1938+ m.to_cell(p0, p1)
1939+ });
1940+ }
1941+ let cu_mode = if is_skip {
1942+ CuPredMode::Skip
1943+ } else {
1944+ CuPredMode::Inter
1945+ };
1946+ modes.record_non_intra_cu(x0, y0, CTB, cu_mode);
1947+ // §8.7.2.4 — mark each luma TRANSFORM BLOCK carrying a
1948+ // coded coefficient (the decoder marks per tree leaf,
1949+ // not per CU; intra CUs are never marked — their edges
1950+ // are bS 2 regardless).
1951+ match &chosen.levels {
1952+ Some(CuLevels::Depth0(l)) if l[0].iter().any(|&v| v != 0) => {
1953+ field.mark_nonzero_coeff(x0, y0, CTB, CTB);
1954+ }
1955+ Some(CuLevels::Depth1(d)) => {
1956+ for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
1957+ if d.luma[k].iter().any(|&v| v != 0) {
1958+ field.mark_nonzero_coeff(x0 + zx * 8, y0 + zy * 8, 8, 8);
1959+ }
1960+ }
1961+ }
1962+ _ => {}
1963+ }
1964+ }
1965+ }
1966+ store(&mut recon.y, width, x0, y0, CTB, &chosen.recon[0]);
1967+ store(&mut recon.cb, cw, cx0, cy0, 8, &chosen.recon[1]);
1968+ store(&mut recon.cr, cw, cx0, cy0, 8, &chosen.recon[2]);
1969+ plans.push(chosen);
1970+ }
1971+
1972+ // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ----
1973+ let mut lf_sig = SliceLfSignalling {
1974+ cfg: lf,
1975+ deblock_on: false,
1976+ beta_offset_div2: 0,
1977+ tc_offset_div2: 0,
1978+ sao_luma: false,
1979+ sao_chroma: false,
1980+ };
1981+ let mut sao_ctbs: Vec<crate::slice_data::SaoCtbParams> = Vec::new();
1982+ if lf.any() {
1983+ let shapes: Vec<CtbShape> = plans
1984+ .iter()
1985+ .map(|c| CtbShape {
1986+ part_mode: match &c.kind {
1987+ CuKind::TwoPu { part, .. } => bin_part_mode(*part),
1988+ _ => crate::binarization::PartMode::Part2Nx2N,
1989+ },
1990+ split_depth1: matches!(c.levels, Some(CuLevels::Depth1(_))),
1991+ })
1992+ .collect();
1993+ let out = filter_frame(
1994+ &FilterInput {
1995+ width,
1996+ height,
1997+ qp,
1998+ lambda,
1999+ recon: [&recon.y, &recon.cb, &recon.cr],
2000+ src: [frame.y, frame.cb, frame.cr],
vendor/oxideav-h265/src/encoder/intra.rsadded+1514 -0
@@ -0,0 +1,1514 @@
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+use crate::encoder::pcm::{level_idc_for, write_pps_lf, write_ptl, write_vps, write_vps_cfg};
58+use crate::encoder::residual::encode_residual_coding;
59+use crate::intra_mode_field::{IntraModeField, Neighbour};
60+use crate::intra_pred::{
61+ intra_predict_with_substitution, Component as PredComponent, IntraPredParams,
62+ MarkedReferenceSamples,
63+};
64+use crate::motion::MotionField;
65+use crate::residual::{residual_coding_scan_idx, ResidualCodingParams};
66+use crate::slice_data::SaoCtbParams;
67+use crate::transform::{forward_dct_1d, residual_block, BlockParams, Component, PredMode};
68+
69+/// The fixed CTB / coding-block log2 size (16x16).
70+const CTB_LOG2: u32 = 4;
71+/// The fixed CTB size.
72+const CTB: usize = 1 << CTB_LOG2;
73+/// Fixed 8-bit depth.
74+const BIT_DEPTH: u32 = 8;
75+/// The z-order offsets of the four NxN prediction blocks / depth-1
76+/// transform units within a CTB (§6.5.2 z-scan of the four halves).
77+const Z_OFFSETS: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)];
78+
79+/// Errors from the intra encoder.
80+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
81+pub enum IntraEncodeError {
82+ /// Width or height is zero or not a multiple of the 16-sample CTB.
83+ BadDimensions {
84+ /// Requested luma width.
85+ width: usize,
86+ /// Requested luma height.
87+ height: usize,
88+ },
89+ /// A supplied plane's length does not match the 4:2:0 geometry.
90+ PlaneSize {
91+ /// Which plane (`"y"`, `"cb"`, `"cr"`).
92+ plane: &'static str,
93+ /// Required sample count.
94+ expected: usize,
95+ /// Supplied sample count.
96+ got: usize,
97+ },
98+ /// `SliceQpY` outside 0..=51.
99+ BadQp(i32),
100+}
101+
102+impl core::fmt::Display for IntraEncodeError {
103+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
104+ match self {
105+ Self::BadDimensions { width, height } => write!(
106+ f,
107+ "intra encoder requires nonzero dimensions that are multiples of 16, got {width}x{height}"
108+ ),
109+ Self::PlaneSize {
110+ plane,
111+ expected,
112+ got,
113+ } => write!(f, "{plane} plane has {got} samples, expected {expected}"),
114+ Self::BadQp(qp) => write!(f, "slice QP {qp} outside 0..=51"),
115+ }
116+ }
117+}
118+
119+impl std::error::Error for IntraEncodeError {}
120+
121+/// The encoded access unit plus the encoder's own reconstruction
122+/// (what a conforming decoder outputs — in-loop filters are off).
123+#[derive(Debug, Clone)]
124+pub struct IntraEncodedAu {
125+ /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP`).
126+ pub au: Vec<u8>,
127+ /// Reconstructed luma plane (`width * height`).
128+ pub recon_y: Vec<u8>,
129+ /// Reconstructed Cb plane (`width/2 * height/2`).
130+ pub recon_cb: Vec<u8>,
131+ /// Reconstructed Cr plane.
132+ pub recon_cr: Vec<u8>,
133+}
134+
135+/// The stream-level geometry / buffering knobs of the shared SPS
136+/// (everything the intra, low-delay and hierarchical-B encoders vary
137+/// between them; the rest of the SPS is fixed 4:2:0 8-bit CTB-16).
138+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139+pub(crate) struct SpsCfg {
140+ /// `sps_max_dec_pic_buffering_minus1[0]`.
141+ pub max_dec_pic_buffering_minus1: u32,
142+ /// `sps_max_num_reorder_pics[0]` (nonzero for the out-of-order
143+ /// hierarchical-B GOPs).
144+ pub max_num_reorder_pics: u32,
145+ /// `MinCbLog2SizeY` (4 for the legacy CTB == CU geometry; 3 for
146+ /// the AMP-enabled geometry, where every CTB is an UNSPLIT 16x16
147+ /// CU with `log2CbSize > MinCbLog2SizeY`).
148+ pub min_cb_log2: u32,
149+ /// `amp_enabled_flag` (requires `min_cb_log2 == 3` — Table 9-45
150+ /// only reaches the AMP bin strings when `log2CbSize >
151+ /// MinCbLog2SizeY`).
152+ pub amp: bool,
153+ // --- edith patch (see the crate-level note in vendor/) ---
154+ /// `conf_win_right_offset` / `conf_win_bottom_offset`, in
155+ /// **chroma** units (§7.4.3.2.1: the luma crop is these times
156+ /// `SubWidthC`/`SubHeightC`, i.e. 2 at 4:2:0). `(0, 0)` writes
157+ /// `conformance_window_flag = 0`, which is what upstream always
158+ /// wrote.
159+ pub conf_win: (u32, u32),
160+ // --- end edith patch ---
161+}
162+
163+impl SpsCfg {
164+ /// The legacy fixed geometry: `MinCbSizeY == CtbSizeY == 16`, no
165+ /// AMP, no output reordering.
166+ pub(crate) fn legacy(max_dec_pic_buffering_minus1: u32) -> Self {
167+ Self {
168+ max_dec_pic_buffering_minus1,
169+ max_num_reorder_pics: 0,
170+ min_cb_log2: CTB_LOG2,
171+ amp: false,
172+ conf_win: (0, 0),
173+ }
174+ }
175+}
176+
177+/// §7.3.2.2 — the fixed-geometry SPS (4:2:0, 8-bit, CTB 16, PCM off,
178+/// SAO per `sao_enabled`) with the [`SpsCfg`] knob set (coding-block
179+/// geometry, `amp_enabled_flag`, DPB / reorder bounds). Shared by the
180+/// intra, low-delay and hierarchical-B encoders (nothing in it is
181+/// slice-type specific: the P / B slices code their §7.4.8 short-term
182+/// RPS inline and `sps_temporal_mvp_enabled_flag` is 0).
183+pub(crate) fn write_sps_cfg(
184+ width: usize,
185+ height: usize,
186+ level_idc: u8,
187+ cfg: &SpsCfg,
188+ sao_enabled: bool,
189+) -> Vec<u8> {
190+ debug_assert!(
191+ !cfg.amp || cfg.min_cb_log2 < CTB_LOG2,
192+ "AMP requires log2CbSize > MinCbLog2SizeY (Table 9-45)"
193+ );
194+ let mut w = BitWriter::new();
195+ w.put_bits(0, 4); // sps_video_parameter_set_id
196+ w.put_bits(0, 3); // sps_max_sub_layers_minus1
197+ w.put_bit(1); // sps_temporal_id_nesting_flag
198+ write_ptl(&mut w, level_idc);
199+ w.ue(0); // sps_seq_parameter_set_id
200+ w.ue(1); // chroma_format_idc = 4:2:0
201+ w.ue(width as u32); // pic_width_in_luma_samples
202+ w.ue(height as u32); // pic_height_in_luma_samples
203+ // --- edith patch: conformance window (upstream always wrote 0) ---
204+ match cfg.conf_win {
205+ (0, 0) => w.put_bit(0), // conformance_window_flag
206+ (right, bottom) => {
207+ w.put_bit(1); // conformance_window_flag
208+ w.ue(0); // conf_win_left_offset
209+ w.ue(right); // conf_win_right_offset
210+ w.ue(0); // conf_win_top_offset
211+ w.ue(bottom); // conf_win_bottom_offset
212+ }
213+ }
214+ // --- end edith patch ---
215+ w.ue(0); // bit_depth_luma_minus8
216+ w.ue(0); // bit_depth_chroma_minus8
217+ w.ue(4); // log2_max_pic_order_cnt_lsb_minus4
218+ w.put_bit(1); // sps_sub_layer_ordering_info_present_flag
219+ w.ue(cfg.max_dec_pic_buffering_minus1); // sps_max_dec_pic_buffering_minus1[0]
220+ w.ue(cfg.max_num_reorder_pics); // sps_max_num_reorder_pics[0]
221+ w.ue(0); // sps_max_latency_increase_plus1[0]
222+ w.ue(cfg.min_cb_log2 - 3); // log2_min_luma_coding_block_size_minus3
223+ w.ue(CTB_LOG2 - cfg.min_cb_log2); // log2_diff_max_min_luma_coding_block_size (CTB 16)
224+ w.ue(0); // log2_min_luma_transform_block_size_minus2 (4)
225+ w.ue(2); // log2_diff_max_min_luma_transform_block_size (16)
226+ w.ue(0); // max_transform_hierarchy_depth_inter
227+ w.ue(0); // max_transform_hierarchy_depth_intra
228+ w.put_bit(0); // scaling_list_enabled_flag
229+ w.put_bit(u8::from(cfg.amp)); // amp_enabled_flag
230+ w.put_bit(u8::from(sao_enabled)); // sample_adaptive_offset_enabled_flag
231+ w.put_bit(0); // pcm_enabled_flag
232+ w.ue(0); // num_short_term_ref_pic_sets
233+ w.put_bit(0); // long_term_ref_pics_present_flag
234+ w.put_bit(0); // sps_temporal_mvp_enabled_flag
235+ w.put_bit(0); // strong_intra_smoothing_enabled_flag
236+ w.put_bit(0); // vui_parameters_present_flag
237+ w.put_bit(0); // sps_extension_present_flag
238+ w.rbsp_trailing_bits();
239+ w.finish()
240+}
241+
242+/// Table 8-10 — the `ChromaArrayType == 1` chroma QP mapping
243+/// `qPC = f(qPi)` (§8.6.1; `QpBdOffsetC == 0` at 8-bit).
244+pub(crate) fn chroma_qp_420(qp_y: i32) -> u32 {
245+ let qpi = qp_y.clamp(0, 57);
246+ (match qpi {
247+ x if x < 30 => x,
248+ 30..=33 => qpi - 1, // 30..=33 -> 29, 30, 31, 32
249+ 34..=43 => 33 + (qpi - 34) / 2, // 34..=43 -> 33, 33, 34, 34 .. 37, 37
250+ x => x - 6,
251+ }) as u32
252+}
253+
254+/// §8.6.3-derived reciprocal quantizer scale: `levelScale[qP % 6]` is
255+/// `{40, 45, 51, 57, 64, 72}`; the forward reciprocal is
256+/// `round(2^20 / levelScale)` so `quant ∘ dequant` has unity gain.
257+fn quant_scale(qp_rem: u32) -> i64 {
258+ let ls = i64::from(crate::transform::LEVEL_SCALE[qp_rem as usize]);
259+ ((1i64 << 20) + ls / 2) / ls
260+}
261+
262+/// Forward 2-D DCT-II (the transpose of the §8.6.4 inverse): stage 1
263+/// over rows with `shift1 = log2TbS + BitDepth − 9`, stage 2 over
264+/// columns with `shift2 = log2TbS + 6` — the normalization that makes
265+/// the §8.6.3 dequant + §8.6.4 inverse reproduce the residual.
266+fn forward_transform(res: &[i32], n: usize) -> Vec<i32> {
267+ let log2 = n.trailing_zeros();
268+ let shift1 = log2 + BIT_DEPTH - 9;
269+ let shift2 = log2 + 6;
270+ let r1 = 1i64 << (shift1 - 1);
271+ let r2 = 1i64 << (shift2 - 1);
272+ // Stage 1: horizontal analysis per row y -> a[y][u].
273+ let mut a = vec![0i64; n * n];
274+ for y in 0..n {
275+ let row: Vec<i64> = (0..n).map(|x| i64::from(res[y * n + x])).collect();
276+ let t = forward_dct_1d(&row, n);
277+ for (u, &v) in t.iter().enumerate() {
278+ a[y * n + u] = (v + r1) >> shift1;
279+ }
280+ }
281+ // Stage 2: vertical analysis per column u -> coef[v][u].
282+ let mut coef = vec![0i32; n * n];
283+ for u in 0..n {
284+ let col: Vec<i64> = (0..n).map(|y| a[y * n + u]).collect();
285+ let t = forward_dct_1d(&col, n);
286+ for (v, &val) in t.iter().enumerate() {
287+ coef[v * n + u] = ((val + r2) >> shift2) as i32;
288+ }
289+ }
290+ coef
291+}
292+
293+/// Scalar quantization to `TransCoeffLevel`: `level = sign ·
294+/// (|coef| · quantScale + offset) >> qBits` with `qBits = 14 + qP/6 +
295+/// (15 − BitDepth − log2TbS)` (the inverse of the §8.6.3 eq. 8-309
296+/// scaling chain) and a one-third rounding offset; clamped to the
297+/// §7.4.9.11 CoeffMax.
298+fn quantize(coef: &[i32], n: usize, qp: u32) -> Vec<i32> {
299+ let log2 = n.trailing_zeros();
300+ let qbits = 14 + qp / 6 + (15 - BIT_DEPTH - log2);
301+ let scale = quant_scale(qp % 6);
302+ let offset = (1i64 << qbits) / 3;
303+ coef.iter()
304+ .map(|&c| {
305+ let level = ((i64::from(c.unsigned_abs()) * scale + offset) >> qbits).min(0x7FFF);
306+ (level as i32) * c.signum()
307+ })
308+ .collect()
309+}
310+
311+/// §6.4.1-shaped z-scan availability of the sample at `(nx, ny)`
312+/// relative to the block being decoded: available iff inside the
313+/// plane AND its covering coding block precedes in decode order —
314+/// an earlier CTB (raster), or the same CTB with a smaller depth-1
315+/// z-order quadrant index (`cur_z`; pass 0 when the current TB is the
316+/// whole CTB, making every same-CTB neighbour unavailable).
317+#[allow(clippy::too_many_arguments)]
318+pub(crate) fn zscan_avail(
319+ nx: i64,
320+ ny: i64,
321+ plane_w: usize,
322+ plane_h: usize,
323+ blk: usize,
324+ ctbs_x: usize,
325+ cur_ctb: usize,
326+ cur_z: u32,
327+) -> bool {
328+ if nx < 0 || ny < 0 || nx >= plane_w as i64 || ny >= plane_h as i64 {
329+ return false;
330+ }
331+ let (nx, ny) = (nx as usize, ny as usize);
332+ let nctb = (ny / blk) * ctbs_x + nx / blk;
333+ match nctb.cmp(&cur_ctb) {
334+ core::cmp::Ordering::Less => true,
335+ core::cmp::Ordering::Greater => false,
336+ core::cmp::Ordering::Equal => {
337+ let half = blk / 2;
338+ let z = ((ny % blk) / half) * 2 + ((nx % blk) / half);
339+ (z as u32) < cur_z
340+ }
341+ }
342+}
343+
344+/// Gather the §8.4.4.2.1 marked reference array for an `n`-sample TB
345+/// at `(x0, y0)`: values through `read`, availability through `avail`.
346+pub(crate) fn gather_refs(
347+ read: &dyn Fn(usize, usize) -> i32,
348+ avail: &dyn Fn(i64, i64) -> bool,
349+ x0: usize,
350+ y0: usize,
351+ n: usize,
352+) -> MarkedReferenceSamples {
353+ let get = |x: i64, y: i64| -> (i32, bool) {
354+ if avail(x, y) {
355+ (read(x as usize, y as usize), true)
356+ } else {
357+ (0, false)
358+ }
359+ };
360+ let corner = get(x0 as i64 - 1, y0 as i64 - 1);
361+ let left: Vec<(i32, bool)> = (0..2 * n)
362+ .map(|k| get(x0 as i64 - 1, (y0 + k) as i64))
363+ .collect();
364+ let top: Vec<(i32, bool)> = (0..2 * n)
365+ .map(|k| get((x0 + k) as i64, y0 as i64 - 1))
366+ .collect();
367+ MarkedReferenceSamples::new(n, corner, left, top).expect("legal TB geometry")
368+}
369+
370+pub(crate) fn pred_params(mode: u8, cidx: PredComponent) -> IntraPredParams {
371+ IntraPredParams {
372+ pred_mode_intra: mode,
373+ cidx,
374+ bit_depth: BIT_DEPTH as u8,
375+ bit_depth_luma: BIT_DEPTH as u8,
376+ intra_smoothing_disabled: false,
377+ strong_intra_smoothing_enabled: false,
378+ chroma_array_type_3: false,
379+ disable_boundary_filter: false,
380+ }
381+}
382+
383+/// SAD-search all 35 §8.4.2 modes; returns `(mode, prediction)`.
384+pub(crate) fn search_best_mode(marked: &MarkedReferenceSamples, src: &[i32]) -> (u8, Vec<i32>) {
385+ let mut best = (0u8, Vec::new());
386+ let mut best_cost = u64::MAX;
387+ for mode in 0..=34u8 {
388+ let pred = intra_predict_with_substitution(marked, &pred_params(mode, PredComponent::Luma))
389+ .expect("legal prediction params");
390+ let cost: u64 = src
391+ .iter()
392+ .zip(pred.iter())
393+ .map(|(&s, &p)| u64::from(s.abs_diff(p)))
394+ .sum();
395+ if cost < best_cost {
396+ best_cost = cost;
397+ best = (mode, pred);
398+ }
399+ }
400+ best
401+}
402+
403+/// Transform + quantize one component TB and reconstruct it through
404+/// the DECODE-side §8.6.2 path. Returns `(levels, recon_samples)`;
405+/// `levels` all-zero ⇔ cbf 0 (recon = clipped prediction).
406+///
407+/// `pred_mode` selects the §8.6.4 transform family exactly as the
408+/// decoder does (the intra-luma 4x4 DST case; every TB the intra and
409+/// low-delay-P encoders emit at other geometries is DCT either way).
410+pub(crate) fn code_tb(
411+ src: &[i32],
412+ pred: &[i32],
413+ n: usize,
414+ qp: u32,
415+ component: Component,
416+ pred_mode: PredMode,
417+) -> (Vec<i32>, Vec<u8>) {
418+ let res: Vec<i32> = src.iter().zip(pred.iter()).map(|(&s, &p)| s - p).collect();
419+ let coef = forward_transform(&res, n);
420+ let levels = quantize(&coef, n, qp);
421+ let recon: Vec<u8> = if levels.iter().all(|&v| v == 0) {
422+ pred.iter().map(|&p| p.clamp(0, 255) as u8).collect()
423+ } else {
424+ let r = residual_block(
425+ &levels,
426+ None,
427+ BlockParams {
428+ n_tbs: n,
429+ q_p: qp,
430+ component,
431+ pred_mode,
432+ bit_depth: BIT_DEPTH as u8,
433+ extended_precision: false,
434+ transquant_bypass: false,
435+ transform_skip: false,
436+ transform_skip_rotation_enabled: false,
437+ },
438+ )
439+ .expect("legal block params");
440+ pred.iter()
441+ .zip(r.iter())
442+ .map(|(&p, &d)| (p + d).clamp(0, 255) as u8)
443+ .collect()
444+ };
445+ (levels, recon)
446+}
447+
448+pub(crate) fn ssd(a: &[u8], b: &[i32]) -> u64 {
449+ a.iter()
450+ .zip(b.iter())
451+ .map(|(&x, &y)| {
452+ let d = i64::from(x) - i64::from(y);
453+ (d * d) as u64
454+ })
455+ .sum()
456+}
457+
458+/// Crude bit-cost proxy for one TB's quantized levels: each nonzero
459+/// coefficient costs roughly its magnitude's bit length (sig flag +
460+/// sign + level bins); a coded-but-empty TB is nearly free, a coded
461+/// TB pays a small last-sig overhead.
462+fn rate_proxy(levels: &[i32]) -> u64 {
463+ let bits: u64 = levels
464+ .iter()
465+ .filter(|&&l| l != 0)
466+ .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros()))
467+ .sum();
468+ if bits == 0 {
469+ 1
470+ } else {
471+ bits + 8
472+ }
473+}
474+
475+/// One coded luma partition candidate for a CTB.
476+struct LumaPlan {
477+ /// `PART_NxN`?
478+ nxn: bool,
479+ /// PB modes (1 used for 2Nx2N, 4 for NxN, z-order).
480+ modes: [u8; 4],
481+ /// TB level arrays (1 x 16x16 or 4 x 8x8, z-order).
482+ levels: Vec<Vec<i32>>,
483+ /// The CTB's 16x16 luma reconstruction, row-major.
484+ recon: Vec<u8>,
485+}
486+
487+/// One CTB's pass-1 coding decisions (pass 2 emits the syntax after
488+/// the in-loop filter elections are known).
489+struct CtbPlan {
490+ /// The elected luma partition + levels.
491+ plan: LumaPlan,
492+ /// Chroma Cb TB levels (1 x 8x8 or 4 x 4x4, z-order).
493+ cb_levels: Vec<Vec<i32>>,
494+ /// Chroma Cr TB levels.
495+ cr_levels: Vec<Vec<i32>>,
496+}
497+
498+/// Encode one 4:2:0 8-bit frame as a self-contained intra IDR access
499+/// unit at `SliceQpY == qp` and return it with the reconstruction a
500+/// conforming decoder produces.
501+///
502+/// # Errors
503+/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP.
504+#[allow(clippy::too_many_lines)]
505+pub fn encode_idr_intra_au(
506+ y: &[u8],
507+ cb: &[u8],
508+ cr: &[u8],
509+ width: usize,
510+ height: usize,
511+ qp: i32,
512+) -> Result<IntraEncodedAu, IntraEncodeError> {
513+ // A standalone intra AU needs one reference slot beyond the
514+ // current picture (`sps_max_dec_pic_buffering_minus1 == 1`).
515+ encode_idr_intra_au_cfg(y, cb, cr, width, height, qp, 1)
516+}
517+
518+// --- edith patch ---
519+/// [`encode_idr_intra_au`] for a picture whose display size is not a
520+/// multiple of the 16-sample CTB: the planes handed over are the
521+/// **padded** ones (`width`/`height`, both multiples of 16) and the SPS
522+/// carries a §7.4.3.2.1 conformance window cropping `crop_right` /
523+/// `crop_bottom` **luma** samples off, so a decoder outputs the display
524+/// size. Both crops must be even (4:2:0 addresses the window in chroma
525+/// units) and smaller than 16.
526+///
527+/// # Errors
528+/// [`IntraEncodeError`] as [`encode_idr_intra_au`], plus
529+/// [`IntraEncodeError::BadDimensions`] for an odd or oversized crop.
530+pub fn encode_idr_intra_au_cropped(
531+ y: &[u8],
532+ cb: &[u8],
533+ cr: &[u8],
534+ width: usize,
535+ height: usize,
536+ qp: i32,
537+ crop_right: usize,
538+ crop_bottom: usize,
539+) -> Result<IntraEncodedAu, IntraEncodeError> {
540+ if crop_right % 2 != 0 || crop_bottom % 2 != 0 || crop_right >= CTB || crop_bottom >= CTB {
541+ return Err(IntraEncodeError::BadDimensions {
542+ width: width - crop_right,
543+ height: height - crop_bottom,
544+ });
545+ }
546+ let mut cfg = SpsCfg::legacy(1);
547+ cfg.conf_win = ((crop_right / 2) as u32, (crop_bottom / 2) as u32);
548+ encode_idr_intra_au_full(y, cb, cr, width, height, qp, &cfg, &LoopFilterCfg::off())
549+}
550+// --- end edith patch ---
551+
552+/// [`encode_idr_intra_au`] with the §8.7 in-loop filters enabled per
553+/// `lf`: the reconstruction runs through the crate's decode-side
554+/// deblocking (per-slice on/off elected against distortion) and SAO
555+/// (per-CTB §7.3.8.3 parameters from statistics-driven offset
556+/// estimation), and the returned `recon_*` planes are the *filtered*
557+/// picture — still exactly what a conforming decoder outputs.
558+///
559+/// # Errors
560+/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP.
561+pub fn encode_idr_intra_au_lf(
562+ y: &[u8],
563+ cb: &[u8],
564+ cr: &[u8],
565+ width: usize,
566+ height: usize,
567+ qp: i32,
568+ lf: &LoopFilterCfg,
569+) -> Result<IntraEncodedAu, IntraEncodeError> {
570+ encode_idr_intra_au_full(y, cb, cr, width, height, qp, &SpsCfg::legacy(1), lf)
571+}
572+
573+/// [`encode_idr_intra_au`] with an explicit
574+/// `sps_max_dec_pic_buffering_minus1` — the low-delay GOP encoder
575+/// passes 2 so a conforming decoder keeps BOTH short-term references
576+/// alive alongside the current picture.
577+pub(crate) fn encode_idr_intra_au_cfg(
578+ y: &[u8],
579+ cb: &[u8],
580+ cr: &[u8],
581+ width: usize,
582+ height: usize,
583+ qp: i32,
584+ max_dec_pic_buffering_minus1: u32,
585+) -> Result<IntraEncodedAu, IntraEncodeError> {
586+ encode_idr_intra_au_full(
587+ y,
588+ cb,
589+ cr,
590+ width,
591+ height,
592+ qp,
593+ &SpsCfg::legacy(max_dec_pic_buffering_minus1),
594+ &LoopFilterCfg::off(),
595+ )
596+}
597+
598+/// The full-configuration intra encode: two passes (per-CTB mode
599+/// decision + reconstruction, then syntax emission) around the §8.7
600+/// in-loop filter stage, so the per-CTB §7.3.8.3 SAO parameters and
601+/// the slice-header filter elections are known before the slice is
602+/// written.
603+#[allow(clippy::too_many_lines, clippy::too_many_arguments)]
604+pub(crate) fn encode_idr_intra_au_full(
605+ y: &[u8],
606+ cb: &[u8],
607+ cr: &[u8],
608+ width: usize,
609+ height: usize,
610+ qp: i32,
611+ cfg: &SpsCfg,
612+ lf: &LoopFilterCfg,
613+) -> Result<IntraEncodedAu, IntraEncodeError> {
614+ if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 {
615+ return Err(IntraEncodeError::BadDimensions { width, height });
616+ }
617+ if !(0..=51).contains(&qp) {
618+ return Err(IntraEncodeError::BadQp(qp));
619+ }
620+ let check = |plane: &'static str, buf: &[u8], expected: usize| {
621+ if buf.len() != expected {
622+ Err(IntraEncodeError::PlaneSize {
623+ plane,
624+ expected,
625+ got: buf.len(),
626+ })
627+ } else {
628+ Ok(())
629+ }
630+ };
631+ check("y", y, width * height)?;
632+ check("cb", cb, width * height / 4)?;
633+ check("cr", cr, width * height / 4)?;
634+
635+ let (cw, ch) = (width / 2, height / 2);
636+ let ctbs_x = width / CTB;
637+ let ctbs_y = height / CTB;
638+ let qp_y = qp as u32;
639+ let qp_c = chroma_qp_420(qp);
640+ // Rate-distortion tradeoff for the partition decision: SSD per
641+ // estimated bit, doubling every 3 QP (integer, deterministic).
642+ let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3);
643+
644+ let mut recon_y = vec![0u8; width * height];
645+ let mut recon_cb = vec![0u8; cw * ch];
646+ let mut recon_cr = vec![0u8; cw * ch];
647+ let mut modes = IntraModeField::new(width, height, CTB_LOG2);
648+ let mut plans: Vec<CtbPlan> = Vec::with_capacity(ctbs_x * ctbs_y);
649+
650+ let extract = |plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize| -> Vec<i32> {
651+ let mut out = Vec::with_capacity(n * n);
652+ for j in 0..n {
653+ for i in 0..n {
654+ out.push(i32::from(plane[(y0 + j) * pw + x0 + i]));
655+ }
656+ }
657+ out
658+ };
659+ let store = |plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]| {
660+ for j in 0..n {
661+ plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n]
662+ .copy_from_slice(&s[j * n..(j + 1) * n]);
663+ }
664+ };
665+
666+ for ctb in 0..ctbs_x * ctbs_y {
667+ let x0 = (ctb % ctbs_x) * CTB;
668+ let y0 = (ctb / ctbs_x) * CTB;
669+ let src16 = extract(y, width, x0, y0, CTB);
670+
671+ // ---- candidate PART_2Nx2N: one 16x16 PB/TB ----
672+ let plan_2n = {
673+ let read = |x: usize, yy: usize| i32::from(recon_y[yy * width + x]);
674+ let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0);
675+ let marked = gather_refs(&read, &avail, x0, y0, CTB);
676+ let (mode, pred) = search_best_mode(&marked, &src16);
677+ let (levels, recon) =
678+ code_tb(&src16, &pred, CTB, qp_y, Component::Luma, PredMode::Intra);
679+ LumaPlan {
680+ nxn: false,
681+ modes: [mode; 4],
682+ levels: vec![levels],
683+ recon,
684+ }
685+ };
686+
687+ // ---- candidate PART_NxN: four 8x8 PBs/TBs, z-order ----
688+ // Only at the legacy MinCb geometry: at `log2CbSize >
689+ // MinCbLog2SizeY` an intra CU's `part_mode` is not present
690+ // (§7.3.8.5), so PART_NxN cannot be signalled.
691+ let plan_nxn = if cfg.min_cb_log2 < CTB_LOG2 {
692+ None
693+ } else {
694+ let mut scratch = vec![0u8; CTB * CTB]; // in-progress CTB recon
695+ let mut pb_modes = [0u8; 4];
696+ let mut pb_levels: Vec<Vec<i32>> = Vec::with_capacity(4);
697+ for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
698+ let (px, py) = (x0 + zx * 8, y0 + zy * 8);
699+ let read = |x: usize, yy: usize| -> i32 {
700+ if (x0..x0 + CTB).contains(&x) && (y0..y0 + CTB).contains(&yy) {
701+ i32::from(scratch[(yy - y0) * CTB + (x - x0)])
702+ } else {
703+ i32::from(recon_y[yy * width + x])
704+ }
705+ };
706+ let avail = |nx: i64, ny: i64| {
707+ zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, k as u32)
708+ };
709+ let marked = gather_refs(&read, &avail, px, py, 8);
710+ let src8 = extract(y, width, px, py, 8);
711+ let (mode, pred) = search_best_mode(&marked, &src8);
712+ let (levels, recon8) =
713+ code_tb(&src8, &pred, 8, qp_y, Component::Luma, PredMode::Intra);
714+ for j in 0..8 {
715+ scratch[(zy * 8 + j) * CTB + zx * 8..(zy * 8 + j) * CTB + zx * 8 + 8]
716+ .copy_from_slice(&recon8[j * 8..(j + 1) * 8]);
717+ }
718+ pb_modes[k] = mode;
719+ pb_levels.push(levels);
720+ }
721+ Some(LumaPlan {
722+ nxn: true,
723+ modes: pb_modes,
724+ levels: pb_levels,
725+ recon: scratch,
726+ })
727+ };
728+
729+ // Luma-only rate-distortion comparison: SSD of the coded
730+ // reconstruction + lambda times a bit proxy (residual levels +
731+ // mode signalling: ~6 bits per PB).
732+ let cost = |plan: &LumaPlan| -> u64 {
733+ let rate: u64 = plan.levels.iter().map(|lv| rate_proxy(lv)).sum::<u64>()
734+ + plan.levels.len() as u64 * 6;
735+ ssd(&plan.recon, &src16) + lambda * rate
736+ };
737+ let plan = match plan_nxn {
738+ Some(nxn) if cost(&nxn) < cost(&plan_2n) => nxn,
739+ _ => plan_2n,
740+ };
741+ store(&mut recon_y, width, x0, y0, CTB, &plan.recon);
742+ // §8.4.3: IntraPredModeC derives from the CU's first PB.
743+ let mode_c = plan.modes[0];
744+
745+ // ---- chroma: 8x8 TBs (2Nx2N) or four 4x4 TBs (NxN) ----
746+ let (cx0, cy0) = (x0 / 2, y0 / 2);
747+ let code_chroma = |plane: &[u8],
748+ recon: &mut Vec<u8>,
749+ comp: Component,
750+ pc: PredComponent|
751+ -> Vec<Vec<i32>> {
752+ if !plan.nxn {
753+ let read = |x: usize, yy: usize| i32::from(recon[yy * cw + x]);
754+ let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0);
755+ let marked = gather_refs(&read, &avail, cx0, cy0, 8);
756+ let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc))
757+ .expect("legal prediction params");
758+ let src = extract(plane, cw, cx0, cy0, 8);
759+ let (levels, rec) = code_tb(&src, &pred, 8, qp_c, comp, PredMode::Intra);
760+ store(recon, cw, cx0, cy0, 8, &rec);
761+ vec![levels]
762+ } else {
763+ let mut out = Vec::with_capacity(4);
764+ let mut scratch = vec![0u8; 64]; // 8x8 chroma CTB recon
765+ for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() {
766+ let (px, py) = (cx0 + zx * 4, cy0 + zy * 4);
767+ let read = |x: usize, yy: usize| -> i32 {
768+ if (cx0..cx0 + 8).contains(&x) && (cy0..cy0 + 8).contains(&yy) {
769+ i32::from(scratch[(yy - cy0) * 8 + (x - cx0)])
770+ } else {
771+ i32::from(recon[yy * cw + x])
772+ }
773+ };
774+ let avail = |nx: i64, ny: i64| {
775+ zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, k as u32)
776+ };
777+ let marked = gather_refs(&read, &avail, px, py, 4);
778+ let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc))
779+ .expect("legal prediction params");
780+ let src = extract(plane, cw, px, py, 4);
781+ let (levels, rec) = code_tb(&src, &pred, 4, qp_c, comp, PredMode::Intra);
782+ for j in 0..4 {
783+ scratch[(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4]
784+ .copy_from_slice(&rec[j * 4..(j + 1) * 4]);
785+ }
786+ out.push(levels);
787+ }
788+ store(recon, cw, cx0, cy0, 8, &scratch);
789+ out
790+ }
791+ };
792+ let cb_levels = code_chroma(cb, &mut recon_cb, Component::Cb, PredComponent::Cb);
793+ let cr_levels = code_chroma(cr, &mut recon_cr, Component::Cr, PredComponent::Cr);
794+
795+ plans.push(CtbPlan {
796+ plan,
797+ cb_levels,
798+ cr_levels,
799+ });
800+ }
801+
802+ // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ----
803+ let mut deblock_on = false;
804+ let mut beta_offset_div2 = 0i32;
805+ let mut tc_offset_div2 = 0i32;
806+ let mut slice_sao_luma = false;
807+ let mut slice_sao_chroma = false;
808+ let mut sao_ctbs: Vec<SaoCtbParams> = Vec::new();
809+ if lf.any() {
810+ let shapes: Vec<CtbShape> = plans
811+ .iter()
812+ .map(|p| CtbShape {
813+ part_mode: if p.plan.nxn {
814+ PartMode::PartNxN
815+ } else {
816+ PartMode::Part2Nx2N
817+ },
818+ split_depth1: p.plan.nxn,
819+ })
820+ .collect();
821+ // Every CU is intra: the fresh motion field's all-intra
822+ // background is exactly the decoder's state (bS == 2 at every
823+ // filtered edge).
824+ let field = MotionField::new(width, height);
825+ let out = filter_frame(
826+ &FilterInput {
827+ width,
828+ height,
829+ qp,
830+ lambda,
831+ recon: [&recon_y, &recon_cb, &recon_cr],
832+ src: [y, cb, cr],
833+ field: &field,
834+ shapes: &shapes,
835+ },
836+ lf,
837+ );
838+ deblock_on = out.deblock_on;
839+ beta_offset_div2 = out.beta_offset_div2;
840+ tc_offset_div2 = out.tc_offset_div2;
841+ slice_sao_luma = out.slice_sao_luma;
842+ slice_sao_chroma = out.slice_sao_chroma;
843+ sao_ctbs = out.sao_ctbs;
844+ recon_y = out.y;
845+ recon_cb = out.cb;
846+ recon_cr = out.cr;
847+ }
848+
849+ // ---- slice_segment_header( ) ----
850+ let mut w = BitWriter::new();
851+ w.put_bit(1); // first_slice_segment_in_pic_flag
852+ w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL)
853+ w.ue(0); // slice_pic_parameter_set_id
854+ w.ue(2); // slice_type = I
855+ if lf.sao() {
856+ // SPS SAO enabled: the per-slice component gates are present.
857+ w.put_bit(u8::from(slice_sao_luma)); // slice_sao_luma_flag
858+ w.put_bit(u8::from(slice_sao_chroma)); // slice_sao_chroma_flag
859+ }
860+ w.se(qp - 26); // slice_qp_delta (init_qp_minus26 == 0)
861+ if lf.deblocking {
862+ // §7.3.6.1 deblocking override group (the PPS signals
863+ // override-enabled + deblocking disabled; an electing slice
864+ // overrides to enabled with zero β/tC offsets).
865+ w.put_bit(u8::from(deblock_on)); // deblocking_filter_override_flag
866+ if deblock_on {
867+ w.put_bit(0); // slice_deblocking_filter_disabled_flag
868+ w.se(beta_offset_div2); // slice_beta_offset_div2
869+ w.se(tc_offset_div2); // slice_tc_offset_div2
870+ }
871+ }
872+ if slice_sao_luma || slice_sao_chroma || deblock_on {
873+ // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and
874+ // some in-loop filter is active for this slice.
875+ w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag
876+ }
877+ w.rbsp_trailing_bits(); // byte_alignment()
878+
879+ // ---- slice_segment_data( ) — pass 2: syntax emission ----
880+ let mut cabac = CabacEncoder::new();
881+ // Table 9-4: I slice => initType 0 (raw slice_type 2).
882+ let mut ctxs = SliceContexts::init(init_type(2, false), qp);
883+ for (ctb, ctb_plan) in plans.iter().enumerate() {
884+ let x0 = (ctb % ctbs_x) * CTB;
885+ let y0 = (ctb / ctbs_x) * CTB;
886+ if slice_sao_luma || slice_sao_chroma {
887+ // §7.3.8.3 sao( rx, ry ) ahead of the coding quadtree.
888+ encode_sao_ctb(
889+ &mut w,
890+ &mut cabac,
891+ &mut ctxs,
892+ &sao_ctbs[ctb],
893+ ctb % ctbs_x,
894+ ctb / ctbs_x,
895+ slice_sao_luma,
896+ slice_sao_chroma,
897+ );
898+ }
899+ let plan = &ctb_plan.plan;
900+ let cb_levels = &ctb_plan.cb_levels;
901+ let cr_levels = &ctb_plan.cr_levels;
902+ // §8.4.3: IntraPredModeC derives from the CU's first PB.
903+ let mode_c = plan.modes[0];
904+
905+ // ---- §7.3.8.5 coding_unit( ) syntax ----
906+ if cfg.min_cb_log2 < CTB_LOG2 {
907+ // §7.3.8.4: log2CbSize (4) > MinCbLog2SizeY — split_cu_flag
908+ // is coded, and every CTB stays one UNSPLIT 16x16 CU. All
909+ // CtDepth values are 0, so both §9.3.4.2.2 conds are 0 and
910+ // the ctxInc is 0. part_mode is then NOT present for an
911+ // intra CU at log2CbSize > MinCbLog2SizeY (§7.3.8.5;
912+ // inferred PART_2Nx2N).
913+ cabac.encode_decision(&mut w, &mut ctxs.split_cu_flag[0], 0);
914+ debug_assert!(!plan.nxn, "PART_NxN cannot be signalled above MinCb");
915+ } else {
916+ // part_mode: §9.3.3.7 intra at MinCb — "1" = PART_2Nx2N,
917+ // "0" = PART_NxN.
918+ cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], u8::from(!plan.nxn));
919+ }
920+ // §7.3.8.5 two-loop luma mode group: all
921+ // prev_intra_luma_pred_flag bins first, then the mpm_idx /
922+ // rem_intra_luma_pred_mode group. The §8.4.2 candidate list of
923+ // PB k sees the recorded modes of PBs < k, so record as we go
924+ // through the SECOND loop (derivation order).
925+ let n_pb = if plan.nxn { 4 } else { 1 };
926+ let pb_size = if plan.nxn { 8 } else { CTB };
927+ let pb_pos = |k: usize| (x0 + Z_OFFSETS[k].0 * 8, y0 + Z_OFFSETS[k].1 * 8);
928+ let mut selections: Vec<Option<usize>> = Vec::with_capacity(n_pb);
929+ {
930+ // The candidate list depends only on ALREADY-decoded PBs,
931+ // which are identical in both loop passes; precompute the
932+ // per-PB MPM position by simulating the record order.
933+ for k in 0..n_pb {
934+ let (px, py) = pb_pos(k);
935+ let avail_l = zscan_avail(
936+ px as i64 - 1,
937+ py as i64,
938+ width,
939+ height,
940+ CTB,
941+ ctbs_x,
942+ ctb,
943+ k as u32,
944+ );
945+ let avail_a = zscan_avail(
946+ px as i64,
947+ py as i64 - 1,
948+ width,
949+ height,
950+ CTB,
951+ ctbs_x,
952+ ctb,
953+ k as u32,
954+ );
955+ let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l);
956+ let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a);
957+ let list = intra_luma_cand_mode_list(cand_a, cand_b);
958+ selections.push(list.iter().position(|&m| m == plan.modes[k]));
959+ // Loop 1: prev_intra_luma_pred_flag[k].
960+ cabac.encode_decision(
961+ &mut w,
962+ &mut ctxs.prev_intra_luma_pred_flag[0],
963+ u8::from(selections[k].is_some()),
964+ );
965+ // Record now: the next PB's candidates must see this
966+ // one (§8.4.2 derivation order).
967+ modes.record_intra_pb(px, py, pb_size, plan.modes[k], false);
968+ }
969+ // Loop 2: mpm_idx / rem_intra_luma_pred_mode.
970+ for (k, sel) in selections.iter().enumerate() {
971+ match *sel {
972+ Some(0) => cabac.encode_bypass(&mut w, 0),
973+ Some(1) => {
974+ cabac.encode_bypass(&mut w, 1);
975+ cabac.encode_bypass(&mut w, 0);
976+ }
977+ Some(_) => {
978+ cabac.encode_bypass(&mut w, 1);
979+ cabac.encode_bypass(&mut w, 1);
980+ }
981+ None => {
982+ // §8.4.2: rem = mode with each smaller
983+ // candidate removed. Recompute the list the
984+ // same way the decoder will (earlier PBs
985+ // recorded).
986+ let (px, py) = pb_pos(k);
987+ let avail_l = zscan_avail(
988+ px as i64 - 1,
989+ py as i64,
990+ width,
991+ height,
992+ CTB,
993+ ctbs_x,
994+ ctb,
995+ k as u32,
996+ );
997+ let avail_a = zscan_avail(
998+ px as i64,
999+ py as i64 - 1,
1000+ width,
1001+ height,
1002+ CTB,
1003+ ctbs_x,
1004+ ctb,
1005+ k as u32,
1006+ );
1007+ let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l);
1008+ let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a);
1009+ let list = intra_luma_cand_mode_list(cand_a, cand_b);
1010+ let mut rem = u32::from(plan.modes[k]);
1011+ for &c in &list {
1012+ if u32::from(plan.modes[k]) > u32::from(c) {
1013+ rem -= 1;
1014+ }
1015+ }
1016+ cabac.encode_bypass_bits(&mut w, rem, 5); // FL cMax 31
1017+ }
1018+ }
1019+ }
1020+ }
1021+ // intra_chroma_pred_mode = 4 (derived from luma): bin "0".
1022+ cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0);
1023+
1024+ // ---- §7.3.8.8 transform_tree + §7.3.8.10 transform_unit ----
1025+ let rc_params = |log2: u32, is_chroma: bool, mode: u8| ResidualCodingParams {
1026+ log2_trafo_size: log2,
1027+ is_chroma,
1028+ // §7.4.9.11 mode-dependent scan (only 4x4 / 8x8-luma TBs
1029+ // are eligible; larger TBs come back Diagonal).
1030+ scan_idx: residual_coding_scan_idx(true, log2, u8::from(is_chroma), 1, u32::from(mode)),
1031+ sign_data_hiding_enabled_flag: false,
1032+ sign_hidden_suppressed: false,
1033+ transform_skip_sig_ctx: false,
1034+ persistent_rice_adaptation_enabled_flag: false,
1035+ cabac_bypass_alignment_enabled_flag: false,
1036+ extended_precision_processing_flag: false,
1037+ bit_depth: 8,
1038+ rice_stat_transform_skip: false,
1039+ };
1040+ if !plan.nxn {
1041+ // Single 16x16 TU at depth 0.
1042+ let cbf_cb = cb_levels[0].iter().any(|&v| v != 0);
1043+ let cbf_cr = cr_levels[0].iter().any(|&v| v != 0);
1044+ let cbf_luma = plan.levels[0].iter().any(|&v| v != 0);
1045+ cabac.encode_decision(
1046+ &mut w,
1047+ &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
1048+ u8::from(cbf_cb),
1049+ );
1050+ cabac.encode_decision(
1051+ &mut w,
1052+ &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
1053+ u8::from(cbf_cr),
1054+ );
1055+ cabac.encode_decision(
1056+ &mut w,
1057+ &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize],
1058+ u8::from(cbf_luma),
1059+ );
1060+ if cbf_luma {
1061+ encode_residual_coding(
1062+ &mut w,
1063+ &mut cabac,
1064+ &mut ctxs.residual,
1065+ &rc_params(4, false, plan.modes[0]),
1066+ &plan.levels[0],
1067+ )
1068+ .expect("validated luma levels");
1069+ }
1070+ if cbf_cb {
1071+ encode_residual_coding(
1072+ &mut w,
1073+ &mut cabac,
1074+ &mut ctxs.residual,
1075+ &rc_params(3, true, mode_c),
1076+ &cb_levels[0],
1077+ )
1078+ .expect("validated cb levels");
1079+ }
1080+ if cbf_cr {
1081+ encode_residual_coding(
1082+ &mut w,
1083+ &mut cabac,
1084+ &mut ctxs.residual,
1085+ &rc_params(3, true, mode_c),
1086+ &cr_levels[0],
1087+ )
1088+ .expect("validated cr levels");
1089+ }
1090+ } else {
1091+ // IntraSplitFlag == 1: split_transform_flag inferred 1 at
1092+ // depth 0 (§7.4.9.8); four 8x8 leaves at depth 1. Root
1093+ // cbf_cb / cbf_cr gate the per-leaf chroma flags
1094+ // (§7.3.8.8 inheritance).
1095+ let leaf_cbf = |lv: &Vec<i32>| lv.iter().any(|&v| v != 0);
1096+ let root_cb = cb_levels.iter().any(&leaf_cbf);
1097+ let root_cr = cr_levels.iter().any(&leaf_cbf);
1098+ cabac.encode_decision(
1099+ &mut w,
1100+ &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize],
1101+ u8::from(root_cb),
1102+ );
1103+ cabac.encode_decision(
1104+ &mut w,
1105+ &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize],
1106+ u8::from(root_cr),
1107+ );
1108+ for k in 0..4 {
1109+ let cbf_cb_k = leaf_cbf(&cb_levels[k]);
1110+ let cbf_cr_k = leaf_cbf(&cr_levels[k]);
1111+ let cbf_luma_k = leaf_cbf(&plan.levels[k]);
1112+ if root_cb {
1113+ cabac.encode_decision(
1114+ &mut w,
1115+ &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(1) as usize],
1116+ u8::from(cbf_cb_k),
1117+ );
1118+ }
1119+ if root_cr {
1120+ cabac.encode_decision(
1121+ &mut w,
1122+ &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(1) as usize],
1123+ u8::from(cbf_cr_k),
1124+ );
1125+ }
1126+ cabac.encode_decision(
1127+ &mut w,
1128+ &mut ctxs.cbf_luma[cbf_luma_ctx_inc(1) as usize],
1129+ u8::from(cbf_luma_k),
1130+ );
1131+ if cbf_luma_k {
1132+ encode_residual_coding(
1133+ &mut w,
1134+ &mut cabac,
1135+ &mut ctxs.residual,
1136+ &rc_params(3, false, plan.modes[k]),
1137+ &plan.levels[k],
1138+ )
1139+ .expect("validated luma levels");
1140+ }
1141+ if root_cb && cbf_cb_k {
1142+ encode_residual_coding(
1143+ &mut w,
1144+ &mut cabac,
1145+ &mut ctxs.residual,
1146+ &rc_params(2, true, mode_c),
1147+ &cb_levels[k],
1148+ )
1149+ .expect("validated cb levels");
1150+ }
1151+ if root_cr && cbf_cr_k {
1152+ encode_residual_coding(
1153+ &mut w,
1154+ &mut cabac,
1155+ &mut ctxs.residual,
1156+ &rc_params(2, true, mode_c),
1157+ &cr_levels[k],
1158+ )
1159+ .expect("validated cr levels");
1160+ }
1161+ }
1162+ }
1163+
1164+ // end_of_slice_segment_flag.
1165+ cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1));
1166+ }
1167+ // The final terminate-1 flush wrote the rbsp_stop_one_bit;
1168+ // rbsp_slice_segment_trailing_bits() is alignment zeros from here.
1169+ w.align_zero();
1170+ let slice_rbsp = w.finish();
1171+
1172+ let level_idc = level_idc_for(width * height);
1173+ // The reorder-free streams keep the historical VPS bounds (1, 0)
1174+ // so every golden pin stays byte-stable; a reordering
1175+ // (hierarchical-B) stream signals its honest DPB bounds.
1176+ let vps = if cfg.max_num_reorder_pics == 0 {
1177+ write_vps(level_idc)
1178+ } else {
1179+ write_vps_cfg(
1180+ level_idc,
1181+ cfg.max_dec_pic_buffering_minus1,
1182+ cfg.max_num_reorder_pics,
1183+ )
1184+ };
1185+ let units = vec![
1186+ nal_unit(32, 0, 0, &vps), // VPS_NUT
1187+ nal_unit(
1188+ 33,
1189+ 0,
1190+ 0,
1191+ &write_sps_cfg(width, height, level_idc, cfg, lf.sao()),
1192+ ), // SPS_NUT
1193+ nal_unit(34, 0, 0, &write_pps_lf(false, false, lf.deblocking, None)), // PPS_NUT
1194+ nal_unit(20, 0, 0, &slice_rbsp), // IDR_N_LP
1195+ ];
1196+ Ok(IntraEncodedAu {
1197+ au: annexb(&units),
1198+ recon_y,
1199+ recon_cb,
1200+ recon_cr,
1201+ })
1202+}
1203+
1204+#[cfg(test)]
1205+mod tests {
1206+ use super::*;
1207+ use crate::binarization::PartMode;
1208+ use crate::sequence::{decode_annexb_sequence, decode_annexb_sequence_debug};
1209+ use crate::slice_data::CodingQuadtree;
1210+
1211+ /// Deterministic test content: smooth gradients + a diagonal
1212+ /// texture component so directional modes and residuals both work.
1213+ fn planes(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1214+ let y: Vec<u8> = (0..w * h)
1215+ .map(|i| {
1216+ let (x, yy) = (i % w, i / w);
1217+ ((x * 3 + yy * 2 + (x * yy / 7) % 31) % 256) as u8
1218+ })
1219+ .collect();
1220+ let cb: Vec<u8> = (0..w * h / 4)
1221+ .map(|i| ((i % (w / 2)) * 4 % 200 + 20) as u8)
1222+ .collect();
1223+ let cr: Vec<u8> = (0..w * h / 4)
1224+ .map(|i| (240 - (i / (w / 2)) * 3 % 200) as u8)
1225+ .collect();
1226+ (y, cb, cr)
1227+ }
1228+
1229+ /// Content with per-8x8 alternating strong directions: drives the
1230+ /// partition decision toward PART_NxN.
1231+ fn blocky_planes(w: usize, h: usize) -> (Vec<u8>, Vec<u8>, Vec<u8>) {
1232+ let y: Vec<u8> = (0..w * h)
1233+ .map(|i| {
1234+ let (x, yy) = (i % w, i / w);
1235+ let (bx, by) = (x / 8, yy / 8);
1236+ match (bx + by) % 3 {
1237+ 0 => ((x % 8) * 30) as u8,
1238+ 1 => ((yy % 8) * 30) as u8,
1239+ _ => (((x + yy) % 16) * 15) as u8,
1240+ }
1241+ })
1242+ .collect();
1243+ let cb = vec![100u8; w * h / 4];
1244+ let cr = vec![160u8; w * h / 4];
1245+ (y, cb, cr)
1246+ }
1247+
1248+ fn psnr(a: &[u8], b: &[u8]) -> f64 {
1249+ let mse: f64 = a
1250+ .iter()
1251+ .zip(b.iter())
1252+ .map(|(&x, &y)| {
1253+ let d = f64::from(x) - f64::from(y);
1254+ d * d
1255+ })
1256+ .sum::<f64>()
1257+ / a.len() as f64;
1258+ if mse == 0.0 {
1259+ f64::INFINITY
1260+ } else {
1261+ 10.0 * (255.0f64 * 255.0 / mse).log10()
1262+ }
1263+ }
1264+
1265+ fn assert_roundtrip_exact(y: &[u8], cb: &[u8], cr: &[u8], w: usize, h: usize, qp: i32) {
1266+ let enc = encode_idr_intra_au(y, cb, cr, w, h, qp).expect("encode");
1267+ let frames = decode_annexb_sequence(&enc.au).expect("decode");
1268+ assert_eq!(frames.len(), 1, "{w}x{h} qp{qp}");
1269+ let mut recon = Vec::new();
1270+ recon.extend_from_slice(&enc.recon_y);
1271+ recon.extend_from_slice(&enc.recon_cb);
1272+ recon.extend_from_slice(&enc.recon_cr);
1273+ assert_eq!(
1274+ frames[0].picture.to_planar_u8().expect("8-bit"),
1275+ recon,
1276+ "{w}x{h} qp{qp}: decoder output == encoder reconstruction"
1277+ );
1278+ }
1279+
1280+ /// The core contract: the crate's own decoder reproduces the
1281+ /// encoder's reconstruction EXACTLY (dual-decoder bit-exactness),
1282+ /// on both smooth and NxN-inducing content.
1283+ #[test]
1284+ fn intra_au_decodes_to_encoder_recon_exactly() {
1285+ for (w, h) in [(16usize, 16usize), (64, 48), (48, 80)] {
1286+ let (y, cb, cr) = planes(w, h);
1287+ for qp in [4i32, 22, 32, 45] {
1288+ assert_roundtrip_exact(&y, &cb, &cr, w, h, qp);
1289+ }
1290+ let (y, cb, cr) = blocky_planes(w, h);
1291+ for qp in [10i32, 27, 38] {
1292+ assert_roundtrip_exact(&y, &cb, &cr, w, h, qp);
1293+ }
1294+ }
1295+ }
1296+
1297+ /// The partition decision really selects PART_NxN on content with
1298+ /// per-8x8 directional structure (and the stream decodes exactly).
1299+ #[test]
1300+ fn nxn_partition_is_selected_and_decodes() {
1301+ let (w, h) = (64usize, 64usize);
1302+ let (y, cb, cr) = blocky_planes(w, h);
1303+ let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 27).expect("encode");
1304+ let ctus = decode_annexb_sequence_debug(&enc.au).expect("walk");
1305+ let mut nxn = 0usize;
1306+ let mut two_n = 0usize;
1307+ for (_, _, ctu) in &ctus {
1308+ if let CodingQuadtree::Leaf(cu) = &ctu.quadtree {
1309+ match cu.part_mode {
1310+ PartMode::PartNxN => nxn += 1,
1311+ PartMode::Part2Nx2N => two_n += 1,
1312+ other => panic!("unexpected part mode {other:?}"),
1313+ }
1314+ }
1315+ }
1316+ assert!(nxn > 0, "no PART_NxN CU selected ({two_n} 2Nx2N)");
1317+ }
1318+
1319+ /// Rate/distortion sanity: low QP is near-transparent, and
1320+ /// quality degrades monotonically-ish while staying decodable.
1321+ #[test]
1322+ fn intra_quality_tracks_qp() {
1323+ let (w, h) = (64usize, 64usize);
1324+ let (y, cb, cr) = planes(w, h);
1325+ let at = |qp: i32| {
1326+ let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("encode");
1327+ (psnr(&enc.recon_y, &y), enc.au.len())
1328+ };
1329+ let (p4, s4) = at(4);
1330+ let (p22, s22) = at(22);
1331+ let (p40, s40) = at(40);
1332+ assert!(p4 > 45.0, "qp4 luma PSNR {p4:.1} dB");
1333+ assert!(p22 > 33.0, "qp22 luma PSNR {p22:.1} dB");
1334+ assert!(p40 > 22.0, "qp40 luma PSNR {p40:.1} dB");
1335+ assert!(p4 > p22 && p22 > p40, "PSNR decreases with QP");
1336+ assert!(
1337+ s4 > s22 && s22 > s40,
1338+ "bytes decrease with QP ({s4} > {s22} > {s40})"
1339+ );
1340+ }
1341+
1342+ /// QP 22 on this content should be visually transparent while far
1343+ /// smaller than the PCM (raw) coding — i.e. the transform path
1344+ /// actually compresses.
1345+ #[test]
1346+ fn intra_beats_pcm_size_at_high_quality() {
1347+ let (w, h) = (64usize, 64usize);
1348+ let (y, cb, cr) = planes(w, h);
1349+ let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 22).expect("encode");
1350+ let raw = w * h * 3 / 2;
1351+ assert!(
1352+ enc.au.len() < raw / 2,
1353+ "compressed {} bytes vs raw {raw}",
1354+ enc.au.len()
1355+ );
1356+ }
1357+
1358+ #[test]
1359+ fn rejects_bad_inputs() {
1360+ let (y, cb, cr) = planes(16, 16);
1361+ assert!(matches!(
1362+ encode_idr_intra_au(&y, &cb, &cr, 20, 16, 26),
1363+ Err(IntraEncodeError::BadDimensions { .. })
1364+ ));
1365+ assert!(matches!(
1366+ encode_idr_intra_au(&y, &cb, &cr, 16, 16, 52),
1367+ Err(IntraEncodeError::BadQp(52))
1368+ ));
1369+ assert!(matches!(
1370+ encode_idr_intra_au(&y, &cb, &cr, 32, 16, 26),
1371+ Err(IntraEncodeError::PlaneSize { .. })
1372+ ));
1373+ }
1374+
1375+ /// Filtered intra AUs (§8.7.2 deblocking / §8.7.3 SAO, alone and
1376+ /// combined) decode bit-exactly to the encoder's filtered
1377+ /// reconstruction through the crate's own decoder, across
1378+ /// geometries and QPs.
1379+ #[test]
1380+ fn filtered_intra_au_decodes_to_encoder_recon_exactly() {
1381+ let cfgs = [
1382+ LoopFilterCfg {
1383+ deblocking: true,
1384+ sao_luma: false,
1385+ sao_chroma: false,
1386+ },
1387+ LoopFilterCfg {
1388+ deblocking: false,
1389+ sao_luma: true,
1390+ sao_chroma: true,
1391+ },
1392+ LoopFilterCfg {
1393+ deblocking: false,
1394+ sao_luma: true,
1395+ sao_chroma: false,
1396+ },
1397+ LoopFilterCfg::all(),
1398+ ];
1399+ for (w, h) in [(32usize, 32usize), (64, 48)] {
1400+ for planes_fn in [planes, blocky_planes] {
1401+ let (y, cb, cr) = planes_fn(w, h);
1402+ for qp in [27i32, 38] {
1403+ for cfg in &cfgs {
1404+ let enc =
1405+ encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, cfg).expect("encode");
1406+ let frames = decode_annexb_sequence(&enc.au).expect("decode");
1407+ assert_eq!(frames.len(), 1, "{w}x{h} qp{qp} {cfg:?}");
1408+ let mut recon = enc.recon_y.clone();
1409+ recon.extend_from_slice(&enc.recon_cb);
1410+ recon.extend_from_slice(&enc.recon_cr);
1411+ assert_eq!(
1412+ frames[0].picture.to_planar_u8().expect("8-bit"),
1413+ recon,
1414+ "{w}x{h} qp{qp} {cfg:?}: decoder output == filtered recon"
1415+ );
1416+ }
1417+ }
1418+ }
1419+ }
1420+ }
1421+
1422+ /// The filter elections are distortion-driven, so a filtered
1423+ /// encode is never further from the source than the unfiltered
1424+ /// one — and on smooth content at high QP (where quantization
1425+ /// manufactures block edges the source never had) the filters
1426+ /// actually engage (the reconstruction changes and the slice
1427+ /// header signals them).
1428+ #[test]
1429+ fn filters_never_hurt_and_engage_on_smooth_content() {
1430+ let (w, h) = (64usize, 64usize);
1431+ let (y, cb, cr) = planes(w, h);
1432+ let qp = 40;
1433+ let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("plain");
1434+ let filtered =
1435+ encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, &LoopFilterCfg::all()).expect("lf");
1436+ let ssd = |a: &[u8], b: &[u8]| -> u64 {
1437+ a.iter()
1438+ .zip(b.iter())
1439+ .map(|(&p, &q)| {
1440+ let d = i64::from(p) - i64::from(q);
1441+ (d * d) as u64
1442+ })
1443+ .sum()
1444+ };
1445+ let d_plain =
1446+ ssd(&plain.recon_y, &y) + ssd(&plain.recon_cb, &cb) + ssd(&plain.recon_cr, &cr);
1447+ let d_filt = ssd(&filtered.recon_y, &y)
1448+ + ssd(&filtered.recon_cb, &cb)
1449+ + ssd(&filtered.recon_cr, &cr);
1450+ assert!(
1451+ d_filt <= d_plain,
1452+ "filters must not hurt: filtered {d_filt} vs plain {d_plain}"
1453+ );
1454+ assert_ne!(
1455+ filtered.recon_y, plain.recon_y,
1456+ "high-QP blocky content should engage the loop filters"
1457+ );
1458+
1459+ // The written headers carry the filter signalling: SAO enabled
1460+ // in the SPS, the deblocking override chain in the PPS, and
1461+ // the elected per-slice flags in the slice header.
1462+ let units = crate::nal::collect_nal_units(&filtered.au).expect("walk");
1463+ let sps = crate::sps::SeqParameterSet::parse(&units[1].rbsp).expect("sps");
1464+ assert!(sps.sample_adaptive_offset_enabled_flag);
1465+ let pps = crate::pps::PicParameterSet::parse(&units[2].rbsp).expect("pps");
1466+ assert!(pps.deblocking_filter_control_present_flag);
1467+ assert!(pps.deblocking.override_enabled_flag);
1468+ assert!(pps.deblocking.disabled_flag, "PPS default stays disabled");
1469+ let header = crate::slice::SliceSegmentHeader::parse(
1470+ &units[3].rbsp,
1471+ units[3].header.nal_unit_type,
1472+ &sps,
1473+ &pps,
1474+ )
1475+ .expect("slice header");
1476+ assert!(
1477+ header.slice_sao_luma_flag
1478+ || header.slice_sao_chroma_flag
1479+ || header.deblocking.is_some_and(|d| !d.disabled_flag),
1480+ "some in-loop filter is elected in the slice header"
1481+ );
1482+ }
1483+
1484+ /// `LoopFilterCfg::off()` reproduces the legacy unfiltered stream
1485+ /// byte for byte (headers included) — the golden interop pins stay
1486+ /// valid.
1487+ #[test]
1488+ fn lf_off_is_byte_identical_to_legacy_encode() {
1489+ let (w, h) = (48usize, 32usize);
1490+ let (y, cb, cr) = planes(w, h);
1491+ let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, 24).expect("plain");
1492+ let off =
1493+ encode_idr_intra_au_lf(&y, &cb, &cr, w, h, 24, &LoopFilterCfg::off()).expect("off");
1494+ assert_eq!(plain.au, off.au);
1495+ assert_eq!(plain.recon_y, off.recon_y);
1496+ }
1497+
1498+ /// Table 8-10 spot pins.
1499+ #[test]
1500+ fn chroma_qp_mapping_matches_table_8_10() {
1501+ assert_eq!(chroma_qp_420(0), 0);
1502+ assert_eq!(chroma_qp_420(29), 29);
1503+ assert_eq!(chroma_qp_420(30), 29);
1504+ assert_eq!(chroma_qp_420(33), 32);
1505+ assert_eq!(chroma_qp_420(34), 33);
1506+ assert_eq!(chroma_qp_420(35), 33);
1507+ assert_eq!(chroma_qp_420(36), 34);
1508+ assert_eq!(chroma_qp_420(37), 34);
1509+ assert_eq!(chroma_qp_420(38), 35);
1510+ assert_eq!(chroma_qp_420(43), 37);
1511+ assert_eq!(chroma_qp_420(44), 38);
1512+ assert_eq!(chroma_qp_420(51), 45);
1513+ }
1514+}
vendor/oxideav-h265/src/encoder/loopfilter.rsadded+1308 -0
@@ -0,0 +1,1308 @@
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.rsadded+114 -0
@@ -0,0 +1,114 @@
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.rsadded+1130 -0
@@ -0,0 +1,1130 @@
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.rsadded+1150 -0
@@ -0,0 +1,1150 @@
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.rsadded+718 -0
@@ -0,0 +1,718 @@
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+ conf_win: (0, 0), // edith patch: no crop on the inter paths
234+ }
235+ }
236+
237+ /// The layer-`l` slice QP.
238+ fn layer_qp(&self, layer: u8) -> i32 {
239+ (self.qp + i32::from(layer) * self.layer_qp_step).clamp(0, 51)
240+ }
241+
242+ /// Push the next DISPLAY-order frame; returns every access unit
243+ /// that became codable (none until the current mini-GOP fills,
244+ /// then the whole mini-GOP in decode order).
245+ ///
246+ /// # Errors
247+ /// [`PyramidError::Encode`] on plane-size mismatches.
248+ pub fn encode_frame(&mut self, frame: &YuvFrame<'_>) -> Result<Vec<PyramidAu>, PyramidError> {
249+ let (cw, ch) = (self.width / 2, self.height / 2);
250+ for (plane, buf, expected) in [
251+ ("y", frame.y, self.width * self.height),
252+ ("cb", frame.cb, cw * ch),
253+ ("cr", frame.cr, cw * ch),
254+ ] {
255+ if buf.len() != expected {
256+ return Err(PyramidError::Encode(IntraEncodeError::PlaneSize {
257+ plane,
258+ expected,
259+ got: buf.len(),
260+ }));
261+ }
262+ }
263+
264+ if self.anchor.is_none() {
265+ // The leading IDR (POC 0, layer 0).
266+ let idr = encode_idr_intra_au_full(
267+ frame.y,
268+ frame.cb,
269+ frame.cr,
270+ self.width,
271+ self.height,
272+ self.qp,
273+ &self.sps_cfg(),
274+ &self.filters,
275+ )?;
276+ let recon = FrameRecon {
277+ y: idr.recon_y,
278+ cb: idr.recon_cb,
279+ cr: idr.recon_cr,
280+ };
281+ self.refs.insert(0, recon.clone());
282+ self.anchor = Some(0);
283+ self.next_display = 1;
284+ return Ok(vec![PyramidAu {
285+ au: idr.au,
286+ keyframe: true,
287+ display_order: 0,
288+ layer: 0,
289+ recon,
290+ stats: FrameStats {
291+ intra: (self.width / CTB) * (self.height / CTB),
292+ ..FrameStats::default()
293+ },
294+ }]);
295+ }
296+
297+ self.pending.push(OwnedFrame {
298+ y: frame.y.to_vec(),
299+ cb: frame.cb.to_vec(),
300+ cr: frame.cr.to_vec(),
301+ });
302+ self.next_display += 1;
303+ if self.pending.len() == self.gop {
304+ Ok(self.code_mini_gop())
305+ } else {
306+ Ok(Vec::new())
307+ }
308+ }
309+
310+ /// Code the buffered complete mini-GOP in decode order and drain
311+ /// it. The pending buffer holds displays `a+1 ..= a+gop`.
312+ fn code_mini_gop(&mut self) -> Vec<PyramidAu> {
313+ let a = self.anchor.expect("mini-GOP needs an anchor");
314+ let g = self.gop as i32;
315+ let sched = build_schedule(a, g);
316+ let mut out = Vec::with_capacity(sched.len());
317+ for (i, s) in sched.iter().enumerate() {
318+ // Retained set for THIS slice's RPS: every already-coded
319+ // picture that this or a LATER slice of the schedule
320+ // still references.
321+ let retained: Vec<i32> = {
322+ let mut keep: Vec<i32> = self
323+ .refs
324+ .keys()
325+ .copied()
326+ .filter(|&p| {
327+ sched[i..].iter().any(|t| {
328+ t.l0 == p || t.l1 == Some(p) // still referenced
329+ })
330+ })
331+ .collect();
332+ keep.sort_unstable();
333+ keep
334+ };
335+ // Drop reconstructions nothing references any more.
336+ self.refs.retain(|p, _| retained.contains(p));
337+
338+ let frame = &self.pending[(s.poc - a - 1) as usize];
339+ let au = self.code_slice(frame.as_yuv(), s, &retained);
340+ self.refs.insert(s.poc, au.recon.clone());
341+ out.push(au);
342+ }
343+ // Only the new anchor survives into the next mini-GOP.
344+ let new_anchor = a + g;
345+ self.refs.retain(|&p, _| p == new_anchor);
346+ self.anchor = Some(new_anchor);
347+ self.pending.clear();
348+ out
349+ }
350+
351+ /// Encode one scheduled P / B slice against the retained
352+ /// reconstructions.
353+ fn code_slice(&self, frame: YuvFrame<'_>, s: &Sched, retained: &[i32]) -> PyramidAu {
354+ let b_slice = s.l1.is_some();
355+ let rec_of = |p: i32| -> &FrameRecon { self.refs.get(&p).expect("retained recon") };
356+ let l0 = vec![(s.l0, rec_of(s.l0))];
357+ let l1: Vec<(i32, &FrameRecon)> = s.l1.map(|p| (p, rec_of(p))).into_iter().collect();
358+ // Inline §7.4.8 RPS: negative pics closest-first, positive
359+ // pics closest-first; used flags mark the active references.
360+ let rps_neg: Vec<(u32, bool)> = retained
361+ .iter()
362+ .rev()
363+ .filter(|&&p| p < s.poc)
364+ .map(|&p| ((s.poc - p) as u32, p == s.l0))
365+ .collect();
366+ let rps_pos: Vec<(u32, bool)> = retained
367+ .iter()
368+ .filter(|&&p| p > s.poc)
369+ .map(|&p| ((p - s.poc) as u32, Some(p) == s.l1))
370+ .collect();
371+ let spec = SliceSpec {
372+ poc: s.poc,
373+ qp: self.layer_qp(s.layer),
374+ b_slice,
375+ rps_neg,
376+ rps_pos,
377+ l0,
378+ l1,
379+ lf: &self.filters,
380+ big_cu: self.amp,
381+ };
382+ let (rbsp, recon, stats) = encode_inter_slice(&frame, &spec, self.width, self.height);
383+ PyramidAu {
384+ au: annexb(&[nal_unit(1, 0, 0, &rbsp)]), // TRAIL_R
385+ keyframe: false,
386+ display_order: s.poc as usize,
387+ layer: s.layer,
388+ recon,
389+ stats,
390+ }
391+ }
392+
393+ /// Flush the trailing frames that never filled a mini-GOP: a
394+ /// low-delay P chain from the last anchor (decode order ==
395+ /// display order). Returns their access units; the encoder is
396+ /// ready for more input afterwards (the last tail frame becomes
397+ /// the new anchor).
398+ pub fn flush(&mut self) -> Vec<PyramidAu> {
399+ let Some(a) = self.anchor else {
400+ return Vec::new();
401+ };
402+ let mut out = Vec::with_capacity(self.pending.len());
403+ let pending = std::mem::take(&mut self.pending);
404+ for (k, frame) in pending.iter().enumerate() {
405+ let poc = a + 1 + k as i32;
406+ let s = Sched {
407+ poc,
408+ l0: poc - 1,
409+ l1: None,
410+ layer: 0,
411+ };
412+ let retained = vec![poc - 1];
413+ self.refs.retain(|&p, _| p == poc - 1);
414+ let au = self.code_slice(frame.as_yuv(), &s, &retained);
415+ self.refs.insert(poc, au.recon.clone());
416+ out.push(au);
417+ }
418+ if let Some(last) = out.last() {
419+ let new_anchor = last.display_order as i32;
420+ self.refs.retain(|&p, _| p == new_anchor);
421+ self.anchor = Some(new_anchor);
422+ }
423+ out
424+ }
425+}
426+
427+/// Errors from the pyramid encoder.
428+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
429+pub enum PyramidError {
430+ /// The shared input-validation contract (dimensions, planes, QP).
431+ Encode(IntraEncodeError),
432+ /// `gop` is not a power of two in 2..=16.
433+ BadGop(usize),
434+}
435+
436+impl From<IntraEncodeError> for PyramidError {
437+ fn from(e: IntraEncodeError) -> Self {
438+ Self::Encode(e)
439+ }
440+}
441+
442+impl core::fmt::Display for PyramidError {
443+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
444+ match self {
445+ Self::Encode(e) => e.fmt(f),
446+ Self::BadGop(g) => write!(f, "pyramid gop must be a power of two in 2..=16, got {g}"),
447+ }
448+ }
449+}
450+
451+impl std::error::Error for PyramidError {}
452+
453+/// The encoded hierarchical-B sequence, with the per-frame outputs in
454+/// DISPLAY order (the stream itself is decode-ordered).
455+#[derive(Debug, Clone)]
456+pub struct PyramidEncoded {
457+ /// The whole Annex B byte stream (decode order).
458+ pub stream: Vec<u8>,
459+ /// Per-frame reconstruction, display order.
460+ pub recon: Vec<FrameRecon>,
461+ /// Per-frame CU mode-decision counters, display order.
462+ pub stats: Vec<FrameStats>,
463+ /// Per-frame pyramid layer, display order.
464+ pub layers: Vec<u8>,
465+ /// The display order of each access unit of `stream`, in decode
466+ /// order (the coding schedule, for inspection).
467+ pub decode_order: Vec<usize>,
468+}
469+
470+/// Encode a whole sequence through a [`PyramidEncoder`] (leading IDR,
471+/// dyadic mini-GOPs, low-delay tail) and return the stream plus the
472+/// display-ordered per-frame outputs.
473+///
474+/// # Errors
475+/// [`PyramidError`] on bad dimensions / planes / QP / GOP length.
476+pub fn encode_pyramid(
477+ frames: &[YuvFrame<'_>],
478+ width: usize,
479+ height: usize,
480+ qp: i32,
481+ gop: usize,
482+) -> Result<PyramidEncoded, PyramidError> {
483+ encode_pyramid_with(PyramidEncoder::new(width, height, qp, gop)?, frames)
484+}
485+
486+/// [`encode_pyramid`] over a pre-configured encoder (filters, AMP,
487+/// layer QP step).
488+///
489+/// # Errors
490+/// [`PyramidError`] on bad plane geometry.
491+pub fn encode_pyramid_with(
492+ mut enc: PyramidEncoder,
493+ frames: &[YuvFrame<'_>],
494+) -> Result<PyramidEncoded, PyramidError> {
495+ let n = frames.len();
496+ let mut out = PyramidEncoded {
497+ stream: Vec::new(),
498+ recon: vec![FrameRecon::default(); n],
499+ stats: vec![FrameStats::default(); n],
500+ layers: vec![0; n],
501+ decode_order: Vec::with_capacity(n),
502+ };
503+ let push = |out: &mut PyramidEncoded, aus: Vec<PyramidAu>| {
504+ for au in aus {
505+ out.stream.extend_from_slice(&au.au);
506+ out.decode_order.push(au.display_order);
507+ out.recon[au.display_order] = au.recon;
508+ out.stats[au.display_order] = au.stats;
509+ out.layers[au.display_order] = au.layer;
510+ }
511+ };
512+ for f in frames {
513+ let aus = enc.encode_frame(f)?;
514+ push(&mut out, aus);
515+ }
516+ push(&mut out, enc.flush());
517+ Ok(out)
518+}
519+
520+#[cfg(test)]
521+mod tests {
522+ use super::*;
523+ use crate::encoder::inter::encode_low_delay_p;
524+ use crate::sequence::decode_annexb_sequence;
525+
526+ /// A deterministic "camera-noise" scene: a static textured
527+ /// background under small temporally-independent sensor noise,
528+ /// with a small bright square drifting 1 px per frame. Motion
529+ /// prediction cancels everything except the noise — the content
530+ /// class where the pyramid's per-layer QP allocation wins (the
531+ /// top layers spend fewer bits on noise nobody references).
532+ fn pan_scene(w: usize, h: usize, n: usize) -> Vec<(Vec<u8>, Vec<u8>, Vec<u8>)> {
533+ let tex = |u: usize, v: usize| -> i32 { ((u * 3 + v * 5 + (u / 9) * 7) % 200) as i32 };
534+ let noise = |x: usize, yy: usize, t: usize| -> i32 {
535+ let h32 = (x
536+ .wrapping_mul(73_856_093)
537+ .wrapping_add(yy.wrapping_mul(19_349_663))
538+ .wrapping_add(t.wrapping_mul(83_492_791))) as u32;
539+ ((h32 >> 13) % 9) as i32 - 4
540+ };
541+ (0..n)
542+ .map(|t| {
543+ let y: Vec<u8> = (0..w * h)
544+ .map(|i| {
545+ let (x, yy) = (i % w, i / w);
546+ let (sx, sy) = (10 + t, 24);
547+ let obj = x >= sx && x < sx + 8 && yy >= sy && yy < sy + 8;
548+ let base = tex(x, yy) + if obj { 45 } else { 0 };
549+ (base + 8 + noise(x, yy, t)).clamp(0, 255) as u8
550+ })
551+ .collect();
552+ let cb: Vec<u8> = (0..w * h / 4)
553+ .map(|i| (90 + (i % (w / 2)) % 70) as u8)
554+ .collect();
555+ let cr: Vec<u8> = (0..w * h / 4)
556+ .map(|i| (180 - (i / (w / 2)) % 60) as u8)
557+ .collect();
558+ (y, cb, cr)
559+ })
560+ .collect()
561+ }
562+
563+ fn as_frames(planes: &[(Vec<u8>, Vec<u8>, Vec<u8>)]) -> Vec<YuvFrame<'_>> {
564+ planes
565+ .iter()
566+ .map(|(y, cb, cr)| YuvFrame { y, cb, cr })
567+ .collect()
568+ }
569+
570+ fn assert_display_order_exact(stream: &[u8], recons: &[FrameRecon], label: &str) {
571+ let decoded = decode_annexb_sequence(stream).expect("decode");
572+ assert_eq!(decoded.len(), recons.len(), "{label}: frame count");
573+ for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() {
574+ assert_eq!(dec.poc, i as i32, "{label}: display order POC {i}");
575+ let mut expect = rec.y.clone();
576+ expect.extend_from_slice(&rec.cb);
577+ expect.extend_from_slice(&rec.cr);
578+ assert_eq!(
579+ dec.picture.to_planar_u8().expect("8-bit"),
580+ expect,
581+ "{label} frame {i}: decoder output == encoder recon"
582+ );
583+ }
584+ }
585+
586+ /// The core contract across GOP shapes: out-of-order coded
587+ /// pyramids decode (through the crate's own §C.5.2.2
588+ /// output-ordering) bit-exactly to the encoder's display-order
589+ /// reconstructions — including a non-filling low-delay tail.
590+ #[test]
591+ fn pyramid_gops_decode_to_encoder_recon_exactly() {
592+ let planes = pan_scene(64, 64, 10);
593+ let frames = as_frames(&planes);
594+ for (gop, qp) in [(2usize, 24i32), (4, 30), (8, 27)] {
595+ let enc = encode_pyramid(&frames, 64, 64, qp, gop).expect("encode");
596+ assert_display_order_exact(&enc.stream, &enc.recon, &format!("gop{gop} qp{qp}"));
597+ }
598+ }
599+
600+ /// The decode-order schedule is the dyadic pyramid, the layers
601+ /// are the recursion depths, and the mid slices really code
602+ /// bi-predictively (past L0 + future L1).
603+ #[test]
604+ fn pyramid_schedule_layers_and_bi_usage() {
605+ let planes = pan_scene(64, 64, 9);
606+ let frames = as_frames(&planes);
607+ let enc = encode_pyramid(&frames, 64, 64, 26, 8).expect("encode");
608+ // IDR, then the mini-GOP in dyadic decode order.
609+ assert_eq!(enc.decode_order, vec![0, 8, 4, 2, 1, 3, 6, 5, 7]);
610+ assert_eq!(
611+ enc.layers,
612+ vec![0, 3, 2, 3, 1, 3, 2, 3, 0],
613+ "display-order layers of a GOP-8 pyramid"
614+ );
615+ // Every B layer >= 1 frame elects some bi-predicted CUs on
616+ // smooth translation.
617+ let bi_frames = (0..9)
618+ .filter(|&i| enc.layers[i] >= 1 && enc.stats[i].bi > 0)
619+ .count();
620+ assert!(
621+ bi_frames >= 4,
622+ "expected widespread bi-prediction, stats: {:?}",
623+ enc.stats
624+ );
625+ }
626+
627+ /// Pyramid coding beats the low-delay chain on smooth motion at
628+ /// the same base QP: fewer bytes for comparable quality.
629+ #[test]
630+ fn pyramid_beats_low_delay_on_smooth_motion() {
631+ let (w, h, n) = (64usize, 64usize, 9usize);
632+ let planes = pan_scene(w, h, n);
633+ let frames = as_frames(&planes);
634+ let qp = 30;
635+ let low = encode_low_delay_p(&frames, w, h, qp).expect("low-delay");
636+ let pyr = encode_pyramid(&frames, w, h, qp, 8).expect("pyramid");
637+ assert!(
638+ pyr.stream.len() < low.stream.len(),
639+ "pyramid ({} B) should undercut low-delay ({} B) on smooth motion",
640+ pyr.stream.len(),
641+ low.stream.len()
642+ );
643+ // Quality stays in the same class (the per-layer QP offsets
644+ // trade a little PSNR on the top layers for the rate win).
645+ let psnr = |rec: &FrameRecon, t: usize| -> f64 {
646+ let mse: f64 = rec
647+ .y
648+ .iter()
649+ .zip(planes[t].0.iter())
650+ .map(|(&a, &b)| {
651+ let d = f64::from(a) - f64::from(b);
652+ d * d
653+ })
654+ .sum::<f64>()
655+ / rec.y.len() as f64;
656+ 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10()
657+ };
658+ for t in 0..n {
659+ assert!(
660+ psnr(&pyr.recon[t], t) > 30.0,
661+ "frame {t}: pyramid luma PSNR too low"
662+ );
663+ }
664+ }
665+
666+ /// Pyramids compose with the AMP configuration and the §8.7
667+ /// in-loop filters — everything still decodes bit-exactly.
668+ #[test]
669+ fn pyramid_composes_with_amp_and_filters() {
670+ let planes = pan_scene(64, 48, 9);
671+ let frames = as_frames(&planes);
672+ for (amp, lf) in [
673+ (true, LoopFilterCfg::off()),
674+ (false, LoopFilterCfg::all()),
675+ (true, LoopFilterCfg::all()),
676+ ] {
677+ let enc = PyramidEncoder::new(64, 48, 32, 4)
678+ .expect("encoder")
679+ .with_amp(amp)
680+ .with_loop_filters(lf);
681+ let out = encode_pyramid_with(enc, &frames).expect("encode");
682+ assert_display_order_exact(&out.stream, &out.recon, &format!("amp={amp} {lf:?}"));
683+ }
684+ }
685+
686+ /// Successive mini-GOPs chain across anchors, and flushing midway
687+ /// (a 6-frame sequence at GOP 4: IDR + one mini-GOP + 1-frame
688+ /// tail) stays bit-exact.
689+ #[test]
690+ fn pyramid_multi_gop_and_tail_roundtrip() {
691+ let planes = pan_scene(48, 32, 6);
692+ let frames = as_frames(&planes);
693+ let enc = encode_pyramid(&frames, 48, 32, 22, 4).expect("encode");
694+ assert_eq!(enc.decode_order, vec![0, 4, 2, 1, 3, 5]);
695+ assert_display_order_exact(&enc.stream, &enc.recon, "gop4 tail");
696+ }
697+
698+ /// Input validation.
699+ #[test]
700+ fn rejects_bad_configs() {
701+ assert!(matches!(
702+ PyramidEncoder::new(64, 64, 26, 3),
703+ Err(PyramidError::BadGop(3))
704+ ));
705+ assert!(matches!(
706+ PyramidEncoder::new(64, 64, 26, 32),
707+ Err(PyramidError::BadGop(32))
708+ ));
709+ assert!(matches!(
710+ PyramidEncoder::new(20, 64, 26, 4),
711+ Err(PyramidError::Encode(IntraEncodeError::BadDimensions { .. }))
712+ ));
713+ assert!(matches!(
714+ PyramidEncoder::new(64, 64, 99, 4),
715+ Err(PyramidError::Encode(IntraEncodeError::BadQp(99)))
716+ ));
717+ }
718+}
vendor/oxideav-h265/src/encoder/rdpcm_streams.rsadded+772 -0

Diff too large; view file

@@ -0,0 +1,772 @@
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.
vendor/oxideav-h265/src/encoder/residual.rsadded+641 -0

Diff too large; view file

vendor/oxideav-h265/src/encoder/scc_streams.rsadded+936 -0

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file

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

Diff too large; view file