diff --git a/Cargo.lock b/Cargo.lock index 3ac3b68..bc63ce6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1637,6 +1637,7 @@ dependencies = [ "mp4", "oxideav-ac3", "oxideav-core", + "oxideav-h265", "rav1e", "rusty_aac", "rusty_h264", @@ -3950,6 +3951,13 @@ dependencies = [ "thiserror 2.0.20", ] +[[package]] +name = "oxideav-h265" +version = "0.0.9" +dependencies = [ + "oxideav-core", +] + [[package]] name = "parking" version = "2.2.1" diff --git a/Cargo.toml b/Cargo.toml index 9d98afd..2fb73a0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,14 +2,20 @@ resolver = "3" members = ["crates/engine", "crates/engine-hw", "crates/engine-audio", "crates/app"] # Vendored third-party (see [patch.crates-io]); not ours to build or test. -exclude = ["vendor/cros-libva", "vendor/cros-codecs", "vendor/rusty_aac"] +exclude = [ + "vendor/cros-libva", + "vendor/cros-codecs", + "vendor/rusty_aac", + "vendor/oxideav-h265", +] [workspace.package] version = "0.1.0" edition = "2024" -# Three upstream crates vendored verbatim except for one clearly marked fix each, -# all blockers on this machine and all still unfixed upstream as of 0.0.6/0.0.13/0.5.0: +# Four upstream crates vendored verbatim except for one clearly marked fix each, +# all blockers on this machine and all still unfixed upstream as of +# 0.0.6/0.0.13/0.5.0/0.0.9: # cros-libva - fails to build against libva >= 1.23 headers # cros-codecs - probes VA-API with a 16x16 context that Mesa radeonsi refuses; # and creates every decode context as 8-bit 4:2:0, which no HEVC @@ -18,7 +24,18 @@ edition = "2024" # term (the fast path in the same file serves the encoder only), # which is 4x slower than real time for 5.1 and therefore not # playable at all; the patch caches the cosine matrix -# Drop `vendor/` entirely once released versions handle all three. +# oxideav-h265 - its intra encoder writes `conformance_window_flag = 0` and +# refuses any dimension that is not a multiple of the 16-sample +# CTB, so 1920x1080 could not be written at all; the patch adds +# the §7.4.3.2.1 conformance window (`SpsCfg::conf_win`, one +# marked block in `encoder/intra.rs`) so the picture is coded +# padded to 1920x1088 and *displayed* at 1920x1080. Taken from +# git master rather than the registry -- crates.io 0.0.9 is the +# pre-encoder release -- at rev d35963a02c872d12e6878b4ed3cf17a +# 69bde5a6e, and it is a plain path dependency (no +# `[patch.crates-io]` line) because nothing else in the tree +# asks for it. +# Drop `vendor/` entirely once released versions handle all four. [patch.crates-io] cros-libva = { path = "vendor/cros-libva" } cros-codecs = { path = "vendor/cros-codecs" } diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index a1be829..086587d 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -337,8 +337,9 @@ pub const FIXED: [Fixed; 16] = [ category: Category::File, }, Fixed { - chord: "m / a / v / w / f / p", - label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, WAV, FLAC or MP3", + chord: "m / a / v / h / x / w / f / p", + label: "Pick the export format: MP4, AV1 in MKV, AV1 in MP4, HEVC in MKV, \ + HEVC in MP4, WAV, FLAC or MP3", category: Category::File, }, Fixed { diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 1751d83..0cf3abc 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -117,7 +117,7 @@ const KEYS_ROW_H: f32 = HIT_MIN; /// editor grows -- ten rows fit here, and the eleventh is a scroll away. const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H; /// The same for the export card, which carries a fixed-format line and a button -/// under its list and so has less room: destination, nine formats and five +/// under its list and so has less room: destination, ten formats and five /// qualities are fifteen rows, eight of them on screen. const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H; /// The menu a right-click on a clip opens: wide enough for the longest label @@ -4802,11 +4802,12 @@ impl Player { .text_size(px(11.)) .text_color(rgb(INK_DIM)) .child(self.notice.clone().unwrap_or_else(|| { - "pick a format (m/a/v/w/f/p), then Export — esc closes".into() + "pick a format (m/a/v/h/x/w/f/p), then Export — esc closes" + .into() })), ) // Capped and scrolling like the keybindings list: the - // destination, nine formats and five qualities are more + // destination, ten formats and five qualities are more // rows than a 360 px window has room for, and it is the // list that scrolls, never the card that grows. .child( @@ -6941,20 +6942,23 @@ impl Quality { /// as a claim that nothing else exists -- so the refusals are rows too, dimmed /// and unclickable. /// -/// `None` is exactly that kind of row, and there are three left. MP3 stopped +/// `None` is exactly that kind of row, and there are two left. MP3 stopped /// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL /// `shine-rs` was the licence question, and it is not the only encoder any -/// more). HEVC and VP9 are the two this program *reads* and cannot write -- the -/// plugin decodes both and there is no encoder for either here -- so they are -/// rows for the same reason: a codec that opens but never comes back out is -/// exactly the gap a user would otherwise go looking for. AAC is not a row at -/// all: it is what both containers' sound *is*, never a file of its own. +/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an +/// encoder — an *intra-only* one, which the rows say rather than let a user +/// find out from the size of the file. VP9 is the one this program still only +/// *reads*: the plugin decodes it and there is no encoder for it here, so it is +/// a row for the reason the refusals are rows at all — a codec that opens but +/// never comes back out is exactly the gap a user would otherwise go looking +/// for. AAC is not a row at all: it is what both containers' sound *is*, never a +/// file of its own. /// /// AV1 is two rows because a codec and a container are two choices: the same /// picture and the same AAC track go into a Matroska file or into an mp4, and /// which one a user needs is about what has to play the file, not about the -/// encode. -const FORMATS: [(Option, &str, &str, &str); 9] = [ +/// encode. HEVC is two rows for the same reason. +const FORMATS: [(Option, &str, &str, &str); 10] = [ (Some(Format::Mp4), "m", "MP4", "H.264 picture + AAC sound"), ( Some(Format::Av1), @@ -6968,6 +6972,18 @@ const FORMATS: [(Option, &str, &str, &str); 9] = [ "AV1 · MP4", "the same AV1 picture and sound in .mp4", ), + ( + Some(Format::Hevc), + "h", + "HEVC · MKV", + "intra-only HEVC + AAC in .mkv — large files", + ), + ( + Some(Format::HevcMp4), + "x", + "HEVC · MP4", + "the same intra-only HEVC and sound in .mp4", + ), (Some(Format::Wav), "w", "WAV", "16-bit PCM — audio only"), (Some(Format::Flac), "f", "FLAC", "lossless — audio only"), ( @@ -6977,12 +6993,6 @@ const FORMATS: [(Option, &str, &str, &str); 9] = [ "MPEG-1 Layer III, 256 kbps — audio only", ), (None, "", "OGG", "no pure-Rust Vorbis or Opus encoder"), - ( - None, - "", - "HEVC", - "no encoder in this stack, and patent-encumbered", - ), (None, "", "VP9", "superseded by AV1, which is the row above"), ]; @@ -7167,6 +7177,8 @@ fn format_line(format: Format) -> &'static str { Format::Mp4 => "H.264 · MP4 · moov at end", Format::Av1 => "AV1 · Matroska · picture and sound", Format::Av1Mp4 => "AV1 · MP4 · picture and sound", + Format::Hevc => "HEVC intra · Matroska · picture and sound", + Format::HevcMp4 => "HEVC intra · MP4 · picture and sound", Format::Wav => "16-bit PCM · WAV · timeline audio only", Format::Flac => "FLAC · lossless · timeline audio only", Format::Mp3 => "MP3 · 256 kbps · timeline audio only", @@ -10254,6 +10266,8 @@ mod tests { Format::Mp4, Format::Av1, Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, Format::Wav, Format::Flac, Format::Mp3 @@ -10261,10 +10275,14 @@ mod tests { ); assert_eq!(Format::Av1.ext(), "mkv"); assert_eq!(Format::Av1Mp4.ext(), "mp4"); + assert_eq!(Format::Hevc.ext(), "mkv"); + assert_eq!(Format::HevcMp4.ext(), "mp4"); for (format, _, label, _) in FORMATS { match format { Some(Format::Av1) => assert_eq!(label, "AV1 · MKV"), Some(Format::Av1Mp4) => assert_eq!(label, "AV1 · MP4"), + Some(Format::Hevc) => assert_eq!(label, "HEVC · MKV"), + Some(Format::HevcMp4) => assert_eq!(label, "HEVC · MP4"), Some(format) => assert_eq!(format.ext(), label.to_lowercase()), // A refused format is a row with a reason, never a hidden one: // an empty detail column would read as an oversight. @@ -10277,7 +10295,12 @@ mod tests { // dims them off exactly this. assert_eq!( format.is_some_and(Format::has_video), - matches!(format, Some(Format::Mp4 | Format::Av1 | Format::Av1Mp4)) + matches!( + format, + Some( + Format::Mp4 | Format::Av1 | Format::Av1Mp4 | Format::Hevc | Format::HevcMp4 + ) + ) ); // Every row that can be picked has a key of its own, and no two // share one: the card is drivable without a pointer. @@ -10290,10 +10313,11 @@ mod tests { ); } } - // The two codecs this program reads and cannot write are rows of their - // own, refused by name rather than absent -- HEVC for want of an encoder - // (and for its patents), VP9 because AV1 is the row that replaced it. - for (label, word) in [("HEVC", "no encoder"), ("VP9", "superseded")] { + // The codec this program reads and cannot write is a row of its own, + // refused by name rather than absent: VP9, because AV1 is the row that + // replaced it. HEVC used to be one beside it and is now two rows that + // pick -- an intra-only encoder is still an encoder. + for (label, word) in [("VP9", "superseded")] { let (format, _, _, detail) = FORMATS .into_iter() .find(|(_, _, row, _)| *row == label) @@ -10312,8 +10336,21 @@ mod tests { assert!(detail.contains("sound"), "{detail}"); assert!(format_line(format).contains("picture and sound")); } + // ...and both HEVC rows say what they are before a user waits on one: + // intra-only, which is a file several times the size of the AV1 above + // it. A row that hid that would be found out by the disk. + for format in [Format::Hevc, Format::HevcMp4] { + let (_, _, _, detail) = FORMATS + .into_iter() + .find(|(f, ..)| *f == Some(format)) + .expect("an HEVC row"); + assert!(detail.contains("intra-only"), "{detail}"); + assert!(format_line(format).contains("picture and sound")); + } assert_eq!(format_key("a"), Some(Format::Av1), "the Matroska one"); assert_eq!(format_key("v"), Some(Format::Av1Mp4), "and the mp4 one"); + assert_eq!(format_key("h"), Some(Format::Hevc), "HEVC's Matroska"); + assert_eq!(format_key("x"), Some(Format::HevcMp4), "and its mp4"); assert_eq!(format_key("p"), Some(Format::Mp3)); assert_eq!(format_key("m"), Some(Format::Mp4), "not MP3, which is p"); // The destination follows the format and keeps the stem, mp4 included. diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index bc6648f..418d61b 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -74,6 +74,14 @@ oxideav-core = "0.1.34" # inside rav1e itself and is what keeps an export minutes rather than tens of # minutes; the cost of no assembly is measured in `export::Enc::open_av1`. rav1e = { version = "0.8.1", default-features = false, features = ["threading"] } +# The software HEVC encoder, intra-only: OxideAV's pure-Rust H.265, MIT, no C +# and no FFI like everything else here. Its *inter* modes run at 0.81 fps on +# 1080p across 12 cores (measured 2026-08-11) and are therefore not an export +# anyone would wait for; its intra AU is a stateless free function that fans out +# across cores at 4.30 fps for the same picture, which is the export this +# project offers -- an intraframe master, ProRes-shaped, large files and all. +# Built from `vendor/oxideav-h265`; see the note in the workspace manifest. +oxideav-h265 = { path = "../../vendor/oxideav-h265" } [dev-dependencies] # The still-image suite compares what the timeline shows against the file's own diff --git a/crates/engine/src/export.rs b/crates/engine/src/export.rs index bbf26a6..ade9f98 100644 --- a/crates/engine/src/export.rs +++ b/crates/engine/src/export.rs @@ -1,6 +1,13 @@ -//! Export: the edit list rendered back out as one mp4 (H.264 or AV1) or one -//! AV1-in-Matroska — or, picture left behind, as one WAV, FLAC or MP3 of the -//! timeline's audio alone. +//! Export: the edit list rendered back out as one mp4 (H.264, AV1 or HEVC) or +//! one Matroska file (AV1 or HEVC) — or, picture left behind, as one WAV, FLAC +//! or MP3 of the timeline's audio alone. +//! +//! The HEVC pair is **intra-only**, and says so wherever it is offered: every +//! frame is a self-contained IDR from the vendored `oxideav-h265`, which is the +//! only shape of a pure-Rust HEVC encode fast enough to wait for (its inter +//! modes code 1080p at 0.81 fps across 12 cores against the intra path's 4.30). +//! That makes it an intraframe master in the family of ProRes and DNxHD — large +//! files, every frame a cut point — and not a delivery codec. //! //! Video is fully re-encoded — a cut lands mid-GOP, so stream-copying across it //! is impossible — while audio is copied packet for packet wherever a copy can @@ -55,7 +62,7 @@ use flacenc::error::Verify; use crate::audio::{AudioMeta, AudioSession}; use crate::demux::{Demuxer, VideoMeta}; use crate::hw::{HwEncoder, HwSession}; -use crate::mux::{AudioParams, Av1Params, MkvMuxer, Mp4Muxer, VideoParams}; +use crate::mux::{AudioParams, Av1Params, HevcParams, MkvMuxer, Mp4Muxer, VideoParams}; use crate::project::{LaneKind, Project, Rate}; use crate::scale::Composer; @@ -73,15 +80,30 @@ const MAX_BITRATE: u64 = 20_000_000; /// on a build with no assembly, which is what this one is. const AV1_SPEED: u8 = 10; -/// What an export writes. H.264-in-mp4 and AV1 -- in Matroska or in mp4, the -/// user's pick of container -- are the only *video* pairs with both an encoder -/// and a decoder under this project's no-install rule, and WAV, FLAC and MP3 are -/// the standalone audio formats with a pure-Rust encoder: `hound`, `flacenc` and -/// `rusty_mp3`. Vorbis and Opus have none. (AAC does -- `rusty_aac`, which is -/// what a re-encoded video track's sound leaves through -- but AAC is a -/// container's own audio, never a file of its own here.) HEVC and VP9 have no -/// encoder here at all (`hevc`/`vp9` import through the plugin and stop there). -/// A front-end says so rather than hiding the rows. +/// The HEVC coding tree block this encoder is fixed at: the coded picture is a +/// whole number of them, which is what the conformance window crops back. +const CTB: usize = 16; +/// How many frames the intra HEVC encoder codes at once. Twelve is where the +/// 2026-08-11 bench stopped scaling on this box (4.30 fps at 1080p); more lanes +/// only holds more decoded frames in memory. +const HEVC_LANES: usize = 12; +/// Bits per pixel the intra encoder spends at QP 27, measured on the same bench: +/// 0.607 at 720p and 0.586 at 1080p. What [`hevc_qp`] maps a bitrate row through. +const HEVC_BPP_AT_27: f64 = 0.6; +/// The band [`hevc_qp`] is clamped into, for the reason stated there. +const HEVC_QP_MIN: i32 = 22; +const HEVC_QP_MAX: i32 = 40; + +/// What an export writes. H.264-in-mp4, AV1 and HEVC -- each of the last two in +/// Matroska or in mp4, the user's pick of container -- are the *video* pairs +/// with both an encoder and a decoder under this project's no-install rule, and +/// WAV, FLAC and MP3 are the standalone audio formats with a pure-Rust encoder: +/// `hound`, `flacenc` and `rusty_mp3`. Vorbis and Opus have none. (AAC does -- +/// `rusty_aac`, which is what a re-encoded video track's sound leaves through -- +/// but AAC is a container's own audio, never a file of its own here.) VP9 is the +/// one codec left that comes in through the plugin and stops there, HEVC having +/// gained an encoder (an intra-only one, which the rows say). A front-end says +/// so rather than hiding the row. /// /// **Every video format carries sound.** Which way it carries it is the only /// difference: copied packet for packet where a copy can say what the timeline @@ -103,6 +125,14 @@ pub enum Format { /// ([`crate::mux::Mp4Muxer::create_av1`]); the sound is the mp4 path's own, /// unchanged. Av1Mp4, + /// HEVC in Matroska, **intra-only**: every frame is a self-contained IDR + /// picture ([`Enc::open_hevc`]), which is what makes a pure-Rust HEVC + /// encoder fast enough to be an export at all. An intraframe master, like + /// ProRes or DNxHD -- large files, and every frame a cut point. + Hevc, + /// The same HEVC stream in an mp4 (`hvc1`), for everything that plays mp4 + /// and not Matroska -- the AV1 pair's split, for the same reason. + HevcMp4, /// The audio lanes alone, 16-bit PCM. Wav, /// The audio lanes alone, losslessly compressed. @@ -116,8 +146,8 @@ impl Format { /// the destination path from it, so the name never disagrees with the bytes. pub fn ext(self) -> &'static str { match self { - Self::Mp4 | Self::Av1Mp4 => "mp4", - Self::Av1 => "mkv", + Self::Mp4 | Self::Av1Mp4 | Self::HevcMp4 => "mp4", + Self::Av1 | Self::Hevc => "mkv", Self::Wav => "wav", Self::Flac => "flac", Self::Mp3 => "mp3", @@ -127,7 +157,10 @@ impl Format { /// Whether this format carries the picture. The bitrate settings are video /// settings and mean nothing to the audio-only ones. pub fn has_video(self) -> bool { - matches!(self, Self::Mp4 | Self::Av1 | Self::Av1Mp4) + matches!( + self, + Self::Mp4 | Self::Av1 | Self::Av1Mp4 | Self::Hevc | Self::HevcMp4 + ) } /// Whether the picture in it is AV1 rather than H.264 -- which encoder runs @@ -137,12 +170,20 @@ impl Format { matches!(self, Self::Av1 | Self::Av1Mp4) } + /// The same question for HEVC, and the same answer for both its containers: + /// one encoder, two boxes to put its stream in. + fn is_hevc(self) -> bool { + matches!(self, Self::Hevc | Self::HevcMp4) + } + /// What the format is called where a refusal names it. pub fn name(self) -> &'static str { match self { Self::Mp4 => "an mp4", Self::Av1 => "an AV1 Matroska", Self::Av1Mp4 => "an AV1 mp4", + Self::Hevc => "an HEVC Matroska", + Self::HevcMp4 => "an HEVC mp4", Self::Wav => "a WAV", Self::Flac => "a FLAC", Self::Mp3 => "an MP3", @@ -339,6 +380,11 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { let (fps_num, fps_den) = crate::mux::frame_timing(meta.frame_rate).ok()?; let bitrate = bitrate_of(meta, settings); match settings.format { + // The HEVC pair is software only, and not for want of a GPU: the plugin + // has no HEVC *encode* entry point at all (`hw::HwEncoder` opens H.264 + // and AV1), so there is no seat to probe. Said here rather than left to + // a failed open, which would read as a driver refusal. + format if format.is_hevc() => None, // Opt-in only, for the reason [`Enc::open_av1`] states in full. Both // AV1 formats sit on it: the container is not the encoder's business. format if format.is_av1() && !forced("VE_HW_AV1") => None, @@ -355,10 +401,11 @@ fn hw_seat(meta: &VideoMeta, settings: &ExportSettings) -> Option { /// place, so what a card says before an export and what its progress line says /// during one cannot drift apart. fn video_label(format: Format, hw: bool) -> &'static str { - match (format.is_av1(), hw) { + match (format, hw) { (_, true) => "HW encode (VA-API)", - (true, false) => "SW encode (rav1e)", - (false, false) => "SW encode (rusty_h264)", + (Format::Hevc | Format::HevcMp4, false) => "SW encode (oxideav-h265 intra)", + (Format::Av1 | Format::Av1Mp4, false) => "SW encode (rav1e)", + (_, false) => "SW encode (rusty_h264)", } } @@ -936,9 +983,7 @@ fn run_audio( Format::Wav => write_wav(out, &samples, &audio)?, Format::Flac => write_flac(out, &samples, &audio)?, Format::Mp3 => write_mp3(out, &samples, &audio)?, - Format::Mp4 | Format::Av1 | Format::Av1Mp4 => { - unreachable!("the picture formats are `run`") - } + _ => unreachable!("the picture formats are `run`"), } shared.progress.store(PROGRESS_SCALE, Ordering::Relaxed); Ok(()) @@ -1105,6 +1150,60 @@ fn write_video( au: &[u8], key: bool, ) -> crate::Result<()> { + if settings.format.is_hevc() { + // The parameter sets are in the access unit -- every intra AU carries + // VPS, SPS and PPS -- and the record built from them is what *both* + // containers declare the track with: an mp4's `hvcC` box and a + // Matroska `CodecPrivate` are the same bytes, so the two files are one + // stream written twice rather than two. + let sample = + crate::mux::annex_b_to_hvcc(au).ok_or("a coded HEVC unit with no slice in it")?; + if settings.format == Format::Hevc { + let muxer = match muxer { + Some(Muxer::Mkv(mkv)) => mkv, + Some(Muxer::Mp4(_)) => unreachable!("the format picks the muxer once"), + none => { + let hvcc = hevc_params(au)?; + let sound = audio.zip(packets.take()); + let Muxer::Mkv(mkv) = none.insert(Muxer::Mkv(MkvMuxer::create_hevc( + out, + &HevcParams { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + hvcc: &hvcc, + }, + sound, + )?)) else { + unreachable!("just inserted a Matroska muxer") + }; + mkv + } + }; + return muxer.write_frame(&sample, key); + } + let muxer = match muxer { + Some(Muxer::Mp4(mp4)) => mp4, + Some(Muxer::Mkv(_)) => unreachable!("the format picks the muxer once"), + none => { + let hvcc = hevc_params(au)?; + let Muxer::Mp4(mp4) = none.insert(Muxer::Mp4(Mp4Muxer::create_hevc( + out, + &HevcParams { + width: meta.width, + height: meta.height, + frame_rate: meta.frame_rate, + hvcc: &hvcc, + }, + audio, + )?)) else { + unreachable!("just inserted an mp4 muxer") + }; + mp4 + } + }; + return muxer.write_coded_sample(&sample, key); + } if settings.format.is_av1() { // Every AV1 stream opens on a keyframe, and a keyframe carries the // sequence header the track has to declare: an encoder that handed back @@ -1153,7 +1252,7 @@ fn write_video( mp4 } }; - return muxer.write_av1_frame(au, key); + return muxer.write_coded_sample(au, key); } if !crate::mux::has_coded_slice(au) { return Ok(()); @@ -1183,6 +1282,13 @@ fn write_video( muxer.write_video_au(au) } +/// The `hvcC` record of the first coded unit, or the refusal by name. Split out +/// because both HEVC containers ask it in the same words. +fn hevc_params(au: &[u8]) -> crate::Result> { + crate::mux::hvcc_record(au) + .ok_or_else(|| crate::Error::from("the first coded picture carries no HEVC VPS/SPS/PPS")) +} + fn bitrate_for(meta: &VideoMeta) -> u64 { let raw = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate * BITS_PER_PIXEL; (raw as u64).clamp(MIN_BITRATE, MAX_BITRATE) @@ -1219,6 +1325,38 @@ enum Enc { au: Vec, flushed: bool, }, + /// HEVC, intra-only and software only: `encode_idr_intra_au_cropped` is a + /// *stateless* function of one picture, so a batch of frames is coded on as + /// many cores as there are lanes and collected back in order. + Hevc(HevcEnc), +} + +/// The intra HEVC seat. Frames arrive one at a time (the export walk is one +/// picture per timeline frame) and are held until there are [`lanes`] of them, +/// then coded in parallel and queued in **display order** -- fanning out is the +/// only thing that makes a pure-Rust HEVC export bearable (4.30 fps at 1080p on +/// 12 lanes against 0.55 fps on one, measured 2026-08-11), and an export whose +/// frames came back shuffled would be no export at all. +/// +/// ponytail: a batch of padded planes sits in memory (~3 MB a frame at 1080p, +/// so ~37 MB at 12 lanes) and the tail of a timeline is coded on fewer lanes +/// than the middle. Upgrade path is a pipeline that keeps every lane fed from a +/// decoder running ahead of the encoder rather than a batch barrier. +struct HevcEnc { + /// Padded I420 planes waiting for a lane, in display order. + pending: Vec<(Vec, Vec, Vec)>, + /// Coded access units not yet collected, in the same order. + ready: std::collections::VecDeque>, + /// The unit currently lent out, for the reason `Sw` owns one. + au: Vec, + /// The *coded* size: the picture's, rounded up to the 16-sample CTB grid. + width: usize, + height: usize, + /// Luma samples the conformance window crops off the right and the bottom, + /// so a decoder outputs the picture's own size ([`pad_to_ctb`]). + crop: (usize, usize), + qp: i32, + lanes: usize, } impl Enc { @@ -1231,15 +1369,19 @@ impl Enc { Self::Sw { .. } => video_label(Format::Mp4, false), Self::Av1Hw(_) => video_label(Format::Av1, true), Self::Av1Sw { .. } => video_label(Format::Av1, false), + Self::Hevc(_) => video_label(Format::Hevc, false), } } fn open(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { // Which *codec* the picture is, not which container it goes in: both AV1 - // formats run the same encoder. + // formats run the same encoder, and so do both HEVC ones. if settings.format.is_av1() { return Self::open_av1(meta, settings); } + if settings.format.is_hevc() { + return Self::open_hevc(meta, settings); + } // A caller's number goes through the same clamp as the computed one: a // zero bitrate switches the software encoder's lookahead on, which would // break the one-picture-per-call contract `encode` documents below. @@ -1331,6 +1473,53 @@ impl Enc { }) } + /// The intra HEVC seat, software and frame-parallel. There is no hardware + /// half: the plugin encodes H.264 and AV1 and nothing else, which + /// [`hw_seat`] says by refusing to probe one. + /// + /// **Intra-only, deliberately.** The vendored encoder's inter modes code + /// 1080p at 0.81 fps across 12 cores (measured 2026-08-11) -- a minute of + /// timeline in half an hour, which is not an export anybody waits for -- + /// while the intra path does 4.30 fps on the same picture and the same + /// cores. So every frame is an IDR, the file is an intraframe master in the + /// shape of ProRes or DNxHD, and the card says so where a user picks it. + /// + /// The picture is coded **padded** to the 16-sample CTB grid and the SPS + /// crops it back ([`pad_to_ctb`], the vendored conformance-window patch), so + /// 1920x1080 is a legal export rather than a refusal. + fn open_hevc(meta: &VideoMeta, settings: &ExportSettings) -> crate::Result { + // The muxers time by it and the mp4 one wants an exact rational: asked + // here so an impossible rate fails before a frame is coded. + crate::mux::frame_timing(meta.frame_rate)?; + // 4:2:0 addresses its conformance window in *chroma* samples, so an odd + // picture cannot be cropped back to itself -- and an odd dimension has + // no chroma plane of its own to begin with. Named rather than padded to + // something a decoder would then show a column of. + if meta.width % 2 != 0 || meta.height % 2 != 0 { + return Err(format!( + "{}x{} cannot be written as HEVC: 4:2:0 needs even dimensions", + meta.width, meta.height + ) + .into()); + } + let (width, height) = ( + (meta.width as usize).next_multiple_of(CTB), + (meta.height as usize).next_multiple_of(CTB), + ); + let lanes = std::thread::available_parallelism().map_or(1, |n| n.get()); + eprintln!("export encoder: software HEVC intra (oxideav-h265)"); + Ok(Self::Hevc(HevcEnc { + pending: Vec::new(), + ready: std::collections::VecDeque::new(), + au: Vec::new(), + width, + height, + crop: (width - meta.width as usize, height - meta.height as usize), + qp: hevc_qp(meta, settings), + lanes: lanes.min(HEVC_LANES), + })) + } + /// One picture in, at most one access unit out, and whether that unit is one /// a decoder may be started from -- which only the Matroska muxer asks, the /// mp4 one reading its own sync flag off the IDR slice. @@ -1373,6 +1562,23 @@ impl Enc { collect_av1(context, ready)?; Ok(pop_av1(ready, au)) } + Self::Hevc(hevc) => { + hevc.pending.push(pad_to_ctb( + y, + u, + v, + width as usize, + height as usize, + hevc.width, + hevc.height, + )); + if hevc.pending.len() >= hevc.lanes { + hevc.code_batch()?; + } + // Every intra AU is an IDR, so every one of them is a key + // frame -- which is what an intraframe master means. + Ok(pop_hevc(hevc)) + } Self::Hw(hw) => Ok(hw .encode(y, u, v, width, height, false)? .map(|au| (au, false))), @@ -1412,6 +1618,14 @@ impl Enc { } Ok(pop_av1(ready, au)) } + Self::Hevc(hevc) => { + // The tail batch: fewer frames than lanes, coded on as many + // cores as there are frames left. + if !hevc.pending.is_empty() { + hevc.code_batch()?; + } + Ok(pop_hevc(hevc)) + } Self::Hw(hw) => Ok(hw.drain()?.map(|au| (au, false))), Self::Sw { encoder, @@ -1431,6 +1645,103 @@ impl Enc { } } +impl HevcEnc { + /// The whole pending batch, one frame per lane, collected back in the order + /// it went out -- `std::thread::scope`, because the encode borrows the + /// planes rather than copying them again. A panic inside a lane comes back + /// as an error rather than unwinding the export thread. + fn code_batch(&mut self) -> crate::Result<()> { + let (width, height, qp, crop) = (self.width, self.height, self.qp, self.crop); + let coded: Vec>> = std::thread::scope(|scope| { + let lanes: Vec<_> = self + .pending + .iter() + .map(|(y, cb, cr)| { + scope.spawn(move || { + oxideav_h265::encoder::intra::encode_idr_intra_au_cropped( + y, cb, cr, width, height, qp, crop.0, crop.1, + ) + .map(|coded| coded.au) + .map_err(|e| crate::Error::from(format!("HEVC intra encode: {e:?}"))) + }) + }) + .collect(); + lanes + .into_iter() + .map(|lane| { + lane.join() + .unwrap_or_else(|_| Err("an HEVC encode lane panicked".into())) + }) + .collect() + }); + for au in coded { + self.ready.push_back(au?); + } + self.pending.clear(); + Ok(()) + } +} + +/// The oldest coded intra AU, lent out under the same "valid until the next +/// call" contract [`pop_av1`] has. Every one of them is an IDR, so the key flag +/// is not a guess. +fn pop_hevc(hevc: &mut HevcEnc) -> Option<(&[u8], bool)> { + hevc.au = hevc.ready.pop_front()?; + Some((&hevc.au[..], true)) +} + +/// One I420 picture copied onto the padded plane sizes the CTB grid needs, the +/// added rows and columns filled by **replicating the edge** rather than with +/// black: the padding is coded and then cropped away, and a black border would +/// bleed into the last real column through the intra prediction and the +/// transform that straddles it. +fn pad_to_ctb( + y: &[u8], + u: &[u8], + v: &[u8], + width: usize, + height: usize, + padded_w: usize, + padded_h: usize, +) -> (Vec, Vec, Vec) { + let plane = |src: &[u8], w: usize, h: usize, pw: usize, ph: usize| { + let mut out = vec![0u8; pw * ph]; + for row in 0..ph { + let src_row = &src[row.min(h - 1) * w..][..w]; + let dst = &mut out[row * pw..][..pw]; + dst[..w].copy_from_slice(src_row); + dst[w..].fill(src_row[w - 1]); + } + out + }; + ( + plane(y, width, height, padded_w, padded_h), + plane(u, width / 2, height / 2, padded_w / 2, padded_h / 2), + plane(v, width / 2, height / 2, padded_w / 2, padded_h / 2), + ) +} + +/// The quantiser an intra HEVC export codes at, mapped from the *bitrate* row a +/// user picked -- the card has no QP control and this codec has no rate control, +/// so the two are joined by measurement rather than promised to each other. +/// +/// The encoder codes ~0.6 bits per pixel at QP 27 ([`HEVC_BPP_AT_27`], measured +/// on the 720p and 1080p benches to within 4% of each other), and a step of 6 QP +/// is a factor of two in rate, which is the classic HEVC relation. So the QP +/// that would land on a target is `27 + 6 * log2(0.6 / target)` -- and it is +/// clamped, because this is a *quality* dial and not a rate controller: below QP +/// 22 the file grows without a picture to show for it, and past QP 40 an +/// intra-only frame goes blocky in a way no bitrate row asked for. A 1080p30 +/// timeline at the automatic 6.2 Mbps therefore codes at QP 40 and comes out +/// bigger than that, which is what "intra-only, large files" on the format row +/// means: the row buys quality, not a size. +fn hevc_qp(meta: &VideoMeta, settings: &ExportSettings) -> i32 { + let pixels = f64::from(meta.width) * f64::from(meta.height) * meta.frame_rate; + let target = bitrate_of(meta, settings) as f64 / pixels.max(1.0); + let qp = 27.0 + 6.0 * (HEVC_BPP_AT_27 / target.max(f64::MIN_POSITIVE)).log2(); + (qp.round() as i32).clamp(HEVC_QP_MIN, HEVC_QP_MAX) +} + /// Every temporal unit `rav1e` has finished, moved into the queue in display /// order. `NeedMoreData` (send another picture) and `LimitReached` (the flush is /// through) are the two ways it says there is nothing more; `Encoded` means a @@ -1587,4 +1898,100 @@ mod tests { assert_eq!(bitrate_for(&meta(320, 240, 30.0)), MIN_BITRATE, "tiny"); assert_eq!(bitrate_for(&meta(3840, 2160, 60.0)), MAX_BITRATE, "huge"); } + + fn meta(width: u32, height: u32) -> VideoMeta { + VideoMeta { + width, + height, + frame_rate: 30.0, + frame_count: 1, + codec: crate::demux::Codec::H264, + } + } + + /// The bitrate row a user picked, read as the quality tier it is: a higher + /// row is a lower QP, the band is honoured at both ends, and the same + /// picture at the same rate gets the same number whatever its size (the + /// mapping is bits per *pixel*, which is what makes 720p and 1080p one + /// table). + #[test] + fn the_quality_rows_map_onto_quantisers_that_only_go_one_way() { + let at = |width, height, mbps: Option| { + hevc_qp( + &meta(width, height), + &ExportSettings { + bitrate: mbps.map(|m| m * 1_000_000), + ..Default::default() + }, + ) + }; + // 20 Mbps at 1080p30 is 0.32 bits a pixel against the 0.6 measured at + // QP 27, which is just over half: five QP up, and QP is not an + // arithmetic scale, so this is the number the formula gives. + assert_eq!(at(1920, 1080, Some(20)), 32); + // Every step down the card is a step up in QP, never sideways. + let rows: Vec = [20, 12, 8, 4, 2, 1] + .into_iter() + .map(|mbps| at(1920, 1080, Some(mbps))) + .collect(); + assert!( + rows.windows(2).all(|w| w[0] <= w[1]), + "a lower bitrate row must never code at a lower QP: {rows:?}" + ); + assert_eq!(*rows.last().unwrap(), HEVC_QP_MAX, "the floor is clamped"); + // ...and the top of the range is the clamp, not an unbounded number: 20 + // Mbps at 320x240 is 8.7 bits a pixel, which no picture needs. + assert_eq!(at(320, 240, Some(20)), HEVC_QP_MIN); + // The same bits per pixel is the same quantiser at any size: 1080p at + // 20 Mbps and 720p at 8.9 Mbps are one picture quality. + assert_eq!(at(1920, 1080, Some(20)), at(1280, 720, Some(9))); + // The automatic bitrate is 0.1 bpp at every size, so it is one QP + // everywhere -- the honest end of "intra-only, large files": the file + // will be bigger than the row says, and the row buys quality. + assert_eq!(at(1920, 1080, None), at(1280, 720, None)); + } + + /// The padding a non-%16 picture is coded with replicates the edge instead + /// of filling black: the coded rows past the picture carry its last row, so + /// nothing bleeds into the last real line through the intra prediction. + #[test] + fn the_ctb_padding_replicates_the_edge() { + // 6x2 luma, values 1..=12, padded to 8x4 (CTB is 16, so this checks the + // copy itself with numbers small enough to read). + let y: Vec = (1..=12).collect(); + let u: Vec = vec![40, 41, 42]; + let v: Vec = vec![50, 51, 52]; + let (py, pu, pv) = pad_to_ctb(&y, &u, &v, 6, 2, 8, 4); + assert_eq!( + py, + vec![ + 1, 2, 3, 4, 5, 6, 6, 6, // the row, then its last sample twice + 7, 8, 9, 10, 11, 12, 12, 12, // + 7, 8, 9, 10, 11, 12, 12, 12, // the last row, replicated + 7, 8, 9, 10, 11, 12, 12, 12, + ] + ); + // Chroma is half of everything, padded the same way. + assert_eq!(pu, vec![40, 41, 42, 42, 40, 41, 42, 42]); + assert_eq!(pv, vec![50, 51, 52, 52, 50, 51, 52, 52]); + } + + /// An odd picture cannot be cropped back to itself in 4:2:0 -- the + /// conformance window is stated in chroma samples -- so it is refused by + /// name rather than written a column wider than the timeline. + #[test] + fn an_odd_picture_is_refused_an_hevc_export_by_name() { + let settings = ExportSettings { + format: Format::Hevc, + ..Default::default() + }; + let refused = Enc::open(&meta(1919, 1080), &settings) + .err() + .expect("an odd width has no chroma plane") + .to_string(); + assert!(refused.contains("1919x1080"), "{refused}"); + assert!(refused.contains("even"), "{refused}"); + // ...and the even one it neighbours opens. + assert!(Enc::open(&meta(1920, 1080), &settings).is_ok()); + } } diff --git a/crates/engine/src/mux.rs b/crates/engine/src/mux.rs index bc629ac..6d6db49 100644 --- a/crates/engine/src/mux.rs +++ b/crates/engine/src/mux.rs @@ -66,10 +66,11 @@ pub struct Mp4Muxer { writer: Mp4Writer>, frame_duration: u32, has_audio: bool, - /// The `av1C` record an AV1 file's sample entry is patched to carry at - /// [`finish`](Mp4Muxer::finish); `None` for H.264, which the crate spells - /// itself. See [`create_av1`](Mp4Muxer::create_av1). - av1c: Option>, + /// The sample entry an AV1 or HEVC file's is patched into at + /// [`finish`](Mp4Muxer::finish) -- entry type, configuration box type and + /// its payload (`av01`/`av1C`, `hvc1`/`hvcC`). `None` for H.264, which the + /// crate spells itself. See [`create_av1`](Mp4Muxer::create_av1). + entry: Option<([u8; 4], [u8; 4], Vec)>, /// Where the file is, for that patch: the writer owns the handle it wrote /// through and the patch reopens the finished file. path: PathBuf, @@ -129,7 +130,37 @@ impl Mp4Muxer { pps: &[0x68, 0xCE, 0x3C, 0x80], }, audio, - Some(av1c), + Some((*b"av01", *b"av1C", av1c)), + ) + } + + /// ...and the same trick for HEVC, which `mp4 0.14` cannot spell either: + /// the file is written with an `avc1` entry and that entry is rewritten at + /// [`finish`](Mp4Muxer::finish) into the `hvc1` + `hvcC` pair ISO/IEC + /// 14496-15 §8.4.1 asks for -- the record being the very bytes the Matroska + /// file puts in `CodecPrivate`, so the two containers carry one stream. + /// `hvc1` rather than `hev1`: the samples this writes carry no parameter + /// sets (they are dropped into `hvcC`), which is exactly what the `hvc1` + /// name promises a reader. + pub fn create_hevc( + path: &Path, + video: &HevcParams, + audio: Option<&AudioParams>, + ) -> crate::Result { + if video.hvcc.is_empty() { + return Err("no hvcC record for the track's sample entry".into()); + } + Self::open( + path, + &VideoParams { + width: video.width, + height: video.height, + frame_rate: video.frame_rate, + sps: &[0x67, 0x42, 0x00, 0x1E], + pps: &[0x68, 0xCE, 0x3C, 0x80], + }, + audio, + Some((*b"hvc1", *b"hvcC", video.hvcc.to_vec())), ) } @@ -137,7 +168,7 @@ impl Mp4Muxer { path: &Path, video: &VideoParams, audio: Option<&AudioParams>, - av1c: Option>, + entry: Option<([u8; 4], [u8; 4], Vec)>, ) -> crate::Result { if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { return Err(format!("bad frame rate {}", video.frame_rate).into()); @@ -166,8 +197,8 @@ impl Mp4Muxer { compatible_brands: vec![ FourCC::from(*b"isom"), FourCC::from(*b"iso2"), - FourCC::from(match av1c { - Some(_) => *b"av01", + FourCC::from(match &entry { + Some((kind, ..)) => *kind, None => *b"avc1", }), FourCC::from(*b"mp41"), @@ -215,7 +246,7 @@ impl Mp4Muxer { writer, frame_duration, has_audio: audio.is_some(), - av1c, + entry, path: path.to_path_buf(), }) } @@ -237,14 +268,15 @@ impl Mp4Muxer { Ok(()) } - /// One coded picture as an AV1 temporal unit, written verbatim: an mp4 AV1 - /// sample is the low-overhead OBU stream the encoder handed over, exactly as - /// a Matroska block is, so there is nothing to reframe. `key` is the + /// One coded picture already framed the way its sample carries it: an AV1 + /// temporal unit is the low-overhead OBU stream the encoder handed over + /// (nothing to reframe, exactly as a Matroska block holds it), and an HEVC + /// sample is the length-prefixed NALs [`annex_b_to_hvcc`] made. `key` is the /// encoder's own word for a unit a decoder may start on -- an mp4 says it in /// `stss` where Matroska says it in the block flags. - pub fn write_av1_frame(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { + pub fn write_coded_sample(&mut self, obus: &[u8], key: bool) -> crate::Result<()> { if obus.is_empty() { - return Err("an empty AV1 temporal unit".into()); + return Err("an empty coded picture".into()); } self.writer.write_sample( VIDEO_TRACK, @@ -284,32 +316,42 @@ impl Mp4Muxer { pub fn finish(mut self) -> crate::Result<()> { self.writer.write_end()?; let Self { - writer, av1c, path, .. + writer, + entry, + path, + .. } = self; // Not a `drop`: the buffered tail of `moov` has to be on disk before the // patch below reads it back, and a `BufWriter` swallows the error of // flushing it on drop. writer.into_writer().flush()?; - match av1c { - Some(av1c) => patch_av01(&path, &av1c), + match entry { + Some((kind, config_kind, config)) => patch_entry(&path, &kind, &config_kind, &config), None => Ok(()), } } } /// Rewrites the finished file's one video sample entry from the `avc1` the crate -/// wrote into the `av01` + `av1C` an AV1 track declares. Called once, on a -/// complete file, and only for a file [`Mp4Muxer::create_av1`] opened. +/// wrote into the `av01` + `av1C` an AV1 track declares -- or the `hvc1` + +/// `hvcC` an HEVC one does. Called once, on a complete file, and only for a file +/// [`Mp4Muxer::create_av1`] or [`Mp4Muxer::create_hevc`] opened. /// /// `moov` sits after `mdat` (the crate writes it at `write_end`), so this only /// ever rewrites the tail of the file: no sample moves and no chunk offset in /// `co64` changes. The box tree is rebuilt rather than patched in place, which /// is what keeps every ancestor's size right by construction. -fn patch_av01(path: &Path, av1c: &[u8]) -> crate::Result<()> { +fn patch_entry( + path: &Path, + kind: &[u8; 4], + config_kind: &[u8; 4], + config: &[u8], +) -> crate::Result<()> { let mut file = OpenOptions::new().read(true).write(true).open(path)?; let end = file.metadata()?.len(); let (at, payload) = top_level(&mut file, end, b"moov")?.ok_or("no moov box to patch")?; - let patched = swap_av01(&payload, 0, av1c).ok_or("no avc1 sample entry to rewrite as av01")?; + let patched = swap_entry(&payload, 0, kind, config_kind, config) + .ok_or("no avc1 sample entry to rewrite")?; let mut out = Vec::with_capacity(patched.len() + 8); push_box(&mut out, b"moov", &patched); 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"]; /// `None` where this branch holds no such entry -- an audio `trak` is walked /// into and comes back untouched, which is how the *video* track is found /// without being told which id it has. -fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option> { +fn swap_entry( + payload: &[u8], + depth: usize, + want: &[u8; 4], + config_kind: &[u8; 4], + config: &[u8], +) -> Option> { if depth == STSD_PATH.len() { // stsd is a FullBox (4) plus entry_count (4), then the sample entries. let mut out = payload.get(..8)?.to_vec(); @@ -364,18 +412,19 @@ fn swap_av01(payload: &[u8], depth: usize, av1c: &[u8]) -> Option> { return None; } // A `VisualSampleEntry` is 78 bytes of fixed fields (dimensions and all) - // before its codec box, and `av01` carries exactly the same ones -- so - // the header is kept and only the configuration box is swapped. + // before its codec box, and `av01` and `hvc1` carry exactly the same + // ones -- so the header is kept and only the configuration box is + // swapped. let mut swapped = entry.get(..78)?.to_vec(); - push_box(&mut swapped, b"av1C", av1c); - push_box(&mut out, b"av01", &swapped); + push_box(&mut swapped, config_kind, config); + push_box(&mut out, want, &swapped); return Some(out); } let mut out = Vec::with_capacity(payload.len()); let mut done = false; for (kind, child) in crate::demux::boxes(payload) { let patched = match !done && kind == STSD_PATH[depth] { - true => swap_av01(child, depth + 1, av1c), + true => swap_entry(child, depth + 1, want, config_kind, config), false => None, }; match patched { @@ -471,6 +520,18 @@ pub struct Av1Params<'a> { pub config: &'a [u8], } +/// What an HEVC track declares in either container: the `hvcC` record +/// [`hvcc_record`] built out of the encoder's own VPS/SPS/PPS. The dimensions +/// are the *displayed* ones -- the coded picture is padded up to the 16-sample +/// CTB grid and the SPS crops it back with a conformance window, which is the +/// size a decoder outputs and therefore the size the container states. +pub struct HevcParams<'a> { + pub width: u32, + pub height: u32, + pub frame_rate: f64, + pub hvcc: &'a [u8], +} + /// Writes one AV1 video track as Matroska (`.mkv`), and the timeline's AAC /// beside it where there is any: an `A_AAC` track whose `CodecPrivate` is the /// two-byte `AudioSpecificConfig` an mp4's `esds` carries, which is what @@ -528,18 +589,66 @@ impl MkvMuxer { video: &Av1Params, audio: Option<(&AudioParams, Vec)>, ) -> crate::Result { - if !video.frame_rate.is_finite() || video.frame_rate <= 0.0 { - return Err(format!("bad frame rate {}", video.frame_rate).into()); + if video.config.is_empty() { + return Err("no AV1 sequence header for the track's CodecPrivate".into()); } - if video.width == 0 || video.height == 0 { - return Err(format!("bad dimensions {}x{}", video.width, video.height).into()); + let mut av1c = AV1C_HEAD.to_vec(); + av1c.extend_from_slice(video.config); + Self::open( + path, + video.width, + video.height, + video.frame_rate, + b"V_AV1", + &av1c, + audio, + ) + } + + /// The same file with an HEVC track in it: `V_MPEGH/ISO/HEVC`, whose + /// `CodecPrivate` is the very `hvcC` record an mp4 puts in its sample entry + /// ([`hvcc_record`]) -- and whose blocks are therefore length-prefixed NALs + /// like an mp4 sample's, not Annex B. That is what this engine's own reader + /// expects back (`demux`'s Matroska branch parses `CodecPrivate` as `hvcC` + /// and reframes the blocks by the length it states), and what every other + /// Matroska reader expects too. + pub fn create_hevc( + path: &Path, + video: &HevcParams, + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { + if video.hvcc.is_empty() { + return Err("no hvcC record for the track's CodecPrivate".into()); } - let frame_ns = (1e9 / video.frame_rate).round() as u64; - if frame_ns == 0 { - return Err(format!("frame rate {} is too fast to time", video.frame_rate).into()); + Self::open( + path, + video.width, + video.height, + video.frame_rate, + b"V_MPEGH/ISO/HEVC", + video.hvcc, + audio, + ) + } + + fn open( + path: &Path, + width: u32, + height: u32, + frame_rate: f64, + codec_id: &[u8], + codec_private: &[u8], + audio: Option<(&AudioParams, Vec)>, + ) -> crate::Result { + if !frame_rate.is_finite() || frame_rate <= 0.0 { + return Err(format!("bad frame rate {frame_rate}").into()); } - if video.config.is_empty() { - return Err("no AV1 sequence header for the track's CodecPrivate".into()); + if width == 0 || height == 0 { + return Err(format!("bad dimensions {width}x{height}").into()); + } + let frame_ns = (1e9 / frame_rate).round() as u64; + if frame_ns == 0 { + return Err(format!("frame rate {frame_rate} is too fast to time").into()); } let mut head = Vec::new(); @@ -576,14 +685,12 @@ impl MkvMuxer { uint(&mut entry, TRACK_UID, 1); uint(&mut entry, TRACK_TYPE, 1); // video uint(&mut entry, FLAG_LACING, 0); - elem(&mut entry, CODEC_ID, b"V_AV1"); - let mut av1c = AV1C_HEAD.to_vec(); - av1c.extend_from_slice(video.config); - elem(&mut entry, CODEC_PRIVATE, &av1c); + elem(&mut entry, CODEC_ID, codec_id); + elem(&mut entry, CODEC_PRIVATE, codec_private); uint(&mut entry, DEFAULT_DURATION, frame_ns); let mut dims = Vec::new(); - uint(&mut dims, PIXEL_WIDTH, u64::from(video.width)); - uint(&mut dims, PIXEL_HEIGHT, u64::from(video.height)); + uint(&mut dims, PIXEL_WIDTH, u64::from(width)); + uint(&mut dims, PIXEL_HEIGHT, u64::from(height)); elem(&mut entry, VIDEO, &dims); let mut tracks = Vec::new(); elem(&mut tracks, TRACK_ENTRY, &entry); @@ -882,6 +989,91 @@ pub fn parameter_sets(annex_b: &[u8]) -> Option<(&[u8], &[u8])> { Some((sps, pps)) } +/// The `HEVCDecoderConfigurationRecord` an HEVC track declares, built out of the +/// parameter sets the encoder put in its first access unit -- the exact record +/// `demux::parse_hvcc` reads back, which is what makes an export of this +/// project's own something it can re-open. +/// +/// The 22 fixed bytes before the arrays: the 12-byte `profile_tier_level` is +/// copied straight out of the SPS (its first 12 bytes after the two-byte NAL +/// header and the four `sps_video_parameter_set_id`/`sps_max_sub_layers_minus1` +/// /`sps_temporal_id_nesting_flag` bits -- §7.3.2.2 puts the PTL there and the +/// hvcC header states the same fields in the same order), and the rest is what +/// this encoder is: 4:2:0, 8-bit, one temporal layer, 4-byte NAL lengths. Only +/// the *arrays* are read by anything here, but a record whose header lied about +/// the profile would be a file `ffprobe` disagrees with. +/// +/// `None` where the unit carries no VPS, SPS or PPS -- the first coded intra AU +/// always carries all three. +pub fn hvcc_record(annex_b: &[u8]) -> Option> { + let nals = split_annex_b(annex_b); + let of = |kind: u8| nals.iter().copied().find(|n| hevc_nal_type(n) == kind); + let (vps, sps, pps) = (of(HEVC_VPS)?, of(HEVC_SPS)?, of(HEVC_PPS)?); + // The SPS as a decoder reads it: the emulation-prevention bytes the encoder + // escaped it with are not part of the syntax, and a run of zeros in the + // constraint flags is exactly where one lands. + let rbsp = unescape(sps.get(2..)?); + let mut rec = vec![1u8]; // configurationVersion + rec.extend_from_slice(rbsp.get(1..13)?); // profile_tier_level, verbatim + rec.extend_from_slice(&[0xF0, 0x00]); // min_spatial_segmentation_idc = 0 + rec.push(0xFC); // parallelismType = 0 (unknown) + rec.push(0xFC | 1); // chroma_format_idc = 1 (4:2:0) + rec.push(0xF8); // bit_depth_luma_minus8 = 0 + rec.push(0xF8); // bit_depth_chroma_minus8 = 0 + rec.extend_from_slice(&0u16.to_be_bytes()); // avgFrameRate: unstated + // constantFrameRate 0, numTemporalLayers 1, temporalIdNested 1, + // lengthSizeMinusOne 3 -- the same 4-byte prefix `annex_b_to_hvcc` writes. + rec.push(0b00_001_1_11); + rec.push(3); // numOfArrays + for (kind, nal) in [(HEVC_VPS, vps), (HEVC_SPS, sps), (HEVC_PPS, pps)] { + rec.push(0x80 | kind); // array_completeness = 1, NAL_unit_type + rec.extend_from_slice(&1u16.to_be_bytes()); // numNalus + rec.extend_from_slice(&(nal.len() as u16).to_be_bytes()); + rec.extend_from_slice(nal); + } + Some(rec) +} + +/// One HEVC access unit as a sample of both containers: 4-byte length prefixes, +/// parameter sets dropped (they are in the `hvcC`, which is what `hvc1` and a +/// Matroska `CodecPrivate` both promise). `None` where the unit holds no coded +/// slice at all. +pub(crate) fn annex_b_to_hvcc(annex_b: &[u8]) -> Option> { + let mut out = Vec::with_capacity(annex_b.len()); + for nal in split_annex_b(annex_b) { + // 32 VPS, 33 SPS, 34 PPS, 35 AUD -- and everything from 40 up is + // non-VCL padding no decoder needs to start. + if matches!(hevc_nal_type(nal), HEVC_VPS | HEVC_SPS | HEVC_PPS | 35) { + continue; + } + out.extend_from_slice(&(nal.len() as u32).to_be_bytes()); + out.extend_from_slice(nal); + } + (!out.is_empty()).then_some(out) +} + +/// §7.3.1.2 `nal_unit_type`, the six bits after the forbidden_zero_bit. +fn hevc_nal_type(nal: &[u8]) -> u8 { + nal.first().map_or(0xFF, |b| (b >> 1) & 0x3F) +} + +const HEVC_VPS: u8 = 32; +const HEVC_SPS: u8 = 33; +const HEVC_PPS: u8 = 34; + +/// A coded NAL payload back to its RBSP: every `00 00 03` loses the `03` +/// (§7.3.1.1). Only ever asked of an SPS, which is short. +fn unescape(nal: &[u8]) -> Vec { + let mut out = Vec::with_capacity(nal.len()); + for (i, &byte) in nal.iter().enumerate() { + if byte == 3 && i >= 2 && nal[i - 1] == 0 && nal[i - 2] == 0 { + continue; + } + out.push(byte); + } + out +} + /// Whether the unit carries a coded picture (NAL types 1..=5). An encoder that /// buffered instead of coding hands back an empty buffer, and one that emitted /// only parameter sets has no sample to write -- both are for the caller to skip @@ -1322,9 +1514,9 @@ mod tests { }), ) .unwrap(); - muxer.write_av1_frame(&key, true).unwrap(); - muxer.write_av1_frame(&inter, false).unwrap(); - muxer.write_av1_frame(&inter, false).unwrap(); + muxer.write_coded_sample(&key, true).unwrap(); + muxer.write_coded_sample(&inter, false).unwrap(); + muxer.write_coded_sample(&inter, false).unwrap(); for packet in &packets { muxer.write_audio_packet(&packet.bytes).unwrap(); } diff --git a/crates/engine/tests/backends.rs b/crates/engine/tests/backends.rs index 0a995e0..bc24508 100644 --- a/crates/engine/tests/backends.rs +++ b/crates/engine/tests/backends.rs @@ -106,6 +106,11 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { (Format::Mp4, "mp4"), (Format::Av1, "mkv"), (Format::Av1Mp4, "mp4"), + // Both HEVC containers, whose seat is software whatever the box has: + // the plugin encodes H.264 and AV1 and no HEVC, so a card that offered + // a hardware seat here would be promising one that cannot exist. + (Format::Hevc, "mkv"), + (Format::HevcMp4, "mp4"), ] { let settings = ExportSettings { format, @@ -145,6 +150,12 @@ fn the_planned_encoders_are_the_ones_the_job_opens() { // carries the timeline's audio now, so a line that said nothing about // it would be the old picture-only lie in a new place. assert!(planned.contains("AAC"), "{ext}: {planned}"); + if matches!(format, Format::Hevc | Format::HevcMp4) { + assert!( + planned.contains("oxideav-h265 intra"), + "{ext}: an HEVC job names the intra encoder that writes it: {planned}" + ); + } } } diff --git a/crates/engine/tests/hevc_export.rs b/crates/engine/tests/hevc_export.rs new file mode 100644 index 0000000..0ae31bb --- /dev/null +++ b/crates/engine/tests/hevc_export.rs @@ -0,0 +1,298 @@ +//! HEVC export: the codec this project could read and not write until OxideAV's +//! pure-Rust H.265 gave it an encoder -- an **intra-only** one, every frame a +//! self-contained IDR, which is the only shape of it fast enough to wait for +//! (the inter modes code 1080p at 0.81 fps across 12 cores; the intra path does +//! 4.30 fps on the same picture). +//! +//! Two things are under test here and neither of them is the encoder's picture +//! quality: that the *containers* say HEVC in the words their readers expect +//! (this project's own demuxer, and ffprobe where it is installed), and that a +//! picture whose height is not a multiple of the 16-sample coding tree block -- +//! 1080, the resolution -- comes back out at its own size, coded padded to 1088 +//! and cropped by the SPS conformance window. +//! +//! ```text +//! cargo test -p engine --release --test hevc_export -- --test-threads=1 +//! ``` +//! +//! Release, always: a debug intra encode is minutes a frame. The 1080p twin +//! needs the `ffmpeg` CLI to make its source and `ffprobe` to read the coded +//! size back; without them it says so and passes, exactly as the hardware tests +//! here do. + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::{Duration, Instant}; + +use engine::demux::{Codec, Demuxer}; +use engine::export::{ExportSettings, Format}; +use engine::{AudioSession, PlaybackSession}; + +fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +fn out_path(name: &str, ext: &str) -> PathBuf { + let path = std::env::temp_dir().join(format!("ve_hevc_{name}_{}.{ext}", std::process::id())); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(format!("{}.part", path.display())); + path +} + +/// Runs an export to completion, failing on the deadline rather than hanging. +fn export(session: &PlaybackSession, out: &Path, format: Format) { + let settings = ExportSettings { + format, + ..Default::default() + }; + let handle = session.export_to_with(out, &settings); + let started = Instant::now(); + while !handle.is_finished() { + assert!( + started.elapsed() < Duration::from_secs(300), + "the export did not finish in 300 s" + ); + std::thread::sleep(Duration::from_millis(20)); + } + handle + .result() + .expect("an outcome") + .expect("an HEVC export"); + assert_eq!(handle.progress(), 1.0, "finished at full progress"); +} + +/// Two frames of the A/V fixture: what is under test is the wiring from the +/// format to the muxer, not how long an encoder takes. +fn two_frames() -> PlaybackSession { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + assert!(session.cut_at(2.0 / 30.0), "cut two frames off the front"); + assert!(session.delete_clip(engine::project::Lane::V1, 1)); + session +} + +/// The container half, in both boxes: an HEVC export is read back as HEVC, at +/// the size and the count it was written at, with the timeline's sound beside +/// it. The `hvcC` record this writes is the one `demux` parses -- Matroska in +/// `CodecPrivate`, mp4 in the sample entry -- so this is where the writer and +/// the reader either agree or do not. +#[test] +fn an_hevc_export_reopens_through_our_own_demuxer_in_either_container() { + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { + let session = two_frames(); + let out = out_path("container", ext); + export(&session, &out, format); + + let (meta, mut demuxer) = Demuxer::open(&out).expect("reopen the export"); + assert_eq!(meta.codec, Codec::Hevc, "{ext}: an HEVC export is HEVC"); + assert_eq!((meta.width, meta.height), (1280, 720), "{ext}"); + assert_eq!(meta.frame_count, 2, "{ext}: every timeline frame is there"); + // Every access unit comes back, and every one of them is a sync point: + // that is what intra-only means, and it is what makes any frame of the + // file a cut point. + let mut count = 0; + while demuxer.next_access_unit().expect("read").is_some() { + count += 1; + } + assert_eq!(count, 2, "{ext}: every coded picture comes back out"); + assert_eq!( + demuxer.seek_to_sync_at_or_before(1), + 1, + "{ext}: an intra-only file syncs on every frame" + ); + + // ...and the sound with it, through the reader an import opens it by. + let (audio, chunks) = AudioSession::open(&out) + .expect("reopen for its sound") + .expect("an HEVC export has an audio track"); + let samples: Vec = chunks.into_iter().flat_map(|c| c.samples).collect(); + let rms = (samples.iter().map(|s| s * s).sum::() / samples.len().max(1) as f32).sqrt(); + eprintln!( + "{ext}: {} Hz x{}, rms {rms:.4}, {} bytes", + audio.sample_rate, + audio.channels, + std::fs::metadata(&out).unwrap().len() + ); + assert!(rms > 0.001, "{ext}: the sound is in the file (rms {rms})"); + std::fs::remove_file(&out).unwrap(); + } +} + +/// The %16 half, and the reason the vendored encoder carries a patch at all: +/// 1080 is not a multiple of the 16-sample CTB, so the picture is coded at +/// 1920x1088 and the SPS crops it back with a §7.4.3.2.1 conformance window. +/// ffprobe is what says whether that worked -- it reads the *bitstream*, not +/// the container's own claim -- and ffmpeg decoding the file without a +/// complaint is what says the stream is legal. +#[test] +fn a_1080p_export_states_1920x1080_through_the_conformance_window() { + let Some(source) = fixture_1080p() else { + eprintln!("no ffmpeg: skipping the 1080p conformance-window twin"); + return; + }; + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { + let mut session = PlaybackSession::open(&source).expect("open the 1080p fixture"); + assert!(session.cut_at(2.0 / 30.0)); + assert!(session.delete_clip(engine::project::Lane::V1, 1)); + let out = out_path("1080p", ext); + export(&session, &out, format); + + // The container's own claim first: this project's reader. + let (meta, _) = Demuxer::open(&out).expect("reopen the 1080p export"); + assert_eq!((meta.width, meta.height), (1920, 1080), "{ext}"); + + // ...and the coded size, out of the SPS, by a reader that is not ours. + let probed = probe(&out); + assert_eq!( + probed.as_deref(), + Some("hevc,1920,1080"), + "{ext}: ffprobe reads the cropped size out of the bitstream" + ); + // ...and the whole file decoded, with ffmpeg's own stderr as the test: + // a stream a decoder complains about is not an export. + let decoded = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(&out) + .args(["-f", "null", "-"]) + .output() + .expect("run ffmpeg"); + let complaints = String::from_utf8_lossy(&decoded.stderr); + assert!( + decoded.status.success() && complaints.is_empty(), + "{ext}: ffmpeg complained: {complaints}" + ); + std::fs::remove_file(&out).unwrap(); + } + let _ = std::fs::remove_file(&source); +} + +/// The loop closed where it matters to a user: the file this wrote is opened +/// again *by edith*, picture and all. HEVC has no software decoder here at all, +/// so the way back in is the plugin -- which is what makes this the twin that +/// needs one, and what makes the test above (the containers, read by the +/// demuxer) the one that does not. +#[test] +#[ignore = "needs libengine_hw.so and a VA-API driver with an HEVC entrypoint"] +fn an_hevc_export_decodes_back_into_pictures_through_edith() { + for (format, ext) in [(Format::Hevc, "mkv"), (Format::HevcMp4, "mp4")] { + let session = two_frames(); + let out = out_path("roundtrip", ext); + export(&session, &out, format); + + let (meta, frames) = engine::DecodeSession::open(&out).expect("decode the export"); + assert_eq!(meta.codec, Codec::Hevc, "{ext}"); + let frames: Vec<_> = frames.into_iter().collect(); + assert_eq!(frames.len(), 2, "{ext}: every written frame decodes back"); + // The picture is the fixture's colour pattern, not black: a conformance + // window read wrong would show as a shifted or empty picture. + for (i, frame) in frames.iter().enumerate() { + assert_eq!((frame.width, frame.height), (1280, 720), "{ext} frame {i}"); + assert!( + frame.bgra.iter().any(|&p| p > 32), + "{ext} frame {i} carries picture" + ); + } + std::fs::remove_file(&out).unwrap(); + } +} + +/// An audio-only timeline has no picture to code, and an HEVC export says so by +/// name exactly as the mp4 and AV1 ones do -- and writes nothing. +#[test] +fn an_audio_only_timeline_is_refused_an_hevc_export_by_name() { + let session = PlaybackSession::open(asset("test_tone.wav")).expect("open the tone"); + let out = out_path("refused", "mkv"); + let settings = ExportSettings { + format: Format::Hevc, + ..Default::default() + }; + let handle = session.export_to_with(&out, &settings); + while !handle.is_finished() { + std::thread::sleep(Duration::from_millis(10)); + } + let refused = handle + .result() + .expect("an outcome") + .expect_err("an audio-only timeline has no picture to code") + .to_string(); + assert!(refused.contains("no picture"), "{refused}"); + assert!(refused.contains("HEVC"), "{refused}"); + assert!(!out.exists(), "nothing is written for a refusal"); +} + +/// A cancelled HEVC export leaves nothing behind -- not the file and not the +/// `.part` the worker was writing. An intra-only export of a whole fixture is +/// long enough to catch mid-flight, and the frame loop checks for a cancel +/// every picture, so this stops in a frame or two rather than at the end. +#[test] +fn a_cancelled_hevc_export_leaves_no_file_behind() { + let session = PlaybackSession::open(asset("test_av.mp4")).expect("open test_av.mp4"); + let out = out_path("cancelled", "mkv"); + let settings = ExportSettings { + format: Format::Hevc, + ..Default::default() + }; + let handle = session.export_to_with(&out, &settings); + handle.cancel(); + let started = Instant::now(); + while !handle.is_finished() { + assert!(started.elapsed() < Duration::from_secs(60), "cancel hung"); + std::thread::sleep(Duration::from_millis(20)); + } + let stopped = handle + .result() + .expect("an outcome") + .expect_err("a cancelled export is an error"); + assert!(stopped.to_string().contains("cancelled"), "{stopped}"); + assert!(!out.exists(), "no output for a cancelled export"); + assert!( + !PathBuf::from(format!("{}.part", out.display())).exists(), + "no partial file either" + ); +} + +/// `codec,width,height` of the file's video stream as ffprobe reads it, or +/// `None` where ffprobe is not installed. +fn probe(path: &Path) -> Option { + let out = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "v:0", + "-show_entries", + "stream=codec_name,width,height", + "-of", + "csv=p=0", + ]) + .arg(path) + .output() + .ok()?; + Some(String::from_utf8_lossy(&out.stdout).trim().to_string()) +} + +/// A two-second 1920x1080 H.264 fixture in the temp directory -- the assets are +/// all 720p, which is a multiple of 16 in both directions and would leave the +/// crop path untested. `None` where ffmpeg is not installed. +fn fixture_1080p() -> Option { + let path = out_path("source1080", "mp4"); + let made = Command::new("ffmpeg") + .args([ + "-y", + "-f", + "lavfi", + "-i", + "testsrc2=size=1920x1080:rate=30:duration=1", + "-c:v", + "libx264", + "-profile:v", + "baseline", + "-pix_fmt", + "yuv420p", + ]) + .arg(&path) + .output() + .ok()?; + made.status.success().then_some(path) +} diff --git a/vendor/oxideav-h265/Cargo.toml b/vendor/oxideav-h265/Cargo.toml new file mode 100644 index 0000000..0326fb4 --- /dev/null +++ b/vendor/oxideav-h265/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "oxideav-h265" +version = "0.0.9" +edition = "2021" +rust-version = "1.80" +license = "MIT" +repository = "https://github.com/OxideAV/oxideav-h265" +authors = ["Mark Karpeles"] +description = "Pure-Rust H.265 / HEVC (ITU-T H.265 | ISO/IEC 23008-2) bitstream parser + decoder scaffold for oxideav" + +readme = "README.md" +homepage = "https://github.com/OxideAV/oxideav-h265" +keywords = ["multimedia", "video", "h265", "hevc", "codec"] +categories = ["multimedia::encoding", "multimedia::video"] + +[dependencies] +oxideav-core = "0.1" diff --git a/vendor/oxideav-h265/LICENSE b/vendor/oxideav-h265/LICENSE new file mode 100644 index 0000000..ffe2468 --- /dev/null +++ b/vendor/oxideav-h265/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Karpelès Lab Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/vendor/oxideav-h265/README.md b/vendor/oxideav-h265/README.md new file mode 100644 index 0000000..bc78fe4 --- /dev/null +++ b/vendor/oxideav-h265/README.md @@ -0,0 +1,243 @@ +# oxideav-h265 + +[![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) + +A pure-Rust H.265 / HEVC video codec for the +[oxideav](https://github.com/OxideAV/oxideav) framework, built +clean-room against ITU-T Recommendation H.265 | ISO/IEC 23008-2. + +## Status + +**Decoder: end to end.** Every Annex B bitstream in the staged +16-fixture conformance corpus decodes byte-exact to its expected YUV +through the whole-bitstream driver (`decode_annexb_sequence` / +`SequenceDecoder`) and the `oxideav_core::Decoder` registry entry +(`make_decoder`, ids `"h265"` / `"hevc"`, `hvc1` / `hev1` / `HEVC` +FourCCs, MP4 ObjectTypeIndication, Matroska tag) — plus self-built +conformance pins for the features the corpus lacks (rounds 413 / 416: +RDPCM, palette, cross-component prediction, adaptive colour +transform, intra block copy), and a 37-stream black-box tool-axis +sweep (round 410) held byte-exact by nine embedded pins. Against the +staged **official JCT-VC RExt / SCC conformance corpus** (61 +decodable bitstreams with published output digests, +`docs/video/h265/conformance/`), 26 streams decode byte-exact +(round 437; docs-gated pins in `tests/conformance_official.rs`) — +including the transform-skip-context, wavefronts-inside-tiles / +aligned-bypass / high-throughput, persistent-Rice-seeded, +Monochrome 8/12-bit, Main 4:2:2 10 and 8-bit +extended-precision-intra families. Coverage: + +* intra pictures at every staged geometry / CTB size (16 / 32 / 64) + and QP extreme (slice QP 1 and 45), with SAO on and off; +* multi-picture sequences: all-intra IDR runs, an IDR+P pair, and an + eight-picture I/P/B pyramid with two reference lists, temporal MVP, + AMVP MVDs, skip/merge CUs and POC output reordering; +* Main10 and the 4:2:2 / 4:4:4 10-bit Range-Extensions streams; +* multi-CTU slices, four-independent-slice pictures, dependent slice + segments (§9.3.2.4/.5 `TableStateIdxDs` context carry + §7.4.7.1 + header inheritance), per-slice loop-filter-across flags, and + `entropy_coding_sync_enabled_flag` (WPP) streams with per-row + entry-point substreams; +* **true tiles**: the staged `true-tiles-2x2` fixture (2×2 uniform + grid, one slice per tile, `loop_filter_across_tiles == 0`) decodes + byte-exact, and multi-tile SINGLE-slice streams work end to end — + §7.3.8.1 tile-boundary subsets (`end_of_subset_one_bit` + byte + alignment), §9.3.2.2 per-tile CABAC re-initialization, tile-relative + WPP row conditions, §8.6.1 per-tile `qPY_PREV` resets; +* §8.5.3.3.4.3 explicit weighted prediction (P uni and B uni/bi, with + non-default per-slice weights / offsets / denominators); +* B pyramids / temporal layers / open-GOP CRA + leading pictures / + RADL streams (a bi-predicted reference B as the §8.5.3.2.9 + collocated picture), §7.4.5 scaling lists (default + explicit, all + TB sizes, intra + inter), §8.4.4.2.3 strong intra smoothing, + §8.4.4.2.1 constrained intra prediction, §7.3.8.11 transform skip, + rectangular/AMP partitions with deep inter RQTs (§7.3.8.10 deferred + chroma), WPP combined with multiple slices per picture, and + 4:2:2 stacked chroma halves (per-half cbf gating and placement); +* §7.3.8.7 PCM coding units, incl. the §8.7.2.5.4 / §8.7.3.1 + loop-filter suppression (`pcm_loop_filter_disabled_flag`, and + transquant-bypass CUs); +* range-extension RDPCM (§8.6.5 implicit intra + explicit inter + directional residual modification) and SCC **palette mode** + (§7.3.8.13 parse incl. the predictor-palette machinery with WPP / + dependent-slice synchronization, §8.4.4.2.7 reconstruction with + transpose and bypass / quantized escapes) — pinned by self-built + conformance streams (`tests/fixture_bytes/r413-*.hevc`), the + implicit-RDPCM stream byte-exact against a black-box reference + decode; +* the Rext/SCC application tail: §8.6.6 **cross-component + prediction** (eq. 8-324 applied on the intra and inter residual + paths, cbf-clear chroma blocks included), §8.6.8 **adaptive colour + transform** (the §8.6.8.2 lifting inverse with ACT-adjusted + quantization, eqs 8-287/8-288/8-291), and **intra block copy** + (current-picture referencing: the §8.3.4 currPic list append, + `use_integer_mv_flag`, the eqs 8-98..8-101 / 8-124..8-125 integer + MV paths, the eqs 8-102/8-103 reduction, prediction from the + pre-filter reconstruction) — pinned by self-built conformance + streams (`tests/fixture_bytes/r416-*.hevc`), the CCP stream + byte-exact against a black-box reference decode (the surveyed + reference decoder rejects SCC streams outright, so the ACT / IBC + pins are decoder-pins); +* both transport forms: Annex B extradata/packets AND `hvcC` + (`HEVCDecoderConfigurationRecord`, ISO/IEC 14496-15 §8.3.3.1) + extradata with length-prefixed packets. + +**Encoder: intra + low-delay inter + hierarchical-B GOPs with AMP +and in-loop filters, registered.** `make_encoder` / `H265Encoder` +with three modes: + +* `mode = "inter"` (`qp` 0..=51, `gop` IDR period, `bslices`, `amp`, + `pyramid`) — low-delay `IDR, P, P, …` / `IDR, B, B, …` GOPs + (`encoder::inter::LowDelayPEncoder`, one frame in / one AU out) or + dyadic **hierarchical-B pyramids** + (`encoder::pyramid::PyramidEncoder`, `pyramid = 2/4/8/16`): + per-CTU **skip / merge / AMVP / two-PU-partition / intra** + decisions under an SSD + λ·rate heuristic, with **two active + reference pictures** on the low-delay path (POC − 1 / POC − 2, + `ref_idx_l0` signalled). Motion candidates are resolved through + the crate's own DECODE-side §8.5.3.2 merge/AMVP derivation against + the in-progress motion field (§6.4.2 availability included), + motion estimation is a seeded greedy integer diamond plus + half-/quarter-pel refinement against the crate's §8.5.3.3.3 + interpolation, two-PU CUs carry the §7.4.9.8 forced depth-1 RQT, + and a `pred_mode_flag == 1` intra fallback rescues scene changes. + The **AMP configuration** (`amp` option / `with_amp`) moves the + stream to `MinCbSizeY == 8` + `amp_enabled_flag == 1` (explicit + `split_cu_flag`, the Table 9-45 big-CU `part_mode` column) and + elects `PART_2NxnU / PART_2NxnD / PART_nLx2N / PART_nRx2N` + alongside the symmetric shapes — on quarter-offset motion-boundary + content the shapes buy **−20 to −29 % bytes at equal PSNR**. The + **pyramid** codes each mini-GOP out of display order (next anchor + as P first, then the midpoint B recursion with the past boundary + on `RefPicList0` and the FUTURE boundary on `RefPicList1`), + signals per-slice negative + positive short-term RPS with + `sps_max_num_reorder_pics = log2(gop)`, allocates rate by + per-layer QP offsets, and searches uni-L0 / uni-L1 / **bi AMVP** + per PU (`inter_pred_idc` `PRED_L0/L1/BI` all emitted); on a + noisy-pan clip the GOP-8 pyramid takes **−11.5 % bytes** vs the + low-delay chain at qp 27. Every stream decodes **bit-exact** to + the encoder reconstruction through this crate's decoder AND a + black-box reference decoder (multi-QP, multi-shape sweeps; golden + GOP / AMP / pyramid / composition streams CI-pinned). Per-frame + `FrameStats` expose the skip/merge/AMVP/intra/bi/rect/amp/ref1 + decisions. +* `mode = "intra"` — per-CTU §8.4 intra prediction over the + encoder's own reconstruction (all 35 modes, per-CTB `PART_2Nx2N` + vs `PART_NxN` rate-distortion decision with per-PB modes, §8.4.2 + MPM signalling, mode-dependent scans), forward DCT-II + reciprocal + quantization, full §7.3.8 syntax through the bin-exact §7.3.8.11 + residual encoder (golden interop stream CI-pinned). +* `mode = "pcm"` (default) — the lossless PCM-IDR bootstrap + (every CTB a 16×16 PCM CU; options for dependent segments, + multi-slice plans, deblocking, band / edge SAO syntax, and true + multi-tile single-slice pictures with §7.4.7.1 entry points). + +Both coding modes accept the §8.7 **in-loop filters** (`deblock` / +`sao` codec options, `LoopFilterCfg` on the direct APIs): the encoder +reconstructs through its own decode-side §8.7.2 deblocking (per-slice +election over off + a {−2, 0, 2}² β/tC-offset sweep, signalled via +the §7.3.6.1 override group) and §8.7.3 SAO (per-CTB statistics-driven band / edge +offset estimation with merge-left/up pricing, every candidate +measured with the decoder's own apply, `encode_sao_ctb` the bin-exact +§7.3.8.3 dual of the parse) — so the filtered pictures its references +and outputs hold are exactly a conforming decoder's. Filtered P/B +GOPs across a 72-configuration sweep decode byte-exact through a +black-box reference decoder (three golden filtered streams +CI-pinned); on the interop clip the filters buy up to +1.5 dB luma +PSNR at equal rate. + +4:2:0 8-bit, dimensions multiples of 16. + +## What's implemented + +* **Whole-bitstream decode driver** (`sequence`) — Annex B demux → + SPS/PPS activation → §7.3.6.1 slice headers (independent and + dependent segments) → the §7.3.8.1 CTU loop (tile-scan addressing, + per-slice CABAC init, the §9.3.2.4/.5 WPP and dependent-segment + context storage/sync, WPP substreams via the §7.4.7.1 entry + points) → picture reconstruction → §8.3.1..§8.3.5 reference + cycle → output reorder. Tile-scan CTU addressing with §9.3.2.2 + per-tile context re-initialization and entry-point subsets shared + with WPP. +* **Registry codec** (`decoder` / `encoder`) — the + `oxideav_core::Decoder` + `Encoder` contracts: Annex B or + hvcC/length-prefixed packets in, output-order `VideoFrame`s out + (reorder queue bounded by `sps_max_num_reorder_pics`, packet-PTS + re-attachment, flush-then-`Eof`); frames in, IDR keyframe packets + out (`mode = "pcm"` lossless or `mode = "intra"` at a chosen QP). + `make_decoder` / `make_encoder` are the direct factory endpoints. +* **Headers** — VPS / SPS / PPS (§7.3.2, incl. range + SCC extension + bodies), VUI + HRD (§E.2), slice segment headers (§7.3.6, all slice + types, RPS forms, `ref_pic_lists_modification()`, + `pred_weight_table()`, entry points incl. dependent segments), + §7.4.8 RPS materialization, scaling lists (§7.3.4 / §7.4.5), and + the `hvcC` record (`hvcc`, ISO/IEC 14496-15 §8.3.3.1). +* **CABAC, both directions** — the §9.3 decode engine and the §9.3.5 + encode engine (decision / bypass / terminate + flush, PCM + align-and-reinit), per-syntax-element binarizations (§9.3.4.2), the + complete §7.3.8 decode syntax tree, and the write-side §7.3.8.11 + `residual_coding( )` dual (`encoder::residual`, differential-tested + to identical levels + context evolution). +* **Reconstruction** — §8.4 intra prediction (all 35 modes), §8.4.1 + PCM sample write-back, §8.5 inter prediction (merge / MVP / + temporal candidates with the §8.5.3.2.3 raw-availability redundancy + gates, §8.5.3.3.3 interpolation, §8.5.3.3.4.2 default AND + §8.5.3.3.4.3 explicit weighted combines with the §7.4.7.3 table + resolution), §8.6 dequant / inverse transform, §8.6.1 per-QG QP + derivation. +* **In-loop filters** — §8.7.2 deblocking and §8.7.3 SAO with + per-slice `slice_loop_filter_across_slices_enabled_flag` gates + (deblocking per the current CU's slice; SAO per the §8.7.3.2 + directional later-slice rule) and the PCM / transquant-bypass + sample suppression (`NoFilterMap`). +* **Reference machinery** — §8.3.1 POC, §8.3.2 RPS marking, §8.3.4 + reference lists, §8.3.5 collocated picture, the DPB, and the + per-picture decode cycle threading motion fields for temporal MVP. + +Thirty-six embedded-fixture regression pins (the 17-stream staged +corpus incl. true tiles + self-built weighted-prediction, +per-slice-loop-filter, hvcC, golden-intra-interop, golden-P-GOP +interop, the round-431 AMP / pyramid / composition interop pins, and +the nine round-410 tool-axis conformance pins), lossless PCM / +exact-reconstruction intra / bit-exact low-delay- and +hierarchical-B-GOP encoder↔decoder roundtrips at multiple +geometries / QPs / partitions / slice types, and ~930 unit tests. + +## Not yet implemented + +* Larger encoder CTB sizes, deeper encoder RQTs / coding quadtrees + (the AMP configuration codes 16x16 CUs above an 8x8 MinCb, but + never splits), 4x4-luma DST TUs, encoder temporal MVP, more than + one active reference per list on the pyramid path, and adaptive + (non-dyadic) GOP structures. +* Non-uniform (`uniform_spacing_flag == 0`) tile-grid *encoding* + (decode side is implemented). +* Known corner: on the §8.7.3.2 SAO cross-slice neighbour rule with + heterogeneous per-slice flags, a black-box reference decoder + consults the current sample's slice flag where the spec text (both + 08/2021 and 01/2026 editions) names the later (decode-order) + slice's flag; this implementation follows the spec text. +* Known corner (RDPCM, spec text followed): §8.4.4.2.6 sets + `disableIntraBoundaryFilter` when implicit RDPCM combines with + transquant bypass, suppressing the mode-10/26 edge filters — a + black-box reference decoder applies those filters regardless. + (The r413 note claiming a reference deviation on explicit-RDPCM + *vertical* blocks is retired: the official `ExplicitRdpcm_A` + conformance stream matches the black-box decode exactly, this + crate's luma decode agrees byte-for-byte, and the remaining + divergence is an unrelated ±1 chroma artifact on isolated rows, + still under investigation.) +* Official-corpus families not yet byte-exact: the 4:4:4 + multi-tool `GENERAL_*_444` / `WAVETILES` / `QMATRIX` parse + desync (mid-picture, first reproduces in a busy 4:4:4 intra CTB), + 16-bit extended-precision reconstruction (the 8-bit + extended-precision streams pass; 10/12/16-bit diverge on their + first picture), unequal luma/chroma bit depths (first divergence + at frame 4), the official CCP / SAO-offset-scale / persistent-Rice + single-stream anchors, and most SCC streams (palette-heavy parse + still desyncs mid-slice; two streams decode all 33 frames with + subtle reconstruction deltas). + +## License + +MIT — see [LICENSE](./LICENSE). diff --git a/vendor/oxideav-h265/src/availability.rs b/vendor/oxideav-h265/src/availability.rs new file mode 100644 index 0000000..0c72b9d --- /dev/null +++ b/vendor/oxideav-h265/src/availability.rs @@ -0,0 +1,569 @@ +//! §6.4 availability processes + the §6.5.1 / §6.5.2 picture-level +//! scanning conversions they depend on. +//! +//! Intra (and, later, inter) sample prediction asks, for each candidate +//! neighbour location `( xNbY, yNbY )`, whether that neighbour is +//! *available for prediction* — i.e. it lies inside the picture, has +//! already been decoded in the current decoding order, and sits in the +//! same slice segment and tile as the current block. ITU-T Rec. H.265 +//! §6.4.1 answers that question, and it does so in terms of a +//! *minimum-transform-block address in z-scan order*, `MinTbAddrZs`. +//! +//! `MinTbAddrZs` (§6.5.2) in turn is built from `CtbAddrRsToTs` +//! (§6.5.1) — the CTB raster-scan ↔ tile-scan address conversion that +//! folds the picture's tile layout into the decoding order. So this +//! module implements three layers, bottom-up: +//! +//! * [`PictureTiling`] — §6.5.1. From the picture geometry in CTBs and +//! the §7.3.2.3.1 tile-partitioning parameters it derives `colWidth` +//! / `rowHeight` (eqs. 6-3 / 6-4), `colBd` / `rowBd` (eqs. 6-5 / +//! 6-6), `CtbAddrRsToTs` / `CtbAddrTsToRs` (eqs. 6-7 / 6-8), and +//! `TileId` (eq. 6-9). +//! * [`PictureTiling::min_tb_addr_zs`] — §6.5.2. The +//! `MinTbAddrZs[ x ][ y ]` array (eq. 6-10) mapping a minimum-block +//! `( x, y )` to its z-scan address, interleaving the within-CTB +//! Morton (z) order with the tile-scan CTB order. +//! * [`PictureTiling::z_scan_availability`] — §6.4.1, and +//! [`PictureTiling::prediction_block_availability`] — §6.4.2. +//! +//! ## Scope +//! +//! The numerics are self-contained. The caller supplies the picture +//! geometry (in CTBs and in luma samples), the `Log2SizeY` shifts, the +//! tile parameters from the active PPS, and a `slice_addr_rs` lookup +//! that maps a CTB raster address to the `SliceAddrRs` of the slice +//! segment that owns it (§6.4.1's slice-boundary test). For §6.4.2 the +//! caller additionally supplies a `CuPredMode` lookup (the final +//! `MODE_INTRA` masking step). Building those lookups is the slice-data +//! walk's responsibility; this module starts at the geometry and stops +//! at `availableN`. + +/// `CuPredMode` value `MODE_INTRA` — used by the §6.4.2 final masking +/// step. Mirrors the Table 7-10 enumeration without depending on the +/// slice module's richer type. +pub const MODE_INTRA: u8 = 1; + +/// Errors from constructing a [`PictureTiling`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum AvailabilityError { + /// A geometry input was zero where the spec requires a positive + /// value (`PicWidthInCtbsY` / `PicHeightInCtbsY` must be ≥ 1). + ZeroGeometry { + /// Name of the offending field. + field: &'static str, + }, + /// `CtbLog2SizeY` is smaller than `MinTbLog2SizeY`, which would make + /// the §6.5.2 `( CtbLog2SizeY − MinTbLog2SizeY )` shift negative. + InvalidLog2Sizes { + /// `CtbLog2SizeY`. + ctb_log2: u32, + /// `MinTbLog2SizeY`. + min_tb_log2: u32, + }, + /// The explicit (`uniform_spacing_flag == 0`) tile-size array had a + /// length other than the required `num_tile_*_minus1`. + TileArrayLength { + /// Name of the offending array. + field: &'static str, + /// Length the spec requires. + expected: usize, + /// Length that was supplied. + got: usize, + }, + /// An explicit tile column/row was wider/taller than the picture, so + /// the implied last tile would have a non-positive size. + TileOverflow { + /// `"column"` or `"row"`. + dimension: &'static str, + }, +} + +impl core::fmt::Display for AvailabilityError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::ZeroGeometry { field } => { + write!(f, "picture geometry field {field} must be positive") + } + Self::InvalidLog2Sizes { + ctb_log2, + min_tb_log2, + } => write!( + f, + "CtbLog2SizeY ({ctb_log2}) must be >= MinTbLog2SizeY ({min_tb_log2})" + ), + Self::TileArrayLength { + field, + expected, + got, + } => write!(f, "tile array {field} length {got} != expected {expected}"), + Self::TileOverflow { dimension } => { + write!(f, "explicit tile {dimension} sizes overflow the picture") + } + } + } +} + +impl std::error::Error for AvailabilityError {} + +/// The §7.3.2.3.1 tile-partitioning parameters needed to build the +/// CTB-scan conversion, as carried by the active PPS. +/// +/// When `tiles_enabled_flag == 0` the picture is a single tile; pass +/// [`TilingParams::single_tile`] (one column, one row). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TilingParams { + /// `num_tile_columns_minus1` — the number of tile columns is this + /// plus one. + pub num_tile_columns_minus1: u32, + /// `num_tile_rows_minus1` — the number of tile rows is this plus + /// one. + pub num_tile_rows_minus1: u32, + /// `uniform_spacing_flag`. When `true` the columns/rows are spread + /// as evenly as possible (eqs. 6-3 / 6-4 uniform branch) and the + /// explicit arrays are ignored. + pub uniform_spacing_flag: bool, + /// `column_width_minus1[ i ]` for `i` in + /// `0..num_tile_columns_minus1` (only when not uniform). + pub column_width_minus1: Vec, + /// `row_height_minus1[ j ]` for `j` in `0..num_tile_rows_minus1` + /// (only when not uniform). + pub row_height_minus1: Vec, +} + +impl TilingParams { + /// The single-tile layout used when `tiles_enabled_flag == 0`. + pub fn single_tile() -> Self { + Self { + num_tile_columns_minus1: 0, + num_tile_rows_minus1: 0, + uniform_spacing_flag: true, + column_width_minus1: Vec::new(), + row_height_minus1: Vec::new(), + } + } +} + +/// Picture-level geometry plus the derived §6.5.1 / §6.5.2 conversion +/// tables. Construct with [`PictureTiling::new`], then query availability +/// with [`PictureTiling::z_scan_availability`] / +/// [`PictureTiling::prediction_block_availability`]. +#[derive(Debug, Clone)] +pub struct PictureTiling { + pic_width_in_ctbs_y: u32, + pic_height_in_ctbs_y: u32, + pic_width_in_luma_samples: u32, + pic_height_in_luma_samples: u32, + ctb_log2_size_y: u32, + min_tb_log2_size_y: u32, + /// `colBd[ 0..=num_tile_columns_minus1 + 1 ]` (eq. 6-5). + col_bd: Vec, + /// `rowBd[ 0..=num_tile_rows_minus1 + 1 ]` (eq. 6-6). + row_bd: Vec, + /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7). + ctb_addr_rs_to_ts: Vec, + /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8). + ctb_addr_ts_to_rs: Vec, + /// `TileId[ ctbAddrTs ]` (eq. 6-9). + tile_id: Vec, +} + +impl PictureTiling { + /// Build the §6.5.1 conversion tables from the picture geometry and + /// tile parameters. + /// + /// * `pic_width_in_ctbs_y` / `pic_height_in_ctbs_y` — + /// `PicWidthInCtbsY` / `PicHeightInCtbsY` (eqs. 7-20 / 7-21). + /// * `pic_width_in_luma_samples` / `pic_height_in_luma_samples` — + /// the SPS conformance-relevant `pic_width_in_luma_samples` / + /// `pic_height_in_luma_samples` used by §6.4.1's boundary test. + /// * `ctb_log2_size_y` — `CtbLog2SizeY` (eq. 7-11). + /// * `min_tb_log2_size_y` — `MinTbLog2SizeY` + /// (= `log2_min_luma_transform_block_size_minus2 + 2`). + /// * `tiles` — the active PPS tile-partitioning parameters. + pub fn new( + pic_width_in_ctbs_y: u32, + pic_height_in_ctbs_y: u32, + pic_width_in_luma_samples: u32, + pic_height_in_luma_samples: u32, + ctb_log2_size_y: u32, + min_tb_log2_size_y: u32, + tiles: &TilingParams, + ) -> Result { + if pic_width_in_ctbs_y == 0 { + return Err(AvailabilityError::ZeroGeometry { + field: "PicWidthInCtbsY", + }); + } + if pic_height_in_ctbs_y == 0 { + return Err(AvailabilityError::ZeroGeometry { + field: "PicHeightInCtbsY", + }); + } + if ctb_log2_size_y < min_tb_log2_size_y { + return Err(AvailabilityError::InvalidLog2Sizes { + ctb_log2: ctb_log2_size_y, + min_tb_log2: min_tb_log2_size_y, + }); + } + + let num_cols = (tiles.num_tile_columns_minus1 + 1) as usize; + let num_rows = (tiles.num_tile_rows_minus1 + 1) as usize; + + // §6.5.1 eqs. 6-3 / 6-4 — colWidth / rowHeight (in CTBs). + let col_width = derive_tile_sizes( + pic_width_in_ctbs_y, + tiles.num_tile_columns_minus1, + tiles.uniform_spacing_flag, + &tiles.column_width_minus1, + "column_width_minus1", + "column", + )?; + let row_height = derive_tile_sizes( + pic_height_in_ctbs_y, + tiles.num_tile_rows_minus1, + tiles.uniform_spacing_flag, + &tiles.row_height_minus1, + "row_height_minus1", + "row", + )?; + + // §6.5.1 eqs. 6-5 / 6-6 — colBd / rowBd (cumulative boundaries). + let mut col_bd = vec![0u32; num_cols + 1]; + for i in 0..num_cols { + col_bd[i + 1] = col_bd[i] + col_width[i]; + } + let mut row_bd = vec![0u32; num_rows + 1]; + for j in 0..num_rows { + row_bd[j + 1] = row_bd[j] + row_height[j]; + } + + let pic_size_in_ctbs_y = (pic_width_in_ctbs_y * pic_height_in_ctbs_y) as usize; + + // §6.5.1 eq. 6-7 — CtbAddrRsToTs. + let mut ctb_addr_rs_to_ts = vec![0u32; pic_size_in_ctbs_y]; + for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 { + let tb_x = ctb_addr_rs % pic_width_in_ctbs_y; + let tb_y = ctb_addr_rs / pic_width_in_ctbs_y; + let mut tile_x = 0usize; + for (i, &bd) in col_bd.iter().take(num_cols).enumerate() { + if tb_x >= bd { + tile_x = i; + } + } + let mut tile_y = 0usize; + for (j, &bd) in row_bd.iter().take(num_rows).enumerate() { + if tb_y >= bd { + tile_y = j; + } + } + let mut val = 0u32; + for &cw in col_width.iter().take(tile_x) { + val += row_height[tile_y] * cw; + } + for &rh in row_height.iter().take(tile_y) { + val += pic_width_in_ctbs_y * rh; + } + val += (tb_y - row_bd[tile_y]) * col_width[tile_x] + tb_x - col_bd[tile_x]; + ctb_addr_rs_to_ts[ctb_addr_rs as usize] = val; + } + + // §6.5.1 eq. 6-8 — CtbAddrTsToRs (inverse permutation). + let mut ctb_addr_ts_to_rs = vec![0u32; pic_size_in_ctbs_y]; + for ctb_addr_rs in 0..pic_size_in_ctbs_y as u32 { + ctb_addr_ts_to_rs[ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize] = ctb_addr_rs; + } + + // §6.5.1 eq. 6-9 — TileId. + let mut tile_id = vec![0u32; pic_size_in_ctbs_y]; + let mut tile_idx = 0u32; + for j in 0..num_rows { + for i in 0..num_cols { + for y in row_bd[j]..row_bd[j + 1] { + for x in col_bd[i]..col_bd[i + 1] { + let rs = (y * pic_width_in_ctbs_y + x) as usize; + tile_id[ctb_addr_rs_to_ts[rs] as usize] = tile_idx; + } + } + tile_idx += 1; + } + } + + Ok(Self { + pic_width_in_ctbs_y, + pic_height_in_ctbs_y, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + ctb_log2_size_y, + min_tb_log2_size_y, + col_bd, + row_bd, + ctb_addr_rs_to_ts, + ctb_addr_ts_to_rs, + tile_id, + }) + } + + /// `CtbAddrRsToTs[ ctbAddrRs ]` (eq. 6-7). Panics on out-of-range + /// `ctb_addr_rs`; valid indices are `0..PicSizeInCtbsY`. + pub fn ctb_addr_rs_to_ts(&self, ctb_addr_rs: u32) -> u32 { + self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] + } + + /// `CtbAddrTsToRs[ ctbAddrTs ]` (eq. 6-8). + pub fn ctb_addr_ts_to_rs(&self, ctb_addr_ts: u32) -> u32 { + self.ctb_addr_ts_to_rs[ctb_addr_ts as usize] + } + + /// `TileId[ ctbAddrTs ]` (eq. 6-9) — the tile a tile-scan CTB + /// address belongs to. + pub fn tile_id(&self, ctb_addr_ts: u32) -> u32 { + self.tile_id[ctb_addr_ts as usize] + } + + /// `colBd[ i ]` (eq. 6-5) — the i-th tile-column boundary in units + /// of CTBs, for `i` in `0..=num_tile_columns_minus1 + 1`. + pub fn col_bd(&self) -> &[u32] { + &self.col_bd + } + + /// `rowBd[ j ]` (eq. 6-6) — the j-th tile-row boundary in units of + /// CTBs, for `j` in `0..=num_tile_rows_minus1 + 1`. + pub fn row_bd(&self) -> &[u32] { + &self.row_bd + } + + /// `PicWidthInCtbsY`. + pub fn pic_width_in_ctbs_y(&self) -> u32 { + self.pic_width_in_ctbs_y + } + + /// `PicHeightInCtbsY`. + pub fn pic_height_in_ctbs_y(&self) -> u32 { + self.pic_height_in_ctbs_y + } + + /// The TileId of the tile covering luma sample `( xY, yY )`. + /// Convenience over [`Self::tile_id`] that converts the luma + /// location through the CTB raster→tile-scan conversion. The caller + /// is responsible for keeping `( xY, yY )` inside the picture. + fn tile_id_at_luma(&self, x_y: u32, y_y: u32) -> u32 { + let ctb_x = x_y >> self.ctb_log2_size_y; + let ctb_y = y_y >> self.ctb_log2_size_y; + let ctb_addr_rs = ctb_y * self.pic_width_in_ctbs_y + ctb_x; + self.tile_id[self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] as usize] + } + + /// `MinTbAddrZs[ x ][ y ]` (§6.5.2 eq. 6-10) — the minimum-block + /// location `( x, y )` (in units of `MinTbLog2SizeY`-sized blocks) + /// converted to a minimum-block address in z-scan order. + /// + /// Combines the tile-scan CTB order (high bits) with the within-CTB + /// Morton / z interleave of the block's `( x, y )` low bits. The + /// caller is responsible for keeping `( x, y )` within the picture's + /// minimum-block grid. + pub fn min_tb_addr_zs(&self, x: u32, y: u32) -> u32 { + let shift = self.ctb_log2_size_y - self.min_tb_log2_size_y; + let tb_x = (x << self.min_tb_log2_size_y) >> self.ctb_log2_size_y; + let tb_y = (y << self.min_tb_log2_size_y) >> self.ctb_log2_size_y; + let ctb_addr_rs = self.pic_width_in_ctbs_y * tb_y + tb_x; + let mut addr = self.ctb_addr_rs_to_ts[ctb_addr_rs as usize] << (shift * 2); + let mut p = 0u32; + for i in 0..shift { + let m = 1u32 << i; + p += if m & x != 0 { m * m } else { 0 } + if m & y != 0 { 2 * m * m } else { 0 }; + } + addr += p; + addr + } + + /// §6.4.1 — derivation process for z-scan order block availability. + /// + /// Returns whether the neighbouring block covering luma location + /// `( x_nb_y, y_nb_y )` is available for the current block whose + /// top-left luma sample is `( x_curr, y_curr )`. + /// + /// `slice_addr_rs` maps a CTB raster-scan address to the + /// `SliceAddrRs` of the slice segment that owns that CTB — the + /// slice-boundary test of §6.4.1. The caller's slice-data walk + /// builds it; for a single-slice picture it is the constant `0`. + pub fn z_scan_availability( + &self, + x_curr: u32, + y_curr: u32, + x_nb_y: i32, + y_nb_y: i32, + slice_addr_rs: F, + ) -> bool + where + F: Fn(u32) -> u32, + { + // eq. 6-1. + let min_block_addr_curr = self.min_tb_addr_zs( + x_curr >> self.min_tb_log2_size_y, + y_curr >> self.min_tb_log2_size_y, + ); + + // eq. 6-2 — out-of-picture neighbours get minBlockAddrN = −1. + if x_nb_y < 0 + || y_nb_y < 0 + || x_nb_y as u32 >= self.pic_width_in_luma_samples + || y_nb_y as u32 >= self.pic_height_in_luma_samples + { + return false; + } + let x_nb_y = x_nb_y as u32; + let y_nb_y = y_nb_y as u32; + let min_block_addr_n = self.min_tb_addr_zs( + x_nb_y >> self.min_tb_log2_size_y, + y_nb_y >> self.min_tb_log2_size_y, + ); + + // The neighbour must already be decoded (z-scan order test). + if min_block_addr_n > min_block_addr_curr { + return false; + } + + // Slice-segment boundary: compare the SliceAddrRs of the CTBs + // owning each block. The block addresses are in z-scan order; + // map them back to the owning CTB raster address. + let ctb_rs_curr = self.ctb_rs_of_z(min_block_addr_curr); + let ctb_rs_n = self.ctb_rs_of_z(min_block_addr_n); + if slice_addr_rs(ctb_rs_n) != slice_addr_rs(ctb_rs_curr) { + return false; + } + + // Tile boundary: the neighbour must be in the same tile. + if self.tile_id_at_luma(x_nb_y, y_nb_y) != self.tile_id_at_luma(x_curr, y_curr) { + return false; + } + + true + } + + /// §6.4.2 — derivation process for prediction block availability. + /// + /// Wraps [`Self::z_scan_availability`] with the `sameCb` short-cut + /// (a neighbour in the *same* coding block is unavailable when it + /// would not yet have been decoded under the §7.4.9 partitioning + /// order) and the final `MODE_INTRA` masking. + /// + /// * `( x_cb, y_cb )` / `n_cb_s` — the current coding block. + /// * `( x_pb, y_pb )` / `n_pb_w` / `n_pb_h` / `part_idx` — the + /// current prediction block and its partition index. + /// * `( x_nb_y, y_nb_y )` — the neighbour location. + /// * `slice_addr_rs` — as in [`Self::z_scan_availability`]. + /// * `cu_pred_mode` — maps a luma location to its `CuPredMode` + /// (`MODE_INTRA` / `MODE_INTER` / `MODE_SKIP`). Only consulted for + /// in-picture neighbours that are otherwise available. + #[allow(clippy::too_many_arguments)] + pub fn prediction_block_availability( + &self, + x_cb: u32, + y_cb: u32, + n_cb_s: u32, + x_pb: u32, + y_pb: u32, + n_pb_w: u32, + n_pb_h: u32, + part_idx: u32, + x_nb_y: i32, + y_nb_y: i32, + slice_addr_rs: S, + cu_pred_mode: M, + ) -> bool + where + S: Fn(u32) -> u32, + M: Fn(u32, u32) -> u8, + { + // sameCb: does the neighbour cover the current coding block? + let same_cb = x_nb_y >= 0 + && y_nb_y >= 0 + && x_cb <= x_nb_y as u32 + && y_cb <= y_nb_y as u32 + && (x_cb + n_cb_s) > x_nb_y as u32 + && (y_cb + n_cb_s) > y_nb_y as u32; + + let mut available_n = if !same_cb { + self.z_scan_availability(x_pb, y_pb, x_nb_y, y_nb_y, slice_addr_rs) + } else if (n_pb_w << 1) == n_cb_s + && (n_pb_h << 1) == n_cb_s + && part_idx == 1 + && (y_cb + n_pb_h) <= y_nb_y as u32 + && (x_cb + n_pb_w) > x_nb_y as u32 + { + // The Nx2N / 2NxN second partition cannot reference the not- + // yet-decoded partition-0 region inside the same CU. + false + } else { + true + }; + + // Final §6.4.2 step: intra neighbours are unavailable for the + // (inter) prediction-block availability query. + if available_n { + let x = x_nb_y as u32; + let y = y_nb_y as u32; + if cu_pred_mode(x, y) == MODE_INTRA { + available_n = false; + } + } + + available_n + } + + /// Map a minimum-block z-scan address back to the CTB raster-scan + /// address that contains it. The high + /// `( CtbLog2SizeY − MinTbLog2SizeY ) * 2` bits of a z-scan block + /// address are the tile-scan CTB address (see eq. 6-10). + fn ctb_rs_of_z(&self, min_block_addr_z: u32) -> u32 { + let shift = (self.ctb_log2_size_y - self.min_tb_log2_size_y) * 2; + let ctb_addr_ts = min_block_addr_z >> shift; + self.ctb_addr_ts_to_rs[ctb_addr_ts as usize] + } +} + +/// §6.5.1 eqs. 6-3 / 6-4 — derive the per-tile sizes (`colWidth` / +/// `rowHeight`) in CTBs, for one dimension. +fn derive_tile_sizes( + pic_size_in_ctbs: u32, + num_tiles_minus1: u32, + uniform_spacing_flag: bool, + explicit_minus1: &[u32], + array_field: &'static str, + dimension: &'static str, +) -> Result, AvailabilityError> { + let num_tiles = (num_tiles_minus1 + 1) as usize; + let mut sizes = vec![0u32; num_tiles]; + if uniform_spacing_flag { + for (i, slot) in sizes.iter_mut().enumerate() { + let i = i as u32; + *slot = ((i + 1) * pic_size_in_ctbs) / (num_tiles_minus1 + 1) + - (i * pic_size_in_ctbs) / (num_tiles_minus1 + 1); + } + } else { + if explicit_minus1.len() != num_tiles_minus1 as usize { + return Err(AvailabilityError::TileArrayLength { + field: array_field, + expected: num_tiles_minus1 as usize, + got: explicit_minus1.len(), + }); + } + // The last tile takes the remainder; the first num_tiles_minus1 + // are explicit. + sizes[num_tiles - 1] = pic_size_in_ctbs; + for i in 0..num_tiles_minus1 as usize { + sizes[i] = explicit_minus1[i] + 1; + if sizes[i] > sizes[num_tiles - 1] { + return Err(AvailabilityError::TileOverflow { dimension }); + } + sizes[num_tiles - 1] -= sizes[i]; + } + if sizes[num_tiles - 1] == 0 { + return Err(AvailabilityError::TileOverflow { dimension }); + } + } + Ok(sizes) +} + +#[cfg(test)] +mod tests; diff --git a/vendor/oxideav-h265/src/availability/tests.rs b/vendor/oxideav-h265/src/availability/tests.rs new file mode 100644 index 0000000..e585aeb --- /dev/null +++ b/vendor/oxideav-h265/src/availability/tests.rs @@ -0,0 +1,315 @@ +//! Tests for §6.4 availability + §6.5.1 / §6.5.2 scan conversions. +//! +//! Expected values are hand-derived from the ITU-T H.265 equations, not +//! taken from any implementation. + +use super::*; + +/// Build the simplest single-tile geometry: `w`×`h` CTBs, CtbLog2 = 6 +/// (64-sample CTBs), MinTbLog2 = 2 (4-sample minimum blocks). +fn single_tile(w: u32, h: u32) -> PictureTiling { + PictureTiling::new(w, h, w * 64, h * 64, 6, 2, &TilingParams::single_tile()).unwrap() +} + +#[test] +fn single_tile_rs_to_ts_is_identity() { + let t = single_tile(3, 2); + for rs in 0..6 { + assert_eq!(t.ctb_addr_rs_to_ts(rs), rs, "rs->ts identity at {rs}"); + assert_eq!(t.ctb_addr_ts_to_rs(rs), rs, "ts->rs identity at {rs}"); + assert_eq!(t.tile_id(rs), 0, "single tile id at {rs}"); + } +} + +#[test] +fn min_tb_addr_zs_within_one_ctb_is_morton() { + // One 64-sample CTB = 16×16 4-sample min-blocks. shift = 4. + // Within a single CTB (tile-scan addr 0), MinTbAddrZs is the pure + // Morton interleave of the block (x, y) bits (eq. 6-10 with the + // CtbAddrRsToTs term zero). + let t = single_tile(1, 1); + // (0,0) -> 0 + assert_eq!(t.min_tb_addr_zs(0, 0), 0); + // (1,0): x bit0 set -> p += 1*1 = 1 + assert_eq!(t.min_tb_addr_zs(1, 0), 1); + // (0,1): y bit0 set -> p += 2*1*1 = 2 + assert_eq!(t.min_tb_addr_zs(0, 1), 2); + // (1,1): 1 + 2 = 3 + assert_eq!(t.min_tb_addr_zs(1, 1), 3); + // (2,0): x bit1 (m=2) set -> p += 2*2 = 4 + assert_eq!(t.min_tb_addr_zs(2, 0), 4); + // (0,2): y bit1 set -> p += 2*2*2 = 8 + assert_eq!(t.min_tb_addr_zs(0, 2), 8); + // (3,3): x bits 0,1 -> 1 + 4 = 5; y bits 0,1 -> 2 + 8 = 10; sum 15 + assert_eq!(t.min_tb_addr_zs(3, 3), 15); + // (15,15): all four x bits -> 1+4+16+64 = 85; y doubles -> 170; 255 + assert_eq!(t.min_tb_addr_zs(15, 15), 255); +} + +#[test] +fn min_tb_addr_zs_second_ctb_offsets_by_256() { + // Two CTBs wide, single tile/slice. The min-block grid is 32 wide. + // A block in the second CTB (x >= 16) sits at tile-scan CTB addr 1, + // so its z-address starts at 1 << (shift*2) = 256. + let t = single_tile(2, 1); + assert_eq!(t.min_tb_addr_zs(16, 0), 256); + assert_eq!(t.min_tb_addr_zs(17, 0), 257); + // First CTB still occupies 0..255. + assert_eq!(t.min_tb_addr_zs(15, 15), 255); +} + +#[test] +fn uniform_two_column_tiles_split_evenly() { + // 4 CTBs wide, 1 tall, 2 uniform columns -> colWidth = [2, 2]. + // colBd = [0, 2, 4]. CtbAddrRsToTs: tile 0 holds CTBs (0,1), tile 1 + // holds (2,3); tile scan visits tile 0 fully then tile 1. + let tiles = TilingParams { + num_tile_columns_minus1: 1, + num_tile_rows_minus1: 0, + uniform_spacing_flag: true, + column_width_minus1: vec![], + row_height_minus1: vec![], + }; + let t = PictureTiling::new(4, 1, 256, 64, 6, 2, &tiles).unwrap(); + // rs 0,1 (tile 0) -> ts 0,1; rs 2,3 (tile 1) -> ts 2,3 (here the + // single row keeps tile-scan == raster for this layout). + assert_eq!(t.ctb_addr_rs_to_ts(0), 0); + assert_eq!(t.ctb_addr_rs_to_ts(1), 1); + assert_eq!(t.ctb_addr_rs_to_ts(2), 2); + assert_eq!(t.ctb_addr_rs_to_ts(3), 3); + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0); + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(2)), 1); +} + +#[test] +fn uniform_two_by_two_tiles_reorder_tile_scan() { + // 4×4 CTBs, 2×2 uniform tiles. colWidth = rowHeight = [2, 2]. + // Tile scan visits tile (0,0)'s 4 CTBs, then (1,0), then (0,1), + // then (1,1). So raster CTB 2 (top-right tile) maps to tile-scan 4. + let tiles = TilingParams { + num_tile_columns_minus1: 1, + num_tile_rows_minus1: 1, + uniform_spacing_flag: true, + column_width_minus1: vec![], + row_height_minus1: vec![], + }; + let t = PictureTiling::new(4, 4, 256, 256, 6, 2, &tiles).unwrap(); + // Raster addr of CTB at (col=0,row=0) = 0 -> ts 0, tile 0. + assert_eq!(t.ctb_addr_rs_to_ts(0), 0); + assert_eq!(t.tile_id(0), 0); + // CTB at (col=2,row=0) raster = 2; it is tile (1,0) = tile idx 1, + // first CTB after tile 0's 4 -> ts 4. + assert_eq!(t.ctb_addr_rs_to_ts(2), 4); + assert_eq!(t.tile_id(4), 1); + // CTB at (col=0,row=2) raster = 8; tile (0,1) = tile idx 2 -> ts 8. + assert_eq!(t.ctb_addr_rs_to_ts(8), 8); + assert_eq!(t.tile_id(8), 2); + // CTB at (col=2,row=2) raster = 10; tile (1,1) = tile idx 3 -> ts 12. + assert_eq!(t.ctb_addr_rs_to_ts(10), 12); + assert_eq!(t.tile_id(12), 3); + // ts->rs is the inverse permutation. + for rs in 0..16 { + assert_eq!(t.ctb_addr_ts_to_rs(t.ctb_addr_rs_to_ts(rs)), rs); + } +} + +#[test] +fn explicit_tile_widths() { + // 5 CTBs wide, 1 tall, 2 columns, column_width_minus1[0] = 0 + // -> colWidth = [1, 4]. + let tiles = TilingParams { + num_tile_columns_minus1: 1, + num_tile_rows_minus1: 0, + uniform_spacing_flag: false, + column_width_minus1: vec![0], + row_height_minus1: vec![], + }; + let t = PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles).unwrap(); + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(0)), 0); // first CTB, tile 0 + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(1)), 1); // rest, tile 1 + assert_eq!(t.tile_id(t.ctb_addr_rs_to_ts(4)), 1); +} + +#[test] +fn explicit_tile_overflow_rejected() { + // column_width_minus1[0] = 5 implies first tile is 6 CTBs wide in a + // 5-CTB-wide picture -> overflow. + let tiles = TilingParams { + num_tile_columns_minus1: 1, + num_tile_rows_minus1: 0, + uniform_spacing_flag: false, + column_width_minus1: vec![5], + row_height_minus1: vec![], + }; + assert!(matches!( + PictureTiling::new(5, 1, 320, 64, 6, 2, &tiles), + Err(AvailabilityError::TileOverflow { + dimension: "column" + }) + )); +} + +#[test] +fn explicit_array_length_mismatch_rejected() { + let tiles = TilingParams { + num_tile_columns_minus1: 2, // expects 2 entries + num_tile_rows_minus1: 0, + uniform_spacing_flag: false, + column_width_minus1: vec![0], // only 1 supplied + row_height_minus1: vec![], + }; + assert!(matches!( + PictureTiling::new(6, 1, 384, 64, 6, 2, &tiles), + Err(AvailabilityError::TileArrayLength { .. }) + )); +} + +#[test] +fn invalid_log2_sizes_rejected() { + // CtbLog2 < MinTbLog2. + assert!(matches!( + PictureTiling::new(1, 1, 64, 64, 2, 4, &TilingParams::single_tile()), + Err(AvailabilityError::InvalidLog2Sizes { .. }) + )); +} + +#[test] +fn zero_geometry_rejected() { + assert!(matches!( + PictureTiling::new(0, 1, 0, 64, 6, 2, &TilingParams::single_tile()), + Err(AvailabilityError::ZeroGeometry { + field: "PicWidthInCtbsY" + }) + )); +} + +// ---- §6.4.1 z-scan availability ---- + +#[test] +fn neighbour_outside_picture_is_unavailable() { + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + // Current block at (64, 64). Left neighbour at x = -1 -> out. + assert!(!t.z_scan_availability(64, 64, -1, 64, same_slice)); + // Top neighbour at y = -1 -> out. + assert!(!t.z_scan_availability(64, 64, 64, -1, same_slice)); + // Right of picture (picture is 128 wide). + assert!(!t.z_scan_availability(64, 64, 128, 64, same_slice)); + // Below picture (128 tall). + assert!(!t.z_scan_availability(64, 64, 64, 128, same_slice)); +} + +#[test] +fn already_decoded_left_and_above_are_available() { + // 2×2 CTBs, single slice/tile. Current block top-left at (64, 64) + // (the bottom-right CTB, decoded last in raster order). Its left + // (63, 64) and above (64, 63) neighbours decode earlier -> available. + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + assert!(t.z_scan_availability(64, 64, 63, 64, same_slice)); // left + assert!(t.z_scan_availability(64, 64, 64, 63, same_slice)); // above + assert!(t.z_scan_availability(64, 64, 63, 63, same_slice)); // above-left +} + +#[test] +fn not_yet_decoded_neighbour_is_unavailable() { + // Current at the top-left CTB (0,0). The below-right neighbour at + // (64, 64) decodes later -> minBlockAddrN > minBlockAddrCurr -> + // unavailable even though it is inside the picture. + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + assert!(!t.z_scan_availability(0, 0, 64, 64, same_slice)); + // The above-right of the bottom-left CTB: current (0,64), + // neighbour (64, 63) is in the top-right CTB which decodes before + // the bottom-left CTB in raster order -> available. + assert!(t.z_scan_availability(0, 64, 64, 63, same_slice)); +} + +#[test] +fn different_slice_is_unavailable() { + // 2×2 CTBs. Put the second slice starting at raster CTB 3 (the + // bottom-right). Current block in CTB 3, left neighbour in CTB 2. + let t = single_tile(2, 2); + let slice_of = |rs: u32| if rs >= 3 { 1u32 } else { 0u32 }; + // current (64,64) is CTB 3 (slice 1); left (63,64) is CTB 2 (slice 0) + assert!(!t.z_scan_availability(64, 64, 63, 64, slice_of)); + // within-slice neighbour: above (64,63) is CTB 1 (slice 0) too, but + // it differs from current's slice 1 -> still unavailable. + assert!(!t.z_scan_availability(64, 64, 64, 63, slice_of)); +} + +#[test] +fn different_tile_is_unavailable() { + // 2 columns × 1 row of tiles over 2×1 CTBs: each CTB is its own + // tile. Current block in the right CTB, left neighbour in the left + // CTB -> different tile -> unavailable even within one slice. + let tiles = TilingParams { + num_tile_columns_minus1: 1, + num_tile_rows_minus1: 0, + uniform_spacing_flag: true, + column_width_minus1: vec![], + row_height_minus1: vec![], + }; + let t = PictureTiling::new(2, 1, 128, 64, 6, 2, &tiles).unwrap(); + let same_slice = |_rs: u32| 0u32; + // current (64,0) right tile; left (63,0) left tile. + assert!(!t.z_scan_availability(64, 0, 63, 0, same_slice)); + // within the same (right) tile a left neighbour is available. + assert!(t.z_scan_availability(127, 0, 126, 0, same_slice)); +} + +// ---- §6.4.2 prediction block availability ---- + +#[test] +fn prediction_block_intra_neighbour_masked_out() { + // 2×2 CTBs single slice/tile. Current PB top-left (64,64). Left + // neighbour (63,64) would be z-scan available, but its CuPredMode + // is MODE_INTRA -> masked to unavailable for the inter query. + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + let all_intra = |_x: u32, _y: u32| MODE_INTRA; + let all_inter = |_x: u32, _y: u32| 0u8; // MODE_INTER + // 64×64 CU == one 64×64 PB (2Nx2N), partIdx 0. + assert!(!t.prediction_block_availability( + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_intra, + )); + assert!(t.prediction_block_availability( + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter, + )); +} + +#[test] +fn prediction_block_second_partition_cannot_see_first() { + // The §6.4.2 same-CB forced-FALSE branch fires only for the NxN + // partitioning ((nPbW << 1) == nCbS AND (nPbH << 1) == nCbS): a + // 64×64 CU split into four 32×32 PBs. The top-right PB (partIdx 1, + // top-left (32, 0)) must not reference the bottom-left PB region + // (yNbY >= yCb + nPbH = 32, xNbY < xCb + nPbW = 32), which the + // §7.4.9 partitioning order has not decoded yet. + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + let all_inter = |_x: u32, _y: u32| 0u8; + // CU (0,0) size 64; PB1 (32,0) 32×32, partIdx 1. Neighbour (31, 32) + // is the bottom-left PB region — same CB, the forced-FALSE branch. + assert!(!t + .prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 31, 32, same_slice, all_inter,)); + // The bottom-right region (xNbY >= 32) is NOT forced false by this + // branch (it sits at xNbY = 32, failing xCb+nPbW > xNbY); it falls + // through to availableN = TRUE since it is the same CB. + assert!( + t.prediction_block_availability(0, 0, 64, 32, 0, 32, 32, 1, 32, 32, same_slice, all_inter,) + ); +} + +#[test] +fn prediction_block_normal_left_neighbour_available() { + // Same-CB short-cut not triggered (neighbour outside the CU): a + // normal left neighbour of an inter 2Nx2N PB resolves through + // §6.4.1 and is available. + let t = single_tile(2, 2); + let same_slice = |_rs: u32| 0u32; + let all_inter = |_x: u32, _y: u32| 0u8; + assert!(t.prediction_block_availability( + 64, 64, 64, 64, 64, 64, 64, 0, 63, 64, same_slice, all_inter, + )); +} diff --git a/vendor/oxideav-h265/src/binarization.rs b/vendor/oxideav-h265/src/binarization.rs new file mode 100644 index 0000000..2686d94 --- /dev/null +++ b/vendor/oxideav-h265/src/binarization.rs @@ -0,0 +1,8000 @@ +//! §9.3.4.2 per-syntax-element binarization + context-index derivation. +//! +//! Sits one layer above the §9.3 arithmetic decoding engine +//! ([`crate::cabac::CabacEngine`]). For each entropy-coded syntax +//! element this module supplies the §9.3.3 binarization shape (truncated +//! rice, fixed length, Exp-Golomb of order *k*, …) plus the §9.3.4.2.X +//! per-bin `ctxInc` derivation, returning a context-index into the +//! per-slice context-model array. +//! +//! Round 26 ships the two syntax elements unblocked by the clean-room +//! CABAC trace `docs/video/h265/fixtures/main-422-10bit/cabac-cu-qp-delta-last-sig-trace.md`: +//! +//! * **`cu_qp_delta_abs` / `cu_qp_delta_sign_flag`** (H.265 §7.3.8.14, +//! §7.4.9.14). Binarization: §9.3.3.10 TR prefix (`cMax = 5`, +//! `cRiceParam = 0`) followed, when the prefix is the all-ones escape +//! (`prefixVal == 5`), by an EGk suffix with `k = 0` (§9.3.3.11). The +//! per-bin `ctxInc` (§9.3.4.2.2, Table 9-32): bin 0 uses `ctxInc = 0`, +//! bins 1..=4 share `ctxInc = 1`. The sign flag is bypass-coded. +//! `CuQpDeltaVal = cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`. +//! +//! * **`last_sig_coeff_{x,y}_prefix`** (H.265 §7.3.8.11, §7.4.9.11). +//! Binarization: §9.3.3.10 TR prefix with +//! `cMax = (log2TrafoSize << 1) − 1` and `cRiceParam = 0`. The per-bin +//! `ctxInc` (§9.3.4.2.3) is +//! `ctxInc = (binIdx >> ctxShift) + ctxOffset`. For luma: +//! `ctxOffset = 3 * (log2TrafoSize − 2) + ((log2TrafoSize − 1) >> 2)`, +//! `ctxShift = (log2TrafoSize + 1) >> 2`. For chroma (cIdx > 0): +//! `ctxOffset = 15`, `ctxShift = log2TrafoSize − 2`. The X and Y +//! prefix bins live in separate context banks; this module hands back +//! only the bank-relative `ctxInc` and the matching +//! [`LastSigCoeffBank`] tag for caller-side routing. +//! +//! * **`last_sig_coeff_{x,y}_suffix`** (H.265 §7.3.8.11, §7.4.9.11). A +//! `nBits = (prefix >> 1) − 1`-bit fixed-length bypass field, present +//! only when `prefix > 3`. Together with the prefix the final +//! `LastSignificantCoeffX` / `Y` position is derived per equations +//! 7-74..7-77. +//! +//! Both elements live downstream of the §9.3.4.2 binarization layer +//! that the slice-data parser (§7.3.8) drives; this module is the +//! reusable per-element building block. +//! +//! Round 27 extends the ctxInc-derivation surface with three more +//! syntax elements that are pure-functional given their neighbour / +//! sub-block context (no CABAC engine drive needed at this layer — +//! callers compose the engine call themselves): +//! +//! * **`coded_sub_block_flag`** (H.265 §7.3.8.11, §7.4.9.11) — the +//! §9.3.4.2.4 derivation of `ctxInc` from the colour-component +//! index, the current sub-block scan location `(xS, yS)`, the +//! transform-block size, and the previously decoded +//! `coded_sub_block_flag[xS+1][yS]` / `coded_sub_block_flag[xS][yS+1]` +//! neighbours. Implemented in +//! [`coded_sub_block_flag_ctx_inc`] following equations 9-35..9-39. +//! +//! * **`split_cu_flag` / `cu_skip_flag`** (H.265 §7.3.8.4, §7.4.9.4, +//! §7.3.8.5, §7.4.9.5) — the §9.3.4.2.2 Table 9-49 derivation of +//! `ctxInc` from the left and above neighbours' `condL` / `condA` +//! booleans plus their availability: +//! `ctxInc = (condL && availableL) + (condA && availableA)`. +//! Implemented as the shared +//! [`left_above_ctx_inc`] helper (the body of Table 9-49) plus +//! the [`split_cu_flag_cond`] and [`cu_skip_flag_cond`] callbacks +//! the caller wires into it. The Table 9-49 row for +//! `split_cu_flag` compares each neighbour's `CtDepth[xNb][yNb]` +//! to the current `cqtDepth`; the row for `cu_skip_flag` reads +//! each neighbour's `cu_skip_flag[xNb][yNb]` directly. Both rows +//! produce a `ctxInc` in `{0, 1, 2}`. +//! +//! Round 28 extends the ctxInc-derivation surface with six more +//! syntax elements whose Table 9-48 entry is itself a closed-form +//! expression on parameters the caller already has in hand (no +//! neighbour table walk, no CABAC engine drive at this layer): +//! +//! * **`split_transform_flag[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10) +//! — Table 9-48 row: `ctxInc = 5 − log2TrafoSize`. Valid +//! `log2TrafoSize ∈ {2, 3, 4, 5}` for the residual-quadtree +//! transform-block sizes, so `ctxInc ∈ {0, 1, 2, 3}`. Implemented +//! in [`split_transform_flag_ctx_inc`]. +//! +//! * **`cbf_luma[ ][ ][ ]`** (H.265 §7.3.8.10, §7.4.9.10) — Table +//! 9-48 row: `ctxInc = (trafoDepth == 0) ? 1 : 0`. Implemented in +//! [`cbf_luma_ctx_inc`]. +//! +//! * **`cbf_cb[ ][ ][ ]` / `cbf_cr[ ][ ][ ]`** (H.265 §7.3.8.10, +//! §7.4.9.10) — Table 9-48 row: `ctxInc = trafoDepth`. The two +//! syntax elements live in separate context banks (Table 9-22 +//! shares the bank shape but each chroma component has its own +//! `ctxIdxOffset`); this layer hands back the bank-relative +//! `ctxInc` only. Implemented in [`cbf_cb_ctx_inc`] and +//! [`cbf_cr_ctx_inc`] (each is a wafer over the shared +//! [`cbf_chroma_ctx_inc`] helper). +//! +//! * **`inter_pred_idc[ x0 ][ y0 ]`** (H.265 §7.3.8.6, §7.4.9.6) — +//! Table 9-48 row: bin 0 uses +//! `ctxInc = (nPbW + nPbH != 12) ? CtDepth[x0][y0] : 4`; bin 1 +//! uses `ctxInc = 4`. The `nPbW + nPbH == 12` condition picks out +//! the prediction-block shapes whose luma area is 16 samples +//! (8×4 and 4×8 PUs), which are encoded with the bin-0 escape +//! onto the bin-1 context bank. Implemented in +//! [`inter_pred_idc_ctx_inc`]. +//! +//! * **`log2_res_scale_abs_plus1[ c ]`** (H.265 §7.3.8.13, +//! §7.4.9.13) — Table 9-48 row: `ctxInc = 4*c + binIdx` for +//! `binIdx ∈ {0, 1, 2, 3}` and `c ∈ {0, 1}` (Cb / Cr). The four +//! bins of the TR(`cMax = 4`) prefix occupy four consecutive +//! contexts per chroma component, so the per-component banks are +//! `{0, 1, 2, 3}` (Cb) and `{4, 5, 6, 7}` (Cr). Implemented in +//! [`log2_res_scale_abs_plus1_ctx_inc`]. +//! +//! * **`res_scale_sign_flag[ c ]`** (H.265 §7.3.8.13, §7.4.9.13) — +//! Table 9-48 row: `ctxInc = c` for `c ∈ {0, 1}`. One bit per +//! chroma component, each on its own context. Implemented in +//! [`res_scale_sign_flag_ctx_inc`]. +//! +//! All round-28 entries are bin-0 (and bin-1 for `inter_pred_idc` / +//! `log2_res_scale_abs_plus1`) ctxInc derivations only; the matching +//! binarization shapes (FL for the flags, TR(`cMax = 4`) for +//! `log2_res_scale_abs_plus1` followed by a bypass tail) are driven +//! by the slice-data parser the same way as the round-26 / 27 +//! elements. +//! +//! Round 30 extends the surface with the §7.3.4 `sao()` per-CTU +//! syntax-element family. Every element has either a single +//! context-coded bin-0 followed by zero or more bypass-coded bins +//! (Table 9-48) or is fully bypass-coded; no neighbour walk is +//! needed at this layer. +//! +//! * **`sao_merge_left_flag` / `sao_merge_up_flag`** (H.265 §7.3.4, +//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`. The FL +//! binarization has `cMax = 1` (single bin). The two merge flags +//! share the Table 9-5 context bank (Table 9-4). Implemented in +//! [`sao_merge_flag_ctx_inc`] + [`SAO_MERGE_FLAG_FL_CMAX`]. +//! +//! * **`sao_type_idx_luma` / `sao_type_idx_chroma`** (H.265 §7.3.4, +//! §7.4.9.3) — Table 9-48 row: bin 0 `ctxInc = 0`, bin 1 bypass. +//! The TR(`cMax = 2`, `cRiceParam = 0`) binarization caps the +//! prefix at two bins, encoding `SaoTypeIdx ∈ {0, 1, 2}`. The two +//! variants share the Table 9-6 context bank. Implemented in +//! [`sao_type_idx_ctx_inc`] + [`SAO_TYPE_IDX_TR_CMAX`]. +//! +//! * **`sao_offset_abs`** (H.265 §7.3.4, §7.4.9.3) — Table 9-48 row: +//! all bins bypass. TR(`cMax = (1 << min(bitDepth, 10) − 5) − 1`, +//! `cRiceParam = 0`). Implemented in [`sao_offset_abs_tr_cmax`]. +//! +//! * **`sao_offset_sign`**, **`sao_band_position`**, +//! **`sao_eo_class_luma` / `sao_eo_class_chroma`** (H.265 §7.3.4, +//! §7.4.9.3) — Table 9-48 row: all bins bypass; FL binarizations +//! with `cMax = 1`, `cMax = 31`, `cMax = 3` respectively. +//! Implemented as [`SAO_OFFSET_SIGN_FL_CMAX`], +//! [`SAO_BAND_POSITION_FL_CMAX`] + [`SAO_BAND_POSITION_FL_NBITS`], +//! and [`SAO_EO_CLASS_FL_CMAX`] + [`SAO_EO_CLASS_FL_NBITS`]. +//! +//! Round 31 extends the surface with the two §9.3.4.2.6 / +//! §9.3.4.2.7 derivations whose `ctxInc` carries *persistent* +//! per-transform-block state across sub-block invocations: the +//! greater-than-1 / greater-than-2 absolute-level flags. Both +//! elements are FL binarized with `cMax = 1` (one context-coded +//! bin) per Table 9-43, but the bin's ctxInc is driven by a small +//! sub-block-scoped state machine (`ctxSet`, `greater1Ctx`, +//! `lastGreater1Ctx`, `lastGreater1Flag`) that the residual-coding +//! loop threads from sub-block to sub-block within the same +//! transform block. +//! +//! * **`coeff_abs_level_greater1_flag[ n ]`** (H.265 §7.3.8.11, +//! §7.4.9.11) — §9.3.4.2.6, equations 9-56..9-60. The per-bin +//! `ctxInc = (ctxSet * 4) + min(3, greater1Ctx)` for luma; chroma +//! adds `+16`. `ctxSet` is initialised at the start of each +//! sub-block from the previous sub-block's terminal `greater1Ctx` +//! value, and rotates within `{0, 1, 2, 3}` per the spec's +//! `lastGreater1Ctx == 0` increment rule. Implemented as a +//! pure-functional state machine in [`Greater1State`] (the +//! walker the slice-data parser carries across the residual +//! sub-blocks of one transform block) plus the per-flag step +//! functions [`Greater1State::on_subblock_entry`] + +//! [`Greater1State::on_coeff_abs_level_greater1_flag`]. +//! +//! * **`coeff_abs_level_greater2_flag[ lastGreater1ScanPos ]`** +//! (H.265 §7.3.8.11, §7.4.9.11) — §9.3.4.2.7, equations +//! 9-61..9-62. `ctxInc = ctxSet` (luma) / `ctxInc = ctxSet + 4` +//! (chroma). The element is signalled at most once per sub-block +//! at the first scan position that took the greater-1 escape +//! (`lastGreater1ScanPos`). Implemented in +//! [`coeff_abs_level_greater2_flag_ctx_inc`], reading the +//! `ctxSet` value the §9.3.4.2.6 walker has already produced for +//! that same sub-block. +//! +//! Round 32 extends the residual-coding surface with the +//! §9.3.4.2.5 `sig_coeff_flag` ctxInc derivation: the per-scan-position +//! significance bin that the §7.3.8.11 residual-coding loop emits +//! before any greater-1 / greater-2 step. The derivation is a +//! four-branch dispatch on `(log2TrafoSize, xC + yC, +//! transform_skip_context_enabled_flag && (transform_skip_flag || +//! cu_transquant_bypass_flag))`: +//! +//! * **transform-skip / transquant-bypass fast path** (eq. 9-40): +//! `sigCtx = 42` (luma) / `sigCtx = 16` (chroma). One context +//! per colour component, position-independent. Implemented in +//! [`sig_coeff_flag_sig_ctx_transform_skip`]. +//! +//! * **`log2TrafoSize == 2`** (eq. 9-41) — the 4×4 TB case reads +//! `sigCtx` from the 16-entry Table 9-50 lookup at +//! `(yC << 2) + xC`. Implemented in +//! [`sig_coeff_flag_sig_ctx_log2_2`] + +//! [`SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2`]. +//! +//! * **DC position** (eq. 9-42) — `xC + yC == 0` on `log2 > 2` skips +//! the eq.-9-43..9-48 neighbour walk; `sigCtx` starts at 0 and +//! only the colour / size tail (eq.-9-49..9-53) applies. +//! Implemented in [`sig_coeff_flag_sig_ctx_dc`]. +//! +//! * **general case** (eq. 9-43..9-53) — for `log2 > 2`, `xC + +//! yC > 0` the `prevCsbf` parity of the right / below sub-block +//! neighbours plus the inner sub-block position `(xC & 3, yC & 3)` +//! route through one of four `sigCtx` rules (eq. 9-45..9-48), then +//! the colour / size / scan-order tail (eq. 9-49..9-53). Implemented +//! in [`sig_coeff_flag_sig_ctx_general`], with the eq.-9-43 / 9-44 +//! edge gates on `xS / yS < (1 << (log2TrafoSize − 2)) − 1` +//! applied internally. +//! +//! Eq. 9-54 / 9-55 carry the per-component `ctxInc` offset +//! (`ctxInc = sigCtx` for luma, `ctxInc = 27 + sigCtx` for chroma); +//! see [`sig_coeff_flag_ctx_inc_from_sig_ctx`]. Table 9-43 captures +//! the `sig_coeff_flag` binarization shape as FL with `cMax = 1` via +//! [`SIG_COEFF_FLAG_FL_CMAX`]. +//! +//! Round 33 extends the ctxInc-derivation surface with the +//! §9.3.4.2.8 `palette_run_prefix` derivation — the §7.3.8.13 +//! palette-coding (SCC) syntax element that signals the unary part +//! of the run length following a palette index or copy-above +//! decision. Inputs are the bin index `binIdx`, the per-pixel +//! `copy_above_palette_indices_flag`, and the `palette_idx_idc` +//! decoded at the start of the run. The `ctxInc` is: +//! +//! * **`copy_above_palette_indices_flag == 0` and `binIdx == 0`** +//! (eq. 9-63) — a piecewise function of `palette_idx_idc` in +//! `{0, 1, 2}`: +//! `ctxInc = (palette_idx_idc < 1) ? 0 : ((palette_idx_idc < 3) +//! ? 1 : 2)`. Implemented in +//! [`palette_run_prefix_ctx_inc_eq_9_63`]. +//! +//! * **otherwise** — `ctxInc = ctxIdxMap[copy_above_palette_indices_flag][binIdx]` +//! per Table 9-51, captured verbatim in +//! [`PALETTE_RUN_PREFIX_CTX_IDX_MAP`]. The `binIdx >= 5` cells of +//! Table 9-51 are bypass-coded per Table 9-48, so the lookup +//! covers `binIdx ∈ {0, 1, 2, 3, 4}` and the public entry point +//! [`palette_run_prefix_ctx_inc`] dispatches both branches with +//! an `Option` return (`None` ⇒ bypass). +//! +//! Round 33 also captures the matching Table 9-43 binarization +//! shape: `palette_run_prefix` is a TR with +//! `cMax = Floor(Log2(PaletteMaxRunMinus1)) + 1` and `cRiceParam = 0`; +//! the helper [`palette_run_prefix_tr_cmax`] returns the per-block +//! `cMax` from the `PaletteMaxRunMinus1` input. +//! +//! Round 34 adds the §9.3.3.11 `coeff_abs_level_remaining[ n ]` +//! Rice-adaptive binarization + decode primitive (non-persistent +//! branch: `persistent_rice_adaptation_enabled_flag == 0`): +//! +//! * [`coeff_abs_level_remaining_c_rice_param_eq_9_24`] — eq. 9-24 +//! adapts `cRiceParam` from the previous coefficient in the +//! sub-block: `cRiceParam = Min(cLastRiceParam + (cLastAbsLevel > +//! (3 << cLastRiceParam) ? 1 : 0), 4)`. +//! * [`coeff_abs_level_remaining_c_max_eq_9_26`] — eq. 9-26: +//! `cMax = 4 << cRiceParam`. +//! * [`coeff_abs_level_remaining_prefix_val_eq_9_27`] — eq. 9-27: +//! `prefixVal = Min(cMax, level)` (the value the §9.3.3.2 TR +//! prefix is built from). +//! * [`coeff_abs_level_remaining_suffix_val_eq_9_28`] — eq. 9-28: +//! `suffixVal = level - cMax` (only meaningful when the prefix is +//! the all-ones escape). +//! * [`decode_coeff_abs_level_remaining`] — full bypass-coded decode +//! driver: reads a unary prefix capped at +//! `COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN = 4`, and when +//! the prefix terminates short, returns +//! `prefix << cRiceParam`; otherwise reads an EGk suffix with +//! `k = cRiceParam + 1` and returns `cMax + suffixVal`. +//! +//! The persistent-Rice branch (eq. 9-25; the +//! `persistent_rice_adaptation_enabled_flag == 1` path that walks +//! the SCC `StatCoeff[sbType]` state via eq. 9-22/9-23) is left for +//! a follow-up round; the non-persistent branch is the Main-profile +//! path the slice-data parser drives by default. +//! +//! Round 35 adds the §9.3.4.2 / Table 9-48 entry for +//! `coeff_sign_flag[ n ]` — the per-scan-position sign bit that +//! pairs with `coeff_abs_level_remaining[ n ]` to form the signed +//! transform-coefficient level per §7.4.9.11. The element is fully +//! bypass-coded (Table 9-48 marks bin 0 `bypass`, all later columns +//! `na`) and FL binarized with `cMax = 1` (Table 9-43), so the +//! on-wire string is a single bin per invocation. The §9.3.4.3.6 +//! alignment process (`ivlCurrRange := 256`) runs prior to the +//! bypass tail at slice-data-loop scope; the per-flag entry point +//! [`decode_coeff_sign_flag`] consumes one [`CabacEngine::decode_bypass`] +//! bin from the post-alignment engine state. The signed level is +//! composed via [`signed_level_from_sign_flag`] applying the +//! §7.4.9.11 `(1 − 2 * coeff_sign_flag[n])` factor; the FL shape +//! is captured as [`COEFF_SIGN_FLAG_FL_CMAX`] + +//! [`COEFF_SIGN_FLAG_FL_NBITS`]. +//! +//! Round 36 adds the §9.3.4.2 / Table 9-48 entries for the +//! `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` transform-unit +//! syntax pair (H.265 §7.3.8.11, §7.4.9.10). Both elements have a +//! Table 9-48 row whose context-coded bins are all `ctxInc = 0` — the +//! flag occupies a single context (Table 9-34, three ctxIdx slots +//! across initType), and the idx occupies a single context (Table +//! 9-35, three ctxIdx slots across initType). The flag is FL +//! `cMax = 1`; the idx is TR with `cMax = +//! chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`. The §7.4.9.10 +//! derivation pair the flag + idx feed is `CuQpOffsetCb = (flag == 1) +//! ? cb_qp_offset_list[idx] : 0` (and symmetric for Cr). The new +//! public surface: [`CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX`] (= 1, Table +//! 9-43 shape) and [`CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS`] (= 1); +//! [`cu_chroma_qp_offset_flag_ctx_inc`] returns the Table 9-48 bin-0 +//! `ctxInc = 0` for the FL flag; [`cu_chroma_qp_offset_idx_tr_cmax`] +//! returns the per-TU `cMax` from the PPS-resolved +//! `chroma_qp_offset_list_len_minus1`; [`cu_chroma_qp_offset_idx_ctx_inc`] +//! returns the Table 9-48 `ctxInc = 0` (constant across the TR-prefix +//! bins 0..=4, since Table 9-48 lists `0` for every context-coded +//! binIdx column); and [`decode_cu_chroma_qp_offset`] drives the +//! CABAC engine to produce the typed [`CuChromaQpOffset`] (the +//! flag plus, when the flag is 1, the idx with the §7.4.9.10 +//! derivation gates surfaced via [`CuChromaQpOffset::offset_indices`]). +//! +//! Round 37 adds the §9.3.4.2 / Table 9-48 entry for +//! `cu_transquant_bypass_flag` — the per-CU bypass switch that, when +//! set, replaces the scaling + transform + in-loop-filter path with a +//! verbatim residual passthrough (H.265 §7.3.8.5, §7.4.9.5). Per +//! Table 9-43 the flag is FL with `cMax = 1` (a single context-coded +//! bin); Table 9-48's row lists `ctxInc = 0` for bin 0 and `na` for +//! every later binIdx column. The flag occupies a single context +//! (Table 9-8: `initValue = 154` at all three initType slots) which +//! sits at the slice-init-allocated bank entry the parser hands to +//! the decode primitive. The PPS gate is +//! `transquant_bypass_enabled_flag` (§7.4.3.3.1): the flag is read +//! from the bitstream only when that PPS field is 1, otherwise +//! §7.4.9.5 infers the value to 0 (the normal scaling-and-transform +//! path). The new public surface: +//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and +//! [`CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS`] (= 1); +//! [`cu_transquant_bypass_flag_ctx_inc`] returns the Table 9-48 bin-0 +//! `ctxInc = 0`; [`decode_cu_transquant_bypass_flag`] drives one +//! [`CabacEngine::decode_decision`] against the caller's context and +//! returns the decoded `u8`; [`cu_transquant_bypass_flag_inferred`] +//! surfaces the §7.4.9.5 "PPS gate off ⇒ value is 0" inference as a +//! pure helper for callers that branch on the PPS without entering +//! the engine. +//! +//! Round 38 adds the §9.3.4.2 / Table 9-48 entry for `rqt_root_cbf` — +//! the inter-CU gate that signals whether the `transform_tree( )` +//! syntax structure follows the current coding unit (H.265 §7.3.8.5, +//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single +//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0 +//! and `na` for every later binIdx column. Table 9-14 supplies a +//! single ctxIdx slot with `initValue = 79` at both initType 1 and +//! initType 2 (initType 0 is `na` in Table 9-4 — `rqt_root_cbf` is +//! only ever read in inter slices, where §7.3.8.5 wires it under +//! `CuPredMode != MODE_INTRA && !cu_skip_flag`). When the §7.3.8.5 +//! guard fails (intra CU, or skip CU) the flag is not present on the +//! wire and the §7.4.9.5 inferred value is 1 (the `transform_tree( )` +//! syntax structure is taken to be present). The new public surface: +//! [`RQT_ROOT_CBF_FL_CMAX`] (= 1, Table 9-43 shape) and +//! [`RQT_ROOT_CBF_FL_NBITS`] (= 1); [`rqt_root_cbf_ctx_inc`] returns +//! the Table 9-48 bin-0 `ctxInc = 0`; [`decode_rqt_root_cbf`] drives +//! one [`CabacEngine::decode_decision`] against the caller's context +//! and returns the decoded `u8`; [`rqt_root_cbf_inferred`] surfaces +//! the §7.4.9.5 "not present ⇒ value is 1" inference as a pure helper +//! for callers that branch on the §7.3.8.5 guard without entering the +//! engine. +//! +//! Round 39 adds the §9.3.4.2 / Table 9-48 entry for `pred_mode_flag` — +//! the per-CU bit that selects between MODE_INTER (value 0) and +//! MODE_INTRA (value 1) inside a P or B slice (H.265 §7.3.8.5, +//! §7.4.9.5). Per Table 9-43 the flag is FL with `cMax = 1` (a single +//! context-coded bin); Table 9-48's row lists `ctxInc = 0` for bin 0 +//! and `na` for every later binIdx column. Table 9-10 supplies two +//! ctxIdx slots with `initValue = {149, 134}` for initType 1 and +//! initType 2 (initType 0 is `na` in Table 9-4 — the §7.3.8.5 +//! `slice_type != I` guard skips the read for I slices, where the +//! mode is unconditionally intra). When the §7.3.8.5 guard fails the +//! flag is not present on the wire and §7.4.9.5 derives `CuPredMode` +//! directly: I slice ⇒ MODE_INTRA; P or B slice with +//! `cu_skip_flag == 1` ⇒ MODE_SKIP. The new public surface: +//! [`PRED_MODE_FLAG_FL_CMAX`] (= 1, Table 9-43 shape) and +//! [`PRED_MODE_FLAG_FL_NBITS`] (= 1); [`pred_mode_flag_ctx_inc`] +//! returns the Table 9-48 bin-0 `ctxInc = 0`; +//! [`decode_pred_mode_flag`] drives one +//! [`CabacEngine::decode_decision`] against the caller's context and +//! returns the decoded `u8`; the [`CuPredMode`] enum captures the +//! §7.4.9.5 mapping (`0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`, plus the +//! not-present-only MODE_SKIP state); [`cu_pred_mode_from_flag`] +//! applies the present-on-wire mapping; and +//! [`pred_mode_flag_inferred_cu_pred_mode`] applies the §7.4.9.5 +//! not-present inference branching on `slice_type` and `cu_skip_flag`. +//! +//! Round 40 adds the §9.3.4.2 / Table 9-48 entry for +//! `prev_intra_luma_pred_flag` — the per-luma-prediction-block bit that +//! selects, for an intra CU, whether the luma intra prediction mode is +//! taken from the most-probable-mode list (`mpm_idx` follows) or from +//! the remaining-mode field (`rem_intra_luma_pred_mode` follows), per +//! H.265 §7.3.8.5, §7.4.9.2. Per Table 9-43 the flag is FL with +//! `cMax = 1` (a single context-coded bin); Table 9-48's row lists +//! `ctxInc = 0` for bin 0 and `na` for every later binIdx column. +//! Table 9-12 supplies three ctxIdx slots with +//! `initValue = {184, 154, 183}` for initType 0, 1 and 2 — unlike +//! `pred_mode_flag`, this element is read in I, P and B slices (intra +//! CUs occur in every slice type), so all three initType slots are +//! populated. The flag is always present when the §7.3.8.5 intra-PB +//! loop reaches it (no inferred-value rule); when it is 1 the §8.4.2 +//! candidate-mode derivation supplies `IntraPredModeY` and `mpm_idx` +//! selects among the candidates, when it is 0 +//! `rem_intra_luma_pred_mode` carries the mode directly. The new +//! public surface: [`PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX`] (= 1, Table +//! 9-43 shape) and [`PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS`] (= 1); +//! [`prev_intra_luma_pred_flag_ctx_inc`] returns the Table 9-48 bin-0 +//! `ctxInc = 0`; the [`LumaIntraModeSource`] enum captures the +//! §7.4.9.2 selection (`1 ⇒ Mpm`, `0 ⇒ Remaining`); +//! [`luma_intra_mode_source_from_flag`] folds a decoded flag into the +//! enum; and [`decode_prev_intra_luma_pred_flag`] drives one +//! [`CabacEngine::decode_decision`] against the caller's context and +//! returns the decoded `u8`. +//! +//! Round 41 adds the two §7.3.8.5 luma-mode fields the round-40 flag +//! gates: `mpm_idx` (Table 9-43 TR with `cMax = 2`, `cRiceParam = 0`) +//! and `rem_intra_luma_pred_mode` (Table 9-43 FL with `cMax = 31`), +//! per H.265 §7.4.9.2 / §8.4.2. Both are fully bypass-coded (Table 9-48 +//! marks every bin `bypass`), so neither consumes a context model and +//! presence is exactly the [`LumaIntraModeSource`] selection. The new +//! public surface: [`MPM_IDX_TR_CMAX`] (= 2) + +//! [`MPM_IDX_TR_C_RICE_PARAM`] (= 0) and [`decode_mpm_idx`] (the +//! truncated-unary prefix through the bypass decoder, output `0..=2`); +//! [`REM_INTRA_LUMA_PRED_MODE_FL_CMAX`] (= 31) + +//! [`REM_INTRA_LUMA_PRED_MODE_FL_NBITS`] (= 5) and +//! [`decode_rem_intra_luma_pred_mode`] (five FL bypass bins MSB-first, +//! output `0..=31`). +//! +//! Round 42 adds the §7.3.8.5 chroma-mode field that follows the +//! round-40/41 luma-mode group: `intra_chroma_pred_mode`, per H.265 +//! §7.4.9.5 / §9.3.3.8 / §8.4.3. Unlike the Table 9-43 generic shapes, +//! this element has its own binarization process (§9.3.3.8 / Table +//! 9-46): the single-bin string `0` signals value 4, and a `1` prefix +//! followed by a two-bit FL suffix signals values 0..=3. Table 9-48 +//! marks bin 0 context-coded with `ctxInc = 0` (Table 9-13 supplies +//! `initValue = {63, 152, 152}` for initType 0, 1 and 2) and bins 1..2 +//! `bypass`. The §8.4.3 derivation maps the decoded value plus +//! `IntraPredModeY` to `modeIdx` via Table 8-2 (value 4 tracks the luma +//! mode; values 0..=3 select from {0, 26, 10, 1} with a collision +//! substitute of 34), then — when `ChromaArrayType == 2` — remaps +//! `modeIdx` through Table 8-3. The new public surface: +//! [`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`] (= 4, the Table 9-46 +//! single-bin value), [`INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS`] (= 2), +//! [`intra_chroma_pred_mode_ctx_inc`] (the Table 9-48 bin-0 +//! `ctxInc = 0`), [`decode_intra_chroma_pred_mode`] (one +//! [`CabacEngine::decode_decision`] then, for the `1` prefix, two +//! bypass bins; output `{0, 1, 2, 3, 4}`), +//! [`intra_pred_mode_c_mode_idx`] (Table 8-2), +//! [`INTRA_PRED_MODE_C_CHROMA_422_MAP`] / +//! [`intra_pred_mode_c_chroma_422`] (Table 8-3), and +//! [`derive_intra_pred_mode_c`] (the full §8.4.3 output). + +use crate::cabac::{CabacEngine, CabacError, ContextModel}; + +// --------------------------------------------------------------------- +// Truncated-rice helper — §9.3.3.10 +// --------------------------------------------------------------------- + +/// §9.3.3.10 — read a truncated-rice prefix with `cMax` and +/// `cRiceParam = 0` (the only configuration this module currently +/// needs). The prefix is unary up to a maximum of `cMax >> 0` = `cMax` +/// bins; a value of `cMax / (1 << 0)` = `cMax` is the "escape" form +/// signalling that a suffix follows for callers that pair TR with an +/// EGk continuation. +/// +/// `read_bin(bin_idx)` decodes the bin at index `bin_idx` (0-based) +/// using the caller's choice of context-coded or bypass-coded path, and +/// returns the decoded bin (0 = continue, 1 = terminate / escape). +/// +/// Returns `(prefix_val, is_escape)`. `is_escape` is `true` exactly +/// when `prefix_val == cMax`: i.e. all `cMax` bins were 1, signalling +/// that a TR + EGk continuation suffix must be read by the caller. +pub(crate) fn read_truncated_rice_prefix( + c_max: u32, + mut read_bin: F, +) -> Result<(u32, bool), CabacError> +where + F: FnMut(u32) -> Result, +{ + // Unary: count leading 1s up to c_max. The decoded bin tally is + // simultaneously the prefix value (number of leading 1s) and the + // escape signal (all-ones when value == c_max). + let mut value: u32 = 0; + while value < c_max { + let bin = read_bin(value)?; + if bin == 0 { + return Ok((value, false)); + } + value += 1; + } + Ok((value, true)) +} + +// --------------------------------------------------------------------- +// §9.3.3.3 — Exp-Golomb of order k (bypass-coded, MSB-first prefix then +// suffix). Per the §9.3.3.3 NOTE the EGk prefix uses 1's and 0's in the +// reverse meaning of the §9.2 EG0 prefix: it is a unary run of `1` bins +// terminated by a single `0`, followed by `prefix_ones + k` suffix bits. +// --------------------------------------------------------------------- + +/// §9.3.3.3 — decode an EGk-coded value from the bypass stream for +/// arbitrary Exp-Golomb order `k`. +/// +/// The reader counts leading `1` bypass bins until a terminating `0` +/// (call this count `prefix_ones`); reads `prefix_ones + k` more +/// bypass bins as the suffix; and returns +/// `((1 << prefix_ones) - 1) << k + suffix`. +/// +/// For `k = 0` the reader collapses to the `cu_qp_delta_abs`-style +/// "(1 << lz) - 1 + suffix" form (suffix length == `leading_zeros`, +/// `<< 0` factor disappears) — preserved as +/// [`decode_eg_k0`] for callers that only need the `k = 0` case. +/// +/// `leading_zeros` is capped at 32 to keep the decoder defensive +/// against runaway encodings; the cap is comfortably above any legal +/// HEVC bypass-coded suffix value (§7.4.9.11 puts the practical +/// ceiling well below `2^31`). +pub(crate) fn decode_eg_k(engine: &mut CabacEngine<'_>, k: u32) -> Result { + read_eg_k_with(k, || engine.decode_bypass()) +} + +/// §9.3.3.3 — decode an EGk-coded value of order `k` from a generic +/// bin reader (each call yields the next bypass bin). Factored out of +/// [`decode_eg_k`] so the §7.3.8.9 `abs_mvd_minus2` EG1 escape can be +/// composed and unit-tested without driving the arithmetic engine's +/// range/offset state. The decode follows the equation-9-13 do-while: +/// per the §9.3.3.3 NOTE the EGk unary prefix uses 1's and 0's in the +/// reverse meaning of the §9.2 EG0 prefix, so the prefix is a run of +/// `1` bins terminated by a single `0`. Count those leading `1` bins +/// (`prefix_ones`), then read `prefix_ones + k` suffix bins, yielding +/// `((1 << prefix_ones) − 1) << k + suffix`. +pub(crate) fn read_eg_k_with(k: u32, mut read_bin: F) -> Result +where + F: FnMut() -> Result, +{ + let mut prefix_ones: u32 = 0; + while prefix_ones < 32 { + let bin = read_bin()?; + if bin == 0 { + break; + } + prefix_ones += 1; + } + // Guard against accidental >32-bit reads (cap `prefix_ones` at + // 32 already bounds this; the saturate keeps the read width inside + // a single `u32` if `k` is unusually large). + let suffix_bits = (prefix_ones + k).min(32); + let mut suffix: u32 = 0; + for _ in 0..suffix_bits { + suffix = (suffix << 1) | u32::from(read_bin()?); + } + let base = ((1u64 << prefix_ones) - 1) << k; + let value = base + u64::from(suffix); + // The defensive cap above keeps `value` inside `u32`; the + // saturate keeps us inside the public return type if the + // pathological 32-bit edge is ever reached. + Ok(u32::try_from(value).unwrap_or(u32::MAX)) +} + +/// §9.3.3.11 — decode an EGk-coded value with `k = 0` from the bypass +/// stream. Preserved as a named alias for the `cu_qp_delta_abs` / +/// `palette_escape_val` callers that historically used the `k = 0` +/// fast path; equivalent to `decode_eg_k(engine, 0)`. +fn decode_eg_k0(engine: &mut CabacEngine<'_>) -> Result { + decode_eg_k(engine, 0) +} + +// --------------------------------------------------------------------- +// cu_qp_delta_abs / cu_qp_delta_sign_flag (§7.3.8.14, §7.4.9.14) +// --------------------------------------------------------------------- + +/// §9.3.4.2.2 Table 9-32 — per-bin `ctxInc` for `cu_qp_delta_abs`. Bin +/// 0 uses a dedicated context (`ctxInc = 0`); bins 1..=4 share a second +/// dedicated context (`ctxInc = 1`). The TR prefix carries at most +/// `cMax = 5` bins; the EGk(k=0) suffix is bypass-coded and not +/// indexed. +#[must_use] +pub fn cu_qp_delta_abs_ctx_inc(bin_idx: u32) -> u32 { + if bin_idx == 0 { + 0 + } else { + 1 + } +} + +/// `cu_qp_delta_abs` TR prefix `cMax`. §9.3.3.10 (with §9.3.4.2.2 +/// row). +pub const CU_QP_DELTA_ABS_TR_CMAX: u32 = 5; + +/// Decoded `cu_qp_delta` pair plus the §7.4.9.14 derived +/// `CuQpDeltaVal`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CuQpDelta { + /// `cu_qp_delta_abs` from the wire. + pub abs: u32, + /// `cu_qp_delta_sign_flag` from the wire; `None` when + /// `abs == 0` (the flag is not signalled in that case). + pub sign_flag: Option, + /// Derived signed delta: + /// `cu_qp_delta_abs * (1 − 2 * cu_qp_delta_sign_flag)`. + /// Equals `0` when `abs == 0`. + pub value: i32, +} + +/// Decode the `cu_qp_delta` syntax pair (§7.3.8.14 / §7.4.9.14) from +/// the CABAC engine, consuming the two context variables for the +/// `cu_qp_delta_abs` TR prefix (bin 0 + bins 1..=4) and any required +/// bypass bins for the EGk(k=0) suffix and the sign flag. +/// +/// `ctx_bin0` and `ctx_bin_rest` are the caller's +/// `(pStateIdx, valMps)` state for the two `cu_qp_delta_abs` contexts; +/// they are mutated in place per §9.3.4.3.2.2 state transition. +/// +/// Returns the decoded [`CuQpDelta`] including the §7.4.9.14 +/// `CuQpDeltaVal` derivation. +pub fn decode_cu_qp_delta( + engine: &mut CabacEngine<'_>, + ctx_bin0: &mut ContextModel, + ctx_bin_rest: &mut ContextModel, +) -> Result { + // Decode the §9.3.3.10 TR prefix using two contexts: bin 0 uses + // ctx_bin0, all subsequent bins share ctx_bin_rest. + let (prefix, is_escape) = read_truncated_rice_prefix(CU_QP_DELTA_ABS_TR_CMAX, |bin_idx| { + if cu_qp_delta_abs_ctx_inc(bin_idx) == 0 { + engine.decode_decision(ctx_bin0) + } else { + engine.decode_decision(ctx_bin_rest) + } + })?; + + // §9.3.3.10: if the prefix is the all-ones escape (== cMax), an + // EGk(k=0) suffix follows; the decoded value is prefix + suffix. + let abs = if is_escape { + prefix + decode_eg_k0(engine)? + } else { + prefix + }; + + // §7.4.9.14: the sign flag is signalled only when abs != 0. + let (sign_flag, signed) = if abs == 0 { + (None, 0i32) + } else { + let s = engine.decode_bypass()?; + // CuQpDeltaVal = abs * (1 − 2 * sign_flag) + let sign_factor = 1i32 - 2 * (s as i32); + (Some(s), abs as i32 * sign_factor) + }; + + Ok(CuQpDelta { + abs, + sign_flag, + value: signed, + }) +} + +// --------------------------------------------------------------------- +// cu_chroma_qp_offset_flag / cu_chroma_qp_offset_idx +// (§7.3.8.11 transform_unit() / §7.4.9.10 — PPS chroma-QP-offset list +// gating). Table 9-43 binarizations + Table 9-48 ctxInc derivations. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `cu_chroma_qp_offset_flag`: FL +/// with `cMax = 1` (a single context-coded bin). +pub const CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `cu_chroma_qp_offset_flag`: one +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_flag`. Bin 0 +/// is context-coded with `ctxInc = 0`; later bin-index columns are +/// `na` (the FL `cMax = 1` shape only emits a single bin). +/// +/// The flag's Table 9-34 ctxIdx layout (`initValue = 154` at every +/// initType slot) is consumed at slice-init scope; this layer hands +/// back the bank-relative `ctxInc` only. +#[must_use] +pub fn cu_chroma_qp_offset_flag_ctx_inc() -> u32 { + 0 +} + +/// §9.3.4.2.1 / Table 9-48 row for `cu_chroma_qp_offset_idx`. Every +/// context-coded bin column (binIdx 0..=4 of the TR prefix) lists +/// `ctxInc = 0`; binIdx 5 is `na` (the §7.4.9.10 idx range tops out +/// at `chroma_qp_offset_list_len_minus1 <= 5`, so the spec-mandated +/// `cMax <= 5` TR prefix can produce at most five bins). +/// +/// The idx's Table 9-35 ctxIdx layout (`initValue = 154` at every +/// initType slot) is consumed at slice-init scope; this layer hands +/// back the bank-relative `ctxInc` only. +/// +/// `bin_idx` is the §9.3.4.2 binIdx of the bin being coded; values +/// outside `0..=4` are `na` per Table 9-48. +#[must_use] +pub fn cu_chroma_qp_offset_idx_ctx_inc(bin_idx: u32) -> u32 { + debug_assert!( + bin_idx <= 4, + "cu_chroma_qp_offset_idx Table 9-48 row: binIdx > 4 is na" + ); + 0 +} + +/// §9.3.3.10 / Table 9-43 row for `cu_chroma_qp_offset_idx`: TR with +/// `cMax = chroma_qp_offset_list_len_minus1`, `cRiceParam = 0`. +/// `chroma_qp_offset_list_len_minus1` is the PPS-signalled length of +/// `cb_qp_offset_list[ ]` / `cr_qp_offset_list[ ]` minus one +/// (§7.4.3.3.1: a `u(3)` field, bounded by `<= 5`). +#[must_use] +pub fn cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1: u32) -> u32 { + chroma_qp_offset_list_len_minus1 +} + +/// Decoded `cu_chroma_qp_offset_flag` / `cu_chroma_qp_offset_idx` pair +/// with the §7.4.9.10 chroma-QP-offset-list dereference surfaced as a +/// typed accessor. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CuChromaQpOffset { + /// `cu_chroma_qp_offset_flag` from the wire. + pub flag: u8, + /// `cu_chroma_qp_offset_idx` from the wire; `None` when the flag + /// is 0 (the idx is not signalled in that case per §7.3.8.11). + /// When the flag is 1 and `chroma_qp_offset_list_len_minus1 == 0` + /// the idx is also not signalled (the TR prefix has `cMax = 0`, + /// emitting zero bins) and the value is inferred to be 0. + pub idx: Option, +} + +impl CuChromaQpOffset { + /// §7.4.9.10 — return the `(cb_qp_offset_list, cr_qp_offset_list)` + /// indices to dereference for `CuQpOffsetCb` / `CuQpOffsetCr`. + /// `None` is returned when the flag is 0: per §7.4.9.10 the + /// offsets are then both 0 (no list dereference). + #[must_use] + pub fn offset_indices(&self) -> Option { + if self.flag == 0 { + None + } else { + // §7.4.9.10: when present, idx defaults to 0; absent ⇒ + // also 0 (the cMax = 0 / not-signalled paths share the + // same inferred value). + Some(self.idx.unwrap_or(0)) + } + } +} + +/// Decode the `cu_chroma_qp_offset` syntax pair (§7.3.8.11 / +/// §7.4.9.10) from the CABAC engine, consuming one context for the +/// FL `cu_chroma_qp_offset_flag` bin and (when the flag is 1 and +/// `chroma_qp_offset_list_len_minus1 > 0`) one context for the TR +/// prefix of `cu_chroma_qp_offset_idx`. All bins of both elements +/// share `ctxInc = 0` per Table 9-48; the contexts live in separate +/// Table 9-4 banks (Table 9-34 for the flag, Table 9-35 for the +/// idx). +/// +/// `ctx_flag` and `ctx_idx` are the caller's +/// `(pStateIdx, valMps)` state for the two contexts; they are +/// mutated in place per §9.3.4.3.2.2 state transition. +/// +/// `chroma_qp_offset_list_len_minus1` is the PPS field that bounds +/// the TR prefix; the function panics in debug if it exceeds 5 +/// (the §7.4.3.3.1 `u(3)` field's upper bound). +/// +/// Returns the decoded [`CuChromaQpOffset`]. +pub fn decode_cu_chroma_qp_offset( + engine: &mut CabacEngine<'_>, + ctx_flag: &mut ContextModel, + ctx_idx: &mut ContextModel, + chroma_qp_offset_list_len_minus1: u32, +) -> Result { + debug_assert!( + chroma_qp_offset_list_len_minus1 <= 5, + "chroma_qp_offset_list_len_minus1 is a u(3) field bounded by 5 per §7.4.3.3.1" + ); + + // §9.3.4.2.1 + Table 9-48 + Table 9-43: bin 0 of the FL flag + // uses ctxInc = 0 and the FL cMax = 1 shape emits exactly one + // bin. + let flag = engine.decode_decision(ctx_flag)?; + + // §7.3.8.11: the idx is signalled only when the flag is 1 and + // the list has more than one entry (else the TR cMax = 0 shape + // emits no bins and the idx is inferred to be 0 per §7.4.9.10). + let idx = if flag == 1 && chroma_qp_offset_list_len_minus1 > 0 { + let c_max = cu_chroma_qp_offset_idx_tr_cmax(chroma_qp_offset_list_len_minus1); + // §9.3.3.10 TR prefix with cRiceParam = 0; every bin uses + // ctx_idx (Table 9-48 ctxInc = 0). + let (prefix, _is_escape) = + read_truncated_rice_prefix(c_max, |_bin_idx| engine.decode_decision(ctx_idx))?; + // The TR escape (all-ones prefix == cMax) terminates the + // idx — there is no suffix continuation for this element + // (Table 9-43 has no follow-on EGk row). + Some(prefix) + } else { + None + }; + + Ok(CuChromaQpOffset { flag, idx }) +} + +// --------------------------------------------------------------------- +// cu_transquant_bypass_flag (§7.3.8.5 coding_unit() / §7.4.9.5) +// PPS gate: transquant_bypass_enabled_flag (§7.4.3.3.1). Table 9-43 +// FL binarization + Table 9-48 ctxInc + Table 9-8 ctxIdx initValue. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `cu_transquant_bypass_flag`: FL +/// with `cMax = 1` (a single context-coded bin per CU). +pub const CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `cu_transquant_bypass_flag`: one +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `cu_transquant_bypass_flag`. Bin 0 +/// is context-coded with `ctxInc = 0`; every later binIdx column is +/// `na` (the FL `cMax = 1` shape only emits a single bin). +/// +/// The flag's Table 9-8 ctxIdx layout (`initValue = 154` at every +/// initType slot — same `pStateIdx`/`valMps` start at all three +/// slice-type initialisation rows) is consumed at slice-init scope; +/// this layer hands back the bank-relative `ctxInc` only. +#[must_use] +pub fn cu_transquant_bypass_flag_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.5 — inferred value of `cu_transquant_bypass_flag` when the +/// PPS gate `transquant_bypass_enabled_flag` is 0 and the element is +/// not present on the wire. The spec mandates an inferred value of +/// `0` (normal scaling-and-transform path). +/// +/// Exposed as a pure helper so the parser can branch on the PPS +/// without entering the CABAC engine: when the PPS gate is off the +/// caller skips [`decode_cu_transquant_bypass_flag`] entirely and +/// records the inferred `0`. +#[must_use] +pub fn cu_transquant_bypass_flag_inferred() -> u8 { + 0 +} + +/// Decode `cu_transquant_bypass_flag` (§7.3.8.5 / §7.4.9.5) from the +/// CABAC engine, consuming one context for the FL bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-8 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per +/// §9.3.4.3.2.2 state transition. +/// +/// The PPS gate `transquant_bypass_enabled_flag` (§7.4.3.3.1) is +/// upstream of this primitive: when the gate is 0 the parser does +/// **not** call this function — see [`cu_transquant_bypass_flag_inferred`] +/// for the §7.4.9.5 inferred value. +/// +/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.6 / §8.7 +/// transquant-bypass passthrough for the current CU per §7.4.9.5. +pub fn decode_cu_transquant_bypass_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table + // 9-8 entry) per the Table 9-48 row. + debug_assert_eq!( + cu_transquant_bypass_flag_ctx_inc(), + 0, + "Table 9-48 row for cu_transquant_bypass_flag: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// rqt_root_cbf (§7.3.8.5 coding_unit() / §7.4.9.5) +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-14 ctxIdx +// initValue. Present only when the current coding unit is not +// IntraPredMode (i.e. CuPredMode == MODE_INTER) and the cu_skip_flag +// is 0; absent ⇒ inferred to 1 (the §7.4.9.5 / 2021 spec wording). +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `rqt_root_cbf`: FL with `cMax = 1` +/// (a single context-coded bin per inter CU). Marks whether the +/// `transform_tree( )` syntax structure is present for the current +/// coding unit (§7.4.9.5). +pub const RQT_ROOT_CBF_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `rqt_root_cbf`: one context-coded bin +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const RQT_ROOT_CBF_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `rqt_root_cbf`. Bin 0 is +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` +/// (the FL `cMax = 1` shape only emits a single bin). +/// +/// The flag's Table 9-14 ctxIdx layout has only the initType 1 and +/// initType 2 slots populated (`initValue = 79` at both); initType 0 +/// is `na` per Table 9-4, since `rqt_root_cbf` is only ever read in +/// inter slices (§7.3.8.5 routes the read under +/// `CuPredMode != MODE_INTRA && !cu_skip_flag`). This layer hands back +/// the bank-relative `ctxInc` only; the Table 9-14 initValue plus +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init +/// scope. +#[must_use] +pub fn rqt_root_cbf_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.5 — inferred value of `rqt_root_cbf` when the element is not +/// present on the wire. The 2021 spec wording (V8/v8.0) mandates an +/// inferred value of `1` (the `transform_tree( )` syntax structure is +/// taken to be present); the V11/2026 revision conditions the +/// inference on `!DcOnlyFlag[ x0 ][ y0 ]`, but the V8 baseline this +/// rebuild targets is the unconditional 1. +/// +/// Exposed as a pure helper so the parser can branch without entering +/// the CABAC engine when the §7.3.8.5 guard (`CuPredMode == MODE_INTRA +/// || cu_skip_flag == 1`) selects the not-present path. +#[must_use] +pub fn rqt_root_cbf_inferred() -> u8 { + 1 +} + +/// Decode `rqt_root_cbf` (§7.3.8.5 / §7.4.9.5) from the CABAC engine, +/// consuming one context for the FL bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-14 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per +/// §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.5 guard (`CuPredMode != MODE_INTRA && !cu_skip_flag`) is +/// upstream of this primitive: when the guard fails the parser does +/// **not** call this function — see [`rqt_root_cbf_inferred`] for the +/// §7.4.9.5 inferred value. +/// +/// Returns the decoded `u8` (0 or 1) — 1 means the `transform_tree( )` +/// syntax structure follows the current coding-unit body; 0 means the +/// CU has no transform-tree (samples derive from prediction only per +/// §7.4.9.5). +pub fn decode_rqt_root_cbf( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table + // 9-14 entry) per the Table 9-48 row. + debug_assert_eq!( + rqt_root_cbf_ctx_inc(), + 0, + "Table 9-48 row for rqt_root_cbf: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// merge_flag (§7.3.8.6 prediction_unit() / §7.4.9.6) +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-15 ctxIdx +// initValue. Read in the §7.3.8.6 `else /* MODE_INTER */` branch +// (i.e. cu_skip_flag == 0); when present and 1 the inter-prediction +// parameters are inferred from a neighbouring inter partition +// (merge_idx follows), when 0 the explicit motion fields +// (inter_pred_idc / ref_idx / mvp) are coded. Absent ⇒ inferred per +// §7.4.9.6 from CuPredMode (MODE_SKIP ⇒ 1, otherwise 0). +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `merge_flag`: FL with `cMax = 1` +/// (a single context-coded bin per non-skip inter prediction unit). +/// Selects between the merge path (value 1 — inter-prediction +/// parameters inferred from a neighbouring inter-predicted partition) +/// and the explicit-motion path (value 0) per §7.4.9.6. +pub const MERGE_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `merge_flag`: one context-coded bin +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const MERGE_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `merge_flag`. Bin 0 is +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` +/// (the FL `cMax = 1` shape only emits a single bin). +/// +/// The flag's Table 9-15 ctxIdx layout has only the initType 1 and +/// initType 2 slots populated (`initValue = 110` at initType 1, +/// `initValue = 154` at initType 2); initType 0 is `na` in Table 9-4 +/// because `merge_flag` is only ever read in inter (P/B) slices — the +/// §7.3.8.6 `prediction_unit( )` read sits under the coding-unit's +/// inter path (`CuPredMode != MODE_INTRA && !cu_skip_flag`), which is +/// unreachable in an I slice. This layer hands back the bank-relative +/// `ctxInc` only; the Table 9-15 initValue plus Table 9-4 +/// initType-to-ctxIdx mapping is consumed at slice-init scope (see +/// `ctx_init::TABLE_9_15_MERGE_FLAG`). +#[must_use] +pub fn merge_flag_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.6 — inferred value of `merge_flag` when the element is not +/// present on the wire. The §7.3.8.6 guard that suppresses the read is +/// `cu_skip_flag == 1` (the skip path codes only `merge_idx`); the +/// §7.4.9.6 inference is then: +/// +/// * If `CuPredMode[ x0 ][ y0 ]` is equal to `MODE_SKIP`, +/// `merge_flag` is inferred to be equal to 1. +/// * Otherwise, `merge_flag` is inferred to be equal to 0. +/// +/// `cu_pred_mode` is the §7.4.9.5 prediction mode of the current +/// coding unit. The only not-present path the §7.3.8.6 syntax reaches +/// is the `cu_skip_flag == 1` branch, whose CuPredMode is +/// [`CuPredMode::Skip`] per §7.4.9.5 — so this returns 1 for +/// [`CuPredMode::Skip`] and 0 for the inter/intra modes (which would +/// only arise from a caller bug, since a present `merge_flag` is +/// decoded rather than inferred on those paths). +/// +/// Exposed as a pure helper so the parser can branch without entering +/// the CABAC engine when the §7.3.8.6 skip path selects the +/// not-present case. +#[must_use] +pub fn merge_flag_inferred(cu_pred_mode: CuPredMode) -> u8 { + // §7.4.9.6: CuPredMode == MODE_SKIP ⇒ 1, otherwise ⇒ 0. + u8::from(cu_pred_mode == CuPredMode::Skip) +} + +/// Decode `merge_flag` (§7.3.8.6 / §7.4.9.6) from the CABAC engine, +/// consuming one context for the FL bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-15 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per +/// §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.6 guard (the `else /* MODE_INTER */` branch — i.e. +/// `cu_skip_flag == 0`) is upstream of this primitive: when the CU +/// takes the skip path the parser does **not** call this function — +/// see [`merge_flag_inferred`] for the §7.4.9.6 not-present value. +/// +/// Returns the decoded `u8` (0 or 1) — 1 selects the merge path (the +/// inter-prediction parameters are inferred from a neighbouring +/// inter-predicted partition, `merge_idx` follows per §7.3.8.6); 0 +/// selects the explicit-motion path (`inter_pred_idc` / `ref_idx_lX` / +/// `mvp_lX_flag` / `mvd_coding` are coded). +pub fn decode_merge_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table + // 9-15 entry) per the Table 9-48 row. + debug_assert_eq!( + merge_flag_ctx_inc(), + 0, + "Table 9-48 row for merge_flag: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// pred_mode_flag (§7.3.8.5 coding_unit() / §7.4.9.5) +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-10 ctxIdx +// initValue. Present only when the slice is P or B (slice_type != I) +// and cu_skip_flag == 0; absent ⇒ CuPredMode is derived per §7.4.9.5 +// from slice_type and cu_skip_flag without entering the engine. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `pred_mode_flag`: FL with +/// `cMax = 1` (a single context-coded bin per non-skip P/B coding +/// unit). Selects between MODE_INTER (value 0) and MODE_INTRA (value +/// 1) per §7.4.9.5. +pub const PRED_MODE_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `pred_mode_flag`: one context-coded +/// bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const PRED_MODE_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `pred_mode_flag`. Bin 0 is +/// context-coded with `ctxInc = 0`; every later binIdx column is `na` +/// (the FL `cMax = 1` shape only emits a single bin). +/// +/// The flag's Table 9-10 ctxIdx layout has only the initType 1 and +/// initType 2 slots populated (`initValue = 149` at initType 1, +/// `initValue = 134` at initType 2); initType 0 is `na` in Table 9-4 +/// because the §7.3.8.5 `slice_type != I` guard skips the read for I +/// slices entirely. This layer hands back the bank-relative `ctxInc` +/// only; the Table 9-10 initValue plus Table 9-4 initType-to-ctxIdx +/// mapping is consumed at slice-init scope. +#[must_use] +pub fn pred_mode_flag_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.5 / §9.5.1 — the coding-unit prediction mode. Selected by +/// `pred_mode_flag` (when present on the wire) or inferred from +/// slice-level state (when not present), per §7.4.9.5. +/// +/// `pred_mode_flag == 0` maps to [`CuPredMode::Inter`]; +/// `pred_mode_flag == 1` maps to [`CuPredMode::Intra`]. +/// [`CuPredMode::Skip`] is reachable only via the §7.4.9.5 +/// not-present inference path: a P or B slice CU whose `cu_skip_flag` +/// is 1 and whose `pred_mode_flag` was therefore not coded. +/// +/// The enum is local to the binarization module because no other +/// module currently expresses CuPredMode in code; the +/// `coding_unit( )` syntax walker may promote it to a wider type in +/// a future round. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum CuPredMode { + /// MODE_INTER — inter-picture prediction (samples derived from a + /// reference picture). Reachable from `pred_mode_flag == 0` (P + /// or B slice, non-skip CU). + Inter, + /// MODE_INTRA — intra-picture prediction (samples derived from + /// neighbouring reconstructed samples in the current picture). + /// Reachable from `pred_mode_flag == 1` and from the I-slice + /// not-present inference (§7.4.9.5). + Intra, + /// MODE_SKIP — inter-prediction skip path (no residual, no + /// `pred_mode_flag`, no transform tree). Reachable only from + /// §7.4.9.5 not-present inference when `slice_type != I` and + /// `cu_skip_flag == 1`. + Skip, +} + +/// Map a decoded `pred_mode_flag` value to [`CuPredMode`] per +/// §7.4.9.5: `0 ⇒ MODE_INTER`, `1 ⇒ MODE_INTRA`. The mapping is +/// total over the FL `cMax = 1` shape (any other input is rejected +/// in debug builds; release builds fall back to MODE_INTRA to keep +/// the function `must_use`-friendly without panicking on accidental +/// out-of-range inputs). +#[must_use] +pub fn cu_pred_mode_from_flag(pred_mode_flag: u8) -> CuPredMode { + debug_assert!( + pred_mode_flag <= 1, + "pred_mode_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1" + ); + if pred_mode_flag == 0 { + CuPredMode::Inter + } else { + CuPredMode::Intra + } +} + +/// §7.4.9.5 — derive [`CuPredMode`] for a coding unit whose +/// `pred_mode_flag` is not present on the wire. The §7.3.8.5 guard +/// that suppresses the read is `slice_type == I` (no flag is coded +/// because the slice is purely intra) or `cu_skip_flag == 1` (the +/// skip path bypasses the flag). +/// +/// `slice_type_is_i` is `true` iff the current slice has +/// `slice_type == I` per §7.4.7.1. +/// `cu_skip_flag` is the §7.3.8.5 / §7.4.9.5 decoded skip flag (or +/// the 0-inferred value when `slice_type == I`). +/// +/// The §7.4.9.5 derivation: +/// +/// * If the slice is I, `CuPredMode` is inferred to MODE_INTRA +/// regardless of `cu_skip_flag` (which is itself not coded for +/// I slices and inferred to 0 per §7.4.9.5). +/// * Otherwise (P or B slice), the only path that reaches this +/// helper is `cu_skip_flag == 1`; the spec then infers +/// `CuPredMode = MODE_SKIP`. A `cu_skip_flag == 0` input would +/// contradict the §7.3.8.5 guard (the flag *would* be present +/// and decoded); the function asserts this in debug builds and +/// falls back to MODE_INTER in release builds to avoid panicking +/// on a caller bug. +#[must_use] +pub fn pred_mode_flag_inferred_cu_pred_mode(slice_type_is_i: bool, cu_skip_flag: u8) -> CuPredMode { + if slice_type_is_i { + // §7.4.9.5: "If slice_type is equal to I, CuPredMode[ x ][ y ] + // is inferred to be equal to MODE_INTRA." cu_skip_flag is not + // coded for I slices (§7.3.8.5 `if( slice_type != I )` guard) + // and is itself inferred to 0; the I-slice branch is therefore + // unconditional on the skip flag. + CuPredMode::Intra + } else { + // §7.4.9.5: "Otherwise (slice_type is equal to P or B), when + // cu_skip_flag[ x0 ][ y0 ] is equal to 1, CuPredMode[ x ][ y ] + // is inferred to be equal to MODE_SKIP." The §7.3.8.5 + // pred_mode_flag read is gated on `!cu_skip_flag[ x0 ][ y0 ]`, + // so the only way this branch is reached on a P/B slice is + // with cu_skip_flag == 1. + debug_assert_eq!( + cu_skip_flag, 1, + "§7.4.9.5: pred_mode_flag not-present on a P/B slice requires cu_skip_flag == 1" + ); + CuPredMode::Skip + } +} + +/// Decode `pred_mode_flag` (§7.3.8.5 / §7.4.9.5) from the CABAC +/// engine, consuming one context for the FL bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-10 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place +/// per §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.5 guard (`slice_type != I && !cu_skip_flag`) is +/// upstream of this primitive: when the guard fails the parser does +/// **not** call this function — see +/// [`pred_mode_flag_inferred_cu_pred_mode`] for the §7.4.9.5 +/// not-present derivation. +/// +/// Returns the decoded `u8` (0 or 1) — 0 selects MODE_INTER per +/// §7.4.9.5 (`CuPredMode = MODE_INTER`), 1 selects MODE_INTRA +/// (`CuPredMode = MODE_INTRA`). See [`cu_pred_mode_from_flag`] to +/// fold the result into the [`CuPredMode`] enum. +pub fn decode_pred_mode_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table + // 9-10 entry) per the Table 9-48 row. + debug_assert_eq!( + pred_mode_flag_ctx_inc(), + 0, + "Table 9-48 row for pred_mode_flag: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// prev_intra_luma_pred_flag (§7.3.8.5 coding_unit() / §7.4.9.2) +// Table 9-43 FL binarization + Table 9-48 ctxInc + Table 9-12 ctxIdx +// initValue. Read once per luma prediction block of an intra CU (the +// §7.3.8.5 `for( j ) for( i )` PB loop). When the flag is 1 the luma +// intra mode is taken from the §8.4.2 most-probable-mode list (mpm_idx +// follows); when 0 it comes from rem_intra_luma_pred_mode. There is no +// not-present inference: the §7.3.8.5 loop always reads it. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `prev_intra_luma_pred_flag`: FL +/// with `cMax = 1` (a single context-coded bin per luma prediction +/// block of an intra CU). Selects between the MPM-list mode source +/// (value 1) and the remaining-mode field (value 0) per §7.4.9.2. +pub const PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `prev_intra_luma_pred_flag`: one +/// context-coded bin per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `prev_intra_luma_pred_flag`. Bin 0 +/// is context-coded with `ctxInc = 0`; every later binIdx column is +/// `na` (the FL `cMax = 1` shape only emits a single bin). +/// +/// Table 9-12 lists three ctxIdx slots with +/// `initValue = {184, 154, 183}` for initType 0, 1 and 2 — the element +/// is read in I, P and B slices (intra CUs occur in every slice type), +/// so all three initType slots are populated (unlike `pred_mode_flag`, +/// whose initType 0 column is `na`). This layer hands back the +/// bank-relative `ctxInc` only; the Table 9-12 initValue plus the +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init +/// scope. +#[must_use] +pub fn prev_intra_luma_pred_flag_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.2 — the source of a luma prediction block's intra mode, +/// selected by `prev_intra_luma_pred_flag`. +/// +/// `prev_intra_luma_pred_flag == 1` maps to [`LumaIntraModeSource::Mpm`] +/// (the §8.4.2 most-probable-mode candidate list; `mpm_idx` follows in +/// the §7.3.8.5 syntax to select among the candidates). +/// `prev_intra_luma_pred_flag == 0` maps to +/// [`LumaIntraModeSource::Remaining`] (the §7.3.8.5 +/// `rem_intra_luma_pred_mode` field carries the mode directly). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum LumaIntraModeSource { + /// The luma intra mode is taken from the §8.4.2 most-probable-mode + /// candidate list. Reachable from `prev_intra_luma_pred_flag == 1`; + /// the §7.3.8.5 `mpm_idx` element follows to pick a candidate. + Mpm, + /// The luma intra mode is carried directly by the §7.3.8.5 + /// `rem_intra_luma_pred_mode` field. Reachable from + /// `prev_intra_luma_pred_flag == 0`. + Remaining, +} + +/// Map a decoded `prev_intra_luma_pred_flag` value to +/// [`LumaIntraModeSource`] per §7.4.9.2 / §7.3.8.5: `1 ⇒ Mpm`, +/// `0 ⇒ Remaining`. The mapping is total over the FL `cMax = 1` shape +/// (any other input is rejected in debug builds; release builds fall +/// back to [`LumaIntraModeSource::Remaining`] to avoid panicking on an +/// accidental out-of-range input). +#[must_use] +pub fn luma_intra_mode_source_from_flag(prev_intra_luma_pred_flag: u8) -> LumaIntraModeSource { + debug_assert!( + prev_intra_luma_pred_flag <= 1, + "prev_intra_luma_pred_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1" + ); + if prev_intra_luma_pred_flag == 1 { + LumaIntraModeSource::Mpm + } else { + LumaIntraModeSource::Remaining + } +} + +/// Decode `prev_intra_luma_pred_flag` (§7.3.8.5 / §7.4.9.2) from the +/// CABAC engine, consuming one context for the FL bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-12 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per +/// the §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.5 intra-PB loop always reaches this read for an intra CU +/// (there is no not-present inference rule for this element), so the +/// parser unconditionally calls this primitive once per luma +/// prediction block. +/// +/// Returns the decoded `u8` (0 or 1) — 1 selects the §8.4.2 +/// most-probable-mode source (`mpm_idx` follows), 0 selects the +/// `rem_intra_luma_pred_mode` source. See +/// [`luma_intra_mode_source_from_flag`] to fold the result into the +/// [`LumaIntraModeSource`] enum. +pub fn decode_prev_intra_luma_pred_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin uses ctxInc = 0 (a single Table + // 9-12 entry) per the Table 9-48 row. + debug_assert_eq!( + prev_intra_luma_pred_flag_ctx_inc(), + 0, + "Table 9-48 row for prev_intra_luma_pred_flag: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// mpm_idx / rem_intra_luma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.2) +// Table 9-43 binarization + Table 9-48 (both fully bypass-coded). These +// are the two §7.3.8.5 intra-PB luma-mode fields that follow +// prev_intra_luma_pred_flag: when the flag is 1 the §8.4.2 candidate +// list is selected and `mpm_idx` (TR cMax = 2, cRiceParam = 0) picks +// among the three candidates; when 0 `rem_intra_luma_pred_mode` +// (FL cMax = 31) carries the residual mode directly. Neither element is +// context-coded — Table 9-48 marks every bin `bypass` — so the slice +// parser reads them through the §9.3.4.3.4 bypass arithmetic decoder +// without allocating a context model. Presence is exactly the +// LumaIntraModeSource selection: Mpm ⇒ mpm_idx present, Remaining ⇒ +// rem_intra_luma_pred_mode present (the two are mutually exclusive per +// the §7.3.8.5 `if( prev_intra_luma_pred_flag ) … else …` syntax). +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `mpm_idx`: TR with `cMax = 2` and +/// `cRiceParam = 0`. The TR prefix with `cRiceParam = 0` collapses to +/// truncated-unary, so the on-wire string is `0`, `10`, or `11` for the +/// three values 0, 1, 2 — at most two bypass bins (Table 9-48 marks +/// bin 0 and bin 1 `bypass`, binIdx ≥ 2 `na`). +pub const MPM_IDX_TR_CMAX: u32 = 2; + +/// `cRiceParam` for the `mpm_idx` TR binarization (Table 9-43): 0. With +/// `cRiceParam = 0` the §9.3.3.10 TR has no Rice suffix and the prefix +/// is plain truncated-unary. +pub const MPM_IDX_TR_C_RICE_PARAM: u32 = 0; + +/// Table 9-43 binarization shape for `rem_intra_luma_pred_mode`: FL with +/// `cMax = 31`. The §9.3.3.5 derivation gives +/// `fixedLength = Ceil(Log2(cMax + 1)) = Ceil(Log2(32)) = 5`, so the +/// on-wire string is exactly five bypass bins (Table 9-48 marks +/// binIdx 0..=4 `bypass`, binIdx 5 `na`) read MSB-first. +pub const REM_INTRA_LUMA_PRED_MODE_FL_CMAX: u32 = 31; + +/// §9.3.3.5 — bit width of the FL string for `rem_intra_luma_pred_mode`. +/// +/// `Ceil(Log2(REM_INTRA_LUMA_PRED_MODE_FL_CMAX + 1)) = Ceil(Log2(32)) +/// = 5`. The decoded 5-bit value is the §8.4.2 step-2 starting point +/// (`IntraPredModeY` before the candModeList increment pass). +pub const REM_INTRA_LUMA_PRED_MODE_FL_NBITS: u32 = 5; + +/// Decode `mpm_idx` (§7.3.8.5 / §7.4.9.2) from the CABAC engine. +/// +/// Read when `prev_intra_luma_pred_flag == 1` +/// ([`LumaIntraModeSource::Mpm`]): the §8.4.2 derivation sets +/// `IntraPredModeY = candModeList[ mpm_idx ]`, so the returned value is +/// the index into the three-entry most-probable-mode candidate list and +/// is always in `0..=2`. +/// +/// Binarization is TR with `cMax = 2`, `cRiceParam = 0` (Table 9-43) and +/// every bin is bypass-coded (Table 9-48), so this reads the +/// truncated-unary prefix straight from the §9.3.4.3.4 bypass decoder: +/// a `0` bin terminates immediately (value 0), otherwise a second bin +/// distinguishes value 1 (`10`) from value 2 (`11`). No context model is +/// consumed. +pub fn decode_mpm_idx(engine: &mut CabacEngine<'_>) -> Result { + // §9.3.3.10 TR prefix with cRiceParam = 0 driven entirely by the + // bypass decoder. `is_escape` (all `cMax` bins were 1) is the + // value == cMax case; with cRiceParam = 0 there is no suffix to + // read, so the prefix value is the final value either way. + let (value, _is_escape) = + read_truncated_rice_prefix(MPM_IDX_TR_CMAX, |_bin_idx| engine.decode_bypass())?; + debug_assert!( + value <= MPM_IDX_TR_CMAX, + "mpm_idx is TR cMax = 2 (Table 9-43); decoded value must be in 0..=2" + ); + Ok(value as u8) +} + +/// Decode `rem_intra_luma_pred_mode` (§7.3.8.5 / §7.4.9.2) from the +/// CABAC engine. +/// +/// Read when `prev_intra_luma_pred_flag == 0` +/// ([`LumaIntraModeSource::Remaining`]): the §8.4.2 step-2 derivation +/// seeds `IntraPredModeY = rem_intra_luma_pred_mode`, then increments it +/// once for each sorted candModeList entry it meets or exceeds. The +/// returned value is the pre-increment seed and is always in `0..=31`. +/// +/// Binarization is FL with `cMax = 31` (Table 9-43) and every bin is +/// bypass-coded (Table 9-48), so this reads exactly five bypass bins +/// MSB-first via [`CabacEngine::decode_bypass_bits`]. No context model +/// is consumed. +pub fn decode_rem_intra_luma_pred_mode(engine: &mut CabacEngine<'_>) -> Result { + let value = engine.decode_bypass_bits(REM_INTRA_LUMA_PRED_MODE_FL_NBITS as u8)?; + debug_assert!( + value <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX, + "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); decoded value must be in 0..=31" + ); + Ok(value as u8) +} + +// --------------------------------------------------------------------- +// IntraPredModeY derivation (§8.4.2 — derivation process for luma intra +// prediction mode). This is the process the §7.3.8.5 luma-mode signalling +// group (prev_intra_luma_pred_flag, mpm_idx, rem_intra_luma_pred_mode) +// feeds: given the two §8.4.2-step-2 candidate neighbour modes +// candIntraPredModeA / candIntraPredModeB it builds the three-entry +// candModeList (step 3) and then resolves IntraPredModeY from the +// signalled fields (step 4 — either candModeList[ mpm_idx ] on the Mpm +// path, or rem_intra_luma_pred_mode passed through the sorted-list +// increment pass on the Remaining path). +// +// Table 8-1 names the modes: 0 = INTRA_PLANAR, 1 = INTRA_DC, +// 2..34 = INTRA_ANGULAR2..INTRA_ANGULAR34 (35 modes total). The +// §8.4.2-step-2 candidate reduction (availability via §6.4.1, +// CuPredMode / pcm_flag tests, the CTB-row-boundary B clamp) is the +// slice-data parser's responsibility — it holds the neighbour state and +// the §6.4.1 z-scan availability — and yields the two candidate mode +// values this process consumes, matching the availability-as-input +// convention the §9.3.4.2.2 neighbour ctxInc derivations use. +// --------------------------------------------------------------------- + +/// Table 8-1 — `INTRA_PLANAR`, the mode-0 planar predictor. +pub const INTRA_PLANAR: u8 = 0; + +/// Table 8-1 — `INTRA_DC`, the mode-1 DC predictor. This is also the +/// §8.4.2-step-2 substitute value `candIntraPredModeX` takes when the +/// neighbour is unavailable, inter-coded, PCM, or (for B) lies in the +/// CTB row above the current one. +pub const INTRA_DC: u8 = 1; + +/// Table 8-1 — `INTRA_ANGULAR26`, the mode-26 vertical angular +/// predictor. §8.4.2 step 3 uses it as `candModeList[ 2 ]` in the +/// equal-and-low-candidate (eq. 8-23) and the both-PLANAR-and-DC-present +/// (final step-3 else) fall-throughs. +pub const INTRA_ANGULAR26: u8 = 26; + +/// Table 8-1 — the highest luma intra prediction mode index +/// (`INTRA_ANGULAR34`); modes run `0..=34` inclusive. +pub const INTRA_PRED_MODE_MAX: u8 = 34; + +/// §8.4.2 step 3 — build the three-entry most-probable-mode candidate +/// list `candModeList[ 0..=2 ]` from the two §8.4.2-step-2 candidate +/// neighbour modes `candIntraPredModeA` (left, location `(xPb − 1, yPb)`) +/// and `candIntraPredModeB` (above, location `(xPb, yPb − 1)`). +/// +/// Both candidate inputs are already the reduced step-2 values (an +/// available intra neighbour's `IntraPredModeY`, else `INTRA_DC`); this +/// function implements only the step-3 list construction: +/// +/// * `candIntraPredModeB == candIntraPredModeA`: +/// * candidate `< 2` (PLANAR or DC) ⇒ `{PLANAR, DC, ANGULAR26}` +/// (eqs. 8-21..8-23). +/// * otherwise (an angular candidate) ⇒ the candidate plus its two +/// neighbouring angular modes (eqs. 8-24..8-26): +/// `{candA, 2 + ((candA + 29) % 32), 2 + ((candA − 2 + 1) % 32)}`. +/// * `candIntraPredModeB != candIntraPredModeA`: +/// * `candModeList[ 0 ] = candA`, `candModeList[ 1 ] = candB` +/// (eqs. 8-27/8-28); `candModeList[ 2 ]` is the first of +/// `{PLANAR, DC, ANGULAR26}` not already present in the first two +/// entries. +/// +/// Both candidate inputs must be valid Table 8-1 modes (`0..=34`). +#[must_use] +pub fn intra_luma_cand_mode_list( + cand_intra_pred_mode_a: u8, + cand_intra_pred_mode_b: u8, +) -> [u8; 3] { + debug_assert!( + cand_intra_pred_mode_a <= INTRA_PRED_MODE_MAX, + "candIntraPredModeA is a Table 8-1 mode; must be in 0..=34" + ); + debug_assert!( + cand_intra_pred_mode_b <= INTRA_PRED_MODE_MAX, + "candIntraPredModeB is a Table 8-1 mode; must be in 0..=34" + ); + + if cand_intra_pred_mode_b == cand_intra_pred_mode_a { + if cand_intra_pred_mode_a < 2 { + // eqs. 8-21..8-23 — equal low candidate. + [INTRA_PLANAR, INTRA_DC, INTRA_ANGULAR26] + } else { + // eqs. 8-24..8-26 — equal angular candidate; the `% 32` + // arithmetic wraps the two neighbouring angular modes back + // into the 2..=33 angular band (the `2 +` re-bases the + // 0..=31 residue onto INTRA_ANGULAR2). + let a = u32::from(cand_intra_pred_mode_a); + let one = 2 + ((a + 29) % 32); + let two = 2 + ((a - 2 + 1) % 32); + [cand_intra_pred_mode_a, one as u8, two as u8] + } + } else { + // eqs. 8-27/8-28 — distinct candidates fill slots 0 and 1; slot + // 2 is the first default mode (PLANAR, then DC, then ANGULAR26) + // not already present. + let zero = cand_intra_pred_mode_a; + let one = cand_intra_pred_mode_b; + let two = if zero != INTRA_PLANAR && one != INTRA_PLANAR { + INTRA_PLANAR + } else if zero != INTRA_DC && one != INTRA_DC { + INTRA_DC + } else { + INTRA_ANGULAR26 + }; + [zero, one, two] + } +} + +/// §8.4.2 step 4 — derive `IntraPredModeY[ xPb ][ yPb ]` from the step-3 +/// `candModeList` and the §7.3.8.5 signalled luma-mode fields. +/// +/// `cand_mode_list` is the [`intra_luma_cand_mode_list`] output; `source` +/// is the [`LumaIntraModeSource`] the round-40 `prev_intra_luma_pred_flag` +/// selects. +/// +/// * [`LumaIntraModeSource::Mpm`] — `IntraPredModeY = candModeList[ +/// mpm_idx ]` (the `mpm_idx` field, `0..=2`, indexes the candidate +/// list directly). `field` carries the decoded `mpm_idx`. +/// * [`LumaIntraModeSource::Remaining`] — the step-4 ordered procedure: +/// the candidate list is sorted ascending (the eqs. 8-29..8-31 +/// three-compare-and-swap sort), `IntraPredModeY` is seeded with +/// `rem_intra_luma_pred_mode` (`field`, `0..=31`), then incremented by +/// one for every sorted candidate it meets or exceeds (low-to-high, so +/// the running value is re-compared against each successive candidate). +/// This re-injects the three excluded most-probable modes, mapping the +/// 31-value remaining field onto the 35-mode space. +/// +/// The returned value is always a valid Table 8-1 mode (`0..=34`). +#[must_use] +pub fn derive_intra_pred_mode_y( + cand_mode_list: [u8; 3], + source: LumaIntraModeSource, + field: u8, +) -> u8 { + match source { + LumaIntraModeSource::Mpm => { + debug_assert!( + field <= MPM_IDX_TR_CMAX as u8, + "mpm_idx is TR cMax = 2 (Table 9-43); must index the three-entry candModeList" + ); + cand_mode_list[field as usize] + } + LumaIntraModeSource::Remaining => { + debug_assert!( + field <= REM_INTRA_LUMA_PRED_MODE_FL_CMAX as u8, + "rem_intra_luma_pred_mode is FL cMax = 31 (Table 9-43); must be in 0..=31" + ); + // eqs. 8-29..8-31 — sort the three candidates ascending. + let mut sorted = cand_mode_list; + if sorted[0] > sorted[1] { + sorted.swap(0, 1); + } + if sorted[0] > sorted[2] { + sorted.swap(0, 2); + } + if sorted[1] > sorted[2] { + sorted.swap(1, 2); + } + // step-4 increment pass: seed with rem_intra_luma_pred_mode, + // then bump once per sorted candidate at-or-below the running + // value. The candidates are distinct and ascending, so the + // bump count is monotone and the result is the unsigned + // remaining field shifted up past the three excluded modes. + let mut mode = field; + for &cand in &sorted { + if mode >= cand { + mode += 1; + } + } + mode + } + } +} + +// --------------------------------------------------------------------- +// intra_chroma_pred_mode (§7.3.8.5 coding_unit() / §7.4.9.5) +// §9.3.3.8 / Table 9-46 binarization + Table 9-48 + §8.4.3 derivation. +// The chroma-mode field that follows the luma-mode group in §7.3.8.5: +// present once per CU when ChromaArrayType != 0 and != 3, and once per +// luma prediction block (the same i/j loop as the luma fields) when +// ChromaArrayType == 3; absent entirely when ChromaArrayType == 0 +// (monochrome — §8.4.3 is only invoked when ChromaArrayType != 0). +// --------------------------------------------------------------------- + +/// Table 9-46 — the `intra_chroma_pred_mode` value signalled by the +/// single-bin string `0`: 4. Per Table 8-2 row 4 the §8.4.3 `modeIdx` +/// for this value is `IntraPredModeY` itself (the chroma prediction +/// mode tracks the luma mode; for `ChromaArrayType == 2` the tracked +/// mode is then remapped through Table 8-3). +pub const INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA: u8 = 4; + +/// §9.3.3.8 / Table 9-46 — bit width of the FL suffix that follows the +/// `1` prefix bin: 2. The suffix carries values 0..=3 MSB-first +/// (`100`⇒0, `101`⇒1, `110`⇒2, `111`⇒3); both suffix bins are +/// bypass-coded per Table 9-48. +pub const INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS: u32 = 2; + +/// §9.3.4.2.1 / Table 9-48 row for `intra_chroma_pred_mode`. Bin 0 is +/// context-coded with `ctxInc = 0`; bins 1 and 2 are `bypass` and bins +/// beyond binIdx 2 are `na` (the Table 9-46 strings are at most three +/// bins long). +/// +/// Table 9-13 lists three ctxIdx slots with +/// `initValue = {63, 152, 152}` for initType 0, 1 and 2 — the element +/// is read in I, P and B slices (intra CUs occur in every slice type), +/// so all three initType slots are populated. This layer hands back +/// the bank-relative `ctxInc` only; the Table 9-13 initValue plus the +/// Table 9-4 initType-to-ctxIdx mapping is consumed at slice-init +/// scope. +/// +/// Returns the ctxInc when called with `bin_idx == 0`; any other value +/// is bypass (1, 2) or `na` per Table 9-48 and the function returns 0 +/// defensively (callers should not invoke this for the bypass bins). +#[must_use] +pub fn intra_chroma_pred_mode_ctx_inc(bin_idx: u32) -> u32 { + debug_assert!( + bin_idx == 0, + "intra_chroma_pred_mode Table 9-48 row: only bin 0 is context-coded; bins 1..2 are bypass" + ); + 0 +} + +/// Decode `intra_chroma_pred_mode` (§7.3.8.5 / §7.4.9.5) from the +/// CABAC engine. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the single +/// Table 9-13 / §9.3.4.2 `ctxInc = 0` slot; it is mutated in place per +/// the §9.3.4.3.2.2 state transition. +/// +/// Binarization is the §9.3.3.8 / Table 9-46 process: one +/// context-coded prefix bin, then — only when that bin is 1 — a +/// two-bit bypass FL suffix. A `0` prefix decodes to value 4 +/// ([`INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA`]; no suffix bins are read); +/// a `1` prefix is followed by the MSB-first two-bit suffix carrying +/// values 0..=3. The returned value is therefore always in +/// `{0, 1, 2, 3, 4}` — feed it to [`intra_pred_mode_c_mode_idx`] / +/// [`derive_intra_pred_mode_c`] for the §8.4.3 `IntraPredModeC` +/// derivation. +pub fn decode_intra_chroma_pred_mode( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48: bin 0 is context-coded with ctxInc = 0. + debug_assert_eq!( + intra_chroma_pred_mode_ctx_inc(0), + 0, + "Table 9-48 row for intra_chroma_pred_mode: bin 0 ctxInc = 0" + ); + let prefix = engine.decode_decision(ctx)?; + if prefix == 0 { + // Table 9-46: the single-bin string `0` is value 4. + return Ok(INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA); + } + // Table 9-46: `1` prefix + two-bit FL bypass suffix ⇒ values 0..=3. + let suffix = engine.decode_bypass_bits(INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS as u8)?; + debug_assert!( + suffix <= 3, + "intra_chroma_pred_mode suffix is two FL bins (Table 9-46); value must be in 0..=3" + ); + Ok(suffix as u8) +} + +/// §8.4.3 Table 8-2 — derive `modeIdx` from `intra_chroma_pred_mode` +/// and `IntraPredModeY`. +/// +/// Row 4 (`intra_chroma_pred_mode == 4`) yields `IntraPredModeY` +/// itself. Rows 0..=3 select the base mode from `{0, 26, 10, 1}` +/// (planar, vertical, horizontal, DC angular indices in +/// `intra_chroma_pred_mode` order); when the selected base mode equals +/// `IntraPredModeY` the table substitutes 34 instead (each Table 8-2 +/// column places 34 exactly where the row's base mode would collide +/// with the luma mode). +/// +/// `intra_pred_mode_y` must be a valid §8.4.2 mode (0..=34) and +/// `intra_chroma_pred_mode` a decoded Table 9-46 value +/// (`{0, 1, 2, 3, 4}`); out-of-range inputs are rejected in debug +/// builds (release builds fall back to the luma-tracking row to avoid +/// panicking on an accidental out-of-range input). +#[must_use] +pub fn intra_pred_mode_c_mode_idx(intra_chroma_pred_mode: u8, intra_pred_mode_y: u8) -> u8 { + debug_assert!( + intra_chroma_pred_mode <= 4, + "intra_chroma_pred_mode is a Table 9-46 value; must be in 0..=4" + ); + debug_assert!( + intra_pred_mode_y <= 34, + "IntraPredModeY is a §8.4.2 mode index; must be in 0..=34" + ); + // Table 8-2 rows 0..=3 base modes, in intra_chroma_pred_mode order. + const BASE_MODES: [u8; 4] = [0, 26, 10, 1]; + match BASE_MODES.get(intra_chroma_pred_mode as usize) { + Some(&base) if base == intra_pred_mode_y => 34, + Some(&base) => base, + // Row 4 (and the release-build out-of-range fallback): modeIdx + // tracks the luma mode. + None => intra_pred_mode_y, + } +} + +/// §8.4.3 Table 8-3 — `IntraPredModeC` as a function of `modeIdx` when +/// `ChromaArrayType == 2`. Indexed by `modeIdx` 0..=34; entries 0..=2 +/// pass through unchanged (the Table 8-3 `X <= 2` column). +pub const INTRA_PRED_MODE_C_CHROMA_422_MAP: [u8; 35] = [ + 0, 1, 2, // X <= 2 passes through + 2, 2, 2, 3, 5, 7, 8, 10, 12, 13, 15, 17, // modeIdx 3..=14 + 18, 19, 20, 21, 22, 23, 23, 24, 24, 25, 25, // modeIdx 15..=25 + 26, 27, 27, 28, 28, 29, 29, 30, 31, // modeIdx 26..=34 +]; + +/// §8.4.3 Table 8-3 — remap `modeIdx` to `IntraPredModeC` for +/// `ChromaArrayType == 2` streams. `mode_idx` must be in 0..=34; +/// out-of-range inputs are rejected in debug builds (release builds +/// pass the value through unchanged to avoid panicking). +#[must_use] +pub fn intra_pred_mode_c_chroma_422(mode_idx: u8) -> u8 { + debug_assert!( + mode_idx <= 34, + "modeIdx is a §8.4.3 Table 8-2 output; must be in 0..=34" + ); + INTRA_PRED_MODE_C_CHROMA_422_MAP + .get(mode_idx as usize) + .copied() + .unwrap_or(mode_idx) +} + +/// §8.4.3 — the full `IntraPredModeC` derivation: Table 8-2 `modeIdx` +/// from the decoded `intra_chroma_pred_mode` and the §8.4.2 +/// `IntraPredModeY`, then — when `ChromaArrayType == 2` — the Table +/// 8-3 remap; otherwise `IntraPredModeC` is `modeIdx` itself. +/// +/// §8.4.3 is only invoked when `ChromaArrayType != 0`; the §7.3.8.5 +/// syntax never emits `intra_chroma_pred_mode` for a monochrome +/// stream, so a caller holding a decoded value is already past that +/// gate. +#[must_use] +pub fn derive_intra_pred_mode_c( + intra_chroma_pred_mode: u8, + intra_pred_mode_y: u8, + chroma_array_type_is_2: bool, +) -> u8 { + let mode_idx = intra_pred_mode_c_mode_idx(intra_chroma_pred_mode, intra_pred_mode_y); + if chroma_array_type_is_2 { + intra_pred_mode_c_chroma_422(mode_idx) + } else { + mode_idx + } +} + +// --------------------------------------------------------------------- +// last_sig_coeff_{x,y}_{prefix,suffix} (§7.3.8.11, §7.4.9.11) +// --------------------------------------------------------------------- + +/// Which `last_sig_coeff_*_prefix` bank the caller's context-model +/// slice corresponds to. The X and Y prefixes live in separate banks +/// of contexts; we tag the request so the caller can pick the right +/// slice. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum LastSigCoeffBank { + /// `last_sig_coeff_x_prefix` bank. + X, + /// `last_sig_coeff_y_prefix` bank. + Y, +} + +/// §9.3.4.2.3 — `(ctxOffset, ctxShift)` for the +/// `last_sig_coeff_{x,y}_prefix` ctxInc derivation. `log2_trafo_size` +/// is the transform-block log2 dimension (2..=5; 2 = 4×4, 5 = 32×32); +/// `is_chroma` selects the chroma bank when `cIdx > 0`. +/// +/// Spec equations (§9.3.4.2.3 Table 9-26 / 9-27): +/// +/// ```text +/// // luma (cIdx == 0): +/// ctxOffset = 3 * (log2TrafoSize - 2) + ((log2TrafoSize - 1) >> 2) +/// ctxShift = (log2TrafoSize + 1) >> 2 +/// +/// // chroma (cIdx > 0): +/// ctxOffset = 15 +/// ctxShift = log2TrafoSize - 2 +/// ``` +#[must_use] +pub fn last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size: u32, is_chroma: bool) -> (u32, u32) { + if is_chroma { + // §9.3.4.2.3 — chroma TBs always sit at ctxOffset = 15, + // ctxShift = log2TrafoSize − 2. + (15, log2_trafo_size - 2) + } else { + // §9.3.4.2.3 — luma: piecewise linear in log2TrafoSize. + let offset = 3 * (log2_trafo_size - 2) + ((log2_trafo_size - 1) >> 2); + let shift = (log2_trafo_size + 1) >> 2; + (offset, shift) + } +} + +/// §9.3.4.2.3 — bank-relative `ctxInc` for a single +/// `last_sig_coeff_*_prefix` bin: +/// +/// ```text +/// ctxInc = (binIdx >> ctxShift) + ctxOffset +/// ``` +#[must_use] +pub fn last_sig_coeff_prefix_ctx_inc(bin_idx: u32, ctx_offset: u32, ctx_shift: u32) -> u32 { + (bin_idx >> ctx_shift) + ctx_offset +} + +/// §9.3.3.10 — `cMax` for `last_sig_coeff_{x,y}_prefix`: +/// `(log2TrafoSize << 1) − 1`. For a 4×4 TB (log2=2) the prefix is at +/// most 3 bins; for a 32×32 TB (log2=5) at most 9 bins. +#[must_use] +pub fn last_sig_coeff_prefix_cmax(log2_trafo_size: u32) -> u32 { + (log2_trafo_size << 1) - 1 +} + +/// §7.4.9.11 equations 7-74..7-77 — derive the final +/// `LastSignificantCoeffX/Y` position from a decoded +/// `(prefix, optional suffix)` pair. When `prefix <= 3` no suffix is +/// signalled and the position equals the prefix. When `prefix > 3` the +/// suffix is `nBits = (prefix >> 1) − 1` bits, and the position is +/// +/// ```text +/// pos = ( ( 2 + ( prefix & 1 ) ) << ( (prefix >> 1) - 1 ) ) + suffix +/// ``` +/// +/// `suffix` is the unsigned suffix value (caller already decoded the +/// `nBits` bypass bins, MSB-first); pass `None` when `prefix <= 3`. +#[must_use] +pub fn last_sig_coeff_position(prefix: u32, suffix: Option) -> u32 { + if prefix <= 3 { + // §7.4.9.11: no suffix, the prefix is the final value. + prefix + } else { + let n_bits = (prefix >> 1) - 1; + let base = (2 + (prefix & 1)) << n_bits; + base + suffix.unwrap_or(0) + } +} + +/// Suffix bit count for `last_sig_coeff_{x,y}_suffix`: `nBits = +/// (prefix >> 1) − 1` when `prefix > 3`, otherwise 0 (no suffix +/// signalled). +#[must_use] +pub fn last_sig_coeff_suffix_n_bits(prefix: u32) -> u32 { + if prefix > 3 { + (prefix >> 1) - 1 + } else { + 0 + } +} + +/// Decoded `last_sig_coeff_*` element (one of X or Y; same shape for +/// both banks). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LastSigCoeff { + /// `last_sig_coeff_*_prefix` from the wire. + pub prefix: u32, + /// `last_sig_coeff_*_suffix` from the wire (`None` when + /// `prefix <= 3`, the no-suffix-signalled case). + pub suffix: Option, + /// §7.4.9.11 derived `LastSignificantCoeff{X,Y}` position. Range + /// 0..=(1 << log2TrafoSize) - 1. + pub position: u32, +} + +/// Decode one `last_sig_coeff_*_{prefix,suffix}` pair from the CABAC +/// engine. `ctx_bank` is the caller-supplied slice of context variables +/// for the active bank ([`LastSigCoeffBank`]); the bin at index +/// `binIdx` consumes the context at index +/// `ctx_inc = (binIdx >> ctxShift) + ctxOffset` within that slice (the +/// caller is responsible for sizing the slice so the highest used +/// `ctx_inc` index is in-bounds). +/// +/// Returns the decoded prefix, optional suffix, and the §7.4.9.11 +/// derived position. The arguments +/// `log2_trafo_size` and `is_chroma` drive both the TR-prefix `cMax` +/// and the §9.3.4.2.3 `(ctxOffset, ctxShift)` derivation. +/// +/// The §7.4.9.11 swap for `scanIdx == 2` (the diagonal scan reflection +/// of `LastSignificantCoeff{X,Y}`) is **not** applied here; the caller +/// receives the on-wire X / Y positions and applies the swap at the +/// residual-coding level where `scanIdx` is known. +pub fn decode_last_sig_coeff( + engine: &mut CabacEngine<'_>, + log2_trafo_size: u32, + is_chroma: bool, + ctx_bank: &mut [ContextModel], +) -> Result { + let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size); + let (ctx_offset, ctx_shift) = + last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma); + + let (prefix, _is_escape) = read_truncated_rice_prefix(c_max, |bin_idx| { + let ctx_inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift) as usize; + engine.decode_decision(&mut ctx_bank[ctx_inc]) + })?; + + let n_bits = last_sig_coeff_suffix_n_bits(prefix); + let suffix = if n_bits > 0 { + Some(engine.decode_bypass_bits(n_bits as u8)?) + } else { + None + }; + let position = last_sig_coeff_position(prefix, suffix); + Ok(LastSigCoeff { + prefix, + suffix, + position, + }) +} + +// --------------------------------------------------------------------- +// coded_sub_block_flag ctxInc — §9.3.4.2.4 +// --------------------------------------------------------------------- + +/// §9.3.4.2.4 — derive the `ctxInc` for one bin of +/// `coded_sub_block_flag` from the colour-component index, the +/// current sub-block scan location `(xS, yS)`, the transform-block +/// size `log2TrafoSize`, and the two previously decoded neighbour +/// bins in sub-block scan order. +/// +/// Spec equations: +/// +/// ```text +/// // §9.3.4.2.4, equations 9-35..9-39 +/// csbfCtx = 0 +/// if xS < (1 << (log2TrafoSize - 2)) - 1: +/// csbfCtx += coded_sub_block_flag[xS + 1][yS] +/// if yS < (1 << (log2TrafoSize - 2)) - 1: +/// csbfCtx += coded_sub_block_flag[xS][yS + 1] +/// if cIdx == 0: +/// ctxInc = min(csbfCtx, 1) +/// else: +/// ctxInc = 2 + min(csbfCtx, 1) +/// ``` +/// +/// `right_neighbour` is the previously decoded +/// `coded_sub_block_flag[xS + 1][yS]` (0/1); pass `0` whenever the +/// current sub-block sits on the right edge of the TB +/// (`xS == (1 << (log2TrafoSize - 2)) - 1`), where equation 9-36 does +/// not apply. `below_neighbour` is the previously decoded +/// `coded_sub_block_flag[xS][yS + 1]` (0/1); pass `0` whenever the +/// current sub-block sits on the bottom edge of the TB +/// (`yS == (1 << (log2TrafoSize - 2)) - 1`). +/// +/// Returns `ctxInc` in `{0, 1}` for luma (`cIdx == 0`) or +/// `{2, 3}` for chroma (`cIdx > 0`). +/// +/// # Panics +/// Does not panic; both neighbour inputs are clamped via the boolean +/// `>= 1` comparison. +#[must_use] +pub fn coded_sub_block_flag_ctx_inc( + is_chroma: bool, + right_neighbour: u8, + below_neighbour: u8, +) -> u32 { + // §9.3.4.2.4: csbfCtx is the unsigned sum of the two neighbour + // bins (each either 0 or 1), so it lies in {0, 1, 2}. The final + // ctxInc clamps to {0, 1} via min(csbfCtx, 1). + let csbf_ctx = (right_neighbour & 1) as u32 + (below_neighbour & 1) as u32; + let clipped = csbf_ctx.min(1); + if is_chroma { + // §9.3.4.2.4 equation 9-39: chroma uses the {2, 3} bank. + 2 + clipped + } else { + // §9.3.4.2.4 equation 9-38: luma uses the {0, 1} bank. + clipped + } +} + +/// §9.3.4.2.4 — helper that takes the full sub-block location and +/// transform-block size and applies the edge-gating from equations +/// 9-36 / 9-37 before delegating to [`coded_sub_block_flag_ctx_inc`]. +/// The caller passes the previously decoded +/// `coded_sub_block_flag[xS + 1][yS]` and +/// `coded_sub_block_flag[xS][yS + 1]` values regardless of the edge +/// condition; this function zeroes them when the corresponding +/// equation 9-36 / 9-37 does not apply (sub-block on the right / +/// bottom TB edge). +/// +/// `xs` / `ys` are the sub-block scan location in 4-sample units (so +/// a 32×32 TB at `log2TrafoSize == 5` has `xs, ys ∈ 0..8`). +#[must_use] +pub fn coded_sub_block_flag_ctx_inc_with_edge( + is_chroma: bool, + xs: u32, + ys: u32, + log2_trafo_size: u32, + right_neighbour: u8, + below_neighbour: u8, +) -> u32 { + // §9.3.4.2.4 edge gates: ( 1 << ( log2TrafoSize − 2 ) ) − 1 is + // the maximum sub-block index along each axis for the TB. + let max_sub_block_idx = (1u32 << (log2_trafo_size - 2)) - 1; + let right = if xs < max_sub_block_idx { + right_neighbour & 1 + } else { + 0 + }; + let below = if ys < max_sub_block_idx { + below_neighbour & 1 + } else { + 0 + }; + coded_sub_block_flag_ctx_inc(is_chroma, right, below) +} + +// --------------------------------------------------------------------- +// split_cu_flag / cu_skip_flag ctxInc — §9.3.4.2.2 Table 9-49 +// --------------------------------------------------------------------- + +/// §9.3.4.2.2 Table 9-49 — the shared `ctxInc` derivation for +/// syntax elements that take their `ctxInc` from a `condL` / `condA` +/// neighbour pair plus the §6.4.1 availability of the neighbour +/// blocks: +/// +/// ```text +/// ctxInc = (condL && availableL) + (condA && availableA) +/// ``` +/// +/// Used by `split_cu_flag` (with `condL = CtDepth[xNbL][yNbL] > +/// cqtDepth`, `condA = CtDepth[xNbA][yNbA] > cqtDepth`) and +/// `cu_skip_flag` (with `condL = cu_skip_flag[xNbL][yNbL]`, +/// `condA = cu_skip_flag[xNbA][yNbA]`). +/// +/// Returns a `ctxInc` in `{0, 1, 2}`. +#[must_use] +pub fn left_above_ctx_inc(cond_l: bool, available_l: bool, cond_a: bool, available_a: bool) -> u32 { + let l = (cond_l && available_l) as u32; + let a = (cond_a && available_a) as u32; + l + a +} + +/// §9.3.4.2.2 Table 9-49 — `condL` / `condA` predicate for +/// `split_cu_flag`: each neighbour contributes `CtDepth[xNb][yNb] > +/// cqtDepth`. Returns the predicate as a `bool` ready to feed into +/// [`left_above_ctx_inc`]. +/// +/// `neighbour_ct_depth` is the `CtDepth[xNb][yNb]` value already +/// derived by the caller for the neighbouring (left or above) block; +/// `cqt_depth` is the current block's coding-quadtree depth. +#[must_use] +pub fn split_cu_flag_cond(neighbour_ct_depth: u32, cqt_depth: u32) -> bool { + neighbour_ct_depth > cqt_depth +} + +/// §9.3.4.2.2 Table 9-49 — `condL` / `condA` predicate for +/// `cu_skip_flag`: each neighbour contributes +/// `cu_skip_flag[xNb][yNb]` as-is. +#[must_use] +pub fn cu_skip_flag_cond(neighbour_cu_skip_flag: u8) -> bool { + (neighbour_cu_skip_flag & 1) != 0 +} + +/// §9.3.4.2.2 Table 9-49 row for `split_cu_flag`. Convenience: takes +/// the neighbour `CtDepth` values and availability and returns +/// `ctxInc` directly. +/// +/// The neighbour `CtDepth` arguments are ignored when the matching +/// `available` flag is false (the `(condX && availableX)` AND in the +/// Table 9-49 formula short-circuits in that case), but the caller +/// may pass any placeholder for them. +#[must_use] +pub fn split_cu_flag_ctx_inc( + left_ct_depth: u32, + available_l: bool, + above_ct_depth: u32, + available_a: bool, + cqt_depth: u32, +) -> u32 { + left_above_ctx_inc( + split_cu_flag_cond(left_ct_depth, cqt_depth), + available_l, + split_cu_flag_cond(above_ct_depth, cqt_depth), + available_a, + ) +} + +/// §9.3.4.2.2 Table 9-49 row for `cu_skip_flag`. Convenience: takes +/// the neighbour `cu_skip_flag` values and availability and returns +/// `ctxInc` directly. +#[must_use] +pub fn cu_skip_flag_ctx_inc( + left_cu_skip_flag: u8, + available_l: bool, + above_cu_skip_flag: u8, + available_a: bool, +) -> u32 { + left_above_ctx_inc( + cu_skip_flag_cond(left_cu_skip_flag), + available_l, + cu_skip_flag_cond(above_cu_skip_flag), + available_a, + ) +} + +// --------------------------------------------------------------------- +// split_cu_flag (§7.3.8.4 coding_quadtree() / §7.4.9.4) decode primitive +// Table 9-43 FL binarization (cMax = 1) + Table 9-48 / §9.3.4.2.2 ctxInc +// + Table 9-7 ctxIdx initValue. Read once per §7.3.8.4 +// `coding_quadtree( )` node inside the split-presence gate +// ( x0 + ( 1 << log2CbSize ) <= pic_width_in_luma_samples ) && +// ( y0 + ( 1 << log2CbSize ) <= pic_height_in_luma_samples ) && +// log2CbSize > MinCbLog2SizeY +// otherwise it is inferred (§7.4.9.4): 1 when the block extends past the +// picture boundary or log2CbSize > MinCbLog2SizeY, else 0. The caller +// owns that gate / inference and the §9.3.4.2.2 neighbour `CtDepth` +// lookup that feeds [`split_cu_flag_ctx_inc`]; this primitive reads the +// single context-coded bin once the bank slot is selected. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `split_cu_flag[ ][ ]`: FL with +/// `cMax = 1` (a single context-coded bin per §7.3.8.4 coding-quadtree +/// node). Value 1 splits the coding block into four quarter-size child +/// nodes; value 0 makes it a leaf coding unit (§7.4.9.4). +pub const SPLIT_CU_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `split_cu_flag`: one context-coded bin +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const SPLIT_CU_FLAG_FL_NBITS: u32 = 1; + +/// Decode `split_cu_flag[ x0 ][ y0 ]` (§7.3.8.4 / §7.4.9.4) from the +/// CABAC engine, consuming one context for the FL `cMax = 1` bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the +/// §9.3.4.2.2 ctxInc slot in the §7.3.8.4 `split_cu_flag[3]` bank +/// (derive the slot with [`split_cu_flag_ctx_inc`] from the left / +/// above neighbours' `CtDepth` and §6.4.1 availability); it is mutated +/// in place per the §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.4 split-presence gate and the §7.4.9.4 not-present +/// inference (1 at a picture boundary or when `log2CbSize > +/// MinCbLog2SizeY`, else 0) are the `coding_quadtree( )` caller's +/// responsibility; this primitive is reached only when the flag is +/// present on the wire. +/// +/// Returns the decoded `u8` (0 or 1): 1 recurses into four quarter-size +/// `coding_quadtree( )` children, 0 enters `coding_unit( )` for the +/// current block. +pub fn decode_split_cu_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; that bin's ctxInc comes from §9.3.4.2.2 + // (Table 9-49) and selects the bank slot the caller already bound + // into `ctx`, so the decode itself is a single context decision. + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// cu_skip_flag (§7.3.8.5 coding_unit() / §7.4.9.5) decode primitive +// Table 9-43 FL binarization (cMax = 1) + Table 9-48 / §9.3.4.2.2 ctxInc +// + Table 9-9 ctxIdx initValue. Read once at the start of a §7.3.8.4 +// `coding_quadtree( )` leaf when `slice_type != I` (inter-only); absent +// for I slices, where §7.4.9.5 infers it to 0. When 1 the CU takes the +// MODE_SKIP path: no `pred_mode_flag`, no `part_mode`, no transform +// tree — only the §7.3.8.6 merge-mode `prediction_unit( )` is parsed. +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `cu_skip_flag`: FL with +/// `cMax = 1` (a single context-coded bin per non-I coding unit). +/// Value 1 selects the MODE_SKIP path (§7.4.9.5). +pub const CU_SKIP_FLAG_FL_CMAX: u32 = 1; + +/// FL-binarization bit count for `cu_skip_flag`: one context-coded bin +/// per §9.3.3.5 `Ceil(Log2(cMax + 1)) = 1`. +pub const CU_SKIP_FLAG_FL_NBITS: u32 = 1; + +/// Decode `cu_skip_flag[ x0 ][ y0 ]` (§7.3.8.5 / §7.4.9.5) from the +/// CABAC engine, consuming one context for the FL `cMax = 1` bin. +/// +/// `ctx` is the caller's `(pStateIdx, valMps)` state for the +/// §9.3.4.2.2 ctxInc slot in the §7.3.8.5 `cu_skip_flag[3]` bank +/// (derive the slot with [`cu_skip_flag_ctx_inc`] from the left / +/// above neighbours' decoded `cu_skip_flag` and §6.4.1 availability); +/// it is mutated in place per the §9.3.4.3.2.2 state transition. +/// +/// The §7.3.8.5 read is gated on `slice_type != I`; for I slices the +/// flag is not present and §7.4.9.5 infers it to 0 (the caller owns +/// that gate). When the decoded value is 1 the coding unit takes the +/// MODE_SKIP path: see [`cu_pred_mode_from_skip`] for the §7.4.9.5 +/// not-present `CuPredMode` inference that follows. +/// +/// Returns the decoded `u8` (0 or 1). +pub fn decode_cu_skip_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // §9.3.4.2.1 + Table 9-48 + Table 9-43: the FL `cMax = 1` shape + // emits exactly one bin; the ctxInc comes from §9.3.4.2.2 (Table + // 9-49) and selects the bank slot the caller already bound into + // `ctx`, so the decode is a single context decision. + engine.decode_decision(ctx) +} + +/// §7.4.9.5 — derive [`CuPredMode`] for a coding unit from its decoded +/// `cu_skip_flag` and the slice type, for the path where +/// `pred_mode_flag` is therefore not present. +/// +/// `cu_skip_flag == 1` (only reachable for `slice_type != I`) maps to +/// [`CuPredMode::Skip`]; `cu_skip_flag == 0` in a P / B slice leaves the +/// mode to be decided by the subsequent `pred_mode_flag` (returns +/// `None`, signalling the caller must read that flag). For an I slice +/// `cu_skip_flag` is inferred to 0 and the mode is MODE_INTRA without a +/// `pred_mode_flag` read. +/// +/// * `slice_type_is_i` — `true` iff `slice_type == I` (§7.4.7.1). +/// * `cu_skip_flag` — the §7.3.8.5 decoded flag (or 0-inferred for I). +/// +/// Returns `Some(mode)` when the mode is fully determined without a +/// `pred_mode_flag` read, or `None` when a P / B non-skip CU still needs +/// `pred_mode_flag` to disambiguate MODE_INTER vs MODE_INTRA. +#[must_use] +pub fn cu_pred_mode_from_skip(slice_type_is_i: bool, cu_skip_flag: u8) -> Option { + debug_assert!( + cu_skip_flag <= 1, + "cu_skip_flag is FL cMax = 1 (Table 9-43); decoded value must be 0 or 1" + ); + if slice_type_is_i { + // §7.4.9.5: I slices infer cu_skip_flag = 0 and CuPredMode = + // MODE_INTRA without coding pred_mode_flag. + Some(CuPredMode::Intra) + } else if cu_skip_flag != 0 { + // P / B skip CU: §7.4.9.5 infers MODE_SKIP, pred_mode_flag absent. + Some(CuPredMode::Skip) + } else { + // P / B non-skip CU: pred_mode_flag is present and decides the + // mode; the caller must read it. + None + } +} + +// --------------------------------------------------------------------- +// split_transform_flag ctxInc — Table 9-48 row +// --------------------------------------------------------------------- + +/// Table 9-48 row for `split_transform_flag[ ][ ][ ]`: +/// +/// ```text +/// ctxInc = 5 − log2TrafoSize +/// ``` +/// +/// The residual-quadtree transform-block sizes are +/// `log2TrafoSize ∈ {2, 3, 4, 5}` (4×4, 8×8, 16×16, 32×32), so the +/// returned `ctxInc` lies in `{0, 1, 2, 3}`. +/// +/// The §7.4.9.10 `split_transform_flag` syntax element is itself +/// only signalled when `log2TrafoSize > MaxTbLog2SizeY` is false and +/// `log2TrafoSize > MinTbLog2SizeY` is true; the caller is responsible +/// for that gate. This function is the per-bin ctxInc derivation +/// only. +/// +/// # Panics +/// Does not panic. For `log2TrafoSize > 5` the result is `u32::MAX` +/// (a wrap of the `5 − x` subtraction); the spec only defines the +/// derivation for `log2TrafoSize ∈ {2, 3, 4, 5}` and the caller is +/// expected to honour that range. +#[must_use] +pub fn split_transform_flag_ctx_inc(log2_trafo_size: u32) -> u32 { + // §7.4.9.10 restricts the syntax element to log2TrafoSize in + // {2, 3, 4, 5}; perform the subtraction wrap-safely so an + // out-of-range caller surfaces a u32::MAX rather than panics. + 5u32.wrapping_sub(log2_trafo_size) +} + +// --------------------------------------------------------------------- +// cbf_luma / cbf_cb / cbf_cr ctxInc — Table 9-48 rows +// --------------------------------------------------------------------- + +/// Table 9-48 row for `cbf_luma[ ][ ][ ]`: +/// +/// ```text +/// ctxInc = (trafoDepth == 0) ? 1 : 0 +/// ``` +/// +/// `trafoDepth` is the §7.4.9.10 transform-tree depth, where 0 is +/// the root of the residual quadtree. The two-context bank is +/// `{0, 1}` and the spec assigns the *deeper* depths to context 0 +/// (the "no further split, deeper TU" case) and the depth-0 root +/// to context 1. +#[must_use] +pub fn cbf_luma_ctx_inc(trafo_depth: u32) -> u32 { + if trafo_depth == 0 { + 1 + } else { + 0 + } +} + +/// Shared `ctxInc` derivation for `cbf_cb` and `cbf_cr` (Table 9-48 +/// row): `ctxInc = trafoDepth`. The §7.4.9.10 residual quadtree +/// allows `trafoDepth ∈ {0, 1, 2, 3, 4}`; the chroma cbf +/// context banks supplied by Table 9-22 are five entries per +/// component, matching the depth range. +/// +/// The two callers ([`cbf_cb_ctx_inc`] and [`cbf_cr_ctx_inc`]) +/// delegate to this helper; the per-component `ctxIdxOffset` is the +/// caller's responsibility (Cb and Cr each have a distinct bank in +/// Table 9-4). +#[must_use] +pub fn cbf_chroma_ctx_inc(trafo_depth: u32) -> u32 { + trafo_depth +} + +/// Table 9-48 row for `cbf_cb[ ][ ][ ]`: `ctxInc = trafoDepth`. +/// Forwards to [`cbf_chroma_ctx_inc`] for the shared formula. +#[must_use] +pub fn cbf_cb_ctx_inc(trafo_depth: u32) -> u32 { + cbf_chroma_ctx_inc(trafo_depth) +} + +/// Table 9-48 row for `cbf_cr[ ][ ][ ]`: `ctxInc = trafoDepth`. +/// Forwards to [`cbf_chroma_ctx_inc`] for the shared formula. +#[must_use] +pub fn cbf_cr_ctx_inc(trafo_depth: u32) -> u32 { + cbf_chroma_ctx_inc(trafo_depth) +} + +// --------------------------------------------------------------------- +// split_transform_flag / cbf_luma / cbf_cb / cbf_cr decode primitives +// (§7.3.8.8 transform_tree). Each is an FL `cMax = 1` single +// context-coded bin (§9.3.4.2.1 / Table 9-48). The caller selects the +// `ctxInc` via the matching `*_ctx_inc` helper and supplies the +// resolved [`ContextModel`] slot; these primitives only drive the +// CABAC engine for that one bin per §9.3.4.3.2. +// --------------------------------------------------------------------- + +/// Decode `split_transform_flag[ x0 ][ y0 ][ trafoDepth ]` (§7.3.8.8 / +/// §7.4.9.8) from the CABAC engine, consuming one context-coded bin. +/// +/// `ctx` is the caller's `split_transform_flag` bank slot for the +/// `ctxInc = 5 − log2TrafoSize` index ([`split_transform_flag_ctx_inc`]); +/// it is mutated in place per §9.3.4.3.2.2 state transition. The +/// §7.3.8.8 presence gate (`log2TrafoSize <= MaxTbLog2SizeY && +/// log2TrafoSize > MinTbLog2SizeY && trafoDepth < MaxTrafoDepth && +/// !( IntraSplitFlag && trafoDepth == 0 )`) is upstream of this +/// primitive; when the gate fails the caller infers the value via +/// [`split_transform_flag_inferred`] instead. +pub fn decode_split_transform_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + engine.decode_decision(ctx) +} + +/// §7.4.9.8 — inferred value of `split_transform_flag` when the element +/// is not present on the wire. +/// +/// The flag is inferred to be `1` when any of: +/// * `log2TrafoSize > MaxTbLog2SizeY`, +/// * `IntraSplitFlag == 1 && trafoDepth == 0`, +/// * `interSplitFlag == 1` +/// +/// and to `0` otherwise. `interSplitFlag` is `1` exactly when +/// `max_transform_hierarchy_depth_inter == 0 && CuPredMode == MODE_INTER +/// && PartMode != PART_2Nx2N && trafoDepth == 0` (§7.4.9.8); the caller +/// passes its derived value in `inter_split_flag`. +#[must_use] +pub fn split_transform_flag_inferred( + log2_trafo_size: u32, + max_tb_log2_size_y: u32, + intra_split_flag: bool, + trafo_depth: u32, + inter_split_flag: bool, +) -> u8 { + if log2_trafo_size > max_tb_log2_size_y + || (intra_split_flag && trafo_depth == 0) + || inter_split_flag + { + 1 + } else { + 0 + } +} + +/// Decode `cbf_luma[ x0 ][ y0 ][ trafoDepth ]` (§7.3.8.8 / §7.4.9.8) +/// from the CABAC engine, consuming one context-coded bin. +/// +/// `ctx` is the caller's `cbf_luma` bank slot for the +/// `ctxInc = (trafoDepth == 0) ? 1 : 0` index ([`cbf_luma_ctx_inc`]). +/// When the §7.3.8.8 presence condition fails the value is inferred to +/// `1` ([`cbf_luma_inferred`]). +pub fn decode_cbf_luma( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + engine.decode_decision(ctx) +} + +/// §7.4.9.8 — inferred value of `cbf_luma` when not present: `1`. +#[must_use] +pub fn cbf_luma_inferred() -> u8 { + 1 +} + +/// Decode `cbf_cb[ x0 ][ y0 ][ trafoDepth ]` (§7.3.8.8 / §7.4.9.8) from +/// the CABAC engine, consuming one context-coded bin. +/// +/// `ctx` is the caller's shared `cbf_chroma` bank slot for the +/// `ctxInc = trafoDepth` index ([`cbf_cb_ctx_inc`]). When not present +/// the value is inferred to `0` ([`cbf_chroma_inferred`]). +pub fn decode_cbf_cb( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + engine.decode_decision(ctx) +} + +/// Decode `cbf_cr[ x0 ][ y0 ][ trafoDepth ]` (§7.3.8.8 / §7.4.9.8) from +/// the CABAC engine, consuming one context-coded bin. +/// +/// `ctx` is the caller's shared `cbf_chroma` bank slot for the +/// `ctxInc = trafoDepth` index ([`cbf_cr_ctx_inc`]). When not present +/// the value is inferred to `0` ([`cbf_chroma_inferred`]). +pub fn decode_cbf_cr( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + engine.decode_decision(ctx) +} + +/// §7.4.9.8 — inferred value of `cbf_cb` / `cbf_cr` when not present: `0`. +#[must_use] +pub fn cbf_chroma_inferred() -> u8 { + 0 +} + +// --------------------------------------------------------------------- +// inter_pred_idc ctxInc — Table 9-48 row +// --------------------------------------------------------------------- + +/// Table 9-48 row for `inter_pred_idc[ x0 ][ y0 ]`: +/// +/// ```text +/// bin 0: ctxInc = (nPbW + nPbH != 12) ? CtDepth[x0][y0] : 4 +/// bin 1: ctxInc = 4 +/// ``` +/// +/// `n_pb_w` and `n_pb_h` are the prediction-block width and height in +/// luma samples (the §7.3.8.6 `nPbW` / `nPbH` derivation). The +/// `nPbW + nPbH == 12` condition picks the two prediction-block +/// shapes whose luma area is 16 samples — namely 8×4 (sum = 12) and +/// 4×8 (sum = 12) — which are encoded with the bin-0 escape onto +/// the shared bin-1 context bank (`ctxInc = 4`). All other shapes +/// route bin 0 through the per-`CtDepth` context bank `{0, 1, 2, 3}`. +/// +/// `ct_depth` is the §7.4.9.4 `CtDepth[x0][y0]` value (the coding- +/// quadtree depth of the current coding unit); valid range is +/// `{0, 1, 2, 3}` matching the §7.4.7.1 MaxCuDepth limit. +/// +/// Returns `ctxInc` for any `binIdx`; `binIdx ∈ {2, 3, 4}` is `na` +/// per Table 9-48 (the binarization is a TR with `cMax = 2`), so the +/// function returns `4` for `binIdx >= 1` (matching bin 1). +#[must_use] +pub fn inter_pred_idc_ctx_inc(bin_idx: u32, n_pb_w: u32, n_pb_h: u32, ct_depth: u32) -> u32 { + if bin_idx == 0 { + // Bin 0 routes through CtDepth unless the PU is 8×4 or 4×8 + // (luma area 16 samples ⇒ nPbW + nPbH == 12), in which case + // it shares the bin-1 context bank. + if n_pb_w + n_pb_h != 12 { + ct_depth + } else { + 4 + } + } else { + // Bin 1 — and the `na` entries `binIdx >= 2` — use ctx 4. + // Table 9-47 caps the prefix at `cMax = 2` (one or two bins), + // so the slice-data parser never invokes this with binIdx >= + // 2; the return value is the spec's bin-1 ctxInc. + 4 + } +} + +// --------------------------------------------------------------------- +// log2_res_scale_abs_plus1 / res_scale_sign_flag ctxInc — +// Table 9-48 rows for §7.3.8.13 cross-component prediction +// --------------------------------------------------------------------- + +/// Table 9-48 row for `log2_res_scale_abs_plus1[ c ]`: +/// +/// ```text +/// ctxInc = 4*c + binIdx +/// ``` +/// +/// `c` is the chroma-component index passed at the §7.3.8.13 +/// `cross_comp_pred()` call site: `c == 0` for Cb, `c == 1` for Cr. +/// The TR(`cMax = 4`) prefix occupies four consecutive contexts per +/// chroma component, so the per-component banks are `{0, 1, 2, 3}` +/// (Cb) and `{4, 5, 6, 7}` (Cr). +/// +/// `binIdx` is the position of the bin within the TR prefix, in +/// `{0, 1, 2, 3}`. The `binIdx >= 4` slots (the EGk(k=0) bypass +/// escape, when the prefix is the all-ones escape `0b1111`) are +/// `na` for the context-coded path; the caller switches to bypass +/// decoding at that point and never passes them here. +#[must_use] +pub fn log2_res_scale_abs_plus1_ctx_inc(bin_idx: u32, c: u32) -> u32 { + // Per-component bank offset (4) times c, plus the bin position + // within the TR prefix. + 4 * c + bin_idx +} + +/// Table 9-48 row for `res_scale_sign_flag[ c ]`: +/// +/// ```text +/// ctxInc = c +/// ``` +/// +/// `c == 0` for Cb, `c == 1` for Cr; each component has its own +/// single-bin sign-flag context. +#[must_use] +pub fn res_scale_sign_flag_ctx_inc(c: u32) -> u32 { + c +} + +/// Table 9-43 binarization shape for `log2_res_scale_abs_plus1[ c ]`: +/// TR with `cMax = 4`, `cRiceParam = 0` (the prefix is the entire +/// element — there is no EGk continuation; the all-ones `0b1111` +/// prefix simply encodes the value `4`). +pub const LOG2_RES_SCALE_ABS_PLUS1_TR_CMAX: u32 = 4; + +/// Decoded §7.3.8.12 `cross_comp_pred( x0, y0, c )` pair plus the +/// §7.4.9.12 derived `ResScaleVal` for the chroma component `c`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct CrossCompPred { + /// `log2_res_scale_abs_plus1[ c ]` from the wire (TR, `cMax = 4`). + /// When this is 0, `res_scale_sign_flag` is not signalled and + /// `ResScaleVal` is 0. + pub log2_res_scale_abs_plus1: u32, + /// `res_scale_sign_flag[ c ]` from the wire; `None` when + /// `log2_res_scale_abs_plus1 == 0` (the flag is not present). + pub res_scale_sign_flag: Option, + /// §7.4.9.12 derived scaling factor `ResScaleVal[ c+1 ][ x0 ][ y0 ]` + /// (equations 7-79 / 7-80): `0` when `log2_res_scale_abs_plus1 == 0`, + /// else `(1 << (log2_res_scale_abs_plus1 − 1)) * (1 − 2 * + /// res_scale_sign_flag)`. + pub res_scale_val: i32, +} + +/// Decode the §7.3.8.12 `cross_comp_pred( x0, y0, c )` syntax structure +/// from the CABAC engine, returning the decoded pair and the §7.4.9.12 +/// derived [`CrossCompPred::res_scale_val`]. +/// +/// The TR(`cMax = 4`) prefix of `log2_res_scale_abs_plus1[ c ]` is +/// context-coded; bin `binIdx` uses `ctx[binIdx]` (the per-component +/// `{0, 1, 2, 3}` bank already sliced out of the Table 9-36 bank by the +/// caller via [`log2_res_scale_abs_plus1_ctx_inc`]). When the prefix is +/// non-zero, the single-bin `res_scale_sign_flag[ c ]` follows, +/// context-coded against `ctx_sign` (Table 9-37, ctxInc = c — also +/// pre-sliced by the caller). +/// +/// `ctx` must provide at least [`LOG2_RES_SCALE_ABS_PLUS1_TR_CMAX`] +/// context slots for the prefix bins; only as many as are actually +/// decoded are mutated in place per §9.3.4.3.2.2. +pub fn decode_cross_comp_pred( + engine: &mut CabacEngine<'_>, + ctx: &mut [ContextModel], + ctx_sign: &mut ContextModel, +) -> Result { + debug_assert!( + ctx.len() >= LOG2_RES_SCALE_ABS_PLUS1_TR_CMAX as usize, + "cross_comp_pred needs cMax = 4 prefix contexts for the component bank" + ); + // §9.3.3.10 TR prefix (cRiceParam = 0); each bin uses its own + // context within the per-component bank (Table 9-48 ctxInc = + // 4*c + binIdx, with the *c offset already applied by the caller's + // slice). The all-ones escape simply yields the value cMax = 4 — + // there is no EGk continuation for this element (Table 9-43). + let (log2_res_scale_abs_plus1, _is_escape) = + read_truncated_rice_prefix(LOG2_RES_SCALE_ABS_PLUS1_TR_CMAX, |bin_idx| { + engine.decode_decision(&mut ctx[bin_idx as usize]) + })?; + + // §7.3.8.12: res_scale_sign_flag is present only when the prefix is + // non-zero. §7.4.9.12 eqs 7-79 / 7-80 derive ResScaleVal. + let (res_scale_sign_flag, res_scale_val) = if log2_res_scale_abs_plus1 == 0 { + (None, 0i32) + } else { + let sign = engine.decode_decision(ctx_sign)?; + let magnitude = 1i32 << (log2_res_scale_abs_plus1 - 1); + let val = magnitude * (1 - 2 * i32::from(sign)); + (Some(sign), val) + }; + + Ok(CrossCompPred { + log2_res_scale_abs_plus1, + res_scale_sign_flag, + res_scale_val, + }) +} + +// --------------------------------------------------------------------- +// tu_residual_act_flag (§7.3.8.10 transform_unit() / §7.4.9.10) +// Table 9-39 ctxIdx initValue; FL (cMax = 1) binarization; Table 9-48 +// ctxInc = 0. Present only when the SCC residual adaptive colour +// transform gate is satisfied (§7.3.8.10). +// --------------------------------------------------------------------- + +/// Table 9-43 binarization shape for `tu_residual_act_flag`: FL with +/// `cMax = 1` (a single context-coded bin per transform unit). +pub const TU_RESIDUAL_ACT_FLAG_FL_CMAX: u32 = 1; + +/// §9.3.4.2.1 / Table 9-48 row for `tu_residual_act_flag`: bin 0 is +/// context-coded with `ctxInc = 0`; the FL `cMax = 1` shape emits only +/// that one bin. +#[must_use] +pub fn tu_residual_act_flag_ctx_inc() -> u32 { + 0 +} + +/// §7.4.9.10 — inferred value of `tu_residual_act_flag` when it is not +/// present (the adaptive-colour-transform gate is not satisfied): the +/// spec mandates an inferred value of `0` (no adaptive colour +/// transform). +#[must_use] +pub fn tu_residual_act_flag_inferred() -> u8 { + 0 +} + +/// Decode `tu_residual_act_flag` (§7.3.8.10 / §7.4.9.10) from the CABAC +/// engine, consuming one Table 9-39 context for the single FL bin +/// (Table 9-48 ctxInc = 0). The gate that decides whether the element +/// is present (the §7.3.8.10 `residual_adaptive_colour_transform_enabled_flag` +/// predicate) is the caller's responsibility; see +/// [`tu_residual_act_flag_inferred`] for the absent case. +pub fn decode_tu_residual_act_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + debug_assert_eq!( + tu_residual_act_flag_ctx_inc(), + 0, + "Table 9-48 row for tu_residual_act_flag: bin 0 ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// §7.3.4 sao() — per-CTU SAO syntax elements (Table 9-48 / Table 9-43) +// --------------------------------------------------------------------- +// +// Round 30 extends the §9.3.4.2 surface with the SAO syntax-element +// family, all decoded inside the §7.3.4 `sao()` per-CTU block. Every +// element is either a single context-coded bin-0 followed by zero or +// more bypass-coded bins (Table 9-48), or fully bypass-coded; no +// neighbour-table walk is needed at this layer. +// +// Table 9-48 rows captured here: +// +// * `sao_merge_left_flag` → bin 0: ctxInc = 0 (FL, cMax = 1) +// * `sao_merge_up_flag` → bin 0: ctxInc = 0 (FL, cMax = 1) +// * `sao_type_idx_luma` → bin 0: ctxInc = 0; bin 1: bypass +// (TR, cMax = 2, cRiceParam = 0) +// * `sao_type_idx_chroma` → bin 0: ctxInc = 0; bin 1: bypass +// (TR, cMax = 2, cRiceParam = 0) +// * `sao_offset_abs[ ][ ][ ][ ]` → bypass × all +// (TR, cMax = (1 << (min(bitDepth, 10) − 5)) − 1, +// cRiceParam = 0) +// * `sao_offset_sign[ ][ ][ ][ ]` → bypass × 1 (FL, cMax = 1) +// * `sao_band_position[ ][ ][ ]` → bypass × 5 (FL, cMax = 31) +// * `sao_eo_class_luma` → bypass × 2 (FL, cMax = 3) +// * `sao_eo_class_chroma` → bypass × 2 (FL, cMax = 3) +// +// Table 9-4 association (the ctx banks each element lives in): +// +// * `sao_merge_left_flag` + `sao_merge_up_flag` share Table 9-5 (one +// ctxIdx per initType). +// * `sao_type_idx_luma` + `sao_type_idx_chroma` share Table 9-6 (one +// ctxIdx per initType). +// +// The two pairs are distinct context banks; this layer hands back the +// bank-relative ctxInc only (0 for every context-coded SAO bin). + +/// Table 9-48 row for `sao_merge_left_flag` and `sao_merge_up_flag`: +/// +/// ```text +/// bin 0: ctxInc = 0 +/// ``` +/// +/// Only bin 0 is context-coded; the FL binarization has `cMax = 1`, so +/// there is exactly one bin and the function returns 0 for any call. +/// The two merge flags share the same Table 9-5 context bank (see +/// Table 9-4); this layer returns the bank-relative ctxInc only. +#[must_use] +pub fn sao_merge_flag_ctx_inc() -> u32 { + 0 +} + +/// Table 9-48 row for `sao_type_idx_luma` and `sao_type_idx_chroma`: +/// +/// ```text +/// bin 0: ctxInc = 0 +/// bin 1: bypass +/// ``` +/// +/// `binIdx == 0` is context-coded with `ctxInc = 0`; `binIdx == 1` is +/// bypass per Table 9-48 and is **not** routed through a context. The +/// TR(`cMax = 2`) binarization caps the prefix at two bins. Callers +/// driving the §9.3 engine must invoke `decode_decision` for bin 0 and +/// `decode_bypass` for bin 1 directly, switching paths between bins. +/// +/// Returns the ctxInc when called with `bin_idx == 0`; any other value +/// is `na` per Table 9-48 and the function returns 0 defensively +/// (callers should not invoke this for the bypass bin). +#[must_use] +pub fn sao_type_idx_ctx_inc(bin_idx: u32) -> u32 { + debug_assert!( + bin_idx == 0, + "sao_type_idx Table 9-48 row: only bin 0 is context-coded; bin >= 1 is bypass" + ); + 0 +} + +/// Table 9-43 binarization shape for `sao_merge_left_flag` and +/// `sao_merge_up_flag`: FL with `cMax = 1` (single bin). +pub const SAO_MERGE_FLAG_FL_CMAX: u32 = 1; + +/// Table 9-43 binarization shape for `sao_type_idx_luma` and +/// `sao_type_idx_chroma`: TR with `cMax = 2`, `cRiceParam = 0`. The +/// prefix is at most two bins; bin 0 is context-coded (ctxInc = 0), +/// bin 1 is bypass-coded per Table 9-48. +pub const SAO_TYPE_IDX_TR_CMAX: u32 = 2; + +/// Table 9-43 binarization shape for `sao_offset_sign`: FL with +/// `cMax = 1` (single bypass-coded bin). +pub const SAO_OFFSET_SIGN_FL_CMAX: u32 = 1; + +/// Table 9-43 binarization shape for `sao_band_position`: FL with +/// `cMax = 31` (five bypass-coded bins; the FL-of-cMax-31 form +/// uses `ceil(log2(cMax + 1)) = 5` bits per §9.3.3.5). +pub const SAO_BAND_POSITION_FL_CMAX: u32 = 31; + +/// FL-binarization bit count for `sao_band_position`: 5 bypass bins. +/// Per §9.3.3.5, FL of `cMax = N` uses `ceil(log2(N + 1))` bits. +pub const SAO_BAND_POSITION_FL_NBITS: u32 = 5; + +/// Table 9-43 binarization shape for `sao_eo_class_luma` and +/// `sao_eo_class_chroma`: FL with `cMax = 3` (two bypass-coded bins, +/// encoding the §7.4.9.3 `SaoEoClass` ∈ {0, 1, 2, 3}: horizontal, +/// vertical, 135-degree, 45-degree). +pub const SAO_EO_CLASS_FL_CMAX: u32 = 3; + +/// FL-binarization bit count for `sao_eo_class_luma` / +/// `sao_eo_class_chroma`: 2 bypass bins. +pub const SAO_EO_CLASS_FL_NBITS: u32 = 2; + +/// Table 9-43 binarization shape for `sao_offset_abs`: TR with +/// +/// ```text +/// cMax = (1 << min(bitDepth, 10) - 5) - 1 +/// cRiceParam = 0 +/// ``` +/// +/// where `bitDepth` is the component's bit-depth in samples. For the +/// canonical 8-bit case `cMax = (1 << 3) - 1 = 7`; for 10-bit and +/// beyond `cMax = (1 << 5) - 1 = 31` (Min-clamped to 10 by the spec +/// to keep the maximum SAO offset range bounded). All bins of the TR +/// prefix are bypass-coded per Table 9-48. +/// +/// `bit_depth` is the §7.4.7.1 `BitDepthY` or `BitDepthC` value +/// for the colour component being decoded. +#[must_use] +pub fn sao_offset_abs_tr_cmax(bit_depth: u32) -> u32 { + // §9.3.3.5: Min(bitDepth, 10). Clamp at the spec maximum so the + // SAO offset range never exceeds [−31, 31]. + let clamped = if bit_depth < 10 { bit_depth } else { 10 }; + // The subtraction is well-defined for bit_depth >= 5; HEVC mandates + // bitDepth >= 8 in every conformant profile, so the result is + // always positive in practice. + (1u32 << (clamped - 5)) - 1 +} + +/// Decode `sao_merge_left_flag` / `sao_merge_up_flag` (§7.3.8.3) — the +/// two §7.4.9.3 SAO-merge flags. Both are Table 9-43 FL `cMax = 1` with +/// a single `ctxInc = 0` context-coded bin (Table 9-48) sharing the +/// Table 9-5 `sao_merge_flag` bank. The §7.3.8.3 presence gates +/// (`rx > 0 && leftCtbInSliceSeg && leftCtbInTile` for the left flag; +/// `ry > 0 && !sao_merge_left_flag && upCtbInSliceSeg && upCtbInTile` +/// for the up flag) are the caller's responsibility; when the gate +/// fails the flag is inferred to 0 (§7.4.9.3) and this function is not +/// called. +pub fn decode_sao_merge_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + debug_assert_eq!( + sao_merge_flag_ctx_inc(), + 0, + "Table 9-48: sao_merge ctxInc = 0" + ); + engine.decode_decision(ctx) +} + +/// Decode `sao_type_idx_luma` / `sao_type_idx_chroma` (§7.3.8.3) — the +/// §7.4.9.3 `SaoTypeIdx[cIdx][rx][ry]` selector. Table 9-43 TR +/// `cMax = 2, cRiceParam = 0`: bin 0 is context-coded (`ctxInc = 0`, +/// `ctx`), bin 1 is bypass (Table 9-48). The decoded value is +/// 0 (not applied), 1 (band offset) or 2 (edge offset) per §7.4.9.3. +pub fn decode_sao_type_idx( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + // TR(cMax = 2): bin 0 context-coded, bin 1 bypass. + let bin0 = engine.decode_decision(ctx)?; + if bin0 == 0 { + return Ok(0); + } + let bin1 = engine.decode_bypass()?; + Ok(if bin1 == 0 { 1 } else { 2 }) +} + +/// Decode `sao_offset_abs[cIdx][rx][ry][i]` (§7.3.8.3) — one of the +/// four §7.4.9.3 SAO offset magnitudes. Table 9-43 TR +/// `cMax = (1 << (Min(bitDepth, 10) − 5)) − 1, cRiceParam = 0`; every +/// bin is bypass (Table 9-48). `bit_depth` is `BitDepthY` (luma) or +/// `BitDepthC` (chroma); see [`sao_offset_abs_tr_cmax`]. +pub fn decode_sao_offset_abs( + engine: &mut CabacEngine<'_>, + bit_depth: u32, +) -> Result { + let c_max = sao_offset_abs_tr_cmax(bit_depth); + let (value, _is_escape) = read_truncated_rice_prefix(c_max, |_| engine.decode_bypass())?; + Ok(value) +} + +/// Decode `sao_offset_sign[cIdx][rx][ry][i]` (§7.3.8.3) — the sign of a +/// band-offset SAO offset. Table 9-43 FL `cMax = 1`, a single bypass +/// bin (Table 9-48). Read only for band-offset (`SaoTypeIdx == 1`) +/// when the corresponding `sao_offset_abs != 0`; otherwise inferred to +/// 0 (§7.4.9.3). Returns 0 (positive) or 1 (negative). +pub fn decode_sao_offset_sign(engine: &mut CabacEngine<'_>) -> Result { + engine.decode_bypass() +} + +/// Decode `sao_band_position[cIdx][rx][ry]` (§7.3.8.3) — the §7.4.9.3 +/// starting band of a band-offset SAO. Table 9-43 FL `cMax = 31`, five +/// bypass bins MSB-first (Table 9-48). Read only for band offset +/// (`SaoTypeIdx == 1`). +pub fn decode_sao_band_position(engine: &mut CabacEngine<'_>) -> Result { + Ok(engine.decode_bypass_bits(SAO_BAND_POSITION_FL_NBITS as u8)? as u8) +} + +/// Decode `sao_eo_class_luma` / `sao_eo_class_chroma` (§7.3.8.3) — the +/// §7.4.9.3 `SaoEoClass[cIdx][rx][ry]` edge-offset direction. Table +/// 9-43 FL `cMax = 3`, two bypass bins MSB-first (Table 9-48). Read +/// only for edge offset (`SaoTypeIdx == 2`). Returns 0 (horizontal), +/// 1 (vertical), 2 (135°) or 3 (45°). +pub fn decode_sao_eo_class(engine: &mut CabacEngine<'_>) -> Result { + Ok(engine.decode_bypass_bits(SAO_EO_CLASS_FL_NBITS as u8)? as u8) +} + +// --------------------------------------------------------------------- +// part_mode (§7.3.8.5 coding_unit() / §7.4.9.5 / §9.3.3.7). +// Table 9-45 binarization (CuPredMode + log2CbSize dependent) + Table +// 9-48 ctxInc (bin 0/1/2 context-coded, bin 3 bypass) + Table 7-10 +// PartMode / IntraSplitFlag derivation. The bin string is variable so +// the decoder walks it bin-by-bin against the active-CU geometry. +// --------------------------------------------------------------------- + +/// §7.4.9.5 / Table 7-10 — the coding-unit partitioning mode `PartMode` +/// derived from `part_mode`. The eight values cover the square split +/// (`PART_2Nx2N`, `PART_NxN`), the symmetric halves (`PART_2NxN`, +/// `PART_Nx2N`), and the four asymmetric-motion-partition (AMP) forms +/// (`PART_2NxnU/nD/nLx2N/nRx2N`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PartMode { + /// `PART_2Nx2N` (part_mode 0) — a single prediction block covering + /// the whole CU. + Part2Nx2N, + /// `PART_2NxN` (part_mode 1) — two horizontal halves. + Part2NxN, + /// `PART_Nx2N` (part_mode 2) — two vertical halves. + PartNx2N, + /// `PART_NxN` (part_mode 3 inter / part_mode 1 intra) — four + /// quarter-size blocks. For intra it sets `IntraSplitFlag = 1`. + PartNxN, + /// `PART_2NxnU` (part_mode 4) — AMP, top quarter + bottom + /// three-quarters (inter only). + Part2NxnU, + /// `PART_2NxnD` (part_mode 5) — AMP, top three-quarters + bottom + /// quarter (inter only). + Part2NxnD, + /// `PART_nLx2N` (part_mode 6) — AMP, left quarter + right + /// three-quarters (inter only). + PartNLx2N, + /// `PART_nRx2N` (part_mode 7) — AMP, left three-quarters + right + /// quarter (inter only). + PartNRx2N, +} + +impl PartMode { + /// `true` for the four asymmetric-motion-partition modes + /// (`PART_2NxnU/nD/nLx2N/nRx2N`), which are only valid for inter + /// CUs with `amp_enabled_flag == 1`. + #[must_use] + pub fn is_amp(self) -> bool { + matches!( + self, + Self::Part2NxnU | Self::Part2NxnD | Self::PartNLx2N | Self::PartNRx2N + ) + } +} + +/// Decoded `part_mode` result: the §7.4.9.5 `PartMode` plus the +/// `IntraSplitFlag` it implies (set only by intra `PART_NxN`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PartModeResult { + /// The §7.4.9.5 `PartMode`. + pub part_mode: PartMode, + /// §7.4.9.5 `IntraSplitFlag` — 1 only for an intra CU split into + /// `PART_NxN`, 0 otherwise. + pub intra_split_flag: bool, +} + +/// §7.4.9.5 — the `part_mode`-not-present inference: `PartMode = +/// PART_2Nx2N`, `IntraSplitFlag = 0`. The §7.3.8.5 read is suppressed +/// when `CuPredMode == MODE_INTRA && log2CbSize > MinCbLog2SizeY`. +#[must_use] +pub fn part_mode_inferred() -> PartModeResult { + PartModeResult { + part_mode: PartMode::Part2Nx2N, + intra_split_flag: false, + } +} + +/// Decode `part_mode` (§7.3.8.5 / §9.3.3.7) from the CABAC engine, +/// returning the §7.4.9.5 `PartMode` + `IntraSplitFlag`. +/// +/// The Table 9-45 binarization is selected by `cu_pred_mode`, +/// `log2_cb_size`, `min_cb_log2_size` (`MinCbLog2SizeY`) and +/// `amp_enabled` (`amp_enabled_flag`). Table 9-48 routes bin 0..=2 +/// through the per-bin `part_mode[ctxInc]` bank (`ctx0` / `ctx1`; +/// bin 2's ctxInc is 2 for `log2CbSize == MinCbLog2SizeY`, 3 for +/// `log2CbSize > MinCbLog2SizeY`, so the caller passes both context +/// slots); bin 3 is bypass. +/// +/// * `ctx0` — `part_mode` bank slot 0 (bin 0). +/// * `ctx1` — `part_mode` bank slot 1 (bin 1). +/// * `ctx_bin2` — `part_mode` bank slot 2 or 3 (bin 2), already +/// selected by the caller from `log2_cb_size == min_cb_log2_size`. +#[allow(clippy::too_many_arguments)] +pub fn decode_part_mode( + engine: &mut CabacEngine<'_>, + ctx0: &mut ContextModel, + ctx1: &mut ContextModel, + ctx_bin2: &mut ContextModel, + cu_pred_mode: CuPredMode, + log2_cb_size: u32, + min_cb_log2_size: u32, + amp_enabled: bool, +) -> Result { + // Table 9-45 bin 0 is always context-coded. + let b0 = engine.decode_decision(ctx0)?; + + if cu_pred_mode == CuPredMode::Intra { + // Intra: only PART_2Nx2N (bin "1") or PART_NxN (bin "0"). + // Table 9-45 intra column: part_mode 0 → "1", part_mode 1 → "0". + return Ok(if b0 == 1 { + PartModeResult { + part_mode: PartMode::Part2Nx2N, + intra_split_flag: false, + } + } else { + PartModeResult { + part_mode: PartMode::PartNxN, + intra_split_flag: true, + } + }); + } + + // Inter (MODE_INTER). part_mode 0 (PART_2Nx2N) = "1". + if b0 == 1 { + return Ok(PartModeResult { + part_mode: PartMode::Part2Nx2N, + intra_split_flag: false, + }); + } + + // bin 0 == 0: read bin 1 (context-coded). + let b1 = engine.decode_decision(ctx1)?; + + // The asymmetric/quarter tail is only present when + // log2CbSize > MinCbLog2SizeY (the "amp_enabled_flag" / + // "!amp_enabled_flag" Table 9-45 columns) or + // log2CbSize == MinCbLog2SizeY && log2CbSize > 3 (the trailing + // "001"/"000" forms). When log2CbSize == MinCbLog2SizeY && + // log2CbSize == 3 only the two-bin forms "01"/"00" exist. + let big = log2_cb_size > min_cb_log2_size; + + if big { + if !amp_enabled { + // Columns "!amp_enabled_flag": "01" → PART_2NxN, + // "00" → PART_Nx2N. Two bins total. + return Ok(PartModeResult { + part_mode: if b1 == 1 { + PartMode::Part2NxN + } else { + PartMode::PartNx2N + }, + intra_split_flag: false, + }); + } + // amp_enabled_flag column. After "0x" a third context bin + // distinguishes the symmetric ("011"/"001") from the AMP + // ("0100"/"0101"/"0000"/"0001") forms. + let b2 = engine.decode_decision(ctx_bin2)?; + if b2 == 1 { + // "011" → PART_2NxN, "001" → PART_Nx2N. + return Ok(PartModeResult { + part_mode: if b1 == 1 { + PartMode::Part2NxN + } else { + PartMode::PartNx2N + }, + intra_split_flag: false, + }); + } + // b2 == 0: AMP. Bin 3 is bypass. b1 selects horizontal + // (PART_2NxnU/nD, "010x") vs vertical (PART_nLx2N/nRx2N, + // "000x"); b3 selects the U/L vs D/R half. + let b3 = engine.decode_bypass()?; + let part_mode = match (b1, b3) { + (1, 0) => PartMode::Part2NxnU, // 0100 + (1, 1) => PartMode::Part2NxnD, // 0101 + (0, 0) => PartMode::PartNLx2N, // 0000 + _ => PartMode::PartNRx2N, // 0001 + }; + return Ok(PartModeResult { + part_mode, + intra_split_flag: false, + }); + } + + // log2CbSize == MinCbLog2SizeY. "01" → PART_2NxN. The "00" prefix + // continues to PART_Nx2N ("00") when log2CbSize == 3, or splits + // into "001" (PART_Nx2N) / "000" (PART_NxN) when log2CbSize > 3. + if b1 == 1 { + return Ok(PartModeResult { + part_mode: PartMode::Part2NxN, + intra_split_flag: false, + }); + } + if log2_cb_size == 3 { + // "00" → PART_Nx2N (no third bin at the 8×8 minimum). + return Ok(PartModeResult { + part_mode: PartMode::PartNx2N, + intra_split_flag: false, + }); + } + // log2CbSize > 3 && == MinCbLog2SizeY: third bin (context-coded, + // ctxInc = bin2 slot). "001" → PART_Nx2N, "000" → PART_NxN. + let b2 = engine.decode_decision(ctx_bin2)?; + Ok(PartModeResult { + part_mode: if b2 == 1 { + PartMode::PartNx2N + } else { + PartMode::PartNxN + }, + intra_split_flag: false, + }) +} + +/// Decode `pcm_flag[x0][y0]` (§7.3.8.5) — the §7.4.9.5 PCM gate. Table +/// 9-43 FL `cMax = 1` whose single bin is the §9.3.4.3.5 *terminate* +/// path (Table 9-48 `terminate` row), so it is decoded via +/// [`CabacEngine::decode_terminate`], **not** `decode_decision`. The +/// §7.3.8.5 presence gate (`PartMode == PART_2Nx2N && pcm_enabled_flag +/// && Log2MinIpcmCbSizeY <= log2CbSize <= Log2MaxIpcmCbSizeY`) is the +/// caller's; not-present infers 0 (§7.4.9.5). +pub fn decode_pcm_flag(engine: &mut CabacEngine<'_>) -> Result { + engine.decode_terminate() +} + +/// Decode `end_of_slice_segment_flag` (§7.3.8.1) — the per-CTU loop +/// terminator. Table 9-43 FL `cMax = 1` decoded via the §9.3.4.3.5 +/// *terminate* path (Table 9-48 `terminate` row), +/// [`CabacEngine::decode_terminate`]. 1 ends the slice-segment data +/// loop. +pub fn decode_end_of_slice_segment_flag(engine: &mut CabacEngine<'_>) -> Result { + engine.decode_terminate() +} + +/// Decode `merge_idx[x0][y0]` (§7.3.8.6) — the §7.4.9.6 merge-candidate +/// index. Table 9-43 TR `cMax = MaxNumMergeCand − 1, cRiceParam = 0`: +/// bin 0 is context-coded (`ctxInc = 0`, `ctx`), bins >= 1 are bypass +/// (Table 9-48). Read only when `MaxNumMergeCand > 1`; otherwise +/// inferred to 0 (§7.4.9.6). +pub fn decode_merge_idx( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, + max_num_merge_cand: u32, +) -> Result { + let c_max = max_num_merge_cand.saturating_sub(1); + if c_max == 0 { + return Ok(0); + } + // bin 0 context-coded; remaining bins bypass. + let b0 = engine.decode_decision(ctx)?; + if b0 == 0 { + return Ok(0); + } + let mut value: u32 = 1; + while value < c_max { + if engine.decode_bypass()? == 0 { + return Ok(value as u8); + } + value += 1; + } + Ok(value as u8) +} + +/// §9.3.3.9 / Table 9-47 / §7.4.9.6 — the §7.4.9.6 `inter_pred_idc` +/// values: which reference lists a P/B prediction block uses. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum InterPredIdc { + /// `PRED_L0` — uni-prediction from RefPicList0. + PredL0, + /// `PRED_L1` — uni-prediction from RefPicList1. + PredL1, + /// `PRED_BI` — bi-prediction from both lists. + PredBi, +} + +/// Decode `inter_pred_idc[x0][y0]` (§7.3.8.6 / §9.3.3.9) — the §7.4.9.6 +/// reference-list selector. Table 9-47 binarization depends on +/// `nPbW + nPbH`: when `!= 12` bin 0 (`PRED_BI` = "1", else two bins) +/// uses `ctxInc = CtDepth`, bin 1 uses `ctxInc = 4` (Table 9-48); when +/// `== 12` the single bin uses `ctxInc = 4`. Read only on B slices; +/// a non-B inter PB is `PRED_L0` (§7.4.9.6, not signalled here). +/// +/// * `ctx_b0` — the `inter_pred_idc` bank slot `CtDepth` (bin 0, +/// `nPbW + nPbH != 12` case) or slot 4 (`== 12` case), selected by +/// the caller. +/// * `ctx_b1` — the `inter_pred_idc` bank slot 4 (bin 1). +/// * `n_pb_w` / `n_pb_h` — the prediction-block width / height. +pub fn decode_inter_pred_idc( + engine: &mut CabacEngine<'_>, + ctx_b0: &mut ContextModel, + ctx_b1: &mut ContextModel, + n_pb_w: u32, + n_pb_h: u32, +) -> Result { + if n_pb_w + n_pb_h == 12 { + // Single bin, ctxInc = 4: "0" → PRED_L0, "1" → PRED_L1. + let b = engine.decode_decision(ctx_b0)?; + return Ok(if b == 0 { + InterPredIdc::PredL0 + } else { + InterPredIdc::PredL1 + }); + } + // bin 0 (ctxInc = CtDepth): "1" → PRED_BI. + let b0 = engine.decode_decision(ctx_b0)?; + if b0 == 1 { + return Ok(InterPredIdc::PredBi); + } + // "00" → PRED_L0, "01" → PRED_L1 (bin 1, ctxInc = 4). + let b1 = engine.decode_decision(ctx_b1)?; + Ok(if b1 == 0 { + InterPredIdc::PredL0 + } else { + InterPredIdc::PredL1 + }) +} + +/// Decode `ref_idx_l0[x0][y0]` / `ref_idx_l1[x0][y0]` (§7.3.8.6) — the +/// §7.4.9.6 reference-picture index. Table 9-43 TR +/// `cMax = num_ref_idx_lX_active_minus1, cRiceParam = 0`: bin 0 uses +/// `ctxInc = 0` (`ctx0`), bin 1 uses `ctxInc = 1` (`ctx1`), bins >= 2 +/// are bypass (Table 9-48). Read only when +/// `num_ref_idx_lX_active_minus1 > 0`; else inferred to 0 (§7.4.9.6). +pub fn decode_ref_idx( + engine: &mut CabacEngine<'_>, + ctx0: &mut ContextModel, + ctx1: &mut ContextModel, + num_ref_idx_active_minus1: u32, +) -> Result { + let c_max = num_ref_idx_active_minus1; + if c_max == 0 { + return Ok(0); + } + // bin 0 (ctxInc = 0). + if engine.decode_decision(ctx0)? == 0 { + return Ok(0); + } + if c_max == 1 { + return Ok(1); + } + // bin 1 (ctxInc = 1). + if engine.decode_decision(ctx1)? == 0 { + return Ok(1); + } + // bins >= 2 bypass. + let mut value: u32 = 2; + while value < c_max { + if engine.decode_bypass()? == 0 { + return Ok(value as u8); + } + value += 1; + } + Ok(value as u8) +} + +/// Decode `mvp_l0_flag[x0][y0]` / `mvp_l1_flag[x0][y0]` (§7.3.8.6) — the +/// §7.4.9.6 motion-vector-predictor candidate flag. Table 9-43 FL +/// `cMax = 1`, a single `ctxInc = 0` context-coded bin (Table 9-48) +/// sharing the `mvp_flag` bank. Returns 0 or 1. +pub fn decode_mvp_flag( + engine: &mut CabacEngine<'_>, + ctx: &mut ContextModel, +) -> Result { + engine.decode_decision(ctx) +} + +// --------------------------------------------------------------------- +// coeff_abs_level_greater1_flag / coeff_abs_level_greater2_flag +// — §9.3.4.2.6 (equations 9-56..9-60) and §9.3.4.2.7 (equations +// 9-61..9-62). Both elements are Table 9-43 FL with cMax = 1, so the +// binarization shape is one context-coded bin. The bin's `ctxInc` is +// driven by a small per-transform-block state machine that threads +// `ctxSet` / `greater1Ctx` from sub-block to sub-block. +// --------------------------------------------------------------------- + +/// Persistent §9.3.4.2.6 state machine carried across the residual +/// sub-blocks of a single transform block. The slice-data parser +/// constructs one [`Greater1State`] per transform block and threads it +/// through the §7.3.8.11 sub-block loop, calling +/// [`Greater1State::on_subblock_entry`] before the sub-block's first +/// `coeff_abs_level_greater1_flag` bin and +/// [`Greater1State::on_coeff_abs_level_greater1_flag`] after each +/// decoded bin's value lands. +/// +/// The machine is the §9.3.4.2.6 equations encoded as a tiny FSM: +/// +/// * Equations 9-56 / 9-57 initialise `ctxSet` for each sub-block +/// based on the sub-block scan index `i` and the colour-component +/// index `cIdx`. +/// * The §9.3.4.2.6 `lastGreater1Ctx == 0` step (the spec's +/// "increment `ctxSet` by one") routes the sub-block into the +/// *next* context set whenever the previous sub-block ran out of +/// the `greater1Ctx ∈ {1, 2, 3}` band. +/// * Equation 9-59 `ctxInc = (ctxSet * 4) + min(3, greater1Ctx)` +/// plus the chroma `+16` offset (eq. 9-60) is reported by +/// [`Greater1State::current_ctx_inc`]. +/// * The post-bin `greater1Ctx` update from §9.3.4.2.6 (the +/// `lastGreater1Flag == 1` → 0, `lastGreater1Flag == 0` → +/// increment-clamped-by-3 rule) lives in +/// [`Greater1State::on_coeff_abs_level_greater1_flag`]. +/// +/// The §9.3.4.2.7 `coeff_abs_level_greater2_flag` derivation reads +/// the *current* `ctxSet` from this same machine (the per-sub-block +/// value, not the post-update one) via +/// [`Greater1State::ctx_set`], so callers compose the +/// greater-2 invocation after the greater-1 sub-block walk without +/// any cross-state-machine plumbing. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Greater1State { + /// §9.3.4.2.6 `ctxSet` — the current sub-block's context set in + /// `{0, 1, 2, 3}`. Eq. 9-59 multiplies this by 4 to pick the + /// per-set base. + ctx_set: u32, + /// §9.3.4.2.6 `greater1Ctx` — the within-set ctx position in + /// `{0, 1, 2, 3}` (clamped at 3 for the `ctxInc` eq. 9-59). + /// `0` means the sub-block has run out of the active band and + /// the next sub-block's entry will bump `ctxSet`. + greater1_ctx: u32, + /// Has any sub-block been entered yet in this transform block? + /// Used to recognise the "first sub-block" case the spec calls + /// out (`lastGreater1Ctx = 1`). + seen_any_subblock: bool, + /// True iff at least one `coeff_abs_level_greater1_flag` bin has + /// been read in *this* sub-block; signals that the next entry's + /// `lastGreater1Ctx == 0` check has a well-defined + /// `lastGreater1Flag` value to consume. + has_last_greater1_flag: bool, +} + +impl Greater1State { + /// Construct a fresh state machine at the start of a transform + /// block. No sub-block has yet been entered; + /// [`on_subblock_entry`](Self::on_subblock_entry) must be called + /// before [`current_ctx_inc`](Self::current_ctx_inc) is + /// meaningful. + #[must_use] + pub fn new() -> Self { + Self { + ctx_set: 0, + greater1_ctx: 1, + seen_any_subblock: false, + has_last_greater1_flag: false, + } + } + + /// §9.3.4.2.6 sub-block entry: invoked once per sub-block before + /// the first `coeff_abs_level_greater1_flag` bin is decoded. + /// + /// * `i` — the §7.3.8.11 sub-block scan index inside the + /// transform block. + /// * `is_chroma` — `true` for `cIdx > 0`, used by eq. 9-56 to + /// force `ctxSet = 0` on every chroma sub-block. + /// * `last_greater1_flag` — the most-recently decoded + /// `coeff_abs_level_greater1_flag` value from the *previous* + /// sub-block (0 or 1); ignored when this is the first + /// sub-block being entered (the spec's "first invocation" + /// branch sets `lastGreater1Ctx = 1` unconditionally). + /// + /// Implements equations 9-56, 9-57, and 9-58. After this call + /// returns, [`current_ctx_inc`](Self::current_ctx_inc) yields + /// the eq.-9-59 `ctxInc` for the sub-block's first bin. + pub fn on_subblock_entry(&mut self, i: u32, is_chroma: bool, last_greater1_flag: u8) { + // Eq. 9-56 / 9-57: initialise ctxSet from (i, cIdx). + self.ctx_set = if i == 0 || is_chroma { 0 } else { 2 }; + + // §9.3.4.2.6 lastGreater1Ctx derivation. The spec branches + // on "first invocation" vs not: + // * First sub-block in this transform block: + // lastGreater1Ctx = 1. The ctxSet increment in eq. 9-58 + // never triggers (lastGreater1Ctx > 0). + // * Subsequent sub-block, prior sub-block decoded at + // least one greater1 bin: lastGreater1Ctx is the prior + // sub-block's terminal greater1Ctx, then mutated by the + // prior sub-block's lastGreater1Flag per the spec + // bullets. + // The walker tracks the prior sub-block's terminal + // greater1Ctx as self.greater1_ctx (updated by the per-bin + // step in on_coeff_abs_level_greater1_flag). We replay the + // spec's lastGreater1Ctx mutation here, then the eq. 9-58 + // bump condition is `lastGreater1Ctx == 0`. + let last_greater1_ctx = if !self.seen_any_subblock { + // First sub-block: spec sets lastGreater1Ctx = 1. + 1 + } else if !self.has_last_greater1_flag { + // Prior sub-block existed but decoded zero greater1 + // bins (rare: the sub-block had only sig coeffs equal + // to 1 — i.e. no bin reached this code path). In that + // case the spec's "When lastGreater1Ctx is greater than + // 0, the variable lastGreater1Flag is set equal to ..." + // branch is skipped and lastGreater1Ctx retains the + // prior sub-block's value directly. + self.greater1_ctx + } else { + // Apply the spec's lastGreater1Ctx mutation: if the + // prior sub-block's lastGreater1Flag was 1 the ctx + // resets to 0; otherwise it advances by 1. + if self.greater1_ctx == 0 { + // No mutation: the "When lastGreater1Ctx > 0" + // guard skips the body entirely. + 0 + } else if last_greater1_flag != 0 { + 0 + } else { + self.greater1_ctx + 1 + } + }; + + // Eq. 9-58: bump ctxSet whenever the just-derived + // lastGreater1Ctx is 0. + if last_greater1_ctx == 0 { + self.ctx_set += 1; + } + + // Start-of-sub-block reset of the within-set ctx: §9.3.4.2.6 + // says "greater1Ctx is set equal to 1". + self.greater1_ctx = 1; + self.seen_any_subblock = true; + self.has_last_greater1_flag = false; + } + + /// §9.3.4.2.6 per-bin step: invoked *after* every + /// `coeff_abs_level_greater1_flag` bin in the current sub-block + /// is decoded. Updates `greater1Ctx` per the spec's + /// "lastGreater1Flag = 1 → 0 / = 0 → increment" rule, clamped to + /// `0..=3` by eq. 9-59's `min(3, greater1Ctx)` (the underlying + /// counter is implicitly clamped at 3 because eq. 9-59 truncates + /// any further growth). + /// + /// Note: the §9.3.4.2.6 spec keeps `greater1Ctx` unclamped + /// internally (it grows past 3) but eq. 9-59 clamps it; this + /// implementation tracks the clamped value because the only + /// observable property used downstream is whether + /// `greater1Ctx == 0` (for the next sub-block's eq.-9-58 bump), + /// and the eq. 9-59 reading clamps regardless. + pub fn on_coeff_abs_level_greater1_flag(&mut self, decoded_bin: u8) { + if self.greater1_ctx > 0 { + self.greater1_ctx = if decoded_bin != 0 { + 0 + } else { + (self.greater1_ctx + 1).min(3) + }; + self.has_last_greater1_flag = true; + } + } + + /// Eq. 9-59 + eq. 9-60: returns the `coeff_abs_level_greater1_flag` + /// `ctxInc` for the *next* bin to be decoded, given this state + /// machine's `(ctxSet, greater1Ctx)`. + /// + /// `is_chroma == true` (cIdx > 0) adds the eq.-9-60 `+ 16` + /// offset. + #[must_use] + pub fn current_ctx_inc(&self, is_chroma: bool) -> u32 { + let base = self.ctx_set * 4 + self.greater1_ctx.min(3); + if is_chroma { + base + 16 + } else { + base + } + } + + /// Current `ctxSet` value, exported for §9.3.4.2.7 + /// `coeff_abs_level_greater2_flag` ctxInc derivation (which + /// reads the same sub-block's `ctxSet` per eq. 9-61). + #[must_use] + pub fn ctx_set(&self) -> u32 { + self.ctx_set + } +} + +impl Default for Greater1State { + fn default() -> Self { + Self::new() + } +} + +/// §9.3.4.2.7 ctxInc derivation for +/// `coeff_abs_level_greater2_flag[ lastGreater1ScanPos ]`. The spec +/// equations are: +/// +/// ```text +/// ctxInc = ctxSet (9-61) // luma +/// ctxInc = ctxSet + 4 (9-62) // chroma (cIdx > 0) +/// ``` +/// +/// `ctxSet` is the value derived by §9.3.4.2.6 for the same +/// sub-block, available from [`Greater1State::ctx_set`]. +/// +/// The element is signalled at most once per sub-block at the first +/// scan position that took the greater-1 escape; the per-sub-block +/// `Greater1State` already has the matching `ctxSet` at the time +/// the residual loop reaches that scan position, so the caller +/// simply reads it off without further state plumbing. +#[must_use] +pub fn coeff_abs_level_greater2_flag_ctx_inc(ctx_set: u32, is_chroma: bool) -> u32 { + if is_chroma { + ctx_set + 4 + } else { + ctx_set + } +} + +/// Table 9-43 binarization shape for `coeff_abs_level_greater1_flag` +/// and `coeff_abs_level_greater2_flag`: FL with `cMax = 1` (single +/// context-coded bin per element invocation). +pub const COEFF_ABS_LEVEL_GREATER_X_FL_CMAX: u32 = 1; + +// --------------------------------------------------------------------- +// sig_coeff_flag ctxInc — §9.3.4.2.5 +// --------------------------------------------------------------------- + +/// §9.3.4.2.5 Table 9-50 — the `ctxIdxMap[ ]` 4×4 lookup that maps +/// the inner-block scan position `(yC << 2) + xC` to a `sigCtx` for +/// `log2TrafoSize == 2` transform blocks. Index order is row-major +/// over `(yC, xC) ∈ {0..=3}^2`. +/// +/// The published Table 9-50 renders only `i ∈ 0..=14`; the `i = 15` +/// cell is cropped past the page margin (a publishing/layout +/// artefact — eq. 9-41 indexes the map by `( yC << 2 ) + xC` over a +/// full 4×4 sub-block, so the 16th entry is normative content). The +/// staged H.265 errata file +/// (`docs/video/h265/h265-errata-and-clarifications.md`, entry #93) +/// pins `ctxIdxMap[ 15 ] = 8` from the table's anti-diagonal +/// pair-symmetry and the eq. 9-49..9-53 offset structure, matching +/// the value this constant has carried since round 32. +pub const SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2: [u8; 16] = + [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8]; + +/// §9.3.4.2.5 first-branch sigCtx (equation 9-40) — used when +/// `transform_skip_context_enabled_flag` is 1 and either +/// `transform_skip_flag[ x0 ][ y0 ][ cIdx ]` is 1 or +/// `cu_transquant_bypass_flag` is 1. Returns 42 for luma, 16 for +/// chroma. +#[must_use] +pub fn sig_coeff_flag_sig_ctx_transform_skip(is_chroma: bool) -> u32 { + // Eq. 9-40: sigCtx = (cIdx == 0) ? 42 : 16. + if is_chroma { + 16 + } else { + 42 + } +} + +/// §9.3.4.2.5 second-branch sigCtx (equation 9-41) — used for the +/// `log2TrafoSize == 2` (4×4) transform-block case. Reads +/// [`SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2`] at index +/// `(yC << 2) + xC`. +/// +/// `xc` and `yc` are the 4×4 inner-block scan coordinates, each in +/// `0..=3`. Inputs outside this range are clamped via `& 3` so the +/// caller's debug build does not panic on a malformed scan order +/// driver — well-formed callers always pass `xc, yc < 4`. +#[must_use] +pub fn sig_coeff_flag_sig_ctx_log2_2(xc: u32, yc: u32) -> u32 { + let xc = (xc & 3) as usize; + let yc = (yc & 3) as usize; + // Eq. 9-41: sigCtx = ctxIdxMap[ (yC << 2) + xC ]. + SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2[(yc << 2) + xc] as u32 +} + +/// §9.3.4.2.5 fourth-branch sigCtx derivation (equations 9-43..9-53) +/// for `log2TrafoSize > 2` and `xC + yC > 0`. Combines: +/// +/// * `prevCsbf` from the right / below sub-block neighbours of the +/// current sub-block (equations 9-43, 9-44; edge-gated by the +/// `xS < (1 << (log2TrafoSize − 2)) − 1` / +/// `yS < (1 << (log2TrafoSize − 2)) − 1` conditions), +/// * the inner-sub-block position `(xP, yP) = (xC & 3, yC & 3)` +/// routed through equations 9-45..9-48 based on `prevCsbf`, +/// * the colour / size / scan-order tail offsets in equations +/// 9-49..9-53. +/// +/// Inputs: +/// +/// * `is_chroma` — true when `cIdx > 0` (selects the chroma branch +/// of equations 9-49..9-53), +/// * `log2_trafo_size` — `3..=5` for this code path (the caller +/// must have dispatched the 4×4 case to +/// [`sig_coeff_flag_sig_ctx_log2_2`]), +/// * `xc`, `yc` — coefficient scan position inside the TB, +/// * `xs`, `ys` — sub-block scan position +/// (`xs = xC >> 2`, `ys = yC >> 2`), +/// * `right_csbf` / `below_csbf` — the previously decoded +/// `coded_sub_block_flag[ xS + 1 ][ yS ]` / `[ xS ][ yS + 1 ]` +/// neighbour bits (each 0 or 1); ignored when on the right / +/// bottom TB edge per the equation 9-43 / 9-44 gates, +/// * `scan_idx` — the §6.5.2 scan order index in `{0, 1, 2}` +/// (`0` = up-right diagonal, `1` = horizontal, `2` = vertical); +/// only `scan_idx == 0` is special-cased by equation 9-50 for +/// the 8×8 luma case. +/// +/// The `xC + yC == 0` DC-coefficient case (equation 9-42 — `sigCtx +/// = 0` before the tail offsets) is **not** handled by this +/// function; callers must route the DC position separately through +/// [`sig_coeff_flag_sig_ctx_dc`]. +#[must_use] +#[allow(clippy::too_many_arguments)] +pub fn sig_coeff_flag_sig_ctx_general( + is_chroma: bool, + log2_trafo_size: u32, + xc: u32, + yc: u32, + xs: u32, + ys: u32, + right_csbf: u8, + below_csbf: u8, + scan_idx: u32, +) -> u32 { + // Equations 9-43 / 9-44: prevCsbf gates on the edge of the TB + // sub-block grid. + let max_sub_block_idx = (1u32 << (log2_trafo_size - 2)) - 1; + let right_bit = if xs < max_sub_block_idx { + (right_csbf & 1) as u32 + } else { + 0 + }; + let below_bit = if ys < max_sub_block_idx { + (below_csbf & 1) as u32 + } else { + 0 + }; + let prev_csbf = right_bit + (below_bit << 1); + + // §9.3.4.2.5 inner-sub-block position. + let xp = xc & 3; + let yp = yc & 3; + + // Equations 9-45..9-48: route by prevCsbf. + let mut sig_ctx: u32 = match prev_csbf { + 0 => { + // Eq. 9-45: (xP + yP == 0) ? 2 : (xP + yP < 3) ? 1 : 0. + if xp + yp == 0 { + 2 + } else if xp + yp < 3 { + 1 + } else { + 0 + } + } + 1 => { + // Eq. 9-46: (yP == 0) ? 2 : (yP == 1) ? 1 : 0. + if yp == 0 { + 2 + } else if yp == 1 { + 1 + } else { + 0 + } + } + 2 => { + // Eq. 9-47: (xP == 0) ? 2 : (xP == 1) ? 1 : 0. + if xp == 0 { + 2 + } else if xp == 1 { + 1 + } else { + 0 + } + } + // prevCsbf == 3: eq. 9-48 — sigCtx = 2. + _ => 2, + }; + + // Equations 9-49..9-53: colour / size / scan tail offsets. + if !is_chroma { + // Luma branch. + // Eq. 9-49: when (xS + yS) > 0, sigCtx += 3. + if xs + ys > 0 { + sig_ctx += 3; + } + // Eq. 9-50 / 9-51: size-dependent constant. + if log2_trafo_size == 3 { + sig_ctx += if scan_idx == 0 { 9 } else { 15 }; + } else { + sig_ctx += 21; + } + } else { + // Chroma branch. + // Eq. 9-52 / 9-53. + if log2_trafo_size == 3 { + sig_ctx += 9; + } else { + sig_ctx += 12; + } + } + + sig_ctx +} + +/// §9.3.4.2.5 DC sigCtx for `log2TrafoSize > 2` and `xC + yC == 0` +/// (equation 9-42). The DC coefficient takes the third branch of the +/// §9.3.4.2.5 cascade: `sigCtx = 0`, full stop — the +/// equations-9-49..9-53 size / colour / scan modifications are nested +/// inside the *fourth* ("Otherwise") branch and do **not** apply to the +/// DC position. The resulting ctxInc is 0 for luma and 27 for chroma +/// (equations 9-54 / 9-55): every `log2TrafoSize > 2` transform block +/// shares one dedicated DC context per colour component. +/// +/// The `is_chroma` / `log2_trafo_size` / `scan_idx` inputs are retained +/// for signature parity with the sibling branch helpers; equation 9-42 +/// uses none of them. +#[must_use] +pub fn sig_coeff_flag_sig_ctx_dc(is_chroma: bool, log2_trafo_size: u32, scan_idx: u32) -> u32 { + let _ = (is_chroma, log2_trafo_size, scan_idx); + // Eq. 9-42: sigCtx = 0. + 0 +} + +/// §9.3.4.2.5 ctxInc from sigCtx (equations 9-54, 9-55): +/// +/// ```text +/// ctxInc = sigCtx // cIdx == 0 (9-54) +/// ctxInc = 27 + sigCtx // cIdx > 0 (9-55) +/// ``` +#[must_use] +pub fn sig_coeff_flag_ctx_inc_from_sig_ctx(sig_ctx: u32, is_chroma: bool) -> u32 { + if is_chroma { + 27 + sig_ctx + } else { + sig_ctx + } +} + +/// Table 9-43 binarization shape for `sig_coeff_flag`: FL with +/// `cMax = 1` (single context-coded bin per scan position). +pub const SIG_COEFF_FLAG_FL_CMAX: u32 = 1; + +// --------------------------------------------------------------------- +// palette_run_prefix ctxInc — §9.3.4.2.8 (equation 9-63, Table 9-51) +// --------------------------------------------------------------------- + +/// §9.3.4.2.8 Table 9-51 — the `ctxIdxMap[ ][ ]` lookup that maps +/// `(copy_above_palette_indices_flag, binIdx)` to `ctxInc` for the +/// non-eq.-9-63 branch of the §9.3.4.2.8 derivation. The table is a +/// 2 × 5 fixed permutation listed verbatim in Table 9-51 of the spec; +/// the `binIdx >= 5` columns are bypass-coded per Table 9-48 and +/// therefore omitted here. +/// +/// Layout: `PALETTE_RUN_PREFIX_CTX_IDX_MAP[copy_above_flag][binIdx]`, +/// with `copy_above_flag ∈ {0, 1}` and `binIdx ∈ {0, 1, 2, 3, 4}`. +/// +/// The `copy_above_flag == 0, binIdx == 0` cell is spec-listed as +/// `"0, 1, 2"` (i.e. dispatched to eq. 9-63 on `palette_idx_idc`). +/// This module surfaces that branch separately as +/// [`palette_run_prefix_ctx_inc_eq_9_63`], so the table entry is held +/// as `u8::MAX` to mark "must dispatch to eq. 9-63" defensively (the +/// public [`palette_run_prefix_ctx_inc`] handles the branch). +pub const PALETTE_RUN_PREFIX_CTX_IDX_MAP: [[u8; 5]; 2] = [ + // copy_above_palette_indices_flag == 0: bin 0 dispatches to eq. + // 9-63 (sentinel); bins 1..=4 are 3, 3, 4, 4. + [u8::MAX, 3, 3, 4, 4], + // copy_above_palette_indices_flag == 1: 5, 6, 6, 7, 7. + [5, 6, 6, 7, 7], +]; + +/// Sentinel marking the eq.-9-63 dispatch cell in +/// [`PALETTE_RUN_PREFIX_CTX_IDX_MAP`]. +pub const PALETTE_RUN_PREFIX_EQ_9_63_DISPATCH: u8 = u8::MAX; + +/// §9.3.4.2.8 first `binIdx >= 5` index at which Table 9-51 declares +/// `palette_run_prefix` bypass-coded. Equivalent to the TR prefix +/// `cMax = 5` boundary above which §9.3.4.2.8 stops emitting ctxInc +/// values. +pub const PALETTE_RUN_PREFIX_FIRST_BYPASS_BIN_IDX: u32 = 5; + +/// §9.3.4.2.8 equation 9-63 — the eq.-9-63 dispatch when +/// `copy_above_palette_indices_flag == 0` and `binIdx == 0`: +/// +/// ```text +/// ctxInc = ( palette_idx_idc < 1 ) ? 0 +/// : ( ( palette_idx_idc < 3 ) ? 1 : 2 ) (9-63) +/// ``` +/// +/// Returns `ctxInc ∈ {0, 1, 2}`. +#[must_use] +pub fn palette_run_prefix_ctx_inc_eq_9_63(palette_idx_idc: u32) -> u32 { + if palette_idx_idc < 1 { + 0 + } else if palette_idx_idc < 3 { + 1 + } else { + 2 + } +} + +/// §9.3.4.2.8 — full `palette_run_prefix` ctxInc derivation. +/// +/// Inputs: +/// +/// * `bin_idx` — the §9.3.3.10 TR-prefix bin index (0-based). +/// * `copy_above_palette_indices_flag` — the §7.4.9.6 palette flag +/// that selects "copy-above" vs explicit-index palette mode for +/// this run. +/// * `palette_idx_idc` — the palette index decoded at the start of +/// the run; only consulted on the eq.-9-63 branch. +/// +/// Returns: +/// +/// * `Some(ctxInc)` — when the bin is context-coded. The eq.-9-63 +/// branch returns `{0, 1, 2}`; otherwise the value is read from +/// [`PALETTE_RUN_PREFIX_CTX_IDX_MAP`]. +/// * `None` — when `bin_idx >= 5`, the Table 9-51 ">4" column, +/// signalling that the bin is bypass-coded per Table 9-48 and the +/// caller must invoke the engine's bypass path. +#[must_use] +pub fn palette_run_prefix_ctx_inc( + bin_idx: u32, + copy_above_palette_indices_flag: bool, + palette_idx_idc: u32, +) -> Option { + if bin_idx >= PALETTE_RUN_PREFIX_FIRST_BYPASS_BIN_IDX { + return None; + } + if !copy_above_palette_indices_flag && bin_idx == 0 { + // §9.3.4.2.8 first bullet — dispatch to eq. 9-63. + return Some(palette_run_prefix_ctx_inc_eq_9_63(palette_idx_idc)); + } + // Otherwise: Table 9-51 lookup. + let row = usize::from(copy_above_palette_indices_flag); + let col = bin_idx as usize; + let v = PALETTE_RUN_PREFIX_CTX_IDX_MAP[row][col]; + debug_assert!( + v != PALETTE_RUN_PREFIX_EQ_9_63_DISPATCH, + "palette_run_prefix Table 9-51: the eq.-9-63 dispatch cell is \ + already handled above; reaching the lookup with the sentinel \ + indicates a derivation bug" + ); + Some(u32::from(v)) +} + +/// Table 9-43 binarization shape `cMax` for `palette_run_prefix`: +/// +/// ```text +/// cMax = Floor( Log2( PaletteMaxRunMinus1 ) ) + 1 +/// cRiceParam = 0 +/// ``` +/// +/// `PaletteMaxRunMinus1` is the §7.4.9.6 per-CU palette-run cap (one +/// less than the maximum allowed run length). When +/// `PaletteMaxRunMinus1 == 0` the TR prefix is degenerate (a single +/// terminating bin); the helper returns `1` in that case so callers +/// can still emit a one-bin TR prefix. +#[must_use] +pub fn palette_run_prefix_tr_cmax(palette_max_run_minus1: u32) -> u32 { + if palette_max_run_minus1 == 0 { + // Floor(Log2(0)) is undefined; the spec's TR-prefix shape + // collapses to a single-bin terminator in this degenerate + // case. Returning 1 keeps the TR reader well-defined. + return 1; + } + // Floor(Log2(x)) for x > 0 == 31 - leading_zeros(x). + let floor_log2 = 31 - palette_max_run_minus1.leading_zeros(); + floor_log2 + 1 +} + +// --------------------------------------------------------------------- +// coeff_abs_level_remaining (§9.3.3.11) +// --------------------------------------------------------------------- + +/// §9.3.3.11 — TR-prefix escape length for `coeff_abs_level_remaining`. +/// The §9.3.3.2 TR(`cMax`, `cRiceParam`) prefix is `cMax / (1 << +/// cRiceParam)` bins long; substituting eq. 9-26 (`cMax = 4 << +/// cRiceParam`) collapses that to a constant **4** bins regardless of +/// `cRiceParam`. The all-4-ones prefix is the escape that signals the +/// EGk(`cRiceParam + 1`) suffix is present. +pub const COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN: u32 = 4; + +/// §9.3.3.11 — `cRiceParam` adaptation, non-persistent path +/// (`persistent_rice_adaptation_enabled_flag == 0`), eq. 9-24: +/// +/// ```text +/// cRiceParam = Min( cLastRiceParam + +/// ( cLastAbsLevel > ( 3 * ( 1 << cLastRiceParam ) ) ? 1 : 0 ), +/// 4 ) +/// ``` +/// +/// The bump (+1) fires when the previous coefficient's absolute level +/// exceeded `3 << cLastRiceParam`; `cRiceParam` saturates at 4 (the +/// non-persistent ceiling). +/// +/// Inputs: +/// +/// * `c_last_abs_level` — the `cAbsLevel` from the previous invocation +/// in the same sub-block (`baseLevel + coeff_abs_level_remaining[n]` +/// of the previous scan position; `0` if this is the first +/// invocation for the sub-block). +/// * `c_last_rice_param` — the `cRiceParam` from the previous +/// invocation in the same sub-block (`0` if this is the first +/// invocation). +/// +/// Returns the per-coefficient `cRiceParam ∈ {0, 1, 2, 3, 4}` that +/// drives eq. 9-26 + the §9.3.3.2 TR-prefix shape. +#[must_use] +pub fn coeff_abs_level_remaining_c_rice_param_eq_9_24( + c_last_abs_level: u32, + c_last_rice_param: u32, +) -> u32 { + // `3 * (1 << r)` == `3 << r`; using the left-shift form keeps the + // comparison overflow-free for `r` up to 29 (3 << 29 < 2^32). + let threshold = 3u32 << c_last_rice_param; + let bump = u32::from(c_last_abs_level > threshold); + (c_last_rice_param + bump).min(4) +} + +/// §9.3.3.11 — `cRiceParam` adaptation, persistent path +/// (`persistent_rice_adaptation_enabled_flag == 1`), eq. 9-25: +/// +/// ```text +/// cRiceParam = cLastRiceParam + +/// ( cLastAbsLevel > ( 3 * ( 1 << cLastRiceParam ) ) ? 1 : 0 ) +/// ``` +/// +/// Unlike the eq. 9-24 path there is **no** Min(…, 4) ceiling — the +/// parameter keeps growing while consecutive levels exceed the +/// threshold, and the per-sub-block start value is `initRiceValue = +/// StatCoeff[ sbType ] / 4` (eq. 9-22) rather than 0. A defensive cap +/// of 24 keeps the downstream `4 << cRiceParam` / TR-suffix shifts +/// sound; reaching it would need `cLastAbsLevel > 3 << 23`, beyond +/// the §7.4.9.11 `CoeffMax` bound (eqs. 7-27 .. 7-30, at most +/// `2^22 − 1` even with `extended_precision_processing_flag == 1` at +/// `BitDepth` 16), so no conforming stream is affected. +#[must_use] +pub fn coeff_abs_level_remaining_c_rice_param_eq_9_25( + c_last_abs_level: u32, + c_last_rice_param: u32, +) -> u32 { + let r = c_last_rice_param.min(24); + let threshold = 3u32 << r; + let bump = u32::from(c_last_abs_level > threshold); + (r + bump).min(24) +} + +/// §9.3.3.4 — decode the **limited EGk** suffix of +/// `coeff_abs_level_remaining[ n ]`, invoked only when +/// `extended_precision_processing_flag == 1` and the §9.3.3.2 TR +/// prefix was the all-ones escape. `rice_param` is the §9.3.3.11 +/// "riceParam = cRiceParam + 1" input; `log2_transform_range` is +/// eq. 9-14 (`Max( 15, BitDepth + 6 )` for the block's component). +/// +/// The eq. 9-16 bin string is a unary prefix-extension run of `1` +/// bins capped at `maxPrefixExtensionLength = 28 − +/// log2TransformRange` (eq. 9-15), then — only when the run stopped +/// short of the cap — a `0` terminator, then a fixed-length escape of +/// `PrefixExtensionLength + riceParam` bits (or `log2TransformRange` +/// bits when the run hit the cap, with no terminator). The decoded +/// `symbolVal` is the escape value plus +/// `( ( 1 << PrefixExtensionLength ) − 1 ) << riceParam`. +pub fn decode_limited_egk_suffix_with( + rice_param: u32, + log2_transform_range: u32, + mut read_bin: F, +) -> Result +where + F: FnMut() -> Result, +{ + let max_prefix_extension_length = 28u32.saturating_sub(log2_transform_range); + let mut prefix_extension_length: u32 = 0; + let mut hit_cap = true; + while prefix_extension_length < max_prefix_extension_length { + if read_bin()? == 0 { + hit_cap = false; + break; + } + prefix_extension_length += 1; + } + let escape_length = if hit_cap { + log2_transform_range + } else { + prefix_extension_length + rice_param + }; + let mut escape: u64 = 0; + for _ in 0..escape_length.min(32) { + escape = (escape << 1) | u64::from(read_bin()?); + } + // Compose in u64 and saturate: the §7.4.9.11 conformance bound + // keeps every conforming value far below u32 saturation. + let base = ((1u64 << prefix_extension_length.min(32)) - 1) << rice_param.min(31); + Ok(u32::try_from(base + escape).unwrap_or(u32::MAX)) +} + +/// §9.3.3.11 eq. 9-26 — `cMax = 4 << cRiceParam`. +/// +/// Drives the §9.3.3.2 TR-prefix `cMax` input. For `cRiceParam ∈ +/// {0, 1, 2, 3, 4}` this is `{4, 8, 16, 32, 64}`. +#[must_use] +pub fn coeff_abs_level_remaining_c_max_eq_9_26(c_rice_param: u32) -> u32 { + 4u32 << c_rice_param +} + +/// §9.3.3.11 eq. 9-27 — `prefixVal = Min(cMax, level)`. +/// +/// The TR-prefix input value: clamped to `cMax` so the prefix +/// terminates at the all-ones escape when the level overflows the +/// TR-only range. +#[must_use] +pub fn coeff_abs_level_remaining_prefix_val_eq_9_27(level: u32, c_max: u32) -> u32 { + level.min(c_max) +} + +/// §9.3.3.11 eq. 9-28 — `suffixVal = level - cMax`. +/// +/// Only meaningful when the TR prefix is the all-ones escape (i.e. +/// `level >= cMax`); otherwise the suffix bin string is absent. +/// Returns `0` for `level < cMax` so callers can avoid a separate +/// branch when probing the suffix shape. +#[must_use] +pub fn coeff_abs_level_remaining_suffix_val_eq_9_28(level: u32, c_max: u32) -> u32 { + level.saturating_sub(c_max) +} + +/// §9.3.3.11 — bin-source-driven core of `coeff_abs_level_remaining[ +/// n ]` decode. Factored out of [`decode_coeff_abs_level_remaining`] +/// so the algorithm can be exercised by tests that supply a flat bin +/// sequence directly, independently of the §9.3.4.3.4 CABAC +/// arithmetic engine's bin / stream-bit relationship. +/// +/// `read_bin()` returns one bypass-coded bin (0 or 1); the closure +/// owns the underlying source state. +/// +/// See [`decode_coeff_abs_level_remaining`] for the full §9.3.3.11 +/// scope, branch coverage, and follow-up notes. +pub fn decode_coeff_abs_level_remaining_with( + c_rice_param: u32, + mut read_bin: F, +) -> Result +where + F: FnMut() -> Result, +{ + // §9.3.3.2 truncated-rice prefix: up to ESCAPE_LEN unary bins. + let mut prefix_len: u32 = 0; + while prefix_len < COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN { + let bin = read_bin()?; + if bin == 0 { + // §9.3.3.2 terminator — the value is contained inside + // the TR shape; finish with the `cRiceParam`-bit suffix. + let mut tr_suffix: u32 = 0; + for _ in 0..c_rice_param { + tr_suffix = (tr_suffix << 1) | u32::from(read_bin()?); + } + return Ok((prefix_len << c_rice_param) + tr_suffix); + } + prefix_len += 1; + } + // Escape: all-ones prefix. EGk(cRiceParam + 1) suffix follows. + let k = c_rice_param + 1; + // §9.3.3.3 eq. 9-13: the EGk unary prefix is a run of `1` bins + // terminated by a single `0` bin (the loop emits `put( 1 )` while + // `absV >= ( 1 << k )`, then `put( 0 )` to stop). The decoded prefix + // length is the count of leading `1` bins before that terminating + // `0`. + let mut prefix_ones: u32 = 0; + while prefix_ones < 32 { + let bin = read_bin()?; + if bin == 0 { + break; + } + prefix_ones += 1; + } + let suffix_bits = (prefix_ones + k).min(32); + let mut suffix: u32 = 0; + for _ in 0..suffix_bits { + suffix = (suffix << 1) | u32::from(read_bin()?); + } + // Compose in u64: `prefix_ones` can reach 32 on a non-conformant + // bin stream, where `base` alone exceeds u32::MAX. The §7.4.9.11 + // conformance requirement bounds the corresponding TransCoeffLevel + // to [CoeffMin, CoeffMax] (eqs. 7-27 .. 7-30), far below the + // saturation point, so the clamp only fires on bin streams the + // spec already rejects — the decode stays total instead of + // overflowing. + let base = ((1u64 << prefix_ones) - 1) << k; + let c_max = u64::from(coeff_abs_level_remaining_c_max_eq_9_26(c_rice_param)); + let value = c_max + base + u64::from(suffix); + Ok(u32::try_from(value).unwrap_or(u32::MAX)) +} + +/// §9.3.3.11, `extended_precision_processing_flag == 1` variant of +/// [`decode_coeff_abs_level_remaining_with`]: the §9.3.3.2 TR prefix +/// and `cRiceParam`-bit TR suffix are unchanged, but the all-ones +/// escape switches to the §9.3.3.4 **limited EGk** suffix +/// ([`decode_limited_egk_suffix_with`]) with `riceParam = cRiceParam +/// + 1` and the component's `log2TransformRange` (eq. 9-14). +pub fn decode_coeff_abs_level_remaining_ext_with( + c_rice_param: u32, + log2_transform_range: u32, + mut read_bin: F, +) -> Result +where + F: FnMut() -> Result, +{ + let mut prefix_len: u32 = 0; + while prefix_len < COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN { + let bin = read_bin()?; + if bin == 0 { + let mut tr_suffix: u32 = 0; + for _ in 0..c_rice_param { + tr_suffix = (tr_suffix << 1) | u32::from(read_bin()?); + } + return Ok((prefix_len << c_rice_param) + tr_suffix); + } + prefix_len += 1; + } + let suffix = decode_limited_egk_suffix_with(c_rice_param + 1, log2_transform_range, read_bin)?; + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(c_rice_param); + Ok(c_max.saturating_add(suffix)) +} + +/// §9.3.3.11 — full bypass-coded decode of `coeff_abs_level_remaining[ +/// n ]` given the per-coefficient `cRiceParam` already adapted by +/// [`coeff_abs_level_remaining_c_rice_param_eq_9_24`]. +/// +/// The decoder: +/// +/// 1. Reads a unary TR prefix of up to +/// [`COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN`] = `4` bypass +/// bins. The prefix length is the number of leading `1` bins. +/// 2. If the prefix terminated short (length `< 4`), reads +/// `cRiceParam` more bypass bins as the TR-suffix portion of the +/// §9.3.3.2 shape; the decoded value is +/// `(prefix_length << cRiceParam) + tr_suffix`. +/// 3. Otherwise (the all-4-ones escape), reads an EGk suffix with +/// `k = cRiceParam + 1` per the §9.3.3.11 "non-extended-precision" +/// bullet; the decoded value is `cMax + suffixVal` where +/// `cMax = 4 << cRiceParam`. +/// +/// The function returns the bit-exact `coeff_abs_level_remaining[ n ]` +/// value (not `baseLevel + remaining`); the caller composes the final +/// signed coefficient using the §7.4.9.11 coding loop (`baseLevel`, +/// `coeff_sign_flag[n]`). +/// +/// This implements the §9.3.3.11 **non-persistent** path +/// (`persistent_rice_adaptation_enabled_flag == 0`) and the +/// **non-extended-precision** suffix branch +/// (`extended_precision_processing_flag == 0`). The persistent and +/// extended-precision branches are left for follow-up rounds; their +/// inputs (StatCoeff[sbType], the §9.3.3.4 limited EGk shape) require +/// trace material beyond what this round covers. +pub fn decode_coeff_abs_level_remaining( + engine: &mut CabacEngine<'_>, + c_rice_param: u32, +) -> Result { + decode_coeff_abs_level_remaining_with(c_rice_param, || engine.decode_bypass()) +} + +// --------------------------------------------------------------------- +// coeff_sign_flag[ n ] — §7.3.8.11 / §7.4.9.11 / Table 9-43 / Table 9-48 +// --------------------------------------------------------------------- + +/// §9.3.3.5 / Table 9-43 — `coeff_sign_flag[ n ]` binarization shape. +/// +/// Fixed-length with `cMax = 1` — a single bin per scan position. The +/// spec's §9.3.3.5 derivation gives `fixedLength = Ceil(Log2(cMax + 1)) +/// = Ceil(Log2(2)) = 1`, so the on-wire string is exactly one bit +/// whose value is the flag itself. +pub const COEFF_SIGN_FLAG_FL_CMAX: u32 = 1; +/// §9.3.3.5 — bit width of the FL string for `coeff_sign_flag[ n ]`. +/// +/// `Ceil(Log2(COEFF_SIGN_FLAG_FL_CMAX + 1)) = 1`. Exposed so callers +/// composing the slice-data bypass tail can iterate the per-scan-position +/// sign bits without re-deriving the FL width. +pub const COEFF_SIGN_FLAG_FL_NBITS: u32 = 1; + +/// §9.3.4.2 / Table 9-48 — `coeff_sign_flag[ n ]` is fully bypass-coded. +/// +/// Table 9-48 marks the bin-0 cell `bypass` and all subsequent bin-index +/// columns `na`; there is one bin per invocation and it carries no +/// context coupling. +/// +/// Returns the per-scan-position sign bit: `0` ⇒ positive, +/// `1` ⇒ negative (per §7.4.9.11). The signed transform-coefficient +/// level the slice-data residual loop emits is then +/// `(coeff_abs_level_remaining[n] + baseLevel) * (1 − 2 * +/// coeff_sign_flag[n])`; see [`signed_level_from_sign_flag`] for the +/// arithmetic helper. +/// +/// §9.3.4.3.6 specifies an alignment process that runs prior to +/// bypass decoding of `coeff_abs_level_remaining[ ]` and +/// `coeff_sign_flag[ ]` (`ivlCurrRange := 256`); the slice-data parser +/// invokes [`CabacEngine::align`] once at the start of the bypass +/// run, so this entry point reads a single bypass bin via the +/// post-alignment engine state. +pub fn decode_coeff_sign_flag(engine: &mut CabacEngine<'_>) -> Result { + engine.decode_bypass() +} + +/// §7.4.9.11 — compose the signed transform-coefficient level from the +/// unsigned `cAbsLevel` (`baseLevel + coeff_abs_level_remaining[n]`) +/// and the per-scan-position `coeff_sign_flag[n]`. +/// +/// Implements `level * (1 − 2 * sign_flag)`: +/// +/// * `sign_flag == 0` ⇒ the level is positive, returns `+abs_level`. +/// * `sign_flag == 1` ⇒ the level is negative, returns `-abs_level`. +/// +/// Inputs: +/// +/// * `abs_level` — the unsigned absolute level emitted by the +/// §7.3.8.11 residual loop (`baseLevel` plus, when present, +/// [`decode_coeff_abs_level_remaining`]'s output). +/// * `sign_flag` — the per-scan-position bin read via +/// [`decode_coeff_sign_flag`] (or inferred to `0` per §7.4.9.11 +/// when the syntax element is not present). +/// +/// The §7.4.9.11 sign-data-hiding adjustment (when +/// `sign_data_hiding_enabled_flag && signHidden` and the +/// `firstSigScanPos` sum-of-absolute-levels parity is odd) is a +/// post-step the slice-data loop applies at a different scope and is +/// **not** folded into this helper. +/// +/// The return type is `i32` because `coeff_abs_level_remaining[n] + +/// baseLevel` can exceed `i16::MAX` for high-bit-depth profiles before +/// the §7.4.9.11 / Annex A clipping to `[CoeffMin, CoeffMax]`. +#[must_use] +pub fn signed_level_from_sign_flag(abs_level: u32, sign_flag: u8) -> i32 { + let abs_signed = abs_level as i32; + if sign_flag == 0 { + abs_signed + } else { + -abs_signed + } +} + +// --------------------------------------------------------------------- +// mvd_coding( x0, y0, refList ) — §7.3.8.9 / §7.4.9.9 / Table 9-43 / +// Table 9-48. Motion-vector-difference binarization: two context-coded +// magnitude flags (`abs_mvd_greater0_flag`, `abs_mvd_greater1_flag`), +// a bypass EG1 escape magnitude (`abs_mvd_minus2`), and a bypass FL +// sign bit (`mvd_sign_flag`), composed per equation 7-73 into the +// signed component difference `lMvd`. +// --------------------------------------------------------------------- + +/// §9.3.4.2 / Table 9-48 — `abs_mvd_greater0_flag[ ]` is context-coded +/// with a single context (`ctxInc = 0` at bin 0; all later bin-index +/// columns are `na` since the FL `cMax = 1` binarization is one bin). +/// +/// Table 9-4 maps the element to its `Table 9-23` context bank; per +/// [`SliceContexts`] this is the single-entry `abs_mvd_greater0_flag` +/// array (inter slices only). The caller passes the corresponding +/// [`ContextModel`]; this function returns the fixed `ctxInc`. +#[must_use] +pub fn abs_mvd_greater0_flag_ctx_inc() -> u32 { + 0 +} + +/// §9.3.4.2 / Table 9-48 — `abs_mvd_greater1_flag[ ]` is context-coded +/// with a single context (`ctxInc = 0` at bin 0; later columns `na`). +/// +/// The element binds to its own `Table 9-23` context bank (distinct +/// from `abs_mvd_greater0_flag`); the returned `ctxInc` selects within +/// that single-entry bank. +#[must_use] +pub fn abs_mvd_greater1_flag_ctx_inc() -> u32 { + 0 +} + +/// Table 9-43 — `abs_mvd_greater0_flag[ ]` / `abs_mvd_greater1_flag[ ]` +/// / `mvd_sign_flag[ ]` are FL with `cMax = 1` (a single bin each). +pub const ABS_MVD_GREATER_FLAG_FL_CMAX: u32 = 1; + +/// Table 9-43 — `abs_mvd_minus2[ ]` uses EG1 (k-th order Exp-Golomb +/// with `k = 1`), fully bypass-coded per Table 9-48. +pub const ABS_MVD_MINUS2_EG_K: u32 = 1; + +/// Table 9-43 — `mvd_sign_flag[ ]` is FL with `cMax = 1`; the single +/// bin (bypass-coded per Table 9-48) is the sign bit itself. +pub const MVD_SIGN_FLAG_FL_CMAX: u32 = 1; + +/// One decoded `mvd_coding( )` motion-vector-difference component +/// (§7.3.8.9 / §7.4.9.9). All four wire fields are retained alongside +/// the equation-7-73 composed signed value so callers can both record +/// the parsed syntax and consume `lMvd` directly. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MvdComponent { + /// `abs_mvd_greater0_flag[ compIdx ]` — magnitude `> 0`. + pub greater0_flag: u8, + /// `abs_mvd_greater1_flag[ compIdx ]` — magnitude `> 1`. + /// `None` when not present (inferred `0` per §7.4.9.9), i.e. when + /// `greater0_flag == 0`. + pub greater1_flag: Option, + /// `abs_mvd_minus2[ compIdx ]` from the EG1 bypass escape. + /// `None` when not present (inferred `−1` per §7.4.9.9), i.e. when + /// `greater1_flag` is `0`/absent. + pub minus2: Option, + /// `mvd_sign_flag[ compIdx ]`. `None` when not present (inferred + /// `0` per §7.4.9.9), i.e. when `greater0_flag == 0`. + pub sign_flag: Option, + /// `lMvd[ compIdx ]` per equation 7-73: + /// `greater0_flag * (abs_mvd_minus2 + 2) * (1 − 2 * sign_flag)`. + /// Zero when `greater0_flag == 0`. + pub value: i32, +} + +/// §7.4.9.9 equation 7-73 — compose the signed component difference +/// `lMvd` from the four `mvd_coding( )` wire fields, applying the +/// not-present inferences: +/// +/// * `abs_mvd_greater1_flag` inferred `0` ⇒ when `greater0_flag == 1` +/// but `greater1_flag` is absent/`0`, the magnitude is exactly `1`. +/// * `abs_mvd_minus2` inferred `−1` ⇒ when absent, `minus2 + 2 == 1` +/// (the magnitude-equals-1 case); when present, magnitude is +/// `minus2 + 2` (`>= 2`). +/// * `mvd_sign_flag` inferred `0` ⇒ a positive value. +/// +/// `greater0_flag == 0` short-circuits to `0` (the whole product +/// vanishes), matching the §7.3.8.9 parse where no further fields are +/// signalled. +#[must_use] +pub fn mvd_component_value(greater0_flag: u8, minus2: Option, sign_flag: Option) -> i32 { + if greater0_flag == 0 { + return 0; + } + // abs_mvd_minus2 inferred −1 when absent ⇒ magnitude (minus2 + 2): + // absent → −1 + 2 = 1 + // present → minus2 + 2 (>= 2) + let magnitude = match minus2 { + Some(m) => m as i32 + 2, + None => 1, + }; + // mvd_sign_flag inferred 0 when absent ⇒ positive. + let sign = sign_flag.unwrap_or(0); + magnitude * (1 - 2 * i32::from(sign)) +} + +/// Decode one `mvd_coding( )` component (§7.3.8.9) from split bin +/// readers, factored out of [`decode_mvd_component`] so the +/// composition can be unit-tested without driving the arithmetic +/// engine's range/offset state. +/// +/// `read_ctx_bin` is invoked for each context-coded bin in parse +/// order — first `abs_mvd_greater0_flag`, then (only when that bin is +/// `1`) `abs_mvd_greater1_flag`. `read_bypass_bin` is invoked for each +/// bypass bin of the EG1 `abs_mvd_minus2` escape and the +/// `mvd_sign_flag` bit; the EG1 read consumes the §9.3.3.3 leading-zero +/// prefix plus `leading_zeros + 1` suffix bins. +/// +/// The reader split mirrors Table 9-48: the two `greater` flags are +/// `DecodeDecision` bins, `abs_mvd_minus2` and `mvd_sign_flag` are +/// `DecodeBypass` bins. Per §7.3.8.9, `abs_mvd_minus2` is only read +/// when `abs_mvd_greater1_flag == 1`, and `mvd_sign_flag` only when +/// `abs_mvd_greater0_flag == 1`. The EG1 read consumes the §9.3.3.3 +/// prefix (a run of `1` bins terminated by `0`) plus `prefix_ones + 1` +/// suffix bins. +pub fn decode_mvd_component_with( + mut read_ctx_bin: C, + mut read_bypass_bin: B, +) -> Result +where + C: FnMut() -> Result, + B: FnMut() -> Result, +{ + let greater0_flag = read_ctx_bin()?; + if greater0_flag == 0 { + // §7.3.8.9: no further fields signalled; all inferred absent. + return Ok(MvdComponent { + greater0_flag: 0, + greater1_flag: None, + minus2: None, + sign_flag: None, + value: 0, + }); + } + let greater1_flag = read_ctx_bin()?; + // abs_mvd_minus2 is present only when greater1_flag == 1. + let minus2 = if greater1_flag == 1 { + Some(read_eg_k_with(ABS_MVD_MINUS2_EG_K, &mut read_bypass_bin)?) + } else { + None + }; + // mvd_sign_flag is present whenever greater0_flag == 1. + let sign_flag = read_bypass_bin()?; + let value = mvd_component_value(greater0_flag, minus2, Some(sign_flag)); + Ok(MvdComponent { + greater0_flag, + greater1_flag: Some(greater1_flag), + minus2, + sign_flag: Some(sign_flag), + value, + }) +} + +/// Decode one `mvd_coding( )` component (§7.3.8.9 / §7.4.9.9) from the +/// CABAC engine. +/// +/// `ctx_greater0` and `ctx_greater1` are the caller's +/// [`SliceContexts::abs_mvd_greater0_flag`] / `abs_mvd_greater1_flag` +/// single-entry context models (Table 9-23 banks); they are mutated in +/// place per the §9.3.4.3.2.2 state transition. The `abs_mvd_minus2` +/// EG1 escape and the `mvd_sign_flag` bit are read via +/// [`CabacEngine::decode_bypass`]. +/// +/// The caller decodes both components (`compIdx = 0` then `1`) of a +/// `mvd_coding( )` invocation by calling this twice with the same two +/// context models; the §7.3.8.9 interleaving of the two +/// `abs_mvd_greater0_flag` bins ahead of the rest is a slice-data +/// concern handled one layer up. This entry point decodes a single +/// component end-to-end. +pub fn decode_mvd_component( + engine: &mut CabacEngine<'_>, + ctx_greater0: &mut ContextModel, + ctx_greater1: &mut ContextModel, +) -> Result { + let greater0_flag = engine.decode_decision(ctx_greater0)?; + if greater0_flag == 0 { + return Ok(MvdComponent { + greater0_flag: 0, + greater1_flag: None, + minus2: None, + sign_flag: None, + value: 0, + }); + } + let greater1_flag = engine.decode_decision(ctx_greater1)?; + let minus2 = if greater1_flag == 1 { + Some(decode_eg_k(engine, ABS_MVD_MINUS2_EG_K)?) + } else { + None + }; + let sign_flag = engine.decode_bypass()?; + let value = mvd_component_value(greater0_flag, minus2, Some(sign_flag)); + Ok(MvdComponent { + greater0_flag, + greater1_flag: Some(greater1_flag), + minus2, + sign_flag: Some(sign_flag), + value, + }) +} + +/// Decode one whole `mvd_coding( x0, y0, refList )` invocation +/// (§7.3.8.9) — BOTH components in the spec's interleaved bin order: +/// +/// ```text +/// abs_mvd_greater0_flag[ 0 ] +/// abs_mvd_greater0_flag[ 1 ] +/// if( g0[0] ) abs_mvd_greater1_flag[ 0 ] +/// if( g0[1] ) abs_mvd_greater1_flag[ 1 ] +/// if( g0[0] ) { if( g1[0] ) abs_mvd_minus2[ 0 ] mvd_sign_flag[ 0 ] } +/// if( g0[1] ) { if( g1[1] ) abs_mvd_minus2[ 1 ] mvd_sign_flag[ 1 ] } +/// ``` +/// +/// A per-component decode (two [`decode_mvd_component`] calls) reads +/// the same bins in the wrong order whenever `abs_mvd_greater0_flag[0]` +/// is set, desynchronizing the engine. +/// +/// # Errors +/// Propagates [`CabacError`] from the engine. +pub fn decode_mvd_pair( + engine: &mut CabacEngine<'_>, + ctx_greater0: &mut ContextModel, + ctx_greater1: &mut ContextModel, +) -> Result<[MvdComponent; 2], CabacError> { + let g0_0 = engine.decode_decision(ctx_greater0)?; + let g0_1 = engine.decode_decision(ctx_greater0)?; + let g1_0 = if g0_0 == 1 { + Some(engine.decode_decision(ctx_greater1)?) + } else { + None + }; + let g1_1 = if g0_1 == 1 { + Some(engine.decode_decision(ctx_greater1)?) + } else { + None + }; + let mut out = [MvdComponent { + greater0_flag: 0, + greater1_flag: None, + minus2: None, + sign_flag: None, + value: 0, + }; 2]; + for (comp, (g0, g1)) in [(g0_0, g1_0), (g0_1, g1_1)].into_iter().enumerate() { + if g0 == 0 { + continue; + } + let minus2 = if g1 == Some(1) { + Some(decode_eg_k(engine, ABS_MVD_MINUS2_EG_K)?) + } else { + None + }; + let sign_flag = engine.decode_bypass()?; + out[comp] = MvdComponent { + greater0_flag: g0, + greater1_flag: g1, + minus2, + sign_flag: Some(sign_flag), + value: mvd_component_value(g0, minus2, Some(sign_flag)), + }; + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + + // ------------------------------------------------------------- + // ctxInc derivation — pure-function tables + // ------------------------------------------------------------- + + #[test] + fn cu_qp_delta_abs_ctx_inc_table_9_32() { + // Bin 0 → dedicated ctx 0; bins 1..=4 → shared ctx 1. + assert_eq!(cu_qp_delta_abs_ctx_inc(0), 0); + assert_eq!(cu_qp_delta_abs_ctx_inc(1), 1); + assert_eq!(cu_qp_delta_abs_ctx_inc(2), 1); + assert_eq!(cu_qp_delta_abs_ctx_inc(3), 1); + assert_eq!(cu_qp_delta_abs_ctx_inc(4), 1); + } + + #[test] + fn last_sig_coeff_prefix_offset_shift_luma() { + // §9.3.4.2.3, equations for cIdx == 0: + // ctxOffset = 3*(log2-2) + ((log2-1) >> 2) + // ctxShift = (log2+1) >> 2 + // log2=2 (4x4): off = 0 + 0 = 0; shift = 3 >> 2 = 0 + // log2=3 (8x8): off = 3 + 0 = 3; shift = 4 >> 2 = 1 + // log2=4 (16x16): off = 6 + 0 = 6; shift = 5 >> 2 = 1 + // log2=5 (32x32): off = 9 + 1 = 10; shift = 6 >> 2 = 1 + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(2, false), (0, 0)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(3, false), (3, 1)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(4, false), (6, 1)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(5, false), (10, 1)); + } + + #[test] + fn last_sig_coeff_prefix_offset_shift_chroma() { + // §9.3.4.2.3, chroma row: ctxOffset = 15, ctxShift = log2 - 2. + // log2=2: (15, 0); log2=3: (15, 1); log2=4: (15, 2) + // (4:4:4 chroma can also reach log2=5 → (15, 3)). + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(2, true), (15, 0)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(3, true), (15, 1)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(4, true), (15, 2)); + assert_eq!(last_sig_coeff_prefix_ctx_offset_shift(5, true), (15, 3)); + } + + #[test] + fn last_sig_coeff_prefix_ctx_inc_eq() { + // ctxInc = (binIdx >> ctxShift) + ctxOffset. + // 32x32 luma: offset=10, shift=1. binIdx 0..=9 → + // 0,0,1,1,2,2,3,3,4,4 + 10 = 10,10,11,11,12,12,13,13,14,14. + for bin in 0..=9 { + let inc = last_sig_coeff_prefix_ctx_inc(bin, 10, 1); + assert_eq!(inc, (bin >> 1) + 10); + } + // 4x4 luma: offset=0, shift=0. binIdx 0..=2 → 0,1,2. + for bin in 0..=2 { + let inc = last_sig_coeff_prefix_ctx_inc(bin, 0, 0); + assert_eq!(inc, bin); + } + } + + #[test] + fn last_sig_coeff_cmax_per_size() { + // (log2 << 1) - 1. + assert_eq!(last_sig_coeff_prefix_cmax(2), 3); + assert_eq!(last_sig_coeff_prefix_cmax(3), 5); + assert_eq!(last_sig_coeff_prefix_cmax(4), 7); + assert_eq!(last_sig_coeff_prefix_cmax(5), 9); + } + + // ------------------------------------------------------------- + // §7.4.9.11 position derivation — trace-derived examples + // ------------------------------------------------------------- + + #[test] + fn last_sig_coeff_position_no_suffix() { + // prefix <= 3 → no suffix, position == prefix. From the + // multi-slice-per-frame trace: ctb 0, cIdx 1, prefix=2 → LastX=2. + assert_eq!(last_sig_coeff_position(0, None), 0); + assert_eq!(last_sig_coeff_position(1, None), 1); + assert_eq!(last_sig_coeff_position(2, None), 2); + assert_eq!(last_sig_coeff_position(3, None), 3); + } + + #[test] + fn last_sig_coeff_position_with_suffix_from_trace() { + // From cabac-cu-qp-delta-last-sig-trace.md, main-422-10bit + // primary fixture, luma 32x32 TB: + // x_prefix = 6, LastX = 8 → nBits = 2, suffix = 0, + // position = ((2 + (6&1)) << 2) + 0 = (2 << 2) = 8. + // y_prefix = 4, LastY = 5 → nBits = 1, suffix = 1, + // position = ((2 + (4&1)) << 1) + 1 = (2 << 1) + 1 = 5. + assert_eq!(last_sig_coeff_position(6, Some(0)), 8); + assert_eq!(last_sig_coeff_position(4, Some(1)), 5); + // Chroma 16x16 Cb (cIdx 1) row: x_prefix=4, LastX=4 → + // nBits = 1, suffix = 0 → ((2+0)<<1)+0 = 4. y_prefix=1, + // LastY=1 → no suffix. + assert_eq!(last_sig_coeff_position(4, Some(0)), 4); + assert_eq!(last_sig_coeff_position(1, None), 1); + } + + #[test] + fn last_sig_coeff_suffix_n_bits_table() { + // nBits = (prefix >> 1) - 1 for prefix > 3, else 0. + assert_eq!(last_sig_coeff_suffix_n_bits(0), 0); + assert_eq!(last_sig_coeff_suffix_n_bits(3), 0); + assert_eq!(last_sig_coeff_suffix_n_bits(4), 1); + assert_eq!(last_sig_coeff_suffix_n_bits(5), 1); + assert_eq!(last_sig_coeff_suffix_n_bits(6), 2); + assert_eq!(last_sig_coeff_suffix_n_bits(7), 2); + assert_eq!(last_sig_coeff_suffix_n_bits(8), 3); + assert_eq!(last_sig_coeff_suffix_n_bits(9), 3); + } + + // ------------------------------------------------------------- + // §9.3.3.10 / §9.3.3.11 TR + EGk helpers + // ------------------------------------------------------------- + + #[test] + fn tr_prefix_returns_value_at_terminator_bin() { + // Read four bins (0, 1, 0, 0) via a closure. cMax = 5; the + // unary terminates at the first 0 → prefix = 0, is_escape = false. + let bins = [0u8, 1, 0, 0]; + let mut idx = 0; + let (v, esc) = read_truncated_rice_prefix(5, |_bin_idx| { + let b = bins[idx]; + idx += 1; + Ok::(b) + }) + .unwrap(); + assert_eq!(v, 0); + assert!(!esc); + assert_eq!(idx, 1); + } + + #[test] + fn tr_prefix_escape_when_all_ones_to_cmax() { + // Five 1s with cMax = 5 → prefix = 5, is_escape = true. + let bins = [1u8; 5]; + let mut idx = 0; + let (v, esc) = read_truncated_rice_prefix(5, |_bin_idx| { + let b = bins[idx]; + idx += 1; + Ok::(b) + }) + .unwrap(); + assert_eq!(v, 5); + assert!(esc); + assert_eq!(idx, 5); + } + + // ------------------------------------------------------------- + // End-to-end CABAC integration — drive the engine on a crafted + // bitstream and confirm the decoded element matches the trace. + // ------------------------------------------------------------- + + /// Helper: drop an MPS-only context (`pStateIdx = 62`, very high + /// confidence) into the caller's slot. With this state the LPS + /// range is tiny and an all-zero bitstream (after init) keeps + /// taking the MPS path with `valMps = 0`, so every bin decodes to + /// 0 and the unary TR prefix terminates at the first bin. + fn fresh_mps_ctx(val_mps: u8) -> ContextModel { + ContextModel { + p_state_idx: 62, + val_mps, + } + } + + #[test] + fn cu_qp_delta_zero_when_first_bin_zero() { + // All-zero stream: 9 init bits = 0, then the first + // cu_qp_delta_abs bin is 0 → abs = 0, sign flag NOT signalled, + // value = 0. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(0); + let mut c1 = fresh_mps_ctx(0); + let d = decode_cu_qp_delta(&mut eng, &mut c0, &mut c1).unwrap(); + assert_eq!(d.abs, 0); + assert_eq!(d.sign_flag, None); + assert_eq!(d.value, 0); + } + + #[test] + fn cu_qp_delta_value_eq_neg_two_when_sign_one() { + // Engineer abs = 2 by hand: walking the TR prefix bins of the + // arithmetic decoder is non-trivial because the LPS range + // depends on context state. Instead, validate the §7.4.9.14 + // derivation directly with the trace-observed (abs=2, sign=1) + // values from the main-422-10bit primary fixture. + let abs = 2u32; + let sign = 1u8; + let value = abs as i32 * (1 - 2 * sign as i32); + assert_eq!(value, -2); + } + + #[test] + fn cu_qp_delta_signed_derivation_matches_trace_rows() { + // Walk every row of the multi-slice-per-frame trace + // (abs, sign_flag) → CuQpDeltaVal. Confirms the §7.4.9.14 + // arithmetic step in isolation. + let rows = [ + (3u32, 0u8, 3i32), + (1, 1, -1), + (1, 0, 1), + (3, 0, 3), + (2, 1, -2), + (2, 0, 2), + (3, 0, 3), + (2, 1, -2), + (1, 0, 1), + (3, 0, 3), + ]; + for (abs, sign, expected) in rows { + let got = abs as i32 * (1 - 2 * sign as i32); + assert_eq!(got, expected, "abs={abs} sign={sign}"); + } + } + + #[test] + fn last_sig_coeff_round_trips_from_a_known_bypass_stream() { + // Test the bypass-suffix path end-to-end by manually decoding + // a fixture-traced prefix=6 + suffix=0 = LastX=8 sequence. + // The TR prefix is hard to inject without controlling the LPS + // range; instead, we re-derive position from the trace's + // (prefix, observed-LastX-and-LastY) pairs and verify equation + // 7-74 directly across all primary-fixture rows. + let rows = [ + // (cIdx, prefix_x, prefix_y, LastX, LastY) + (0u32, 6u32, 4u32, 8u32, 5u32), + (1, 4, 1, 4, 1), + (1, 4, 2, 4, 2), + (2, 2, 1, 2, 1), + (2, 2, 0, 2, 0), + ]; + for (_c, px, py, lx, ly) in rows { + // X side + let n_x = last_sig_coeff_suffix_n_bits(px); + // From the trace, suffix can be inferred: + // For (6, 8): n=2, base=8 → suffix=0 + // For (4, 4): n=1, base=4 → suffix=0 + // For (2, 2): n=0, suffix=None → pos=2 + let inferred_suf_x = if n_x == 0 { + None + } else { + let base = (2 + (px & 1)) << ((px >> 1) - 1); + Some(lx - base) + }; + assert_eq!(last_sig_coeff_position(px, inferred_suf_x), lx); + // Y side + let n_y = last_sig_coeff_suffix_n_bits(py); + let inferred_suf_y = if n_y == 0 { + None + } else { + let base = (2 + (py & 1)) << ((py >> 1) - 1); + Some(ly - base) + }; + assert_eq!(last_sig_coeff_position(py, inferred_suf_y), ly); + } + } + + #[test] + fn last_sig_coeff_bank_tag_round_trip() { + // The bank tag is a routing helper for callers; verify the + // enum survives a copy + equality check. + let x = LastSigCoeffBank::X; + let y = LastSigCoeffBank::Y; + assert_ne!(x, y); + assert_eq!(x, LastSigCoeffBank::X); + assert_eq!(y, LastSigCoeffBank::Y); + } + + // ------------------------------------------------------------- + // §9.3.3.11 EGk(k=0) — driven through the engine. The bin emitted + // by `decode_bypass` depends on `ivlCurrRange` (510) versus the + // shifted `ivlOffset`, not directly on the read bit value, so we + // construct an offset that crosses the threshold on the first + // bypass read: init `ivlOffset` to 256, then a fed 1-bit pushes + // it to 513 ≥ 510, the engine returns bin = 1, and EGk's + // §9.3.3.3 EGk(0): the prefix is a run of `1` bins terminated by a + // `0`; a value of 0 is the bare terminating `0` (no prefix ones, no + // suffix bits). + #[test] + fn eg_k0_decodes_zero_when_first_bypass_returns_zero() { + // 9-bit init offset = 0 (all-zero buffer). The first bypass bin + // is `(0 << 1) | 0 = 0 < ivlCurrRange`, so DecodeBypass returns + // 0 — the bare EGk prefix terminator ⇒ value 0. + let buf = [0u8, 0, 0]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_offset(), 0); + let v = decode_eg_k0(&mut eng).unwrap(); + assert_eq!(v, 0); + } + + // ------------------------------------------------------------- + // §9.3.4.2.4 coded_sub_block_flag ctxInc + // ------------------------------------------------------------- + + #[test] + fn coded_sub_block_flag_ctx_inc_luma_no_neighbours_active() { + // §9.3.4.2.4: both neighbours = 0 → csbfCtx = 0 → + // ctxInc = min(0, 1) = 0 for luma. + assert_eq!(coded_sub_block_flag_ctx_inc(false, 0, 0), 0); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_luma_one_neighbour_active() { + // One neighbour set → csbfCtx = 1 → ctxInc = min(1, 1) = 1. + assert_eq!(coded_sub_block_flag_ctx_inc(false, 1, 0), 1); + assert_eq!(coded_sub_block_flag_ctx_inc(false, 0, 1), 1); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_luma_both_neighbours_active_clamps() { + // Both neighbours set → csbfCtx = 2 → min(2, 1) = 1 + // (equation 9-38 clamps the sum). The luma bank is {0, 1} + // so the maximum value is 1. + assert_eq!(coded_sub_block_flag_ctx_inc(false, 1, 1), 1); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_chroma_offset_two() { + // §9.3.4.2.4 equation 9-39: chroma adds 2 to the luma + // ctxInc, putting chroma in {2, 3}. + assert_eq!(coded_sub_block_flag_ctx_inc(true, 0, 0), 2); + assert_eq!(coded_sub_block_flag_ctx_inc(true, 1, 0), 3); + assert_eq!(coded_sub_block_flag_ctx_inc(true, 0, 1), 3); + assert_eq!(coded_sub_block_flag_ctx_inc(true, 1, 1), 3); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_ignores_high_bits() { + // Only the LSB of each neighbour input is consulted (the + // function masks with & 1). Confirms a defensive input + // does not leak into csbfCtx. + assert_eq!(coded_sub_block_flag_ctx_inc(false, 0xFE, 0), 0); + assert_eq!(coded_sub_block_flag_ctx_inc(false, 0xFF, 0xFE), 1); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_with_edge_drops_right() { + // 4×4 TB: log2 = 2, max sub-block index = (1 << 0) − 1 = 0. + // So xs = 0 == max → equation 9-36 does NOT apply; the + // right_neighbour input is ignored. + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 0, 0, 2, 1, 0), + 0 + ); + // 8×8 TB: log2 = 3, max sub-block index = (1 << 1) − 1 = 1. + // xs = 0 < 1 → right neighbour counts; xs = 1 == max → it + // does not. + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 0, 0, 3, 1, 0), + 1 + ); + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 1, 0, 3, 1, 0), + 0 + ); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_with_edge_drops_below() { + // 16×16 TB: log2 = 4, max sub-block index = (1 << 2) − 1 = + // 3. ys = 2 < 3 → below counts; ys = 3 == max → it does not. + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 0, 2, 4, 0, 1), + 1 + ); + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 0, 3, 4, 0, 1), + 0 + ); + } + + #[test] + fn coded_sub_block_flag_ctx_inc_with_edge_32x32_interior() { + // 32×32 TB: log2 = 5, max sub-block index = (1 << 3) − 1 = + // 7. An interior sub-block at (3, 3) with both neighbours + // active → csbfCtx = 2 → ctxInc = min(2, 1) = 1. + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(false, 3, 3, 5, 1, 1), + 1 + ); + // Same location, chroma: ctxInc = 2 + 1 = 3. + assert_eq!( + coded_sub_block_flag_ctx_inc_with_edge(true, 3, 3, 5, 1, 1), + 3 + ); + } + + // ------------------------------------------------------------- + // §9.3.4.2.2 Table 9-49 — split_cu_flag / cu_skip_flag ctxInc + // ------------------------------------------------------------- + + #[test] + fn left_above_ctx_inc_truth_table() { + // ctxInc = (condL && availableL) + (condA && availableA); + // for the four combinations of the two AND'ed booleans the + // sum is 0, 1, 1, or 2. + assert_eq!(left_above_ctx_inc(false, true, false, true), 0); + assert_eq!(left_above_ctx_inc(true, true, false, true), 1); + assert_eq!(left_above_ctx_inc(false, true, true, true), 1); + assert_eq!(left_above_ctx_inc(true, true, true, true), 2); + } + + #[test] + fn left_above_ctx_inc_unavailable_zeroes_branch() { + // If a neighbour is unavailable per §6.4.1, its branch + // contributes 0 regardless of the cond value. + assert_eq!(left_above_ctx_inc(true, false, true, false), 0); + assert_eq!(left_above_ctx_inc(true, false, true, true), 1); + assert_eq!(left_above_ctx_inc(true, true, true, false), 1); + } + + #[test] + fn split_cu_flag_cond_table() { + // §9.3.4.2.2 Table 9-49: condX = CtDepth[xNb][yNb] > + // cqtDepth. Strict inequality, so equal depth → false. + assert!(!split_cu_flag_cond(0, 0)); + assert!(!split_cu_flag_cond(1, 1)); + assert!(split_cu_flag_cond(1, 0)); + assert!(split_cu_flag_cond(3, 2)); + assert!(!split_cu_flag_cond(2, 3)); + } + + #[test] + fn cu_skip_flag_cond_table() { + // §9.3.4.2.2 Table 9-49: condX = cu_skip_flag[xNb][yNb]. + assert!(!cu_skip_flag_cond(0)); + assert!(cu_skip_flag_cond(1)); + // Only the LSB matters. + assert!(!cu_skip_flag_cond(0b1110)); + assert!(cu_skip_flag_cond(0b1111)); + } + + #[test] + fn split_cu_flag_ctx_inc_both_neighbours_deeper() { + // Both neighbours at depth 2, current cqtDepth = 1 → both + // conds true. Both available → ctxInc = 2. + assert_eq!(split_cu_flag_ctx_inc(2, true, 2, true, 1), 2); + } + + #[test] + fn split_cu_flag_ctx_inc_only_left_deeper() { + // Left at depth 2, above at depth 1, current cqtDepth = 1. + // condL true (2 > 1), condA false (1 > 1 == false) → + // ctxInc = 1. + assert_eq!(split_cu_flag_ctx_inc(2, true, 1, true, 1), 1); + } + + #[test] + fn split_cu_flag_ctx_inc_unavailable_left_drops_contribution() { + // Same conds as the both-deeper test, but left is + // unavailable per §6.4.1 → its contribution is 0. + assert_eq!(split_cu_flag_ctx_inc(2, false, 2, true, 1), 1); + // Both unavailable → 0 regardless of CtDepth. + assert_eq!(split_cu_flag_ctx_inc(7, false, 7, false, 0), 0); + } + + #[test] + fn cu_skip_flag_ctx_inc_table() { + // Walk the (L, availL, A, availA) truth table for cu_skip_flag. + assert_eq!(cu_skip_flag_ctx_inc(0, true, 0, true), 0); + assert_eq!(cu_skip_flag_ctx_inc(1, true, 0, true), 1); + assert_eq!(cu_skip_flag_ctx_inc(0, true, 1, true), 1); + assert_eq!(cu_skip_flag_ctx_inc(1, true, 1, true), 2); + // Unavailable neighbours zero their contribution even if + // the flag itself is set. + assert_eq!(cu_skip_flag_ctx_inc(1, false, 1, true), 1); + assert_eq!(cu_skip_flag_ctx_inc(1, true, 1, false), 1); + assert_eq!(cu_skip_flag_ctx_inc(1, false, 1, false), 0); + } + + #[test] + fn split_cu_flag_ctx_inc_bounded_zero_three() { + // ctxInc must lie in {0, 1, 2} regardless of the inputs. + for left_d in 0u32..=4 { + for above_d in 0u32..=4 { + for &cqt in &[0u32, 1, 2, 3] { + for &avl in &[false, true] { + for &ava in &[false, true] { + let c = split_cu_flag_ctx_inc(left_d, avl, above_d, ava, cqt); + assert!(c <= 2, "ctxInc out of {{0,1,2}} for inputs"); + } + } + } + } + } + } + + // ------------------------------------------------------------- + // split_transform_flag ctxInc — Table 9-48 row + // ------------------------------------------------------------- + + #[test] + fn split_transform_flag_ctx_inc_table_row() { + // ctxInc = 5 − log2TrafoSize for log2TrafoSize in + // {2, 3, 4, 5} → ctxInc in {3, 2, 1, 0}. + assert_eq!(split_transform_flag_ctx_inc(2), 3); + assert_eq!(split_transform_flag_ctx_inc(3), 2); + assert_eq!(split_transform_flag_ctx_inc(4), 1); + assert_eq!(split_transform_flag_ctx_inc(5), 0); + } + + #[test] + fn split_transform_flag_ctx_inc_bounded_zero_three() { + // The four legal residual-quadtree TB sizes map exactly + // onto the four-context bank {0, 1, 2, 3}. + for log2 in 2u32..=5 { + let inc = split_transform_flag_ctx_inc(log2); + assert!(inc <= 3, "ctxInc {} out of bank {{0..=3}}", inc); + } + } + + // ------------------------------------------------------------- + // cbf_luma / cbf_cb / cbf_cr ctxInc — Table 9-48 rows + // ------------------------------------------------------------- + + #[test] + fn cbf_luma_ctx_inc_table_row() { + // ctxInc = (trafoDepth == 0) ? 1 : 0. + assert_eq!(cbf_luma_ctx_inc(0), 1); + assert_eq!(cbf_luma_ctx_inc(1), 0); + assert_eq!(cbf_luma_ctx_inc(2), 0); + assert_eq!(cbf_luma_ctx_inc(3), 0); + assert_eq!(cbf_luma_ctx_inc(4), 0); + } + + #[test] + fn cbf_luma_ctx_inc_bank_zero_one() { + // The two-ctx bank {0, 1}: every legal trafoDepth lands in + // one of those two slots. + for d in 0u32..=4 { + let inc = cbf_luma_ctx_inc(d); + assert!(inc <= 1, "cbf_luma ctxInc {} out of {{0, 1}}", inc); + } + } + + #[test] + fn cbf_chroma_ctx_inc_identity() { + // ctxInc = trafoDepth for both cbf_cb and cbf_cr (shared). + for d in 0u32..=4 { + assert_eq!(cbf_chroma_ctx_inc(d), d); + assert_eq!(cbf_cb_ctx_inc(d), d); + assert_eq!(cbf_cr_ctx_inc(d), d); + } + } + + #[test] + fn cbf_cb_cr_share_formula() { + // cbf_cb and cbf_cr always agree at the bank-relative + // ctxInc layer; the distinct context banks are encoded in + // the caller's ctxIdxOffset, not here. + for d in 0u32..=4 { + assert_eq!(cbf_cb_ctx_inc(d), cbf_cr_ctx_inc(d)); + } + } + + // ------------------------------------------------------------- + // inter_pred_idc ctxInc — Table 9-48 row + // ------------------------------------------------------------- + + #[test] + fn inter_pred_idc_bin_0_routes_ct_depth() { + // For a PU that is not 8×4 or 4×8 (nPbW+nPbH != 12), bin 0 + // ctxInc = CtDepth. + // 64×64 PU (CTU root): 64+64=128 != 12; CtDepth=0 → 0. + assert_eq!(inter_pred_idc_ctx_inc(0, 64, 64, 0), 0); + // 16×16 PU at CtDepth 2: 16+16=32 != 12 → ctxInc = 2. + assert_eq!(inter_pred_idc_ctx_inc(0, 16, 16, 2), 2); + // 8×8 PU at CtDepth 3: 8+8=16 != 12 → ctxInc = 3. + assert_eq!(inter_pred_idc_ctx_inc(0, 8, 8, 3), 3); + } + + #[test] + fn inter_pred_idc_bin_0_escape_on_16_sample_pus() { + // 8×4 PU: nPbW + nPbH = 12 → bin 0 ctxInc = 4, regardless + // of CtDepth. + assert_eq!(inter_pred_idc_ctx_inc(0, 8, 4, 0), 4); + assert_eq!(inter_pred_idc_ctx_inc(0, 8, 4, 3), 4); + // 4×8 PU: same. + assert_eq!(inter_pred_idc_ctx_inc(0, 4, 8, 0), 4); + assert_eq!(inter_pred_idc_ctx_inc(0, 4, 8, 3), 4); + } + + #[test] + fn inter_pred_idc_bin_1_always_ctx_4() { + // Bin 1 ctxInc = 4 regardless of nPbW / nPbH / CtDepth. + assert_eq!(inter_pred_idc_ctx_inc(1, 64, 64, 0), 4); + assert_eq!(inter_pred_idc_ctx_inc(1, 8, 4, 3), 4); + assert_eq!(inter_pred_idc_ctx_inc(1, 4, 8, 2), 4); + assert_eq!(inter_pred_idc_ctx_inc(1, 16, 8, 1), 4); + } + + #[test] + fn inter_pred_idc_ctx_inc_bank_zero_four() { + // ctxInc ∈ {0, 1, 2, 3, 4} across all legal inputs. + for &(w, h) in &[ + (64, 64), + (32, 32), + (16, 16), + (8, 8), + (8, 4), + (4, 8), + (16, 8), + (8, 16), + ] { + for ct_depth in 0u32..=3 { + for bin_idx in 0u32..=1 { + let inc = inter_pred_idc_ctx_inc(bin_idx, w, h, ct_depth); + assert!(inc <= 4, "ctxInc {} out of {{0..=4}}", inc); + } + } + } + } + + // ------------------------------------------------------------- + // log2_res_scale_abs_plus1 / res_scale_sign_flag ctxInc — + // Table 9-48 rows for §7.3.8.13 cross_comp_pred() + // ------------------------------------------------------------- + + #[test] + fn log2_res_scale_abs_plus1_ctx_inc_cb_bank() { + // c = 0 (Cb): ctxInc = binIdx for binIdx ∈ {0, 1, 2, 3} → + // bank {0, 1, 2, 3}. + for bin_idx in 0u32..=3 { + assert_eq!(log2_res_scale_abs_plus1_ctx_inc(bin_idx, 0), bin_idx); + } + } + + #[test] + fn log2_res_scale_abs_plus1_ctx_inc_cr_bank() { + // c = 1 (Cr): ctxInc = 4 + binIdx for binIdx ∈ {0, 1, 2, 3} + // → bank {4, 5, 6, 7}. + for bin_idx in 0u32..=3 { + assert_eq!(log2_res_scale_abs_plus1_ctx_inc(bin_idx, 1), 4 + bin_idx); + } + } + + #[test] + fn log2_res_scale_abs_plus1_ctx_inc_banks_disjoint() { + // Cb and Cr banks must not overlap. + for bin_idx in 0u32..=3 { + let cb = log2_res_scale_abs_plus1_ctx_inc(bin_idx, 0); + let cr = log2_res_scale_abs_plus1_ctx_inc(bin_idx, 1); + assert!( + cb < 4 && (4..8).contains(&cr), + "Cb / Cr ctxInc not in disjoint banks: cb={}, cr={}", + cb, + cr + ); + } + } + + #[test] + fn res_scale_sign_flag_ctx_inc_identity() { + // ctxInc = c. One bit per chroma component, each on its own + // context. + assert_eq!(res_scale_sign_flag_ctx_inc(0), 0); + assert_eq!(res_scale_sign_flag_ctx_inc(1), 1); + } + + #[test] + fn cross_comp_pred_smoke_and_res_scale_val() { + // §7.3.8.12 decode end-to-end: the TR(cMax=4) prefix plus the + // conditional sign flag, with the §7.4.9.12 ResScaleVal + // derivation (eqs 7-79 / 7-80) consistent with the decoded + // pair. + let buf = [0x5A; 32]; + let mut engine = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut prefix = [ContextModel::init(154, 26); 4]; + let mut sign = ContextModel::init(154, 26); + let ccp = decode_cross_comp_pred(&mut engine, &mut prefix, &mut sign).unwrap(); + assert!(ccp.log2_res_scale_abs_plus1 <= LOG2_RES_SCALE_ABS_PLUS1_TR_CMAX); + if ccp.log2_res_scale_abs_plus1 == 0 { + assert_eq!(ccp.res_scale_val, 0); + assert!(ccp.res_scale_sign_flag.is_none()); + } else { + let s = ccp + .res_scale_sign_flag + .expect("sign present when prefix != 0"); + let mag = 1i32 << (ccp.log2_res_scale_abs_plus1 - 1); + assert_eq!(ccp.res_scale_val, mag * (1 - 2 * i32::from(s))); + } + } + + #[test] + fn tu_residual_act_flag_inferred_and_ctx_inc() { + // §7.4.9.10 inferred 0; Table 9-48 ctxInc 0; FL cMax = 1. + assert_eq!(tu_residual_act_flag_inferred(), 0); + assert_eq!(tu_residual_act_flag_ctx_inc(), 0); + assert_eq!(TU_RESIDUAL_ACT_FLAG_FL_CMAX, 1); + // A single context-coded bin decodes to 0 or 1. + let buf = [0x5A; 8]; + let mut engine = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = ContextModel::init(154, 26); + let bit = decode_tu_residual_act_flag(&mut engine, &mut ctx).unwrap(); + assert!(bit <= 1); + } + + // ------------------------------------------------------------- + // SAO ctxInc / binarization-shape — Table 9-48 + Table 9-43 + // ------------------------------------------------------------- + + #[test] + fn sao_merge_flag_ctx_inc_is_zero() { + // Table 9-48 row for sao_merge_left_flag / sao_merge_up_flag: + // bin 0 ctxInc = 0; the FL cMax = 1 ⇒ exactly one bin total. + assert_eq!(sao_merge_flag_ctx_inc(), 0); + assert_eq!(SAO_MERGE_FLAG_FL_CMAX, 1); + } + + #[test] + fn sao_type_idx_ctx_inc_bin_zero() { + // Table 9-48 row for sao_type_idx_{luma,chroma}: bin 0 ctxInc + // = 0 (the only context-coded bin); bin 1 is bypass per + // Table 9-48 and not routed through this helper. + assert_eq!(sao_type_idx_ctx_inc(0), 0); + } + + #[test] + fn sao_type_idx_tr_cmax_is_two() { + // §9.3.3.10 Table 9-43: TR cMax = 2 caps the prefix at two + // bins (the §7.4.9.3 SaoTypeIdx range {0, 1, 2}: NOT_APPLIED + // / BAND / EDGE). + assert_eq!(SAO_TYPE_IDX_TR_CMAX, 2); + } + + #[test] + fn sao_offset_sign_fl_cmax_is_one() { + // Table 9-43: FL cMax = 1 ⇒ single bypass bin. + assert_eq!(SAO_OFFSET_SIGN_FL_CMAX, 1); + } + + #[test] + fn sao_band_position_fl_shape() { + // Table 9-43: FL cMax = 31 ⇒ 5 bypass bins (§9.3.3.5 + // ceil(log2(32)) = 5). + assert_eq!(SAO_BAND_POSITION_FL_CMAX, 31); + assert_eq!(SAO_BAND_POSITION_FL_NBITS, 5); + // Sanity: the FL-of-cMax-31 nbits is the expected log2 ceil. + // 2^5 = 32 = cMax + 1. + assert_eq!( + 1u32 << SAO_BAND_POSITION_FL_NBITS, + SAO_BAND_POSITION_FL_CMAX + 1 + ); + } + + #[test] + fn sao_eo_class_fl_shape() { + // Table 9-43: FL cMax = 3 ⇒ 2 bypass bins (encoding §7.4.9.3 + // SaoEoClass ∈ {0, 1, 2, 3}). + assert_eq!(SAO_EO_CLASS_FL_CMAX, 3); + assert_eq!(SAO_EO_CLASS_FL_NBITS, 2); + // Sanity: 2^2 = 4 = cMax + 1. + assert_eq!(1u32 << SAO_EO_CLASS_FL_NBITS, SAO_EO_CLASS_FL_CMAX + 1); + } + + #[test] + fn sao_offset_abs_tr_cmax_8bit() { + // §9.3.3.5: cMax = (1 << min(bitDepth, 10) − 5) − 1. + // bitDepth = 8 ⇒ (1 << 3) − 1 = 7. + assert_eq!(sao_offset_abs_tr_cmax(8), 7); + } + + #[test] + fn sao_offset_abs_tr_cmax_10bit() { + // bitDepth = 10 ⇒ (1 << 5) − 1 = 31. + assert_eq!(sao_offset_abs_tr_cmax(10), 31); + } + + #[test] + fn sao_offset_abs_tr_cmax_9bit() { + // bitDepth = 9 ⇒ (1 << 4) − 1 = 15. + assert_eq!(sao_offset_abs_tr_cmax(9), 15); + } + + #[test] + fn sao_offset_abs_tr_cmax_clamps_above_10() { + // §9.3.3.5 Min(bitDepth, 10): bitDepth >= 10 must clamp to + // the 10-bit cMax = 31. Covers 12-bit and 16-bit profiles. + assert_eq!(sao_offset_abs_tr_cmax(11), 31); + assert_eq!(sao_offset_abs_tr_cmax(12), 31); + assert_eq!(sao_offset_abs_tr_cmax(16), 31); + } + + #[test] + fn sao_offset_abs_tr_cmax_monotone() { + // cMax is non-decreasing in bitDepth across the clamp at 10. + let mut prev = sao_offset_abs_tr_cmax(8); + for bd in 9u32..=16 { + let cur = sao_offset_abs_tr_cmax(bd); + assert!( + cur >= prev, + "cMax must be non-decreasing in bitDepth: bd={} cur={} prev={}", + bd, + cur, + prev + ); + prev = cur; + } + } + + // ------------------------------------------------------------- + // §9.3.4.2.6 coeff_abs_level_greater1_flag — Greater1State + // ------------------------------------------------------------- + + #[test] + fn greater1_initial_state_is_set_zero_ctx_one() { + // Per §9.3.4.2.6, the first sub-block enters with + // lastGreater1Ctx = 1 (no eq.-9-58 bump) and greater1Ctx = 1. + // Eq. 9-56 forces ctxSet = 0 when i == 0. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + assert_eq!(s.ctx_set, 0); + assert_eq!(s.greater1_ctx, 1); + // Eq. 9-59 first-bin ctxInc = 0 * 4 + 1 = 1 for luma. + assert_eq!(s.current_ctx_inc(false), 1); + // Chroma adds +16 per eq. 9-60. + assert_eq!(s.current_ctx_inc(true), 17); + } + + #[test] + fn greater1_eq_9_57_luma_nonzero_subblock_uses_ctx_set_two() { + // Eq. 9-57: i > 0 and cIdx == 0 (luma) ⇒ ctxSet starts at 2. + let mut s = Greater1State::new(); + s.on_subblock_entry(1, false, 0); + assert_eq!(s.ctx_set, 2); + // First-bin ctxInc = 2 * 4 + 1 = 9 for luma. + assert_eq!(s.current_ctx_inc(false), 9); + } + + #[test] + fn greater1_eq_9_56_chroma_always_starts_at_zero() { + // Eq. 9-56: cIdx > 0 (chroma) ⇒ ctxSet = 0 regardless of i. + for i in [0u32, 1, 2, 5, 7] { + let mut s = Greater1State::new(); + s.on_subblock_entry(i, true, 0); + assert_eq!(s.ctx_set, 0, "chroma sub-block i={} ctxSet", i); + // Chroma first-bin ctxInc = 0 * 4 + 1 + 16 = 17. + assert_eq!(s.current_ctx_inc(true), 17); + } + } + + #[test] + fn greater1_per_bin_step_flag_one_resets_ctx_to_zero() { + // §9.3.4.2.6: lastGreater1Flag == 1 ⇒ greater1Ctx becomes 0. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(1); + assert_eq!(s.greater1_ctx, 0); + // Eq. 9-59 next-bin ctxInc = 0 * 4 + min(3, 0) = 0. + assert_eq!(s.current_ctx_inc(false), 0); + } + + #[test] + fn greater1_per_bin_step_flag_zero_increments() { + // §9.3.4.2.6: lastGreater1Flag == 0 ⇒ greater1Ctx + // incremented (until eq.-9-59 clamps at 3). + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + // 1 → 2 → 3 → 3 (clamped). + s.on_coeff_abs_level_greater1_flag(0); + assert_eq!(s.greater1_ctx, 2); + s.on_coeff_abs_level_greater1_flag(0); + assert_eq!(s.greater1_ctx, 3); + s.on_coeff_abs_level_greater1_flag(0); + assert_eq!(s.greater1_ctx, 3); + // Eq. 9-59: 0 * 4 + 3 = 3. + assert_eq!(s.current_ctx_inc(false), 3); + } + + #[test] + fn greater1_per_bin_step_after_reset_stops_advancing() { + // §9.3.4.2.6: once greater1Ctx reaches 0 the "When + // greater1Ctx > 0" guard skips the update on every later bin + // in the same sub-block. The terminal value stays 0. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(1); // → 0 + s.on_coeff_abs_level_greater1_flag(0); // skipped + s.on_coeff_abs_level_greater1_flag(1); // skipped + assert_eq!(s.greater1_ctx, 0); + } + + #[test] + fn greater1_eq_9_58_bumps_ctx_set_when_last_greater1_ctx_zero() { + // Sub-block 0: read one flag = 0 → greater1Ctx terminal = 2. + // Then enter sub-block 1 with last_greater1_flag = 0: + // lastGreater1Ctx = 2 (post-spec mutation) ≠ 0 ⇒ no bump. + // But sub-block 1 with i > 0 starts at ctxSet = 2 by eq. 9-57. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(0); // greater1Ctx 1→2 + s.on_subblock_entry(1, false, 0); + // ctxSet starts at 2 per eq. 9-57; no eq.-9-58 bump since + // lastGreater1Ctx mutation 2+1=3 ≠ 0. + assert_eq!(s.ctx_set, 2); + } + + #[test] + fn greater1_eq_9_58_bump_triggers_after_flag_one_ladder() { + // Sub-block 0: greater1Ctx 1→0 via flag = 1. Then sub-block 1 + // enters with last_greater1_flag = 1: lastGreater1Ctx is 0 + // (the spec's "When lastGreater1Ctx > 0" guard skips the + // mutation, retaining 0). Eq. 9-58 bumps ctxSet by 1. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(1); // → 0 + s.on_subblock_entry(1, false, 1); + // Eq. 9-57 says ctxSet = 2 (i > 0, luma), then eq. 9-58 + // bumps by one ⇒ 3. + assert_eq!(s.ctx_set, 3); + // greater1Ctx resets to 1 per §9.3.4.2.6. + assert_eq!(s.greater1_ctx, 1); + // Eq. 9-59 first-bin ctxInc = 3 * 4 + 1 = 13. + assert_eq!(s.current_ctx_inc(false), 13); + } + + #[test] + fn greater1_chroma_subblock_with_eq_9_58_bump() { + // Chroma sub-block 0: flag = 1 → greater1Ctx 1→0. + // Sub-block 1 (chroma) enters with last_greater1_flag = 1 + // ⇒ eq. 9-56 forces ctxSet = 0, then eq. 9-58 bumps to 1. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, true, 0); + s.on_coeff_abs_level_greater1_flag(1); + s.on_subblock_entry(1, true, 1); + assert_eq!(s.ctx_set, 1); + // Chroma ctxInc = 1 * 4 + 1 + 16 = 21. + assert_eq!(s.current_ctx_inc(true), 21); + } + + #[test] + fn greater1_ctx_inc_clamps_at_min_three() { + // Eq. 9-59 explicitly takes Min(3, greater1Ctx). The state + // machine tracks the clamped value, so synthesising ctxSet=1, + // greater1Ctx=3 gives ctxInc = 4 + 3 = 7 for luma; greater1Ctx + // can never exceed 3 internally so this is enforced by the + // type, not the read path. + let mut s = Greater1State::new(); + // Manually push to (ctxSet=1, greater1Ctx=3) by reading three + // greater1=0 bins from the first sub-block (the third hits + // the clamp). + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(0); // 1→2 + s.on_coeff_abs_level_greater1_flag(0); // 2→3 + s.on_coeff_abs_level_greater1_flag(0); // 3→3 (clamped) + assert_eq!(s.greater1_ctx, 3); + // Eq. 9-59 = 0*4 + 3 = 3. + assert_eq!(s.current_ctx_inc(false), 3); + // Chroma adds +16. + assert_eq!(s.current_ctx_inc(true), 19); + } + + // ------------------------------------------------------------- + // §9.3.4.2.7 coeff_abs_level_greater2_flag — ctxInc derivation + // ------------------------------------------------------------- + + #[test] + fn greater2_ctx_inc_is_ctx_set_for_luma() { + // Eq. 9-61: ctxInc = ctxSet for cIdx == 0. + for ctx_set in 0u32..=3 { + assert_eq!( + coeff_abs_level_greater2_flag_ctx_inc(ctx_set, false), + ctx_set, + "luma ctxSet={}", + ctx_set + ); + } + } + + #[test] + fn greater2_ctx_inc_chroma_adds_four() { + // Eq. 9-62: ctxInc = ctxSet + 4 for cIdx > 0. + for ctx_set in 0u32..=3 { + assert_eq!( + coeff_abs_level_greater2_flag_ctx_inc(ctx_set, true), + ctx_set + 4, + "chroma ctxSet={}", + ctx_set + ); + } + } + + #[test] + fn greater2_reads_same_ctx_set_as_greater1_machine() { + // §9.3.4.2.7 explicitly references the §9.3.4.2.6 ctxSet for + // the same sub-block. Walk a small example: luma, sub-block 0, + // first greater-1 flag = 1, then the greater-2 flag is read at + // the lastGreater1ScanPos in the same sub-block ⇒ ctxSet = 0. + let mut s = Greater1State::new(); + s.on_subblock_entry(0, false, 0); + s.on_coeff_abs_level_greater1_flag(1); + assert_eq!(s.ctx_set(), 0); + assert_eq!(coeff_abs_level_greater2_flag_ctx_inc(s.ctx_set(), false), 0); + + // After the eq.-9-58 bump on entry to sub-block 1 (last + // flag = 1), ctxSet = 3 and the greater-2 read picks up 3. + s.on_subblock_entry(1, false, 1); + assert_eq!(s.ctx_set(), 3); + assert_eq!(coeff_abs_level_greater2_flag_ctx_inc(s.ctx_set(), false), 3); + assert_eq!(coeff_abs_level_greater2_flag_ctx_inc(s.ctx_set(), true), 7); + } + + #[test] + fn coeff_abs_level_greater_x_fl_shape_is_one_bin() { + // Table 9-43: both flags are FL with cMax = 1 (a single + // context-coded bin per invocation). + assert_eq!(COEFF_ABS_LEVEL_GREATER_X_FL_CMAX, 1); + } + + // ------------------------------------------------------------- + // §9.3.4.2.5 sig_coeff_flag ctxInc derivation + // ------------------------------------------------------------- + + #[test] + fn sig_coeff_flag_ctx_idx_map_matches_table_9_50() { + // Table 9-50 verbatim — sixteen entries indexed by i ∈ 0..16. + let expected: [u8; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8]; + assert_eq!(SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2, expected); + // Range invariant: every entry is in {0..=8} (matches the + // 4×4 luma / chroma context-bank slot space). + for &v in SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2.iter() { + assert!(v <= 8); + } + } + + #[test] + fn sig_coeff_flag_sig_ctx_transform_skip_eq_9_40() { + // Eq. 9-40: luma 42, chroma 16. + assert_eq!(sig_coeff_flag_sig_ctx_transform_skip(false), 42); + assert_eq!(sig_coeff_flag_sig_ctx_transform_skip(true), 16); + } + + #[test] + fn sig_coeff_flag_log2_2_dc_position_eq_9_41() { + // Eq. 9-41 at (0, 0) ⇒ ctxIdxMap[0] = 0 (the table's first + // entry). + assert_eq!(sig_coeff_flag_sig_ctx_log2_2(0, 0), 0); + } + + #[test] + fn sig_coeff_flag_log2_2_sweep_matches_table_9_50_indexing() { + // Verify the row-major (yC, xC) indexing pattern reads back + // Table 9-50 verbatim across the full 4×4 scan space. + for y in 0..4u32 { + for x in 0..4u32 { + let expected = + SIG_COEFF_FLAG_CTX_IDX_MAP_LOG2_TRAFO_SIZE_2[((y << 2) + x) as usize] as u32; + assert_eq!(sig_coeff_flag_sig_ctx_log2_2(x, y), expected); + } + } + } + + #[test] + fn sig_coeff_flag_log2_2_indexing_masks_oversized_input() { + // Defensive: oversized coordinates wrap to 0..=3 via & 3. + // (xC, yC) = (4, 0) wraps to (0, 0) ⇒ ctxIdxMap[0] = 0. + assert_eq!(sig_coeff_flag_sig_ctx_log2_2(4, 0), 0); + // (5, 1) wraps to (1, 1) ⇒ ctxIdxMap[5] = 3. + assert_eq!(sig_coeff_flag_sig_ctx_log2_2(5, 1), 3); + } + + #[test] + fn sig_coeff_flag_general_eq_9_45_prev_csbf_zero_luma_8x8() { + // log2 = 3, luma, (xS, yS) = (0, 0), prevCsbf = 0. + // Eq. 9-45 at (xP, yP): + // (0, 0): xP + yP == 0 → sigCtx = 2. + // (1, 0): xP + yP < 3 → sigCtx = 1. + // (2, 2): xP + yP == 4 ≥ 3 → sigCtx = 0. + // Then no eq.-9-49 luma bump (xS + yS == 0). Eq. 9-50 with + // scan_idx = 0 ⇒ += 9. + // (0, 0, 0, 0): 2 + 9 = 11. + // (1, 0, 0, 0): 1 + 9 = 10. + // (2, 2, 0, 0): 0 + 9 = 9. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 3, 0, 0, 0, 0, 0, 0, 0), + 11 + ); + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 3, 1, 0, 0, 0, 0, 0, 0), + 10 + ); + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 3, 2, 2, 0, 0, 0, 0, 0), + 9 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_50_scan_idx_branch_8x8_luma() { + // log2 = 3, luma, scan_idx = 1 (horizontal) ⇒ += 15 instead + // of 9. (xP, yP) = (1, 0), prevCsbf = 0 ⇒ sigCtx = 1 + 15 = 16. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 3, 1, 0, 0, 0, 0, 0, 1), + 16 + ); + // scan_idx = 2 (vertical) ⇒ += 15 (the else branch covers + // every non-zero scan_idx). + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 3, 1, 0, 0, 0, 0, 0, 2), + 16 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_51_large_luma_size() { + // log2 = 4 (16×16), luma, (xP, yP) = (0, 0), prevCsbf = 0, + // (xS, yS) = (0, 0). sigCtx = 2 + 21 = 23 (eq. 9-51 applies + // for log2 ≠ 3, scan_idx irrelevant). + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 0, 0, 0, 0, 0, 0), + 23 + ); + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 5, 0, 0, 0, 0, 0, 0, 0), + 23 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_49_luma_subblock_offset_bump() { + // log2 = 4, luma, (xS, yS) = (1, 0) ⇒ eq.-9-49 adds 3. + // (xP, yP) = (0, 0), prevCsbf = 0 ⇒ sigCtx = 2 + 3 + 21 = 26. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 4, 0, 1, 0, 0, 0, 0), + 26 + ); + // (xS, yS) = (0, 0) leaves the +3 off ⇒ sigCtx = 2 + 21 = 23. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 0, 0, 0, 0, 0, 0), + 23 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_46_prev_csbf_one() { + // log2 = 4, luma, right_csbf = 1 (gives prevCsbf bit 0 = 1), + // below_csbf = 0 → prevCsbf = 1. Eq. 9-46: + // yP == 0 → sigCtx = 2. + // yP == 1 → sigCtx = 1. + // yP >= 2 → sigCtx = 0. + // (xS, yS) = (0, 0) keeps eq.-9-49 off; eq. 9-51 adds 21. + // (xP, yP) = (0, 0): 2 + 21 = 23. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 0, 0, 0, 1, 0, 0), + 23 + ); + // (xP, yP) = (0, 1) ⇒ 1 + 21 = 22. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 1, 0, 0, 1, 0, 0), + 22 + ); + // (xP, yP) = (0, 2) ⇒ 0 + 21 = 21. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 2, 0, 0, 1, 0, 0), + 21 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_47_prev_csbf_two() { + // log2 = 4, luma, below_csbf = 1 → prevCsbf = 2. + // Eq. 9-47: + // xP == 0 → sigCtx = 2. + // xP == 1 → sigCtx = 1. + // xP >= 2 → sigCtx = 0. + // Add eq.-9-51 luma tail: + 21. + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 0, 0, 0, 0, 0, 1, 0), + 23 + ); + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 1, 0, 0, 0, 0, 1, 0), + 22 + ); + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, 2, 0, 0, 0, 0, 1, 0), + 21 + ); + } + + #[test] + fn sig_coeff_flag_general_eq_9_48_prev_csbf_three() { + // log2 = 4, luma, right_csbf = 1 + below_csbf = 1 → prevCsbf + // = 3. Eq. 9-48: sigCtx = 2 (position-independent). + 21 + // luma tail. (xP, yP) sweep all stay at 23. + for xp in 0..4 { + for yp in 0..4 { + assert_eq!( + sig_coeff_flag_sig_ctx_general(false, 4, xp, yp, 0, 0, 1, 1, 0), + 23 + ); + } + } + } + + #[test] + fn sig_coeff_flag_general_edge_gates_neighbour_inputs() { + // log2 = 3 (8×8) ⇒ max sub-block index 1. (xS, yS) = (1, 0): + // xS is at the right edge (1 == 1) ⇒ eq.-9-43 gate suppresses + // right_csbf. yS is not at the bottom edge ⇒ eq.-9-44 admits + // below_csbf. So passing right_csbf = 1 with (xS, yS) = (1, 0) + // has the same effect as passing right_csbf = 0. + let with_right = sig_coeff_flag_sig_ctx_general(false, 3, 4, 0, 1, 0, 1, 0, 0); + let without_right = sig_coeff_flag_sig_ctx_general(false, 3, 4, 0, 1, 0, 0, 0, 0); + assert_eq!(with_right, without_right); + + // (xS, yS) = (0, 1) ⇒ yS at bottom edge, below_csbf gated. + let with_below = sig_coeff_flag_sig_ctx_general(false, 3, 0, 4, 0, 1, 0, 1, 0); + let without_below = sig_coeff_flag_sig_ctx_general(false, 3, 0, 4, 0, 1, 0, 0, 0); + assert_eq!(with_below, without_below); + + // Sanity: (xS, yS) = (0, 0) on a 16×16 TB admits both + // neighbours (max sub-block index = 3, both 0 < 3). + let admits = sig_coeff_flag_sig_ctx_general(false, 4, 0, 0, 0, 0, 1, 1, 0); + // prevCsbf = 3 ⇒ eq.-9-48 sigCtx = 2; eq. 9-51 + 21 = 23. + assert_eq!(admits, 23); + } + + #[test] + fn sig_coeff_flag_general_chroma_eq_9_52_9_53_tail() { + // Chroma branch never bumps via eq. 9-49. + // log2 = 3, chroma, (xP, yP) = (0, 0), prevCsbf = 0, + // (xS, yS) = (1, 0) ⇒ eq. 9-49 NOT applied; eq. 9-52 += 9. + // sigCtx = 2 + 9 = 11. + assert_eq!( + sig_coeff_flag_sig_ctx_general(true, 3, 4, 0, 1, 0, 0, 0, 0), + 11 + ); + // log2 = 4 chroma ⇒ eq. 9-53 += 12 (scan_idx irrelevant). + // (0, 0) prevCsbf 0 ⇒ 2 + 12 = 14. + assert_eq!( + sig_coeff_flag_sig_ctx_general(true, 4, 0, 0, 0, 0, 0, 0, 0), + 14 + ); + // log2 = 5 chroma ⇒ same eq. 9-53 += 12. + assert_eq!( + sig_coeff_flag_sig_ctx_general(true, 5, 0, 0, 0, 0, 0, 0, 0), + 14 + ); + } + + #[test] + fn sig_coeff_flag_general_chroma_eq_9_52_scan_idx_irrelevant() { + // Eq. 9-52 (chroma, log2 == 3) does NOT branch on scan_idx; + // unlike eq. 9-50 the chroma 8×8 tail is a flat += 9. + let s0 = sig_coeff_flag_sig_ctx_general(true, 3, 0, 0, 0, 0, 0, 0, 0); + let s1 = sig_coeff_flag_sig_ctx_general(true, 3, 0, 0, 0, 0, 0, 0, 1); + let s2 = sig_coeff_flag_sig_ctx_general(true, 3, 0, 0, 0, 0, 0, 0, 2); + assert_eq!(s0, s1); + assert_eq!(s0, s2); + assert_eq!(s0, 11); + } + + #[test] + fn sig_coeff_flag_dc_eq_9_42_luma_log2_3() { + // Eq. 9-42: sigCtx = 0 — the third branch of the §9.3.4.2.5 + // cascade; the eq.-9-49..9-53 modifications belong to the + // fourth branch only, so neither log2TrafoSize nor scanIdx + // moves the DC context. + assert_eq!(sig_coeff_flag_sig_ctx_dc(false, 3, 0), 0); + assert_eq!(sig_coeff_flag_sig_ctx_dc(false, 3, 1), 0); + } + + #[test] + fn sig_coeff_flag_dc_eq_9_42_luma_large_size() { + // Eq. 9-42: sigCtx = 0 for every log2TrafoSize > 2 — the DC + // position shares one luma context (ctxInc 0). + assert_eq!(sig_coeff_flag_sig_ctx_dc(false, 4, 0), 0); + assert_eq!(sig_coeff_flag_sig_ctx_dc(false, 5, 0), 0); + assert_eq!(sig_coeff_flag_sig_ctx_dc(false, 4, 2), 0); + } + + #[test] + fn sig_coeff_flag_dc_eq_9_42_chroma() { + // Eq. 9-42: sigCtx = 0 for chroma too; eq. 9-55 then lands the + // DC position on ctxInc 27. + assert_eq!(sig_coeff_flag_sig_ctx_dc(true, 3, 0), 0); + assert_eq!(sig_coeff_flag_sig_ctx_dc(true, 4, 0), 0); + assert_eq!(sig_coeff_flag_sig_ctx_dc(true, 5, 0), 0); + } + + #[test] + fn sig_coeff_flag_ctx_inc_eq_9_54_luma_identity() { + // Eq. 9-54: ctxInc = sigCtx. + for sig in 0..=44 { + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(sig, false), sig); + } + } + + #[test] + fn sig_coeff_flag_ctx_inc_eq_9_55_chroma_offset() { + // Eq. 9-55: ctxInc = 27 + sigCtx. + for sig in 0..=20 { + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(sig, true), 27 + sig); + } + // Anchor values: transform-skip chroma (sigCtx = 16) ⇒ 43. + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(16, true), 43); + // Transform-skip luma (sigCtx = 42, eq. 9-54) ⇒ 42. + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(42, false), 42); + } + + #[test] + fn sig_coeff_flag_fl_shape_is_one_bin() { + // Table 9-43: sig_coeff_flag is FL with cMax = 1 (single + // context-coded bin per scan position). + assert_eq!(SIG_COEFF_FLAG_FL_CMAX, 1); + } + + #[test] + fn sig_coeff_flag_general_composes_with_ctx_inc_full_pipe_luma() { + // End-to-end: log2 = 4, luma, (xC, yC) = (4, 0) → (xS, yS) + // = (1, 0), (xP, yP) = (0, 0). prevCsbf 0 ⇒ sigCtx = 2; + // eq.-9-49 +3 ⇒ 5; eq.-9-51 +21 ⇒ 26. ctxInc = 26 (eq. 9-54). + let sig = sig_coeff_flag_sig_ctx_general(false, 4, 4, 0, 1, 0, 0, 0, 0); + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(sig, false), 26); + } + + #[test] + fn sig_coeff_flag_general_composes_with_ctx_inc_full_pipe_chroma() { + // log2 = 4, chroma, (xC, yC) = (0, 0) DC → must route via + // sig_coeff_flag_sig_ctx_dc (eq. 9-42: sigCtx = 0). + // ctxInc = 27 + 0 = 27 (eq. 9-55). + let sig_dc = sig_coeff_flag_sig_ctx_dc(true, 4, 0); + assert_eq!(sig_coeff_flag_ctx_inc_from_sig_ctx(sig_dc, true), 27); + } + + // ----------------------------------------------------------------- + // §9.3.4.2.8 palette_run_prefix — eq. 9-63 + Table 9-51 + // ----------------------------------------------------------------- + + #[test] + fn palette_run_prefix_eq_9_63_low_idx() { + // Eq. 9-63: palette_idx_idc < 1 ⇒ ctxInc = 0. + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(0), 0); + } + + #[test] + fn palette_run_prefix_eq_9_63_mid_idx() { + // Eq. 9-63: 1 <= palette_idx_idc < 3 ⇒ ctxInc = 1. + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(1), 1); + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(2), 1); + } + + #[test] + fn palette_run_prefix_eq_9_63_high_idx() { + // Eq. 9-63: palette_idx_idc >= 3 ⇒ ctxInc = 2. + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(3), 2); + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(4), 2); + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(100), 2); + assert_eq!(palette_run_prefix_ctx_inc_eq_9_63(u32::MAX), 2); + } + + #[test] + fn palette_run_prefix_ctx_inc_copy_above_zero_bin_zero_dispatches_eq_9_63() { + // copy_above == 0 and bin_idx == 0 ⇒ eq. 9-63 dispatch on + // palette_idx_idc. Verify the public entry point agrees with the + // standalone eq.-9-63 helper across the three eq.-9-63 bands. + for idc in [0u32, 1, 2, 3, 7] { + let expected = Some(palette_run_prefix_ctx_inc_eq_9_63(idc)); + assert_eq!( + palette_run_prefix_ctx_inc(0, false, idc), + expected, + "palette_idx_idc = {idc}" + ); + } + } + + #[test] + fn palette_run_prefix_ctx_inc_copy_above_zero_bins_one_through_four_table_9_51() { + // Table 9-51, copy_above_palette_indices_flag == 0: + // binIdx 1 → 3, binIdx 2 → 3, binIdx 3 → 4, binIdx 4 → 4. + // palette_idx_idc is irrelevant on this branch. + assert_eq!(palette_run_prefix_ctx_inc(1, false, 0), Some(3)); + assert_eq!(palette_run_prefix_ctx_inc(2, false, 0), Some(3)); + assert_eq!(palette_run_prefix_ctx_inc(3, false, 0), Some(4)); + assert_eq!(palette_run_prefix_ctx_inc(4, false, 0), Some(4)); + // palette_idx_idc swept high/low must produce identical results + // on this branch (Table 9-51 only consults binIdx when + // copy_above == 0 and binIdx > 0). + assert_eq!(palette_run_prefix_ctx_inc(1, false, 42), Some(3)); + assert_eq!(palette_run_prefix_ctx_inc(4, false, u32::MAX), Some(4)); + } + + #[test] + fn palette_run_prefix_ctx_inc_copy_above_one_table_9_51() { + // Table 9-51, copy_above_palette_indices_flag == 1: + // binIdx 0 → 5, binIdx 1 → 6, binIdx 2 → 6, + // binIdx 3 → 7, binIdx 4 → 7. + assert_eq!(palette_run_prefix_ctx_inc(0, true, 0), Some(5)); + assert_eq!(palette_run_prefix_ctx_inc(1, true, 0), Some(6)); + assert_eq!(palette_run_prefix_ctx_inc(2, true, 0), Some(6)); + assert_eq!(palette_run_prefix_ctx_inc(3, true, 0), Some(7)); + assert_eq!(palette_run_prefix_ctx_inc(4, true, 0), Some(7)); + // palette_idx_idc has no influence on this branch. + assert_eq!(palette_run_prefix_ctx_inc(0, true, 99), Some(5)); + assert_eq!(palette_run_prefix_ctx_inc(2, true, u32::MAX), Some(6)); + } + + #[test] + fn palette_run_prefix_ctx_inc_bypass_above_four() { + // Table 9-51 ">4" column: bypass-coded per Table 9-48. + for bin_idx in 5..=20 { + assert_eq!(palette_run_prefix_ctx_inc(bin_idx, false, 0), None); + assert_eq!(palette_run_prefix_ctx_inc(bin_idx, true, 0), None); + } + // First-bypass boundary anchor. + assert_eq!(PALETTE_RUN_PREFIX_FIRST_BYPASS_BIN_IDX, 5); + } + + #[test] + fn palette_run_prefix_ctx_idx_map_layout_matches_table_9_51() { + // Verify the static table layout matches Table 9-51 verbatim + // (modulo the eq.-9-63 dispatch sentinel at row 0, col 0). + assert_eq!( + PALETTE_RUN_PREFIX_CTX_IDX_MAP[0], + [PALETTE_RUN_PREFIX_EQ_9_63_DISPATCH, 3, 3, 4, 4] + ); + assert_eq!(PALETTE_RUN_PREFIX_CTX_IDX_MAP[1], [5, 6, 6, 7, 7]); + } + + #[test] + fn palette_run_prefix_ctx_inc_max_eight_distinct_contexts() { + // Table 9-40 declares 8 init values per init type (ctxIdx + // 0..7). Verify the eq.-9-63 dispatch + Table 9-51 lookup + // produce only values in 0..=7. + for copy_above in [false, true] { + for bin_idx in 0..PALETTE_RUN_PREFIX_FIRST_BYPASS_BIN_IDX { + for idc in 0..=8 { + let ctx = palette_run_prefix_ctx_inc(bin_idx, copy_above, idc) + .expect("all bin_idx < first-bypass should be context-coded"); + assert!( + ctx < 8, + "ctxInc = {ctx} >= 8 for bin_idx = {bin_idx}, \ + copy_above = {copy_above}, palette_idx_idc = {idc}" + ); + } + } + } + } + + #[test] + fn palette_run_prefix_tr_cmax_degenerate_zero() { + // PaletteMaxRunMinus1 == 0 ⇒ Floor(Log2(0)) is undefined; the + // helper returns 1 so the TR reader emits a single + // terminating bin. + assert_eq!(palette_run_prefix_tr_cmax(0), 1); + } + + #[test] + fn palette_run_prefix_tr_cmax_power_of_two_anchors() { + // Floor(Log2(x)) + 1 for x = 1, 2, 3, 4, 7, 8, 15, 16, 31, 32. + // x = 1 → Floor(Log2(1)) + 1 = 0 + 1 = 1. + assert_eq!(palette_run_prefix_tr_cmax(1), 1); + // x = 2 → 1 + 1 = 2. + assert_eq!(palette_run_prefix_tr_cmax(2), 2); + // x = 3 → 1 + 1 = 2. + assert_eq!(palette_run_prefix_tr_cmax(3), 2); + // x = 4 → 2 + 1 = 3. + assert_eq!(palette_run_prefix_tr_cmax(4), 3); + // x = 7 → 2 + 1 = 3. + assert_eq!(palette_run_prefix_tr_cmax(7), 3); + // x = 8 → 3 + 1 = 4. + assert_eq!(palette_run_prefix_tr_cmax(8), 4); + // x = 15 → 3 + 1 = 4. + assert_eq!(palette_run_prefix_tr_cmax(15), 4); + // x = 16 → 4 + 1 = 5. + assert_eq!(palette_run_prefix_tr_cmax(16), 5); + // x = 31 → 4 + 1 = 5. + assert_eq!(palette_run_prefix_tr_cmax(31), 5); + // x = 32 → 5 + 1 = 6. + assert_eq!(palette_run_prefix_tr_cmax(32), 6); + } + + #[test] + fn palette_run_prefix_tr_cmax_max_block_sizes() { + // Largest plausible PaletteMaxRunMinus1 values (a 64×64 CU + // with all pixels in a single run: 4095, plus the absolute + // u32::MAX defensive sweep). + // 4095 → Floor(Log2(4095)) + 1 = 11 + 1 = 12. + assert_eq!(palette_run_prefix_tr_cmax(4095), 12); + // 4096 → Floor(Log2(4096)) + 1 = 12 + 1 = 13. + assert_eq!(palette_run_prefix_tr_cmax(4096), 13); + // u32::MAX → 31 + 1 = 32. + assert_eq!(palette_run_prefix_tr_cmax(u32::MAX), 32); + } + + #[test] + fn palette_run_prefix_tr_cmax_monotone_nondecreasing() { + // PaletteMaxRunMinus1 → cMax is non-decreasing for x >= 1. + let mut prev = palette_run_prefix_tr_cmax(1); + for x in 2..=64 { + let cur = palette_run_prefix_tr_cmax(x); + assert!(cur >= prev, "cMax({x}) = {cur} < cMax({}) = {prev}", x - 1); + prev = cur; + } + } + + #[test] + fn palette_run_prefix_ctx_inc_eq_9_63_full_coverage_with_table_9_51_disjoint() { + // Sanity invariant: when copy_above == 0 and bin_idx == 0 the + // ctxInc is in {0, 1, 2} (eq. 9-63 range), and the + // Table 9-51 lookup row 0 entries (bin_idx 1..=4) are in + // {3, 4}. The two value sets are disjoint and together cover + // {0, 1, 2, 3, 4} — the spec's ctxIdx assignment for the + // copy_above == 0 case. + let bin0_ctxs: std::collections::BTreeSet = + (0..=4).map(palette_run_prefix_ctx_inc_eq_9_63).collect(); + assert_eq!(bin0_ctxs, [0u32, 1, 2].into_iter().collect()); + let tail_ctxs: std::collections::BTreeSet = (1 + ..PALETTE_RUN_PREFIX_FIRST_BYPASS_BIN_IDX) + .map(|bi| palette_run_prefix_ctx_inc(bi, false, 0).unwrap()) + .collect(); + assert_eq!(tail_ctxs, [3u32, 4].into_iter().collect()); + // No overlap. + assert!(bin0_ctxs.is_disjoint(&tail_ctxs)); + } + + // ----------------------------------------------------------------- + // §9.3.3.11 coeff_abs_level_remaining — pure-function derivations + // ----------------------------------------------------------------- + + #[test] + fn coeff_abs_level_remaining_c_rice_param_eq_9_24_initial_state() { + // First invocation in a sub-block: cLastAbsLevel = 0, + // cLastRiceParam = 0 ⇒ threshold = 3 << 0 = 3; 0 > 3 is false + // ⇒ no bump ⇒ cRiceParam = 0. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(0, 0), 0); + } + + #[test] + fn coeff_abs_level_remaining_c_rice_param_eq_9_24_no_bump_at_threshold() { + // The bump condition is strictly greater (>), not >=. + // r = 0, threshold = 3: level 3 ⇒ no bump. + // r = 1, threshold = 6: level 6 ⇒ no bump. + // r = 2, threshold = 12: level 12 ⇒ no bump. + // r = 3, threshold = 24: level 24 ⇒ no bump. + // r = 4, threshold = 48: level 48 ⇒ no bump (already at cap). + for r in 0..=4u32 { + let thresh = 3u32 << r; + assert_eq!( + coeff_abs_level_remaining_c_rice_param_eq_9_24(thresh, r), + r, + "boundary at threshold for r = {r}" + ); + } + } + + #[test] + fn coeff_abs_level_remaining_c_rice_param_eq_9_24_bumps_one_above_threshold() { + // r = 0, threshold = 3, level = 4 ⇒ bump ⇒ 1. + // r = 1, threshold = 6, level = 7 ⇒ bump ⇒ 2. + // r = 2, threshold = 12, level = 13 ⇒ bump ⇒ 3. + // r = 3, threshold = 24, level = 25 ⇒ bump ⇒ 4. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(4, 0), 1); + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(7, 1), 2); + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(13, 2), 3); + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(25, 3), 4); + } + + #[test] + fn coeff_abs_level_remaining_c_rice_param_eq_9_24_saturates_at_four() { + // r = 4 already at cap; even a level vastly above threshold + // must stay clamped at 4. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(49, 4), 4); + assert_eq!( + coeff_abs_level_remaining_c_rice_param_eq_9_24(u32::MAX, 4), + 4 + ); + // r = 3 bumped + clamped ⇒ 4. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(1_000, 3), 4); + // r = 4 with no bump still 4. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(0, 4), 4); + } + + #[test] + fn coeff_abs_level_remaining_c_rice_param_eq_9_24_monotone_in_level() { + // Holding r fixed, the bump probability is non-decreasing in + // cLastAbsLevel: once we pass the threshold, every larger + // level also triggers (until we hit r = 4 saturation). + for r in 0..=3u32 { + let thresh = 3u32 << r; + // Just below threshold: no bump. + if thresh > 0 { + assert_eq!( + coeff_abs_level_remaining_c_rice_param_eq_9_24(thresh - 1, r), + r + ); + } + // At threshold: no bump. + assert_eq!(coeff_abs_level_remaining_c_rice_param_eq_9_24(thresh, r), r); + // Just above: bump. + assert_eq!( + coeff_abs_level_remaining_c_rice_param_eq_9_24(thresh + 1, r), + r + 1 + ); + // Far above: still r + 1 (no double-bump in eq. 9-24). + assert_eq!( + coeff_abs_level_remaining_c_rice_param_eq_9_24(u32::MAX / 2, r), + r + 1 + ); + } + } + + #[test] + fn coeff_abs_level_remaining_c_max_eq_9_26_table() { + // Eq. 9-26 anchors for cRiceParam ∈ {0..=4}. + assert_eq!(coeff_abs_level_remaining_c_max_eq_9_26(0), 4); + assert_eq!(coeff_abs_level_remaining_c_max_eq_9_26(1), 8); + assert_eq!(coeff_abs_level_remaining_c_max_eq_9_26(2), 16); + assert_eq!(coeff_abs_level_remaining_c_max_eq_9_26(3), 32); + assert_eq!(coeff_abs_level_remaining_c_max_eq_9_26(4), 64); + } + + #[test] + fn coeff_abs_level_remaining_tr_prefix_escape_len_is_four() { + // §9.3.3.2: TR(cMax, cRiceParam) prefix length is + // cMax / (1 << cRiceParam) = (4 << r) / (1 << r) = 4 — invariant + // across cRiceParam. + assert_eq!(COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN, 4); + for r in 0..=4u32 { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(r); + let len = c_max / (1u32 << r); + assert_eq!( + len, COEFF_ABS_LEVEL_REMAINING_TR_PREFIX_ESCAPE_LEN, + "TR prefix length mismatch at r = {r}" + ); + } + } + + #[test] + fn coeff_abs_level_remaining_prefix_val_eq_9_27_clamps_at_c_max() { + // Below cMax: prefixVal = level. + // At or above cMax: prefixVal = cMax (escape). + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(0); // 4 + assert_eq!(coeff_abs_level_remaining_prefix_val_eq_9_27(0, c_max), 0); + assert_eq!(coeff_abs_level_remaining_prefix_val_eq_9_27(3, c_max), 3); + assert_eq!(coeff_abs_level_remaining_prefix_val_eq_9_27(4, c_max), 4); + assert_eq!(coeff_abs_level_remaining_prefix_val_eq_9_27(5, c_max), 4); + assert_eq!( + coeff_abs_level_remaining_prefix_val_eq_9_27(u32::MAX, c_max), + c_max + ); + } + + #[test] + fn coeff_abs_level_remaining_suffix_val_eq_9_28_subtracts_c_max() { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(1); // 8 + // Below cMax: clamp at 0 (suffix is absent; caller checks the + // prefix-escape flag before consuming it). + assert_eq!(coeff_abs_level_remaining_suffix_val_eq_9_28(0, c_max), 0); + assert_eq!(coeff_abs_level_remaining_suffix_val_eq_9_28(7, c_max), 0); + // At cMax: suffix = 0 (escape boundary). + assert_eq!(coeff_abs_level_remaining_suffix_val_eq_9_28(8, c_max), 0); + // Above cMax: linear in level. + assert_eq!(coeff_abs_level_remaining_suffix_val_eq_9_28(9, c_max), 1); + assert_eq!(coeff_abs_level_remaining_suffix_val_eq_9_28(100, c_max), 92); + } + + #[test] + fn coeff_abs_level_remaining_prefix_plus_suffix_recomposes_level() { + // For any level and any cRiceParam ∈ {0..=4}: level == + // prefixVal when level < cMax + // cMax + suffixVal when level >= cMax + // Anchors a round-trip invariant the binarization+decode pipe + // must preserve. + for r in 0..=4u32 { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(r); + for &level in &[0u32, 1, 3, 4, 7, 8, 15, 16, 63, 64, 65, 100, 4096] { + let prefix = coeff_abs_level_remaining_prefix_val_eq_9_27(level, c_max); + let suffix = coeff_abs_level_remaining_suffix_val_eq_9_28(level, c_max); + let recomposed = if level < c_max { + prefix + } else { + c_max + suffix + }; + assert_eq!( + recomposed, level, + "round-trip failed at r = {r}, level = {level}" + ); + } + } + } + + // ----------------------------------------------------------------- + // §9.3.3.11 coeff_abs_level_remaining — bin-source round-trips + // + // The §9.3.4.3.4 bypass arithmetic decoder does not map stream + // bits to bins 1-for-1 (the offset accumulator gates `bin == 1` + // by a 510 threshold), so end-to-end engine tests can't trivially + // synthesise a target bin sequence. Instead we drive the + // [`decode_coeff_abs_level_remaining_with`] entry point with a + // flat bin queue — the algorithm logic is identical and the + // engine wrapper is a one-line trampoline. + // ----------------------------------------------------------------- + + /// Helper: a FIFO bin source for + /// [`decode_coeff_abs_level_remaining_with`]. + fn bin_queue(bins: &[u8]) -> impl FnMut() -> Result + '_ { + let mut idx = 0usize; + move || { + let b = bins.get(idx).copied().ok_or(CabacError::EndOfBuffer)?; + idx += 1; + Ok(b) + } + } + + #[test] + fn decode_coeff_abs_level_remaining_zero_level_r0() { + // Smallest case: cRiceParam = 0, level = 0. TR prefix + // terminates at the first bin (0). No TR-suffix (r = 0) and + // no escape. Output = 0. + let bins = [0u8]; + assert_eq!( + decode_coeff_abs_level_remaining_with(0, bin_queue(&bins)).unwrap(), + 0 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_short_prefix_r0() { + // cRiceParam = 0, level = 3. TR prefix: 1, 1, 1, 0 + // (three 1s then terminator). No TR-suffix bits. Output = 3. + let bins = [1u8, 1, 1, 0]; + assert_eq!( + decode_coeff_abs_level_remaining_with(0, bin_queue(&bins)).unwrap(), + 3 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_short_prefix_r1() { + // cRiceParam = 1: TR prefix length capped at 4; each prefix + // step contributes (1 << r) = 2 to the value, plus a 1-bit + // TR-suffix carrying the low bit. + // + // level = 5 = (2 << 1) | 1 → prefix_len = 2, tr_suffix = 1. + // Bins: 1, 1, 0 (prefix) + 1 (TR-suffix). + let bins = [1u8, 1, 0, 1]; + assert_eq!( + decode_coeff_abs_level_remaining_with(1, bin_queue(&bins)).unwrap(), + 5 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_short_prefix_r2() { + // cRiceParam = 2: each prefix step contributes 4, TR-suffix + // is 2 bits. level = 9 = (2 << 2) | 1 → prefix_len = 2, + // tr_suffix = 1 (binary 01). + let bins = [1u8, 1, 0, /* TR-suffix high */ 0, /* low */ 1]; + assert_eq!( + decode_coeff_abs_level_remaining_with(2, bin_queue(&bins)).unwrap(), + 9 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_escape_path_r0() { + // cRiceParam = 0, level = 4 (== cMax). TR prefix = all 4 ones + // (escape). EGk(k = 1) suffix for suffixVal = 0: + // §9.3.3.3 eq. 9-13 — the EGk unary prefix is a run of `1` + // bins terminated by a `0`. suffixVal = 0 ⇒ prefix is the bare + // terminating `0` (prefix_ones = 0), suffix bits = 0 + 1 = 1, + // payload = 0. value = ((1 << 0) − 1) << 1 + 0 = 0. + // Decoded level = cMax + 0 = 4. + let bins = [ + 1u8, 1, 1, 1, /* EGk prefix terminator */ 0, /* suffix bit */ 0, + ]; + assert_eq!( + decode_coeff_abs_level_remaining_with(0, bin_queue(&bins)).unwrap(), + 4 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_escape_path_with_suffix_payload_r0() { + // cRiceParam = 0, level = 7. cMax = 4. suffixVal = 3. + // EGk(k = 1) of 3: prefix_ones = 1 (a `1` then the terminating + // `0`), suffix bits = 1 + 1 = 2, payload = 01 ⇒ value = + // ((1 << 1) − 1) << 1 + 1 = 3. Decoded level = 4 + 3 = 7. + let bins = [ + 1u8, 1, 1, 1, // TR escape prefix + 1, 0, // EGk prefix: one `1` bin then the terminating `0` + 0, 1, // suffix bits MSB-first + ]; + assert_eq!( + decode_coeff_abs_level_remaining_with(0, bin_queue(&bins)).unwrap(), + 7 + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_escape_saturates_instead_of_overflowing() { + // Fuzz regression (r282 `decode_residual`): a non-conformant + // bypass-bin stream can drive the EGk escape to its maximal + // shape — 4 TR escape ones, then 32 leading prefix ones (the + // loop cap), then 32 all-ones suffix bits — whose composed value + // exceeds u32. The decode must saturate, not overflow. + // §7.4.9.11 conformance (eqs. 7-27 .. 7-30) keeps every legal + // stream far below the saturation point. + let mut bins = vec![1u8, 1, 1, 1]; // TR escape prefix + bins.extend([1u8; 32]); // EGk prefix ones (loop cap) + bins.extend([1u8; 32]); // suffix payload + assert_eq!( + decode_coeff_abs_level_remaining_with(0, bin_queue(&bins)).unwrap(), + u32::MAX + ); + } + + #[test] + fn decode_coeff_abs_level_remaining_round_trips_tr_path_r0_thru_r4() { + // For each (cRiceParam, level) in the TR-only range + // (0..cMax), synthesise the §9.3.3.11 bin sequence, + // run the decoder, and confirm the original level comes back. + for r in 0..=4u32 { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(r); + for level in 0..c_max { + let prefix_len = level >> r; + let tr_suffix = level & ((1u32 << r) - 1); + let mut bins: Vec = (0..prefix_len).map(|_| 1u8).collect(); + bins.push(0); // TR terminator + for i in (0..r).rev() { + bins.push(((tr_suffix >> i) & 1) as u8); + } + let got = decode_coeff_abs_level_remaining_with(r, bin_queue(&bins)).unwrap(); + assert_eq!(got, level, "round-trip r = {r}, level = {level}"); + } + } + } + + #[test] + fn decode_coeff_abs_level_remaining_round_trips_escape_path_anchors() { + // Escape-path anchors for cRiceParam ∈ {0..=4}: pick a few + // (suffix-value) anchors per r, synthesise the all-ones TR + // prefix + EGk(r + 1) suffix, decode, and confirm. + for r in 0..=4u32 { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(r); + let k = r + 1; + for &suffix_val in &[0u32, 1, 3, 5, 12] { + // Encode suffix_val as EGk(k). Find smallest `lz` + // such that base = ((1 << lz) − 1) << k <= suffix_val + // and base + ((1 << (lz + k)) − 1) >= suffix_val. + let mut lz = 0u32; + while { + let base = (((1u64 << lz) - 1) << k) as u32; + let suffix_bits_capacity: u64 = 1u64 << (lz + k); + let max_val = base as u64 + suffix_bits_capacity - 1; + !(suffix_val >= base && suffix_val as u64 <= max_val) + } { + lz += 1; + } + let base = (((1u64 << lz) - 1) << k) as u32; + let suffix_payload = suffix_val - base; + // Bins: all-ones TR prefix (4 ones) + the §9.3.3.3 EGk + // prefix `lz` ones + a terminating zero + (lz + k) suffix + // bits MSB-first. + let mut bins: Vec = std::iter::repeat_n(1u8, 4).collect(); + bins.extend(std::iter::repeat_n(1u8, lz as usize)); + bins.push(0); + for i in (0..lz + k).rev() { + bins.push(((suffix_payload >> i) & 1) as u8); + } + let got = decode_coeff_abs_level_remaining_with(r, bin_queue(&bins)).unwrap(); + assert_eq!( + got, + c_max + suffix_val, + "escape-path round-trip r = {r}, suffix_val = {suffix_val}" + ); + } + } + } + + #[test] + fn decode_coeff_abs_level_remaining_engine_wrapper_smoke() { + // End-to-end engine wrapper smoke: drive + // `decode_coeff_abs_level_remaining` with an all-zero stream + // and a stuck-MPS context state is unnecessary because the + // bypass path doesn't consult ContextModel. We just confirm + // the wrapper compiles, runs, and returns 0 on an all-zero + // bypass bin stream (which is the natural decode of the + // smallest-level case from the bin-source test above). + let buf = [0u8; 16]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(decode_coeff_abs_level_remaining(&mut eng, 0).unwrap(), 0); + } + + // ------------------------------------------------------------- + // coeff_sign_flag[ n ] — §7.3.8.11 / §7.4.9.11 / Table 9-43 / + // Table 9-48 + // ------------------------------------------------------------- + + #[test] + fn coeff_sign_flag_fl_shape_table_9_43() { + // Table 9-43: coeff_sign_flag[ ] is FL with cMax = 1; the + // §9.3.3.5 fixedLength derivation gives Ceil(Log2(2)) = 1. + assert_eq!(COEFF_SIGN_FLAG_FL_CMAX, 1); + assert_eq!(COEFF_SIGN_FLAG_FL_NBITS, 1); + // §9.3.3.5: fixedLength = Ceil(Log2(cMax + 1)). + // For cMax = 1: cMax + 1 = 2, Log2(2) = 1, Ceil = 1. + let n_plus_1 = COEFF_SIGN_FLAG_FL_CMAX + 1; + // Ceil(Log2(x)) for x >= 1 is `bit_width(x − 1)`, i.e. + // `u32::BITS − (x − 1).leading_zeros()` for x >= 2 and + // `0` for x == 1. + let derived = if n_plus_1 <= 1 { + 0 + } else { + u32::BITS - (n_plus_1 - 1).leading_zeros() + }; + assert_eq!(derived, COEFF_SIGN_FLAG_FL_NBITS); + } + + #[test] + fn signed_level_from_sign_flag_positive_branch() { + // §7.4.9.11: sign_flag == 0 ⇒ (1 − 2 * 0) = +1, so + // level * (+1) = +abs_level. + assert_eq!(signed_level_from_sign_flag(0, 0), 0); + assert_eq!(signed_level_from_sign_flag(1, 0), 1); + assert_eq!(signed_level_from_sign_flag(7, 0), 7); + assert_eq!(signed_level_from_sign_flag(127, 0), 127); + assert_eq!(signed_level_from_sign_flag(32_767, 0), 32_767); + } + + #[test] + fn signed_level_from_sign_flag_negative_branch() { + // §7.4.9.11: sign_flag == 1 ⇒ (1 − 2 * 1) = −1, so + // level * (−1) = −abs_level. + assert_eq!(signed_level_from_sign_flag(0, 1), 0); + assert_eq!(signed_level_from_sign_flag(1, 1), -1); + assert_eq!(signed_level_from_sign_flag(7, 1), -7); + assert_eq!(signed_level_from_sign_flag(127, 1), -127); + assert_eq!(signed_level_from_sign_flag(32_767, 1), -32_767); + } + + #[test] + fn signed_level_from_sign_flag_inverse_identity() { + // For every abs_level in a representative sweep: + // signed(abs, 1) == −signed(abs, 0). + // Confirms the (1 − 2 * sign_flag) factor is the only + // difference between the two branches. + for level in [0u32, 1, 2, 5, 17, 42, 255, 1_023, 65_535] { + let pos = signed_level_from_sign_flag(level, 0); + let neg = signed_level_from_sign_flag(level, 1); + assert_eq!(pos + neg, 0, "level = {level}"); + } + } + + #[test] + fn signed_level_from_sign_flag_high_bit_depth_range() { + // High-bit-depth profiles (Main 4:4:4 12 / 14, RExt 16-bit) can + // produce |level| up to CoeffMax = (1 << 15) − 1 = 32_767 for + // 16-bit coding under the §A.4.2 transform bit-depth bounds, + // and CoeffMin ≥ −(1 << 15) = −32_768. The helper must round- + // trip across that full range without saturation. + let max = (1i32 << 15) - 1; + let min = -(1i32 << 15); + assert_eq!(signed_level_from_sign_flag(max as u32, 0), max); + assert_eq!(signed_level_from_sign_flag(max as u32, 1), -max); + // Magnitude of CoeffMin = 32_768 → encode with sign_flag = 1. + assert_eq!( + signed_level_from_sign_flag((-min) as u32, 1), + min, + "CoeffMin recovers when |level| = 32_768" + ); + } + + #[test] + fn decode_coeff_sign_flag_reads_one_bypass_bin_zero() { + // §9.3.4.2 / Table 9-48: the element is fully bypass-coded + // (bin 0 = bypass; all subsequent bin indices are `na`). One + // §9.3.4.3.4 DecodeBypass invocation reproduces the wire bit. + // + // An all-zero NAL body, after §9.3.4.3.6 alignment, is + // decoded by the §9.3.4.3.4 bypass routine as a 0 bin per + // the `ivlOffset < ivlCurrRange` (= 256) test: doubling a + // zero offset and OR-ing in a zero stream bit yields 0, + // which is below the post-double range 512. + let buf = [0u8; 16]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + eng.align(); + assert_eq!(decode_coeff_sign_flag(&mut eng).unwrap(), 0); + } + + #[test] + fn decode_coeff_sign_flag_well_typed_output() { + // §9.3.4.3.4 bypass decode: `decode_bypass` always returns + // a value in `{0, 1}` regardless of stream contents, since + // the routine compares `ivl_offset` against `ivl_curr_range` + // and returns 0 or 1 only. Strict-bit recovery from the + // wire is exercised by the cabac-module bypass tests; this + // test confirms the wrapper threads through without altering + // the output range. + let mut buf = [0u8; 16]; + buf[1] = 0x40; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + eng.align(); + let bin = decode_coeff_sign_flag(&mut eng).unwrap(); + assert!(bin == 0 || bin == 1); + } + + #[test] + fn decode_coeff_sign_flag_matches_underlying_decode_bypass() { + // The wrapper is `engine.decode_bypass()` — these two paths + // must produce identical sequences when fed the same engine + // state. Confirm via two engines initialised from the same + // buffer: the first runs the wrapper N times; the second + // runs `decode_bypass` N times; the bin sequences agree. + let mut buf = [0u8; 16]; + buf[0] = 0x5a; + buf[1] = 0xa5; + buf[2] = 0x3c; + buf[3] = 0xc3; + + let mut eng_a = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut eng_b = CabacEngine::new(BitReader::new(&buf)).unwrap(); + eng_a.align(); + eng_b.align(); + for _ in 0..8 { + let via_wrapper = decode_coeff_sign_flag(&mut eng_a).unwrap(); + let via_direct = eng_b.decode_bypass().unwrap(); + assert_eq!(via_wrapper, via_direct); + } + } + + // ------------------------------------------------------------- + // cu_chroma_qp_offset_flag / cu_chroma_qp_offset_idx + // (§9.3.4.2.1 / Table 9-48, §7.4.9.10) + // ------------------------------------------------------------- + + #[test] + fn cu_chroma_qp_offset_flag_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for cu_chroma_qp_offset_flag: bin 0 ctxInc = 0, + // all later columns na. + assert_eq!(cu_chroma_qp_offset_flag_ctx_inc(), 0); + } + + #[test] + fn cu_chroma_qp_offset_flag_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 → one bin, Ceil(Log2(2)) = 1 + // per §9.3.3.5. + assert_eq!(CU_CHROMA_QP_OFFSET_FLAG_FL_CMAX, 1); + assert_eq!(CU_CHROMA_QP_OFFSET_FLAG_FL_NBITS, 1); + } + + #[test] + fn cu_chroma_qp_offset_idx_table_9_48_ctx_inc_is_zero_across_prefix() { + // Table 9-48 row for cu_chroma_qp_offset_idx: binIdx 0..=4 all + // ctxInc = 0 (the TR prefix never escapes its single context + // bank). + for bin in 0..=4u32 { + assert_eq!(cu_chroma_qp_offset_idx_ctx_inc(bin), 0, "binIdx = {bin}"); + } + } + + #[test] + fn cu_chroma_qp_offset_idx_tr_cmax_passthrough() { + // §9.3.3.10 cMax = chroma_qp_offset_list_len_minus1; the + // §7.4.3.3.1 u(3) field caps the input at 5. + for n in 0..=5u32 { + assert_eq!(cu_chroma_qp_offset_idx_tr_cmax(n), n); + } + } + + #[test] + fn cu_chroma_qp_offset_offset_indices_gating() { + // §7.4.9.10: flag = 0 ⇒ no list dereference (offset = 0). + let off0 = CuChromaQpOffset { flag: 0, idx: None }; + assert_eq!(off0.offset_indices(), None); + + // flag = 1, idx present ⇒ dereference at idx. + let off1 = CuChromaQpOffset { + flag: 1, + idx: Some(3), + }; + assert_eq!(off1.offset_indices(), Some(3)); + + // flag = 1, idx not signalled (cMax = 0 case) ⇒ inferred 0. + let off2 = CuChromaQpOffset { flag: 1, idx: None }; + assert_eq!(off2.offset_indices(), Some(0)); + } + + #[test] + fn cu_chroma_qp_offset_flag_zero_does_not_signal_idx() { + // All-zero stream + fresh MPS-only context: the FL flag + // decodes to valMps = 0, so the idx is not read and no + // context-state walk is required on the idx side. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_flag = fresh_mps_ctx(0); + let ctx_idx_pre = fresh_mps_ctx(0); + let mut ctx_idx = ctx_idx_pre; + let off = decode_cu_chroma_qp_offset(&mut eng, &mut ctx_flag, &mut ctx_idx, 5).unwrap(); + assert_eq!(off.flag, 0); + assert_eq!(off.idx, None); + assert_eq!(off.offset_indices(), None); + // §7.4.9.10 gate: the idx context was not touched (its state + // matches the pre-call snapshot exactly). + assert_eq!(ctx_idx, ctx_idx_pre); + } + + #[test] + fn cu_chroma_qp_offset_flag_one_and_zero_len_skips_idx_read() { + // Even when flag = 1, the idx is not signalled when + // chroma_qp_offset_list_len_minus1 == 0 (TR cMax = 0 emits + // zero bins). §7.4.9.10 then infers idx = 0. Engineer the + // flag = 1 path with a (valMps = 1) MPS-only context. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_flag = fresh_mps_ctx(1); + let ctx_idx_pre = fresh_mps_ctx(0); + let mut ctx_idx = ctx_idx_pre; + let off = decode_cu_chroma_qp_offset(&mut eng, &mut ctx_flag, &mut ctx_idx, 0).unwrap(); + assert_eq!(off.flag, 1); + assert_eq!(off.idx, None); + // §7.4.9.10: absent idx ⇒ inferred to 0 via offset_indices(). + assert_eq!(off.offset_indices(), Some(0)); + // The idx context is untouched: TR cMax = 0 reads zero bins. + assert_eq!(ctx_idx, ctx_idx_pre); + } + + #[test] + fn cu_chroma_qp_offset_idx_ctx_inc_default_is_zero_for_each_legal_bin() { + // The §7.4.3.3.1 PPS field caps the TR prefix at five bins + // (cMax = chroma_qp_offset_list_len_minus1 ≤ 5). Every legal + // bin index lives in the single Table 9-48 ctxInc = 0 slot. + for n in 0..=5u32 { + let c_max = cu_chroma_qp_offset_idx_tr_cmax(n); + for bin in 0..c_max { + assert_eq!( + cu_chroma_qp_offset_idx_ctx_inc(bin), + 0, + "cMax = {c_max}, binIdx = {bin}" + ); + } + } + } + + #[test] + fn signed_level_composition_residual_loop_anchors() { + // §7.4.9.11 final composition anchors. baseLevel ∈ {1, 2, 3} + // (1 = greater1==0 fast path; 2 = greater1==1 / greater2==0; + // 3 = greater1==1 && greater2==1 at lastGreater1ScanPos); + // coeff_abs_level_remaining[n] ∈ {0, 1, 5, 17}; sign ∈ {0, 1}. + // The full level is `(remaining + baseLevel) * (1 − 2 * sign)`. + let cases: &[(u32, u32, u8, i32)] = &[ + (0, 1, 0, 1), + (0, 1, 1, -1), + (0, 3, 0, 3), + (0, 3, 1, -3), + (1, 2, 0, 3), + (1, 2, 1, -3), + (5, 1, 0, 6), + (5, 1, 1, -6), + (17, 3, 0, 20), + (17, 3, 1, -20), + ]; + for &(remaining, base_level, sign_flag, expected) in cases { + let abs_level = remaining + base_level; + let got = signed_level_from_sign_flag(abs_level, sign_flag); + assert_eq!( + got, expected, + "remaining = {remaining}, baseLevel = {base_level}, sign = {sign_flag}" + ); + } + } + + // ----------------------------------------------------------------- + // cu_transquant_bypass_flag (§7.3.8.5 / §7.4.9.5) + // ----------------------------------------------------------------- + + #[test] + fn cu_transquant_bypass_flag_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for cu_transquant_bypass_flag: bin 0 ctxInc + // = 0; all later binIdx columns are na. + assert_eq!(cu_transquant_bypass_flag_ctx_inc(), 0); + } + + #[test] + fn cu_transquant_bypass_flag_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(CU_TRANSQUANT_BYPASS_FLAG_FL_CMAX, 1); + assert_eq!(CU_TRANSQUANT_BYPASS_FLAG_FL_NBITS, 1); + } + + #[test] + fn cu_transquant_bypass_flag_inferred_is_zero_per_7_4_9_5() { + // §7.4.9.5: when transquant_bypass_enabled_flag (PPS) is 0 + // the flag is not present and inferred to 0 — the normal + // scaling-and-transform path. + assert_eq!(cu_transquant_bypass_flag_inferred(), 0); + } + + #[test] + fn decode_cu_transquant_bypass_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the + // FL flag decodes to 0 (the §8.6 / §8.7 normal path stays). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_cu_transquant_bypass_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + } + + #[test] + fn decode_cu_transquant_bypass_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the + // FL flag decodes to 1 (the §7.4.9.5 / §8.6 / §8.7 bypass + // passthrough is selected for the current CU). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_cu_transquant_bypass_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + } + + #[test] + fn decode_cu_transquant_bypass_flag_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on + // the same engine each consume exactly one bin (Table 9-43 + // FL cMax = 1). The second call's outcome is independent of + // the first since the contexts are separate. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_cu_transquant_bypass_flag(&mut eng, &mut ctx_a).unwrap(); + let b = decode_cu_transquant_bypass_flag(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + // ----------------------------------------------------------------- + // rqt_root_cbf (§7.3.8.5 / §7.4.9.5) + // ----------------------------------------------------------------- + + #[test] + fn rqt_root_cbf_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for rqt_root_cbf: bin 0 ctxInc = 0; every + // later binIdx column is na (Table 9-43 FL cMax = 1 — only + // one bin is ever emitted). + assert_eq!(rqt_root_cbf_ctx_inc(), 0); + } + + #[test] + fn rqt_root_cbf_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(RQT_ROOT_CBF_FL_CMAX, 1); + assert_eq!(RQT_ROOT_CBF_FL_NBITS, 1); + } + + #[test] + fn rqt_root_cbf_inferred_is_one_per_7_4_9_5() { + // §7.4.9.5 (V8 / 2021 baseline): when rqt_root_cbf is not + // present (the §7.3.8.5 guard CuPredMode == MODE_INTRA || + // cu_skip_flag == 1 selects the not-present path), the value + // is inferred to 1 — the transform_tree() syntax structure is + // taken to be present. + assert_eq!(rqt_root_cbf_inferred(), 1); + } + + #[test] + fn decode_rqt_root_cbf_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the + // FL flag decodes to 0 (CU has no transform_tree per §7.4.9.5 + // — samples derive from prediction only). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_rqt_root_cbf(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + } + + #[test] + fn decode_rqt_root_cbf_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the + // FL flag decodes to 1 (the transform_tree() syntax structure + // follows the current coding-unit body per §7.4.9.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_rqt_root_cbf(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + } + + #[test] + fn decode_rqt_root_cbf_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on + // the same engine each consume exactly one bin (Table 9-43 + // FL cMax = 1). The second call's outcome is independent of + // the first since the contexts are separate. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_rqt_root_cbf(&mut eng, &mut ctx_a).unwrap(); + let b = decode_rqt_root_cbf(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + #[test] + fn rqt_root_cbf_inferred_distinguishes_from_transquant_bypass() { + // rqt_root_cbf (not present ⇒ inferred to 1, §7.4.9.5) vs. + // cu_transquant_bypass_flag (PPS gate off ⇒ inferred to 0, + // §7.4.9.5). The two flags share the same §7.4.9.5 reference + // but their not-present-inference branches in opposite + // directions; this anchor pins both values against any + // accidental cross-wiring. + assert_eq!(rqt_root_cbf_inferred(), 1); + assert_eq!(cu_transquant_bypass_flag_inferred(), 0); + } + + // ----------------------------------------------------------------- + // merge_flag (§7.3.8.6 / §7.4.9.6) + // ----------------------------------------------------------------- + + #[test] + fn merge_flag_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for merge_flag: bin 0 ctxInc = 0; every later + // binIdx column is na (Table 9-43 FL cMax = 1 — only one bin is + // ever emitted). + assert_eq!(merge_flag_ctx_inc(), 0); + } + + #[test] + fn merge_flag_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(MERGE_FLAG_FL_CMAX, 1); + assert_eq!(MERGE_FLAG_FL_NBITS, 1); + } + + #[test] + fn merge_flag_inferred_skip_is_one_per_7_4_9_6() { + // §7.4.9.6: when merge_flag is not present (the §7.3.8.6 + // cu_skip_flag == 1 path), and CuPredMode == MODE_SKIP, the + // value is inferred to 1. + assert_eq!(merge_flag_inferred(CuPredMode::Skip), 1); + } + + #[test] + fn merge_flag_inferred_non_skip_is_zero_per_7_4_9_6() { + // §7.4.9.6: otherwise (CuPredMode != MODE_SKIP) the not-present + // inference is 0. These modes are not reached via the §7.3.8.6 + // not-present path in practice, but the pure helper is total. + assert_eq!(merge_flag_inferred(CuPredMode::Inter), 0); + assert_eq!(merge_flag_inferred(CuPredMode::Intra), 0); + } + + #[test] + fn decode_merge_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the FL + // flag decodes to 0 (explicit-motion path — inter_pred_idc / + // ref_idx / mvp follow per §7.3.8.6). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_merge_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + } + + #[test] + fn decode_merge_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the FL + // flag decodes to 1 (merge path — merge_idx follows per + // §7.3.8.6). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_merge_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + } + + #[test] + fn decode_merge_flag_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on the + // same engine each consume exactly one bin (Table 9-43 FL + // cMax = 1). The second call's outcome is independent of the + // first since the contexts are separate. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_merge_flag(&mut eng, &mut ctx_a).unwrap(); + let b = decode_merge_flag(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + // ----------------------------------------------------------------- + // pred_mode_flag (§7.3.8.5 / §7.4.9.5) + // ----------------------------------------------------------------- + + #[test] + fn pred_mode_flag_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for pred_mode_flag: bin 0 ctxInc = 0; every + // later binIdx column is na (Table 9-43 FL cMax = 1 — only + // one bin is ever emitted). + assert_eq!(pred_mode_flag_ctx_inc(), 0); + } + + #[test] + fn pred_mode_flag_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(PRED_MODE_FLAG_FL_CMAX, 1); + assert_eq!(PRED_MODE_FLAG_FL_NBITS, 1); + } + + #[test] + fn cu_pred_mode_from_flag_maps_table_9_48_values() { + // §7.4.9.5: pred_mode_flag == 0 ⇒ MODE_INTER; + // pred_mode_flag == 1 ⇒ MODE_INTRA. The two-valued FL + // shape covers the full Table 9-48 binIdx 0 column. + assert_eq!(cu_pred_mode_from_flag(0), CuPredMode::Inter); + assert_eq!(cu_pred_mode_from_flag(1), CuPredMode::Intra); + } + + #[test] + fn pred_mode_flag_inferred_i_slice_is_intra() { + // §7.4.9.5: "If slice_type is equal to I, CuPredMode[ x ][ y ] + // is inferred to be equal to MODE_INTRA." cu_skip_flag is not + // coded on I slices (§7.3.8.5 `if( slice_type != I )` guard) + // and is itself inferred to 0; pin both `cu_skip_flag = 0` + // inputs to confirm the slice-type branch dominates. + assert_eq!( + pred_mode_flag_inferred_cu_pred_mode(true, 0), + CuPredMode::Intra + ); + } + + #[test] + fn pred_mode_flag_inferred_pb_skip_is_skip() { + // §7.4.9.5: "Otherwise (slice_type is equal to P or B), when + // cu_skip_flag[ x0 ][ y0 ] is equal to 1, CuPredMode[ x ][ y ] + // is inferred to be equal to MODE_SKIP." This is the only + // not-present path on P/B slices (the §7.3.8.5 guard reads + // the flag whenever cu_skip_flag == 0). + assert_eq!( + pred_mode_flag_inferred_cu_pred_mode(false, 1), + CuPredMode::Skip + ); + } + + #[test] + fn decode_pred_mode_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the + // FL flag decodes to 0 (MODE_INTER per §7.4.9.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_pred_mode_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + assert_eq!(cu_pred_mode_from_flag(flag), CuPredMode::Inter); + } + + #[test] + fn decode_pred_mode_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the + // FL flag decodes to 1 (MODE_INTRA per §7.4.9.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_pred_mode_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + assert_eq!(cu_pred_mode_from_flag(flag), CuPredMode::Intra); + } + + #[test] + fn decode_pred_mode_flag_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on + // the same engine each consume exactly one bin (Table 9-43 + // FL cMax = 1). The second call's outcome is independent of + // the first since the contexts are separate. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_pred_mode_flag(&mut eng, &mut ctx_a).unwrap(); + let b = decode_pred_mode_flag(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + #[test] + fn cu_pred_mode_variants_distinct() { + // §7.4.9.5 lists three reachable CuPredMode values: MODE_INTER + // (pred_mode_flag == 0), MODE_INTRA (pred_mode_flag == 1 OR + // I-slice not-present inference), MODE_SKIP (P/B not-present + // with cu_skip_flag == 1). Pin all three as distinct. + assert_ne!(CuPredMode::Inter, CuPredMode::Intra); + assert_ne!(CuPredMode::Inter, CuPredMode::Skip); + assert_ne!(CuPredMode::Intra, CuPredMode::Skip); + } + + // ----------------------------------------------------------------- + // prev_intra_luma_pred_flag (§7.3.8.5 / §7.4.9.2) + // ----------------------------------------------------------------- + + #[test] + fn prev_intra_luma_pred_flag_table_9_48_ctx_inc_is_zero() { + // Table 9-48 row for prev_intra_luma_pred_flag: bin 0 + // ctxInc = 0; every later binIdx column is na (Table 9-43 FL + // cMax = 1 — only one bin is ever emitted). + assert_eq!(prev_intra_luma_pred_flag_ctx_inc(), 0); + } + + #[test] + fn prev_intra_luma_pred_flag_fl_shape_table_9_43() { + // Table 9-43 FL row with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(PREV_INTRA_LUMA_PRED_FLAG_FL_CMAX, 1); + assert_eq!(PREV_INTRA_LUMA_PRED_FLAG_FL_NBITS, 1); + } + + #[test] + fn luma_intra_mode_source_from_flag_maps_table_9_48_values() { + // §7.4.9.2 / §7.3.8.5: prev_intra_luma_pred_flag == 1 ⇒ the + // §8.4.2 MPM-list source (mpm_idx follows); + // prev_intra_luma_pred_flag == 0 ⇒ the rem_intra_luma_pred_mode + // source. The two-valued FL shape covers the full Table 9-48 + // binIdx 0 column. + assert_eq!( + luma_intra_mode_source_from_flag(1), + LumaIntraModeSource::Mpm + ); + assert_eq!( + luma_intra_mode_source_from_flag(0), + LumaIntraModeSource::Remaining + ); + } + + #[test] + fn luma_intra_mode_source_variants_distinct() { + // §7.4.9.2 lists two reachable mode sources for an intra luma + // PB: the §8.4.2 MPM list (flag == 1) and the + // rem_intra_luma_pred_mode field (flag == 0). Pin them as + // distinct. + assert_ne!(LumaIntraModeSource::Mpm, LumaIntraModeSource::Remaining); + } + + #[test] + fn decode_prev_intra_luma_pred_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the + // FL flag decodes to 0 (the rem_intra_luma_pred_mode source + // per §7.4.9.2). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_prev_intra_luma_pred_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + assert_eq!( + luma_intra_mode_source_from_flag(flag), + LumaIntraModeSource::Remaining + ); + } + + #[test] + fn decode_prev_intra_luma_pred_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the + // FL flag decodes to 1 (the §8.4.2 MPM-list source per + // §7.4.9.2 — mpm_idx follows in §7.3.8.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_prev_intra_luma_pred_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + assert_eq!( + luma_intra_mode_source_from_flag(flag), + LumaIntraModeSource::Mpm + ); + } + + #[test] + fn decode_prev_intra_luma_pred_flag_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on + // the same engine each consume exactly one bin (Table 9-43 + // FL cMax = 1). The second call's outcome is independent of + // the first since the contexts are separate. The §7.3.8.5 + // intra-PB loop reads this element once per luma prediction + // block, so the exactly-one-bin invariant is the per-PB + // contract. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_prev_intra_luma_pred_flag(&mut eng, &mut ctx_a).unwrap(); + let b = decode_prev_intra_luma_pred_flag(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + // ------------------------------------------------------------- + // mpm_idx / rem_intra_luma_pred_mode (§7.3.8.5 / §7.4.9.2) + // Table 9-43 binarization + Table 9-48 (fully bypass-coded) + // ------------------------------------------------------------- + + #[test] + fn mpm_idx_tr_shape_table_9_43() { + // Table 9-43 row: TR with cMax = 2, cRiceParam = 0 — the + // three-value truncated-unary string set {0, 10, 11}. + assert_eq!(MPM_IDX_TR_CMAX, 2); + assert_eq!(MPM_IDX_TR_C_RICE_PARAM, 0); + } + + #[test] + fn rem_intra_luma_pred_mode_fl_shape_table_9_43() { + // Table 9-43 row: FL with cMax = 31 → §9.3.3.5 + // Ceil(Log2(32)) = 5 bins. + assert_eq!(REM_INTRA_LUMA_PRED_MODE_FL_CMAX, 31); + assert_eq!(REM_INTRA_LUMA_PRED_MODE_FL_NBITS, 5); + // Cross-check the §9.3.3.5 derivation against the constant. + let derived = 32u32.next_power_of_two().trailing_zeros(); + assert_eq!(derived, REM_INTRA_LUMA_PRED_MODE_FL_NBITS); + } + + #[test] + fn mpm_idx_decodes_value_zero_on_first_zero_bin() { + // §9.3.3.10 TR prefix, cRiceParam = 0: the first bypass bin is + // 0 ⇒ value 0 (no second bin read). An all-zero stream decodes + // a 0 bypass bin per the §9.3.4.3.4 `ivlOffset < ivlCurrRange` + // test, so mpm_idx = 0. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(decode_mpm_idx(&mut eng).unwrap(), 0); + } + + #[test] + fn mpm_idx_output_always_in_range() { + // Whatever the stream, the TR cMax = 2 binarization caps the + // decoded value at 2 — the §8.4.2 candModeList has exactly three + // entries, so mpm_idx ∈ {0, 1, 2}. + // First 9 bits seed ivlOffset (must be < 510 per §9.3.2.5); + // the 0xfe lead keeps a near-all-ones stream while staying + // valid (509). + let seeds: [[u8; 8]; 4] = [ + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], + [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66], + [0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01], + ]; + for buf in seeds { + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let v = decode_mpm_idx(&mut eng).unwrap(); + assert!(v <= 2, "mpm_idx out of range: {v} for {buf:?}"); + } + } + + #[test] + fn mpm_idx_consumes_at_most_two_bins() { + // The TR cMax = 2 prefix reads one bin (terminating 0) or two + // (a leading 1 then either 0 or the cMax escape). Drive two + // engines from the same buffer: one runs the wrapper once, the + // other replays the equivalent raw bypass sequence and must + // land on the same post-read engine offset. + let buf = [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66]; + let mut eng_a = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut eng_b = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let v = decode_mpm_idx(&mut eng_a).unwrap(); + // Replay: first bin always read; second read iff first was 1. + let b0 = eng_b.decode_bypass().unwrap(); + let bins_read = if b0 == 1 { + let _ = eng_b.decode_bypass().unwrap(); + 2 + } else { + 1 + }; + // value 0 ⇒ one bin (terminating 0); value 1 or 2 ⇒ two bins + // (a leading 1 then the second prefix bin). + let expected_bins = if v == 0 { 1 } else { 2 }; + assert_eq!(bins_read, expected_bins); + assert_eq!(eng_a.ivl_offset(), eng_b.ivl_offset()); + } + + #[test] + fn rem_intra_luma_pred_mode_reads_five_bypass_bins() { + // FL cMax = 31: the wrapper is exactly decode_bypass_bits(5). + // Drive two engines from the same buffer — the wrapper and a + // direct five-bin MSB-first accumulation must agree on both the + // returned value and the post-read engine offset. + let buf = [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66]; + let mut eng_a = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut eng_b = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let via_wrapper = decode_rem_intra_luma_pred_mode(&mut eng_a).unwrap(); + let mut via_direct: u32 = 0; + for _ in 0..5 { + via_direct = (via_direct << 1) | (eng_b.decode_bypass().unwrap() as u32); + } + assert_eq!(via_wrapper as u32, via_direct); + assert_eq!(eng_a.ivl_offset(), eng_b.ivl_offset()); + } + + #[test] + fn rem_intra_luma_pred_mode_output_always_in_range() { + // The five-bit FL string caps the decoded value at 31 — the + // §8.4.2 step-2 seed for IntraPredModeY before the candModeList + // increment pass. + // First 9 bits seed ivlOffset (must be < 510 per §9.3.2.5). + let seeds: [[u8; 8]; 4] = [ + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], + [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66], + [0x13, 0x57, 0x9b, 0xdf, 0x24, 0x68, 0xac, 0xe0], + ]; + for buf in seeds { + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let v = decode_rem_intra_luma_pred_mode(&mut eng).unwrap(); + assert!( + v <= 31, + "rem_intra_luma_pred_mode out of range: {v} for {buf:?}" + ); + } + } + + // ------------------------------------------------------------- + // intra_chroma_pred_mode (§7.3.8.5 / §7.4.9.5) + // §9.3.3.8 / Table 9-46 + Table 9-48 + §8.4.3 (Tables 8-2, 8-3) + // ------------------------------------------------------------- + + #[test] + fn intra_chroma_pred_mode_table_9_46_shape() { + // Table 9-46: the single-bin string `0` carries value 4; the + // `1`-prefixed strings carry a two-bit FL suffix for 0..=3. + assert_eq!(INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA, 4); + assert_eq!(INTRA_CHROMA_PRED_MODE_SUFFIX_FL_NBITS, 2); + } + + #[test] + fn intra_chroma_pred_mode_ctx_inc_table_9_48_anchor() { + // Table 9-48 row: bin 0 ctxInc = 0 (bins 1..2 are bypass and + // never routed through this function). + assert_eq!(intra_chroma_pred_mode_ctx_inc(0), 0); + } + + #[test] + fn decode_intra_chroma_pred_mode_zero_prefix_is_value_4() { + // A 0 prefix bin (fresh valMps = 0 context against the all-zero + // stream) terminates the Table 9-46 string immediately: value 4, + // no suffix bins read. Cross-check the bin count by replaying + // the raw decision on a second engine and comparing offsets. + let buf = [0u8; 8]; + let mut eng_a = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut eng_b = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(0); + let v = decode_intra_chroma_pred_mode(&mut eng_a, &mut ctx_a).unwrap(); + assert_eq!(v, INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA); + let _ = eng_b.decode_decision(&mut ctx_b).unwrap(); + assert_eq!(eng_a.ivl_offset(), eng_b.ivl_offset()); + } + + #[test] + fn decode_intra_chroma_pred_mode_one_prefix_reads_two_suffix_bins() { + // A 1 prefix bin (fresh valMps = 1 context) is followed by the + // two-bit MSB-first bypass suffix. Replay the raw sequence on a + // second engine: same value, same post-read offset. + let buf = [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66]; + let mut eng_a = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut eng_b = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(1); + let mut ctx_b = fresh_mps_ctx(1); + let v = decode_intra_chroma_pred_mode(&mut eng_a, &mut ctx_a).unwrap(); + let prefix = eng_b.decode_decision(&mut ctx_b).unwrap(); + let expected = if prefix == 0 { + INTRA_CHROMA_PRED_MODE_SAME_AS_LUMA + } else { + let hi = eng_b.decode_bypass().unwrap(); + let lo = eng_b.decode_bypass().unwrap(); + (hi << 1) | lo + }; + assert_eq!(v, expected); + assert_eq!(eng_a.ivl_offset(), eng_b.ivl_offset()); + } + + #[test] + fn decode_intra_chroma_pred_mode_output_always_in_table_9_46_domain() { + // Whatever the stream and context polarity, the Table 9-46 + // binarization only produces {0, 1, 2, 3, 4}. + // First 9 bits seed ivlOffset (must be < 510 per §9.3.2.5). + let seeds: [[u8; 8]; 4] = [ + [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00], + [0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff], + [0x5a, 0xa5, 0x3c, 0xc3, 0x0f, 0xf0, 0x99, 0x66], + [0x13, 0x57, 0x9b, 0xdf, 0x24, 0x68, 0xac, 0xe0], + ]; + for buf in seeds { + for mps in [0u8, 1u8] { + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(mps); + let v = decode_intra_chroma_pred_mode(&mut eng, &mut ctx).unwrap(); + assert!( + v <= 4, + "intra_chroma_pred_mode out of range: {v} for {buf:?} mps {mps}" + ); + } + } + } + + #[test] + fn intra_pred_mode_c_mode_idx_table_8_2_rows() { + // Table 8-2 rows 0..=3: base modes {0, 26, 10, 1}, substituting + // 34 exactly where the base mode collides with IntraPredModeY. + // Columns: Y ∈ {0, 26, 10, 1, X (other)}. + let columns = [0u8, 26, 10, 1, 7]; + let rows: [(u8, [u8; 5]); 4] = [ + (0, [34, 0, 0, 0, 0]), + (1, [26, 34, 26, 26, 26]), + (2, [10, 10, 34, 10, 10]), + (3, [1, 1, 1, 34, 1]), + ]; + for (icpm, expected) in rows { + for (y, want) in columns.iter().zip(expected.iter()) { + assert_eq!( + intra_pred_mode_c_mode_idx(icpm, *y), + *want, + "Table 8-2 row {icpm} column Y = {y}" + ); + } + } + } + + #[test] + fn intra_pred_mode_c_mode_idx_row_4_tracks_luma() { + // Table 8-2 row 4: modeIdx = IntraPredModeY for every column, + // including the four base-mode columns. + for y in [0u8, 1, 10, 26, 7, 34] { + assert_eq!(intra_pred_mode_c_mode_idx(4, y), y); + } + } + + #[test] + fn intra_pred_mode_c_chroma_422_map_table_8_3_anchors() { + // Table 8-3 spot anchors across both printed rows, plus the + // X <= 2 pass-through column. + assert_eq!(INTRA_PRED_MODE_C_CHROMA_422_MAP.len(), 35); + for x in 0u8..=2 { + assert_eq!(intra_pred_mode_c_chroma_422(x), x); + } + let anchors: [(u8, u8); 10] = [ + (3, 2), + (5, 2), + (6, 3), + (10, 10), + (17, 20), + (18, 21), + (26, 26), + (28, 27), + (31, 29), + (34, 31), + ]; + for (mode_idx, want) in anchors { + assert_eq!( + intra_pred_mode_c_chroma_422(mode_idx), + want, + "Table 8-3 modeIdx {mode_idx}" + ); + } + } + + #[test] + fn intra_pred_mode_c_chroma_422_map_is_monotonic_and_in_range() { + // The Table 8-3 row is non-decreasing in modeIdx and every + // output is itself a valid mode index (0..=34) — a structural + // cross-check on the transcription. + let map = INTRA_PRED_MODE_C_CHROMA_422_MAP; + for w in map.windows(2) { + assert!(w[0] <= w[1], "Table 8-3 row must be non-decreasing: {w:?}"); + } + assert!(map.iter().all(|&m| m <= 34)); + } + + #[test] + fn derive_intra_pred_mode_c_applies_table_8_3_only_for_422() { + // §8.4.3: ChromaArrayType == 2 routes modeIdx through Table 8-3; + // every other (non-zero) ChromaArrayType passes modeIdx through. + // icpm 4 with Y = 30: modeIdx = 30, Table 8-3 ⇒ 28. + assert_eq!(derive_intra_pred_mode_c(4, 30, true), 28); + assert_eq!(derive_intra_pred_mode_c(4, 30, false), 30); + // icpm 1 with Y = 26 collides ⇒ modeIdx = 34, Table 8-3 ⇒ 31. + assert_eq!(derive_intra_pred_mode_c(1, 26, true), 31); + assert_eq!(derive_intra_pred_mode_c(1, 26, false), 34); + // icpm 0 with Y = 7 ⇒ modeIdx = 0; X <= 2 passes through under + // Table 8-3, so both paths agree. + assert_eq!(derive_intra_pred_mode_c(0, 7, true), 0); + assert_eq!(derive_intra_pred_mode_c(0, 7, false), 0); + } + + // ------------------------------------------------------------- + // §8.4.2 — derivation process for luma intra prediction mode + // (candModeList construction + IntraPredModeY resolution) + // ------------------------------------------------------------- + + #[test] + fn intra_mode_table_8_1_name_constants() { + // Table 8-1: 0 = INTRA_PLANAR, 1 = INTRA_DC, 26 = INTRA_ANGULAR26, + // 34 = INTRA_ANGULAR34 (the max mode). + assert_eq!(INTRA_PLANAR, 0); + assert_eq!(INTRA_DC, 1); + assert_eq!(INTRA_ANGULAR26, 26); + assert_eq!(INTRA_PRED_MODE_MAX, 34); + } + + #[test] + fn cand_mode_list_equal_low_candidate_eqs_8_21_8_23() { + // candB == candA and candA < 2 ⇒ {PLANAR, DC, ANGULAR26}, for + // both the PLANAR (0) and DC (1) equal-candidate cases. + assert_eq!(intra_luma_cand_mode_list(0, 0), [0, 1, 26]); + assert_eq!(intra_luma_cand_mode_list(1, 1), [0, 1, 26]); + } + + #[test] + fn cand_mode_list_equal_angular_candidate_eqs_8_24_8_26() { + // candB == candA and candA >= 2 ⇒ the candidate plus its two + // neighbouring angular modes (mod-32 wrap into 2..=33). + // candA = 26: {26, 2 + (55 % 32) = 25, 2 + (25 % 32) = 27}. + assert_eq!(intra_luma_cand_mode_list(26, 26), [26, 25, 27]); + // candA = 2 (low angular edge): {2, 2 + (31 % 32) = 33, + // 2 + (1 % 32) = 3} — the −1 neighbour wraps to the top mode 33. + assert_eq!(intra_luma_cand_mode_list(2, 2), [2, 33, 3]); + // candA = 34 (top angular edge): {34, 2 + (63 % 32) = 2 + 31 = 33, + // 2 + (33 % 32) = 2 + 1 = 3} — the +1 neighbour wraps to mode 3. + assert_eq!(intra_luma_cand_mode_list(34, 34), [34, 33, 3]); + } + + #[test] + fn cand_mode_list_distinct_third_is_first_missing_default() { + // candA != candB ⇒ slots 0/1 = candA/candB (eqs. 8-27/8-28); + // slot 2 is the first of PLANAR, DC, ANGULAR26 not already present. + // Neither is PLANAR ⇒ slot 2 = PLANAR. + assert_eq!(intra_luma_cand_mode_list(1, 26), [1, 26, 0]); + // PLANAR present, DC absent ⇒ slot 2 = DC. + assert_eq!(intra_luma_cand_mode_list(0, 26), [0, 26, 1]); + // PLANAR and DC both present ⇒ slot 2 = ANGULAR26. + assert_eq!(intra_luma_cand_mode_list(0, 1), [0, 1, 26]); + assert_eq!(intra_luma_cand_mode_list(1, 0), [1, 0, 26]); + } + + #[test] + fn cand_mode_list_entries_are_valid_modes() { + // Structural invariant: every candModeList entry is a Table 8-1 + // mode (0..=34) across the full candidate-pair product. + for a in 0u8..=34 { + for b in 0u8..=34 { + let list = intra_luma_cand_mode_list(a, b); + for &m in &list { + assert!( + m <= INTRA_PRED_MODE_MAX, + "candModeList entry {m} out of range" + ); + } + } + } + } + + #[test] + fn derive_intra_pred_mode_y_mpm_indexes_cand_list() { + // step-4 Mpm path: IntraPredModeY = candModeList[ mpm_idx ]. + let list = [26u8, 25, 27]; + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Mpm, 0), + 26 + ); + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Mpm, 1), + 25 + ); + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Mpm, 2), + 27 + ); + } + + #[test] + fn derive_intra_pred_mode_y_remaining_low_modes() { + // step-4 Remaining path with candModeList = {0, 1, 26} (sorted). + // rem = 0 ⇒ 0>=0→1, 1>=1→2, 2>=26? no ⇒ 2. + let list = [0u8, 1, 26]; + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 0), + 2 + ); + // rem = 23 ⇒ 23>=0→24, 24>=1→25, 25>=26? no ⇒ 25. + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 23), + 25 + ); + // rem = 24 ⇒ 24>=0→25, 25>=1→26, 26>=26→27 ⇒ 27 (jumps over the + // ANGULAR26 candidate too). + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 24), + 27 + ); + } + + #[test] + fn derive_intra_pred_mode_y_remaining_sorts_cand_list() { + // step-4 sorts candModeList ascending before the increment pass: + // an unsorted {26, 25, 27} input sorts to {25, 26, 27}. + // rem = 24 ⇒ 24>=25? no ⇒ 24 (below all three candidates). + let list = [26u8, 25, 27]; + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 24), + 24 + ); + // rem = 25 ⇒ 25>=25→26, 26>=26→27, 27>=27→28 ⇒ 28. + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 25), + 28 + ); + } + + #[test] + fn derive_intra_pred_mode_y_remaining_bijective_over_full_range() { + // The Remaining path maps the 31 rem values 0..=30 onto a set of + // 31 distinct modes that excludes exactly the three candModeList + // modes — a bijection onto (0..=34) \ candModeList. + let list = [0u8, 1, 26]; // sorted, the equal-low-candidate list + let mut produced = std::collections::BTreeSet::new(); + for rem in 0u8..=31 { + let mode = derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, rem); + assert!(mode <= INTRA_PRED_MODE_MAX, "mode {mode} out of range"); + assert!( + produced.insert(mode), + "rem path produced duplicate mode {mode}" + ); + } + // 32 distinct outputs (rem 0..=31) — none equal to a candidate. + for &cand in &list { + assert!( + !produced.contains(&cand), + "rem path produced candidate mode {cand}" + ); + } + } + + #[test] + fn intra_pred_mode_y_end_to_end_remaining() { + // End-to-end §8.4.2: distinct neighbour candidates A = 10, B = 2 + // ⇒ candModeList {10, 2, 0} (slot 2 = PLANAR, neither slot is + // PLANAR), Remaining with rem = 0: + // sorted {0, 2, 10}; 0>=0→1, 1>=2? no, 1>=10? no ⇒ 1. + let list = intra_luma_cand_mode_list(10, 2); + assert_eq!(list, [10, 2, 0]); + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Remaining, 0), + 1 + ); + // Same list, Mpm path with mpm_idx = 0 ⇒ candModeList[0] = 10. + assert_eq!( + derive_intra_pred_mode_y(list, LumaIntraModeSource::Mpm, 0), + 10 + ); + } + + // ------------------------------------------------------------- + // §7.3.8.9 / §7.4.9.9 mvd_coding( ) — Table 9-43 / Table 9-48 + // ------------------------------------------------------------- + + #[test] + fn mvd_ctx_inc_single_context_each() { + // Table 9-48: both `greater` flags are context-coded with a + // single dedicated context (ctxInc = 0 at bin 0). + assert_eq!(abs_mvd_greater0_flag_ctx_inc(), 0); + assert_eq!(abs_mvd_greater1_flag_ctx_inc(), 0); + } + + #[test] + fn mvd_binarization_constants_match_table_9_43() { + // FL cMax = 1 for the two greater flags + the sign flag; EG1 + // for abs_mvd_minus2. + assert_eq!(ABS_MVD_GREATER_FLAG_FL_CMAX, 1); + assert_eq!(MVD_SIGN_FLAG_FL_CMAX, 1); + assert_eq!(ABS_MVD_MINUS2_EG_K, 1); + } + + #[test] + fn mvd_value_equation_7_73_inference_branches() { + // greater0 == 0 ⇒ lMvd == 0 (all other fields absent). + assert_eq!(mvd_component_value(0, None, None), 0); + // greater0 == 1, greater1 absent/0 (minus2 absent, inferred −1) + // ⇒ magnitude = (−1 + 2) = 1; sign absent ⇒ +1. + assert_eq!(mvd_component_value(1, None, Some(0)), 1); + // ... with sign_flag == 1 ⇒ −1. + assert_eq!(mvd_component_value(1, None, Some(1)), -1); + // greater0 == 1, greater1 == 1 ⇒ minus2 present. + // minus2 = 0 ⇒ magnitude 2; minus2 = 3 ⇒ magnitude 5. + assert_eq!(mvd_component_value(1, Some(0), Some(0)), 2); + assert_eq!(mvd_component_value(1, Some(0), Some(1)), -2); + assert_eq!(mvd_component_value(1, Some(3), Some(0)), 5); + assert_eq!(mvd_component_value(1, Some(3), Some(1)), -5); + // Sign defaults to positive when absent. + assert_eq!(mvd_component_value(1, Some(7), None), 9); + } + + #[test] + fn mvd_component_with_greater0_zero_short_circuits() { + // First context bin = 0 ⇒ no bypass bins consumed at all; every + // downstream field stays inferred-absent. + let mut bypass_called = false; + let c = decode_mvd_component_with( + || Ok(0u8), + || { + bypass_called = true; + Ok(0u8) + }, + ) + .unwrap(); + assert!(!bypass_called, "no bypass bin should be read"); + assert_eq!( + c, + MvdComponent { + greater0_flag: 0, + greater1_flag: None, + minus2: None, + sign_flag: None, + value: 0, + } + ); + } + + #[test] + fn mvd_component_with_magnitude_one() { + // greater0 = 1, greater1 = 0 ⇒ abs_mvd_minus2 absent, only the + // sign bit is bypass-read. Sign = 1 ⇒ lMvd = −1. + let ctx_bins = [1u8, 0]; // greater0, greater1 + let bypass_bins = [1u8]; // mvd_sign_flag + let c = decode_mvd_component_with(bin_queue(&ctx_bins), bin_queue(&bypass_bins)).unwrap(); + assert_eq!( + c, + MvdComponent { + greater0_flag: 1, + greater1_flag: Some(0), + minus2: None, + sign_flag: Some(1), + value: -1, + } + ); + } + + #[test] + fn mvd_component_with_eg1_escape() { + // greater0 = 1, greater1 = 1 ⇒ abs_mvd_minus2 is EG1-coded then + // the sign bit follows. §9.3.3.3 EG1 of value 0 is the bin string + // "0 0": the prefix is the bare terminating `0` (prefix_ones = 0), + // then prefix_ones + k = 0 + 1 = 1 suffix bin = `0` ⇒ value 0. + // So minus2 = 0 ⇒ magnitude = 2; sign = 0 ⇒ lMvd = +2. + let ctx_bins = [1u8, 1]; + let bypass_bins = [0u8, 0, 0]; // EG1 prefix '0', suffix '0', sign '0' + let c = decode_mvd_component_with(bin_queue(&ctx_bins), bin_queue(&bypass_bins)).unwrap(); + assert_eq!( + c, + MvdComponent { + greater0_flag: 1, + greater1_flag: Some(1), + minus2: Some(0), + sign_flag: Some(0), + value: 2, + } + ); + } + + #[test] + fn mvd_component_with_eg1_value_one_full() { + // greater0 = 1, greater1 = 1, abs_mvd_minus2 = 1 (§9.3.3.3 EG1 + // "0 1": prefix_ones = 0, suffix bits = prefix_ones + k = 1 = + // "1" ⇒ base 0 + suffix 1 = 1), then sign = 0. magnitude = + // minus2 + 2 = 3 ⇒ lMvd = +3. + let ctx_bins = [1u8, 1]; + let bypass_bins = [0u8, 1, 0]; // EG1(1)='0','1' ; sign '0' + let c = decode_mvd_component_with(bin_queue(&ctx_bins), bin_queue(&bypass_bins)).unwrap(); + assert_eq!(c.minus2, Some(1)); + assert_eq!(c.value, 3); + } + + #[test] + fn read_eg_k_with_eg1_battery() { + // §9.3.3.3 EG1 (k = 1) decode across a battery of bin strings, + // confirming the closure reader implements the do-while shared + // with the engine-driven `decode_eg_k`. The EGk unary prefix is a + // run of `1` bins terminated by a `0` (the §9.3.3.3 NOTE), then + // prefix_ones + k suffix bits: + // "0 s" prefix_ones=0 → suffix 1 bit + // "1 0 s1 s0" prefix_ones=1 → base 2, suffix 2 bits + let cases: &[(&[u8], u32)] = &[ + (&[0, 0], 0), // p0, suffix 0 ⇒ 0 + (&[0, 1], 1), // p0, suffix 1 ⇒ 1 + (&[1, 0, 0, 0], 2), // p1, base=2, suffix 0 ⇒ 2 + (&[1, 0, 0, 1], 3), // p1, base=2, suffix 1 ⇒ 3 + (&[1, 0, 1, 0], 4), // p1, base=2, suffix 2 ⇒ 4 + (&[1, 1, 0, 0, 0, 0], 6), // p2, base=6, suffix 0 ⇒ 6 + ]; + for (bins, expected) in cases { + assert_eq!( + read_eg_k_with(1, bin_queue(bins)).unwrap(), + *expected, + "bins {bins:?}" + ); + } + } + + #[test] + fn mvd_component_engine_greater0_zero() { + // All-zero stream: 9 init bits then the first DecodeDecision + // returns 0 for an MPS-state context ⇒ greater0 = 0, value 0. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut g0 = fresh_mps_ctx(0); + let mut g1 = fresh_mps_ctx(0); + let c = decode_mvd_component(&mut eng, &mut g0, &mut g1).unwrap(); + assert_eq!(c.greater0_flag, 0); + assert_eq!(c.value, 0); + assert_eq!(c.greater1_flag, None); + } + + // ----------------------------------------------------------------- + // split_cu_flag (§7.3.8.4 / §7.4.9.4) + // ----------------------------------------------------------------- + + #[test] + fn split_cu_flag_fl_shape_table_9_43() { + // Table 9-43 row: FL with cMax = 1 ⇒ one bin, §9.3.3.5 nBits + // = Ceil(Log2(cMax + 1)) = 1. + assert_eq!(SPLIT_CU_FLAG_FL_CMAX, 1); + assert_eq!(SPLIT_CU_FLAG_FL_NBITS, 1); + } + + #[test] + fn decode_split_cu_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the FL + // flag decodes to 0 (leaf coding unit — coding_unit() follows + // per §7.3.8.4). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_split_cu_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + } + + #[test] + fn decode_split_cu_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the FL + // flag decodes to 1 (split into four quarter-size children per + // §7.3.8.4). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_split_cu_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + } + + #[test] + fn decode_split_cu_flag_consumes_exactly_one_bin() { + // Two back-to-back calls against fresh MPS-only contexts on the + // same engine each consume exactly one bin (Table 9-43 FL + // cMax = 1); separate contexts make the outcomes independent. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx_a = fresh_mps_ctx(0); + let mut ctx_b = fresh_mps_ctx(1); + let a = decode_split_cu_flag(&mut eng, &mut ctx_a).unwrap(); + let b = decode_split_cu_flag(&mut eng, &mut ctx_b).unwrap(); + assert_eq!(a, 0); + assert_eq!(b, 1); + } + + // ----------------------------------------------------------------- + // cu_skip_flag (§7.3.8.5 / §7.4.9.5) + // ----------------------------------------------------------------- + + #[test] + fn cu_skip_flag_fl_shape_table_9_43() { + // Table 9-43 row: FL with cMax = 1 ⇒ one bin, §9.3.3.5 nBits = 1. + assert_eq!(CU_SKIP_FLAG_FL_CMAX, 1); + assert_eq!(CU_SKIP_FLAG_FL_NBITS, 1); + } + + #[test] + fn decode_cu_skip_flag_zero_path() { + // Empty bin stream + fresh MPS-only valMps = 0 context: the FL + // flag decodes to 0 (non-skip CU — pred_mode_flag / part_mode + // follow per §7.3.8.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let flag = decode_cu_skip_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 0); + } + + #[test] + fn decode_cu_skip_flag_one_path() { + // Empty bin stream + fresh MPS-only valMps = 1 context: the FL + // flag decodes to 1 (MODE_SKIP path per §7.4.9.5). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(1); + let flag = decode_cu_skip_flag(&mut eng, &mut ctx).unwrap(); + assert_eq!(flag, 1); + assert_eq!(cu_pred_mode_from_skip(false, flag), Some(CuPredMode::Skip)); + } + + #[test] + fn cu_pred_mode_from_skip_i_slice_is_intra() { + // §7.4.9.5: I slices infer cu_skip_flag = 0 and CuPredMode = + // MODE_INTRA without a pred_mode_flag read. The cu_skip_flag + // input is pinned 0 (its inferred value). + assert_eq!(cu_pred_mode_from_skip(true, 0), Some(CuPredMode::Intra)); + } + + #[test] + fn cu_pred_mode_from_skip_pb_skip_is_skip() { + // §7.4.9.5: a P / B CU with cu_skip_flag == 1 infers MODE_SKIP; + // pred_mode_flag is not present. + assert_eq!(cu_pred_mode_from_skip(false, 1), Some(CuPredMode::Skip)); + } + + #[test] + fn cu_pred_mode_from_skip_pb_non_skip_needs_pred_mode_flag() { + // §7.3.8.5 / §7.4.9.5: a P / B CU with cu_skip_flag == 0 still + // codes pred_mode_flag, so the mode is not yet determined — + // the helper returns None to signal that read is required. + assert_eq!(cu_pred_mode_from_skip(false, 0), None); + } + + // ------------------------------------------------------------- + // §7.3.8.3 SAO element decoders + // ------------------------------------------------------------- + + #[test] + fn sao_offset_abs_cmax_by_bit_depth() { + // §9.3.3.5: cMax = (1 << (Min(bitDepth, 10) − 5)) − 1. + assert_eq!(sao_offset_abs_tr_cmax(8), 7); // (1<<3)-1 + assert_eq!(sao_offset_abs_tr_cmax(10), 31); // (1<<5)-1 + assert_eq!(sao_offset_abs_tr_cmax(12), 31); // clamped at 10 + } + + #[test] + fn sao_type_idx_zero_when_first_bin_zero() { + // All-zero stream → bin 0 (context, MPS=0) decodes to 0 → + // SaoTypeIdx = 0 (not applied), no second bin consumed. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + assert_eq!(decode_sao_type_idx(&mut eng, &mut ctx).unwrap(), 0); + } + + #[test] + fn sao_band_position_reads_five_bypass_bits() { + // All-zero buffer → five bypass bins → 0. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(decode_sao_band_position(&mut eng).unwrap(), 0); + } + + #[test] + fn sao_eo_class_reads_two_bypass_bits() { + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let c = decode_sao_eo_class(&mut eng).unwrap(); + assert!(c <= 3); + } + + // ------------------------------------------------------------- + // §7.4.9.5 part_mode + // ------------------------------------------------------------- + + #[test] + fn part_mode_is_amp_classification() { + assert!(!PartMode::Part2Nx2N.is_amp()); + assert!(!PartMode::PartNxN.is_amp()); + assert!(PartMode::Part2NxnU.is_amp()); + assert!(PartMode::Part2NxnD.is_amp()); + assert!(PartMode::PartNLx2N.is_amp()); + assert!(PartMode::PartNRx2N.is_amp()); + } + + #[test] + fn part_mode_inferred_is_2nx2n() { + let r = part_mode_inferred(); + assert_eq!(r.part_mode, PartMode::Part2Nx2N); + assert!(!r.intra_split_flag); + } + + #[test] + fn part_mode_intra_nxn_sets_intra_split_flag() { + // Intra column: bin 0 == 0 → PART_NxN, IntraSplitFlag = 1. + // All-zero stream gives bin 0 == 0 with an MPS=0 context. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(0); + let mut c1 = fresh_mps_ctx(0); + let mut c2 = fresh_mps_ctx(0); + let r = decode_part_mode( + &mut eng, + &mut c0, + &mut c1, + &mut c2, + CuPredMode::Intra, + 4, + 3, + false, + ) + .unwrap(); + assert_eq!(r.part_mode, PartMode::PartNxN); + assert!(r.intra_split_flag); + } + + #[test] + fn part_mode_intra_2nx2n_when_bin0_one() { + // Intra column: bin 0 == 1 → PART_2Nx2N. MPS=1 all-zero stream + // decodes bin 0 == 1. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(1); + let mut c1 = fresh_mps_ctx(1); + let mut c2 = fresh_mps_ctx(1); + let r = decode_part_mode( + &mut eng, + &mut c0, + &mut c1, + &mut c2, + CuPredMode::Intra, + 4, + 3, + false, + ) + .unwrap(); + assert_eq!(r.part_mode, PartMode::Part2Nx2N); + assert!(!r.intra_split_flag); + } + + #[test] + fn part_mode_inter_2nx2n_when_bin0_one() { + // Inter, bin 0 == 1 → PART_2Nx2N (single bin). + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(1); + let mut c1 = fresh_mps_ctx(1); + let mut c2 = fresh_mps_ctx(1); + let r = decode_part_mode( + &mut eng, + &mut c0, + &mut c1, + &mut c2, + CuPredMode::Inter, + 5, + 3, + true, + ) + .unwrap(); + assert_eq!(r.part_mode, PartMode::Part2Nx2N); + } + + // ------------------------------------------------------------- + // merge_idx / ref_idx / mvp_flag / inter_pred_idc / pcm / + // end_of_slice_segment_flag + // ------------------------------------------------------------- + + #[test] + fn merge_idx_zero_when_max_cand_one() { + // MaxNumMergeCand == 1 → cMax == 0 → inferred 0, no bins read. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + assert_eq!(decode_merge_idx(&mut eng, &mut ctx, 1).unwrap(), 0); + } + + #[test] + fn merge_idx_zero_when_first_bin_zero() { + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + assert_eq!(decode_merge_idx(&mut eng, &mut ctx, 5).unwrap(), 0); + } + + #[test] + fn ref_idx_zero_when_active_minus1_zero() { + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(0); + let mut c1 = fresh_mps_ctx(0); + assert_eq!(decode_ref_idx(&mut eng, &mut c0, &mut c1, 0).unwrap(), 0); + } + + #[test] + fn ref_idx_zero_when_first_bin_zero() { + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(0); + let mut c1 = fresh_mps_ctx(0); + assert_eq!(decode_ref_idx(&mut eng, &mut c0, &mut c1, 3).unwrap(), 0); + } + + #[test] + fn inter_pred_idc_npb12_is_single_bin() { + // nPbW + nPbH == 12: single bin, "0" → PRED_L0. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(0); + let mut c1 = fresh_mps_ctx(0); + let r = decode_inter_pred_idc(&mut eng, &mut c0, &mut c1, 8, 4).unwrap(); + assert_eq!(r, InterPredIdc::PredL0); + } + + #[test] + fn inter_pred_idc_bi_when_bin0_one() { + // nPbW + nPbH != 12, bin 0 == 1 → PRED_BI. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut c0 = fresh_mps_ctx(1); + let mut c1 = fresh_mps_ctx(1); + let r = decode_inter_pred_idc(&mut eng, &mut c0, &mut c1, 16, 16).unwrap(); + assert_eq!(r, InterPredIdc::PredBi); + } + + #[test] + fn pcm_and_end_of_slice_use_terminate() { + // The terminate path on an all-zero buffer returns 0 (not the + // termination value); both share decode_terminate. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let pcm = decode_pcm_flag(&mut eng).unwrap(); + assert!(pcm <= 1); + let eos = decode_end_of_slice_segment_flag(&mut eng).unwrap(); + assert!(eos <= 1); + } + + #[test] + fn mvp_flag_single_bin() { + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_mps_ctx(0); + let v = decode_mvp_flag(&mut eng, &mut ctx).unwrap(); + assert!(v <= 1); + } +} diff --git a/vendor/oxideav-h265/src/bitreader.rs b/vendor/oxideav-h265/src/bitreader.rs new file mode 100644 index 0000000..a116ce4 --- /dev/null +++ b/vendor/oxideav-h265/src/bitreader.rs @@ -0,0 +1,300 @@ +//! MSB-first bit reader for H.265 syntax-element parsing. +//! +//! H.265 syntax elements are read most-significant-bit-first from the +//! RBSP byte stream (see ITU-T Rec. H.265 §7.2 — the `read_bits(n)` +//! function described there returns the next `n` bits as an unsigned +//! integer with the MSB written first). This module provides the +//! minimum surface needed for §7.3.2.1 (VPS) and §7.3.3 +//! (profile_tier_level): +//! +//! * [`BitReader::u`] — fixed-width unsigned integer (the `u(n)` +//! descriptor of §7.2). +//! * [`BitReader::ue`] — 0-th-order unsigned Exp-Golomb (the `ue(v)` +//! descriptor, parsed per §9.2). +//! +//! The reader takes an already-unescaped RBSP buffer (see +//! [`crate::nal::strip_emulation_prevention`]) and does not attempt to +//! locate the RBSP stop bit — that is left to the calling parser. + +/// Errors that can arise while consuming bits from an RBSP buffer. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum BitReaderError { + /// A read requested more bits than remained in the buffer. + EndOfBuffer, + /// More than 32 bits requested in a single `u()` read. + TooManyBits, + /// A 0-th-order Exp-Golomb code's leading-zero run exceeded 32 + /// (the §9.2 contract caps `codeNum` at `2^32 - 2`). A run of 33 + /// zeros would overflow the 32-bit return type. + ExpGolombOverflow, +} + +impl core::fmt::Display for BitReaderError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::EndOfBuffer => f.write_str("read past end of RBSP buffer"), + Self::TooManyBits => f.write_str("u(n) called with n > 32"), + Self::ExpGolombOverflow => f.write_str("ue(v) leading-zero run exceeded 32"), + } + } +} + +impl std::error::Error for BitReaderError {} + +/// MSB-first bit reader. +#[derive(Debug, Clone)] +pub struct BitReader<'a> { + buf: &'a [u8], + /// Bit cursor measured from the start of `buf` (0 == MSB of + /// `buf[0]`). + bit_pos: usize, +} + +impl<'a> BitReader<'a> { + /// Construct a bit reader over `buf`. + pub fn new(buf: &'a [u8]) -> Self { + Self { buf, bit_pos: 0 } + } + + /// Number of bits still available. + pub fn bits_left(&self) -> usize { + self.buf + .len() + .saturating_mul(8) + .saturating_sub(self.bit_pos) + } + + /// Read a single bit (the `u(1)` descriptor). + pub fn u1(&mut self) -> Result { + if self.bit_pos >= self.buf.len() * 8 { + return Err(BitReaderError::EndOfBuffer); + } + let byte = self.buf[self.bit_pos / 8]; + let bit = 7 - (self.bit_pos % 8); + self.bit_pos += 1; + Ok((byte >> bit) & 0x01) + } + + /// Read `n` bits MSB-first as an unsigned integer (the `u(n)` + /// descriptor, with `n` in `0..=32`). `n == 0` returns 0 and does + /// not advance the cursor. + pub fn u(&mut self, n: u8) -> Result { + if n > 32 { + return Err(BitReaderError::TooManyBits); + } + if n == 0 { + return Ok(0); + } + if self.bits_left() < n as usize { + return Err(BitReaderError::EndOfBuffer); + } + let mut value: u32 = 0; + for _ in 0..n { + value = (value << 1) | (self.u1()? as u32); + } + Ok(value) + } + + /// Skip `n` bits without interpreting them. Useful when a syntax + /// element appears in the bitstream but is not needed by the + /// caller (e.g. the 32 profile_compatibility flags after the + /// caller has already recorded the few of interest). + pub fn skip(&mut self, n: usize) -> Result<(), BitReaderError> { + if self.bits_left() < n { + return Err(BitReaderError::EndOfBuffer); + } + self.bit_pos += n; + Ok(()) + } + + /// Read a 0-th-order unsigned Exp-Golomb code (the `ue(v)` + /// descriptor). Per ITU-T Rec. H.265 §9.2: count `leadingZeroBits` + /// 0 bits until the first 1 bit is seen; then read another + /// `leadingZeroBits` bits and compute + /// `codeNum = 2^leadingZeroBits + read_bits(leadingZeroBits) - 1`. + pub fn ue(&mut self) -> Result { + let mut leading_zero_bits: u32 = 0; + loop { + if leading_zero_bits > 32 { + return Err(BitReaderError::ExpGolombOverflow); + } + let b = self.u1()?; + if b == 1 { + break; + } + leading_zero_bits += 1; + } + if leading_zero_bits == 0 { + return Ok(0); + } + if leading_zero_bits == 32 { + // 2^32 would overflow u32; the suffix must therefore be 0 + // to keep `codeNum` representable. Treat any other input + // as an overflow. + let suffix = self.u(32)?; + return suffix + .checked_sub(1) + .and_then(|v| (1u64 << 32).checked_add(v as u64)) + .and_then(|big| u32::try_from(big).ok()) + .ok_or(BitReaderError::ExpGolombOverflow); + } + let suffix = self.u(leading_zero_bits as u8)?; + Ok((1u32 << leading_zero_bits) - 1 + suffix) + } + + /// Read a 0-th-order signed Exp-Golomb code (the `se(v)` + /// descriptor). Per ITU-T Rec. H.265 §9.2.2: read a `ue(v)` + /// `codeNum`, then map it to a signed value per Table 9-3 as + /// `(-1)^(codeNum + 1) * Ceil(codeNum / 2)` — `codeNum` 0 → 0, + /// 1 → +1, 2 → -1, 3 → +2, 4 → -2, … + pub fn se(&mut self) -> Result { + let code_num = self.ue()?; + // Ceil(codeNum / 2) without overflow: (codeNum + 1) / 2. + let magnitude = ((code_num as i64) + 1) / 2; + let value = if code_num % 2 == 0 { + // Even codeNum (0, 2, 4, …) maps to a non-positive value + // (0, -1, -2, …). + -magnitude + } else { + // Odd codeNum (1, 3, 5, …) maps to a positive value. + magnitude + }; + // `value` is bounded by ±2^31 because `ue()` caps `codeNum` + // at `2^32 - 2`, whose mapped magnitude is `2^31 - 1`. + i32::try_from(value).map_err(|_| BitReaderError::ExpGolombOverflow) + } + + /// Current bit position from the start of the buffer. + pub fn bit_pos(&self) -> usize { + self.bit_pos + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reads_individual_bits_msb_first() { + // 0b1010_0110, 0b1100_0011 → bits: 1 0 1 0 0 1 1 0 1 1 0 0 0 0 1 1 + let buf = [0xA6, 0xC3]; + let mut br = BitReader::new(&buf); + let want = [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 1, 1]; + for &w in &want { + assert_eq!(br.u1().unwrap(), w); + } + assert!(br.u1().is_err()); + } + + #[test] + fn reads_u_n_across_byte_boundary() { + // Two bytes: 0xAB, 0xCD → 0b1010_1011_1100_1101 + let buf = [0xAB, 0xCD]; + let mut br = BitReader::new(&buf); + // Take 12 bits: 0b1010_1011_1100 = 0xABC + assert_eq!(br.u(12).unwrap(), 0xABC); + // Remaining 4 bits: 0xD + assert_eq!(br.u(4).unwrap(), 0xD); + } + + #[test] + fn u_zero_returns_zero_and_does_not_consume() { + let buf = [0xFF]; + let mut br = BitReader::new(&buf); + assert_eq!(br.u(0).unwrap(), 0); + assert_eq!(br.bit_pos(), 0); + } + + #[test] + fn u_thirty_two_full_word() { + let buf = [0x12, 0x34, 0x56, 0x78]; + let mut br = BitReader::new(&buf); + assert_eq!(br.u(32).unwrap(), 0x1234_5678); + } + + #[test] + fn ue_table_b9_2() { + // Per H.265 §9.2 Table 9-2 first few codewords: + // codeNum=0 → '1' (1 bit) + // codeNum=1 → '010' (3 bits) + // codeNum=2 → '011' (3 bits) + // codeNum=3 → '00100' (5 bits) + // codeNum=4 → '00101' (5 bits) + // codeNum=5 → '00110' (5 bits) + // codeNum=6 → '00111' (5 bits) + // Pack codewords 0..=6 into a byte stream MSB-first: + // Bits: 1 010 011 00100 00101 00110 00111 = 27 bits, padded + // with 5 zero bits to land on a 32-bit byte boundary. + // Group as bytes (MSB first): + // bit 0..7 : 1 0 1 0 0 1 1 0 = 0xA6 + // bit 8..15 : 0 1 0 0 0 0 1 0 = 0x42 + // bit 16..23: 1 0 0 1 1 0 0 0 = 0x98 + // bit 24..31: 1 1 1 0 0 0 0 0 = 0xE0 (last 5 bits are pad) + let buf = [0xA6, 0x42, 0x98, 0xE0]; + let mut br = BitReader::new(&buf); + let got: Vec = (0..7).map(|_| br.ue().unwrap()).collect(); + assert_eq!(got, vec![0, 1, 2, 3, 4, 5, 6]); + } + + #[test] + fn ue_zero_is_single_one_bit() { + let buf = [0b1000_0000]; + let mut br = BitReader::new(&buf); + assert_eq!(br.ue().unwrap(), 0); + assert_eq!(br.bit_pos(), 1); + } + + #[test] + fn end_of_buffer_errors() { + let buf = [0xFF]; + let mut br = BitReader::new(&buf); + assert_eq!(br.u(8).unwrap(), 0xFF); + assert_eq!(br.u(1), Err(BitReaderError::EndOfBuffer)); + } + + #[test] + fn too_many_bits_errors() { + let buf = [0xFF; 8]; + let mut br = BitReader::new(&buf); + assert_eq!(br.u(33), Err(BitReaderError::TooManyBits)); + } + + #[test] + fn skip_advances_cursor() { + let buf = [0xFF, 0xAA]; + let mut br = BitReader::new(&buf); + br.skip(8).unwrap(); + assert_eq!(br.u(8).unwrap(), 0xAA); + } + + #[test] + fn se_table_9_3() { + // Per H.265 §9.2.2 Table 9-3, codeNum → se(v) value: + // 0 → 0, 1 → +1, 2 → -1, 3 → +2, 4 → -2, 5 → +3, 6 → -3. + // codeNum is itself ue(v); reuse the codewords 0..=6 packing + // from `ue_table_b9_2` (bits 1 010 011 00100 00101 00110 00111). + let buf = [0xA6, 0x42, 0x98, 0xE0]; + let mut br = BitReader::new(&buf); + let got: Vec = (0..7).map(|_| br.se().unwrap()).collect(); + assert_eq!(got, vec![0, 1, -1, 2, -2, 3, -3]); + } + + #[test] + fn se_zero_is_single_one_bit() { + // codeNum 0 ('1') maps to value 0 and consumes one bit. + let buf = [0b1000_0000]; + let mut br = BitReader::new(&buf); + assert_eq!(br.se().unwrap(), 0); + assert_eq!(br.bit_pos(), 1); + } + + #[test] + fn ue_overflow_run_too_long() { + // 33 leading zero bits with no terminating 1 in the buffer. + // The reader should surface ExpGolombOverflow before running + // off the end (we never reach the suffix read). + let buf = [0u8; 8]; // 64 zero bits + let mut br = BitReader::new(&buf); + assert_eq!(br.ue(), Err(BitReaderError::ExpGolombOverflow)); + } +} diff --git a/vendor/oxideav-h265/src/cabac.rs b/vendor/oxideav-h265/src/cabac.rs new file mode 100644 index 0000000..41032e4 --- /dev/null +++ b/vendor/oxideav-h265/src/cabac.rs @@ -0,0 +1,820 @@ +//! §9.3 CABAC arithmetic decoding engine. +//! +//! This module is a clean-room transcription of the ITU-T Rec. H.265 | +//! ISO/IEC 23008-2 §9.3 context-adaptive binary arithmetic coding +//! *decode* engine — the lowest layer of HEVC entropy decoding, the +//! gateway through which all slice-data syntax elements (§7.3.8) are +//! read. It deliberately stops at the engine boundary: it exposes the +//! four arithmetic-decode primitives plus the context-variable model, +//! but does not implement the §9.3.4.2 binarization / context-index +//! derivation for any specific syntax element (those sit one layer up, +//! in the slice-data parser). +//! +//! The pieces transcribed here are: +//! +//! * §9.3.2.6 — [`CabacEngine::new`] / [`CabacEngine::init_engine`]: +//! `ivlCurrRange = 510`, `ivlOffset = read_bits(9)`. +//! * §9.3.2.2 — [`ContextModel::init`] (equations 9-4, 9-5, 9-6) plus +//! the §9.3.2.2 `initType` derivation (equation 9-7, +//! [`init_type`]). A context variable is a `(pStateIdx, valMps)` +//! pair derived from an 8-bit `initValue` and the slice QP. +//! * §9.3.4.3.2 — [`CabacEngine::decode_decision`] (DecodeDecision): +//! the regular context-coded bin, with the Table 9-52 `rangeTabLps` +//! interval split, the §9.3.4.3.2.2 state transition (Table 9-53), +//! and the §9.3.4.3.3 renormalization. +//! * §9.3.4.3.4 — [`CabacEngine::decode_bypass`] (DecodeBypass): the +//! equal-probability bin. +//! * §9.3.4.3.5 — [`CabacEngine::decode_terminate`] (DecodeTerminate): +//! the `end_of_slice_segment_flag` / `end_of_subset_one_bit` / +//! `pcm_flag` decision before termination. +//! * §9.3.4.3.6 — [`CabacEngine::align`] (the alignment process prior +//! to aligned bypass decoding for `coeff_abs_level_remaining[ ]` / +//! `coeff_sign_flag[ ]`): `ivlCurrRange = 256`. +//! +//! The Table 9-52 / Table 9-53 values are transcribed directly from the +//! H.265 specification text (`docs/video/h265/`). They are arithmetic +//! constants of the format, not external-library code. +//! +//! # Bit source +//! +//! The engine reads raw bits via [`BitReader`] (`read_bits(1)` in the +//! spec is [`BitReader::u1`], `read_bits(9)` is `BitReader::u(9)`). The +//! caller positions the reader at the first byte of `slice_segment_data()` +//! — for example via +//! [`crate::slice::SliceSegmentHeader::byte_offset_to_slice_data`] — and +//! then constructs the engine, which immediately consumes the 9-bit +//! initial `ivlOffset` per §9.3.2.6. + +use crate::bitreader::{BitReader, BitReaderError}; + +/// Errors that can arise while running the CABAC decode engine. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CabacError { + /// The bit reader ran out of bits (a `read_bits()` past the end of + /// the slice-segment-data buffer). A conforming bitstream never + /// reaches this state during a valid decode, so it indicates a + /// truncated or malformed stream. + EndOfBuffer, + /// §9.3.2.6 forbids `ivlOffset` taking the value 510 or 511 after + /// the initial 9-bit read ("The bitstream shall not contain data + /// that result in a value of ivlOffset being equal to 510 or + /// 511."). + InvalidInitOffset(u16), +} + +impl core::fmt::Display for CabacError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::EndOfBuffer => f.write_str("CABAC engine read past end of slice-data buffer"), + Self::InvalidInitOffset(v) => { + write!(f, "CABAC init ivlOffset {v} is forbidden (must be < 510)") + } + } + } +} + +impl std::error::Error for CabacError {} + +impl From for CabacError { + fn from(_: BitReaderError) -> Self { + // The only `BitReaderError` the engine can provoke is running + // out of bits — every other `BitReader` failure mode (too many + // bits, Exp-Golomb overflow) is unreachable from `u1()` / + // `u(9)`. + Self::EndOfBuffer + } +} + +/// The §9.3.2.2 `initType` selector (equation 9-7). `slice_type` is the +/// §7.4.7.1 enum (0 = B, 1 = P, 2 = I); `cabac_init_flag` is the +/// slice-header flag (only present for P / B slices). +/// +/// ```text +/// if( slice_type == I ) initType = 0 +/// else if( slice_type == P ) initType = cabac_init_flag ? 2 : 1 +/// else /* B */ initType = cabac_init_flag ? 1 : 2 +/// ``` +/// +/// `slice_type` here uses [`crate::slice::SliceType`]'s numeric values: +/// `SliceType::B == 0`, `SliceType::P == 1`, `SliceType::I == 2`. +#[must_use] +pub fn init_type(slice_type: u8, cabac_init_flag: bool) -> u8 { + match slice_type { + // I slice. + 2 => 0, + // P slice. + 1 => { + if cabac_init_flag { + 2 + } else { + 1 + } + } + // B slice (any other slice_type value funnels here). + _ => { + if cabac_init_flag { + 1 + } else { + 2 + } + } + } +} + +/// A single CABAC context variable: the §9.3.4.3 probability-state +/// index `pStateIdx` (0..=63) paired with the most-probable-symbol +/// value `valMps` (0 or 1). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContextModel { + /// §9.3.4.3 probability state index, 0..=63. State 0 is the + /// `pLPS == 0.5` extreme; higher indices have lower LPS + /// probability. + pub p_state_idx: u8, + /// The value of the most probable symbol (0 or 1). + pub val_mps: u8, +} + +impl ContextModel { + /// §9.3.2.2 context-variable initialization (equations 9-4, 9-5, + /// 9-6). `init_value` is the 8-bit `initValue` table entry for the + /// context; `slice_qp_y` is `SliceQpY` (equation 7-54). + /// + /// ```text + /// slopeIdx = initValue >> 4 + /// offsetIdx = initValue & 15 (9-4) + /// m = slopeIdx * 5 − 45 + /// n = ( offsetIdx << 3 ) − 16 (9-5) + /// preCtxState = Clip3( 1, 126, + /// ( ( m * Clip3( 0, 51, SliceQpY ) ) >> 4 ) + n ) + /// valMps = ( preCtxState <= 63 ) ? 0 : 1 + /// pStateIdx = valMps ? ( preCtxState − 64 ) : ( 63 − preCtxState ) (9-6) + /// ``` + /// + /// The `>> 4` in equation 9-6 is an arithmetic shift of a signed + /// product (`m` can be negative); this is reproduced with signed + /// arithmetic. + #[must_use] + pub fn init(init_value: u8, slice_qp_y: i32) -> Self { + // Equation 9-4. + let slope_idx = (init_value >> 4) as i32; + let offset_idx = (init_value & 15) as i32; + // Equation 9-5. + let m = slope_idx * 5 - 45; + let n = (offset_idx << 3) - 16; + // Equation 9-6: Clip3(0, 51, SliceQpY) then the signed + // arithmetic-shift product, then Clip3(1, 126, …). + let qp = slice_qp_y.clamp(0, 51); + let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126); + let (val_mps, p_state_idx) = if pre_ctx_state <= 63 { + (0u8, (63 - pre_ctx_state) as u8) + } else { + (1u8, (pre_ctx_state - 64) as u8) + }; + Self { + p_state_idx, + val_mps, + } + } + + /// The non-adapting state described in §9.3.2.2 NOTE 2 for + /// `ctxTable == 0`, `ctxIdx == 0` (the `end_of_slice_segment_flag` + /// / `end_of_subset_one_bit` / `pcm_flag` decision when emulated + /// through DecodeDecision): `pStateIdx = 63`, `valMps = 0`. + /// `decode_terminate` does not need this state — it is provided for + /// completeness of the model. + #[must_use] + pub fn terminate_state() -> Self { + Self { + p_state_idx: 63, + val_mps: 0, + } + } +} + +/// Table 9-52 — `rangeTabLps[ pStateIdx ][ qRangeIdx ]`. 64 states × +/// 4 quantized-range columns. Transcribed from the H.265 specification +/// text (§9.3.4.3.2.1). +#[rustfmt::skip] +pub(crate) const RANGE_TAB_LPS: [[u8; 4]; 64] = [ + [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205], + [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166], + [ 95, 116, 137, 158], [ 90, 110, 130, 150], [ 85, 104, 123, 142], [ 81, 99, 117, 135], + [ 77, 94, 111, 128], [ 73, 89, 105, 122], [ 69, 85, 100, 116], [ 66, 80, 95, 110], + [ 62, 76, 90, 104], [ 59, 72, 86, 99], [ 56, 69, 81, 94], [ 53, 65, 77, 89], + [ 51, 62, 73, 85], [ 48, 59, 69, 80], [ 46, 56, 66, 76], [ 43, 53, 63, 72], + [ 41, 50, 59, 69], [ 39, 48, 56, 65], [ 37, 45, 54, 62], [ 35, 43, 51, 59], + [ 33, 41, 48, 56], [ 32, 39, 46, 53], [ 30, 37, 43, 50], [ 29, 35, 41, 48], + [ 27, 33, 39, 45], [ 26, 31, 37, 43], [ 24, 30, 35, 41], [ 23, 28, 33, 39], + [ 22, 27, 32, 37], [ 21, 26, 30, 35], [ 20, 24, 29, 33], [ 19, 23, 27, 31], + [ 18, 22, 26, 30], [ 17, 21, 25, 28], [ 16, 20, 23, 27], [ 15, 19, 22, 25], + [ 14, 18, 21, 24], [ 14, 17, 20, 23], [ 13, 16, 19, 22], [ 12, 15, 18, 21], + [ 12, 14, 17, 20], [ 11, 14, 16, 19], [ 11, 13, 15, 18], [ 10, 12, 15, 17], + [ 10, 12, 14, 16], [ 9, 11, 13, 15], [ 9, 11, 12, 14], [ 8, 10, 12, 14], + [ 8, 9, 11, 13], [ 7, 9, 11, 12], [ 7, 9, 10, 12], [ 7, 8, 10, 11], + [ 6, 8, 9, 11], [ 6, 7, 9, 10], [ 6, 7, 8, 9], [ 2, 2, 2, 2], +]; + +/// Table 9-53 — `transIdxLps[ pStateIdx ]`, the probability-state +/// transition after decoding the LPS (`1 − valMps`). Transcribed from +/// the H.265 specification text (§9.3.4.3.2.2). +#[rustfmt::skip] +pub(crate) const TRANS_IDX_LPS: [u8; 64] = [ + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, + 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, + 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, + 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, +]; + +/// Table 9-53 — `transIdxMps[ pStateIdx ]`, the probability-state +/// transition after decoding the MPS (`valMps`). Transcribed from the +/// H.265 specification text (§9.3.4.3.2.2). +#[rustfmt::skip] +pub(crate) const TRANS_IDX_MPS: [u8; 64] = [ + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, +]; + +/// The §9.3.4.3 arithmetic decoding engine state plus its bit source. +/// +/// The engine holds the two §9.3.2.6 registers `ivlCurrRange` and +/// `ivlOffset` and the [`BitReader`] from which renormalization / +/// bypass pull `read_bits(1)`. Context variables ([`ContextModel`]) +/// live in the caller's context-model array; each +/// [`decode_decision`](CabacEngine::decode_decision) call takes and +/// mutates one in place. +#[derive(Debug)] +pub struct CabacEngine<'a> { + reader: BitReader<'a>, + /// §9.3.2.6 `ivlCurrRange` (held in a 16-bit-wide register; values + /// stay within 9 bits during decode). + ivl_curr_range: u16, + /// §9.3.2.6 `ivlOffset` (10-bit register precision is required for + /// bypass). + ivl_offset: u16, +} + +impl<'a> CabacEngine<'a> { + /// §9.3.2.6 — construct and initialize the arithmetic decoding + /// engine over `reader`, which the caller has positioned at the + /// first bit of `slice_segment_data()`. Sets `ivlCurrRange = 510` + /// and `ivlOffset = read_bits(9)`, and validates the §9.3.2.6 + /// constraint that `ivlOffset` is not 510 or 511. + pub fn new(mut reader: BitReader<'a>) -> Result { + let ivl_offset = reader.u(9)? as u16; + if ivl_offset >= 510 { + return Err(CabacError::InvalidInitOffset(ivl_offset)); + } + Ok(Self { + reader, + ivl_curr_range: 510, + ivl_offset, + }) + } + + /// §9.3.2.6 — re-initialize the engine registers on an already + /// constructed engine (e.g. after `pcm_flag == 1` data is consumed, + /// per §9.3.2.5 / §9.3.2.6). The bit reader is *not* repositioned; + /// the caller is responsible for having advanced it to the byte + /// boundary following the PCM samples before calling this. + pub fn init_engine(&mut self) -> Result<(), CabacError> { + let ivl_offset = self.reader.u(9)? as u16; + if ivl_offset >= 510 { + return Err(CabacError::InvalidInitOffset(ivl_offset)); + } + self.ivl_curr_range = 510; + self.ivl_offset = ivl_offset; + Ok(()) + } + + /// Current `ivlCurrRange` register value (for tests / inspection). + #[must_use] + pub fn ivl_curr_range(&self) -> u16 { + self.ivl_curr_range + } + + /// §9.3.4.3.6 — alignment process prior to aligned bypass + /// decoding: `ivlCurrRange` is set equal to 256. Invoked when + /// `cabac_bypass_alignment_enabled_flag == 1` before the bypass + /// decoding of `coeff_sign_flag[ ]` / `coeff_abs_level_remaining[ + /// ]` (and the §7.3.8.13 palette escape group) when + /// `escapeDataPresent == 1`. After alignment every bypass bin + /// consumes exactly one stream bit (the NOTE's shift-register + /// view); bypass decoding itself never changes `ivlCurrRange`, so + /// repeated invocations inside one aligned run are no-ops. + pub fn align_bypass(&mut self) { + self.ivl_curr_range = 256; + } + + /// Current `ivlOffset` register value (for tests / inspection). + #[must_use] + pub fn ivl_offset(&self) -> u16 { + self.ivl_offset + } + + /// Bit position of the underlying reader (for tests / locating the + /// engine's consumption point in the buffer). + #[must_use] + pub fn bit_pos(&self) -> usize { + self.reader.bit_pos() + } + + /// §7.3.8.7 support — consume `pcm_alignment_zero_bit` from the + /// raw bit source until it is byte-aligned. Called right after a + /// `pcm_flag == 1` terminate bin: §9.3.4.3.5 leaves the bitstream + /// pointer directly after the terminating one bit, so the raw + /// reader position is authoritative for `byte_aligned()`. + /// + /// # Errors + /// [`CabacError::EndOfBuffer`] on a truncated stream. + pub fn pcm_align(&mut self) -> Result<(), CabacError> { + while self.reader.bit_pos() % 8 != 0 { + let _ = self.reader.u1()?; + } + Ok(()) + } + + /// §7.3.8.7 support — read one raw `u(n)` field (a + /// `pcm_sample_luma` / `pcm_sample_chroma` value) directly from the + /// bit source, bypassing the arithmetic engine. + /// + /// # Errors + /// [`CabacError::EndOfBuffer`] on a truncated stream. + pub fn read_raw_bits(&mut self, n: u8) -> Result { + Ok(self.reader.u(n)?) + } + + /// Consume the engine and hand back its bit source (tests / callers + /// that continue non-CABAC parsing after termination). + #[must_use] + pub fn into_reader(self) -> BitReader<'a> { + self.reader + } + + /// §9.3.4.3.3 — renormalization in the arithmetic decoding engine + /// (RenormD). While `ivlCurrRange < 256`, double `ivlCurrRange` and + /// shift one fresh bit into `ivlOffset`. + fn renorm(&mut self) -> Result<(), CabacError> { + while self.ivl_curr_range < 256 { + self.ivl_curr_range <<= 1; + let bit = self.reader.u1()? as u16; + self.ivl_offset = (self.ivl_offset << 1) | bit; + } + Ok(()) + } + + /// §9.3.4.3.2 — DecodeDecision: decode one regular context-coded + /// bin against the supplied context variable `ctx`, mutating it + /// per the §9.3.4.3.2.2 state-transition process. Returns the + /// decoded bin value (0 or 1). + pub fn decode_decision(&mut self, ctx: &mut ContextModel) -> Result { + // Step 1 (equations 9-64, 9-65): the LPS sub-range. + let q_range_idx = ((self.ivl_curr_range >> 6) & 3) as usize; + let ivl_lps_range = RANGE_TAB_LPS[ctx.p_state_idx as usize][q_range_idx] as u16; + + // Step 2: subtract the LPS range; compare ivlOffset. + self.ivl_curr_range -= ivl_lps_range; + let bin_val; + if self.ivl_offset >= self.ivl_curr_range { + // LPS path. + bin_val = 1 - ctx.val_mps; + self.ivl_offset -= self.ivl_curr_range; + self.ivl_curr_range = ivl_lps_range; + } else { + // MPS path. + bin_val = ctx.val_mps; + } + + // §9.3.4.3.2.2 state transition (equation 9-66). + if bin_val == ctx.val_mps { + ctx.p_state_idx = TRANS_IDX_MPS[ctx.p_state_idx as usize]; + } else { + if ctx.p_state_idx == 0 { + ctx.val_mps = 1 - ctx.val_mps; + } + ctx.p_state_idx = TRANS_IDX_LPS[ctx.p_state_idx as usize]; + } + + // §9.3.4.3.3 renormalization. + self.renorm()?; + Ok(bin_val) + } + + /// §9.3.4.3.4 — DecodeBypass: decode one equal-probability bin. + /// Doubles `ivlOffset` (shifting in one fresh bit), then compares + /// against `ivlCurrRange`. Returns the decoded bin (0 or 1). + pub fn decode_bypass(&mut self) -> Result { + let bit = self.reader.u1()? as u16; + self.ivl_offset = (self.ivl_offset << 1) | bit; + if self.ivl_offset >= self.ivl_curr_range { + self.ivl_offset -= self.ivl_curr_range; + Ok(1) + } else { + Ok(0) + } + } + + /// §9.3.4.3.4 — convenience wrapper: decode `n` bypass bins + /// MSB-first and accumulate them into an integer (`n` in 0..=32). + /// This is the common pattern for fixed-length bypass-coded fields. + /// `n == 0` returns 0 and consumes nothing. + pub fn decode_bypass_bits(&mut self, n: u8) -> Result { + let mut value: u32 = 0; + for _ in 0..n { + value = (value << 1) | (self.decode_bypass()? as u32); + } + Ok(value) + } + + /// §9.3.4.3.5 — DecodeTerminate: the decision before termination + /// (`end_of_slice_segment_flag`, `end_of_subset_one_bit`, + /// `pcm_flag`; `ctxTable == 0`, `ctxIdx == 0`). Decrements + /// `ivlCurrRange` by 2; if `ivlOffset >= ivlCurrRange` the result + /// is 1 (no renormalization, decoding is terminated), otherwise the + /// result is 0 and renormalization is applied. + pub fn decode_terminate(&mut self) -> Result { + self.ivl_curr_range -= 2; + if self.ivl_offset >= self.ivl_curr_range { + Ok(1) + } else { + self.renorm()?; + Ok(0) + } + } + + /// §9.3.4.3.6 — alignment process prior to aligned bypass decoding + /// (applied before `coeff_abs_level_remaining[ ]` and + /// `coeff_sign_flag[ ]`): `ivlCurrRange = 256`. The bit reader and + /// `ivlOffset` are left untouched. + pub fn align(&mut self) { + self.ivl_curr_range = 256; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // --- §9.3.2.2 context-variable init (equations 9-4..9-6) --- + + #[test] + fn init_type_eq_9_7() { + // I slice (slice_type == 2) → 0 regardless of cabac_init_flag. + assert_eq!(init_type(2, false), 0); + assert_eq!(init_type(2, true), 0); + // P slice (slice_type == 1). + assert_eq!(init_type(1, false), 1); + assert_eq!(init_type(1, true), 2); + // B slice (slice_type == 0). + assert_eq!(init_type(0, false), 2); + assert_eq!(init_type(0, true), 1); + } + + #[test] + fn context_init_worked_example() { + // Hand-evaluate equations 9-4..9-6 for initValue = 154, + // SliceQpY = 26 (a common mid-range QP). + // slopeIdx = 154 >> 4 = 9 + // offsetIdx = 154 & 15 = 10 + // m = 9*5 - 45 = 0 + // n = (10 << 3) - 16 = 64 + // preCtxState = Clip3(1,126, (0*26 >> 4) + 64) = 64 + // valMps = (64 <= 63) ? 0 : 1 = 1 + // pStateIdx = 1 ? (64-64) : … = 0 + let c = ContextModel::init(154, 26); + assert_eq!(c.val_mps, 1); + assert_eq!(c.p_state_idx, 0); + } + + #[test] + fn context_init_negative_slope() { + // initValue = 0, SliceQpY = 51 (max). Exercises a negative m + // and the signed arithmetic shift in equation 9-6. + // slopeIdx = 0, offsetIdx = 0 + // m = -45, n = -16 + // m*Clip3(0,51,51) = -45*51 = -2295 + // -2295 >> 4 = -144 (arithmetic shift toward -inf) + // preCtxState = Clip3(1,126, -144 + -16) = Clip3(1,126,-160) = 1 + // valMps = (1 <= 63) ? 0 : 1 = 0 + // pStateIdx = 0 ? … : (63 - 1) = 62 + let c = ContextModel::init(0, 51); + assert_eq!(c.val_mps, 0); + assert_eq!(c.p_state_idx, 62); + } + + #[test] + fn context_init_high_initvalue() { + // initValue = 255, SliceQpY = 0. Drives preCtxState toward the + // high clip. + // slopeIdx = 15, offsetIdx = 15 + // m = 15*5 - 45 = 30 + // n = (15 << 3) - 16 = 104 + // preCtxState = Clip3(1,126, (30*0 >> 4) + 104) = 104 + // valMps = (104 <= 63) ? 0 : 1 = 1 + // pStateIdx = 104 - 64 = 40 + let c = ContextModel::init(255, 0); + assert_eq!(c.val_mps, 1); + assert_eq!(c.p_state_idx, 40); + } + + #[test] + fn context_init_clips_low_qp_range() { + // SliceQpY below 0 is clipped to 0 by Clip3(0,51,SliceQpY); + // verify the negative-QP input lands at the same state as QP 0. + let c_neg = ContextModel::init(154, -10); + let c_zero = ContextModel::init(154, 0); + assert_eq!(c_neg, c_zero); + } + + #[test] + fn terminate_state_is_non_adapting() { + // §9.3.2.2 NOTE 2: pStateIdx = 63, valMps = 0. + let c = ContextModel::terminate_state(); + assert_eq!(c.p_state_idx, 63); + assert_eq!(c.val_mps, 0); + } + + // --- Table integrity --- + + #[test] + fn range_tab_lps_corner_values() { + // Spot-check the four corners of Table 9-52. + assert_eq!(RANGE_TAB_LPS[0], [128, 176, 208, 240]); + assert_eq!(RANGE_TAB_LPS[31], [29, 35, 41, 48]); + assert_eq!(RANGE_TAB_LPS[32], [27, 33, 39, 45]); + assert_eq!(RANGE_TAB_LPS[63], [2, 2, 2, 2]); + // The whole table is non-increasing down each column (a + // structural property of the LPS-range quantization). + for (s, row) in RANGE_TAB_LPS.iter().enumerate().skip(1) { + let prev = &RANGE_TAB_LPS[s - 1]; + for (col, (cur, p)) in row.iter().zip(prev.iter()).enumerate() { + assert!(cur <= p, "column {col} not non-increasing at state {s}"); + } + } + } + + #[test] + fn trans_idx_tables_bounds_and_endpoints() { + // Every transition target is a valid state index (0..=63). + for s in 0..64usize { + assert!(TRANS_IDX_LPS[s] < 64); + assert!(TRANS_IDX_MPS[s] < 64); + } + // State 0 LPS stays at 0; state 63 is the absorbing terminal + // state for both transitions. + assert_eq!(TRANS_IDX_LPS[0], 0); + assert_eq!(TRANS_IDX_MPS[63], 63); + assert_eq!(TRANS_IDX_LPS[63], 63); + // transIdxMps is monotonically non-decreasing — confidence + // never goes backward after an MPS. (Equality is allowed near + // the upper extreme: index 62 maps to 62 in Table 9-53.) + for (s, &mps) in TRANS_IDX_MPS.iter().enumerate().take(63) { + assert!( + mps >= s as u8, + "transIdxMps[{s}] = {mps} is below the state" + ); + } + // transIdxLps is monotonically non-decreasing too (LPS at a + // high-confidence state drops to a less-confident state, but + // not below the LPS landing at a lower state). + for win in TRANS_IDX_LPS.windows(2) { + assert!(win[1] >= win[0]); + } + } + + // --- §9.3.2.6 engine init --- + + #[test] + fn engine_init_reads_nine_bit_offset() { + // First 9 bits = "1 01010101" = 341; ivlCurrRange = 510. + // byte0 = 0b10101010, byte1 MSB = 1 → 9-bit value 0x155 = 341. + let buf = [0b1010_1010, 0b1000_0000]; + let eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_curr_range(), 510); + assert_eq!(eng.ivl_offset(), 341); + assert_eq!(eng.bit_pos(), 9); + } + + #[test] + fn engine_init_rejects_offset_510_511() { + // 9 bits = 0x1FE = 510 → forbidden. byte0 = 0xFF, byte1 MSB + // = 0. + let buf = [0xFF, 0b0000_0000]; + match CabacEngine::new(BitReader::new(&buf)) { + Err(CabacError::InvalidInitOffset(510)) => {} + other => panic!("expected InvalidInitOffset(510), got {other:?}"), + } + // 9 bits = 0x1FF = 511 → forbidden. byte0 = 0xFF, byte1 MSB + // = 1. + let buf = [0xFF, 0b1000_0000]; + match CabacEngine::new(BitReader::new(&buf)) { + Err(CabacError::InvalidInitOffset(511)) => {} + other => panic!("expected InvalidInitOffset(511), got {other:?}"), + } + // 509 is allowed: 0x1FD; byte0 = 0xFE, byte1 MSB = 1. + let buf = [0xFE, 0b1000_0000]; + assert!(CabacEngine::new(BitReader::new(&buf)).is_ok()); + } + + // --- §9.3.4.3.4 bypass --- + + #[test] + fn bypass_reads_bits_msb_first() { + // After init, ivlCurrRange = 510, ivlOffset is the first 9 + // bits. Each bypass doubles ivlOffset (shift in one bit) and + // compares to 510. + // + // Construct so the bypass bins are deterministic. Init offset + // = 0 (9 zero bits at stream bits 0..=8). The next 4 stream + // bits feed four bypass decisions and must come out MSB-first. + // 9 init bits use byte0 (bits 0..=7) and bit 8 = byte1 MSB. + // For init = 0, byte0 = 0x00 and byte1 MSB = 0. The bypass + // bits start at stream bit 9 = byte1 bits 1..=4. We want them + // to be 1, 0, 1, 1 → byte1 bits 1..=4 = 1011 → byte1 LSBs are + // ignored, byte1 = 0b0_1011_000 = 0x58. + // bin0: offset = (0<<1)|1 = 1; 1 < 510 → 0 + // bin1: offset = (1<<1)|0 = 2; 2 < 510 → 0 + // bin2: offset = (2<<1)|1 = 5; 5 < 510 → 0 + // bin3: offset = (5<<1)|1 = 11; 11 < 510 → 0 + // Small offsets always yield 0 — verify offset accumulation. + let buf = [0x00, 0x58, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_offset(), 0); + assert_eq!(eng.decode_bypass().unwrap(), 0); + assert_eq!(eng.ivl_offset(), 1); + assert_eq!(eng.decode_bypass().unwrap(), 0); + assert_eq!(eng.ivl_offset(), 2); + assert_eq!(eng.decode_bypass().unwrap(), 0); + assert_eq!(eng.ivl_offset(), 5); + assert_eq!(eng.decode_bypass().unwrap(), 0); + assert_eq!(eng.ivl_offset(), 11); + } + + #[test] + fn bypass_one_when_offset_exceeds_range() { + // Init offset = 256. After one bypass shifting in a 1: offset + // = (256<<1)|1 = 513 >= 510 → bin 1, offset -= 510 → 3. + // + // 9-bit offset stream bits 0..=8: 1, 0, 0, 0, 0, 0, 0, 0, 0 + // → byte0 = 0b1000_0000, byte1 MSB = 0. We then want bypass + // bit (stream bit 9) = 1 → byte1 bit1 = 1 → byte1 = 0b0100_0000. + let buf = [0b1000_0000, 0b0100_0000]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_offset(), 256); + let bin = eng.decode_bypass().unwrap(); + assert_eq!(bin, 1); + assert_eq!(eng.ivl_offset(), 513 - 510); + } + + #[test] + fn bypass_bits_accumulates_msb_first() { + // decode_bypass_bits(0) is a no-op returning 0. + let buf = [0x00, 0x00, 0xFF]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.decode_bypass_bits(0).unwrap(), 0); + assert_eq!(eng.bit_pos(), 9); + } + + // --- §9.3.4.3.5 terminate --- + + #[test] + fn terminate_returns_one_and_stops() { + // Init offset = 509 (max legal). ivlCurrRange = 510. terminate: + // range -= 2 → 508; offset (509) >= 508 → return 1, no renorm. + let buf = [0xFE, 0b1000_0000]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_offset(), 509); + let pos_before = eng.bit_pos(); + assert_eq!(eng.decode_terminate().unwrap(), 1); + assert_eq!(eng.ivl_curr_range(), 508); + // No renormalization → no further bits consumed. + assert_eq!(eng.bit_pos(), pos_before); + } + + #[test] + fn terminate_returns_zero_and_renorms() { + // Init offset = 0. ivlCurrRange = 510. terminate: range -= 2 → + // 508; offset (0) < 508 → return 0, then renorm: 508 >= 256 so + // no renorm bits consumed. + let buf = [0x00, 0x00, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.decode_terminate().unwrap(), 0); + assert_eq!(eng.ivl_curr_range(), 508); + assert_eq!(eng.bit_pos(), 9); + } + + // --- §9.3.4.3.6 alignment --- + + #[test] + fn align_sets_range_256() { + let buf = [0x00, 0x00, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + eng.align(); + assert_eq!(eng.ivl_curr_range(), 256); + // ivlOffset and the reader are untouched. + assert_eq!(eng.ivl_offset(), 0); + assert_eq!(eng.bit_pos(), 9); + } + + // --- §9.3.4.3.2 DecodeDecision: MPS / LPS paths + renorm --- + + #[test] + fn decode_decision_mps_path_no_renorm() { + // Init offset = 0, ivlCurrRange = 510. Context: pStateIdx = 0, + // valMps = 0. + // qRangeIdx = (510 >> 6) & 3 = 7 & 3 = 3 + // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240 + // ivlCurrRange = 510 - 240 = 270 + // offset (0) < 270 → MPS → binVal = valMps = 0 + // transition: binVal == valMps → pStateIdx = transIdxMps[0]=1 + // renorm: 270 >= 256 → none + let buf = [0x00, 0x00, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = ContextModel { + p_state_idx: 0, + val_mps: 0, + }; + let bin = eng.decode_decision(&mut ctx).unwrap(); + assert_eq!(bin, 0); + assert_eq!(eng.ivl_curr_range(), 270); + assert_eq!(ctx.p_state_idx, 1); + assert_eq!(ctx.val_mps, 0); + assert_eq!(eng.bit_pos(), 9); // no renorm bits + } + + #[test] + fn decode_decision_lps_path_flips_mps_and_renorms() { + // Drive the LPS path with pStateIdx = 0 (so valMps flips). + // Init offset must be >= ivlCurrRange after the LPS subtraction. + // qRangeIdx = (510 >> 6) & 3 = 3 + // ivlLpsRange = RANGE_TAB_LPS[0][3] = 240 + // ivlCurrRange = 510 - 240 = 270 + // Need offset >= 270. Use init offset = 300 (0b1_0010_1100). + // LPS: binVal = 1 - valMps = 1 + // offset = 300 - 270 = 30 + // ivlCurrRange = 240 + // transition: binVal != valMps, pStateIdx==0 → valMps flips + // to 1; pStateIdx = transIdxLps[0] = 0 + // renorm: 240 < 256 → one doubling: range = 480, offset = + // (30<<1)|nextbit. + // 9-bit offset 300 = 0b1_0010_1100. Pack into bytes: + // byte0 = 0b1001_0110 (bits 0..7), byte1 MSB = 0 (bit 8). + // 300 binary (9 bits): 1 0010 1100. + // bit0=1 bit1=0 bit2=0 bit3=1 bit4=0 bit5=1 bit6=1 bit7=0 → 0x96 + // bit8=0 → byte1 MSB 0. + // The renorm bit (stream bit 9) = byte1 bit1; set it to 1. + let buf = [0x96, 0b0100_0000, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + assert_eq!(eng.ivl_offset(), 300); + let mut ctx = ContextModel { + p_state_idx: 0, + val_mps: 0, + }; + let bin = eng.decode_decision(&mut ctx).unwrap(); + assert_eq!(bin, 1); + assert_eq!(ctx.val_mps, 1); // flipped + assert_eq!(ctx.p_state_idx, 0); // transIdxLps[0] + assert_eq!(eng.ivl_curr_range(), 480); // 240 << 1 + assert_eq!(eng.ivl_offset(), (30 << 1) | 1); + assert_eq!(eng.bit_pos(), 10); // one renorm bit + } + + #[test] + fn end_of_buffer_surfaces_error() { + // Provide exactly 9 bits (one byte + one bit). After init, the + // bit reader is at its end, so the next bypass fails. We pad + // the buffer to 9 bits by giving 2 bytes but truncating the + // BitReader via `skip` would be circular — instead exercise + // the path that needs more than the buffer holds by consuming + // enough bypass bits to overrun. + let buf = [0x00, 0x00]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + // 16 - 9 = 7 bits left; the 8th bypass call must fail. + for _ in 0..7 { + eng.decode_bypass().unwrap(); + } + assert_eq!(eng.decode_bypass(), Err(CabacError::EndOfBuffer)); + } + + #[test] + fn round_trips_a_known_state_sequence() { + // Decode several MPS bins in a row from an all-zero stream with + // a fresh I-slice-style context and confirm the probability + // state walks up the transIdxMps ladder deterministically. + let buf = [0u8; 8]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = ContextModel { + p_state_idx: 0, + val_mps: 0, + }; + let mut states = Vec::new(); + for _ in 0..5 { + let bin = eng.decode_decision(&mut ctx).unwrap(); + assert_eq!(bin, 0); // all-zero offset always takes MPS here + states.push(ctx.p_state_idx); + } + // transIdxMps ladder from 0: 1, 2, 3, 4, 5. + assert_eq!(states, vec![1, 2, 3, 4, 5]); + } +} diff --git a/vendor/oxideav-h265/src/ctx_init.rs b/vendor/oxideav-h265/src/ctx_init.rs new file mode 100644 index 0000000..acc6dcf --- /dev/null +++ b/vendor/oxideav-h265/src/ctx_init.rs @@ -0,0 +1,994 @@ +//! §9.3.2.2 context-variable initialization — the `initValue` tables +//! (Tables 9-5 .. 9-42) and the per-slice context-array setup. +//! +//! This module is a clean-room transcription from the ITU-T Rec. H.265 +//! | ISO/IEC 23008-2 specification text (`docs/video/h265/`): +//! +//! * The 8-bit `initValue` tables for every context-coded syntax +//! element of clauses 7.3.8.1 through 7.3.8.12 (except +//! `end_of_slice_segment_flag`, `end_of_subset_one_bit` and +//! `pcm_flag`, which use the §9.3.2.2 NOTE 2 non-adapting +//! `ctxTable == 0` state — [`ContextModel::terminate_state`]). +//! Each constant is laid out flat over the table's printed ctxIdx +//! axis, exactly as in the spec. +//! * The Table 9-4 association of ctxIdx ranges to the three +//! initialization types: most tables devote a contiguous span of +//! `N` ctxIdx slots to each `initType` column, but several are +//! irregular (`part_mode`, `cbf_cb`/`cbf_cr`, the +//! `abs_mvd_greater0_flag`/`abs_mvd_greater1_flag` interleave, +//! `transform_skip_flag`, the `explicit_rdpcm_*` pairs and the +//! `sig_coeff_flag` transform-skip tail) — see the per-bank +//! helpers. +//! * [`SliceContexts`] — the whole per-slice context array, one bank +//! per syntax element (or per Table 9-4 shared-variable group), +//! initialised for a given `initType` and `SliceQpY` through the +//! §9.3.2.2 process ([`ContextModel::init`], equations 9-4..9-6). +//! [`SliceContexts::for_slice`] additionally applies the +//! equation 9-7 `initType` derivation from `slice_type` and +//! `cabac_init_flag` ([`crate::cabac::init_type`]). +//! +//! # Shared context variables +//! +//! Table 9-4 assigns the *same* `(ctxTable, ctxIdx)` slots to a few +//! element groups, which therefore share one adapting context +//! variable per `initType`: +//! +//! * `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5), +//! * `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6), +//! * `ref_idx_l0` / `ref_idx_l1` (Table 9-18), +//! * `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19), +//! * `cbf_cb` / `cbf_cr` (Table 9-22), +//! * `copy_above_palette_indices_flag` / +//! `copy_above_indices_for_final_run_flag` (Table 9-41), +//! * the chroma planes of `transform_skip_flag[ ][ ][ 1 ]` / +//! `[ 2 ]` (Table 9-25), `explicit_rdpcm_flag[ ][ ][ 1 ]` / `[ 2 ]` +//! (Table 9-32) and `explicit_rdpcm_dir_flag[ ][ ][ 1 ]` / `[ 2 ]` +//! (Table 9-33). +//! +//! # Inter-only elements in I slices +//! +//! Table 9-4 leaves the `initType == 0` column empty for the elements +//! that can only occur in P / B slices (`cu_skip_flag`, +//! `pred_mode_flag`, `rqt_root_cbf`, `merge_flag`, `merge_idx`, +//! `inter_pred_idc`, `ref_idx_l0`/`l1`, `mvp_l0_flag`/`l1`, +//! `abs_mvd_greater0_flag`/`greater1_flag`, `explicit_rdpcm_flag` and +//! `explicit_rdpcm_dir_flag`) — no initialization is specified +//! because a conforming I slice never decodes them. [`SliceContexts`] +//! still materialises those banks so the array shape is +//! `initType`-independent; at `initType == 0` they are populated with +//! the §9.3.2.2 NOTE 2 non-adapting state +//! ([`ContextModel::terminate_state`], `pStateIdx = 63`, +//! `valMps = 0`), which no table-derived context can take +//! (equations 9-4..9-6 bound `pStateIdx` to 0..=62), making an +//! accidental read recognisable. The same placeholder fills the +//! `part_mode` slots 1..=3 at `initType == 0` (Table 9-4 gives +//! `part_mode` only ctxIdx 0 there: the I-slice §9.3.4.2 binarization +//! uses a single context-coded bin). + +use crate::cabac::{init_type, ContextModel}; +use crate::residual::ResidualContexts; +use crate::slice::SliceType; + +// --------------------------------------------------------------------- +// initValue tables (Tables 9-5 .. 9-42) +// --------------------------------------------------------------------- + +/// Table 9-5 — `initValue` for ctxIdx of `sao_merge_left_flag` and +/// `sao_merge_up_flag` (one shared context per `initType`; ctxIdx +/// 0 / 1 / 2 for `initType` 0 / 1 / 2). +pub const TABLE_9_5_SAO_MERGE_FLAG: [u8; 3] = [153, 153, 153]; + +/// Table 9-6 — `initValue` for ctxIdx of `sao_type_idx_luma` and +/// `sao_type_idx_chroma` (one shared context per `initType`). +pub const TABLE_9_6_SAO_TYPE_IDX: [u8; 3] = [200, 185, 160]; + +/// Table 9-7 — `initValue` for ctxIdx of `split_cu_flag` (ctxIdx +/// 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2 per Table 9-4). +pub const TABLE_9_7_SPLIT_CU_FLAG: [u8; 9] = [139, 141, 157, 107, 139, 126, 107, 139, 126]; + +/// Table 9-8 — `initValue` for ctxIdx of `cu_transquant_bypass_flag`. +pub const TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG: [u8; 3] = [154, 154, 154]; + +/// Table 9-9 — `initValue` for ctxIdx of `cu_skip_flag` (ctxIdx 0..2 / +/// 3..5 for `initType` 1 / 2; the element does not occur in I slices). +pub const TABLE_9_9_CU_SKIP_FLAG: [u8; 6] = [197, 185, 201, 197, 185, 201]; + +/// Table 9-10 — `initValue` for ctxIdx of `pred_mode_flag` (ctxIdx +/// 0 / 1 for `initType` 1 / 2; inter-only). +pub const TABLE_9_10_PRED_MODE_FLAG: [u8; 2] = [149, 134]; + +/// Table 9-11 — `initValue` for ctxIdx of `part_mode`. Irregular +/// Table 9-4 mapping: ctxIdx 0 for `initType` 0 (the I-slice +/// binarization has one context-coded bin), ctxIdx 1..4 / 5..8 for +/// `initType` 1 / 2. +pub const TABLE_9_11_PART_MODE: [u8; 9] = [184, 154, 139, 154, 154, 154, 139, 154, 154]; + +/// Table 9-12 — `initValue` for ctxIdx of `prev_intra_luma_pred_flag`. +pub const TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG: [u8; 3] = [184, 154, 183]; + +/// Table 9-13 — `initValue` for ctxIdx of `intra_chroma_pred_mode`. +pub const TABLE_9_13_INTRA_CHROMA_PRED_MODE: [u8; 3] = [63, 152, 152]; + +/// Table 9-14 — `initValue` for ctxIdx of `rqt_root_cbf` (ctxIdx 0 / 1 +/// for `initType` 1 / 2; inter-only). +pub const TABLE_9_14_RQT_ROOT_CBF: [u8; 2] = [79, 79]; + +/// Table 9-15 — `initValue` for ctxIdx of `merge_flag` (`initType` +/// 1 / 2; inter-only). +pub const TABLE_9_15_MERGE_FLAG: [u8; 2] = [110, 154]; + +/// Table 9-16 — `initValue` for ctxIdx of `merge_idx` (`initType` +/// 1 / 2; inter-only). +pub const TABLE_9_16_MERGE_IDX: [u8; 2] = [122, 137]; + +/// Table 9-17 — `initValue` for ctxIdx of `inter_pred_idc` (ctxIdx +/// 0..4 / 5..9 for `initType` 1 / 2; inter-only). +pub const TABLE_9_17_INTER_PRED_IDC: [u8; 10] = [95, 79, 63, 31, 31, 95, 79, 63, 31, 31]; + +/// Table 9-18 — `initValue` for ctxIdx of `ref_idx_l0` and +/// `ref_idx_l1` (shared bank; ctxIdx 0..1 / 2..3 for `initType` 1 / 2; +/// inter-only). +pub const TABLE_9_18_REF_IDX: [u8; 4] = [153, 153, 153, 153]; + +/// Table 9-19 — `initValue` for ctxIdx of `mvp_l0_flag` and +/// `mvp_l1_flag` (shared bank; ctxIdx 0 / 1 for `initType` 1 / 2; +/// inter-only). +pub const TABLE_9_19_MVP_FLAG: [u8; 2] = [168, 168]; + +/// Table 9-20 — `initValue` for ctxIdx of `split_transform_flag` +/// (ctxIdx 0..2 / 3..5 / 6..8 for `initType` 0 / 1 / 2). +pub const TABLE_9_20_SPLIT_TRANSFORM_FLAG: [u8; 9] = [153, 138, 138, 124, 138, 94, 224, 167, 122]; + +/// Table 9-21 — `initValue` for ctxIdx of `cbf_luma` (ctxIdx 0..1 / +/// 2..3 / 4..5 for `initType` 0 / 1 / 2). +pub const TABLE_9_21_CBF_LUMA: [u8; 6] = [111, 141, 153, 111, 153, 111]; + +/// Table 9-22 — `initValue` for ctxIdx of `cbf_cb` and `cbf_cr` +/// (shared bank). Irregular Table 9-4 mapping: ctxIdx 0..3 / 4..7 / +/// 8..11 carry the four trafo-depth contexts for `initType` 0 / 1 / 2 +/// and ctxIdx 12 / 13 / 14 carry the fifth (`ctxInc == 4`) context +/// for `initType` 0 / 1 / 2. +#[rustfmt::skip] +pub const TABLE_9_22_CBF_CHROMA: [u8; 15] = [ + 94, 138, 182, 154, + 149, 107, 167, 154, + 149, 92, 167, 154, + 154, 154, 154, +]; + +/// Table 9-23 — `initValue` for ctxIdx of `abs_mvd_greater0_flag` and +/// `abs_mvd_greater1_flag`. Irregular Table 9-4 mapping (inter-only): +/// `abs_mvd_greater0_flag` takes ctxIdx 0 / 2 for `initType` 1 / 2 and +/// `abs_mvd_greater1_flag` takes ctxIdx 1 / 3. +pub const TABLE_9_23_ABS_MVD_GREATER_FLAG: [u8; 4] = [140, 198, 169, 198]; + +/// Table 9-24 — `initValue` for ctxIdx of `cu_qp_delta_abs` (ctxIdx +/// 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2). +pub const TABLE_9_24_CU_QP_DELTA_ABS: [u8; 6] = [154, 154, 154, 154, 154, 154]; + +/// Table 9-25 — `initValue` for ctxIdx of `transform_skip_flag`. +/// Irregular Table 9-4 mapping: ctxIdx 0 / 1 / 2 carry the luma +/// (`cIdx == 0`) context for `initType` 0 / 1 / 2 and ctxIdx 3 / 4 / 5 +/// the context shared by both chroma planes (`cIdx == 1` / `2`). +pub const TABLE_9_25_TRANSFORM_SKIP_FLAG: [u8; 6] = [139, 139, 139, 139, 139, 139]; + +/// Table 9-26 — `initValue` for ctxIdx of `last_sig_coeff_x_prefix` +/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2). +#[rustfmt::skip] +pub const TABLE_9_26_LAST_SIG_COEFF_X_PREFIX: [u8; 54] = [ + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, + 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, + 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, +]; + +/// Table 9-27 — `initValue` for ctxIdx of `last_sig_coeff_y_prefix` +/// (ctxIdx 0..17 / 18..35 / 36..53 for `initType` 0 / 1 / 2). The +/// printed values coincide with Table 9-26 entry-for-entry, but the +/// two elements adapt separate context variables. +#[rustfmt::skip] +pub const TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX: [u8; 54] = [ + 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63, + 125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108, + 125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93, +]; + +/// Table 9-28 — `initValue` for ctxIdx of `coded_sub_block_flag` +/// (ctxIdx 0..3 / 4..7 / 8..11 for `initType` 0 / 1 / 2). +#[rustfmt::skip] +pub const TABLE_9_28_CODED_SUB_BLOCK_FLAG: [u8; 12] = [ + 91, 171, 134, 141, + 121, 140, 61, 154, + 121, 140, 61, 154, +]; + +/// Table 9-29 — `initValue` for ctxIdx of `sig_coeff_flag`. Irregular +/// Table 9-4 mapping: ctxIdx 0..41 / 42..83 / 84..125 carry the 42 +/// §9.3.4.2.5 contexts for `initType` 0 / 1 / 2 and ctxIdx 126..127 / +/// 128..129 / 130..131 carry the two equation 9-40 transform-skip +/// contexts (luma, chroma) for `initType` 0 / 1 / 2. +#[rustfmt::skip] +pub const TABLE_9_29_SIG_COEFF_FLAG: [u8; 132] = [ + 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107, + 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152, + 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 155, 154, 139, 153, 139, 123, + 123, 63, 153, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, + 183, 140, 136, 153, 154, 170, 153, 123, 123, 107, 121, 107, 121, 167, 151, 183, + 140, 151, 183, 140, 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, + 136, 153, 154, 166, 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, + 153, 138, 138, 122, 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 141, 111, + 140, 140, 140, 140, +]; + +/// Table 9-30 — `initValue` for ctxIdx of +/// `coeff_abs_level_greater1_flag` (ctxIdx 0..23 / 24..47 / 48..71 for +/// `initType` 0 / 1 / 2). +#[rustfmt::skip] +pub const TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG: [u8; 72] = [ + 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152, + 140, 179, 166, 182, 140, 227, 122, 197, 154, 196, 196, 167, 154, 152, 167, 182, + 182, 134, 149, 136, 153, 121, 136, 137, 169, 194, 166, 167, 154, 167, 137, 182, + 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122, + 169, 208, 166, 167, 154, 152, 167, 182, +]; + +/// Table 9-31 — `initValue` for ctxIdx of +/// `coeff_abs_level_greater2_flag` (ctxIdx 0..5 / 6..11 / 12..17 for +/// `initType` 0 / 1 / 2). +#[rustfmt::skip] +pub const TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG: [u8; 18] = [ + 138, 153, 136, 167, 152, 152, + 107, 167, 91, 122, 107, 167, + 107, 167, 91, 107, 107, 167, +]; + +/// Table 9-32 — `initValue` for ctxIdx of `explicit_rdpcm_flag`. +/// Irregular Table 9-4 mapping (inter-only): ctxIdx 0 / 1 carry the +/// luma (`cIdx == 0`) context for `initType` 1 / 2 and ctxIdx 2 / 3 +/// the context shared by both chroma planes. +pub const TABLE_9_32_EXPLICIT_RDPCM_FLAG: [u8; 4] = [139, 139, 139, 139]; + +/// Table 9-33 — `initValue` for ctxIdx of `explicit_rdpcm_dir_flag` +/// (same irregular mapping as Table 9-32; inter-only). +pub const TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG: [u8; 4] = [139, 139, 139, 139]; + +/// Table 9-34 — `initValue` for ctxIdx of `cu_chroma_qp_offset_flag`. +pub const TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG: [u8; 3] = [154, 154, 154]; + +/// Table 9-35 — `initValue` for ctxIdx of `cu_chroma_qp_offset_idx`. +pub const TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX: [u8; 3] = [154, 154, 154]; + +/// Table 9-36 — `initValue` for ctxIdx of `log2_res_scale_abs_plus1` +/// (ctxIdx 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2). +pub const TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1: [u8; 24] = [154; 24]; + +/// Table 9-37 — `initValue` for ctxIdx of `res_scale_sign_flag` +/// (ctxIdx 0..1 / 2..3 / 4..5 for `initType` 0 / 1 / 2). +pub const TABLE_9_37_RES_SCALE_SIGN_FLAG: [u8; 6] = [154; 6]; + +/// Table 9-38 — `initValue` for ctxIdx of `palette_mode_flag`. +pub const TABLE_9_38_PALETTE_MODE_FLAG: [u8; 3] = [154, 154, 154]; + +/// Table 9-39 — `initValue` for ctxIdx of `tu_residual_act_flag`. +pub const TABLE_9_39_TU_RESIDUAL_ACT_FLAG: [u8; 3] = [154, 154, 154]; + +/// Table 9-40 — `initValue` for ctxIdx of `palette_run_prefix` (ctxIdx +/// 0..7 / 8..15 / 16..23 for `initType` 0 / 1 / 2). +pub const TABLE_9_40_PALETTE_RUN_PREFIX: [u8; 24] = [154; 24]; + +/// Table 9-41 — `initValue` for ctxIdx of +/// `copy_above_palette_indices_flag` and +/// `copy_above_indices_for_final_run_flag` (shared bank: Table 9-4 +/// assigns both elements ctxIdx 0 / 1 / 2 of this table). +pub const TABLE_9_41_PALETTE_COPY_ABOVE_FLAG: [u8; 3] = [154, 154, 154]; + +/// Table 9-42 — `initValue` for ctxIdx of `palette_transpose_flag`. +pub const TABLE_9_42_PALETTE_TRANSPOSE_FLAG: [u8; 3] = [154, 154, 154]; + +// --------------------------------------------------------------------- +// Table 9-4 ctxIdx-span selection helpers +// --------------------------------------------------------------------- + +/// Select the `N` per-`initType` `initValue` entries from a table +/// whose Table 9-4 mapping is the regular contiguous layout (ctxIdx +/// `0..N` / `N..2N` / `2N..3N` for `initType` 0 / 1 / 2). +/// +/// # Panics +/// +/// Panics when `init_type > 2` or `table.len() != 3 * N`. +#[must_use] +pub fn uniform_init_values(table: &[u8], init_type: u8) -> [u8; N] { + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); + assert_eq!(table.len(), 3 * N, "table is not a 3-initType layout"); + let base = N * init_type as usize; + core::array::from_fn(|i| table[base + i]) +} + +/// Select the `N` per-`initType` `initValue` entries from a table for +/// an inter-only element (Table 9-4 leaves `initType == 0` empty; +/// ctxIdx `0..N` / `N..2N` map to `initType` 1 / 2). Returns `None` +/// for `init_type == 0` — the element cannot occur in an I slice. +/// +/// # Panics +/// +/// Panics when `init_type > 2` or `table.len() != 2 * N`. +#[must_use] +pub fn inter_init_values(table: &[u8], init_type: u8) -> Option<[u8; N]> { + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); + assert_eq!(table.len(), 2 * N, "table is not a 2-initType layout"); + if init_type == 0 { + return None; + } + let base = N * (init_type as usize - 1); + Some(core::array::from_fn(|i| table[base + i])) +} + +/// The per-`initType` `sig_coeff_flag` `initValue` bank (44 entries): +/// the 42 §9.3.4.2.5 contexts from the Table 9-29 ctxIdx span +/// `42 * initType ..`, followed by the two equation 9-40 +/// transform-skip contexts (luma then chroma) from ctxIdx +/// `126 + 2 * initType ..`. Matches the +/// [`crate::residual::ResidualContexts`] bank layout (slots 42 / 43 +/// are the transform-skip contexts). +/// +/// # Panics +/// +/// Panics when `init_type > 2`. +#[must_use] +pub fn sig_coeff_flag_init_values(init_type: u8) -> [u8; 44] { + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); + let t = init_type as usize; + core::array::from_fn(|i| { + if i < 42 { + TABLE_9_29_SIG_COEFF_FLAG[42 * t + i] + } else { + TABLE_9_29_SIG_COEFF_FLAG[126 + 2 * t + (i - 42)] + } + }) +} + +/// Initialize an inter-only bank: table entries through +/// [`ContextModel::init`] for `initType` 1 / 2, the +/// [`ContextModel::terminate_state`] placeholder for `initType` 0 +/// (see the module docs). +fn inter_bank(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] { + match inter_init_values::(table, init_type) { + Some(values) => values.map(|v| ContextModel::init(v, slice_qp_y)), + None => [ContextModel::terminate_state(); N], + } +} + +/// Initialize a regular three-`initType` bank. +fn uniform_bank(table: &[u8], init_type: u8, slice_qp_y: i32) -> [ContextModel; N] { + uniform_init_values::(table, init_type).map(|v| ContextModel::init(v, slice_qp_y)) +} + +// --------------------------------------------------------------------- +// SliceContexts +// --------------------------------------------------------------------- + +/// The complete per-slice CABAC context array of §9.3.2.2 / Table 9-4: +/// one bank per syntax element (or per Table 9-4 shared-variable +/// group; see the module docs), each slot a `(pStateIdx, valMps)` +/// [`ContextModel`]. Bank-internal indices are the *bank-relative* +/// ctxIdx (the §9.3.4.2 `ctxInc` value), not the absolute Table 9-4 +/// ctxIdx. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SliceContexts { + /// `sao_merge_left_flag` / `sao_merge_up_flag` (Table 9-5, shared). + pub sao_merge_flag: [ContextModel; 1], + /// `sao_type_idx_luma` / `sao_type_idx_chroma` (Table 9-6, shared). + pub sao_type_idx: [ContextModel; 1], + /// `split_cu_flag` (Table 9-7). + pub split_cu_flag: [ContextModel; 3], + /// `cu_transquant_bypass_flag` (Table 9-8). + pub cu_transquant_bypass_flag: [ContextModel; 1], + /// `cu_skip_flag` (Table 9-9; inter-only). + pub cu_skip_flag: [ContextModel; 3], + /// `palette_mode_flag` (Table 9-38). + pub palette_mode_flag: [ContextModel; 1], + /// `pred_mode_flag` (Table 9-10; inter-only). + pub pred_mode_flag: [ContextModel; 1], + /// `part_mode` (Table 9-11; slot 0 only at `initType == 0`). + pub part_mode: [ContextModel; 4], + /// `prev_intra_luma_pred_flag` (Table 9-12). + pub prev_intra_luma_pred_flag: [ContextModel; 1], + /// `intra_chroma_pred_mode` (Table 9-13). + pub intra_chroma_pred_mode: [ContextModel; 1], + /// `rqt_root_cbf` (Table 9-14; inter-only). + pub rqt_root_cbf: [ContextModel; 1], + /// `merge_flag` (Table 9-15; inter-only). + pub merge_flag: [ContextModel; 1], + /// `merge_idx` (Table 9-16; inter-only). + pub merge_idx: [ContextModel; 1], + /// `inter_pred_idc` (Table 9-17; inter-only). + pub inter_pred_idc: [ContextModel; 5], + /// `ref_idx_l0` / `ref_idx_l1` (Table 9-18, shared; inter-only). + pub ref_idx: [ContextModel; 2], + /// `mvp_l0_flag` / `mvp_l1_flag` (Table 9-19, shared; inter-only). + pub mvp_flag: [ContextModel; 1], + /// `split_transform_flag` (Table 9-20). + pub split_transform_flag: [ContextModel; 3], + /// `cbf_luma` (Table 9-21). + pub cbf_luma: [ContextModel; 2], + /// `cbf_cb` / `cbf_cr` (Table 9-22, shared; slot 4 is the + /// Table 9-4 ctxIdx 12 / 13 / 14 fifth context). + pub cbf_chroma: [ContextModel; 5], + /// `abs_mvd_greater0_flag` (Table 9-23 ctxIdx 0 / 2; inter-only). + pub abs_mvd_greater0_flag: [ContextModel; 1], + /// `abs_mvd_greater1_flag` (Table 9-23 ctxIdx 1 / 3; inter-only). + pub abs_mvd_greater1_flag: [ContextModel; 1], + /// `tu_residual_act_flag` (Table 9-39). + pub tu_residual_act_flag: [ContextModel; 1], + /// `log2_res_scale_abs_plus1` (Table 9-36). + pub log2_res_scale_abs_plus1: [ContextModel; 8], + /// `res_scale_sign_flag` (Table 9-37). + pub res_scale_sign_flag: [ContextModel; 2], + /// `transform_skip_flag` (Table 9-25; slot 0 luma, slot 1 the + /// shared chroma context). + pub transform_skip_flag: [ContextModel; 2], + /// `explicit_rdpcm_flag` (Table 9-32; slot 0 luma, slot 1 the + /// shared chroma context; inter-only). + pub explicit_rdpcm_flag: [ContextModel; 2], + /// `explicit_rdpcm_dir_flag` (Table 9-33; same layout; inter-only). + pub explicit_rdpcm_dir_flag: [ContextModel; 2], + /// The §7.3.8.11 `residual_coding( )` banks (Tables 9-26..9-31). + pub residual: ResidualContexts, + /// `palette_run_prefix` (Table 9-40). + pub palette_run_prefix: [ContextModel; 8], + /// `copy_above_palette_indices_flag` / + /// `copy_above_indices_for_final_run_flag` (Table 9-41, shared). + pub palette_copy_above_flag: [ContextModel; 1], + /// `palette_transpose_flag` (Table 9-42). + pub palette_transpose_flag: [ContextModel; 1], + /// `cu_qp_delta_abs` (Table 9-24). + pub cu_qp_delta_abs: [ContextModel; 2], + /// `cu_chroma_qp_offset_flag` (Table 9-34). + pub cu_chroma_qp_offset_flag: [ContextModel; 1], + /// `cu_chroma_qp_offset_idx` (Table 9-35). + pub cu_chroma_qp_offset_idx: [ContextModel; 1], + /// §9.3.2.1 palette predictor variables (`PredictorPaletteSize` / + /// `PredictorPaletteEntries`) — parse state that initializes, + /// stores and synchronizes ALONGSIDE the context variables + /// (§9.3.2.3 / §9.3.2.4 / §9.3.2.5), so it travels inside this + /// struct. [`Self::init`] leaves it empty; the slice driver + /// assigns the PPS / SPS initializer-derived predictor at every + /// §9.3.2.2 re-initialization point. + pub palette_predictor: crate::palette::PalettePredictor, +} + +impl SliceContexts { + /// The number of distinct adapting context variables per + /// `initType` (shared Table 9-4 groups counted once). + pub const CONTEXT_COUNT: usize = 185; + + /// §9.3.2.2 initialization of the whole context array for one + /// `initType` (0, 1 or 2) and `SliceQpY` (equation 7-54). Every + /// table entry goes through [`ContextModel::init`] + /// (equations 9-4..9-6); inter-only banks at `initType == 0` take + /// the non-adapting placeholder described in the module docs. + /// + /// # Panics + /// + /// Panics when `init_type > 2`. + #[must_use] + pub fn init(init_type: u8, slice_qp_y: i32) -> Self { + assert!(init_type <= 2, "initType must be 0, 1 or 2 (equation 9-7)"); + let t = init_type as usize; + let init = |v: u8| ContextModel::init(v, slice_qp_y); + // Table 9-11 `part_mode`: ctxIdx 0 at initType 0, 1..4 / 5..8 + // at initType 1 / 2. + let part_mode = if init_type == 0 { + let mut bank = [ContextModel::terminate_state(); 4]; + bank[0] = init(TABLE_9_11_PART_MODE[0]); + bank + } else { + core::array::from_fn(|i| init(TABLE_9_11_PART_MODE[1 + 4 * (t - 1) + i])) + }; + // Table 9-22 `cbf_cb` / `cbf_cr`: ctxIdx 4t..4t+3 plus 12 + t. + let cbf_chroma = core::array::from_fn(|i| { + init(if i < 4 { + TABLE_9_22_CBF_CHROMA[4 * t + i] + } else { + TABLE_9_22_CBF_CHROMA[12 + t] + }) + }); + // Table 9-23 interleave: greater0 at ctxIdx 0 / 2, greater1 at + // ctxIdx 1 / 3 for initType 1 / 2. + let (abs_mvd_greater0_flag, abs_mvd_greater1_flag) = if init_type == 0 { + ( + [ContextModel::terminate_state(); 1], + [ContextModel::terminate_state(); 1], + ) + } else { + ( + [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1)])], + [init(TABLE_9_23_ABS_MVD_GREATER_FLAG[2 * (t - 1) + 1])], + ) + }; + // Table 9-25 `transform_skip_flag`: luma at ctxIdx t, the + // shared chroma context at ctxIdx 3 + t. + let transform_skip_flag = [ + init(TABLE_9_25_TRANSFORM_SKIP_FLAG[t]), + init(TABLE_9_25_TRANSFORM_SKIP_FLAG[3 + t]), + ]; + // Tables 9-32 / 9-33 (inter-only): luma at ctxIdx t − 1, the + // shared chroma context at ctxIdx 2 + (t − 1). + let rdpcm_bank = |table: &[u8; 4]| { + if init_type == 0 { + [ContextModel::terminate_state(); 2] + } else { + [init(table[t - 1]), init(table[2 + (t - 1)])] + } + }; + Self { + sao_merge_flag: uniform_bank(&TABLE_9_5_SAO_MERGE_FLAG, init_type, slice_qp_y), + sao_type_idx: uniform_bank(&TABLE_9_6_SAO_TYPE_IDX, init_type, slice_qp_y), + split_cu_flag: uniform_bank(&TABLE_9_7_SPLIT_CU_FLAG, init_type, slice_qp_y), + cu_transquant_bypass_flag: uniform_bank( + &TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG, + init_type, + slice_qp_y, + ), + cu_skip_flag: inter_bank(&TABLE_9_9_CU_SKIP_FLAG, init_type, slice_qp_y), + palette_mode_flag: uniform_bank(&TABLE_9_38_PALETTE_MODE_FLAG, init_type, slice_qp_y), + pred_mode_flag: inter_bank(&TABLE_9_10_PRED_MODE_FLAG, init_type, slice_qp_y), + part_mode, + prev_intra_luma_pred_flag: uniform_bank( + &TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG, + init_type, + slice_qp_y, + ), + intra_chroma_pred_mode: uniform_bank( + &TABLE_9_13_INTRA_CHROMA_PRED_MODE, + init_type, + slice_qp_y, + ), + rqt_root_cbf: inter_bank(&TABLE_9_14_RQT_ROOT_CBF, init_type, slice_qp_y), + merge_flag: inter_bank(&TABLE_9_15_MERGE_FLAG, init_type, slice_qp_y), + merge_idx: inter_bank(&TABLE_9_16_MERGE_IDX, init_type, slice_qp_y), + inter_pred_idc: inter_bank(&TABLE_9_17_INTER_PRED_IDC, init_type, slice_qp_y), + ref_idx: inter_bank(&TABLE_9_18_REF_IDX, init_type, slice_qp_y), + mvp_flag: inter_bank(&TABLE_9_19_MVP_FLAG, init_type, slice_qp_y), + split_transform_flag: uniform_bank( + &TABLE_9_20_SPLIT_TRANSFORM_FLAG, + init_type, + slice_qp_y, + ), + cbf_luma: uniform_bank(&TABLE_9_21_CBF_LUMA, init_type, slice_qp_y), + cbf_chroma, + abs_mvd_greater0_flag, + abs_mvd_greater1_flag, + tu_residual_act_flag: uniform_bank( + &TABLE_9_39_TU_RESIDUAL_ACT_FLAG, + init_type, + slice_qp_y, + ), + log2_res_scale_abs_plus1: uniform_bank( + &TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1, + init_type, + slice_qp_y, + ), + res_scale_sign_flag: uniform_bank( + &TABLE_9_37_RES_SCALE_SIGN_FLAG, + init_type, + slice_qp_y, + ), + transform_skip_flag, + explicit_rdpcm_flag: rdpcm_bank(&TABLE_9_32_EXPLICIT_RDPCM_FLAG), + explicit_rdpcm_dir_flag: rdpcm_bank(&TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG), + residual: ResidualContexts::init(init_type, slice_qp_y), + palette_run_prefix: uniform_bank(&TABLE_9_40_PALETTE_RUN_PREFIX, init_type, slice_qp_y), + palette_copy_above_flag: uniform_bank( + &TABLE_9_41_PALETTE_COPY_ABOVE_FLAG, + init_type, + slice_qp_y, + ), + palette_transpose_flag: uniform_bank( + &TABLE_9_42_PALETTE_TRANSPOSE_FLAG, + init_type, + slice_qp_y, + ), + cu_qp_delta_abs: uniform_bank(&TABLE_9_24_CU_QP_DELTA_ABS, init_type, slice_qp_y), + cu_chroma_qp_offset_flag: uniform_bank( + &TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG, + init_type, + slice_qp_y, + ), + cu_chroma_qp_offset_idx: uniform_bank( + &TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX, + init_type, + slice_qp_y, + ), + palette_predictor: crate::palette::PalettePredictor::default(), + } + } + + /// Initialize the context array for a slice: derives `initType` + /// from `slice_type` and `cabac_init_flag` per equation 9-7 + /// ([`init_type`]), then runs [`SliceContexts::init`]. + /// `cabac_init_flag` is the §7.3.6.1 header flag (inferred 0 when + /// absent — pass `false` for I slices or when + /// `cabac_init_present_flag == 0`); `slice_qp_y` is `SliceQpY` + /// per equation 7-54 (`26 + init_qp_minus26 + slice_qp_delta`). + #[must_use] + pub fn for_slice(slice_type: SliceType, cabac_init_flag: bool, slice_qp_y: i32) -> Self { + let raw = match slice_type { + SliceType::B => 0, + SliceType::P => 1, + SliceType::I => 2, + }; + Self::init(init_type(raw, cabac_init_flag), slice_qp_y) + } +} + +// --------------------------------------------------------------------- +// Tests +// --------------------------------------------------------------------- + +#[cfg(test)] +mod tests { + use super::*; + + /// Every table's printed ctxIdx span (Tables 9-5..9-42). + #[test] + fn table_shapes() { + assert_eq!(TABLE_9_5_SAO_MERGE_FLAG.len(), 3); + assert_eq!(TABLE_9_6_SAO_TYPE_IDX.len(), 3); + assert_eq!(TABLE_9_7_SPLIT_CU_FLAG.len(), 9); + assert_eq!(TABLE_9_8_CU_TRANSQUANT_BYPASS_FLAG.len(), 3); + assert_eq!(TABLE_9_9_CU_SKIP_FLAG.len(), 6); + assert_eq!(TABLE_9_10_PRED_MODE_FLAG.len(), 2); + assert_eq!(TABLE_9_11_PART_MODE.len(), 9); + assert_eq!(TABLE_9_12_PREV_INTRA_LUMA_PRED_FLAG.len(), 3); + assert_eq!(TABLE_9_13_INTRA_CHROMA_PRED_MODE.len(), 3); + assert_eq!(TABLE_9_14_RQT_ROOT_CBF.len(), 2); + assert_eq!(TABLE_9_15_MERGE_FLAG.len(), 2); + assert_eq!(TABLE_9_16_MERGE_IDX.len(), 2); + assert_eq!(TABLE_9_17_INTER_PRED_IDC.len(), 10); + assert_eq!(TABLE_9_18_REF_IDX.len(), 4); + assert_eq!(TABLE_9_19_MVP_FLAG.len(), 2); + assert_eq!(TABLE_9_20_SPLIT_TRANSFORM_FLAG.len(), 9); + assert_eq!(TABLE_9_21_CBF_LUMA.len(), 6); + assert_eq!(TABLE_9_22_CBF_CHROMA.len(), 15); + assert_eq!(TABLE_9_23_ABS_MVD_GREATER_FLAG.len(), 4); + assert_eq!(TABLE_9_24_CU_QP_DELTA_ABS.len(), 6); + assert_eq!(TABLE_9_25_TRANSFORM_SKIP_FLAG.len(), 6); + assert_eq!(TABLE_9_26_LAST_SIG_COEFF_X_PREFIX.len(), 54); + assert_eq!(TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX.len(), 54); + assert_eq!(TABLE_9_28_CODED_SUB_BLOCK_FLAG.len(), 12); + assert_eq!(TABLE_9_29_SIG_COEFF_FLAG.len(), 132); + assert_eq!(TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG.len(), 72); + assert_eq!(TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG.len(), 18); + assert_eq!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.len(), 4); + assert_eq!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.len(), 4); + assert_eq!(TABLE_9_34_CU_CHROMA_QP_OFFSET_FLAG.len(), 3); + assert_eq!(TABLE_9_35_CU_CHROMA_QP_OFFSET_IDX.len(), 3); + assert_eq!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1.len(), 24); + assert_eq!(TABLE_9_37_RES_SCALE_SIGN_FLAG.len(), 6); + assert_eq!(TABLE_9_38_PALETTE_MODE_FLAG.len(), 3); + assert_eq!(TABLE_9_39_TU_RESIDUAL_ACT_FLAG.len(), 3); + assert_eq!(TABLE_9_40_PALETTE_RUN_PREFIX.len(), 24); + assert_eq!(TABLE_9_41_PALETTE_COPY_ABOVE_FLAG.len(), 3); + assert_eq!(TABLE_9_42_PALETTE_TRANSPOSE_FLAG.len(), 3); + // The all-154 tables really are uniform. + assert!(TABLE_9_24_CU_QP_DELTA_ABS.iter().all(|&v| v == 154)); + assert!(TABLE_9_36_LOG2_RES_SCALE_ABS_PLUS1 + .iter() + .all(|&v| v == 154)); + assert!(TABLE_9_37_RES_SCALE_SIGN_FLAG.iter().all(|&v| v == 154)); + assert!(TABLE_9_40_PALETTE_RUN_PREFIX.iter().all(|&v| v == 154)); + // The all-139 tables (transform-skip / RDPCM group). + assert!(TABLE_9_25_TRANSFORM_SKIP_FLAG.iter().all(|&v| v == 139)); + assert!(TABLE_9_32_EXPLICIT_RDPCM_FLAG.iter().all(|&v| v == 139)); + assert!(TABLE_9_33_EXPLICIT_RDPCM_DIR_FLAG.iter().all(|&v| v == 139)); + } + + /// Tables 9-26 and 9-27 print identical values (the elements still + /// adapt independent variables). + #[test] + fn last_sig_coeff_tables_print_identically() { + assert_eq!( + TABLE_9_26_LAST_SIG_COEFF_X_PREFIX, + TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX + ); + } + + fn cm(p_state_idx: u8, val_mps: u8) -> ContextModel { + ContextModel { + p_state_idx, + val_mps, + } + } + + /// §9.3.2.2 derived `(pStateIdx, valMps)` pins across QPs for + /// elements drawn from regular three-`initType` tables. Expected + /// values hand-evaluated from equations 9-4..9-6 on the cited + /// table entries. + #[test] + fn derived_state_pins_uniform_tables() { + // Table 9-7 `split_cu_flag`, initType 0 slot 0 (initValue 139). + assert_eq!(SliceContexts::init(0, 0).split_cu_flag[0], cm(8, 1)); + assert_eq!(SliceContexts::init(0, 26).split_cu_flag[0], cm(0, 0)); + assert_eq!(SliceContexts::init(0, 51).split_cu_flag[0], cm(7, 0)); + // Table 9-7 `split_cu_flag`, initType 2 slot 0 (initValue 107). + assert_eq!(SliceContexts::init(2, 17).split_cu_flag[0], cm(7, 0)); + assert_eq!(SliceContexts::init(2, 26).split_cu_flag[0], cm(16, 0)); + assert_eq!(SliceContexts::init(2, 51).split_cu_flag[0], cm(39, 0)); + // Table 9-6 `sao_type_idx`, initType 0 (initValue 200): the + // valMps flip across the QP range. + assert_eq!(SliceContexts::init(0, 0).sao_type_idx[0], cm(15, 0)); + assert_eq!(SliceContexts::init(0, 26).sao_type_idx[0], cm(8, 1)); + assert_eq!(SliceContexts::init(0, 51).sao_type_idx[0], cm(31, 1)); + // Table 9-6 `sao_type_idx`, initType 2 (initValue 160): + // slopeIdx 10 ⇒ m == 5; the state barely moves with QP. + assert_eq!(SliceContexts::init(2, 0).sao_type_idx[0], cm(62, 0)); + assert_eq!(SliceContexts::init(2, 51).sao_type_idx[0], cm(62, 0)); + // Table 9-20 `split_transform_flag`, initType 2 slot 0 + // (initValue 224). + assert_eq!(SliceContexts::init(2, 0).split_transform_flag[0], cm(62, 0)); + assert_eq!( + SliceContexts::init(2, 37).split_transform_flag[0], + cm(22, 0) + ); + assert_eq!(SliceContexts::init(2, 51).split_transform_flag[0], cm(0, 0)); + // Table 9-21 `cbf_luma`, initType 0 slot 0 (initValue 111). + assert_eq!(SliceContexts::init(0, 17).cbf_luma[0], cm(24, 1)); + assert_eq!(SliceContexts::init(0, 51).cbf_luma[0], cm(7, 0)); + // QP clamp (equation 9-6 Clip3( 0, 51, SliceQpY )): out-of-range + // QPs pin to the endpoints. + assert_eq!( + SliceContexts::init(0, -7).cbf_luma[0], + SliceContexts::init(0, 0).cbf_luma[0] + ); + assert_eq!( + SliceContexts::init(0, 60).cbf_luma[0], + SliceContexts::init(0, 51).cbf_luma[0] + ); + } + + /// Pins for the inter-only banks (Table 9-4 `initType` 1 / 2 + /// columns). + #[test] + fn derived_state_pins_inter_tables() { + // Table 9-9 `cu_skip_flag`, initType 1 slot 0 (initValue 197). + assert_eq!(SliceContexts::init(1, 17).cu_skip_flag[0], cm(24, 0)); + assert_eq!(SliceContexts::init(1, 26).cu_skip_flag[0], cm(15, 0)); + assert_eq!(SliceContexts::init(1, 51).cu_skip_flag[0], cm(7, 1)); + // Table 9-16 `merge_idx`, initType 1 (initValue 122). + assert_eq!(SliceContexts::init(1, 0).merge_idx[0], cm(0, 1)); + assert_eq!(SliceContexts::init(1, 26).merge_idx[0], cm(16, 0)); + assert_eq!(SliceContexts::init(1, 51).merge_idx[0], cm(31, 0)); + // Table 9-17 `inter_pred_idc`, initType 1 slot 0 (initValue 95). + assert_eq!(SliceContexts::init(1, 26).inter_pred_idc[0], cm(7, 1)); + assert_eq!(SliceContexts::init(1, 51).inter_pred_idc[0], cm(23, 0)); + // The initType 2 column starts at the table's second span: + // Table 9-17 ctxIdx 5 also holds 95. + assert_eq!( + SliceContexts::init(2, 26).inter_pred_idc[0], + SliceContexts::init(1, 26).inter_pred_idc[0] + ); + // Table 9-23 interleave: `abs_mvd_greater0_flag` initType 2 + // reads ctxIdx 2 (initValue 169), `abs_mvd_greater1_flag` + // initType 1 reads ctxIdx 1 (initValue 198). + assert_eq!( + SliceContexts::init(2, 26).abs_mvd_greater0_flag[0], + cm(0, 1) + ); + assert_eq!( + SliceContexts::init(2, 51).abs_mvd_greater0_flag[0], + cm(7, 1) + ); + assert_eq!( + SliceContexts::init(1, 26).abs_mvd_greater1_flag[0], + cm(7, 0) + ); + assert_eq!( + SliceContexts::init(1, 51).abs_mvd_greater1_flag[0], + cm(15, 1) + ); + } + + /// Pins for the irregular Table 9-4 layouts (`part_mode`, + /// `cbf_cb`/`cbf_cr`). + #[test] + fn derived_state_pins_irregular_tables() { + // Table 9-11 `part_mode` initType 0: only ctxIdx 0 + // (initValue 184) is initialized; slots 1..3 take the + // non-adapting placeholder. + let i_slice = SliceContexts::init(0, 26); + assert_eq!(i_slice.part_mode[0], cm(0, 1)); + for slot in 1..4 { + assert_eq!(i_slice.part_mode[slot], ContextModel::terminate_state()); + } + assert_eq!(SliceContexts::init(0, 0).part_mode[0], cm(15, 0)); + assert_eq!(SliceContexts::init(0, 51).part_mode[0], cm(15, 1)); + // `part_mode` initType 1 slot 1 reads Table 9-11 ctxIdx 2 + // (initValue 139); initType 2 slot 1 reads ctxIdx 6 (also 139). + assert_eq!(SliceContexts::init(1, 26).part_mode[1], cm(0, 0)); + assert_eq!( + SliceContexts::init(2, 26).part_mode[1], + SliceContexts::init(1, 26).part_mode[1] + ); + // Table 9-22 `cbf_cb`/`cbf_cr` initType 0: slot 0 reads ctxIdx 0 + // (initValue 94), slot 4 reads ctxIdx 12 (initValue 154). + assert_eq!(SliceContexts::init(0, 0).cbf_chroma[0], cm(32, 1)); + assert_eq!(SliceContexts::init(0, 26).cbf_chroma[0], cm(0, 0)); + assert_eq!(SliceContexts::init(0, 51).cbf_chroma[0], cm(31, 0)); + for qp in [0, 26, 51] { + // initValue 154 ⇒ m == 0, n == 64 ⇒ preCtxState == 64 at + // every QP: pStateIdx 0, valMps 1. + assert_eq!(SliceContexts::init(0, qp).cbf_chroma[4], cm(0, 1)); + } + // Table 9-25 `transform_skip_flag` (initValue 139 everywhere): + // luma and chroma slots agree at each initType. + let b = SliceContexts::init(2, 26); + assert_eq!(b.transform_skip_flag[0], b.transform_skip_flag[1]); + assert_eq!(b.transform_skip_flag[0], cm(0, 0)); + } + + /// Whole-array smoke test per `initType`: every table-derived + /// context lands in the equations-9-4..9-6 range + /// (`pStateIdx <= 62`), and the `initType == 0` placeholder + /// (`pStateIdx == 63`) appears exactly on the inter-only banks. + #[test] + fn whole_array_smoke_per_init_type() { + for init_type in 0u8..=2 { + for qp in [0, 26, 51] { + let ctx = SliceContexts::init(init_type, qp); + let inter_only: Vec<&[ContextModel]> = vec![ + &ctx.cu_skip_flag, + &ctx.pred_mode_flag, + &ctx.rqt_root_cbf, + &ctx.merge_flag, + &ctx.merge_idx, + &ctx.inter_pred_idc, + &ctx.ref_idx, + &ctx.mvp_flag, + &ctx.abs_mvd_greater0_flag, + &ctx.abs_mvd_greater1_flag, + &ctx.explicit_rdpcm_flag, + &ctx.explicit_rdpcm_dir_flag, + ]; + let every_type: Vec<&[ContextModel]> = vec![ + &ctx.sao_merge_flag, + &ctx.sao_type_idx, + &ctx.split_cu_flag, + &ctx.cu_transquant_bypass_flag, + &ctx.palette_mode_flag, + &ctx.prev_intra_luma_pred_flag, + &ctx.intra_chroma_pred_mode, + &ctx.split_transform_flag, + &ctx.cbf_luma, + &ctx.cbf_chroma, + &ctx.tu_residual_act_flag, + &ctx.log2_res_scale_abs_plus1, + &ctx.res_scale_sign_flag, + &ctx.transform_skip_flag, + &ctx.residual.last_sig_coeff_x_prefix, + &ctx.residual.last_sig_coeff_y_prefix, + &ctx.residual.coded_sub_block_flag, + &ctx.residual.sig_coeff_flag, + &ctx.residual.coeff_abs_level_greater1_flag, + &ctx.residual.coeff_abs_level_greater2_flag, + &ctx.palette_run_prefix, + &ctx.palette_copy_above_flag, + &ctx.palette_transpose_flag, + &ctx.cu_qp_delta_abs, + &ctx.cu_chroma_qp_offset_flag, + &ctx.cu_chroma_qp_offset_idx, + ]; + let mut total = 0usize; + for bank in &every_type { + for c in bank.iter() { + assert!(c.p_state_idx <= 62, "table-derived state out of range"); + assert!(c.val_mps <= 1); + total += 1; + } + } + // `part_mode` slot 0 is table-derived at every + // initType; slots 1..3 only for initType 1 / 2. + assert!(ctx.part_mode[0].p_state_idx <= 62); + total += 4; + for bank in &inter_only { + for c in bank.iter() { + if init_type == 0 { + assert_eq!(*c, ContextModel::terminate_state()); + } else { + assert!(c.p_state_idx <= 62); + } + total += 1; + } + } + if init_type == 0 { + for slot in 1..4 { + assert_eq!(ctx.part_mode[slot], ContextModel::terminate_state()); + } + } else { + for slot in 1..4 { + assert!(ctx.part_mode[slot].p_state_idx <= 62); + } + } + assert_eq!(total, SliceContexts::CONTEXT_COUNT); + } + } + } + + /// Equation 9-7 routing through [`SliceContexts::for_slice`]: the + /// `cabac_init_flag` swap between P and B, and its irrelevance for + /// I slices. + #[test] + fn for_slice_eq_9_7_routing() { + let qp = 30; + assert_eq!( + SliceContexts::for_slice(SliceType::I, false, qp), + SliceContexts::init(0, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::I, true, qp), + SliceContexts::init(0, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::P, false, qp), + SliceContexts::init(1, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::P, true, qp), + SliceContexts::init(2, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::B, false, qp), + SliceContexts::init(2, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::B, true, qp), + SliceContexts::init(1, qp) + ); + // P with the flag and B without select the same array; P + // without and B with likewise. + assert_eq!( + SliceContexts::for_slice(SliceType::P, true, qp), + SliceContexts::for_slice(SliceType::B, false, qp) + ); + assert_eq!( + SliceContexts::for_slice(SliceType::P, false, qp), + SliceContexts::for_slice(SliceType::B, true, qp) + ); + // The three initTypes produce three distinct arrays. + assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(1, qp)); + assert_ne!(SliceContexts::init(1, qp), SliceContexts::init(2, qp)); + assert_ne!(SliceContexts::init(0, qp), SliceContexts::init(2, qp)); + } + + /// The span-selection helpers reject malformed inputs and slice + /// the right ctxIdx ranges. + #[test] + fn span_selection_helpers() { + assert_eq!( + uniform_init_values::<3>(&TABLE_9_7_SPLIT_CU_FLAG, 1), + [107, 139, 126] + ); + assert_eq!( + inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 2), + Some([197, 185, 201]) + ); + assert_eq!(inter_init_values::<3>(&TABLE_9_9_CU_SKIP_FLAG, 0), None); + let sig0 = sig_coeff_flag_init_values(0); + assert_eq!(sig0[0], 111); + assert_eq!(sig0[41], 111); + // The transform-skip tail: Table 9-29 ctxIdx 126 / 127. + assert_eq!(sig0[42], 141); + assert_eq!(sig0[43], 111); + let sig1 = sig_coeff_flag_init_values(1); + assert_eq!(sig1[0], 155); + assert_eq!(sig1[41], 140); + let sig2 = sig_coeff_flag_init_values(2); + assert_eq!(sig2[0], 170); + assert_eq!(sig2[41], 140); + } + + #[test] + #[should_panic(expected = "initType must be 0, 1 or 2")] + fn init_rejects_init_type_3() { + let _ = SliceContexts::init(3, 26); + } +} diff --git a/vendor/oxideav-h265/src/deblock.rs b/vendor/oxideav-h265/src/deblock.rs new file mode 100644 index 0000000..ac01a45 --- /dev/null +++ b/vendor/oxideav-h265/src/deblock.rs @@ -0,0 +1,2484 @@ +//! §8.7.2.4 — derivation of the deblocking boundary filtering strength. +//! +//! The deblocking filter (§8.7.2) operates on an 8×8 luma grid: vertical +//! edges first, then horizontal edges. For each candidate edge segment +//! the boundary filtering strength `bS ∈ {0, 1, 2}` is derived per +//! §8.7.2.4 from the intra/inter mode, the transform coded-block flags, +//! and the motion vectors / reference pictures of the two prediction +//! blocks straddling the edge. This module implements that derivation — +//! [`derive_boundary_strength`] — reading the per-4×4-block motion / mode +//! state from a [`crate::motion::MotionField`]. +//! +//! The §8.7.2.2 / §8.7.2.3 edge-flag derivation (which marks the +//! transform-block / prediction-block boundaries an edge falls on, from +//! the coding / transform tree geometry) is the input `edgeFlags` array; +//! producing it from the decoded partition tree is the picture driver's +//! follow-up. The §8.7.2.5 edge filtering process (the actual sample +//! modification using `bS`, `β` and `tC`) is implemented by the +//! per-sample primitives [`luma_beta_tc`] (§8.7.2.5.3 β/tC, Table 8-12 +//! via [`beta_prime`] / [`tc_prime`]), [`luma_sample_decision`] +//! (§8.7.2.5.6), [`luma_edge_decision`] (§8.7.2.5.3 `dE`/`dEp`/`dEq`) +//! and [`filter_luma_sample`] (§8.7.2.5.7 strong/weak), plus the chroma +//! path [`chroma_tc`] (§8.7.2.5.5, Table 8-10 via [`chroma_qpc_420`]) +//! and [`filter_chroma_sample`] (§8.7.2.5.8). The plane-level block-edge +//! drivers [`filter_luma_block_edge`] (§8.7.2.5.4) and +//! [`filter_chroma_block_edge`] (§8.7.2.5.5) gather/apply those +//! primitives across a 4-row edge segment of a [`SamplePlane`] in place. + +use crate::binarization::PartMode; +use crate::motion::MotionField; +use crate::picture::{sub_wh_c, Picture, Plane}; + +/// §8.7.2.1 — the edge orientation being filtered. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum EdgeType { + /// `EDGE_VER` — a vertical edge (filtered left-to-right). + Vertical, + /// `EDGE_HOR` — a horizontal edge (filtered top-to-bottom). + Horizontal, +} + +/// The transform-tree split geometry of one luma coding block, used by the +/// §8.7.2.2 edge-flag derivation. +/// +/// Each node is either a `Split` (a `split_transform_flag == 1` node whose +/// four quadrants recurse) or a `Leaf` (a `split_transform_flag == 0` +/// transform block). The deblocker only needs the split structure, not the +/// residual coefficients — the leaves mark where transform-block edges +/// fall on the 8×8 grid. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransformSplit { + /// A `split_transform_flag == 1` node: four quadrants in raster order + /// (top-left, top-right, bottom-left, bottom-right), each spanning + /// `1 << (log2TrafoSize − 1)` luma samples. + Split(Box<[TransformSplit; 4]>), + /// A `split_transform_flag == 0` transform-block leaf. + Leaf, +} + +impl TransformSplit { + /// A leaf spanning the whole coding block (no transform split). + #[inline] + #[must_use] + pub fn leaf() -> Self { + TransformSplit::Leaf + } + + /// A single-level split into four equal quadrants, each a leaf. + #[inline] + #[must_use] + pub fn split_once() -> Self { + TransformSplit::Split(Box::new([ + TransformSplit::Leaf, + TransformSplit::Leaf, + TransformSplit::Leaf, + TransformSplit::Leaf, + ])) + } + + /// Map a parsed §7.3.8.8 [`crate::transform_tree::TransformTree`] to the + /// deblocking transform-split structure the §8.7.2.2 transform-block + /// boundary recursion consumes (only the split topology matters, not the + /// per-leaf residual). A CU with no transform tree (skip / `rqt_root_cbf + /// == 0`) is a single whole-CB leaf. + #[must_use] + pub fn from_tree(tree: Option<&crate::transform_tree::TransformTree>) -> Self { + use crate::transform_tree::TransformTree; + match tree { + None | Some(TransformTree::Leaf { .. }) => TransformSplit::Leaf, + Some(TransformTree::Split { children, .. }) => TransformSplit::Split(Box::new([ + Self::from_tree(Some(&children[0])), + Self::from_tree(Some(&children[1])), + Self::from_tree(Some(&children[2])), + Self::from_tree(Some(&children[3])), + ])), + } + } +} + +/// The invariant context threaded through the §8.7.2.2 recursion. +struct TbBoundaryCtx<'a> { + filter_edge_flag: bool, + edge_type: EdgeType, + n_cbs: usize, + edge_flags: &'a mut [bool], + tb_edge: &'a mut [bool], +} + +/// §8.7.2.2 transform-block-boundary recursion: walk one node of the +/// transform tree, marking the `edge_flags` (any block boundary the edge +/// falls on) and `tb_edge` (transform-block boundaries only) grids. +/// +/// `(xb0, yb0)` is the node's top-left luma sample relative to the coding +/// block; `log2_trafo_size` is the node side. The `ctx.filter_edge_flag` +/// is the §8.7.2.1 `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` that +/// gates the coding-block boundary (xB0/yB0 == 0) edge. +fn transform_block_boundary( + node: &TransformSplit, + xb0: usize, + yb0: usize, + log2_trafo_size: u32, + ctx: &mut TbBoundaryCtx<'_>, +) { + if let TransformSplit::Split(children) = node { + let half = 1usize << (log2_trafo_size - 1); + let xb1 = xb0 + half; + let yb1 = yb0 + half; + let quad_origins = [(xb0, yb0), (xb1, yb0), (xb0, yb1), (xb1, yb1)]; + for (child, &(cx, cy)) in children.iter().zip(quad_origins.iter()) { + transform_block_boundary(child, cx, cy, log2_trafo_size - 1, ctx); + } + return; + } + // Leaf: mark the leading edge of this transform block. EDGE_VER marks + // the column xB0 for k = 0..size; EDGE_HOR marks the row yB0. + let size = 1usize << log2_trafo_size; + let n_cbs = ctx.n_cbs; + match ctx.edge_type { + EdgeType::Vertical => { + // edgeFlags[xB0][yB0+k]: filterEdgeFlag at the CB boundary + // (xB0 == 0), else 1. + let val = if xb0 == 0 { ctx.filter_edge_flag } else { true }; + for k in 0..size { + let idx = (yb0 + k) * n_cbs + xb0; + ctx.edge_flags[idx] = val; + ctx.tb_edge[idx] = val; + } + } + EdgeType::Horizontal => { + let val = if yb0 == 0 { ctx.filter_edge_flag } else { true }; + for k in 0..size { + let idx = yb0 * n_cbs + (xb0 + k); + ctx.edge_flags[idx] = val; + ctx.tb_edge[idx] = val; + } + } + } +} + +/// §8.7.2.3 prediction-block-boundary derivation: mark the internal +/// prediction-partition edge of a coding block into `edge_flags` (a +/// prediction edge is *not* a transform-block edge, so `tb_edge` is left +/// untouched). +fn prediction_block_boundary( + part_mode: PartMode, + log2_cb_size: u32, + edge_type: EdgeType, + n_cbs: usize, + edge_flags: &mut [bool], +) { + // The internal partition column (EDGE_VER) / row (EDGE_HOR), if any. + let half = 1usize << (log2_cb_size - 1); + let quarter = 1usize << (log2_cb_size.saturating_sub(2)); + let pos = match (edge_type, part_mode) { + (EdgeType::Vertical, PartMode::PartNx2N | PartMode::PartNxN) => Some(half), + (EdgeType::Vertical, PartMode::PartNLx2N) => Some(quarter), + (EdgeType::Vertical, PartMode::PartNRx2N) => Some(3 * quarter), + (EdgeType::Horizontal, PartMode::Part2NxN | PartMode::PartNxN) => Some(half), + (EdgeType::Horizontal, PartMode::Part2NxnU) => Some(quarter), + (EdgeType::Horizontal, PartMode::Part2NxnD) => Some(3 * quarter), + _ => None, + }; + if let Some(p) = pos { + for k in 0..n_cbs { + let idx = match edge_type { + EdgeType::Vertical => k * n_cbs + p, + EdgeType::Horizontal => p * n_cbs + k, + }; + edge_flags[idx] = true; + } + } +} + +/// The §8.7.2.2 / §8.7.2.3 edge-flag grids for one coding block. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EdgeFlags { + n_cbs: usize, + /// Row-major `n_cbs²`, `true` where a transform / prediction block + /// boundary falls (the §8.7.2.4 bS input). + edge_flags: Vec, + /// Row-major `n_cbs²`, `true` where the edge is *also* a + /// transform-block boundary (the §8.7.2.4 second-bullet `cbf` test). + tb_edge: Vec, +} + +impl EdgeFlags { + /// The `edge_flags` grid (row-major, `[y * nCbS + x]`). + #[inline] + #[must_use] + pub fn edge_flags(&self) -> &[bool] { + &self.edge_flags + } + + /// The `tb_edge` grid (row-major, `[y * nCbS + x]`). + #[inline] + #[must_use] + pub fn tb_edge(&self) -> &[bool] { + &self.tb_edge + } + + /// `edge_flags[x][y]`. + #[inline] + #[must_use] + pub fn edge_at(&self, x: usize, y: usize) -> bool { + self.edge_flags[y * self.n_cbs + x] + } + + /// `tb_edge[x][y]`. + #[inline] + #[must_use] + pub fn tb_at(&self, x: usize, y: usize) -> bool { + self.tb_edge[y * self.n_cbs + x] + } +} + +/// §8.7.2.2 + §8.7.2.3 — derive the `edge_flags` + `tb_edge` grids for one +/// coding block in one edge direction. +/// +/// `transform_split` is the coding block's transform-tree split geometry +/// ([`TransformSplit`]); `part_mode` is the prediction `PartMode`; +/// `log2_cb_size` is the luma coding-block side; `filter_edge_flag` is the +/// §8.7.2.1 `filterLeftCbEdgeFlag` (EDGE_VER) / `filterTopCbEdgeFlag` +/// (EDGE_HOR) gating the coding-block boundary edge. +/// +/// The result feeds [`derive_boundary_strength`] (`edge_flags` + `tb_edge`) +/// and, after bS, the §8.7.2.5.1 / .2 CU edge filtering driver. +#[must_use] +pub fn derive_edge_flags( + transform_split: &TransformSplit, + part_mode: PartMode, + log2_cb_size: u32, + edge_type: EdgeType, + filter_edge_flag: bool, +) -> EdgeFlags { + let n_cbs = 1usize << log2_cb_size; + let mut edge_flags = vec![false; n_cbs * n_cbs]; + let mut tb_edge = vec![false; n_cbs * n_cbs]; + { + let mut ctx = TbBoundaryCtx { + filter_edge_flag, + edge_type, + n_cbs, + edge_flags: &mut edge_flags, + tb_edge: &mut tb_edge, + }; + transform_block_boundary(transform_split, 0, 0, log2_cb_size, &mut ctx); + } + prediction_block_boundary(part_mode, log2_cb_size, edge_type, n_cbs, &mut edge_flags); + EdgeFlags { + n_cbs, + edge_flags, + tb_edge, + } +} + +/// The §8.7.2.4 boundary filtering strength for one CU's edges, a +/// `(nCbS)×(nCbS)` grid indexed in luma samples (only the §8.7.2.4 +/// sampled positions `xDi`/`yDj` carry meaningful values; the rest are 0). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct BoundaryStrength { + n_cbs: usize, + /// Row-major `n_cbs * n_cbs`, `bs[y * n_cbs + x]`. + bs: Vec, +} + +impl BoundaryStrength { + /// `bS[x][y]` at luma offset `(x, y)` within the coding block. + /// + /// # Panics + /// Panics if `(x, y)` lies outside the `(nCbS)×(nCbS)` block. + #[must_use] + pub fn at(&self, x: usize, y: usize) -> u8 { + self.bs[y * self.n_cbs + x] + } + + /// The coding-block side `nCbS` in luma samples. + #[inline] + #[must_use] + pub fn n_cbs(&self) -> usize { + self.n_cbs + } +} + +/// Whether the §8.7.2.4 "different reference pictures or different number +/// of motion vectors" predicate holds between the p- and q-side blocks. +/// +/// The reference-picture comparison uses the picture identities +/// (`ref_poc_lX`), not the `RefIdxLX` list positions, and is order- and +/// list-independent (spec NOTE 1): block p uses reference-picture set +/// `{ p.l0?, p.l1? }`, block q uses `{ q.l0?, q.l1? }`. +fn different_refs_or_count(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool { + let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1); + let q_count = u8::from(q.pred_flag_l0) + u8::from(q.pred_flag_l1); + if p_count != q_count { + return true; + } + // Compare the *sets* of reference pictures (POCs), list-independent. + let mut p_refs = Vec::new(); + if p.pred_flag_l0 { + p_refs.push(p.ref_poc_l0); + } + if p.pred_flag_l1 { + p_refs.push(p.ref_poc_l1); + } + let mut q_refs = Vec::new(); + if q.pred_flag_l0 { + q_refs.push(q.ref_poc_l0); + } + if q.pred_flag_l1 { + q_refs.push(q.ref_poc_l1); + } + p_refs.sort_unstable(); + q_refs.sort_unstable(); + p_refs != q_refs +} + +/// `|a − b| >= 4` on either component (the §8.7.2.4 quarter-luma-sample +/// MV-difference test). +#[inline] +fn mv_diff_ge4(a: [i32; 2], b: [i32; 2]) -> bool { + (a[0] - b[0]).abs() >= 4 || (a[1] - b[1]).abs() >= 4 +} + +/// §8.7.2.4 motion-only bS test for two inter prediction blocks `p` / `q` +/// (the third bullet onward: same/different references, MV differences). +/// Returns `true` when bS should be 1 on motion grounds. +fn motion_bs_is_one(p: &crate::motion::MotionCell, q: &crate::motion::MotionCell) -> bool { + // Bullet 1: different reference pictures or different number of MVs. + if different_refs_or_count(p, q) { + return true; + } + + let p_count = u8::from(p.pred_flag_l0) + u8::from(p.pred_flag_l1); + + // Bullet 2: one MV each, |Δmv| >= 4. + if p_count == 1 { + let pmv = if p.pred_flag_l0 { p.mv_l0 } else { p.mv_l1 }; + let qmv = if q.pred_flag_l0 { q.mv_l0 } else { q.mv_l1 }; + return mv_diff_ge4(pmv, qmv); + } + + // Two MVs each (p_count == 2). The reference-picture sets are equal + // (different_refs_or_count returned false). + if p.ref_poc_l0 != p.ref_poc_l1 { + // Bullet 3: two different reference pictures. Match each list to + // the q-side list referencing the same picture. + // p.l0 ↔ q.(list with same poc as p.l0), p.l1 ↔ the other. + let (q0, q1) = if q.ref_poc_l0 == p.ref_poc_l0 { + (q.mv_l0, q.mv_l1) + } else { + (q.mv_l1, q.mv_l0) + }; + mv_diff_ge4(p.mv_l0, q0) || mv_diff_ge4(p.mv_l1, q1) + } else { + // Bullet 4: both MVs use the same reference picture. bS = 1 iff + // (|Δl0| or |Δl1| >= 4) AND (|p.l0−q.l1| or |p.l1−q.l0| >= 4). + let straight = mv_diff_ge4(p.mv_l0, q.mv_l0) || mv_diff_ge4(p.mv_l1, q.mv_l1); + let crossed = mv_diff_ge4(p.mv_l0, q.mv_l1) || mv_diff_ge4(p.mv_l1, q.mv_l0); + straight && crossed + } +} + +/// §8.7.2.4 — derive the `(nCbS)×(nCbS)` boundary filtering strength grid +/// for one luma coding block. +/// +/// Inputs: +/// * `field` — the picture's per-4×4-block motion / mode store +/// ([`MotionField`]); the p / q sample look-ups read from it. +/// * `(x_cb, y_cb)` — the coding block's luma top-left position. +/// * `log2_cb_size` — the coding-block side `log2CbSize`. +/// * `edge_type` — `EDGE_VER` or `EDGE_HOR`. +/// * `edge_flags` — the §8.7.2.2/§8.7.2.3 `(nCbS)×(nCbS)` edge-flag grid +/// (row-major, `edge_flags[y * nCbS + x]`), `true` where a transform / +/// prediction block boundary falls. +/// * `tb_edge` — `(nCbS)×(nCbS)` grid, `true` where the edge at that +/// position is *also* a transform-block edge (the §8.7.2.4 second +/// bullet `cbf` test only fires on transform-block edges). +/// +/// The bS at every sampled `(xDi, yDj)` is 2 when either neighbouring +/// sample is intra; 1 when the edge is a transform-block edge and either +/// transform block holds a non-zero coefficient; 1 on the §8.7.2.4 +/// motion criteria; otherwise 0. Positions not sampled by §8.7.2.4 are 0. +/// +/// # Panics +/// Panics if `edge_flags` / `tb_edge` are not `(1 << log2_cb_size)`² +/// long, or if a sampled p / q location falls outside `field`. +pub fn derive_boundary_strength( + field: &MotionField, + x_cb: usize, + y_cb: usize, + log2_cb_size: u32, + edge_type: EdgeType, + edge_flags: &[bool], + tb_edge: &[bool], +) -> BoundaryStrength { + let n_cbs = 1usize << log2_cb_size; + assert_eq!(edge_flags.len(), n_cbs * n_cbs, "edge_flags is nCbS^2"); + assert_eq!(tb_edge.len(), n_cbs * n_cbs, "tb_edge is nCbS^2"); + let mut bs = vec![0u8; n_cbs * n_cbs]; + + // §8.7.2.4 sampling grid: EDGE_VER strides 8 in x, 4 in y; EDGE_HOR + // strides 4 in x, 8 in y. + let (step_x, step_y) = match edge_type { + EdgeType::Vertical => (8usize, 4usize), + EdgeType::Horizontal => (4usize, 8usize), + }; + + let mut y_dj = 0; + while y_dj < n_cbs { + let mut x_di = 0; + while x_di < n_cbs { + let idx = y_dj * n_cbs + x_di; + if edge_flags[idx] { + // p0 / q0 sample positions (§8.7.2.4). + let (px, py, qx, qy) = match edge_type { + EdgeType::Vertical => (x_cb + x_di - 1, y_cb + y_dj, x_cb + x_di, y_cb + y_dj), + EdgeType::Horizontal => { + (x_cb + x_di, y_cb + y_dj - 1, x_cb + x_di, y_cb + y_dj) + } + }; + let p = field.cell_at(px, py); + let q = field.cell_at(qx, qy); + + // §8.7.2.4 cascade: intra ⇒ 2; else a coded-coeff + // transform-block edge OR the motion criteria ⇒ 1; else 0. + let coeff_edge = tb_edge[idx] && (p.has_nonzero_coeff || q.has_nonzero_coeff); + let val = if p.is_intra || q.is_intra { + 2 + } else if coeff_edge || motion_bs_is_one(&p, &q) { + 1 + } else { + 0 + }; + bs[idx] = val; + } + x_di += step_x; + } + y_dj += step_y; + } + + BoundaryStrength { n_cbs, bs } +} + +/// Table 8-12 — `β′` as a function of the input variable `Q` (0..=51). +/// +/// The deblocking threshold `β′` is 0 for `Q < 16`, then rises in the +/// pattern documented in Table 8-12. `Q` outside `0..=51` returns the +/// boundary value (the callers clip `Q` to `0..=51` for `β′`, eq. 8-348). +#[must_use] +pub fn beta_prime(q: i32) -> i32 { + const BETA: [i32; 52] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // Q 0..15 + 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 22, 24, // Q 16..31 + 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, // Q 32..47 + 58, 60, 62, 64, // Q 48..51 + ]; + BETA[q.clamp(0, 51) as usize] +} + +/// Table 8-12 — `tC′` as a function of the input variable `Q` (0..=53). +/// +/// The clipping threshold `tC′` is 0 for `Q <= 17`, `1` at `Q = 18`, +/// then rises per Table 8-12 up to `24` at `Q = 53`. `Q` outside +/// `0..=53` returns the boundary value (callers clip `Q` to `0..=53`, +/// eqs. 8-350 / 8-383). +#[must_use] +pub fn tc_prime(q: i32) -> i32 { + const TC: [i32; 54] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, // Q 0..18 + 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, // Q 19..37 + 5, 5, 6, 6, 7, 8, 9, 10, 11, 13, 14, 16, 18, 20, 22, 24, // Q 38..53 + ]; + TC[q.clamp(0, 53) as usize] +} + +/// §8.7.2.5.3 — derive `β` and `tC` for a luma block edge. +/// +/// `qp_q` / `qp_p` are the `QpY` values of the coding units containing +/// the `q0,0` and `p0,0` samples; `bs` is the §8.7.2.4 boundary strength +/// (must be 1 or 2 for a filtered edge); `beta_offset_div2` / +/// `tc_offset_div2` are the per-slice `slice_beta_offset_div2` / +/// `slice_tc_offset_div2` syntax-element values; `bit_depth` is +/// `BitDepthY`. +/// +/// Returns `(β, tC)` per eqs. 8-347..8-351. +#[must_use] +pub fn luma_beta_tc( + qp_q: i32, + qp_p: i32, + bs: u8, + beta_offset_div2: i32, + tc_offset_div2: i32, + bit_depth: u8, +) -> (i32, i32) { + let qp_l = (qp_q + qp_p + 1) >> 1; // eq. 8-347 + let q_beta = (qp_l + (beta_offset_div2 << 1)).clamp(0, 51); // eq. 8-348 + let beta = beta_prime(q_beta) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-349 + let q_tc = (qp_l + 2 * (i32::from(bs) - 1) + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-350 + let tc = tc_prime(q_tc) * (1 << (i32::from(bit_depth) - 8)); // eq. 8-351 + (beta, tc) +} + +/// §8.7.2.5.6 — decision process for a luma sample. +/// +/// Returns `dSam`: `true` (1) when the long (strong) filter conditions +/// across `p0`/`p3`/`q0`/`q3` hold, given `dpq`, `β` and `tC`. +#[inline] +#[must_use] +pub fn luma_sample_decision( + p0: i32, + p3: i32, + q0: i32, + q3: i32, + dpq: i32, + beta: i32, + tc: i32, +) -> bool { + dpq < (beta >> 2) + && (p3 - p0).abs() + (q0 - q3).abs() < (beta >> 3) + && (p0 - q0).abs() < (5 * tc + 1) >> 1 +} + +/// Decisions emitted by the §8.7.2.5.3 luma edge decision process for a +/// 4-row edge segment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LumaEdgeDecision { + /// `dE`: 0 = no filtering, 1 = weak (normal), 2 = strong (long). + pub de: u8, + /// `dEp`: when 1, the `p1` sample is also filtered (weak filter). + pub dep: u8, + /// `dEq`: when 1, the `q1` sample is also filtered (weak filter). + pub deq: u8, + /// `β` (eq. 8-349). + pub beta: i32, + /// `tC` (eq. 8-351). + pub tc: i32, +} + +/// The result of §8.7.2.5.7 luma-sample filtering for one boundary row. +/// +/// `p[i]` / `q[i]` are the filtered sample values (`pi'` / `qj'`); only +/// the first `ndp` `p[]` and `ndq` `q[]` entries are valid replacements +/// for the input samples. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LumaFilterOut { + /// `nDp` — number of filtered samples on the p side (0..=3). + pub ndp: usize, + /// `nDq` — number of filtered samples on the q side (0..=3). + pub ndq: usize, + /// `p0'`, `p1'`, `p2'` (only `0..ndp` valid). + pub p: [i32; 3], + /// `q0'`, `q1'`, `q2'` (only `0..ndq` valid). + pub q: [i32; 3], +} + +/// §8.7.2.5.7 — filtering process for a luma sample row. +/// +/// `p` / `q` are the four samples each side of the boundary (`p[0]` is +/// `p0`, closest to the edge); `dec` carries `dE` / `dEp` / `dEq` and +/// `tC`; `bit_depth` is `BitDepthY` for the final `Clip1Y`. +/// +/// Strong filtering (`dE == 2`) writes `p0'..p2'` / `q0'..q2'`; weak +/// filtering (`dE == 1`) writes `p0'` (+`p1'` when `dEp`) and `q0'` +/// (+`q1'` when `dEq`). The PCM / transquant-bypass / palette +/// suppressions are applied by the caller (they need per-CU state). +#[must_use] +pub fn filter_luma_sample( + p: [i32; 4], + q: [i32; 4], + de: u8, + dep: u8, + deq: u8, + tc: i32, + bit_depth: u8, +) -> LumaFilterOut { + let [p0, p1, p2, p3] = p; + let [q0, q1, q2, q3] = q; + let clip = |v: i32| crate::picture::clip1(v, bit_depth); + if de == 2 { + // Strong filter (eqs. 8-389..8-394). + let p0p = + (p0 - 2 * tc).max((p0 + 2 * tc).min((p2 + 2 * p1 + 2 * p0 + 2 * q0 + q1 + 4) >> 3)); + let p1p = (p1 - 2 * tc).max((p1 + 2 * tc).min((p2 + p1 + p0 + q0 + 2) >> 2)); + let p2p = (p2 - 2 * tc).max((p2 + 2 * tc).min((2 * p3 + 3 * p2 + p1 + p0 + q0 + 4) >> 3)); + let q0p = + (q0 - 2 * tc).max((q0 + 2 * tc).min((p1 + 2 * p0 + 2 * q0 + 2 * q1 + q2 + 4) >> 3)); + let q1p = (q1 - 2 * tc).max((q1 + 2 * tc).min((p0 + q0 + q1 + q2 + 2) >> 2)); + let q2p = (q2 - 2 * tc).max((q2 + 2 * tc).min((p0 + q0 + q1 + 3 * q2 + 2 * q3 + 4) >> 3)); + return LumaFilterOut { + ndp: 3, + ndq: 3, + p: [p0p, p1p, p2p], + q: [q0p, q1p, q2p], + }; + } + // Weak filter (eqs. 8-395..8-402). + let mut out = LumaFilterOut { + ndp: 0, + ndq: 0, + p: [p0, p1, p2], + q: [q0, q1, q2], + }; + let delta = (9 * (q0 - p0) - 3 * (q1 - p1) + 8) >> 4; // eq. 8-395 + if delta.abs() < tc * 10 { + let delta = delta.clamp(-tc, tc); // eq. 8-396 + out.p[0] = clip(p0 + delta); // eq. 8-397 + out.q[0] = clip(q0 - delta); // eq. 8-398 + if dep == 1 { + let dp = ((((p2 + p0 + 1) >> 1) - p1 + delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-399 + out.p[1] = clip(p1 + dp); // eq. 8-400 + } + if deq == 1 { + let dq = ((((q2 + q0 + 1) >> 1) - q1 - delta) >> 1).clamp(-(tc >> 1), tc >> 1); // eq. 8-401 + out.q[1] = clip(q1 + dq); // eq. 8-402 + } + out.ndp = (dep + 1) as usize; // eq. 8-403 (nDp = dEp + 1) + out.ndq = (deq + 1) as usize; // (nDq = dEq + 1) + } + out +} + +/// §8.7.2.5.3 — decision process for a luma block edge. +/// +/// `p` / `q` are the `(i=0..3) × (k=0,3)` sample grids on each side of +/// the edge, laid out as `p[i][k_idx]` where `k_idx` selects row 0 or +/// row 3 of the edge segment (`p[i][0]` = `pi,0`, `p[i][1]` = `pi,3`). +/// `beta` / `tc` come from [`luma_beta_tc`]. Returns the +/// [`LumaEdgeDecision`] (`dE`, `dEp`, `dEq`) that drives §8.7.2.5.4. +/// +/// The result's `beta` / `tc` fields echo the inputs so a caller can +/// pass the whole decision straight into [`filter_luma_sample`]. +#[must_use] +pub fn luma_edge_decision( + p: [[i32; 2]; 4], + q: [[i32; 2]; 4], + beta: i32, + tc: i32, +) -> LumaEdgeDecision { + // Row 0 (k_idx 0) and row 3 (k_idx 1) second differences (eqs. + // 8-352..8-360 for EDGE_VER, identical form 8-361..8-369 for HOR). + let dp0 = (p[2][0] - 2 * p[1][0] + p[0][0]).abs(); // eq. 8-352 + let dp3 = (p[2][1] - 2 * p[1][1] + p[0][1]).abs(); // eq. 8-353 + let dq0 = (q[2][0] - 2 * q[1][0] + q[0][0]).abs(); // eq. 8-354 + let dq3 = (q[2][1] - 2 * q[1][1] + q[0][1]).abs(); // eq. 8-355 + let dpq0 = dp0 + dq0; // eq. 8-356 + let dpq3 = dp3 + dq3; // eq. 8-357 + let dp = dp0 + dp3; // eq. 8-358 + let dq = dq0 + dq3; // eq. 8-359 + let d = dpq0 + dpq3; // eq. 8-360 + + let mut dec = LumaEdgeDecision { + de: 0, + dep: 0, + deq: 0, + beta, + tc, + }; + if d < beta { + // Strong/weak split (eqs. 8-360 step 3). + let dsam0 = luma_sample_decision(p[0][0], p[3][0], q[0][0], q[3][0], 2 * dpq0, beta, tc); + let dsam3 = luma_sample_decision(p[0][1], p[3][1], q[0][1], q[3][1], 2 * dpq3, beta, tc); + dec.de = if dsam0 && dsam3 { 2 } else { 1 }; + let thr = (beta + (beta >> 1)) >> 3; + if dp < thr { + dec.dep = 1; // eq. step g + } + if dq < thr { + dec.deq = 1; // eq. step h + } + } + dec +} + +/// Table 8-10 — `ChromaArrayType == 1` chroma-QP mapping `QpC = f(qPi)`. +/// +/// The piecewise mapping is identity below `qPi == 30`, a flat-ish run +/// `29..37` across `qPi 30..43`, then `qPi − 6` for `qPi >= 44`. +#[must_use] +pub fn chroma_qpc_420(qpi: i32) -> i32 { + match qpi { + x if x < 30 => x, + 30 => 29, + 31 => 30, + 32 => 31, + 33 => 32, + 34 => 33, + 35 => 33, + 36 => 34, + 37 => 34, + 38 => 35, + 39 => 35, + 40 => 36, + 41 => 36, + 42 => 37, + 43 => 37, + x => x - 6, + } +} + +/// §8.7.2.5.5 — derive `tC` for a chroma block edge. +/// +/// `qp_q` / `qp_p` are the luma `QpY` values of the CUs containing the +/// `q0,0` / `p0,0` chroma samples; `c_qp_pic_offset` is the picture-level +/// `pps_cb_qp_offset` / `pps_cr_qp_offset` for the filtered component; +/// `chroma_array_type` selects Table 8-10 (`== 1`) vs `Min(qPi, 51)`; +/// `tc_offset_div2` is `slice_tc_offset_div2`; `bit_depth` is +/// `BitDepthC`. +/// +/// Returns `tC` per eqs. 8-382..8-384. +#[must_use] +pub fn chroma_tc( + qp_q: i32, + qp_p: i32, + c_qp_pic_offset: i32, + chroma_array_type: u8, + tc_offset_div2: i32, + bit_depth: u8, +) -> i32 { + let qpi = ((qp_q + qp_p + 1) >> 1) + c_qp_pic_offset; // eq. 8-382 + let qp_c = if chroma_array_type == 1 { + chroma_qpc_420(qpi) + } else { + qpi.min(51) + }; + let q = (qp_c + 2 + (tc_offset_div2 << 1)).clamp(0, 53); // eq. 8-383 + tc_prime(q) * (1 << (i32::from(bit_depth) - 8)) // eq. 8-384 +} + +/// §8.7.2.5.8 — filtering process for a chroma sample. +/// +/// `p` / `q` are the two samples each side of the boundary (`p[0]` is +/// `p0`, closest to the edge); `tc` is from [`chroma_tc`]; `bit_depth` +/// is `BitDepthC` for the final `Clip1C`. Returns `(p0', q0')`. The +/// PCM / transquant-bypass / palette suppressions (which restore the +/// input sample) are applied by the caller. +#[inline] +#[must_use] +pub fn filter_chroma_sample(p: [i32; 2], q: [i32; 2], tc: i32, bit_depth: u8) -> (i32, i32) { + let [p0, p1] = p; + let [q0, q1] = q; + let delta = (((q0 - p0) << 2) + p1 - q1 + 4) >> 3; // eq. 8-403 + let delta = delta.clamp(-tc, tc); + let p0p = crate::picture::clip1(p0 + delta, bit_depth); // eq. 8-404 + let q0p = crate::picture::clip1(q0 - delta, bit_depth); // eq. 8-405 + (p0p, q0p) +} + +/// A mutable sample plane: row-major `samples[y * stride + x]`. +/// +/// The §8.7.2.5.4 / .5 block-edge filtering processes read and write +/// this plane in place. Callers wrap their reconstructed luma / chroma +/// component buffer (as `i32` samples) in a [`SamplePlane`]. +pub struct SamplePlane<'a> { + /// Row-major sample storage, `width * height` long. + pub samples: &'a mut [i32], + /// Plane width in samples. + pub width: usize, + /// Row stride in samples (usually equal to `width`). + pub stride: usize, +} + +impl core::fmt::Debug for SamplePlane<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + f.debug_struct("SamplePlane") + .field("len", &self.samples.len()) + .field("width", &self.width) + .field("stride", &self.stride) + .finish() + } +} + +impl SamplePlane<'_> { + #[inline] + fn get(&self, x: usize, y: usize) -> i32 { + self.samples[y * self.stride + x] + } + #[inline] + fn set(&mut self, x: usize, y: usize, v: i32) { + self.samples[y * self.stride + x] = v; + } + /// `(x, y)` plane coordinates for the `i`-th sample on the p (`pi`, + /// negative side) or q (`qi`, positive side) of an edge at `(ex, ey)` + /// for row offset `k` along the edge. + #[inline] + fn edge_xy( + &self, + ex: usize, + ey: usize, + edge: EdgeType, + side_p: bool, + i: usize, + k: usize, + ) -> (usize, usize) { + match (edge, side_p) { + // EDGE_VER: q at x = ex+i, p at x = ex-i-1; both at y = ey+k. + (EdgeType::Vertical, false) => (ex + i, ey + k), + (EdgeType::Vertical, true) => (ex - i - 1, ey + k), + // EDGE_HOR: q at y = ey+i, p at y = ey-i-1; both at x = ex+k. + (EdgeType::Horizontal, false) => (ex + k, ey + i), + (EdgeType::Horizontal, true) => (ex + k, ey - i - 1), + } + } +} + +/// The position + orientation of one 4-row deblocking edge segment. +/// +/// `(ex, ey)` is the plane location of `q0,0`: for `EDGE_VER` the column +/// `ex` is the first q-side column; for `EDGE_HOR` the row `ey` is the +/// first q-side row. +#[derive(Debug, Clone, Copy)] +pub struct EdgePos { + /// `q0,0` x location in the plane. + pub ex: usize, + /// `q0,0` y location in the plane. + pub ey: usize, + /// Edge orientation (`EDGE_VER` / `EDGE_HOR`). + pub edge: EdgeType, +} + +/// The §8.7.2.5.3 / .5 QP + offset context for one block edge. +/// +/// `qp_q` / `qp_p` are the `QpY` values of the CUs containing `q0,0` / +/// `p0,0`; the `*_div2` fields are the per-slice +/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; `bit_depth` is +/// `BitDepthY` (luma) or `BitDepthC` (chroma). +#[derive(Debug, Clone, Copy)] +pub struct EdgeQp { + /// `QpY` of the q-side CU. + pub qp_q: i32, + /// `QpY` of the p-side CU. + pub qp_p: i32, + /// `slice_beta_offset_div2` (luma only; ignored for chroma). + pub beta_offset_div2: i32, + /// `slice_tc_offset_div2`. + pub tc_offset_div2: i32, + /// `BitDepthY` (luma) or `BitDepthC` (chroma). + pub bit_depth: u8, +} + +/// §8.7.2.5.4 — filtering process for a luma block edge. +/// +/// Filters the 4-row edge segment positioned by `pos` (the `q0,0` +/// boundary location). `bs` (1 or 2) and the [`EdgeQp`] context drive +/// [`luma_beta_tc`] / [`luma_edge_decision`] / [`filter_luma_sample`]. +/// +/// Returns the [`LumaEdgeDecision`] that was applied (for inspection / +/// trace); the plane is modified in place. A `bs == 0` edge is a no-op. +/// +/// # Panics +/// Panics if the edge segment reads/writes outside the plane. +pub fn filter_luma_block_edge( + plane: &mut SamplePlane<'_>, + pos: EdgePos, + bs: u8, + qp: EdgeQp, +) -> LumaEdgeDecision { + filter_luma_block_edge_gated(plane, pos, bs, qp, None) +} + +/// [`filter_luma_block_edge`] with the per-CU loop-filter suppression +/// map: a p- / q-side sample whose cell is flagged is left unmodified +/// (the §8.7.2.5.4 `nDp = 0` / `nDq = 0` rule for PCM / +/// transquant-bypass / palette coding units); the filter decision +/// itself still reads both sides. +pub fn filter_luma_block_edge_gated( + plane: &mut SamplePlane<'_>, + pos: EdgePos, + bs: u8, + qp: EdgeQp, + no_filter: Option<&NoFilterMap<'_>>, +) -> LumaEdgeDecision { + let EdgePos { ex, ey, edge } = pos; + let zero = LumaEdgeDecision { + de: 0, + dep: 0, + deq: 0, + beta: 0, + tc: 0, + }; + if bs == 0 { + return zero; + } + let (beta, tc) = luma_beta_tc( + qp.qp_q, + qp.qp_p, + bs, + qp.beta_offset_div2, + qp.tc_offset_div2, + qp.bit_depth, + ); + let bit_depth = qp.bit_depth; + // Gather the decision grid: rows k=0 and k=3, samples i=0..3 each side. + let mut pg = [[0i32; 2]; 4]; + let mut qg = [[0i32; 2]; 4]; + for (k_idx, &k) in [0usize, 3].iter().enumerate() { + for i in 0..4 { + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); + pg[i][k_idx] = plane.get(px, py); + qg[i][k_idx] = plane.get(qx, qy); + } + } + let dec = luma_edge_decision(pg, qg, beta, tc); + if dec.de == 0 { + return dec; + } + // Apply the filter to each of the 4 rows (eq. 8-372/8-373 layout). + for k in 0..4 { + let mut p = [0i32; 4]; + let mut q = [0i32; 4]; + for i in 0..4 { + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); + p[i] = plane.get(px, py); + q[i] = plane.get(qx, qy); + } + let out = filter_luma_sample(p, q, dec.de, dec.dep, dec.deq, tc, bit_depth); + for i in 0..out.ndp { + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); + if no_filter.is_some_and(|m| m.at_luma(px, py)) { + continue; // §8.7.2.5.4 nDp = 0 (PCM / bypass / palette) + } + plane.set(px, py, out.p[i]); + } + for j in 0..out.ndq { + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, j, k); + if no_filter.is_some_and(|m| m.at_luma(qx, qy)) { + continue; // §8.7.2.5.4 nDq = 0 + } + plane.set(qx, qy, out.q[j]); + } + } + dec +} + +/// §8.7.2.5.5 — filtering process for a chroma block edge. +/// +/// Filters the 4-row chroma edge segment positioned by `pos` (the `q0,0` +/// chroma location). The [`EdgeQp`] context carries the luma `QpY` +/// values + `slice_tc_offset_div2` + `BitDepthC`; `c_qp_pic_offset` is +/// the picture chroma offset; `chroma_array_type` selects Table 8-10 +/// (`== 1`) vs `Min(qPi, 51)`. Only `p0`/`q0` are modified (eqs. +/// 8-385..8-388). Returns the `tC` that was applied. +/// +/// # Panics +/// Panics if the edge segment reads/writes outside the plane. +pub fn filter_chroma_block_edge( + plane: &mut SamplePlane<'_>, + pos: EdgePos, + qp: EdgeQp, + c_qp_pic_offset: i32, + chroma_array_type: u8, +) -> i32 { + filter_chroma_block_edge_gated(plane, pos, qp, c_qp_pic_offset, chroma_array_type, None) +} + +/// [`filter_chroma_block_edge`] with the per-CU loop-filter +/// suppression map (§8.7.2.5.5: the flagged side's `p0'` / `q0'` is +/// not written). Chroma sample positions map onto the luma cell grid +/// through the `SubWidthC` / `SubHeightC` factors of +/// `chroma_array_type`. +pub fn filter_chroma_block_edge_gated( + plane: &mut SamplePlane<'_>, + pos: EdgePos, + qp: EdgeQp, + c_qp_pic_offset: i32, + chroma_array_type: u8, + no_filter: Option<&NoFilterMap<'_>>, +) -> i32 { + let (sub_w, sub_h) = sub_wh_c(chroma_array_type); + let EdgePos { ex, ey, edge } = pos; + let bit_depth = qp.bit_depth; + let tc = chroma_tc( + qp.qp_q, + qp.qp_p, + c_qp_pic_offset, + chroma_array_type, + qp.tc_offset_div2, + bit_depth, + ); + for k in 0..4 { + let mut p = [0i32; 2]; + let mut q = [0i32; 2]; + for i in 0..2 { + let (px, py) = plane.edge_xy(ex, ey, edge, true, i, k); + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, i, k); + p[i] = plane.get(px, py); + q[i] = plane.get(qx, qy); + } + let (p0p, q0p) = filter_chroma_sample(p, q, tc, bit_depth); + let (px, py) = plane.edge_xy(ex, ey, edge, true, 0, k); + let (qx, qy) = plane.edge_xy(ex, ey, edge, false, 0, k); + if !no_filter.is_some_and(|m| m.at_luma(px * sub_w, py * sub_h)) { + plane.set(px, py, p0p); + } + if !no_filter.is_some_and(|m| m.at_luma(qx * sub_w, qy * sub_h)) { + plane.set(qx, qy, q0p); + } + } + tc +} + +/// The §8.7.2.5.1 / .2 per-CU deblocking context: the QP + offset state a +/// coding unit contributes to its edge filtering. +/// +/// `qp_y` is the CU's `QpY`; the `*_offset_div2` are the per-slice +/// `slice_beta_offset_div2` / `slice_tc_offset_div2`; the `pps_c*_qp_offset` +/// are the picture chroma QP offsets; the bit depths are `BitDepthY` / +/// `BitDepthC`. The driver reads neighbour `QpY` from `qp_y_at` so a +/// boundary edge can use the p-side CU's `QpY` for `qP,p` (eq. 8-347). +#[derive(Debug, Clone, Copy)] +pub struct DeblockCuParams { + /// The CU's `QpY` (the q-side QP at every edge inside the CU). + pub qp_y: i32, + /// `slice_beta_offset_div2`. + pub beta_offset_div2: i32, + /// `slice_tc_offset_div2`. + pub tc_offset_div2: i32, + /// `pps_cb_qp_offset` for the Cb component — the §8.7.2.5.1/.2 + /// `cQpPicOffset` (slice-level and CU-level chroma QP adjustments + /// are excluded from chroma deblocking by the invocation text). + pub cb_qp_offset: i32, + /// `pps_cr_qp_offset` for the Cr component. + pub cr_qp_offset: i32, + /// `BitDepthY`. + pub bit_depth_luma: u8, + /// `BitDepthC`. + pub bit_depth_chroma: u8, + /// `ChromaArrayType` (selects Table 8-10 / `Min(qPi,51)` + subsampling). + pub chroma_array_type: u8, +} + +/// The geometry + QP context of one coding unit for the §8.7.2.5.1 / .2 +/// edge-filtering driver. +#[derive(Debug, Clone, Copy)] +pub struct DeblockCu { + /// The CU's luma top-left x. + pub x_cb: usize, + /// The CU's luma top-left y. + pub y_cb: usize, + /// `log2CbSize`. + pub log2_cb_size: u32, + /// The CU QP / offset / chroma context. + pub params: DeblockCuParams, + /// The left-neighbour CU's `QpY` at the vertical coding-block + /// boundary edge (xDk == 0); interior edges use `params.qp_y` on + /// both sides. + pub qp_y_p_left: i32, + /// The above-neighbour CU's `QpY` at the horizontal coding-block + /// boundary edge (yDm == 0). + pub qp_y_p_top: i32, +} + +/// §8.7.2.5.1 / .2 — filter all edges of one coding unit in one direction. +/// +/// Applies the §8.7.2.5.4 luma block-edge filter at every `bS > 0` sampled +/// position, then (when `ChromaArrayType != 0`) the §8.7.2.5.5 chroma +/// block-edge filter at every `bS == 2`, 8-luma-sample-aligned position. +/// The luma sampling grid is 8-stride along the edge axis and 4-stride +/// across; the chroma grid steps `8 / SubWidthC` (vertical) / +/// `8 / SubHeightC` (horizontal) in the edge axis. +/// +/// `cu` carries the CU's geometry + QP context; `bs` is the §8.7.2.4 grid +/// for `edge_type`. +/// +/// # Panics +/// Panics if a filtered edge segment reads/writes outside a plane. +pub fn filter_cu_edges( + pic: &mut Picture, + cu: &DeblockCu, + edge_type: EdgeType, + bs: &BoundaryStrength, +) { + filter_cu_edges_with_qp_map(pic, cu, edge_type, bs, None); +} + +/// [`filter_cu_edges`] with the per-position [`QpMap`] (exact `QpQ` / +/// `QpP` when quantization groups vary inside / around the CU). +pub fn filter_cu_edges_with_qp_map( + pic: &mut Picture, + cu: &DeblockCu, + edge_type: EdgeType, + bs: &BoundaryStrength, + qp_map: Option>, +) { + filter_cu_edges_full(pic, cu, edge_type, bs, qp_map, None); +} + +/// [`filter_cu_edges_with_qp_map`] with the per-CU loop-filter +/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 `nDp` / `nDq` zeroing). +pub fn filter_cu_edges_full( + pic: &mut Picture, + cu: &DeblockCu, + edge_type: EdgeType, + bs: &BoundaryStrength, + qp_map: Option>, + no_filter: Option<&NoFilterMap<'_>>, +) { + let DeblockCu { + x_cb, + y_cb, + log2_cb_size, + params, + qp_y_p_left, + qp_y_p_top, + } = *cu; + let n_d = 1usize << (log2_cb_size - 3); + let (sub_w, sub_h) = sub_wh_c(params.chroma_array_type); + + // ----- luma (§8.7.2.5.1 step 2 / §8.7.2.5.2 step 2) ----- + // EDGE_VER: xDk = k<<3 (k=0..nD-1), yDm = m<<2 (m=0..2nD-1). + // EDGE_HOR: yDm = m<<3 (m=0..nD-1), xDk = k<<2 (k=0..2nD-1). + // `edges` indexes the 8-strided axis (nD); `segs` the 4-strided axis. + let (n_edges, n_segs) = (n_d, n_d * 2); + for e in 0..n_edges { + for s_idx in 0..n_segs { + let (x_dk, y_dm) = match edge_type { + EdgeType::Vertical => (e << 3, s_idx << 2), + EdgeType::Horizontal => (s_idx << 2, e << 3), + }; + let s = bs.at(x_dk, y_dm); + if s == 0 { + continue; + } + // p-side QpY: the neighbour CU only at the coding-block + // boundary edge; interior edges share the CU's QpY. + let (boundary, qp_y_p) = match edge_type { + EdgeType::Vertical => (x_dk == 0, qp_y_p_left), + EdgeType::Horizontal => (y_dm == 0, qp_y_p_top), + }; + // §8.7.2.5.3: QpQ / QpP are the QpY of the coding units + // containing the q0 / p0 samples — per position from the QP + // map when supplied, else the per-CU scalars. + let (qp_q, qp_p) = match qp_map { + Some(m) => { + let (qx, qy) = (x_cb + x_dk, y_cb + y_dm); + let (px, py) = match edge_type { + EdgeType::Vertical => (qx - 1, qy), + EdgeType::Horizontal => (qx, qy - 1), + }; + (m.qp_at(qx, qy), m.qp_at(px, py)) + } + None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }), + }; + let qp = EdgeQp { + qp_q, + qp_p, + beta_offset_div2: params.beta_offset_div2, + tc_offset_div2: params.tc_offset_div2, + bit_depth: params.bit_depth_luma, + }; + let (buf, stride) = pic.plane_mut(Plane::Luma); + let mut plane = SamplePlane { + samples: buf, + width: stride, + stride, + }; + let pos = EdgePos { + ex: x_cb + x_dk, + ey: y_cb + y_dm, + edge: edge_type, + }; + filter_luma_block_edge_gated(&mut plane, pos, s, qp, no_filter); + } + } + + // ----- chroma (§8.7.2.5.1 / .2 chroma steps) ----- + if params.chroma_array_type == 0 { + return; + } + let (xc_cb, yc_cb) = (x_cb / sub_w, y_cb / sub_h); + // edgeSpacing / edgeSections per direction. + let (spacing, sections, n_edges) = match edge_type { + EdgeType::Vertical => (8 / sub_w, n_d * (2 / sub_h), n_d), + EdgeType::Horizontal => (8 / sub_h, n_d * (2 / sub_w), n_d), + }; + for plane in [Plane::Cb, Plane::Cr] { + let c_qp_offset = if plane == Plane::Cb { + params.cb_qp_offset + } else { + params.cr_qp_offset + }; + // EDGE_VER: xDk = k*spacing (k=0..nD-1), yDm = m<<2 (m=0..sections-1). + // EDGE_HOR: yDm = m*spacing, xDk = k<<2. + let (k_max, m_max) = match edge_type { + EdgeType::Vertical => (n_edges, sections), + EdgeType::Horizontal => (sections, n_edges), + }; + for kk in 0..k_max { + for mm in 0..m_max { + let (x_dk, y_dm) = match edge_type { + EdgeType::Vertical => (kk * spacing, mm << 2), + EdgeType::Horizontal => (kk << 2, mm * spacing), + }; + // bS[xDk*SubWidthC][yDm*SubHeightC] == 2. + let bx = x_dk * sub_w; + let by = y_dm * sub_h; + if bs.at(bx, by) != 2 { + continue; + } + // 8-luma-grid alignment of the chroma edge position. + let aligned = match edge_type { + EdgeType::Vertical => ((xc_cb + x_dk) >> 3) << 3 == xc_cb + x_dk, + EdgeType::Horizontal => ((yc_cb + y_dm) >> 3) << 3 == yc_cb + y_dm, + }; + if !aligned { + continue; + } + let (boundary, qp_y_p) = match edge_type { + EdgeType::Vertical => (bx == 0, qp_y_p_left), + EdgeType::Horizontal => (by == 0, qp_y_p_top), + }; + // §8.7.2.5.5: QpQ / QpP from the coding units containing + // the chroma edge's q0 / p0 samples (luma positions). + let (qp_q, qp_p) = match qp_map { + Some(m) => { + let (qx, qy) = ((xc_cb + x_dk) * sub_w, (yc_cb + y_dm) * sub_h); + let (px, py) = match edge_type { + EdgeType::Vertical => (qx - 1, qy), + EdgeType::Horizontal => (qx, qy - 1), + }; + (m.qp_at(qx, qy), m.qp_at(px, py)) + } + None => (params.qp_y, if boundary { qp_y_p } else { params.qp_y }), + }; + let qp = EdgeQp { + qp_q, + qp_p, + beta_offset_div2: params.beta_offset_div2, + tc_offset_div2: params.tc_offset_div2, + bit_depth: params.bit_depth_chroma, + }; + let (buf, stride) = pic.plane_mut(plane); + let mut cplane = SamplePlane { + samples: buf, + width: stride, + stride, + }; + let pos = EdgePos { + ex: xc_cb + x_dk, + ey: yc_cb + y_dm, + edge: edge_type, + }; + filter_chroma_block_edge_gated( + &mut cplane, + pos, + qp, + c_qp_offset, + params.chroma_array_type, + no_filter, + ); + } + } + } +} + +/// One coding unit's full §8.7.2 deblocking description, as the +/// picture-level driver [`deblock_picture`] consumes it. +/// +/// Carries everything the §8.7.2.2 / .3 edge-flag derivation, the §8.7.2.4 +/// bS derivation and the §8.7.2.5.1 / .2 filtering need for one CU: its +/// geometry + QP context ([`DeblockCu`]), its transform-tree split +/// ([`TransformSplit`]) + prediction [`PartMode`], and the §8.7.2.1 +/// `filterLeftCbEdgeFlag` / `filterTopCbEdgeFlag` the caller computes from +/// the picture / tile / slice geometry (`false` at a non-filtered +/// boundary). +#[derive(Debug, Clone)] +pub struct DeblockCuDesc { + /// Geometry + QP context. + pub cu: DeblockCu, + /// The CU's transform-tree split structure. + pub transform_split: TransformSplit, + /// The CU's prediction partition mode. + pub part_mode: PartMode, + /// §8.7.2.1 `filterLeftCbEdgeFlag` (gates the left CB-boundary + /// vertical edge). + pub filter_left: bool, + /// §8.7.2.1 `filterTopCbEdgeFlag` (gates the top CB-boundary + /// horizontal edge). + pub filter_top: bool, +} + +/// §8.7.2.1 — the picture-level deblocking filter driver. +/// +/// Filters all vertical edges of the picture first, then all horizontal +/// edges (with the vertically-filtered samples as input), per §8.7.2.1. +/// Each pass walks `cus` in order and, for each CU: derives the +/// §8.7.2.2 / .3 edge flags, the §8.7.2.4 boundary strengths from `field`, +/// then applies the §8.7.2.5.1 / .2 luma + chroma filters via +/// [`filter_cu_edges`]. +/// +/// `cus` must be in coding (z-scan) order; the caller is responsible for +/// the §8.7.2.1 boundary exclusions (picture / tile / slice edges, and the +/// `slice_deblocking_filter_disabled_flag` skip) by setting each +/// descriptor's `filter_left` / `filter_top` (and omitting CUs whose slice +/// disables deblocking). +/// +/// # Panics +/// Panics if a CU's edges read/write outside a `pic` plane. +pub fn deblock_picture(pic: &mut Picture, field: &MotionField, cus: &[DeblockCuDesc]) { + deblock_picture_with_qp_map(pic, field, cus, None); +} + +/// Per-4×4-cell `QpY` map for the §8.7.2.5.3 / §8.7.2.5.5 per-position +/// `QpQ` / `QpP` reads (row-major over the picture's 4×4 cells). When a +/// picture carries per-quantization-group `cu_qp_delta` values, the +/// p-side QP can change along a single coding-block edge, so the +/// per-CU scalar fallback in [`DeblockCu`] is not exact. +#[derive(Debug, Clone, Copy)] +pub struct QpMap<'a> { + /// Per-cell `QpY`. + pub cells: &'a [i8], + /// Cell-grid width (`ceil(pic_width / 4)`). + pub w_cells: usize, +} + +impl QpMap<'_> { + fn qp_at(&self, x_luma: usize, y_luma: usize) -> i32 { + let idx = (y_luma >> 2) * self.w_cells + (x_luma >> 2); + self.cells.get(idx).copied().map_or(0, i32::from) + } +} + +/// Per-4×4-luma-cell in-loop-filter suppression map: `true` cells +/// belong to a coding unit whose reconstructed samples the loop +/// filters must not modify — a `pcm_flag == 1` CU when +/// `pcm_loop_filter_disabled_flag == 1` (§7.4.3.2.1), or a +/// `cu_transquant_bypass_flag == 1` CU (§7.4.9.5). The §8.7.2.5.4 / +/// §8.7.2.5.5 filters zero `nDp` / `nDq` on the flagged side (the +/// decision still reads both sides); §8.7.3 SAO skips flagged samples. +#[derive(Debug, Clone, Copy)] +pub struct NoFilterMap<'a> { + /// Per-cell suppression flags, row-major. + pub cells: &'a [bool], + /// Cell-grid width (`ceil(pic_width / 4)`). + pub w_cells: usize, +} + +impl NoFilterMap<'_> { + /// Suppression flag of the cell covering luma sample + /// `(x_luma, y_luma)` (out-of-range positions are not suppressed). + #[must_use] + pub fn at_luma(&self, x_luma: usize, y_luma: usize) -> bool { + self.cells + .get((y_luma >> 2) * self.w_cells + (x_luma >> 2)) + .copied() + .unwrap_or(false) + } +} + +/// [`deblock_picture`] with the per-position QP map. +pub fn deblock_picture_with_qp_map( + pic: &mut Picture, + field: &MotionField, + cus: &[DeblockCuDesc], + qp_map: Option>, +) { + deblock_picture_full(pic, field, cus, qp_map, None); +} + +/// [`deblock_picture_with_qp_map`] with the per-CU loop-filter +/// suppression map (§8.7.2.5.4 / §8.7.2.5.5 — PCM with +/// `pcm_loop_filter_disabled_flag` and transquant-bypass coding units +/// keep their reconstructed samples). +pub fn deblock_picture_full( + pic: &mut Picture, + field: &MotionField, + cus: &[DeblockCuDesc], + qp_map: Option>, + no_filter: Option<&NoFilterMap<'_>>, +) { + // Pass 1: all vertical edges. + for desc in cus { + apply_cu_direction(pic, field, desc, EdgeType::Vertical, qp_map, no_filter); + } + // Pass 2: all horizontal edges (on the vertically-filtered samples). + for desc in cus { + apply_cu_direction(pic, field, desc, EdgeType::Horizontal, qp_map, no_filter); + } +} + +/// Derive the edge flags + bS for one CU in one direction and filter it. +fn apply_cu_direction( + pic: &mut Picture, + field: &MotionField, + desc: &DeblockCuDesc, + edge_type: EdgeType, + qp_map: Option>, + no_filter: Option<&NoFilterMap<'_>>, +) { + let DeblockCu { + x_cb, + y_cb, + log2_cb_size, + .. + } = desc.cu; + let filter_edge_flag = match edge_type { + EdgeType::Vertical => desc.filter_left, + EdgeType::Horizontal => desc.filter_top, + }; + let ef = derive_edge_flags( + &desc.transform_split, + desc.part_mode, + log2_cb_size, + edge_type, + filter_edge_flag, + ); + let bs = derive_boundary_strength( + field, + x_cb, + y_cb, + log2_cb_size, + edge_type, + ef.edge_flags(), + ef.tb_edge(), + ); + filter_cu_edges_full(pic, &desc.cu, edge_type, &bs, qp_map, no_filter); +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::motion::MotionCell; + + fn inter_cell(mv0: [i32; 2], poc0: i32) -> MotionCell { + MotionCell { + is_intra: false, + has_nonzero_coeff: false, + pred_flag_l0: true, + pred_flag_l1: false, + ref_poc_l0: poc0, + ref_poc_l1: i32::MIN, + mv_l0: mv0, + mv_l1: [0, 0], + } + } + + /// A 16×16 CU's internal vertical edge at xDi=8, with the left + /// (p-side) half intra ⇒ bS == 2 at the sampled positions. + /// + /// The §8.7.2.4 vertical-edge x stride is 8, so a 16-wide CU samples + /// xDi ∈ {0, 8}; the internal edge is at xDi=8. + #[test] + fn intra_neighbour_gives_bs2() { + let mut field = MotionField::new(32, 32); + // CU at (0,0), 16×16. q-side (right half) inter; p-side (left) + // stays intra (background). + field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0)); + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + // Internal vertical edge at xDi=8, sampled yDj 0,4,8,12. + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + // p0 = col 7 (intra), q0 = col 8 (inter) ⇒ bS == 2. + assert_eq!(bs.at(8, 0), 2); + assert_eq!(bs.at(8, 12), 2); + // xDi=4 not sampled for EDGE_VER (8-stride). + assert_eq!(bs.at(4, 0), 0); + } + + /// Transform-block edge with a non-zero coefficient on an inter block + /// ⇒ bS == 1. + #[test] + fn tb_edge_with_coeff_gives_bs1() { + let mut field = MotionField::new(32, 32); + let mut p = inter_cell([0, 0], 0); + p.has_nonzero_coeff = true; + let q = inter_cell([0, 0], 0); + field.fill_rect(0, 0, 16, 16, q); + field.fill_rect(0, 0, 8, 16, p); // left half carries the coeff + let n = 16; + let mut edge_flags = vec![false; n * n]; + let mut tb_edge = vec![false; n * n]; + // Vertical edge at xDi=8 (a transform-block edge). + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + tb_edge[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + // p0 = col 7 (coeff block), q0 = col 8 ⇒ bS == 1. + assert_eq!(bs.at(8, 0), 1); + assert_eq!(bs.at(8, 4), 1); + } + + /// Two inter blocks, same reference, MV difference >= 4 ⇒ bS == 1. + #[test] + fn mv_diff_gives_bs1() { + let mut field = MotionField::new(32, 32); + field.fill_rect(0, 0, 8, 16, inter_cell([0, 0], 0)); // p side + field.fill_rect(8, 0, 8, 16, inter_cell([4, 0], 0)); // q side, Δ=4 + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 1); + assert_eq!(bs.at(8, 12), 1); + } + + /// Two inter blocks, same reference + same MV ⇒ bS == 0. + #[test] + fn same_motion_gives_bs0() { + let mut field = MotionField::new(32, 32); + field.fill_rect(0, 0, 16, 16, inter_cell([3, 1], 0)); // identical motion + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 0); + } + + /// Different reference pictures ⇒ bS == 1 even with identical MVs. + #[test] + fn different_ref_gives_bs1() { + let mut field = MotionField::new(32, 32); + field.fill_rect(0, 0, 8, 16, inter_cell([2, 2], 0)); // poc 0 + field.fill_rect(8, 0, 8, 16, inter_cell([2, 2], 8)); // poc 8 + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 1); + } + + /// Horizontal edges sample 4-stride x, 8-stride y. + #[test] + fn horizontal_edge_sampling() { + let mut field = MotionField::new(32, 32); + // top half intra (background), bottom half inter; internal + // horizontal edge at yDj=8. + field.fill_rect(0, 8, 16, 8, inter_cell([0, 0], 0)); + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for xi in (0..16).step_by(4) { + edge_flags[8 * n + xi] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Horizontal, &edge_flags, &tb_edge); + // yDj=8: p0 = row 7 (intra), q0 = row 8 (inter) ⇒ bS == 2. + assert_eq!(bs.at(0, 8), 2); + assert_eq!(bs.at(12, 8), 2); + // yDj=4 not sampled for EDGE_HOR. + assert_eq!(bs.at(0, 4), 0); + } + + /// edgeFlags == 0 ⇒ bS stays 0 regardless of mode. + #[test] + fn no_edge_flag_gives_bs0() { + let field = MotionField::new(16, 16); // intra background + let n = 8; + let edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + let bs = + derive_boundary_strength(&field, 0, 0, 3, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(0, 0), 0); + } + + /// Bullet-4 path: two MVs each, same single reference picture on both + /// sides; bS == 1 only when both the straight and crossed MV-pair + /// differences reach 4. + #[test] + fn bipred_same_ref_bullet4() { + let mut field = MotionField::new(32, 32); + let bi = |mv0: [i32; 2], mv1: [i32; 2]| MotionCell { + is_intra: false, + has_nonzero_coeff: false, + pred_flag_l0: true, + pred_flag_l1: true, + ref_poc_l0: 0, + ref_poc_l1: 0, // same reference picture for both lists + mv_l0: mv0, + mv_l1: mv1, + }; + // p: l0=[0,0] l1=[0,0]; q: l0=[4,0] l1=[4,0]. + // straight: |Δl0|>=4 ⇒ true. crossed: |p.l0−q.l1|=4 ⇒ true ⇒ bS 1. + field.fill_rect(0, 0, 8, 16, bi([0, 0], [0, 0])); + field.fill_rect(8, 0, 8, 16, bi([4, 0], [4, 0])); + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 1); + } + + // ----- §8.7.2.2 / §8.7.2.3 edge-flag derivation ----- + + /// §8.7.2.2: an un-split 16×16 CB marks only its left CB-boundary + /// column (EDGE_VER), gated by filterEdgeFlag. No internal TB edges. + #[test] + fn edge_flags_single_tb_left_boundary() { + let n = 16; + // filterEdgeFlag = true ⇒ the CB-left column (x=0) is an edge. + let ef = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::Part2Nx2N, + 4, + EdgeType::Vertical, + true, + ); + for y in 0..n { + assert!(ef.edge_at(0, y), "left CB-boundary column must be set"); + assert!(ef.tb_at(0, y), "left CB-boundary is a TB edge"); + } + // No internal column is set (no split, PART_2Nx2N). + for x in 1..n { + for y in 0..n { + assert!(!ef.edge_at(x, y), "interior ({x},{y}) must be clear"); + } + } + } + + /// filterEdgeFlag = false suppresses the CB-boundary edge entirely. + #[test] + fn edge_flags_cb_boundary_gated_off() { + let ef = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::Part2Nx2N, + 4, + EdgeType::Vertical, + false, + ); + for y in 0..16 { + assert!(!ef.edge_at(0, y), "gated-off CB boundary stays clear"); + } + } + + /// §8.7.2.2: a one-level transform split of a 16×16 CB marks the + /// internal vertical TB edge at column 8 (always 1, not gated), plus + /// the gated left boundary. + #[test] + fn edge_flags_split_marks_internal_tb_edge() { + let ef = derive_edge_flags( + &TransformSplit::split_once(), + PartMode::Part2Nx2N, + 4, + EdgeType::Vertical, + true, + ); + for y in 0..16 { + assert!(ef.edge_at(0, y), "left boundary set"); + assert!(ef.edge_at(8, y), "internal split column 8 set"); + assert!(ef.tb_at(8, y), "internal split is a TB edge"); + } + } + + /// §8.7.2.2 EDGE_HOR: the split marks the internal horizontal TB edge + /// at row 8. + #[test] + fn edge_flags_split_horizontal() { + let ef = derive_edge_flags( + &TransformSplit::split_once(), + PartMode::Part2Nx2N, + 4, + EdgeType::Horizontal, + true, + ); + for x in 0..16 { + assert!(ef.edge_at(x, 0), "top boundary set"); + assert!(ef.edge_at(x, 8), "internal split row 8 set"); + assert!(ef.tb_at(x, 8), "internal split is a TB edge"); + } + } + + /// §8.7.2.3 PART_Nx2N marks the prediction column at nCbS/2 — and it + /// is NOT a transform-block edge (tb_edge stays clear there). + #[test] + fn edge_flags_part_nx2n_prediction_edge() { + let ef = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::PartNx2N, + 4, + EdgeType::Vertical, + true, + ); + for y in 0..16 { + assert!(ef.edge_at(8, y), "PART_Nx2N prediction column 8 set"); + assert!(!ef.tb_at(8, y), "prediction edge is not a TB edge"); + } + } + + /// §8.7.2.3 AMP PART_nLx2N marks column nCbS/4; PART_nRx2N marks + /// 3·nCbS/4. + #[test] + fn edge_flags_amp_columns() { + let l = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::PartNLx2N, + 4, + EdgeType::Vertical, + true, + ); + assert!(l.edge_at(4, 0), "PART_nLx2N column 4"); + let r = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::PartNRx2N, + 4, + EdgeType::Vertical, + true, + ); + assert!(r.edge_at(12, 0), "PART_nRx2N column 12"); + } + + /// §8.7.2.3 horizontal AMP: PART_2NxnU row nCbS/4, PART_2NxnD row + /// 3·nCbS/4. + #[test] + fn edge_flags_amp_rows() { + let u = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::Part2NxnU, + 4, + EdgeType::Horizontal, + true, + ); + assert!(u.edge_at(0, 4), "PART_2NxnU row 4"); + let d = derive_edge_flags( + &TransformSplit::leaf(), + PartMode::Part2NxnD, + 4, + EdgeType::Horizontal, + true, + ); + assert!(d.edge_at(0, 12), "PART_2NxnD row 12"); + } + + /// A nested split (one quadrant splits again) marks the deeper TB edge + /// at the 4-sample sub-block column. + #[test] + fn edge_flags_nested_split() { + // 16×16 CB: TL quadrant (8×8) splits into four 4×4; others leaf. + let nested = TransformSplit::Split(Box::new([ + TransformSplit::split_once(), // TL 8×8 → 4×4 leaves + TransformSplit::Leaf, + TransformSplit::Leaf, + TransformSplit::Leaf, + ])); + let ef = derive_edge_flags(&nested, PartMode::Part2Nx2N, 4, EdgeType::Vertical, true); + // The TL quadrant's internal vertical edge is at column 4. + for y in 0..8 { + assert!(ef.edge_at(4, y), "nested TB edge at column 4, row {y}"); + assert!(ef.tb_at(4, y)); + } + // The CB-internal split at column 8 is still present. + for y in 0..16 { + assert!(ef.edge_at(8, y), "CB-level split column 8"); + } + // Column 4 below the TL quadrant (y>=8) is not an edge (BL leaf is + // 8 wide, its only internal edge would be column 8, not 4). + assert!(!ef.edge_at(4, 8), "column 4 row 8 clear (BL leaf)"); + } + + /// The §8.7.2.4 bS derivation consumes the derived flags: an + /// intra/inter split CU with a derived internal TB edge yields bS=2 + /// at the internal column. + #[test] + fn edge_flags_feed_boundary_strength() { + // filterEdgeFlag = false: this CB is at the picture's left edge, so + // only the internal split column (8) is an edge — the bS sampler + // never reads a p-sample at x = −1. + let ef = derive_edge_flags( + &TransformSplit::split_once(), + PartMode::Part2Nx2N, + 4, + EdgeType::Vertical, + false, + ); + let mut field = MotionField::new(32, 32); + // Left half intra (background), right half inter. + field.fill_rect(8, 0, 8, 16, inter_cell([0, 0], 0)); + let bs = derive_boundary_strength( + &field, + 0, + 0, + 4, + EdgeType::Vertical, + ef.edge_flags(), + ef.tb_edge(), + ); + // Internal column 8: p (col 7, intra) vs q (col 8, inter) ⇒ bS 2. + assert_eq!(bs.at(8, 0), 2); + } + + // ----- §8.7.2.5.3 / .6 / .7 luma filtering primitives ----- + + /// Table 8-12 spot checks: β′ is 0 below Q=16 and tracks the listed + /// breakpoints; tC′ is 0 up to Q=17 and 1 at Q=18. + #[test] + fn table_8_12_breakpoints() { + assert_eq!(beta_prime(15), 0); + assert_eq!(beta_prime(16), 6); + assert_eq!(beta_prime(29), 20); + assert_eq!(beta_prime(51), 64); + assert_eq!(tc_prime(17), 0); + assert_eq!(tc_prime(18), 1); + assert_eq!(tc_prime(53), 24); + // Clip behaviour at the table edges. + assert_eq!(beta_prime(-3), 0); + assert_eq!(tc_prime(99), 24); + } + + /// §8.7.2.5.3 β/tC at 8-bit: qPL = (QpQ+QpP+1)>>1, no offsets, bS=2. + /// QpQ=QpP=37 ⇒ qPL=37 ⇒ Q_beta=37 ⇒ β′=36, β=36; Q_tc=37+2=39 ⇒ + /// tC′=5, tC=5. + #[test] + fn luma_beta_tc_no_offset_8bit() { + let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 8); + assert_eq!(beta, 36); + assert_eq!(tc, 5); + // bS=1 lowers the tC index by 2 (Q_tc=37): tC′=4. + let (_, tc1) = luma_beta_tc(37, 37, 1, 0, 0, 8); + assert_eq!(tc1, 4); + } + + /// 10-bit scaling: β and tC are multiplied by 1<<(BitDepthY−8)=4. + #[test] + fn luma_beta_tc_10bit_scaled() { + let (beta, tc) = luma_beta_tc(37, 37, 2, 0, 0, 10); + assert_eq!(beta, 36 * 4); + assert_eq!(tc, 5 * 4); + } + + /// §8.7.2.5.6: a flat region (all-equal samples) passes the decision. + #[test] + fn luma_sample_decision_flat_passes() { + // dpq=0 < β>>2; |p3−p0|+|q0−q3|=0 < β>>3; |p0−q0|=0 < (5tC+1)>>1. + assert!(luma_sample_decision(128, 128, 128, 128, 0, 32, 4)); + // A large step at the boundary fails the |p0−q0| test. + assert!(!luma_sample_decision(64, 64, 200, 200, 0, 32, 4)); + } + + /// §8.7.2.5.7 strong filter: a flat block stays flat (idempotent). + #[test] + fn strong_filter_flat_is_idempotent() { + let s = [100; 4]; + let out = filter_luma_sample(s, s, 2, 0, 0, 6, 8); + assert_eq!(out.ndp, 3); + assert_eq!(out.ndq, 3); + assert_eq!(out.p, [100, 100, 100]); + assert_eq!(out.q, [100, 100, 100]); + } + + /// §8.7.2.5.7 strong filter clips each output to ±2·tC of the input. + #[test] + fn strong_filter_clips_to_two_tc() { + // A hard step: p side 0, q side 255. tC=2 ⇒ p0' clipped to + // p0+2·tC = 0+4 = 4; q0' clipped to q0−2·tC = 255−4 = 251. + let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 2, 0, 0, 2, 8); + assert_eq!(out.p[0], 4); + assert_eq!(out.q[0], 251); + } + + /// §8.7.2.5.7 weak filter: small ramp, dEp=dEq=0 filters only p0/q0. + /// p0=98,q0=102,p1=q1=100 ⇒ δ=(9·4−3·0+8)>>4=2; |δ|<10·tC; clamp to + /// [−tC,tC]=2 ⇒ p0'=100, q0'=100; nDp=nDq=1. + #[test] + fn weak_filter_centres_small_step() { + let out = filter_luma_sample([98, 100, 100, 100], [102, 100, 100, 100], 1, 0, 0, 5, 8); + assert_eq!(out.ndp, 1); + assert_eq!(out.ndq, 1); + assert_eq!(out.p[0], 100); + assert_eq!(out.q[0], 100); + } + + /// §8.7.2.5.7 weak filter no-op when |δ| ≥ 10·tC. + #[test] + fn weak_filter_skips_large_delta() { + // Big step with tiny tC ⇒ |δ| ≥ 10·tC ⇒ nDp=nDq=0, no change. + let out = filter_luma_sample([0, 0, 0, 0], [255, 255, 255, 255], 1, 1, 1, 1, 8); + assert_eq!(out.ndp, 0); + assert_eq!(out.ndq, 0); + assert_eq!(out.p[0], 0); + assert_eq!(out.q[0], 255); + } + + // ----- §8.7.2.5.3 edge decision + §8.7.2.5.5 / .8 chroma ----- + + /// §8.7.2.5.3: a perfectly flat edge (d=0 < β) with no step picks the + /// strong filter (dE=2) and sets dEp=dEq=1 (dp=dq=0 < threshold). + #[test] + fn edge_decision_flat_is_strong() { + let flat = [[128, 128], [128, 128], [128, 128], [128, 128]]; + let dec = luma_edge_decision(flat, flat, 32, 6); + assert_eq!(dec.de, 2); + assert_eq!(dec.dep, 1); + assert_eq!(dec.deq, 1); + } + + /// §8.7.2.5.3: a large hard step (d ≥ β) leaves dE=0 (no filtering). + #[test] + fn edge_decision_hard_step_no_filter() { + // p side ramps strongly so the second differences make d ≥ β. + let p = [[0, 0], [60, 60], [0, 0], [0, 0]]; + let q = [[255, 255], [255, 255], [255, 255], [255, 255]]; + let dec = luma_edge_decision(p, q, 8, 2); + assert_eq!(dec.de, 0); + assert_eq!(dec.dep, 0); + assert_eq!(dec.deq, 0); + } + + /// §8.7.2.5.3: a smooth region that passes d<β but fails the strong + /// per-sample decision (a moderate boundary step) selects the weak + /// filter (dE=1). + #[test] + fn edge_decision_moderate_step_is_weak() { + // Flat halves with a step at the boundary: second differences are + // 0 (d=0<β) but |p0−q0| is large ⇒ luma_sample_decision fails. + let p = [[100, 100], [100, 100], [100, 100], [100, 100]]; + let q = [[140, 140], [140, 140], [140, 140], [140, 140]]; + let dec = luma_edge_decision(p, q, 64, 4); + assert_eq!(dec.de, 1); + } + + /// Table 8-10 (4:2:0) chroma-QP mapping breakpoints. + #[test] + fn table_8_10_chroma_qpc() { + assert_eq!(chroma_qpc_420(29), 29); + assert_eq!(chroma_qpc_420(30), 29); + assert_eq!(chroma_qpc_420(35), 33); + assert_eq!(chroma_qpc_420(43), 37); + assert_eq!(chroma_qpc_420(44), 38); + assert_eq!(chroma_qpc_420(51), 45); + } + + /// §8.7.2.5.5 chroma tC: 4:2:0, QpY=37 both sides, no offsets. + /// qPi=37 ⇒ QpC=34 (Table 8-10) ⇒ Q=34+2=36 ⇒ tC′=4, tC=4 at 8-bit. + #[test] + fn chroma_tc_420_8bit() { + assert_eq!(chroma_tc(37, 37, 0, 1, 0, 8), 4); + // 4:4:4 (chroma_array_type=3): QpC=Min(qPi,51)=37 ⇒ Q=39 ⇒ tC′=5. + assert_eq!(chroma_tc(37, 37, 0, 3, 0, 8), 5); + // 10-bit scales by 1<<(BitDepthC−8)=4. + assert_eq!(chroma_tc(37, 37, 0, 1, 0, 10), 4 * 4); + } + + /// §8.7.2.5.8 chroma sample filter: a flat edge is unchanged. + #[test] + fn chroma_filter_flat_unchanged() { + let (p0, q0) = filter_chroma_sample([100, 100], [100, 100], 6, 8); + assert_eq!(p0, 100); + assert_eq!(q0, 100); + } + + /// §8.7.2.5.8 chroma sample filter centres a small step and clips δ. + /// p0=98,q0=102,p1=q1=100 ⇒ δ=((4·4)+0+4)>>3 = 20>>3 = 2 ⇒ clamp 2 ⇒ + /// p0'=100, q0'=100. + #[test] + fn chroma_filter_small_step() { + let (p0, q0) = filter_chroma_sample([98, 100], [102, 100], 6, 8); + assert_eq!(p0, 100); + assert_eq!(q0, 100); + // tC clamp: hard step 0/255, tC=3 ⇒ δ clamped to 3. + let (p0, q0) = filter_chroma_sample([0, 0], [255, 255], 3, 8); + assert_eq!(p0, 3); + assert_eq!(q0, 252); + } + + // ----- §8.7.2.5.4 / .5 plane-level block-edge filtering ----- + + /// A vertical edge at plane `(x, y)`. + fn vpos(x: usize, y: usize) -> EdgePos { + EdgePos { + ex: x, + ey: y, + edge: EdgeType::Vertical, + } + } + + /// 8-bit QP context with no slice offsets. + fn qp8(qp_q: i32, qp_p: i32) -> EdgeQp { + EdgeQp { + qp_q, + qp_p, + beta_offset_div2: 0, + tc_offset_div2: 0, + bit_depth: 8, + } + } + + /// Build a `w×h` plane filled with a constant value plus a single + /// vertical step at column `step_x` (left = `lo`, right = `hi`). + fn vstep_plane(w: usize, h: usize, step_x: usize, lo: i32, hi: i32) -> Vec { + let mut v = vec![0i32; w * h]; + for y in 0..h { + for x in 0..w { + v[y * w + x] = if x < step_x { lo } else { hi }; + } + } + v + } + + /// §8.7.2.5.4 EDGE_VER: a small uniform step across a vertical edge + /// is smoothed (the boundary columns move toward each other), and the + /// strong filter touches 3 samples each side. + #[test] + fn luma_block_edge_ver_smooths_small_step() { + let (w, h) = (16usize, 8usize); + // Step of 8 at column 8: left=120, right=128. With low QP the + // strong/weak decision fires (flat halves ⇒ d=0 < β). + let mut buf = vstep_plane(w, h, 8, 120, 128); + let before_p0 = buf[7]; // column 7, row 0 (p0) + let before_q0 = buf[8]; // column 8, row 0 (q0) + let mut plane = SamplePlane { + samples: &mut buf, + width: w, + stride: w, + }; + // QP 37 both sides ⇒ β=36, tC=5 (bS=2) at 8-bit; step 8 < β. + let dec = filter_luma_block_edge(&mut plane, vpos(8, 0), 2, qp8(37, 37)); + assert_ne!(dec.de, 0, "edge should be filtered"); + // p0 rose toward the boundary, q0 fell toward it. + assert!(plane.get(7, 0) > before_p0); + assert!(plane.get(8, 0) < before_q0); + // Samples far from the edge (col 0, col 15) are untouched. + assert_eq!(plane.get(0, 0), 120); + assert_eq!(plane.get(15, 0), 128); + } + + /// §8.7.2.5.4: a large step at low QP leaves the plane byte-identical. + /// The flat halves pass `d < β` so `dE` may be 1 (weak filter armed), + /// but the weak filter's `|δ| < 10·tC` guard fails for the huge step, + /// so `nDp = nDq = 0` and no sample is modified. + #[test] + fn luma_block_edge_ver_skips_large_step() { + let (w, h) = (16usize, 8usize); + let mut buf = vstep_plane(w, h, 8, 0, 255); + let snapshot = buf.clone(); + let mut plane = SamplePlane { + samples: &mut buf, + width: w, + stride: w, + }; + // Low QP (β=10, tC=1): the weak filter is rejected by the δ guard. + filter_luma_block_edge(&mut plane, vpos(8, 0), 2, qp8(20, 20)); + assert_eq!(*plane.samples, snapshot[..]); + } + + /// §8.7.2.5.4 EDGE_HOR mirrors EDGE_VER: a horizontal step at row 4 + /// is smoothed across the boundary rows. + #[test] + fn luma_block_edge_hor_smooths_small_step() { + let (w, h) = (8usize, 16usize); + let mut buf = vec![0i32; w * h]; + for y in 0..h { + for x in 0..w { + buf[y * w + x] = if y < 8 { 120 } else { 128 }; + } + } + let mut plane = SamplePlane { + samples: &mut buf, + width: w, + stride: w, + }; + // Boundary at row 8 (q0,0 row): filter the EDGE_HOR segment at x=0. + let pos = EdgePos { + ex: 0, + ey: 8, + edge: EdgeType::Horizontal, + }; + let dec = filter_luma_block_edge(&mut plane, pos, 2, qp8(37, 37)); + assert_ne!(dec.de, 0); + assert!(plane.get(0, 7) > 120); // p0 row rose + assert!(plane.get(0, 8) < 128); // q0 row fell + } + + /// §8.7.2.5.5 chroma EDGE_VER: only p0/q0 columns are modified; p1/q1 + /// and farther samples stay put. + #[test] + fn chroma_block_edge_ver_only_p0_q0() { + let (w, h) = (16usize, 8usize); + let mut buf = vstep_plane(w, h, 8, 124, 128); + let mut plane = SamplePlane { + samples: &mut buf, + width: w, + stride: w, + }; + // 4:2:0, QpY 37 both sides ⇒ tC=4 (8-bit). Step 4 ⇒ δ clamped. + filter_chroma_block_edge(&mut plane, vpos(8, 0), qp8(37, 37), 0, 1); + // p0 (col 7) and q0 (col 8) move; p1 (col 6) and q1 (col 9) don't. + assert!(plane.get(7, 0) > 124); + assert!(plane.get(8, 0) < 128); + assert_eq!(plane.get(6, 0), 124); + assert_eq!(plane.get(9, 0), 128); + } + + /// Integration: a 16×16 luma plane with two flat 120/128 halves, + /// filter the internal vertical edge with strong-filter QP, and + /// confirm the result is monotonic across the (now smoothed) seam and + /// stays within the clip bounds of the original samples. + #[test] + fn integration_internal_vertical_seam() { + let (w, h) = (16usize, 16usize); + let mut buf = vstep_plane(w, h, 8, 120, 128); + let mut plane = SamplePlane { + samples: &mut buf, + width: w, + stride: w, + }; + let dec = filter_luma_block_edge(&mut plane, vpos(8, 0), 2, qp8(40, 40)); + assert_ne!(dec.de, 0); + for y in 0..4 { + // Across the seam columns 5..11 the row is non-decreasing + // (the filter cannot create overshoot beyond the 120..128 + // span for this monotone input). + for x in 5..11 { + let a = plane.get(x, y); + let b = plane.get(x + 1, y); + assert!(a <= b, "row {y}: col {x}={a} > col {}={b}", x + 1); + assert!( + (120..=128).contains(&a), + "col {x} row {y} = {a} out of span" + ); + } + } + } + + // ----- §8.7.2.5.1 / .2 CU-level edge filtering driver ----- + + fn cu_params_420(qp_y: i32) -> DeblockCuParams { + DeblockCuParams { + qp_y, + beta_offset_div2: 0, + tc_offset_div2: 0, + cb_qp_offset: 0, + cr_qp_offset: 0, + bit_depth_luma: 8, + bit_depth_chroma: 8, + chroma_array_type: 1, + } + } + + /// A `DeblockCu` for a 16×16 CU at `(x_cb, y_cb)`, QpY = 37 both sides. + fn cu16(x_cb: usize, y_cb: usize) -> DeblockCu { + DeblockCu { + x_cb, + y_cb, + log2_cb_size: 4, + params: cu_params_420(37), + qp_y_p_left: 37, + qp_y_p_top: 37, + } + } + + /// Build a 16×16 4:2:0 picture whose luma has a vertical 120/128 step + /// at column 8 and flat chroma planes. + fn stepped_pic() -> Picture { + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, if x < 8 { 120 } else { 128 }); + if x < 8 && y < 8 { + pic.set_sample(Plane::Cb, x, y, if x < 4 { 124 } else { 128 }); + pic.set_sample(Plane::Cr, x, y, if x < 4 { 124 } else { 128 }); + } + } + } + pic + } + + /// §8.7.2.5.1: a 16×16 CU's internal vertical luma edge at column 8 + /// (bS=2) is filtered, smoothing the 120/128 step; the picture-left + /// edge (bS grid zero there) is left untouched. + #[test] + fn cu_driver_vertical_luma_internal_edge() { + let mut pic = stepped_pic(); + // bS grid: internal vertical edge at column 8, all 4 row-segments. + let n = 16; + let mut edge_flags = vec![false; n * n]; + let mut tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + tb_edge[yj * n + 8] = true; + } + // Intra both sides ⇒ bS=2 at the internal edge. + let field = MotionField::new(16, 16); + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 2); + let before7 = pic.sample(Plane::Luma, 7, 0); + let before8 = pic.sample(Plane::Luma, 8, 0); + filter_cu_edges(&mut pic, &cu16(0, 0), EdgeType::Vertical, &bs); + // The internal seam smoothed: col 7 rose, col 8 fell. + assert!(pic.sample(Plane::Luma, 7, 0) > before7); + assert!(pic.sample(Plane::Luma, 8, 0) < before8); + // Picture-left column 0 unfiltered (bS=0 there). + assert_eq!(pic.sample(Plane::Luma, 0, 0), 120); + } + + /// §8.7.2.5.1 chroma 4:2:0: an *internal* CU edge at luma column 8 maps + /// to chroma column 4, which is NOT on the 8-chroma-sample grid, so the + /// chroma filter is correctly skipped (only luma is touched). 4:2:0 + /// chroma deblocking falls only every 16 luma samples. + #[test] + fn cu_driver_chroma_skips_non_8_aligned_edge() { + let mut pic = stepped_pic(); + let before_cb3 = pic.sample(Plane::Cb, 3, 0); + let before_cb4 = pic.sample(Plane::Cb, 4, 0); + let n = 16; + let mut edge_flags = vec![false; n * n]; + let mut tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + tb_edge[yj * n + 8] = true; + } + let field = MotionField::new(16, 16); + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + filter_cu_edges(&mut pic, &cu16(0, 0), EdgeType::Vertical, &bs); + // Chroma col 4 is not 8-aligned ⇒ untouched; luma seam moved. + assert_eq!(pic.sample(Plane::Cb, 3, 0), before_cb3); + assert_eq!(pic.sample(Plane::Cb, 4, 0), before_cb4); + assert!(pic.sample(Plane::Luma, 7, 0) > 120); + } + + /// §8.7.2.5.1 chroma 4:2:0: a CU boundary edge that DOES land on the + /// 8-chroma grid (the right CU's left edge at luma column 16 ⇒ chroma + /// column 8) fires the chroma filter; p0/q0 (chroma cols 7/8) move. + #[test] + fn cu_driver_chroma_filters_8_aligned_edge() { + // 32×16 picture: left CU 120, right CU 128; chroma 124/128 step at + // chroma column 8 (= luma column 16). + let mut pic = Picture::new(32, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..32 { + pic.set_sample(Plane::Luma, x, y, if x < 16 { 120 } else { 128 }); + } + } + // 4:2:0 chroma plane is 16×8. + for y in 0..8 { + for x in 0..16 { + pic.set_sample(Plane::Cb, x, y, if x < 8 { 124 } else { 128 }); + pic.set_sample(Plane::Cr, x, y, if x < 8 { 124 } else { 128 }); + } + } + // Right CU at luma (16,0), 16×16. Its left CB-boundary vertical edge + // (xDk=0) is filtered (filterLeftCbEdgeFlag = 1, intra both sides). + let n = 16; + let mut edge_flags = vec![false; n * n]; + let mut tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n] = true; // column 0 = the CU's left boundary + tb_edge[yj * n] = true; + } + // Motion field: left half (cols 0..16) and right CU intra ⇒ bS=2. + let field = MotionField::new(32, 16); + let bs = + derive_boundary_strength(&field, 16, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(0, 0), 2); + filter_cu_edges(&mut pic, &cu16(16, 0), EdgeType::Vertical, &bs); + // Chroma edge at chroma column 8 (8-aligned): p0 (col 7) rose, + // q0 (col 8) fell. + assert!(pic.sample(Plane::Cb, 7, 0) > 124); + assert!(pic.sample(Plane::Cb, 8, 0) < 128); + assert!(pic.sample(Plane::Cr, 7, 0) > 124); + // p1 (col 6) untouched. + assert_eq!(pic.sample(Plane::Cb, 6, 0), 124); + } + + /// §8.7.2.5.2: the horizontal driver mirrors the vertical one — an + /// internal horizontal luma edge at row 8 is smoothed. + #[test] + fn cu_driver_horizontal_luma_internal_edge() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, if y < 8 { 120 } else { 128 }); + } + } + let n = 16; + let mut edge_flags = vec![false; n * n]; + let mut tb_edge = vec![false; n * n]; + for xi in (0..16).step_by(4) { + edge_flags[8 * n + xi] = true; + tb_edge[8 * n + xi] = true; + } + let field = MotionField::new(16, 16); + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Horizontal, &edge_flags, &tb_edge); + assert_eq!(bs.at(0, 8), 2); + filter_cu_edges(&mut pic, &cu16(0, 0), EdgeType::Horizontal, &bs); + assert!(pic.sample(Plane::Luma, 0, 7) > 120); // p0 row rose + assert!(pic.sample(Plane::Luma, 0, 8) < 128); // q0 row fell + } + + /// A bS=1 edge filters luma but NOT chroma (chroma fires only at + /// bS==2). + #[test] + fn cu_driver_bs1_skips_chroma() { + let mut pic = stepped_pic(); + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + // Two inter blocks, MV diff ⇒ bS=1. + let mut field = MotionField::new(16, 16); + field.fill_rect(0, 0, 8, 16, inter_cell([0, 0], 0)); + field.fill_rect(8, 0, 8, 16, inter_cell([4, 0], 0)); + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + assert_eq!(bs.at(8, 0), 1); + filter_cu_edges(&mut pic, &cu16(0, 0), EdgeType::Vertical, &bs); + // Chroma untouched (bS=1 < 2). + assert_eq!(pic.sample(Plane::Cb, 3, 0), 124); + assert_eq!(pic.sample(Plane::Cb, 4, 0), 128); + } + + /// Monochrome (ChromaArrayType 0): the driver filters luma and never + /// touches a chroma plane (there is none). + #[test] + fn cu_driver_monochrome_luma_only() { + let mut pic = Picture::new(16, 16, 0, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, if x < 8 { 120 } else { 128 }); + } + } + let n = 16; + let mut edge_flags = vec![false; n * n]; + let tb_edge = vec![false; n * n]; + for yj in (0..16).step_by(4) { + edge_flags[yj * n + 8] = true; + } + let field = MotionField::new(16, 16); + let bs = + derive_boundary_strength(&field, 0, 0, 4, EdgeType::Vertical, &edge_flags, &tb_edge); + let mut p = cu_params_420(37); + p.chroma_array_type = 0; + let cu = DeblockCu { + x_cb: 0, + y_cb: 0, + log2_cb_size: 4, + params: p, + qp_y_p_left: 37, + qp_y_p_top: 37, + }; + filter_cu_edges(&mut pic, &cu, EdgeType::Vertical, &bs); + assert!(pic.sample(Plane::Luma, 7, 0) > 120); + } + + // ----- §8.7.2.1 picture-level deblocking driver ----- + + /// §8.7.2.1: a 2×1 grid of 16×16 CUs with a 120/128 vertical step at + /// the CU boundary (luma column 16). The driver derives the bS=2 + /// boundary edge (intra both sides) and smooths the seam; the picture's + /// outer-left edge (filter_left=false on CU 0) stays untouched. + #[test] + fn picture_driver_two_cu_vertical_seam() { + let mut pic = Picture::new(32, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..32 { + pic.set_sample(Plane::Luma, x, y, if x < 16 { 120 } else { 128 }); + } + } + for y in 0..8 { + for x in 0..16 { + pic.set_sample(Plane::Cb, x, y, if x < 8 { 124 } else { 128 }); + pic.set_sample(Plane::Cr, x, y, if x < 8 { 124 } else { 128 }); + } + } + // Whole picture intra ⇒ every block boundary is bS=2. + let field = MotionField::new(32, 16); + let cus = vec![ + DeblockCuDesc { + cu: cu16(0, 0), + transform_split: TransformSplit::leaf(), + part_mode: PartMode::Part2Nx2N, + filter_left: false, // picture-left boundary + filter_top: false, // picture-top boundary + }, + DeblockCuDesc { + cu: cu16(16, 0), + transform_split: TransformSplit::leaf(), + part_mode: PartMode::Part2Nx2N, + filter_left: true, // internal CU boundary at column 16 + filter_top: false, + }, + ]; + deblock_picture(&mut pic, &field, &cus); + // The CU-boundary luma seam at column 16 smoothed. + assert!(pic.sample(Plane::Luma, 15, 0) > 120); + assert!(pic.sample(Plane::Luma, 16, 0) < 128); + // The picture-left column 0 untouched. + assert_eq!(pic.sample(Plane::Luma, 0, 0), 120); + // Chroma seam at chroma column 8 (8-aligned, bS=2) smoothed. + assert!(pic.sample(Plane::Cb, 7, 0) > 124); + assert!(pic.sample(Plane::Cb, 8, 0) < 128); + } + + /// §8.7.2.1: with every `filter_left` / `filter_top` false and a single + /// un-split PART_2Nx2N CU, no internal edge exists, so the picture is + /// byte-identical after deblocking (the entire CU is one transform / + /// prediction block at the picture origin). + #[test] + fn picture_driver_single_cu_no_internal_edge_is_noop() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, if x < 8 { 0 } else { 255 }); + } + } + let snapshot: Vec = pic.plane(Plane::Luma).to_vec(); + let field = MotionField::new(16, 16); + let cus = vec![DeblockCuDesc { + cu: cu16(0, 0), + transform_split: TransformSplit::leaf(), + part_mode: PartMode::Part2Nx2N, + filter_left: false, + filter_top: false, + }]; + deblock_picture(&mut pic, &field, &cus); + assert_eq!(pic.plane(Plane::Luma), snapshot.as_slice()); + } + + /// §8.7.2.1: a single CU with a one-level transform split has an + /// internal vertical + horizontal TB edge at the 8-sample mid-lines; + /// the driver smooths both the vertical seam (pass 1) and then the + /// horizontal seam (pass 2) on the already-modified samples. + #[test] + fn picture_driver_internal_split_both_directions() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + // Four quadrants stepping in both x and y for a cross seam. + for y in 0..16 { + for x in 0..16 { + let v = 120 + 4 * i32::from(x >= 8) + 4 * i32::from(y >= 8); + pic.set_sample(Plane::Luma, x, y, v); + } + } + let field = MotionField::new(16, 16); + let cus = vec![DeblockCuDesc { + cu: cu16(0, 0), + transform_split: TransformSplit::split_once(), + part_mode: PartMode::Part2Nx2N, + filter_left: false, + filter_top: false, + }]; + deblock_picture(&mut pic, &field, &cus); + // Vertical seam at column 8 (rows 0..) smoothed: col 7 rose. + assert!(pic.sample(Plane::Luma, 7, 0) > 120); + // Horizontal seam at row 8 smoothed: row 7 rose at a left column. + assert!(pic.sample(Plane::Luma, 0, 7) > 120); + // A corner far from both seams is untouched. + assert_eq!(pic.sample(Plane::Luma, 0, 0), 120); + } +} diff --git a/vendor/oxideav-h265/src/decode.rs b/vendor/oxideav-h265/src/decode.rs new file mode 100644 index 0000000..24aab94 --- /dev/null +++ b/vendor/oxideav-h265/src/decode.rs @@ -0,0 +1,349 @@ +//! Picture-sequence decode state machine: the §8.3.1 → §8.3.2 → §8.3.4 → +//! §8.3.5 per-picture chain that ties the [`crate::poc`] POC derivation +//! and the [`crate::dpb`] decoded-picture buffer together. +//! +//! [`PictureSequenceState`] threads the cross-picture state — the +//! [`crate::poc::PocState`] (`prevTid0Pic`) and the [`crate::dpb::Dpb`] — +//! across a coded video sequence. For each coded picture the driver: +//! +//! 1. derives `PicOrderCntVal` (§8.3.1) from the picture's `NalKind`, +//! `TemporalId`, `NoRaslOutputFlag` and `slice_pic_order_cnt_lsb`; +//! 2. builds the five §8.3.2 RPS POC lists and applies the §8.3.2 marking +//! to the DPB, resolving the RPS to concrete DPB entries; +//! 3. for a P / B slice, constructs `RefPicList0` / `RefPicList1` (§8.3.4) +//! and selects the §8.3.5 `ColPic` + `NoBackwardPredFlag` for temporal +//! MV prediction. +//! +//! After the picture's samples + per-PU motion field are reconstructed, +//! [`PictureSequenceState::store_picture`] inserts it into the DPB as a +//! short-term reference, completing the per-picture cycle. + +use crate::dpb::{ + build_rps_poc_lists, no_backward_pred_flag, select_col_pic, Dpb, DpbEntry, LongTermEntry, + Marking, RefPicListParams, RefPicLists, ResolvedRps, +}; +use crate::motion::MotionField; +use crate::picture::Picture; +use crate::poc::{NalKind, PicOrderCnt, PocState}; +use crate::sps::MaterializedShortTermRefPicSet; + +/// The per-picture §8.3 inputs the [`PictureSequenceState`] driver needs, +/// resolved from the picture's NAL header + activated SPS + parsed slice +/// segment header. +#[derive(Debug, Clone)] +pub struct PictureHeaderInfo { + /// The picture's `nal_unit_type` classification. + pub nal_kind: NalKind, + /// `TemporalId`. + pub temporal_id: u8, + /// `nuh_layer_id`. + pub layer_id: u8, + /// `NoRaslOutputFlag`. + pub no_rasl_output: bool, + /// `slice_pic_order_cnt_lsb` (0 for an IDR). + pub poc_lsb: u32, + /// `MaxPicOrderCntLsb` from the active SPS. + pub max_poc_lsb: u32, + /// The current picture's materialized short-term RPS + /// (`DeltaPocS0` / `UsedByCurrPicS0` / …). + pub short_term_rps: MaterializedShortTermRefPicSet, + /// The current picture's long-term RPS entries (§7.4.7.1-resolved). + pub long_term: Vec, +} + +/// The §8.3 per-picture decode outputs the slice / CU decode then uses. +#[derive(Debug, Clone)] +pub struct PictureRefState { + /// The derived `PicOrderCntVal` (§8.3.1). + pub poc: PicOrderCnt, + /// The §8.3.2 RPS resolved to DPB entry indices. + pub rps: ResolvedRps, + /// `RefPicList0` / `RefPicList1` (§8.3.4), `None` for an I slice. + pub ref_pic_lists: Option, + /// `ColPic` (§8.3.5) — DPB index of the collocated picture, when + /// `slice_temporal_mvp_enabled_flag` and a P / B slice selected one. + pub col_pic: Option, + /// `NoBackwardPredFlag` (§8.3.5). + pub no_backward_pred: bool, +} + +/// The per-slice §8.3.4 / §8.3.5 inputs (the reference-list sizing + the +/// collocated-picture selectors from the slice segment header). +#[derive(Debug, Clone, Copy)] +pub struct SliceRefParams { + /// `true` for a P or B slice (builds reference lists). + pub is_inter: bool, + /// `true` for a B slice (builds `RefPicList1`). + pub is_b: bool, + /// `num_ref_idx_l0_active_minus1`. + pub num_ref_idx_l0_active_minus1: u32, + /// `num_ref_idx_l1_active_minus1`. + pub num_ref_idx_l1_active_minus1: u32, + /// `NumPicTotalCurr` (§7.4.7.2). + pub num_pic_total_curr: u32, + /// `slice_temporal_mvp_enabled_flag`. + pub temporal_mvp_enabled: bool, + /// `collocated_from_l0_flag` (inferred 1 for a P slice). + pub collocated_from_l0_flag: bool, + /// `collocated_ref_idx` (inferred 0 when absent). + pub collocated_ref_idx: u32, + /// `pps_curr_pic_ref_enabled_flag` — the §8.3.4 currPic append + /// (intra block copy). + pub curr_pic_ref_enabled: bool, +} + +/// The cross-picture decode state for one coded video sequence. +#[derive(Debug, Default)] +pub struct PictureSequenceState { + poc_state: PocState, + dpb: Dpb, +} + +impl PictureSequenceState { + /// A fresh state at the start of a coded video sequence. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Borrow the decoded-picture buffer (reference-picture inspection). + #[must_use] + pub fn dpb(&self) -> &Dpb { + &self.dpb + } + + /// §8.3.1 → §8.3.2 → §8.3.4 → §8.3.5 — run the per-picture reference + /// derivation for a picture about to be decoded. + /// + /// `header` carries the POC + RPS inputs; `slice` carries the + /// reference-list / collocated-picture selectors. The returned + /// [`PictureRefState`] is consumed by the slice / CU decode (its + /// `RefPicList0` / `ColPic` resolve `RefPicListX[ refIdx ]` and the + /// temporal-MV collocated picture). + pub fn begin_picture( + &mut self, + header: &PictureHeaderInfo, + slice: &SliceRefParams, + ) -> PictureRefState { + // Step 1 — §8.3.1 POC. + let poc = self.poc_state.decode_picture_poc( + header.nal_kind, + header.temporal_id, + header.no_rasl_output, + header.poc_lsb, + header.max_poc_lsb, + ); + + // Step 2 — §8.3.2 RPS POC lists + DPB marking. + let lists = build_rps_poc_lists( + header.nal_kind.is_idr(), + poc.val, + header.max_poc_lsb, + &header.short_term_rps, + &header.long_term, + ); + let is_irap_no_rasl = header.nal_kind.is_irap() && header.no_rasl_output; + let rps = self + .dpb + .apply_rps(is_irap_no_rasl, header.layer_id, &lists, header.max_poc_lsb); + + // Step 3 — §8.3.4 reference picture lists (P / B only). + let ref_pic_lists = if slice.is_inter { + Some(self.dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_ref_idx_l0_active_minus1: slice.num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1: slice.num_ref_idx_l1_active_minus1, + num_pic_total_curr: slice.num_pic_total_curr, + is_b: slice.is_b, + list_entry_l0: None, + list_entry_l1: None, + curr_pic_ref_enabled: slice.curr_pic_ref_enabled, + }, + )) + } else { + None + }; + + // Step 4 — §8.3.5 ColPic + NoBackwardPredFlag. + let (col_pic, no_backward_pred) = match &ref_pic_lists { + Some(rpl) if slice.temporal_mvp_enabled => ( + select_col_pic( + rpl, + slice.is_b, + slice.collocated_from_l0_flag, + slice.collocated_ref_idx, + ), + no_backward_pred_flag(&self.dpb, rpl, poc.val), + ), + Some(rpl) => (None, no_backward_pred_flag(&self.dpb, rpl, poc.val)), + None => (None, true), + }; + + PictureRefState { + poc, + rps, + ref_pic_lists, + col_pic, + no_backward_pred, + } + } + + /// Insert a freshly-decoded picture into the DPB as a short-term + /// reference, completing the per-picture cycle. `picture` are the + /// reconstructed (in-loop-filtered) samples; `motion` is the per-PU + /// motion field for the §8.5.3.2.9 collocated-MV derivation of future + /// pictures. + pub fn store_picture( + &mut self, + poc: PicOrderCnt, + layer_id: u8, + picture: Picture, + motion: MotionField, + ) { + self.dpb.insert(DpbEntry { + poc: poc.val, + layer_id, + marking: Marking::ShortTerm, + picture, + motion, + }); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn empty_rps() -> MaterializedShortTermRefPicSet { + MaterializedShortTermRefPicSet { + delta_poc_s0: vec![], + used_by_curr_pic_s0: vec![], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + } + } + + fn idr_header() -> PictureHeaderInfo { + PictureHeaderInfo { + nal_kind: NalKind::new(NalKind::IDR_N_LP), + temporal_id: 0, + layer_id: 0, + no_rasl_output: true, + poc_lsb: 0, + max_poc_lsb: 256, + short_term_rps: empty_rps(), + long_term: vec![], + } + } + + fn i_slice() -> SliceRefParams { + SliceRefParams { + is_inter: false, + is_b: false, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + num_pic_total_curr: 0, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + collocated_ref_idx: 0, + curr_pic_ref_enabled: false, + } + } + + #[test] + fn idr_then_p_frame_resolves_ref_pic_list() { + let mut st = PictureSequenceState::new(); + // IDR (POC 0), I slice, no references. + let idr = st.begin_picture(&idr_header(), &i_slice()); + assert_eq!(idr.poc.val, 0); + assert!(idr.ref_pic_lists.is_none()); + st.store_picture( + idr.poc, + 0, + Picture::new(16, 16, 1, 8, 8), + MotionField::new(16, 16), + ); + + // P frame (POC 1), one short-term-before ref at POC 0. + let p_header = PictureHeaderInfo { + nal_kind: NalKind::new(NalKind::TRAIL_R), + no_rasl_output: false, + poc_lsb: 1, + short_term_rps: MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }, + ..idr_header() + }; + let p_slice = SliceRefParams { + is_inter: true, + num_pic_total_curr: 1, + ..i_slice() + }; + let p = st.begin_picture(&p_header, &p_slice); + assert_eq!(p.poc.val, 1); + let rpl = p.ref_pic_lists.expect("P slice builds RefPicList0"); + // RefPicList0[0] points at the IDR (DPB index 0). + assert_eq!(rpl.list0, vec![Some(0)]); + // The IDR stays short-term (it is in the P frame's RPS). + assert_eq!(st.dpb().entries()[0].marking, Marking::ShortTerm); + // NoBackwardPredFlag: the only ref (POC 0) is in the past of POC 1. + assert!(p.no_backward_pred); + } + + #[test] + fn temporal_mvp_selects_col_pic() { + let mut st = PictureSequenceState::new(); + let idr = st.begin_picture(&idr_header(), &i_slice()); + st.store_picture( + idr.poc, + 0, + Picture::new(16, 16, 1, 8, 8), + MotionField::new(16, 16), + ); + + let p_header = PictureHeaderInfo { + nal_kind: NalKind::new(NalKind::TRAIL_R), + no_rasl_output: false, + poc_lsb: 1, + short_term_rps: MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }, + ..idr_header() + }; + let p_slice = SliceRefParams { + is_inter: true, + num_pic_total_curr: 1, + temporal_mvp_enabled: true, + collocated_from_l0_flag: true, + collocated_ref_idx: 0, + curr_pic_ref_enabled: false, + ..i_slice() + }; + let p = st.begin_picture(&p_header, &p_slice); + // ColPic = RefPicList0[0] = the IDR at DPB index 0. + assert_eq!(p.col_pic, Some(0)); + } + + #[test] + fn second_idr_unmarks_prior_references() { + let mut st = PictureSequenceState::new(); + let idr = st.begin_picture(&idr_header(), &i_slice()); + st.store_picture( + idr.poc, + 0, + Picture::new(16, 16, 1, 8, 8), + MotionField::new(16, 16), + ); + // A second IDR with NoRaslOutputFlag == 1 marks the prior IDR + // "unused for reference". + let _ = st.begin_picture(&idr_header(), &i_slice()); + assert_eq!(st.dpb().entries()[0].marking, Marking::Unused); + } +} diff --git a/vendor/oxideav-h265/src/decoder.rs b/vendor/oxideav-h265/src/decoder.rs new file mode 100644 index 0000000..a662e81 --- /dev/null +++ b/vendor/oxideav-h265/src/decoder.rs @@ -0,0 +1,214 @@ +//! Registry decoder — the [`oxideav_core::Decoder`] contract over the +//! whole-bitstream [`crate::sequence`] driver. +//! +//! [`make_decoder`] is the direct factory endpoint (the crate's +//! historical direct-API convention); [`crate::register`] wires the +//! same factory into the [`oxideav_core`] codec registry under the +//! `"h265"` / `"hevc"` ids and the common container tags. +//! +//! Packets carry either Annex B byte-stream chunks (start-code +//! delimited NAL units) or, when `CodecParameters::extradata` is an +//! `hvcC` / `HEVCDecoderConfigurationRecord` (ISO/IEC 14496-15 +//! §8.3.3.1), length-prefixed NAL runs as ISO-BMFF samples carry them. +//! Extradata in either form is fed ahead of the first packet so +//! out-of-band parameter sets activate. Output frames come in output +//! (PicOrderCntVal) order, with packet PTS values re-attached in +//! ascending order; an empty packet flushes the reorder queue. + +use std::collections::BinaryHeap; +use std::collections::VecDeque; + +use oxideav_core::{ + CodecId, CodecParameters, Decoder, Error, Frame, Packet, Result, VideoFrame, VideoPlane, +}; + +use crate::hvcc::{extradata_is_hvcc, parse_hvcc, split_length_prefixed}; +use crate::picture::{Picture, Plane}; +use crate::sequence::{DecodedFrame, SequenceDecoder}; + +/// The default reorder depth when no SPS has been activated yet (the +/// §7.4.3.2.1 `sps_max_num_reorder_pics` bound once one has). +const DEFAULT_REORDER: usize = 8; + +/// H.265 / HEVC Annex B streaming decoder. +pub struct H265Decoder { + codec_id: CodecId, + seq: SequenceDecoder, + /// Decoded pictures not yet emitted, sorted on demand by + /// `(cvs_index, poc)`. + reorder: Vec, + /// Frames ready to hand out. + ready: VecDeque, + /// Min-heap of packet PTS values, re-attached in output order. + pts_queue: BinaryHeap>, + /// `Some(n)` when the extradata was an `hvcC` record: packets are + /// length-prefixed NAL runs with `n`-byte big-endian sizes + /// (ISO/IEC 14496-15 §8.3.3.1.3 `lengthSizeMinusOne + 1`). + /// `None` for Annex B packets. + nal_length_size: Option, + flushed: bool, +} + +impl std::fmt::Debug for H265Decoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("H265Decoder") + .field("codec_id", &self.codec_id) + .field("reorder", &self.reorder.len()) + .field("ready", &self.ready.len()) + .finish() + } +} + +/// Direct factory endpoint: construct the software H.265 decoder. +/// +/// The `extradata` form selects the packet framing: an `hvcC` +/// (`HEVCDecoderConfigurationRecord`) extradata activates its carried +/// parameter sets and switches packets to length-prefixed NAL runs; +/// Annex B extradata (or none) keeps start-code framing. +/// +/// # Errors +/// [`Error::InvalidData`] when the `extradata` fails to parse. +pub fn make_decoder(params: &CodecParameters) -> Result> { + let mut seq = SequenceDecoder::new(); + let mut nal_length_size = None; + if !params.extradata.is_empty() { + if extradata_is_hvcc(¶ms.extradata) { + // hvcC record: out-of-band VPS/SPS/PPS (+ SEI) arrays. + let rec = parse_hvcc(¶ms.extradata) + .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?; + for unit in rec.nal_units { + seq.push_nal_unit(unit) + .map_err(|e| Error::InvalidData(format!("h265 hvcC extradata: {e}")))?; + } + nal_length_size = Some(rec.length_size); + } else { + // Out-of-band parameter sets in Annex B form. + seq.push_annexb(¶ms.extradata) + .map_err(|e| Error::InvalidData(format!("h265 extradata: {e}")))?; + } + } + Ok(Box::new(H265Decoder { + codec_id: params.codec_id.clone(), + seq, + reorder: Vec::new(), + ready: VecDeque::new(), + pts_queue: BinaryHeap::new(), + nal_length_size, + flushed: false, + })) +} + +impl H265Decoder { + /// Move decoded pictures into the reorder buffer and emit every + /// frame that is guaranteed next in output order. + fn drain(&mut self, flush: bool) { + self.reorder.extend(self.seq.take_decoded()); + self.reorder.sort_by_key(|f| (f.cvs_index, f.poc)); + let depth = if flush { + 0 + } else { + self.seq + .max_num_reorder_pics() + .map_or(DEFAULT_REORDER, |n| n as usize) + }; + while self.reorder.len() > depth { + let f = self.reorder.remove(0); + if !f.output { + continue; + } + let pts = self.pts_queue.pop().map(|r| r.0); + self.ready + .push_back(Frame::Video(video_frame(&f.picture, pts))); + } + } +} + +impl Decoder for H265Decoder { + fn codec_id(&self) -> &CodecId { + &self.codec_id + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + if packet.data.is_empty() { + // An empty packet is treated as a flush signal too. + return self.flush(); + } + if let Some(pts) = packet.pts { + self.pts_queue.push(std::cmp::Reverse(pts)); + } + if let Some(length_size) = self.nal_length_size { + let units = split_length_prefixed(&packet.data, length_size) + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; + for unit in units { + self.seq + .push_nal_unit(unit) + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; + } + } else { + self.seq + .push_annexb(&packet.data) + .map_err(|e| Error::InvalidData(format!("h265 decode: {e}")))?; + } + self.drain(false); + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + if let Some(f) = self.ready.pop_front() { + return Ok(f); + } + if self.flushed { + if !self.reorder.is_empty() { + self.drain(true); + if let Some(f) = self.ready.pop_front() { + return Ok(f); + } + } + return Err(Error::Eof); + } + Err(Error::NeedMore) + } + + fn flush(&mut self) -> Result<()> { + // Decode any pending picture and release the reorder queue. + self.seq + .flush() + .map_err(|e| Error::InvalidData(format!("h265 flush: {e}")))?; + self.flushed = true; + self.drain(true); + Ok(()) + } +} + +/// Pack a reconstructed [`Picture`] into a [`VideoFrame`] (8-bit planes +/// as one byte per sample; higher bit depths as little-endian 16-bit, +/// the planar `p010le`-family layout). +fn video_frame(pic: &Picture, pts: Option) -> VideoFrame { + let planes = if pic.chroma_array_type() == 0 { + vec![Plane::Luma] + } else { + vec![Plane::Luma, Plane::Cb, Plane::Cr] + }; + let wide = pic.bit_depth(Plane::Luma) > 8 + || (pic.chroma_array_type() != 0 && pic.bit_depth(Plane::Cb) > 8); + let mut out = Vec::with_capacity(planes.len()); + for plane in planes { + let (w, h) = pic.plane_dims(plane); + let buf = pic.plane(plane); + let mut data; + let stride; + if wide { + stride = w * 2; + data = Vec::with_capacity(w * h * 2); + for &v in buf.iter().take(w * h) { + data.extend_from_slice(&(v as u16).to_le_bytes()); + } + } else { + stride = w; + data = Vec::with_capacity(w * h); + data.extend(buf.iter().take(w * h).map(|&v| v as u8)); + } + out.push(VideoPlane { stride, data }); + } + VideoFrame { pts, planes: out } +} diff --git a/vendor/oxideav-h265/src/dpb.rs b/vendor/oxideav-h265/src/dpb.rs new file mode 100644 index 0000000..543f1c1 --- /dev/null +++ b/vendor/oxideav-h265/src/dpb.rs @@ -0,0 +1,833 @@ +//! §8.3.2 reference-picture-set marking, §8.3.4 reference-picture-list +//! construction, §8.3.5 collocated-picture selection, and the +//! decoded-picture-buffer (DPB) storage that ties them together. +//! +//! A [`Dpb`] holds the previously-decoded pictures available for +//! inter prediction of the current and future pictures. Each +//! [`DpbEntry`] carries: +//! +//! * the reconstructed [`crate::picture::Picture`] samples +//! (`refPicLXL` / `refPicLXCb` / `refPicLXCr` of §8.5.3.3.2), +//! * its `PicOrderCntVal` (the §8.3.1 identity used to address it), +//! * its short/long-term reference [`Marking`], +//! * its per-PU [`crate::motion::MotionField`] (the `MvLXCol` / +//! `PredFlagLXCol` / `RefIdxLXCol`-equivalent arrays the §8.5.3.2.9 +//! collocated-MV derivation reads). +//! +//! The picture-decode driver, after deriving the current picture's POC +//! (§8.3.1), calls [`Dpb::apply_rps`] to build the five §8.3.2 RPS lists +//! (`RefPicSetStCurrBefore` … `RefPicSetLtFoll`) and mark every DPB +//! picture accordingly. For a P / B slice it then calls +//! [`Dpb::build_ref_pic_lists`] (§8.3.4) to construct `RefPicList0` / +//! `RefPicList1`, and [`select_col_pic`] (§8.3.5) to pick the collocated +//! picture for temporal MV prediction. + +use crate::motion::MotionField; +use crate::picture::Picture; +use crate::poc::diff_pic_order_cnt; +use crate::sps::MaterializedShortTermRefPicSet; + +/// A decoded picture's reference marking (§8.3.2). Exactly one of these +/// applies at any moment. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Marking { + /// "unused for reference". + Unused, + /// "used for short-term reference". + ShortTerm, + /// "used for long-term reference". + LongTerm, +} + +/// One decoded picture stored in the [`Dpb`]. +#[derive(Debug)] +pub struct DpbEntry { + /// `PicOrderCntVal` (§8.3.1). + pub poc: i32, + /// `nuh_layer_id` of the picture. + pub layer_id: u8, + /// The current reference [`Marking`]. + pub marking: Marking, + /// The reconstructed sample planes (`SL` / `SCb` / `SCr`). + pub picture: Picture, + /// The per-PU motion field — the §8.5.3.2.9 collocated arrays + /// (`PredFlagLXCol`, `MvLXCol`, the per-cell reference-picture POC + /// identity standing in for `RefIdxLXCol` → `refPicListCol`). + pub motion: MotionField, +} + +impl DpbEntry { + /// `( PicOrderCntVal & ( MaxPicOrderCntLsb − 1 ) )` — the LSB-only + /// identity used for the §8.3.2 short-term-vs-long-term lookup of a + /// long-term entry whose `delta_poc_msb_present_flag` is 0. + #[inline] + #[must_use] + fn poc_lsb(&self, max_poc_lsb: u32) -> u32 { + (self.poc as u32) & (max_poc_lsb - 1) + } +} + +/// The five §8.3.2 RPS POC lists (equation 8-5). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct RpsPocLists { + /// `PocStCurrBefore`. + pub st_curr_before: Vec, + /// `PocStCurrAfter`. + pub st_curr_after: Vec, + /// `PocStFoll`. + pub st_foll: Vec, + /// `PocLtCurr`. + pub lt_curr: Vec, + /// `PocLtFoll`. + pub lt_foll: Vec, + /// `CurrDeltaPocMsbPresentFlag[i]` (paired with `lt_curr`). + pub curr_delta_poc_msb_present: Vec, + /// `FollDeltaPocMsbPresentFlag[i]` (paired with `lt_foll`). + pub foll_delta_poc_msb_present: Vec, +} + +/// One long-term RPS input entry — the §7.4.7.1 / §8.3.2 long-term +/// reference, already resolved to `PocLsbLt[i]` plus the MSB-cycle block. +#[derive(Debug, Clone, Copy)] +pub struct LongTermEntry { + /// `PocLsbLt[i]`. + pub poc_lsb_lt: u32, + /// `UsedByCurrPicLt[i]`. + pub used_by_curr_pic_lt: bool, + /// `delta_poc_msb_present_flag[i]`. + pub delta_poc_msb_present: bool, + /// `DeltaPocMsbCycleLt[i]` (the §7.4.7.1 accumulated cycle). + pub delta_poc_msb_cycle_lt: u32, +} + +/// Build the five §8.3.2 POC lists (equation 8-5) for the current +/// picture from its current short-term RPS + long-term entries. +/// +/// `is_idr` short-circuits all five lists to empty (the §8.3.2 IDR rule). +/// `poc` is the current `PicOrderCntVal`; `max_poc_lsb` is +/// `MaxPicOrderCntLsb`. +#[must_use] +pub fn build_rps_poc_lists( + is_idr: bool, + poc: i32, + max_poc_lsb: u32, + st_rps: &MaterializedShortTermRefPicSet, + lt_entries: &[LongTermEntry], +) -> RpsPocLists { + let mut out = RpsPocLists::default(); + if is_idr { + return out; + } + // Negative (S0) pics — equation 8-5 first loop. + for (i, &delta) in st_rps.delta_poc_s0.iter().enumerate() { + let p = poc + delta; + if st_rps.used_by_curr_pic_s0[i] { + out.st_curr_before.push(p); + } else { + out.st_foll.push(p); + } + } + // Positive (S1) pics — equation 8-5 second loop. + for (i, &delta) in st_rps.delta_poc_s1.iter().enumerate() { + let p = poc + delta; + if st_rps.used_by_curr_pic_s1[i] { + out.st_curr_after.push(p); + } else { + out.st_foll.push(p); + } + } + // Long-term — equation 8-5 third loop. + for e in lt_entries { + let mut poc_lt = e.poc_lsb_lt as i32; + if e.delta_poc_msb_present { + poc_lt += poc + - (e.delta_poc_msb_cycle_lt as i32) * (max_poc_lsb as i32) + - (poc & (max_poc_lsb as i32 - 1)); + } + if e.used_by_curr_pic_lt { + out.lt_curr.push(poc_lt); + out.curr_delta_poc_msb_present.push(e.delta_poc_msb_present); + } else { + out.lt_foll.push(poc_lt); + out.foll_delta_poc_msb_present.push(e.delta_poc_msb_present); + } + } + out +} + +/// The decoded-picture buffer. +#[derive(Debug, Default)] +pub struct Dpb { + entries: Vec, +} + +impl Dpb { + /// An empty DPB. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Number of pictures currently stored. + #[inline] + #[must_use] + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Whether the DPB holds no pictures. + #[inline] + #[must_use] + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// Borrow the stored entries (output / bumping inspection). + #[must_use] + pub fn entries(&self) -> &[DpbEntry] { + &self.entries + } + + /// Insert a freshly-decoded picture, marked "used for short-term + /// reference" per the §8.3.2 default. The picture-decode driver calls + /// this after reconstruction + in-loop filtering, having already run + /// [`Dpb::apply_rps`] for the picture's own RPS. + pub fn insert(&mut self, entry: DpbEntry) { + self.entries.push(entry); + } + + /// Find a stored picture by exact `PicOrderCntVal` and `nuh_layer_id`. + #[must_use] + pub fn find_by_poc(&self, poc: i32, layer_id: u8) -> Option<&DpbEntry> { + self.entries + .iter() + .find(|e| e.poc == poc && e.layer_id == layer_id) + } + + /// Find a short-term reference picture by exact POC (§8.3.2 step 3). + fn find_short_term(&self, poc: i32, layer_id: u8) -> Option { + self.entries + .iter() + .position(|e| e.poc == poc && e.layer_id == layer_id && e.marking == Marking::ShortTerm) + } + + /// Find a long-term candidate by exact POC or by LSB-only POC + /// (§8.3.2 step 1). + fn find_long_term( + &self, + target: i32, + msb_present: bool, + max_poc_lsb: u32, + layer_id: u8, + ) -> Option { + self.entries.iter().position(|e| { + e.layer_id == layer_id + && if msb_present { + e.poc == target + } else { + e.poc_lsb(max_poc_lsb) == (target as u32) & (max_poc_lsb - 1) + } + }) + } + + /// §8.3.2 — apply the reference-picture-set marking for the current + /// picture. + /// + /// `is_irap_no_rasl` is `true` for an IRAP picture with + /// `NoRaslOutputFlag == 1` (all current references become "unused"); + /// `layer_id` is the current picture's `nuh_layer_id`; `lists` is the + /// output of [`build_rps_poc_lists`]; `max_poc_lsb` is + /// `MaxPicOrderCntLsb`. + /// + /// Returns the five resolved RPS reference-picture lists as index + /// vectors into [`Dpb::entries`]; a `None` entry is the §8.3.2 "no + /// reference picture". After this call every DPB picture carries its + /// updated [`Marking`]. + pub fn apply_rps( + &mut self, + is_irap_no_rasl: bool, + layer_id: u8, + lists: &RpsPocLists, + max_poc_lsb: u32, + ) -> ResolvedRps { + // §8.3.2 — an IRAP with NoRaslOutputFlag == 1 marks every current + // reference of this layer "unused for reference" up front. + if is_irap_no_rasl { + for e in &mut self.entries { + if e.layer_id == layer_id { + e.marking = Marking::Unused; + } + } + } + + let mut resolved = ResolvedRps::default(); + + // Step 1 — resolve the long-term RPS sets (LSB or full POC). + for (i, &poc_lt) in lists.lt_curr.iter().enumerate() { + resolved.lt_curr.push(self.find_long_term( + poc_lt, + lists.curr_delta_poc_msb_present[i], + max_poc_lsb, + layer_id, + )); + } + for (i, &poc_lt) in lists.lt_foll.iter().enumerate() { + resolved.lt_foll.push(self.find_long_term( + poc_lt, + lists.foll_delta_poc_msb_present[i], + max_poc_lsb, + layer_id, + )); + } + + // Step 2 — mark the long-term picks "used for long-term reference". + for idx in resolved + .lt_curr + .iter() + .chain(resolved.lt_foll.iter()) + .flatten() + { + self.entries[*idx].marking = Marking::LongTerm; + } + + // Step 3 — resolve the short-term RPS sets (exact POC). + for &poc in &lists.st_curr_before { + resolved + .st_curr_before + .push(self.find_short_term(poc, layer_id)); + } + for &poc in &lists.st_curr_after { + resolved + .st_curr_after + .push(self.find_short_term(poc, layer_id)); + } + for &poc in &lists.st_foll { + resolved.st_foll.push(self.find_short_term(poc, layer_id)); + } + + // Step 4 — any picture of this layer not in any RPS set is + // "unused for reference". + let mut keep = vec![false; self.entries.len()]; + for idx in resolved + .lt_curr + .iter() + .chain(resolved.lt_foll.iter()) + .chain(resolved.st_curr_before.iter()) + .chain(resolved.st_curr_after.iter()) + .chain(resolved.st_foll.iter()) + .flatten() + { + keep[*idx] = true; + } + for (i, e) in self.entries.iter_mut().enumerate() { + if e.layer_id == layer_id && !keep[i] { + e.marking = Marking::Unused; + } + } + + resolved + } + + /// §8.3.4 — construct `RefPicList0` (and, for a B slice, + /// `RefPicList1`) as index vectors into [`Dpb::entries`]. + /// + /// `rps` is the [`apply_rps`](Dpb::apply_rps) output; `params` carries + /// the §8.3.4 sizing + modification inputs. With + /// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) the + /// equation 8-8 / 8-10 wrap appends the current picture — the + /// [`CURR_PIC`] sentinel — after `RefPicSetLtCurr` on every pass, + /// and the equation 8-9 closing clause overrides the last active + /// `RefPicList0` slot when the temp list was longer than the + /// active count and no explicit modification was signalled. + #[must_use] + pub fn build_ref_pic_lists( + &self, + rps: &ResolvedRps, + params: &RefPicListParams<'_>, + ) -> RefPicLists { + // RefPicListTemp0 (equation 8-8): StCurrBefore, StCurrAfter, LtCurr, + // (+ currPic with pps_curr_pic_ref_enabled_flag), repeated until + // NumRpsCurrTempList0 entries are produced. + let active0 = (params.num_ref_idx_l0_active_minus1 + 1) as usize; + let num_temp0 = active0.max(params.num_pic_total_curr as usize); + let temp0 = build_temp_list( + num_temp0, + &[&rps.st_curr_before, &rps.st_curr_after, &rps.lt_curr], + params.curr_pic_ref_enabled, + ); + let mut list0 = apply_list_modification(&temp0, active0, params.list_entry_l0); + // Equation 8-9 closing clause. + if params.curr_pic_ref_enabled && params.list_entry_l0.is_none() && num_temp0 > active0 { + if let Some(last) = list0.last_mut() { + *last = Some(CURR_PIC); + } + } + + let list1 = if params.is_b { + // RefPicListTemp1 (equation 8-10): StCurrAfter, StCurrBefore, + // LtCurr (note the swapped first two sets). + let active1 = (params.num_ref_idx_l1_active_minus1 + 1) as usize; + let num_temp1 = active1.max(params.num_pic_total_curr as usize); + let temp1 = build_temp_list( + num_temp1, + &[&rps.st_curr_after, &rps.st_curr_before, &rps.lt_curr], + params.curr_pic_ref_enabled, + ); + Some(apply_list_modification( + &temp1, + active1, + params.list_entry_l1, + )) + } else { + None + }; + + RefPicLists { list0, list1 } + } +} + +/// The [`RefPicLists`] sentinel index standing for the CURRENT decoded +/// picture (before in-loop filtering) — the §8.3.4 `currPic` appended +/// when `pps_curr_pic_ref_enabled_flag` is 1. It is deliberately out of +/// range for every real DPB entry vector; consumers must test for it +/// before indexing. +pub const CURR_PIC: usize = usize::MAX; + +/// §8.3.4 sizing + modification inputs for +/// [`Dpb::build_ref_pic_lists`]. +#[derive(Debug, Clone, Copy, Default)] +pub struct RefPicListParams<'a> { + /// `num_ref_idx_l0_active_minus1`. + pub num_ref_idx_l0_active_minus1: u32, + /// `num_ref_idx_l1_active_minus1`. + pub num_ref_idx_l1_active_minus1: u32, + /// `NumPicTotalCurr` (§7.4.7.2). + pub num_pic_total_curr: u32, + /// `true` for a B slice (builds `RefPicList1`). + pub is_b: bool, + /// `list_entry_l0[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp0`. + pub list_entry_l0: Option<&'a [u32]>, + /// `list_entry_l1[]` (§7.3.6.2) — `Some` reorders `RefPicListTemp1`. + pub list_entry_l1: Option<&'a [u32]>, + /// `pps_curr_pic_ref_enabled_flag` — appends the [`CURR_PIC`] + /// sentinel per equations 8-8 / 8-9 / 8-10. + pub curr_pic_ref_enabled: bool, +} + +/// The §8.3.2 RPS resolved to DPB entry indices. A `None` is the spec's +/// "no reference picture". +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ResolvedRps { + /// `RefPicSetStCurrBefore`. + pub st_curr_before: Vec>, + /// `RefPicSetStCurrAfter`. + pub st_curr_after: Vec>, + /// `RefPicSetStFoll`. + pub st_foll: Vec>, + /// `RefPicSetLtCurr`. + pub lt_curr: Vec>, + /// `RefPicSetLtFoll`. + pub lt_foll: Vec>, +} + +/// The §8.3.4 reference picture lists, as DPB entry indices. A `None` +/// entry is a "no reference picture" carried through from the RPS. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RefPicLists { + /// `RefPicList0`. + pub list0: Vec>, + /// `RefPicList1` (only for B slices). + pub list1: Option>>, +} + +/// §8.3.5 — select the collocated picture `ColPic` for temporal MV +/// prediction, returning its DPB entry index. +/// +/// `slice_type_is_b` + `collocated_from_l0_flag` choose the list per +/// §8.3.5; `collocated_ref_idx` indexes it. Returns `None` when the +/// chosen entry is "no reference picture" or the index is out of range. +#[must_use] +pub fn select_col_pic( + lists: &RefPicLists, + slice_type_is_b: bool, + collocated_from_l0_flag: bool, + collocated_ref_idx: u32, +) -> Option { + let idx = collocated_ref_idx as usize; + let picked = if slice_type_is_b && !collocated_from_l0_flag { + lists.list1.as_ref()?.get(idx).copied().flatten() + } else { + lists.list0.get(idx).copied().flatten() + }; + // §7.4.7.1: collocated_ref_idx shall not refer to the current + // picture — treat a malformed selection as "no collocated picture". + picked.filter(|&i| i != CURR_PIC) +} + +/// §8.3.5 — `NoBackwardPredFlag`: true iff every reference picture in +/// `RefPicList0` / `RefPicList1` has `DiffPicOrderCnt( aPic, CurrPic ) +/// <= 0`. `curr_poc` is the current picture's `PicOrderCntVal`; the +/// closure resolves a DPB index to its POC. +#[must_use] +pub fn no_backward_pred_flag(dpb: &Dpb, lists: &RefPicLists, curr_poc: i32) -> bool { + let mut all_le = true; + let check = |idx: &Option, all_le: &mut bool| { + if let Some(i) = idx { + // The current picture (CURR_PIC) has DiffPicOrderCnt == 0. + if *i != CURR_PIC && diff_pic_order_cnt(dpb.entries[*i].poc, curr_poc) > 0 { + *all_le = false; + } + } + }; + for idx in &lists.list0 { + check(idx, &mut all_le); + } + if let Some(l1) = &lists.list1 { + for idx in l1 { + check(idx, &mut all_le); + } + } + all_le +} + +/// Build a §8.3.4 `RefPicListTempX` by concatenating the given RPS sets +/// in order — appending the [`CURR_PIC`] sentinel after each pass when +/// `curr_pic_ref_enabled` (`pps_curr_pic_ref_enabled_flag`) — and +/// wrapping around until `len` entries are produced (equations +/// 8-8 / 8-10). +fn build_temp_list( + len: usize, + sets: &[&[Option]], + curr_pic_ref_enabled: bool, +) -> Vec> { + let mut temp = Vec::with_capacity(len); + if sets.iter().all(|s| s.is_empty()) && !curr_pic_ref_enabled { + return temp; + } + while temp.len() < len { + for set in sets { + for &e in *set { + if temp.len() >= len { + break; + } + temp.push(e); + } + } + if curr_pic_ref_enabled { + // The equation 8-8 / 8-10 currPic append carries no + // `rIdx < NumRpsCurrTempListX` guard — the temp list may + // end one entry longer than `len` (reachable through + // `list_entry_lX`). + temp.push(Some(CURR_PIC)); + } + } + temp +} + +/// Apply the §8.3.4 `RefPicListX` selection (equation 8-9 / 8-11): take +/// the first `active` entries of `temp`, reordered through `list_entry` +/// when present. +fn apply_list_modification( + temp: &[Option], + active: usize, + list_entry: Option<&[u32]>, +) -> Vec> { + (0..active) + .map(|r_idx| match list_entry { + Some(le) => temp.get(le[r_idx] as usize).copied().flatten(), + None => temp.get(r_idx).copied().flatten(), + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::picture::Picture; + + fn entry(poc: i32, marking: Marking) -> DpbEntry { + DpbEntry { + poc, + layer_id: 0, + marking, + picture: Picture::new(16, 16, 1, 8, 8), + motion: MotionField::new(16, 16), + } + } + + fn empty_st_rps() -> MaterializedShortTermRefPicSet { + MaterializedShortTermRefPicSet { + delta_poc_s0: vec![], + used_by_curr_pic_s0: vec![], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + } + } + + #[test] + fn idr_rps_lists_are_empty() { + let st = empty_st_rps(); + let lists = build_rps_poc_lists(true, 0, 256, &st, &[]); + assert!(lists.st_curr_before.is_empty()); + assert!(lists.st_curr_after.is_empty()); + assert!(lists.lt_curr.is_empty()); + } + + #[test] + fn p_frame_short_term_before_resolves_idr() { + // One negative pic at delta −1, used by curr ⇒ PocStCurrBefore + // = [poc 1 + (−1)] = [0], which resolves to the IDR in the DPB. + let st = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); + assert_eq!(lists.st_curr_before, vec![0]); + + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + let rps = dpb.apply_rps(false, 0, &lists, 256); + assert_eq!(rps.st_curr_before, vec![Some(0)]); + // The IDR stays short-term (it is in the RPS). + assert_eq!(dpb.entries[0].marking, Marking::ShortTerm); + } + + #[test] + fn picture_not_in_rps_becomes_unused() { + let st = empty_st_rps(); + let lists = build_rps_poc_lists(false, 5, 256, &st, &[]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + dpb.apply_rps(false, 0, &lists, 256); + // poc 0 is in no RPS list ⇒ unused for reference. + assert_eq!(dpb.entries[0].marking, Marking::Unused); + } + + #[test] + fn irap_no_rasl_unmarks_all_references() { + let st = empty_st_rps(); + let lists = build_rps_poc_lists(true, 0, 256, &st, &[]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + dpb.insert(entry(2, Marking::LongTerm)); + dpb.apply_rps(true, 0, &lists, 256); + assert!(dpb.entries.iter().all(|e| e.marking == Marking::Unused)); + } + + #[test] + fn p_ref_pic_list0_takes_curr_before() { + // DPB holds POC 0 (IDR). Current P-frame POC 1 with one + // short-term-before pic at POC 0. + let st = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + let rps = dpb.apply_rps(false, 0, &lists, 256); + let rpl = dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_pic_total_curr: 1, + ..Default::default() + }, + ); + assert_eq!(rpl.list0, vec![Some(0)]); + assert!(rpl.list1.is_none()); + } + + /// §8.3.4 with `pps_curr_pic_ref_enabled_flag`: the current picture + /// (CURR_PIC) is appended after the RPS sets (eq. 8-8) — a P slice + /// with one short-term reference and two active entries lists + /// [ref, currPic]. + #[test] + fn curr_pic_ref_appends_current_picture() { + let st = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + let rps = dpb.apply_rps(false, 0, &lists, 256); + let rpl = dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_ref_idx_l0_active_minus1: 1, + num_pic_total_curr: 2, + curr_pic_ref_enabled: true, + ..Default::default() + }, + ); + assert_eq!(rpl.list0, vec![Some(0), Some(CURR_PIC)]); + } + + /// An IRAP-only stream (empty RPS) with current-picture referencing + /// still builds a list: [currPic] (the intra-block-copy-only case). + #[test] + fn curr_pic_ref_fills_empty_rps_list() { + let dpb = Dpb::new(); + let rps = ResolvedRps::default(); + let rpl = dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_ref_idx_l0_active_minus1: 0, + num_pic_total_curr: 1, + curr_pic_ref_enabled: true, + ..Default::default() + }, + ); + assert_eq!(rpl.list0, vec![Some(CURR_PIC)]); + } + + /// The eq. 8-9 closing clause: with the temp list longer than the + /// active count and no explicit modification, the LAST active slot + /// is overridden to currPic — one short-term ref, one active entry, + /// NumPicTotalCurr 2 ⇒ list0 = [currPic]. + #[test] + fn curr_pic_ref_overrides_last_active_slot() { + let st = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); + let rps = dpb.apply_rps(false, 0, &lists, 256); + let rpl = dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_ref_idx_l0_active_minus1: 0, + num_pic_total_curr: 2, + curr_pic_ref_enabled: true, + ..Default::default() + }, + ); + assert_eq!(rpl.list0, vec![Some(CURR_PIC)]); + } + + /// select_col_pic never yields the CURR_PIC sentinel (§7.4.7.1 + /// forbids collocated_ref_idx referring to the current picture). + #[test] + fn col_pic_selection_rejects_curr_pic() { + let lists = RefPicLists { + list0: vec![Some(CURR_PIC)], + list1: None, + }; + assert_eq!(select_col_pic(&lists, false, true, 0), None); + } + + /// no_backward_pred_flag treats currPic as DiffPicOrderCnt == 0 + /// (not a future reference). + #[test] + fn no_backward_pred_ignores_curr_pic() { + let dpb = Dpb::new(); + let lists = RefPicLists { + list0: vec![Some(CURR_PIC)], + list1: None, + }; + assert!(no_backward_pred_flag(&dpb, &lists, 5)); + } + + #[test] + fn b_ref_pic_lists_swap_before_after() { + // Current B POC 1, with a before-pic at POC 0 and an after-pic at + // POC 2. RefPicList0 = [before, after]; RefPicList1 = [after, + // before]. + let st = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![1], + used_by_curr_pic_s1: vec![true], + }; + let lists = build_rps_poc_lists(false, 1, 256, &st, &[]); + assert_eq!(lists.st_curr_before, vec![0]); + assert_eq!(lists.st_curr_after, vec![2]); + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); // index 0 = POC 0 + dpb.insert(entry(2, Marking::ShortTerm)); // index 1 = POC 2 + let rps = dpb.apply_rps(false, 0, &lists, 256); + let rpl = dpb.build_ref_pic_lists( + &rps, + &RefPicListParams { + num_ref_idx_l0_active_minus1: 1, + num_ref_idx_l1_active_minus1: 1, + num_pic_total_curr: 2, + is_b: true, + ..Default::default() + }, + ); + assert_eq!(rpl.list0, vec![Some(0), Some(1)]); + assert_eq!(rpl.list1, Some(vec![Some(1), Some(0)])); + } + + #[test] + fn col_pic_selection_picks_list0_for_p() { + let lists = RefPicLists { + list0: vec![Some(3)], + list1: None, + }; + // P slice ⇒ list0[collocated_ref_idx 0]. + assert_eq!(select_col_pic(&lists, false, true, 0), Some(3)); + } + + #[test] + fn col_pic_selection_picks_list1_when_b_and_not_from_l0() { + let lists = RefPicLists { + list0: vec![Some(3)], + list1: Some(vec![Some(7)]), + }; + assert_eq!(select_col_pic(&lists, true, false, 0), Some(7)); + // collocated_from_l0_flag true falls back to list0. + assert_eq!(select_col_pic(&lists, true, true, 0), Some(3)); + } + + #[test] + fn no_backward_pred_flag_detects_future_ref() { + let mut dpb = Dpb::new(); + dpb.insert(entry(0, Marking::ShortTerm)); // index 0 (past) + dpb.insert(entry(4, Marking::ShortTerm)); // index 1 (future) + // Current POC 2; list0 references the past pic only ⇒ no backward. + let past_only = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + assert!(no_backward_pred_flag(&dpb, &past_only, 2)); + // list1 references the future pic ⇒ backward prediction present. + let with_future = RefPicLists { + list0: vec![Some(0)], + list1: Some(vec![Some(1)]), + }; + assert!(!no_backward_pred_flag(&dpb, &with_future, 2)); + } + + #[test] + fn long_term_lsb_lookup_marks_long_term() { + // A long-term entry referencing POC 100 by LSB only (msb not + // present). MaxPicOrderCntLsb 256 ⇒ lsb 100. The DPB picture at + // POC 100 is found by its LSB and marked long-term. + let lt = LongTermEntry { + poc_lsb_lt: 100, + used_by_curr_pic_lt: true, + delta_poc_msb_present: false, + delta_poc_msb_cycle_lt: 0, + }; + let st = empty_st_rps(); + let lists = build_rps_poc_lists(false, 300, 256, &st, &[lt]); + assert_eq!(lists.lt_curr, vec![100]); + let mut dpb = Dpb::new(); + dpb.insert(entry(100, Marking::ShortTerm)); + let rps = dpb.apply_rps(false, 0, &lists, 256); + assert_eq!(rps.lt_curr, vec![Some(0)]); + assert_eq!(dpb.entries[0].marking, Marking::LongTerm); + } +} diff --git a/vendor/oxideav-h265/src/encoder.rs b/vendor/oxideav-h265/src/encoder.rs new file mode 100644 index 0000000..bb229db --- /dev/null +++ b/vendor/oxideav-h265/src/encoder.rs @@ -0,0 +1,440 @@ +//! H.265 / HEVC encoder — write-side building blocks. +//! +//! The encode stack mirrors the decode stack bottom-up: +//! +//! * [`bitwriter::BitWriter`] — the MSB-first RBSP bit sink (`u(n)`, +//! `ue(v)` / `se(v)`, `rbsp_trailing_bits()`). +//! * [`nal`] — §7.4.1.1 emulation-prevention escaping, the §7.3.1.2 +//! NAL header, and Annex B framing. +//! * [`cabac::CabacEncoder`] — the §9.3.5 arithmetic encoding engine +//! (the spec's informative encoder that "matches the arithmetic +//! decoding engine described in clause 9.3.4.3"). +//! +//! Every layer is pinned against the crate's own decode side: bit +//! fields re-read through [`crate::bitreader::BitReader`], NAL units +//! re-walked through [`crate::nal`], and CABAC bin streams re-decoded +//! through [`crate::cabac::CabacEngine`]. + +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod bitwriter; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod cabac; +pub mod inter; +pub mod intra; +pub mod loopfilter; +pub mod pyramid; +// internal — exposed for tests/fuzz; not part of the stable API +#[cfg(test)] +mod ccp_streams; +#[doc(hidden)] +pub mod nal; +#[cfg(test)] +mod palette_streams; +pub mod pcm; +#[cfg(test)] +mod rdpcm_streams; +#[cfg(test)] +mod scc_streams; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod residual; + +/// Registry-encoder coding mode, selected by the `mode` codec option. +#[derive(Debug)] +enum EncodeMode { + /// PCM-only IDR bootstrap: bit-exact lossless, every CU a + /// §7.3.8.7 PCM block. The default (`mode` absent or `"pcm"`). + Pcm, + /// Real CABAC intra coding ([`intra::encode_idr_intra_au`]) at + /// the carried `SliceQpY` (`mode = "intra"`, `qp` option, default + /// 26) with the carried §8.7 in-loop filters (`deblock` / `sao` + /// options). + Intra(i32, loopfilter::LoopFilterCfg), + /// Low-delay inter coding (`mode = "inter"`): `IDR, P, P, …` + /// GOPs through [`inter::LowDelayPEncoder`] (`qp` option, default + /// 26; `gop` option = GOP length in frames, default 0 = a single + /// leading IDR). + Inter(inter::LowDelayPEncoder), + /// Hierarchical-B coding (`mode = "inter"` + `pyramid = `): + /// dyadic B pyramids through [`pyramid::PyramidEncoder`] — + /// out-of-order coding, so packets arrive in bursts per mini-GOP + /// and [`Encoder::flush`] emits the low-delay tail. + Pyramid { + /// The buffering pyramid encoder. + enc: pyramid::PyramidEncoder, + /// `log2(gop)` — the dts-behind-pts reorder delay in frames. + delay: i64, + /// The caller-supplied pts of each pushed frame, by display + /// index (`None` ⇒ the display index itself). + pts_by_display: Vec>, + /// Decode-order packet counter (drives dts). + decode_count: i64, + }, +} + +use std::collections::VecDeque; + +use oxideav_core::{ + CodecId, CodecParameters, Encoder, Error, Frame, Packet, PixelFormat, Result, TimeBase, +}; + +/// H.265 registry encoder behind the [`oxideav_core::Encoder`] +/// contract. Every input frame becomes one Annex B access unit — a +/// self-contained IDR (`VPS + SPS + PPS + IDR_N_LP`) in the two intra +/// modes and at inter-mode GOP starts, or a `TRAIL_R` P slice inside +/// an inter-mode GOP. Three coding modes, selected by the `mode` +/// codec option: +/// +/// * `"pcm"` (default) — the PCM-only bootstrap: every coding unit a +/// §7.3.8.7 PCM block, bit-exact lossless. +/// * `"intra"` — real CABAC intra coding (§8.4 prediction + forward +/// transform/quant + §7.3.8 syntax) at the `qp` option's +/// `SliceQpY` (0..=51, default 26). +/// * `"inter"` — low-delay `IDR, P, P, …` coding (§8.5 inter +/// prediction with per-CTU skip / merge / AMVP / intra decisions) +/// at the `qp` option's `SliceQpY`; the `gop` option sets the IDR +/// period in frames (default 0 = a single leading IDR); the +/// `bslices` option (`"1"` / `"true"`) codes the non-IDR frames as +/// low-delay B slices; the `amp` option switches to the AMP stream +/// configuration (`MinCbSizeY == 8`, `amp_enabled_flag == 1`, the +/// four asymmetric PART_2NxnU/2NxnD/nLx2N/nRx2N shapes competing in +/// the inter CU ladder); the `pyramid` option (a power of two in +/// 2..=16) switches to hierarchical-B coding — dyadic mini-GOPs +/// coded out of display order with per-layer QP offsets; packets +/// then arrive in bursts per mini-GOP (dts trails pts by +/// `log2(pyramid)` frames) and `flush()` emits the tail. `pyramid` +/// excludes the `gop` / `bslices` options. +/// +/// The `"intra"` and `"inter"` modes accept the §8.7 in-loop filter +/// options `deblock` and `sao` (`"1"` / `"true"` to enable): the +/// encoder then signals the filters, elects them per slice / CTB +/// against distortion, and reconstructs through them (the reference +/// path a conforming decoder holds). +/// +/// 4:2:0 8-bit, dimensions multiples of 16. +pub struct H265Encoder { + codec_id: CodecId, + output_params: CodecParameters, + width: usize, + height: usize, + mode: EncodeMode, + ready: VecDeque, + frame_index: i64, +} + +/// Former name of [`H265Encoder`] (from when the registry encoder was +/// PCM-only). +pub type H265PcmEncoder = H265Encoder; + +impl std::fmt::Debug for H265Encoder { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("H265Encoder") + .field("width", &self.width) + .field("height", &self.height) + .field("mode", &self.mode) + .field("ready", &self.ready.len()) + .finish() + } +} + +/// Direct factory endpoint: construct the software H.265 encoder. +/// Codec options: `mode` (`"pcm"` lossless bootstrap, the default, +/// `"intra"` real CABAC intra coding, or `"inter"` low-delay P GOPs), +/// `qp` (`SliceQpY` 0..=51 for the intra / inter modes, default 26), +/// `gop` (inter mode IDR period, default 0 = single leading IDR), +/// `amp` (inter mode: asymmetric motion partitions), and the in-loop +/// filter switches `deblock` / `sao` (intra / inter modes; default +/// off). +/// +/// # Errors +/// [`Error::InvalidData`] when width / height are missing or not +/// nonzero multiples of 16, the pixel format is declared and is not +/// 4:2:0 8-bit planar, or a codec option is malformed. +pub fn make_encoder(params: &CodecParameters) -> Result> { + let width = params + .width + .ok_or_else(|| Error::InvalidData("h265 encode: width is required".into()))? + as usize; + let height = params + .height + .ok_or_else(|| Error::InvalidData("h265 encode: height is required".into()))? + as usize; + if width == 0 || height == 0 || width % 16 != 0 || height % 16 != 0 { + return Err(Error::InvalidData(format!( + "h265 encode: dimensions must be nonzero multiples of 16, got {width}x{height}" + ))); + } + if let Some(pf) = params.pixel_format { + if pf != PixelFormat::Yuv420P { + return Err(Error::InvalidData(format!( + "h265 encode: only yuv420p input is supported, got {pf:?}" + ))); + } + } + let parse_qp = |params: &CodecParameters| -> Result { + match params.options.get("qp") { + None => Ok(26), + Some(v) => v + .parse::() + .ok() + .filter(|q| (0..=51).contains(q)) + .ok_or_else(|| { + Error::InvalidData(format!("h265 encode: qp must be 0..=51, got {v:?}")) + }), + } + }; + let parse_flag = |params: &CodecParameters, key: &str| -> Result { + match params.options.get(key) { + None | Some("0") | Some("false") => Ok(false), + Some("1") | Some("true") => Ok(true), + Some(v) => Err(Error::InvalidData(format!( + "h265 encode: {key} must be 0/1/true/false, got {v:?}" + ))), + } + }; + let parse_lf = |params: &CodecParameters| -> Result { + let sao = parse_flag(params, "sao")?; + Ok(loopfilter::LoopFilterCfg { + deblocking: parse_flag(params, "deblock")?, + sao_luma: sao, + sao_chroma: sao, + }) + }; + let mode = match params.options.get("mode") { + None | Some("pcm") => { + if parse_lf(params)?.any() { + return Err(Error::InvalidData( + "h265 encode: deblock/sao options require mode \"intra\" or \"inter\"".into(), + )); + } + if parse_flag(params, "amp")? { + return Err(Error::InvalidData( + "h265 encode: the amp option requires mode \"inter\"".into(), + )); + } + EncodeMode::Pcm + } + Some("intra") => { + if parse_flag(params, "amp")? { + return Err(Error::InvalidData( + "h265 encode: the amp option requires mode \"inter\"".into(), + )); + } + EncodeMode::Intra(parse_qp(params)?, parse_lf(params)?) + } + Some("inter") => { + let qp = parse_qp(params)?; + if let Some(v) = params.options.get("pyramid") { + if params.options.get("gop").is_some() || params.options.get("bslices").is_some() { + return Err(Error::InvalidData( + "h265 encode: pyramid excludes the gop / bslices options".into(), + )); + } + let g = v + .parse::() + .ok() + .filter(|g| g.is_power_of_two() && (2..=16).contains(g)) + .ok_or_else(|| { + Error::InvalidData(format!( + "h265 encode: pyramid must be a power of two in 2..=16, got {v:?}" + )) + })?; + let enc = pyramid::PyramidEncoder::new(width, height, qp, g) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))? + .with_amp(parse_flag(params, "amp")?) + .with_loop_filters(parse_lf(params)?); + EncodeMode::Pyramid { + enc, + delay: i64::from(g.trailing_zeros()), + pts_by_display: Vec::new(), + decode_count: 0, + } + } else { + let gop = match params.options.get("gop") { + None => 0usize, + Some(v) => v.parse::().map_err(|_| { + Error::InvalidData(format!( + "h265 encode: gop must be a non-negative integer, got {v:?}" + )) + })?, + }; + let b_slices = parse_flag(params, "bslices")?; + let enc = inter::LowDelayPEncoder::new(width, height, qp, gop) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))? + .with_b_slices(b_slices) + .with_amp(parse_flag(params, "amp")?) + .with_loop_filters(parse_lf(params)?); + EncodeMode::Inter(enc) + } + } + Some(other) => { + return Err(Error::InvalidData(format!( + "h265 encode: unknown mode {other:?} (expected \"pcm\", \"intra\" or \"inter\")" + ))) + } + }; + let mut output_params = params.clone(); + output_params.media_type = oxideav_core::MediaType::Video; + output_params.pixel_format = Some(PixelFormat::Yuv420P); + // Parameter sets ride in band in every access unit; no extradata. + output_params.extradata.clear(); + Ok(Box::new(H265Encoder { + codec_id: params.codec_id.clone(), + output_params, + width, + height, + mode, + ready: VecDeque::new(), + frame_index: 0, + })) +} + +impl Encoder for H265Encoder { + fn codec_id(&self) -> &CodecId { + &self.codec_id + } + + fn output_params(&self) -> &CodecParameters { + &self.output_params + } + + fn send_frame(&mut self, frame: &Frame) -> Result<()> { + let v = match frame { + Frame::Video(v) => v, + _ => return Err(Error::InvalidData("h265 encode: video frames only".into())), + }; + if v.planes.len() != 3 { + return Err(Error::InvalidData(format!( + "h265 encode: expected 3 planes (yuv420p), got {}", + v.planes.len() + ))); + } + // Repack each plane row-by-row (strides may exceed the width). + let pack = |idx: usize, w: usize, h: usize| -> Result> { + let plane = &v.planes[idx]; + if plane.stride < w || plane.data.len() < plane.stride * h { + return Err(Error::InvalidData(format!( + "h265 encode: plane {idx} too small (stride {}, len {})", + plane.stride, + plane.data.len() + ))); + } + let mut out = Vec::with_capacity(w * h); + for row in 0..h { + out.extend_from_slice(&plane.data[row * plane.stride..row * plane.stride + w]); + } + Ok(out) + }; + let y = pack(0, self.width, self.height)?; + let cb = pack(1, self.width / 2, self.height / 2)?; + let cr = pack(2, self.width / 2, self.height / 2)?; + + let (au, keyframe) = match &mut self.mode { + EncodeMode::Pcm => ( + pcm::encode_idr_pcm_au(&y, &cb, &cr, self.width, self.height) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?, + true, + ), + EncodeMode::Intra(qp, lf) => ( + intra::encode_idr_intra_au_lf(&y, &cb, &cr, self.width, self.height, *qp, lf) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))? + .au, + true, + ), + EncodeMode::Inter(enc) => { + let f = enc + .encode_frame(&inter::YuvFrame { + y: &y, + cb: &cb, + cr: &cr, + }) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?; + (f.au, f.keyframe) + } + EncodeMode::Pyramid { + enc, + delay, + pts_by_display, + decode_count, + } => { + pts_by_display.push(v.pts); + let aus = enc + .encode_frame(&inter::YuvFrame { + y: &y, + cb: &cb, + cr: &cr, + }) + .map_err(|e| Error::InvalidData(format!("h265 encode: {e}")))?; + self.frame_index += 1; + let (delay, decode_count) = (*delay, decode_count); + let mut packets = Self::pyramid_packets(aus, pts_by_display, delay, decode_count); + for pkt in packets.drain(..) { + self.ready.push_back(pkt); + } + return Ok(()); + } + }; + let mut pkt = Packet::new(0, TimeBase::new(1, 25), au); + pkt.pts = v.pts.or(Some(self.frame_index)); + pkt.dts = pkt.pts; + pkt.flags.keyframe = keyframe; + self.frame_index += 1; + self.ready.push_back(pkt); + Ok(()) + } + + fn receive_packet(&mut self) -> Result { + self.ready.pop_front().ok_or(Error::NeedMore) + } + + fn flush(&mut self) -> Result<()> { + // Only the pyramid mode buffers: emit its low-delay tail. + if let EncodeMode::Pyramid { + enc, + delay, + pts_by_display, + decode_count, + } = &mut self.mode + { + let aus = enc.flush(); + let (delay, decode_count) = (*delay, decode_count); + let mut packets = Self::pyramid_packets(aus, pts_by_display, delay, decode_count); + for pkt in packets.drain(..) { + self.ready.push_back(pkt); + } + } + Ok(()) + } +} + +impl H265Encoder { + /// Turn a burst of decode-ordered pyramid access units into + /// packets: pts = the pushed frame's pts (default: its display + /// index), dts = the decode counter minus the reorder delay (a + /// dts never after its pts on the dyadic schedule). + fn pyramid_packets( + aus: Vec, + pts_by_display: &[Option], + delay: i64, + decode_count: &mut i64, + ) -> Vec { + aus.into_iter() + .map(|au| { + let mut pkt = Packet::new(0, TimeBase::new(1, 25), au.au); + pkt.pts = Some( + pts_by_display + .get(au.display_order) + .copied() + .flatten() + .unwrap_or(au.display_order as i64), + ); + pkt.dts = Some(*decode_count - delay); + *decode_count += 1; + pkt.flags.keyframe = au.keyframe; + pkt + }) + .collect() + } +} diff --git a/vendor/oxideav-h265/src/encoder/bitwriter.rs b/vendor/oxideav-h265/src/encoder/bitwriter.rs new file mode 100644 index 0000000..69e999a --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/bitwriter.rs @@ -0,0 +1,190 @@ +//! MSB-first RBSP bit writer — the write-side dual of +//! [`crate::bitreader::BitReader`]. +//! +//! Produces raw RBSP bytes: fixed-width `u(n)` fields, the §9.2 +//! Exp-Golomb `ue(v)` / `se(v)` encodings, the §7.3.2 `rbsp_trailing_ +//! bits()` terminator, and byte alignment. Emulation prevention +//! (§7.4.1.1) is NOT applied here — it belongs to the NAL encapsulation +//! ([`super::nal::escape_rbsp`]), which turns an RBSP into the on-wire +//! escaped payload. + +/// MSB-first bit accumulator over a growable byte buffer. +#[derive(Debug, Default, Clone)] +pub struct BitWriter { + buf: Vec, + /// Bits already used in the trailing partial byte (0..=7). When 0, + /// the writer is byte-aligned and `buf` holds only complete bytes. + partial_bits: u8, +} + +impl BitWriter { + /// A fresh, empty, byte-aligned writer. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Total bits written so far. + #[must_use] + pub fn bit_len(&self) -> usize { + if self.partial_bits == 0 { + self.buf.len() * 8 + } else { + (self.buf.len() - 1) * 8 + self.partial_bits as usize + } + } + + /// `byte_aligned()` per §7.2. + #[must_use] + pub fn byte_aligned(&self) -> bool { + self.partial_bits == 0 + } + + /// Append a single bit (the low bit of `bit`). + pub fn put_bit(&mut self, bit: u8) { + if self.partial_bits == 0 { + self.buf.push(0); + } + let last = self.buf.last_mut().expect("partial byte exists"); + *last |= (bit & 1) << (7 - self.partial_bits); + self.partial_bits = (self.partial_bits + 1) & 7; + } + + /// Append the `n` low bits of `value`, most significant first + /// (`u(n)` / `f(n)`). `n == 0` writes nothing; `n <= 32`. + pub fn put_bits(&mut self, value: u32, n: u8) { + debug_assert!(n <= 32); + for i in (0..n).rev() { + self.put_bit(((value >> i) & 1) as u8); + } + } + + /// §9.2 — 0-th order Exp-Golomb, unsigned (`ue(v)`). + pub fn ue(&mut self, value: u32) { + // codeNum = value; the codeword is `leadingZeroBits` zeros, a + // one, then `leadingZeroBits` LSBs of (codeNum + 1). + let code_num = value as u64 + 1; + let bits = 64 - code_num.leading_zeros() as u8; // >= 1 + self.put_bits(0, bits - 1); + for i in (0..bits).rev() { + self.put_bit(((code_num >> i) & 1) as u8); + } + } + + /// §9.2.2 — 0-th order Exp-Golomb, signed (`se(v)`): + /// `codeNum = value > 0 ? 2*value − 1 : −2*value`. + pub fn se(&mut self, value: i32) { + let code_num = if value > 0 { + 2 * value as u32 - 1 + } else { + 2 * value.unsigned_abs() + }; + self.ue(code_num); + } + + /// §7.3.2 `rbsp_trailing_bits()`: `rbsp_stop_one_bit` then zero + /// bits to the byte boundary. + pub fn rbsp_trailing_bits(&mut self) { + self.put_bit(1); + self.align_zero(); + } + + /// Append zero bits until byte-aligned (`pcm_alignment_zero_bit` / + /// `rbsp_alignment_zero_bit` runs). + pub fn align_zero(&mut self) { + while self.partial_bits != 0 { + self.put_bit(0); + } + } + + /// Consume the writer and return the accumulated bytes. Any + /// trailing partial byte is zero-padded (callers producing RBSPs + /// terminate with [`Self::rbsp_trailing_bits`] first, so a + /// conforming RBSP is already aligned). + #[must_use] + pub fn finish(self) -> Vec { + self.buf + } + + /// Borrow the bytes written so far (trailing partial byte included, + /// zero-padded). + #[must_use] + pub fn as_bytes(&self) -> &[u8] { + &self.buf + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + + #[test] + fn bits_pack_msb_first() { + let mut w = BitWriter::new(); + w.put_bit(1); + w.put_bits(0b0110, 4); + w.put_bits(0b101, 3); + assert_eq!(w.finish(), vec![0b1011_0101]); + } + + #[test] + fn ue_matches_reader_for_first_values() { + for v in 0..200u32 { + let mut w = BitWriter::new(); + w.ue(v); + w.align_zero(); + let bytes = w.finish(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.ue().unwrap(), v, "ue({v})"); + } + } + + #[test] + fn se_matches_reader() { + for v in -100..=100i32 { + let mut w = BitWriter::new(); + w.se(v); + w.align_zero(); + let bytes = w.finish(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.se().unwrap(), v, "se({v})"); + } + } + + #[test] + fn u_fields_roundtrip() { + let mut w = BitWriter::new(); + w.put_bits(0x2A, 6); + w.put_bits(0x1FFFF, 17); + w.put_bits(1, 1); + w.align_zero(); + let bytes = w.finish(); + let mut r = BitReader::new(&bytes); + assert_eq!(r.u(6).unwrap(), 0x2A); + assert_eq!(r.u(17).unwrap(), 0x1FFFF); + assert_eq!(r.u1().unwrap(), 1); + } + + #[test] + fn trailing_bits_terminate_and_align() { + let mut w = BitWriter::new(); + w.put_bits(0b101, 3); + w.rbsp_trailing_bits(); + assert!(w.byte_aligned()); + assert_eq!(w.finish(), vec![0b1011_0000]); + } + + #[test] + fn bit_len_tracks_partial_bytes() { + let mut w = BitWriter::new(); + assert_eq!(w.bit_len(), 0); + w.put_bit(0); + assert_eq!(w.bit_len(), 1); + w.put_bits(0, 7); + assert_eq!(w.bit_len(), 8); + assert!(w.byte_aligned()); + w.put_bits(0, 3); + assert_eq!(w.bit_len(), 11); + } +} diff --git a/vendor/oxideav-h265/src/encoder/cabac.rs b/vendor/oxideav-h265/src/encoder/cabac.rs new file mode 100644 index 0000000..909c30a --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/cabac.rs @@ -0,0 +1,323 @@ +//! §9.3.5 CABAC arithmetic *encoding* engine (the spec's informative +//! encoder, which "matches the arithmetic decoding engine described in +//! clause 9.3.4.3"). +//! +//! The engine state is `ivlLow` / `ivlCurrRange` plus the +//! `firstBitFlag` / `bitsOutstanding` carry-control of the §9.3.5.4 +//! renormalization (Figure 9-11) and its PutBit procedure +//! (Figure 9-12). The four entry points mirror the decoder: +//! +//! * §9.3.5.2 [`CabacEncoder::new`] — `ivlLow = 0`, +//! `ivlCurrRange = 510`, `firstBitFlag = 1`, `bitsOutstanding = 0`. +//! The same initialization re-arms the engine after PCM sample data +//! ([`CabacEncoder::reinit`]). +//! * §9.3.5.3 [`CabacEncoder::encode_decision`] (EncodeDecision) — the +//! Table 9-52 `rangeTabLps` interval split, the §9.3.4.3.2.2 state +//! transition (Table 9-53), then renormalization. +//! * §9.3.5.5 [`CabacEncoder::encode_bypass`] (EncodeBypass). +//! * §9.3.5.6 [`CabacEncoder::encode_terminate`] (EncodeTerminate) — +//! `end_of_slice_segment_flag` / `end_of_subset_one_bit` / +//! `pcm_flag`; a `binVal == 1` runs the Figure 9-15 flush whose last +//! written bit is the `rbsp_stop_one_bit` / +//! `alignment_bit_equal_to_one`. +//! +//! Bits go into the caller's [`BitWriter`]; the encoder is constructed +//! at a byte-aligned position (the start of `slice_segment_data()`) +//! and, via the first-bit suppression, produces exactly the byte +//! sequence whose 9-bit preload the §9.3.2.6 decoder init consumes. +//! +//! Correctness contract: any bin sequence encoded through this engine +//! and decoded through [`crate::cabac::CabacEngine`] (with identically +//! initialized context models) reproduces the original bins — pinned +//! by the roundtrip tests below. + +use crate::cabac::{ContextModel, RANGE_TAB_LPS, TRANS_IDX_LPS, TRANS_IDX_MPS}; +use crate::encoder::bitwriter::BitWriter; + +/// §9.3.5 arithmetic encoding engine over a borrowed [`BitWriter`]. +#[derive(Debug)] +pub struct CabacEncoder { + /// `ivlLow` — low end of the current sub-interval (10-bit register + /// per the §9.3.5.2 NOTE; `u32` gives headroom). + low: u32, + /// `ivlCurrRange` — width of the current sub-interval (9 bits). + range: u32, + /// `firstBitFlag` — suppresses the very first PutBit output (the + /// decoder's 9-bit preload supplies it implicitly). + first_bit: bool, + /// `bitsOutstanding` — pending carry-propagation bits. + outstanding: u64, +} + +impl Default for CabacEncoder { + fn default() -> Self { + Self::new() + } +} + +impl CabacEncoder { + /// §9.3.5.2 InitEncoder. + #[must_use] + pub fn new() -> Self { + Self { + low: 0, + range: 510, + first_bit: true, + outstanding: 0, + } + } + + /// §9.3.5.2 — re-initialize after PCM sample data (`pcm_flag == 1` + /// coding units re-arm the engine exactly like a slice start). + pub fn reinit(&mut self) { + *self = Self::new(); + } + + /// Figure 9-12 PutBit(B): carry-over control. The first bit of a + /// slice segment's arithmetic codeword is not written. + fn put_bit(&mut self, w: &mut BitWriter, b: u8) { + if self.first_bit { + self.first_bit = false; + } else { + w.put_bit(b); + } + while self.outstanding > 0 { + w.put_bit(1 - b); + self.outstanding -= 1; + } + } + + /// Figure 9-11 RenormE. + fn renorm(&mut self, w: &mut BitWriter) { + while self.range < 256 { + if self.low >= 512 { + self.low -= 512; + self.put_bit(w, 1); + } else if self.low < 256 { + self.put_bit(w, 0); + } else { + self.low -= 256; + self.outstanding += 1; + } + self.range <<= 1; + self.low <<= 1; + } + } + + /// §9.3.5.3 EncodeDecision: one context-coded bin. Updates the + /// context model exactly as the decoder's §9.3.4.3.2.2 transition. + pub fn encode_decision(&mut self, w: &mut BitWriter, ctx: &mut ContextModel, bin: u8) { + // Equation 9-64: qRangeIdx = ( ivlCurrRange >> 6 ) & 3. + let q_range_idx = ((self.range >> 6) & 3) as usize; + let lps = u32::from(RANGE_TAB_LPS[ctx.p_state_idx as usize][q_range_idx]); + self.range -= lps; + if bin != ctx.val_mps { + // LPS path: the LPS sub-interval sits above the MPS one. + self.low += self.range; + self.range = lps; + if ctx.p_state_idx == 0 { + ctx.val_mps = 1 - ctx.val_mps; + } + ctx.p_state_idx = TRANS_IDX_LPS[ctx.p_state_idx as usize]; + } else { + ctx.p_state_idx = TRANS_IDX_MPS[ctx.p_state_idx as usize]; + } + self.renorm(w); + } + + /// §9.3.5.5 EncodeBypass: one equal-probability bin (renorm + /// inlined per Figure 9-13). + pub fn encode_bypass(&mut self, w: &mut BitWriter, bin: u8) { + self.low <<= 1; + if bin != 0 { + self.low += self.range; + } + if self.low >= 1024 { + self.low -= 1024; + self.put_bit(w, 1); + } else if self.low < 512 { + self.put_bit(w, 0); + } else { + self.low -= 512; + self.outstanding += 1; + } + } + + /// MSB-first multi-bit bypass helper (the dual of + /// [`crate::cabac::CabacEngine::decode_bypass_bits`]). + pub fn encode_bypass_bits(&mut self, w: &mut BitWriter, value: u32, n: u8) { + for i in (0..n).rev() { + self.encode_bypass(w, ((value >> i) & 1) as u8); + } + } + + /// §9.3.5.6 EncodeTerminate: `end_of_slice_segment_flag` / + /// `end_of_subset_one_bit` / `pcm_flag`. `bin == 1` terminates the + /// arithmetic codeword and flushes (Figure 9-15) — the last written + /// bit is the `rbsp_stop_one_bit` / `alignment_bit_equal_to_one`; + /// the writer is then ready for byte-aligned raw data (PCM) or the + /// slice end. + pub fn encode_terminate(&mut self, w: &mut BitWriter, bin: u8) { + self.range -= 2; + if bin != 0 { + self.low += self.range; + self.flush(w); + } else { + self.renorm(w); + } + } + + /// Figure 9-15 EncodeFlush. + fn flush(&mut self, w: &mut BitWriter) { + self.range = 2; + self.renorm(w); + self.put_bit(w, ((self.low >> 9) & 1) as u8); + // WriteBits( ( ivlLow >> 7 ) & 3 | 1, 2 ) — the trailing 1 is + // the terminating one bit the decoder sees as the last bit + // inserted into ivlOffset. + w.put_bits(((self.low >> 7) & 3) | 1, 2); + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + use crate::cabac::CabacEngine; + + /// Encode `bins` as context-coded decisions with a single shared + /// context (encoder and decoder start from the same init), append a + /// terminate-1, and decode back. + fn roundtrip_decisions(init_value: u8, qp: i32, bins: &[u8]) { + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let mut ectx = ContextModel::init(init_value, qp); + for &b in bins { + enc.encode_decision(&mut w, &mut ectx, b); + } + enc.encode_terminate(&mut w, 1); + w.align_zero(); + let bytes = w.finish(); + + let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init"); + let mut dctx = ContextModel::init(init_value, qp); + for (i, &b) in bins.iter().enumerate() { + assert_eq!(dec.decode_decision(&mut dctx).unwrap(), b, "bin {i}"); + } + assert_eq!(dec.decode_terminate().unwrap(), 1, "terminator"); + // The context models must have walked the same state path. + assert_eq!(ectx, dctx, "context state after roundtrip"); + } + + #[test] + fn decision_roundtrip_simple_patterns() { + roundtrip_decisions(154, 26, &[0]); + roundtrip_decisions(154, 26, &[1]); + roundtrip_decisions(154, 26, &[1, 0, 1, 1, 0, 0, 1, 0]); + roundtrip_decisions(200, 37, &[1; 64]); + roundtrip_decisions(63, 0, &[0; 64]); + } + + #[test] + fn decision_roundtrip_pseudorandom_long() { + // Deterministic LCG bins over several init values / QPs. + let mut x = 0x1234_5678u32; + let mut bins = Vec::new(); + for _ in 0..4096 { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + bins.push(((x >> 16) & 1) as u8); + } + for (iv, qp) in [(154u8, 26), (79, 12), (227, 51), (16, 0)] { + roundtrip_decisions(iv, qp, &bins); + } + } + + #[test] + fn bypass_roundtrip() { + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let pattern = 0xDEAD_BEEFu32; + enc.encode_bypass_bits(&mut w, pattern, 32); + enc.encode_terminate(&mut w, 1); + w.align_zero(); + let bytes = w.finish(); + + let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init"); + assert_eq!(dec.decode_bypass_bits(32).unwrap(), pattern); + assert_eq!(dec.decode_terminate().unwrap(), 1); + } + + #[test] + fn mixed_decision_bypass_terminate_roundtrip() { + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let mut ectx = [ContextModel::init(154, 26), ContextModel::init(31, 40)]; + // Interleave: ctx0, bypass, ctx1, terminate-0 (continue), repeat. + for round in 0..50u32 { + enc.encode_decision(&mut w, &mut ectx[0], (round & 1) as u8); + enc.encode_bypass(&mut w, ((round >> 1) & 1) as u8); + enc.encode_decision(&mut w, &mut ectx[1], ((round >> 2) & 1) as u8); + enc.encode_terminate(&mut w, 0); + } + enc.encode_terminate(&mut w, 1); + w.align_zero(); + let bytes = w.finish(); + + let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init"); + let mut dctx = [ContextModel::init(154, 26), ContextModel::init(31, 40)]; + for round in 0..50u32 { + assert_eq!( + dec.decode_decision(&mut dctx[0]).unwrap(), + (round & 1) as u8 + ); + assert_eq!(dec.decode_bypass().unwrap(), ((round >> 1) & 1) as u8); + assert_eq!( + dec.decode_decision(&mut dctx[1]).unwrap(), + ((round >> 2) & 1) as u8 + ); + assert_eq!(dec.decode_terminate().unwrap(), 0, "round {round}"); + } + assert_eq!(dec.decode_terminate().unwrap(), 1); + assert_eq!(ectx[0], dctx[0]); + assert_eq!(ectx[1], dctx[1]); + } + + /// The PCM shape: terminate-1 mid-stream, byte-align, raw bits, + /// engine re-init on both sides, then more coded bins. + #[test] + fn pcm_style_flush_align_raw_reinit_roundtrip() { + let raw: [u8; 5] = [0x11, 0x22, 0x33, 0xFE, 0x00]; + + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let mut ectx = ContextModel::init(154, 26); + enc.encode_decision(&mut w, &mut ectx, 1); + enc.encode_decision(&mut w, &mut ectx, 0); + // pcm_flag == 1: terminate + flush, then alignment zeros + raw. + enc.encode_terminate(&mut w, 1); + w.align_zero(); + for &b in &raw { + w.put_bits(u32::from(b), 8); + } + // §9.3.5.2: re-init after the PCM data, keep encoding. + enc.reinit(); + enc.encode_decision(&mut w, &mut ectx, 1); + enc.encode_terminate(&mut w, 1); + w.align_zero(); + let bytes = w.finish(); + + let mut dec = CabacEngine::new(BitReader::new(&bytes)).expect("init"); + let mut dctx = ContextModel::init(154, 26); + assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 1); + assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 0); + assert_eq!(dec.decode_terminate().unwrap(), 1); + // pcm_alignment_zero_bit run, raw PCM reads, §9.3.2.6 re-init. + dec.pcm_align().unwrap(); + for &b in &raw { + assert_eq!(dec.read_raw_bits(8).unwrap(), u32::from(b)); + } + dec.init_engine().expect("reinit"); + assert_eq!(dec.decode_decision(&mut dctx).unwrap(), 1); + assert_eq!(dec.decode_terminate().unwrap(), 1); + } +} diff --git a/vendor/oxideav-h265/src/encoder/ccp_streams.rs b/vendor/oxideav-h265/src/encoder/ccp_streams.rs new file mode 100644 index 0000000..c5ca427 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/ccp_streams.rs @@ -0,0 +1,540 @@ +//! Self-built §8.6.6 cross-component-prediction conformance stream +//! (test-only). +//! +//! No black-box encoder binary exposes the range-extension +//! cross-component prediction tool, so this module assembles a tiny +//! 4:4:4 lossless (transquant-bypass) all-intra Annex B bitstream from +//! this crate's own header writers and CABAC encoder. Every coding +//! unit signals derived (DM) chroma so the §7.3.8.10 `cross_comp_pred` +//! gate holds, and the per-CTB `ResScaleVal` plan cycles through every +//! legal magnitude and both signs for Cb and Cr independently — +//! including a CTB whose chroma residual is exactly the scaled luma +//! residual (cbf clear, CCP still signalled) and zero-scale controls. +//! +//! The stream reconstructs losslessly: the encoder codes the chroma +//! residual as `( orig − pred ) − ( ResScaleVal * rY ) >> 3` so the +//! decoder's eq. 8-324 modification restores `orig` exactly. The +//! checked-in copy under `tests/fixture_bytes/` was validated against +//! a black-box reference decoder (byte-exact; SHA-256 sums in +//! `tests/fixture_bytes/r416-generation-notes.md`); the tests here pin +//! (a) that the builder still produces those exact bytes and (b) that +//! this crate's decoder reconstructs the procedural source planes. + +use crate::binarization::{ + cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, intra_luma_cand_mode_list, + log2_res_scale_abs_plus1_ctx_inc, res_scale_sign_flag_ctx_inc, +}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::intra::{gather_refs, zscan_avail}; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::residual::encode_residual_coding; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{ + intra_predict_with_substitution, Component as PredComponent, IntraPredParams, +}; +use crate::residual::{residual_coding_scan_idx, ResidualCodingParams}; + +/// One picture's `(Y, Cb, Cr)` planes (all full-resolution — 4:4:4). +pub(super) type Planes = (Vec, Vec, Vec); + +/// CTB / coding-block log2 size (16x16, `MinCbSizeY == CtbSizeY`). +const CTB_LOG2: u32 = 4; +const CTB: usize = 1 << CTB_LOG2; +/// SliceQpY (immaterial — every CU is transquant-bypassed). +const SLICE_QP: i32 = 26; + +/// Deterministic 4:4:4 source planes: smooth gradients plus a coarse +/// checker texture (full-resolution chroma). +pub(super) fn source_planes_444(w: usize, h: usize) -> Planes { + let lum = |x: i32, y: i32| -> u8 { + let g = (x * 3 + y * 5) % 197; + let t = ((x / 4 + y / 4) % 3) * 23; + (16 + g + t).clamp(0, 255) as u8 + }; + let chr = |x: i32, y: i32, ph: i32| -> u8 { + let g = (x * 7 + y * 2 + ph) % 151; + let t = ((x / 4 + y / 8) % 2) * 31; + (40 + g + t).clamp(0, 255) as u8 + }; + let mut y_p = Vec::with_capacity(w * h); + let mut cb_p = Vec::with_capacity(w * h); + let mut cr_p = Vec::with_capacity(w * h); + for yy in 0..h as i32 { + for xx in 0..w as i32 { + y_p.push(lum(xx, yy)); + cb_p.push(chr(xx, yy, 0)); + cr_p.push(chr(xx, yy, 61)); + } + } + (y_p, cb_p, cr_p) +} + +/// §7.3.3 — profile tier level for Format Range Extensions +/// (`general_profile_idc == 4`) with the 4:4:4 8-bit constraint-flag +/// pattern (`max_422chroma` / `max_420chroma` clear). +fn write_ptl_rext_444(w: &mut BitWriter, level_idc: u8) { + w.put_bits(0, 2); // general_profile_space + w.put_bit(0); // general_tier_flag + w.put_bits(4, 5); // general_profile_idc = 4 (Range Extensions) + let mut compat: u32 = 0; + compat |= 1 << (31 - 4); // flag[4] — Range Extensions + w.put_bits(compat, 32); + w.put_bit(1); // general_progressive_source_flag + w.put_bit(0); // general_interlaced_source_flag + w.put_bit(1); // general_non_packed_constraint_flag + w.put_bit(1); // general_frame_only_constraint_flag + w.put_bit(1); // general_max_12bit_constraint_flag + w.put_bit(1); // general_max_10bit_constraint_flag + w.put_bit(1); // general_max_8bit_constraint_flag + w.put_bit(0); // general_max_422chroma_constraint_flag + w.put_bit(0); // general_max_420chroma_constraint_flag + w.put_bit(0); // general_max_monochrome_constraint_flag + w.put_bit(0); // general_intra_constraint_flag + w.put_bit(0); // general_one_picture_only_constraint_flag + w.put_bit(0); // general_lower_bit_rate_constraint_flag + // general_reserved_zero_34bits + w.put_bits(0, 32); + w.put_bits(0, 2); + w.put_bit(0); // general_inbld_flag (reserved zero) + w.put_bits(level_idc as u32, 8); // general_level_idc + // sps_max_sub_layers_minus1 == 0: no sub-layer flags, no bytes. +} + +/// §7.3.2.1 — minimal single-layer VPS carrying the 4:4:4 Rext PTL. +fn write_vps_rext_444(level_idc: u8) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // vps_video_parameter_set_id + w.put_bit(1); // vps_base_layer_internal_flag + w.put_bit(1); // vps_base_layer_available_flag + w.put_bits(0, 6); // vps_max_layers_minus1 + w.put_bits(0, 3); // vps_max_sub_layers_minus1 + w.put_bit(1); // vps_temporal_id_nesting_flag + w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits + write_ptl_rext_444(&mut w, level_idc); + w.put_bit(1); // vps_sub_layer_ordering_info_present_flag + w.ue(1); // vps_max_dec_pic_buffering_minus1[0] + w.ue(0); // vps_max_num_reorder_pics[0] + w.ue(0); // vps_max_latency_increase_plus1[0] + w.put_bits(0, 6); // vps_max_layer_id + w.ue(0); // vps_num_layer_sets_minus1 + w.put_bit(0); // vps_timing_info_present_flag + w.put_bit(0); // vps_extension_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.2 — 4:4:4 8-bit SPS (CTB 16, no PCM, SAO off, no +/// extensions). +fn write_sps_444(width: usize, height: usize, level_idc: u8) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl_rext_444(&mut w, level_idc); + w.ue(0); // sps_seq_parameter_set_id + w.ue(3); // chroma_format_idc = 4:4:4 + w.put_bit(0); // separate_colour_plane_flag + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + w.put_bit(0); // conformance_window_flag + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(0); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(0); // amp_enabled_flag + w.put_bit(0); // sample_adaptive_offset_enabled_flag + w.put_bit(0); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(0); // sps_extension_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.3 — PPS with `transquant_bypass_enabled_flag == 1` and a +/// `pps_range_extension()` whose +/// `cross_component_prediction_enabled_flag` is 1. +fn write_pps_ccp() -> Vec { + let mut w = BitWriter::new(); + w.ue(0); // pps_pic_parameter_set_id + w.ue(0); // pps_seq_parameter_set_id + w.put_bit(0); // dependent_slice_segments_enabled_flag + w.put_bit(0); // output_flag_present_flag + w.put_bits(0, 3); // num_extra_slice_header_bits + w.put_bit(0); // sign_data_hiding_enabled_flag + w.put_bit(0); // cabac_init_present_flag + w.ue(0); // num_ref_idx_l0_default_active_minus1 + w.ue(0); // num_ref_idx_l1_default_active_minus1 + w.se(SLICE_QP - 26); // init_qp_minus26 + w.put_bit(0); // constrained_intra_pred_flag + w.put_bit(0); // transform_skip_enabled_flag + w.put_bit(0); // cu_qp_delta_enabled_flag + w.se(0); // pps_cb_qp_offset + w.se(0); // pps_cr_qp_offset + w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag + w.put_bit(0); // weighted_pred_flag + w.put_bit(0); // weighted_bipred_flag + w.put_bit(1); // transquant_bypass_enabled_flag + w.put_bit(0); // tiles_enabled_flag + w.put_bit(0); // entropy_coding_sync_enabled_flag + w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag + w.put_bit(1); // deblocking_filter_control_present_flag + w.put_bit(0); // deblocking_filter_override_enabled_flag + w.put_bit(1); // pps_deblocking_filter_disabled_flag + w.put_bit(0); // pps_scaling_list_data_present_flag + w.put_bit(0); // lists_modification_present_flag + w.ue(0); // log2_parallel_merge_level_minus2 + w.put_bit(0); // slice_segment_header_extension_present_flag + w.put_bit(1); // pps_extension_present_flag + w.put_bit(1); // pps_range_extension_flag + w.put_bit(0); // pps_multilayer_extension_flag + w.put_bit(0); // pps_3d_extension_flag + w.put_bit(0); // pps_scc_extension_flag + w.put_bits(0, 4); // pps_extension_4bits + // pps_range_extension() — §7.3.2.3.2 (transform_skip disabled ⇒ no + // log2_max_transform_skip_block_size_minus2). + w.put_bit(1); // cross_component_prediction_enabled_flag + w.put_bit(0); // chroma_qp_offset_list_enabled_flag + w.ue(0); // log2_sao_offset_scale_luma + w.ue(0); // log2_sao_offset_scale_chroma + w.rbsp_trailing_bits(); + w.finish() +} + +pub(super) fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + out.push(i32::from(plane[(y0 + j) * pw + x0 + i])); + } + } + out +} + +/// The intra prediction params mirroring the stream's SPS: 4:4:4, +/// default smoothing, no strong smoothing, boundary filters active +/// (no implicit RDPCM in this stream). +pub(super) fn ip_params_444(mode: u8, cidx: PredComponent) -> IntraPredParams { + IntraPredParams { + pred_mode_intra: mode, + cidx, + bit_depth: 8, + bit_depth_luma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: false, + chroma_array_type_3: true, + disable_boundary_filter: false, + } +} + +/// Per-CTB plan: `(luma_mode, cb_scale, cr_scale)`. Chroma is always +/// DM (`intra_chroma_pred_mode == 4`) so the §7.3.8.10 +/// `cross_comp_pred` gate holds for every CU with a coded luma +/// residual. The ResScaleVal plan sweeps every legal magnitude and +/// both signs across the picture, with zero-scale controls. +fn ccp_plan(ctb: usize) -> (u8, i32, i32) { + const MODES: [u8; 6] = [0, 1, 26, 10, 18, 34]; + const SCALES: [i32; 9] = [1, -1, 2, -2, 4, -4, 8, -8, 0]; + let mode = MODES[ctb % MODES.len()]; + let cb = SCALES[ctb % SCALES.len()]; + let cr = SCALES[(ctb + 4) % SCALES.len()]; + (mode, cb, cr) +} + +/// The CTB index whose chroma source is rewritten so the coded chroma +/// residual is exactly zero while `cross_comp_pred` still fires — the +/// cbf-clear + CCP pin. +const ZERO_RESIDUAL_CTB: usize = 5; + +/// Encode the §9.3.3.8 TR(cMax = 4) `log2_res_scale_abs_plus1[ c ]` +/// prefix plus the `res_scale_sign_flag[ c ]` for one component. +pub(super) fn encode_cross_comp_pred( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + c: u32, + res_scale_val: i32, +) { + let (prefix, sign) = if res_scale_val == 0 { + (0u32, None) + } else { + let mag = res_scale_val.unsigned_abs(); + debug_assert!(mag.is_power_of_two() && mag <= 8); + (mag.trailing_zeros() + 1, Some(u8::from(res_scale_val < 0))) + }; + // TR cMax = 4: `prefix` ones then a terminating zero unless the + // prefix equals cMax; each bin has ctxInc = 4*c + binIdx. + for bin_idx in 0..prefix { + let ctx = log2_res_scale_abs_plus1_ctx_inc(bin_idx, c) as usize; + cabac.encode_decision(w, &mut ctxs.log2_res_scale_abs_plus1[ctx], 1); + } + if prefix < 4 { + let ctx = log2_res_scale_abs_plus1_ctx_inc(prefix, c) as usize; + cabac.encode_decision(w, &mut ctxs.log2_res_scale_abs_plus1[ctx], 0); + } + if let Some(s) = sign { + let ctx = res_scale_sign_flag_ctx_inc(c) as usize; + cabac.encode_decision(w, &mut ctxs.res_scale_sign_flag[ctx], s); + } +} + +/// Encode the all-intra 4:4:4 bypass slice: one 16x16 `PART_2Nx2N` CU +/// per CTB, DM chroma, per-CTB `cross_comp_pred` scales from +/// [`ccp_plan`]. Lossless: the reconstruction equals the source, so +/// reference samples read the (possibly rewritten) source planes. +/// +/// `cb` / `cr` are mutated for [`ZERO_RESIDUAL_CTB`]: its chroma +/// source becomes exactly `pred + ( ResScaleVal * rY ) >> 3`, so the +/// coded chroma residual is zero while CCP still applies. +fn encode_ccp_idr_slice( + y: &[u8], + cb: &mut [u8], + cr: &mut [u8], + width: usize, + height: usize, +) -> Vec { + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + + let mut w = BitWriter::new(); + // ---- slice_segment_header( ) ---- + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(2); // slice_type = I + w.se(0); // slice_qp_delta + w.rbsp_trailing_bits(); // byte_alignment() + + // ---- slice_segment_data( ) ---- + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let (mode, cb_scale, cr_scale) = ccp_plan(ctb); + + // Luma prediction + residual (lossless recon == source). + let read_y = |x: usize, yy: usize| i32::from(y[yy * width + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read_y, &avail, x0, y0, CTB); + let pred = + intra_predict_with_substitution(&marked, &ip_params_444(mode, PredComponent::Luma)) + .expect("legal prediction"); + let src = extract(y, width, x0, y0, CTB); + let res_l: Vec = src.iter().zip(&pred).map(|(s, p)| s - p).collect(); + let cbf_luma = res_l.iter().any(|&v| v != 0); + // §7.3.8.10: cross_comp_pred needs cbf_luma; without it the + // decoder infers ResScaleVal 0. + let (cb_scale, cr_scale) = if cbf_luma { + (cb_scale, cr_scale) + } else { + (0, 0) + }; + + // Chroma 16x16 TBs at (x0, y0) — 4:4:4, DM mode. + let code_chroma = |plane: &mut [u8], pc: PredComponent, scale: i32| -> Vec { + let pred = { + let read = |x: usize, yy: usize| i32::from(plane[yy * width + x]); + let avail = + |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read, &avail, x0, y0, CTB); + intra_predict_with_substitution(&marked, &ip_params_444(mode, pc)) + .expect("legal prediction") + }; + if ctb == ZERO_RESIDUAL_CTB { + // Rewrite the source so orig == pred + ccp_term + // (clamped to 8-bit: pick a value that stays exact). + for j in 0..CTB { + for i in 0..CTB { + let term = (scale * res_l[j * CTB + i]) >> 3; + let v = (pred[j * CTB + i] + term).clamp(0, 255); + plane[(y0 + j) * width + x0 + i] = v as u8; + } + } + } + let src = extract(plane, width, x0, y0, CTB); + src.iter() + .zip(&pred) + .enumerate() + .map(|(k, (s, p))| { + let term = (scale * res_l[k]) >> 3; + s - p - term + }) + .collect() + }; + let res_cb = code_chroma(cb, PredComponent::Cb, cb_scale); + let res_cr = code_chroma(cr, PredComponent::Cr, cr_scale); + + // ---- §7.3.8.5 coding_unit( ) ---- + cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N + let avail_l = zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0); + let avail_a = zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0); + let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + let sel = list.iter().position(|&m| m == mode); + cabac.encode_decision( + &mut w, + &mut ctxs.prev_intra_luma_pred_flag[0], + u8::from(sel.is_some()), + ); + modes.record_intra_pb(x0, y0, CTB, mode, false); + match sel { + Some(0) => cabac.encode_bypass(&mut w, 0), + Some(1) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 0); + } + Some(_) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 1); + } + None => { + let mut rem = u32::from(mode); + for &c in &list { + if u32::from(mode) > u32::from(c) { + rem -= 1; + } + } + cabac.encode_bypass_bits(&mut w, rem, 5); + } + } + // intra_chroma_pred_mode = 4 (derived / DM): single ctx bin 0. + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); + + // ---- transform_tree / transform_unit ---- + let cbf_cb_f = res_cb.iter().any(|&v| v != 0); + let cbf_cr_f = res_cr.iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + let rc = |is_chroma: bool| ResidualCodingParams { + log2_trafo_size: 4, + is_chroma, + scan_idx: residual_coding_scan_idx(true, 4, u8::from(is_chroma), 3, u32::from(mode)), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + if cbf_luma { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(false), &res_l) + .expect("valid luma levels"); + } + // §7.3.8.10 in-place chroma: cross_comp_pred( x0, y0, 0 ), + // Cb residual, cross_comp_pred( x0, y0, 1 ), Cr residual. The + // gate is cross_component_prediction_enabled_flag && cbf_luma + // && intra_chroma_pred_mode == 4. + if cbf_luma { + encode_cross_comp_pred(&mut w, &mut cabac, &mut ctxs, 0, cb_scale); + } + if cbf_cb_f { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cb) + .expect("valid cb levels"); + } + if cbf_luma { + encode_cross_comp_pred(&mut w, &mut cabac, &mut ctxs, 1, cr_scale); + } + if cbf_cr_f { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cr) + .expect("valid cr levels"); + } + + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + w.finish() +} + +/// The cross-component-prediction conformance stream: VPS + SPS(4:4:4) +/// + PPS(rext, CCP) + one all-intra bypass IDR picture (64x48). +/// +/// Returns the Annex B bytes and the expected (lossless) planes. +pub(crate) fn build_ccp_stream() -> (Vec, Planes) { + let (w, h) = (64usize, 48usize); + let (y, mut cb, mut cr) = source_planes_444(w, h); + let slice = encode_ccp_idr_slice(&y, &mut cb, &mut cr, w, h); + let units = vec![ + nal_unit(32, 0, 0, &write_vps_rext_444(30)), + nal_unit(33, 0, 0, &write_sps_444(w, h, 30)), + nal_unit(34, 0, 0, &write_pps_ccp()), + nal_unit(20, 0, 0, &slice), // IDR_N_LP + ]; + (annexb(&units), (y, cb, cr)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sequence::decode_annexb_sequence; + + /// The checked-in stream bytes (black-box-reference-validated; see + /// `tests/fixture_bytes/r416-generation-notes.md`) are exactly + /// what the builder produces, and this crate's decoder + /// reconstructs the procedural source losslessly through the + /// §8.6.6 cross-component-prediction path — every legal + /// ResScaleVal magnitude, both signs, both components, plus the + /// cbf-clear-with-CCP and zero-scale controls. + #[test] + fn ccp_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_ccp_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r416-ccp.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + let got = frames[0].picture.to_planar_u8().expect("8-bit planes"); + assert_eq!(got, expected, "lossless CCP decode"); + } + + /// The plan exercises the cbf-clear + CCP coding unit: the + /// designated CTB codes NO chroma residual yet carries non-zero + /// ResScaleVal (its chroma reconstruction is purely the scaled + /// luma residual on top of the prediction). + #[test] + fn ccp_stream_covers_cbf_clear_ccp_block() { + let (mode, cb_s, cr_s) = ccp_plan(ZERO_RESIDUAL_CTB); + let _ = mode; + assert!(cb_s != 0 || cr_s != 0, "zero-residual CTB must scale"); + } +} diff --git a/vendor/oxideav-h265/src/encoder/inter.rs b/vendor/oxideav-h265/src/encoder/inter.rs new file mode 100644 index 0000000..d032a39 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/inter.rs @@ -0,0 +1,3154 @@ +//! Low-delay GOP encoder — §8.5 inter prediction on the encode side. +//! +//! The sequence shape is `IDR, P, P, …` (or `IDR, B, B, …` with +//! [`LowDelayPEncoder::with_b_slices`]): the first frame goes through +//! the real CABAC intra encoder ([`crate::encoder::intra`]), every +//! following frame is one P / low-delay-B slice (TRAIL_R) whose +//! active reference(s) — `RefPicList0[0]`, and `RefPicList1[0]` on B +//! slices — resolve to the previous frame's reconstruction, signalled +//! with an inline §7.4.8 short-term RPS (`num_negative_pics == 1`, +//! `delta_poc == −1`). Low-delay B keeps decode order == display +//! order while enabling the bi-predictive §8.5.3.2.2 merge candidates +//! (zero-merge and combined candidates are bi on B slices) and the +//! B-side syntax (`inter_pred_idc`, `mvd_l1_zero_flag`, initType 2 +//! contexts). +//! +//! Geometry mirrors the intra bootstrap: `CtbSizeY == MinCbSizeY == +//! 16`, so every CTB is one unsplit CU; inter CUs are `PART_2Nx2N` +//! (one 16x16 PU, one depth-0 TU). Per CTU three coding modes compete +//! under an SSD + λ·rate heuristic: +//! +//! * **skip** (`cu_skip_flag == 1`) — the SAD-best §8.5.3.2.2 merge +//! candidate with no residual; +//! * **merge + residual** (`merge_flag == 1`) — the same candidate +//! with the transform-coded residual (`rqt_root_cbf` is inferred 1 +//! for a 2Nx2N merge CU, so an all-zero residual falls back to +//! skip); +//! * **AMVP** — motion-estimated `mvL0` (greedy integer diamond over +//! seeded predictors, then half- then quarter-pel refinement +//! against the crate's own §8.5.3.3.3 interpolation), signalled as +//! `mvp_l0_flag` + §7.3.8.9 `mvd_coding`, with `rqt_root_cbf` +//! electing the residual. +//! +//! Every candidate's motion is resolved through the DECODE-side +//! §8.5.3.2 derivation ([`crate::pu_mv::resolve_pu_motion`] against +//! the picture's in-progress [`MotionField`] and the §6.4.2 +//! availability of [`crate::availability::PictureTiling`]), its +//! prediction through the decode-side §8.5.3.3 driver +//! ([`predict_inter_pu`]), and its reconstruction through the +//! decode-side §8.6 scaling/transform — so the encoder's reference +//! buffer is bit-identical to a conforming decoder's output (in-loop +//! filters are off), which the roundtrip tests pin frame by frame. + +use crate::availability::{PictureTiling, TilingParams, MODE_INTRA}; +use crate::binarization::{ + cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, cu_skip_flag_ctx_inc, + intra_luma_cand_mode_list, CuPredMode, InterPredIdc, MvdComponent, +}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::intra::{ + chroma_qp_420, code_tb, encode_idr_intra_au_full, gather_refs, pred_params, search_best_mode, + ssd, zscan_avail, IntraEncodeError, SpsCfg, +}; +use crate::encoder::loopfilter::{ + encode_sao_ctb, filter_frame, CtbShape, FilterInput, LoopFilterCfg, +}; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::residual::encode_residual_coding; +use crate::inter_pred::{ + predict_inter_pu, InterPredGeometry, InterPrediction, ListPrediction, RefPlane, +}; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{intra_predict_with_substitution, Component as PredComponent}; +use crate::motion::{derive_chroma_mv, MotionCell, MotionField, Mv}; +use crate::pu_mv::{resolve_pu_motion, PartMode, PuGeometry, PuMotion, PuMvContext}; +use crate::residual::{residual_coding_scan_idx, ResidualCodingParams}; +use crate::slice_data::PredictionUnit; +use crate::transform::{Component, PredMode}; + +/// The fixed CTB / coding-block log2 size (16x16). +const CTB_LOG2: u32 = 4; +/// The fixed CTB size. +const CTB: usize = 1 << CTB_LOG2; +/// Fixed 8-bit depth. +const BIT_DEPTH: u8 = 8; +/// `MaxNumMergeCand` (§7.4.7.1) — `five_minus_max_num_merge_cand = 0`. +const MAX_MERGE: usize = 5; +/// The greedy integer-search iteration cap (diamond steps). +const ME_MAX_STEPS: usize = 24; +/// The z-order offsets of the four depth-1 transform units within a +/// CTB (§6.5.2 z-scan of the four halves). +const Z_OFFSETS: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; + +/// One 4:2:0 8-bit input frame (borrowed planes). +#[derive(Debug, Clone, Copy)] +pub struct YuvFrame<'a> { + /// Luma plane, `width * height` samples. + pub y: &'a [u8], + /// Cb plane, `width/2 * height/2` samples. + pub cb: &'a [u8], + /// Cr plane. + pub cr: &'a [u8], +} + +/// One frame's reconstruction (what a conforming decoder outputs). +#[derive(Debug, Clone, Default)] +pub struct FrameRecon { + /// Reconstructed luma plane. + pub y: Vec, + /// Reconstructed Cb plane. + pub cb: Vec, + /// Reconstructed Cr plane. + pub cr: Vec, +} + +/// The encoded low-delay sequence: the Annex B stream (`VPS + SPS + +/// PPS + IDR, TRAIL_R, TRAIL_R, …`) plus the per-frame encoder +/// reconstructions in output order. +#[derive(Debug, Clone)] +pub struct LowDelayPEncoded { + /// The whole Annex B byte stream. + pub stream: Vec, + /// Per-frame reconstruction, `frames.len()` entries. + pub recon: Vec, + /// Per-frame CU mode decisions, `frames.len()` entries (frame 0 — + /// the IDR — counts every CTB as intra). + pub stats: Vec, +} + +/// Per-frame CU mode-decision counters (one CU per CTB). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct FrameStats { + /// `cu_skip_flag == 1` CUs. + pub skip: usize, + /// Merge-with-residual CUs. + pub merge: usize, + /// AMVP (explicit-MV) CUs. + pub amvp: usize, + /// Intra CUs (`pred_mode_flag == 1`, or every CU of the IDR). + pub intra: usize, + /// Bi-predicted CUs (both `predFlagLX` set on some PU — B slices + /// only; an overlay of the mode classes above). + pub bi: usize, + /// Rectangular-partition CUs (`PART_2NxN` / `PART_Nx2N` — an + /// overlay counted in `merge` / `amvp` too). + pub rect: usize, + /// Asymmetric-partition CUs (`PART_2NxnU` / `PART_2NxnD` / + /// `PART_nLx2N` / `PART_nRx2N` — an overlay counted in `merge` / + /// `amvp` too; AMP streams only). + pub amp: usize, + /// CUs referencing the second reference picture (POC − 2) on some + /// PU / list (an overlay of the mode classes above). + pub ref1: usize, +} + +/// A resolved-and-coded CU candidate. +struct CuCandidate { + /// How the CU is signalled. + kind: CuKind, + /// The §8.5.3.2.1-resolved per-PU motion in §7.3.8.6 order (what + /// the decoder will derive); empty for an intra CU. + motions: Vec, + /// The coded transform tree; `None` ⇔ no tree (skip, or + /// `rqt_root_cbf == 0`). + levels: Option, + /// The CTB reconstruction (y 16x16, cb 8x8, cr 8x8). + recon: [Vec; 3], + /// SSD + λ·rate cost. + cost: u64, +} + +/// The quantized levels of a CU candidate's transform tree. +enum CuLevels { + /// One depth-0 TU: luma 16x16, cb 8x8, cr 8x8. + Depth0([Vec; 3]), + /// The §7.4.9.8 `interSplitFlag` forced depth-1 tree (rectangular + /// inter partitions at `max_transform_hierarchy_depth_inter == 0`): + /// four z-order 8x8 luma and 4x4 chroma TBs per plane (boxed to + /// keep the variant sizes comparable). + Depth1(Box), +} + +/// The four z-order leaves of a forced depth-1 transform tree. +struct Depth1Levels { + luma: [Vec; 4], + cb: [Vec; 4], + cr: [Vec; 4], +} + +/// One list's non-merge (AMVP) signalling group: `ref_idx_lX` (when +/// that list has more than one active reference), the §7.3.8.9 +/// `mvd_coding( )` pair, and `mvp_lX_flag`. +#[derive(Clone, Copy)] +struct AmvpGroup { + ref_idx: u8, + mvd: Mv, + mvp_flag: u8, +} + +/// One prediction unit's §7.3.8.6 signalling (merge or AMVP). +#[derive(Clone, Copy)] +enum PuSyntax { + /// `merge_flag == 1`, `merge_idx`. + Merge { merge_idx: usize }, + /// `merge_flag == 0`: `inter_pred_idc` (on B slices) selects the + /// used list(s) — `PRED_L0`, `PRED_L1` or `PRED_BI` — and each + /// used list carries its [`AmvpGroup`]. + Amvp { + l0: Option, + l1: Option, + }, +} + +/// The signalling class of a chosen CU. +enum CuKind { + /// `cu_skip_flag == 1`, `merge_idx`. + Skip { merge_idx: usize }, + /// `merge_flag == 1`, `merge_idx`, transform tree follows + /// (`rqt_root_cbf` inferred 1). + Merge { merge_idx: usize }, + /// AMVP (one 2Nx2N PU): the carried [`PuSyntax::Amvp`] group; + /// `rqt_root_cbf` signalled. + Amvp { pu: PuSyntax }, + /// Two-PU inter partition (`PART_2NxN` / `PART_Nx2N`, or one of + /// the four AMP shapes on an AMP stream): two prediction units, + /// the forced depth-1 RQT, `rqt_root_cbf` signalled. + TwoPu { part: PartMode, pus: [PuSyntax; 2] }, + /// Intra fallback (`pred_mode_flag == 1`, `PART_2Nx2N`): §8.4 + /// prediction with luma mode `mode`, chroma derived-from-luma. + Intra { mode: u8 }, +} + +/// One frame's output from the streaming [`LowDelayPEncoder`]. +#[derive(Debug, Clone)] +pub struct EncodedPFrame { + /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP` for a + /// keyframe, one `TRAIL_R` slice otherwise). + pub au: Vec, + /// `true` for an IDR access unit (a random access point). + pub keyframe: bool, + /// The frame's reconstruction (== a conforming decoder's output). + pub recon: FrameRecon, + /// The frame's CU mode-decision counters. + pub stats: FrameStats, +} + +/// The streaming low-delay encoder: one frame in, one access unit +/// out. The first frame (and every `gop`-th frame when `gop > 0`) +/// becomes a self-contained IDR access unit; every other frame is a +/// P slice referencing the previous frame's reconstruction. +#[derive(Debug)] +pub struct LowDelayPEncoder { + width: usize, + height: usize, + qp: i32, + /// GOP length in frames (`0` = a single leading IDR, endless P). + gop: usize, + /// Code the non-IDR frames as (low-delay) B slices: both + /// reference lists resolve to the previous picture, enabling + /// bi-predictive merge candidates and the B-slice syntax. + b_slices: bool, + /// The §8.7 in-loop filters this stream signals and applies on + /// its reconstruction path. + filters: LoopFilterCfg, + /// AMP stream configuration: `MinCbSizeY == 8` with every CTB an + /// unsplit 16x16 CU, `amp_enabled_flag == 1`, and the asymmetric + /// PART_2NxnU/2NxnD/nLx2N/nRx2N shapes competing in the inter CU + /// ladder. + amp: bool, + /// POC of the NEXT frame within the current GOP (0 ⇒ IDR next). + poc: i32, + /// The most recent reconstructions, newest first (up to two — the + /// active references POC − 1 and POC − 2). + prevs: Vec, +} + +impl LowDelayPEncoder { + /// Construct a streaming encoder for `width`x`height` 4:2:0 8-bit + /// content at constant `SliceQpY == qp`. `gop == 0` emits a + /// single leading IDR; `gop == n` re-emits an IDR every `n` + /// frames. + /// + /// # Errors + /// [`IntraEncodeError`] on bad dimensions / QP. + pub fn new(width: usize, height: usize, qp: i32, gop: usize) -> Result { + if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 { + return Err(IntraEncodeError::BadDimensions { width, height }); + } + if !(0..=51).contains(&qp) { + return Err(IntraEncodeError::BadQp(qp)); + } + Ok(Self { + width, + height, + qp, + gop, + b_slices: false, + filters: LoopFilterCfg::off(), + amp: false, + poc: 0, + prevs: Vec::new(), + }) + } + + /// Code non-IDR frames as low-delay B slices (both reference + /// lists resolving to the previous picture) instead of P slices. + #[must_use] + pub fn with_b_slices(mut self, on: bool) -> Self { + self.b_slices = on; + self + } + + /// Switch the stream to the AMP configuration: the SPS signals + /// `MinCbSizeY == 8` + `amp_enabled_flag == 1` (every CTB still + /// one unsplit 16x16 CU, now with an explicit `split_cu_flag`), + /// and the inter CU ladder elects the asymmetric + /// `PART_2NxnU / PART_2NxnD / PART_nLx2N / PART_nRx2N` motion + /// partitions alongside the symmetric shapes. + #[must_use] + pub fn with_amp(mut self, on: bool) -> Self { + self.amp = on; + self + } + + /// Enable the §8.7 in-loop filters (deblocking / SAO) on the + /// encoder's reconstruction path: every frame's reference — and + /// the [`EncodedPFrame::recon`] a conforming decoder reproduces — + /// becomes the FILTERED picture, with the filter elections + /// signalled in the parameter sets and slice headers. + #[must_use] + pub fn with_loop_filters(mut self, filters: LoopFilterCfg) -> Self { + self.filters = filters; + self + } + + /// Encode the next frame in display order. + /// + /// # Errors + /// [`IntraEncodeError::PlaneSize`] when a plane length does not + /// match the 4:2:0 geometry. + pub fn encode_frame( + &mut self, + frame: &YuvFrame<'_>, + ) -> Result { + let (cw, ch) = (self.width / 2, self.height / 2); + for (plane, buf, expected) in [ + ("y", frame.y, self.width * self.height), + ("cb", frame.cb, cw * ch), + ("cr", frame.cr, cw * ch), + ] { + if buf.len() != expected { + return Err(IntraEncodeError::PlaneSize { + plane, + expected, + got: buf.len(), + }); + } + } + let idr_now = self.prevs.is_empty() || self.poc == 0; + let out = if idr_now { + // sps_max_dec_pic_buffering_minus1 = 2: the current picture + // plus the two short-term references the P/B slices keep. + let idr = encode_idr_intra_au_full( + frame.y, + frame.cb, + frame.cr, + self.width, + self.height, + self.qp, + &SpsCfg { + max_dec_pic_buffering_minus1: 2, + max_num_reorder_pics: 0, + min_cb_log2: if self.amp { 3 } else { 4 }, + amp: self.amp, + conf_win: (0, 0), // edith patch: no crop on the inter paths + }, + &self.filters, + )?; + let recon = FrameRecon { + y: idr.recon_y, + cb: idr.recon_cb, + cr: idr.recon_cr, + }; + self.prevs = vec![recon.clone()]; + self.poc = 1; + EncodedPFrame { + au: idr.au, + keyframe: true, + recon, + stats: FrameStats { + intra: (self.width / CTB) * (self.height / CTB), + ..FrameStats::default() + }, + } + } else { + // The active references: RefPicListX[i] = the + // reconstruction of POC − 1 − i (newest first, up to two), + // and a low-delay B slice holds the same set on both lists. + let l0: Vec<(i32, &FrameRecon)> = self + .prevs + .iter() + .take(2) + .enumerate() + .map(|(i, rec)| (self.poc - 1 - i as i32, rec)) + .collect(); + let spec = SliceSpec { + poc: self.poc, + qp: self.qp, + b_slice: self.b_slices, + rps_neg: (1..=l0.len() as u32).map(|d| (d, true)).collect(), + rps_pos: Vec::new(), + l1: if self.b_slices { + l0.clone() + } else { + Vec::new() + }, + l0, + lf: &self.filters, + big_cu: self.amp, + }; + let (rbsp, recon, stats) = encode_inter_slice(frame, &spec, self.width, self.height); + let au = annexb(&[nal_unit(1, 0, 0, &rbsp)]); // TRAIL_R + self.prevs.insert(0, recon.clone()); + self.prevs.truncate(2); + self.poc += 1; + EncodedPFrame { + au, + keyframe: false, + recon, + stats, + } + }; + // GOP wrap: schedule the next IDR. + if self.gop > 0 && self.poc >= self.gop as i32 { + self.poc = 0; + } + Ok(out) + } +} + +/// Encode a low-delay `IDR, P, P, …` sequence at a constant +/// `SliceQpY == qp` and return the Annex B stream plus the per-frame +/// reconstructions a conforming decoder reproduces exactly. +/// +/// # Errors +/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP (the +/// validation contract is shared with the intra encoder). +pub fn encode_low_delay_p( + frames: &[YuvFrame<'_>], + width: usize, + height: usize, + qp: i32, +) -> Result { + let mut enc = LowDelayPEncoder::new(width, height, qp, 0)?; + let mut out = LowDelayPEncoded { + stream: Vec::new(), + recon: Vec::new(), + stats: Vec::new(), + }; + for frame in frames { + let f = enc.encode_frame(frame)?; + out.stream.extend_from_slice(&f.au); + out.recon.push(f.recon); + out.stats.push(f.stats); + } + Ok(out) +} + +/// The slice header's in-loop-filter fields (§7.3.6.1): the enabled +/// filter set plus this slice's elections. +struct SliceLfSignalling<'a> { + /// The stream's filter configuration (drives field presence: the + /// SAO gates exist iff the SPS enables SAO, the deblocking + /// override group iff the PPS enables the override). + cfg: &'a LoopFilterCfg, + /// This slice's deblocking election + /// (`slice_deblocking_filter_disabled_flag == !deblock_on`). + deblock_on: bool, + /// Elected `slice_beta_offset_div2`. + beta_offset_div2: i32, + /// Elected `slice_tc_offset_div2`. + tc_offset_div2: i32, + /// Elected `slice_sao_luma_flag`. + sao_luma: bool, + /// Elected `slice_sao_chroma_flag`. + sao_chroma: bool, +} + +/// Everything one P / B slice's coding depends on beyond the frame +/// samples: POC, QP, slice type, the inline §7.4.8 short-term RPS +/// content, and the two active reference lists (POC + reconstruction +/// each, in `RefPicListX` order). The low-delay GOP passes past +/// pictures on both lists; the hierarchical-B GOP passes past +/// pictures on L0 and future pictures on L1. +pub(crate) struct SliceSpec<'a> { + /// `PicOrderCntVal` (== `slice_pic_order_cnt_lsb`, 8 bits). + pub poc: i32, + /// `SliceQpY`. + pub qp: i32, + /// B slice (`slice_type == 0`)? + pub b_slice: bool, + /// Negative RPS entries closest-first: `(PocDelta, used_by_curr)` + /// with `PocDelta = poc − entry POC > 0`, strictly increasing. + pub rps_neg: Vec<(u32, bool)>, + /// Positive RPS entries closest-first: `(entry POC − poc, used)`. + pub rps_pos: Vec<(u32, bool)>, + /// `RefPicList0`: active references, `(POC, reconstruction)`. + pub l0: Vec<(i32, &'a FrameRecon)>, + /// `RefPicList1` (B slices; empty on P slices). + pub l1: Vec<(i32, &'a FrameRecon)>, + /// The stream's §8.7 in-loop filter configuration. + pub lf: &'a LoopFilterCfg, + /// Stream geometry: `log2CbSize > MinCbLog2SizeY` (MinCb 8, one + /// explicit `split_cu_flag == 0` per CTB, the Table 9-45 big-CU + /// `part_mode` column, no intra `part_mode`). Implied by the AMP + /// stream configuration. + pub big_cu: bool, +} + +/// §7.3.6.1 — the P / B slice-segment header: an inline §7.4.8 +/// short-term RPS (negative + positive pictures with per-entry used +/// flags), the `num_ref_idx` override when a list keeps more than one +/// active reference, `MaxNumMergeCand == 5`, `slice_qp_delta` against +/// `init_qp == 26`, then the in-loop-filter block (`slice_sao_*` +/// gates when the SPS enables SAO, the deblocking override group when +/// the PPS enables the override, the across-slices flag when any +/// filter is active). +fn write_inter_slice_header(w: &mut BitWriter, spec: &SliceSpec<'_>, lf: &SliceLfSignalling<'_>) { + w.put_bit(1); // first_slice_segment_in_pic_flag + w.ue(0); // slice_pic_parameter_set_id + w.ue(u32::from(!spec.b_slice)); // slice_type (0 = B, 1 = P) + w.put_bits((spec.poc & 0xFF) as u32, 8); // slice_pic_order_cnt_lsb + w.put_bit(0); // short_term_ref_pic_set_sps_flag + // st_ref_pic_set( 0 ) — idx 0 has no + // inter_ref_pic_set_prediction_flag (§7.3.7). + w.ue(spec.rps_neg.len() as u32); // num_negative_pics + w.ue(spec.rps_pos.len() as u32); // num_positive_pics + let mut prev = 0u32; + for &(delta, used) in &spec.rps_neg { + // §7.4.8: DeltaPocS0[i] = DeltaPocS0[i−1] − (minus1 + 1). + w.ue(delta - prev - 1); // delta_poc_s0_minus1[i] + w.put_bit(u8::from(used)); // used_by_curr_pic_s0_flag[i] + prev = delta; + } + let mut prev = 0u32; + for &(delta, used) in &spec.rps_pos { + // §7.4.8: DeltaPocS1[i] = DeltaPocS1[i−1] + (minus1 + 1). + w.ue(delta - prev - 1); // delta_poc_s1_minus1[i] + w.put_bit(u8::from(used)); // used_by_curr_pic_s1_flag[i] + prev = delta; + } + // sps_temporal_mvp_enabled_flag == 0: nothing. + if lf.cfg.sao() { + // SPS SAO enabled: the per-slice component gates are present. + w.put_bit(u8::from(lf.sao_luma)); // slice_sao_luma_flag + w.put_bit(u8::from(lf.sao_chroma)); // slice_sao_chroma_flag + } + let n_l0 = spec.l0.len() as u32; + let n_l1 = spec.l1.len() as u32; + if n_l0 != 1 || (spec.b_slice && n_l1 != 1) { + // PPS defaults are one active reference per list. + w.put_bit(1); // num_ref_idx_active_override_flag + w.ue(n_l0 - 1); // num_ref_idx_l0_active_minus1 + if spec.b_slice { + w.ue(n_l1 - 1); // num_ref_idx_l1_active_minus1 + } + } else { + w.put_bit(0); // num_ref_idx_active_override_flag (default: 1) + } + // lists_modification_present_flag == 0. + if spec.b_slice { + w.put_bit(0); // mvd_l1_zero_flag + } + // cabac_init_present_flag == 0; TMVP off; WP off. + w.ue((5 - MAX_MERGE) as u32); // five_minus_max_num_merge_cand + w.se(spec.qp - 26); // slice_qp_delta + if lf.cfg.deblocking { + // §7.3.6.1 deblocking override group (the PPS signals + // override-enabled + deblocking disabled; an electing slice + // overrides to enabled with zero β/tC offsets). + w.put_bit(u8::from(lf.deblock_on)); // deblocking_filter_override_flag + if lf.deblock_on { + w.put_bit(0); // slice_deblocking_filter_disabled_flag + w.se(lf.beta_offset_div2); // slice_beta_offset_div2 + w.se(lf.tc_offset_div2); // slice_tc_offset_div2 + } + } + if lf.sao_luma || lf.sao_chroma || lf.deblock_on { + // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and + // some in-loop filter is active for this slice. + w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag + } + // No tiles / WPP: no entry points. + w.rbsp_trailing_bits(); // byte_alignment() +} + +/// Extract an `n`x`n` block of `plane` at `(x0, y0)` as `i32`s. +fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + out.push(i32::from(plane[(y0 + j) * pw + x0 + i])); + } + } + out +} + +/// Store an `n`x`n` block back into `plane` at `(x0, y0)`. +fn store(plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]) { + for j in 0..n { + plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n].copy_from_slice(&s[j * n..(j + 1) * n]); + } +} + +/// The [`crate::binarization::PartMode`] twin of a [`PartMode`] (the +/// loop-filter descriptors speak the binarization enum). +fn bin_part_mode(p: PartMode) -> crate::binarization::PartMode { + use crate::binarization::PartMode as B; + match p { + PartMode::Part2Nx2N => B::Part2Nx2N, + PartMode::Part2NxN => B::Part2NxN, + PartMode::PartNx2N => B::PartNx2N, + PartMode::PartNxN => B::PartNxN, + PartMode::Part2NxnU => B::Part2NxnU, + PartMode::Part2NxnD => B::Part2NxnD, + PartMode::PartNLx2N => B::PartNLx2N, + PartMode::PartNRx2N => B::PartNRx2N, + } +} + +/// `true` for the horizontal-split two-PU shapes (`PART_2NxN` / +/// `PART_2NxnU` / `PART_2NxnD`) — Table 9-45 bin 1. +fn part_is_horizontal(p: PartMode) -> bool { + matches!( + p, + PartMode::Part2NxN | PartMode::Part2NxnU | PartMode::Part2NxnD + ) +} + +/// `true` for the four asymmetric shapes. +fn part_is_amp(p: PartMode) -> bool { + matches!( + p, + PartMode::Part2NxnU | PartMode::Part2NxnD | PartMode::PartNLx2N | PartMode::PartNRx2N + ) +} + +/// The merge / skip PU syntax for candidate `merge_idx` (the §7.3.8.6 +/// fields the §8.5.3.2.2 derivation reads). +fn merge_pu(merge_idx: usize) -> PredictionUnit { + PredictionUnit { + merge_flag: true, + merge_idx: Some(merge_idx as u8), + inter_pred_idc: None, + ref_idx_l0: None, + mvd_l0: None, + mvp_l0_flag: None, + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + } +} + +/// An AMVP PU carrying the given per-list signalling groups (the +/// §7.3.8.6 fields the §8.5.3.2 derivation reads). At least one list +/// must be used; `inter_pred_idc` follows from which are. +fn amvp_pu(l0: Option, l1: Option) -> PredictionUnit { + let comp = |v: i32| MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + }; + let idc = match (l0.is_some(), l1.is_some()) { + (true, true) => InterPredIdc::PredBi, + (false, true) => InterPredIdc::PredL1, + // An AMVP PU uses at least one list; default to L0. + _ => InterPredIdc::PredL0, + }; + PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(idc), + ref_idx_l0: l0.map(|g| g.ref_idx), + mvd_l0: l0.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]), + mvp_l0_flag: l0.map(|g| g.mvp_flag), + ref_idx_l1: l1.map(|g| g.ref_idx), + mvd_l1: l1.map(|g| [comp(g.mvd[0]), comp(g.mvd[1])]), + mvp_l1_flag: l1.map(|g| g.mvp_flag), + } +} + +/// A single-list [`amvp_pu`] probe (zero or explicit mvd) for the +/// §8.5.3.2.6 predictor derivation and the ME resolution step. +fn amvp_pu_list(list: usize, ref_idx: u8, mvd: Mv, mvp_flag: u8) -> PredictionUnit { + let g = Some(AmvpGroup { + ref_idx, + mvd, + mvp_flag, + }); + if list == 0 { + amvp_pu(g, None) + } else { + amvp_pu(None, g) + } +} + +/// Select the plane set a list prediction reads: the used list's +/// `refs[refIdxLX]`, or (for an unused list, whose planes are never +/// read) any legal plane set from either list. +fn pick_ref<'r>( + refs: &'r [RefPlanes], + other: &'r [RefPlanes], + pred_flag: bool, + ref_idx: i32, +) -> &'r RefPlanes { + if pred_flag { + &refs[ref_idx.max(0) as usize] + } else { + refs.first().unwrap_or_else(|| &other[0]) + } +} + +/// §8.5.3.3 — the final clipped prediction for a `w`x`h` PU at +/// `(x0, y0)` with the resolved motion (uni-L0, uni-L1 or bi). Each +/// used list reads `refs_lX[ refIdxLX ]`; the low-delay GOP passes the +/// same past reconstructions on both lists, the hierarchical-B GOP +/// passes past pictures on L0 and future pictures on L1. `chroma` +/// selects whether the Cb / Cr planes are predicted too (the SAD +/// search runs luma-only). +#[allow(clippy::too_many_arguments)] +fn predict_block( + refs_l0: &[RefPlanes], + refs_l1: &[RefPlanes], + x0: usize, + y0: usize, + w: usize, + h: usize, + motion: &PuMotion, + chroma: bool, +) -> InterPrediction { + fn list(refp: &RefPlanes, pred_flag: bool, mv: Mv, chroma: bool) -> ListPrediction<'_> { + let luma = RefPlane::new(&refp.y, refp.width, refp.height).expect("legal ref plane"); + let (cb, cr) = if chroma { + ( + Some( + RefPlane::new(&refp.cb, refp.width / 2, refp.height / 2).expect("legal plane"), + ), + Some( + RefPlane::new(&refp.cr, refp.width / 2, refp.height / 2).expect("legal plane"), + ), + ) + } else { + (None, None) + }; + ListPrediction { + pred_flag, + luma, + cb, + cr, + mv_l: mv, + // §8.5.3.2.10: 4:2:0 chroma MV = luma MV (eighth-pel units). + mv_c: derive_chroma_mv(mv, 2, 2), + } + } + let l0 = list( + pick_ref(refs_l0, refs_l1, motion.pred_flag_l0, motion.ref_idx_l0), + motion.pred_flag_l0, + motion.mv_l0, + chroma, + ); + let l1 = list( + pick_ref(refs_l1, refs_l0, motion.pred_flag_l1, motion.ref_idx_l1), + motion.pred_flag_l1, + motion.mv_l1, + chroma, + ); + let geom = InterPredGeometry { + x_pb: x0 as i32, + y_pb: y0 as i32, + n_pb_w: w, + n_pb_h: h, + chroma_array_type: if chroma { 1 } else { 0 }, + bit_depth_luma: BIT_DEPTH, + bit_depth_chroma: BIT_DEPTH, + }; + predict_inter_pu(&l0, &l1, &geom).expect("legal prediction geometry") +} + +/// Copy a `w`x`h` block into a `bw`-wide buffer at `(bx, by)`. +fn blit(dst: &mut [i32], bw: usize, bx: usize, by: usize, src: &[i32], w: usize, h: usize) { + for j in 0..h { + dst[(by + j) * bw + bx..(by + j) * bw + bx + w].copy_from_slice(&src[j * w..(j + 1) * w]); + } +} + +/// Extract an `n`x`n` sub-block of a `bw`-wide buffer at `(bx, by)`. +fn sub_block(buf: &[i32], bw: usize, bx: usize, by: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + out.extend_from_slice(&buf[(by + j) * bw + bx..(by + j) * bw + bx + n]); + } + out +} + +/// A uni-L0 [`PuMotion`] for motion-search probes (list-0 reference +/// index 0 — the probe caller passes the searched reference's planes +/// as the single-entry `refs` slice). +fn uni_l0(mv: Mv) -> PuMotion { + PuMotion { + pred_flag_l0: true, + pred_flag_l1: false, + ref_idx_l0: 0, + ref_idx_l1: -1, + mv_l0: mv, + mv_l1: [0, 0], + } +} + +/// The previous frame's reconstruction as `i32` planes (the +/// §8.5.3.3.3 interpolation input). +struct RefPlanes { + y: Vec, + cb: Vec, + cr: Vec, + width: usize, + height: usize, +} + +/// Luma SAD between a prediction and the source block. +fn sad(pred: &[i32], src: &[i32]) -> u64 { + pred.iter() + .zip(src.iter()) + .map(|(&p, &s)| u64::from(p.abs_diff(s))) + .sum() +} + +/// Rate proxy (bins) for one signed mvd component. +fn mvd_component_bits(v: i32) -> u64 { + match v.unsigned_abs() { + 0 => 1, + 1 => 3, + a => 5 + 2 * u64::from(32 - (a - 1).leading_zeros()), + } +} + +/// Rate proxy for a full mvd pair. +fn mvd_bits(mvd: Mv) -> u64 { + mvd_component_bits(mvd[0]) + mvd_component_bits(mvd[1]) +} + +/// Crude bit-cost proxy for one TB's quantized levels (mirrors the +/// intra encoder's heuristic). +fn levels_rate(levels: &[i32]) -> u64 { + let bits: u64 = levels + .iter() + .filter(|&&l| l != 0) + .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros())) + .sum(); + if bits == 0 { + 1 + } else { + bits + 8 + } +} + +/// Transform-code the three components of a CTB against `pred`, +/// reconstructing through the decode-side path. Returns +/// `(levels, recon, ssd_total, rate)`. +fn code_ctb_residual( + pred: &InterPrediction, + src: &[Vec; 3], + qp_y: u32, + qp_c: u32, +) -> ([Vec; 3], [Vec; 3], u64, u64) { + let (ly, ry) = code_tb( + &src[0], + &pred.luma, + CTB, + qp_y, + Component::Luma, + PredMode::Inter, + ); + let (lcb, rcb) = code_tb(&src[1], &pred.cb, 8, qp_c, Component::Cb, PredMode::Inter); + let (lcr, rcr) = code_tb(&src[2], &pred.cr, 8, qp_c, Component::Cr, PredMode::Inter); + let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]); + let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr); + ([ly, lcb, lcr], [ry, rcb, rcr], dist, rate) +} + +/// The prediction-only reconstruction (clip to 8-bit) and its SSD. +fn pred_recon(pred: &InterPrediction, src: &[Vec; 3]) -> ([Vec; 3], u64) { + let clip = |v: &Vec| -> Vec { v.iter().map(|&p| p.clamp(0, 255) as u8).collect() }; + let recon = [clip(&pred.luma), clip(&pred.cb), clip(&pred.cr)]; + let dist = ssd(&recon[0], &src[0]) + ssd(&recon[1], &src[1]) + ssd(&recon[2], &src[2]); + (recon, dist) +} + +/// Greedy integer-pel motion search on luma SAD: seeds, then a +/// small-diamond descent (capped). Returns the best full-pel MV in +/// luma samples. +#[allow(clippy::too_many_arguments)] +fn integer_me( + refp: &RefPlanes, + src_y: &[i32], + x0: usize, + y0: usize, + w: usize, + h: usize, + seeds: &[[i32; 2]], + lambda_me: u64, + mvp_q: &[Mv], +) -> [i32; 2] { + // Full-pel prediction == direct (clamped) reference samples. + let sad_at = |mx: i32, my: i32| -> u64 { + let mut acc = 0u64; + for j in 0..h { + for i in 0..w { + let rx = (x0 as i32 + i as i32 + mx).clamp(0, refp.width as i32 - 1); + let ry = (y0 as i32 + j as i32 + my).clamp(0, refp.height as i32 - 1); + let r = refp.y[ry as usize * refp.width + rx as usize]; + acc += u64::from(r.abs_diff(src_y[j * w + i])); + } + } + acc + }; + // Motion-cost proxy at full-pel: cheapest mvd against either MVP. + let mv_cost = |mx: i32, my: i32| -> u64 { + mvp_q + .iter() + .map(|p| mvd_bits([mx * 4 - p[0], my * 4 - p[1]])) + .min() + .unwrap_or(0) + * lambda_me + }; + let mut best = seeds[0]; + let mut best_cost = u64::MAX; + for &s in seeds { + let c = sad_at(s[0], s[1]) + mv_cost(s[0], s[1]); + if c < best_cost { + best_cost = c; + best = s; + } + } + for _ in 0..ME_MAX_STEPS { + let mut improved = false; + for (dx, dy) in [(1, 0), (-1, 0), (0, 1), (0, -1)] { + let (mx, my) = (best[0] + dx, best[1] + dy); + let c = sad_at(mx, my) + mv_cost(mx, my); + if c < best_cost { + best_cost = c; + best = [mx, my]; + improved = true; + } + } + if !improved { + break; + } + } + best +} + +/// Half- then quarter-pel refinement around `best` (quarter-pel +/// units), scoring with the real §8.5.3.3.3 interpolation. +#[allow(clippy::too_many_arguments)] +fn fractional_me( + refp: &RefPlanes, + src_y: &[i32], + x0: usize, + y0: usize, + w: usize, + h: usize, + start: Mv, + lambda_me: u64, + mvp_q: &[Mv], +) -> Mv { + let cost_at = |mv: Mv| -> u64 { + let one = std::slice::from_ref(refp); + let pred = predict_block(one, one, x0, y0, w, h, &uni_l0(mv), false); + let mv_rate = mvp_q + .iter() + .map(|p| mvd_bits([mv[0] - p[0], mv[1] - p[1]])) + .min() + .unwrap_or(0); + sad(&pred.luma, src_y) + lambda_me * mv_rate + }; + let mut best = start; + let mut best_cost = cost_at(best); + for step in [2i32, 1] { + let mut improved = true; + while improved { + improved = false; + for (dx, dy) in [ + (step, 0), + (-step, 0), + (0, step), + (0, -step), + (step, step), + (step, -step), + (-step, step), + (-step, -step), + ] { + let mv = [best[0] + dx, best[1] + dy]; + let c = cost_at(mv); + if c < best_cost { + best_cost = c; + best = mv; + improved = true; + } + } + } + } + best +} + +/// Inputs shared by every per-PU decision of one slice. +struct PuChooseCtx<'a> { + refs_l0: &'a [RefPlanes], + refs_l1: &'a [RefPlanes], + mv_ctx: &'a PuMvContext<'a>, + lambda_me: u64, + b_slice: bool, + /// B slice whose two reference lists differ (hierarchical B): the + /// AMVP election searches L1 and the bi combination too. A + /// low-delay B (both lists the same pictures) keeps the L0-only + /// search — L1 would duplicate it bin for bin at a higher rate. + two_sided: bool, +} + +/// Choose merge-vs-AMVP for one prediction unit against `field` (the +/// motion state the decoder will have when resolving this PU), by +/// luma SAD + λ·signalling-bins. Returns the syntax, the resolved +/// motion, and the motion-rate proxy. +fn choose_pu( + field: &MotionField, + geom: &PuGeometry, + available: &dyn Fn(i32, i32) -> bool, + src_y: &[i32], + ctx: &PuChooseCtx<'_>, +) -> (PuSyntax, PuMotion, u64) { + let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h); + // ---- merge candidates (§8.5.3.2.2) ---- + let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE); + for idx in 0..MAX_MERGE { + let m = resolve_pu_motion(field, geom, &merge_pu(idx), ctx.mv_ctx, available); + // A later duplicate can never beat the earlier index. + if !merge_cands.iter().any(|(_, prev)| *prev == m) { + merge_cands.push((idx, m)); + } + } + let (merge_cost, merge_idx, merge_motion) = merge_cands + .iter() + .map(|&(idx, m)| { + let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &m, false); + ( + sad(&pred.luma, src_y) + ctx.lambda_me * (idx as u64 + 2), + idx, + m, + ) + }) + .min_by_key(|&(cost, idx, _)| (cost, idx)) + .expect("merge list is never empty"); + + let (amvp_syntax, amvp_motion, best_amvp_rate, best_amvp_cost) = + amvp_search(field, geom, available, src_y, ctx, &merge_cands); + + if merge_cost <= best_amvp_cost { + ( + PuSyntax::Merge { merge_idx }, + merge_motion, + merge_idx as u64 + 2, + ) + } else { + (amvp_syntax, amvp_motion, best_amvp_rate) + } +} + +/// §8.5.3.2.6 + motion estimation over every active reference of ONE +/// list: the SAD + λ·bins-best single-list AMVP signalling for one +/// PU. Returns the group, the resolved motion, the rate proxy and the +/// search cost; `None` when the list has no active reference. +#[allow(clippy::too_many_arguments)] +fn amvp_search_list( + field: &MotionField, + geom: &PuGeometry, + available: &dyn Fn(i32, i32) -> bool, + src_y: &[i32], + ctx: &PuChooseCtx<'_>, + merge_cands: &[(usize, PuMotion)], + list: usize, +) -> Option<(AmvpGroup, PuMotion, u64, u64)> { + let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h); + let refs = if list == 0 { ctx.refs_l0 } else { ctx.refs_l1 }; + let mv_of = |m: &PuMotion| if list == 0 { m.mv_l0 } else { m.mv_l1 }; + let mut best: Option<(AmvpGroup, PuMotion, u64, u64)> = None; + for (r, refp) in refs.iter().enumerate() { + let mvp = [ + mv_of(&resolve_pu_motion( + field, + geom, + &amvp_pu_list(list, r as u8, [0, 0], 0), + ctx.mv_ctx, + available, + )), + mv_of(&resolve_pu_motion( + field, + geom, + &amvp_pu_list(list, r as u8, [0, 0], 1), + ctx.mv_ctx, + available, + )), + ]; + let mut seeds: Vec<[i32; 2]> = vec![[0, 0]]; + for p in &mvp { + seeds.push([p[0] >> 2, p[1] >> 2]); + } + for (_, m) in merge_cands { + let mv = mv_of(m); + seeds.push([mv[0] >> 2, mv[1] >> 2]); + } + seeds.dedup(); + let int_mv = integer_me(refp, src_y, x, y, w, h, &seeds, ctx.lambda_me, &mvp); + let me_mv = fractional_me( + refp, + src_y, + x, + y, + w, + h, + [int_mv[0] * 4, int_mv[1] * 4], + ctx.lambda_me, + &mvp, + ); + // Choose the cheaper predictor for the found MV. + let (mvp_flag, mvd) = (0u8..2) + .map(|f| { + let p = mvp[f as usize]; + (f, [me_mv[0] - p[0], me_mv[1] - p[1]]) + }) + .min_by_key(|&(_, d)| mvd_bits(d)) + .expect("two predictors"); + // Resolve through the decoder's derivation (mv wrap etc.). + let motion = resolve_pu_motion( + field, + geom, + &amvp_pu_list(list, r as u8, mvd, mvp_flag), + ctx.mv_ctx, + available, + ); + // merge_flag + mvp_flag + ref_idx bin (2 refs) + idc (B) + mvd. + let rate = 2 + mvd_bits(mvd) + u64::from(refs.len() > 1) + u64::from(ctx.b_slice) * 2; + let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false); + let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate; + let improved = match &best { + None => true, + Some((_, _, _, c)) => cost < *c, + }; + if improved { + let group = AmvpGroup { + ref_idx: r as u8, + mvd, + mvp_flag, + }; + best = Some((group, motion, rate, cost)); + } + } + best +} + +/// The full AMVP election for one PU: the best single-list search on +/// L0 — and, on a two-sided B slice, on L1 plus the bi-predictive +/// combination of the two winners. Returns the syntax, the resolved +/// motion, the rate proxy and the search cost. +fn amvp_search( + field: &MotionField, + geom: &PuGeometry, + available: &dyn Fn(i32, i32) -> bool, + src_y: &[i32], + ctx: &PuChooseCtx<'_>, + merge_cands: &[(usize, PuMotion)], +) -> (PuSyntax, PuMotion, u64, u64) { + let (x, y, w, h) = (geom.x_pb, geom.y_pb, geom.n_pb_w, geom.n_pb_h); + let l0 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 0); + if !ctx.two_sided { + let (g, motion, rate, cost) = l0.expect("at least one L0 reference"); + return ( + PuSyntax::Amvp { + l0: Some(g), + l1: None, + }, + motion, + rate, + cost, + ); + } + let l1 = amvp_search_list(field, geom, available, src_y, ctx, merge_cands, 1); + let mut cands: Vec<(PuSyntax, PuMotion, u64, u64)> = Vec::with_capacity(3); + if let Some((g, motion, rate, cost)) = l0 { + cands.push(( + PuSyntax::Amvp { + l0: Some(g), + l1: None, + }, + motion, + rate, + cost, + )); + } + if let Some((g, motion, rate, cost)) = l1 { + cands.push(( + PuSyntax::Amvp { + l0: None, + l1: Some(g), + }, + motion, + rate, + cost, + )); + } + if let (Some((g0, _, _, _)), Some((g1, _, _, _))) = (&l0, &l1) { + // Bi combination of the two single-list winners: the AMVP + // predictor derivation of each list is independent of the + // other, so the resolved per-list MVs match the uni winners. + let motion = resolve_pu_motion( + field, + geom, + &amvp_pu(Some(*g0), Some(*g1)), + ctx.mv_ctx, + available, + ); + // merge_flag + inter_pred_idc ("1") + per-list mvd/mvp/ref bins. + let rate = 2 + + (mvd_bits(g0.mvd) + 1 + u64::from(ctx.refs_l0.len() > 1)) + + (mvd_bits(g1.mvd) + 1 + u64::from(ctx.refs_l1.len() > 1)); + let pred = predict_block(ctx.refs_l0, ctx.refs_l1, x, y, w, h, &motion, false); + let cost = sad(&pred.luma, src_y) + ctx.lambda_me * rate; + cands.push(( + PuSyntax::Amvp { + l0: Some(*g0), + l1: Some(*g1), + }, + motion, + rate, + cost, + )); + } + cands + .into_iter() + .min_by_key(|&(_, _, _, cost)| cost) + .expect("at least one active reference across the lists") +} + +/// Encode `merge_idx` (§9.3.3.10 TR with `cMax = MaxNumMergeCand − 1`: +/// bin 0 context-coded, the rest bypass). +fn encode_merge_idx( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + idx: usize, +) { + let c_max = MAX_MERGE - 1; + cabac.encode_decision(w, &mut ctxs.merge_idx[0], u8::from(idx > 0)); + if idx > 0 { + for _ in 1..idx { + cabac.encode_bypass(w, 1); + } + if idx < c_max { + cabac.encode_bypass(w, 0); + } + } +} + +/// §9.3.3.3 — encode an EGk-coded value (the dual of the decoder's +/// `read_eg_k_with`): a run of `1` prefix bins, a `0`, then +/// `prefix_ones + k` MSB-first suffix bins. +fn encode_eg_k(w: &mut BitWriter, cabac: &mut CabacEncoder, value: u32, k: u32) { + let mut prefix_ones = 0u32; + while ((1u64 << (prefix_ones + 1)) - 1) << k <= u64::from(value) { + prefix_ones += 1; + } + for _ in 0..prefix_ones { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + let base = ((1u64 << prefix_ones) - 1) << k; + let suffix = (u64::from(value) - base) as u32; + cabac.encode_bypass_bits(w, suffix, (prefix_ones + k) as u8); +} + +/// §7.3.8.9 `mvd_coding( )` — the interleaved bin order the decoder's +/// `decode_mvd_pair` reads: both `abs_mvd_greater0_flag`s, both +/// `abs_mvd_greater1_flag`s, then per component the EG1 +/// `abs_mvd_minus2` escape and `mvd_sign_flag`. +fn encode_mvd_pair(w: &mut BitWriter, cabac: &mut CabacEncoder, ctxs: &mut SliceContexts, mvd: Mv) { + let g0 = [mvd[0] != 0, mvd[1] != 0]; + for &g in &g0 { + cabac.encode_decision(w, &mut ctxs.abs_mvd_greater0_flag[0], u8::from(g)); + } + for (&g, &v) in g0.iter().zip(mvd.iter()) { + if g { + cabac.encode_decision( + w, + &mut ctxs.abs_mvd_greater1_flag[0], + u8::from(v.unsigned_abs() > 1), + ); + } + } + for (&g, &v) in g0.iter().zip(mvd.iter()) { + if g { + let a = v.unsigned_abs(); + if a > 1 { + encode_eg_k(w, cabac, a - 2, 1); + } + cabac.encode_bypass(w, u8::from(v < 0)); + } + } +} + +/// §7.3.8.6 — emit one prediction unit's syntax (merge_flag + +/// merge_idx, or the AMVP groups). On B slices `inter_pred_idc` is +/// coded per Table 9-47 (`PRED_BI` = "1", `PRED_L0` = "00", `PRED_L1` +/// = "01"; bin 0 ctxInc = CtDepth = 0, bin 1 ctxInc = 4 — `nPbW + +/// nPbH != 12` for every PU shape this encoder emits). Each used +/// list codes `ref_idx_lX` (a single context bin — at most two active +/// references per list), `mvd_coding` (`mvd_l1_zero_flag == 0`) and +/// `mvp_lX_flag`. +fn encode_pu_syntax( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + pu: &PuSyntax, + b_slice: bool, + n_l0: usize, + n_l1: usize, +) { + match pu { + PuSyntax::Merge { merge_idx } => { + cabac.encode_decision(w, &mut ctxs.merge_flag[0], 1); + encode_merge_idx(w, cabac, ctxs, *merge_idx); + } + PuSyntax::Amvp { l0, l1 } => { + cabac.encode_decision(w, &mut ctxs.merge_flag[0], 0); + if b_slice { + let (head, tail) = ctxs.inter_pred_idc.split_at_mut(4); + if l0.is_some() && l1.is_some() { + cabac.encode_decision(w, &mut head[0], 1); // PRED_BI + } else { + cabac.encode_decision(w, &mut head[0], 0); + cabac.encode_decision(w, &mut tail[0], u8::from(l1.is_some())); + } + } + for (group, n_active) in [(l0, n_l0), (l1, n_l1)] { + let Some(g) = group else { continue }; + if n_active > 1 { + // §9.3.3 TR cMax = num_ref_idx_lX_active_minus1 == + // 1: a single context-coded bin (ctxInc 0). + debug_assert!(n_active == 2, "at most two active references per list"); + cabac.encode_decision(w, &mut ctxs.ref_idx[0], g.ref_idx); + } + encode_mvd_pair(w, cabac, ctxs, g.mvd); + cabac.encode_decision(w, &mut ctxs.mvp_flag[0], g.mvp_flag); + } + } + } +} + +/// Encode one P / B frame as a single TRAIL_R slice against the +/// reference lists of `spec`: pass 1 makes the per-CTB mode decisions +/// and builds the pre-filter reconstruction, the §8.7 filter stage +/// elects and applies deblocking + SAO, pass 2 emits the slice header +/// and syntax. Returns the slice RBSP, the frame's (filtered) +/// reconstruction, and its CU mode-decision counters. +#[allow(clippy::too_many_lines)] +pub(crate) fn encode_inter_slice( + frame: &YuvFrame<'_>, + spec: &SliceSpec<'_>, + width: usize, + height: usize, +) -> (Vec, FrameRecon, FrameStats) { + let (poc, qp, b_slice, lf) = (spec.poc, spec.qp, spec.b_slice, spec.lf); + let (cw, ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let qp_y = qp as u32; + let qp_c = chroma_qp_420(qp); + // SSD-per-bit tradeoff, doubling every 3 QP (as the intra path); + // the SAD-domain motion-search λ uses the same scale. + let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3); + let lambda_me: u64 = lambda; + + let to_i32 = |p: &[u8]| -> Vec { p.iter().map(|&v| i32::from(v)).collect() }; + let to_planes = |list: &[(i32, &FrameRecon)]| -> Vec { + list.iter() + .map(|&(_, rec)| RefPlanes { + y: to_i32(&rec.y), + cb: to_i32(&rec.cb), + cr: to_i32(&rec.cr), + width, + height, + }) + .collect() + }; + let refs_l0: Vec = to_planes(&spec.l0); + let refs_l1: Vec = to_planes(&spec.l1); + let l0_pocs: Vec = spec.l0.iter().map(|&(p, _)| p).collect(); + let l1_pocs: Vec = spec.l1.iter().map(|&(p, _)| p).collect(); + let n_l0 = l0_pocs.len() as i32; + let n_l1 = l1_pocs.len() as i32; + // Hierarchical B: the two lists differ, so the AMVP election + // searches L1 / bi as well; a low-delay B keeps the L0-only + // search (L1 duplicates it at a higher signalling rate). + let two_sided = b_slice && l0_pocs != l1_pocs; + + let mut recon = FrameRecon { + y: vec![0u8; width * height], + cb: vec![0u8; cw * ch], + cr: vec![0u8; cw * ch], + }; + let mut field = MotionField::new(width, height); + // §8.4.2 luma-mode records for the intra-fallback MPM lists (an + // inter / skip CU records as "not intra" ⇒ candidate INTRA_DC). + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + // Per-CTB cu_skip_flag values (CU == CTB) for the §9.3.4.2.2 ctxInc. + let mut skip_grid = vec![false; ctbs_x * ctbs_y]; + let mut stats = FrameStats::default(); + + // §6.4.2 availability plumbing (single slice, single tile). + let tiling = PictureTiling::new( + ctbs_x as u32, + ctbs_y as u32, + width as u32, + height as u32, + CTB_LOG2, + 2, + &TilingParams::single_tile(), + ) + .expect("legal single-tile geometry"); + + // §8.5.3.2 reference resolvers over the spec's explicit lists. + let list_pocs = |list: usize| -> &Vec { + if list == 0 { + &l0_pocs + } else { + &l1_pocs + } + }; + let ref_poc = |list: usize, ref_idx: i32| -> i32 { + usize::try_from(ref_idx) + .ok() + .and_then(|i| list_pocs(list).get(i).copied()) + .unwrap_or(i32::MIN) + }; + // The decoder's motion-field cells store the REFERENCED + // picture's POC per used list (pu_mv fill: `ref_poc(list, idx)`); + // an unused list's value is ignored by `to_cell`. + let cell_pocs = + |m: &PuMotion| -> (i32, i32) { (ref_poc(0, m.ref_idx_l0), ref_poc(1, m.ref_idx_l1)) }; + let ref_long_term = |_list: usize, _ref_idx: i32| false; + let ref_short_term = |list: usize, ref_idx: i32| { + usize::try_from(ref_idx).is_ok_and(|i| i < list_pocs(list).len()) + }; + let col_ref_long_term = |_poc: i32| false; + // §8.5.3.2.2 NoBackwardPredFlag: 1 iff every active reference of + // both lists precedes the current picture in output order. + let no_backward_pred = !l0_pocs.iter().chain(l1_pocs.iter()).any(|&p| p > poc); + let mv_ctx = PuMvContext { + curr_poc: poc, + slice_is_b: b_slice, + ctb_log2_size_y: CTB_LOG2, + pic_width_luma: width as u32, + pic_height_luma: height as u32, + max_num_merge_cand: MAX_MERGE, + num_ref_idx_l0_active: n_l0, + num_ref_idx_l1_active: if b_slice { n_l1 } else { 0 }, + log2_par_mrg_level: 2, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + col_poc: 0, + no_backward_pred, + ref_poc: &ref_poc, + ref_long_term: &ref_long_term, + ref_short_term: &ref_short_term, + col_field: None, + col_ref_long_term: &col_ref_long_term, + use_integer_mv: false, + two_versions_curr_pic: false, + is_curr_pic: &|_, _| false, + }; + + // ---- pass 1: per-CTB mode decisions + reconstruction ---- + let mut plans: Vec = Vec::with_capacity(ctbs_x * ctbs_y); + // `ctb` also drives the x0/y0 arithmetic, not just the grid index. + #[allow(clippy::needless_range_loop)] + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let (cx0, cy0) = (x0 / 2, y0 / 2); + let src = [ + extract(frame.y, width, x0, y0, CTB), + extract(frame.cb, cw, cx0, cy0, 8), + extract(frame.cr, cw, cx0, cy0, 8), + ]; + + let geom = PuGeometry { + x_cb: x0, + y_cb: y0, + n_cb_s: CTB, + x_pb: x0, + y_pb: y0, + n_pb_w: CTB, + n_pb_h: CTB, + part_mode: PartMode::Part2Nx2N, + part_idx: 0, + }; + + let chosen = { + // §6.4.2 prediction-block availability against the + // in-progress motion field (identical to the decoder's + // closure in the picture-level inter driver). + let available = |x_nb: i32, y_nb: i32| -> bool { + tiling.prediction_block_availability( + x0 as u32, + y0 as u32, + CTB as u32, + x0 as u32, + y0 as u32, + CTB as u32, + CTB as u32, + 0, + x_nb, + y_nb, + |_ctb_rs| 0, + |x, y| { + if field.cell_at(x as usize, y as usize).is_intra { + MODE_INTRA + } else { + 0 + } + }, + ) + }; + + // ---- merge / skip candidates (§8.5.3.2.2) ---- + let mut merge_cands: Vec<(usize, PuMotion)> = Vec::with_capacity(MAX_MERGE); + for idx in 0..MAX_MERGE { + let m = resolve_pu_motion(&field, &geom, &merge_pu(idx), &mv_ctx, &available); + // A later duplicate can never beat the earlier index + // (same samples, more merge_idx bins). + if !merge_cands.iter().any(|(_, prev)| *prev == m) { + merge_cands.push((idx, m)); + } + } + let (best_merge_idx, best_merge_motion) = merge_cands + .iter() + .map(|&(idx, m)| { + let pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &m, false); + ( + sad(&pred.luma, &src[0]) + lambda_me * (idx as u64 + 1), + idx, + m, + ) + }) + .min_by_key(|&(cost, idx, _)| (cost, idx)) + .map(|(_, idx, m)| (idx, m)) + .expect("merge list is never empty"); + + // ---- AMVP: §8.5.3.2.6 predictors + per-reference ME ---- + let choose_ctx = PuChooseCtx { + refs_l0: &refs_l0, + refs_l1: &refs_l1, + mv_ctx: &mv_ctx, + lambda_me, + b_slice, + two_sided, + }; + let (amvp_syntax, amvp_motion, amvp_rate, _) = amvp_search( + &field, + &geom, + &available, + &src[0], + &choose_ctx, + &merge_cands, + ); + + // ---- fully code the finalists ---- + let mut cands: Vec = Vec::with_capacity(6); + + // Skip: best merge candidate, prediction only. + let merge_pred = predict_block( + &refs_l0, + &refs_l1, + x0, + y0, + CTB, + CTB, + &best_merge_motion, + true, + ); + let (skip_recon, skip_dist) = pred_recon(&merge_pred, &src); + cands.push(CuCandidate { + kind: CuKind::Skip { + merge_idx: best_merge_idx, + }, + motions: vec![best_merge_motion], + levels: None, + recon: skip_recon, + cost: skip_dist + lambda * (best_merge_idx as u64 + 2), + }); + + // Merge + residual (only legal when some level is nonzero: + // a 2Nx2N merge CU has rqt_root_cbf inferred 1). + let (m_levels, m_recon, m_dist, m_rate) = + code_ctb_residual(&merge_pred, &src, qp_y, qp_c); + if m_levels.iter().any(|l| l.iter().any(|&v| v != 0)) { + cands.push(CuCandidate { + kind: CuKind::Merge { + merge_idx: best_merge_idx, + }, + motions: vec![best_merge_motion], + levels: Some(CuLevels::Depth0(m_levels)), + recon: m_recon, + cost: m_dist + lambda * (m_rate + best_merge_idx as u64 + 3), + }); + } + + // AMVP (with or without residual). + let amvp_pred = predict_block(&refs_l0, &refs_l1, x0, y0, CTB, CTB, &amvp_motion, true); + let (a_levels, a_recon, a_dist, a_rate) = + code_ctb_residual(&amvp_pred, &src, qp_y, qp_c); + let motion_rate = amvp_rate + 2; // + skip / rqt flags + if a_levels.iter().any(|l| l.iter().any(|&v| v != 0)) { + cands.push(CuCandidate { + kind: CuKind::Amvp { pu: amvp_syntax }, + motions: vec![amvp_motion], + levels: Some(CuLevels::Depth0(a_levels)), + recon: a_recon, + cost: a_dist + lambda * (a_rate + motion_rate), + }); + } else { + // All-zero residual: rqt_root_cbf == 0. + let (pr, pd) = pred_recon(&amvp_pred, &src); + cands.push(CuCandidate { + kind: CuKind::Amvp { pu: amvp_syntax }, + motions: vec![amvp_motion], + levels: None, + recon: pr, + cost: pd + lambda * motion_rate, + }); + } + + // ---- two-PU partitions: the symmetric rectangles, plus + // the four asymmetric shapes on an AMP stream ---- + let mut two_pu_parts = vec![PartMode::Part2NxN, PartMode::PartNx2N]; + if spec.big_cu { + two_pu_parts.extend([ + PartMode::Part2NxnU, + PartMode::Part2NxnD, + PartMode::PartNLx2N, + PartMode::PartNRx2N, + ]); + } + for part in two_pu_parts { + let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part); + // The decoder resolves PU1 with PU0's motion already in + // the field (§8.5.3.2 order): stage the writes on a copy. + let mut tmp = field.clone(); + let mut pus = [PuSyntax::Merge { merge_idx: 0 }; 2]; + let mut motions_r = Vec::with_capacity(2); + let mut pred_y = vec![0i32; CTB * CTB]; + let mut pred_cb = vec![0i32; 64]; + let mut pred_cr = vec![0i32; 64]; + // pred_mode + part_mode bins (the AMP forms carry two + // extra part_mode bins). + let mut motion_rate_r = if part_is_amp(part) { 5u64 } else { 3u64 }; + for (k, r) in rects.iter().enumerate() { + let g = PuGeometry { + x_cb: x0, + y_cb: y0, + n_cb_s: CTB, + x_pb: r.x_pb, + y_pb: r.y_pb, + n_pb_w: r.n_pb_w, + n_pb_h: r.n_pb_h, + part_mode: part, + part_idx: k as u32, + }; + // §6.4.2 availability against the staged field. The + // decoder's closure passes the CU as the PU geometry + // (the sameCb NxN clause never fires for 2-PU + // shapes) and treats the current CU as MODE_INTER. + let avail_k = |x_nb: i32, y_nb: i32| -> bool { + tiling.prediction_block_availability( + x0 as u32, + y0 as u32, + CTB as u32, + x0 as u32, + y0 as u32, + CTB as u32, + CTB as u32, + 0, + x_nb, + y_nb, + |_ctb_rs| 0, + |x, y| { + let (xu, yu) = (x as usize, y as usize); + let inside_cu = + (x0..x0 + CTB).contains(&xu) && (y0..y0 + CTB).contains(&yu); + if !inside_cu && tmp.cell_at(xu, yu).is_intra { + MODE_INTRA + } else { + 0 + } + }, + ) + }; + let mut src_pu = Vec::with_capacity(r.n_pb_w * r.n_pb_h); + for j in 0..r.n_pb_h { + for i in 0..r.n_pb_w { + src_pu.push(i32::from(frame.y[(r.y_pb + j) * width + r.x_pb + i])); + } + } + let (pu_syntax, motion, rate_k) = + choose_pu(&tmp, &g, &avail_k, &src_pu, &choose_ctx); + // eqs 8-80..8-85: PU1's derivation sees PU0's motion. + tmp.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, { + let (p0, p1) = cell_pocs(&motion); + motion.to_cell(p0, p1) + }); + let p = predict_block( + &refs_l0, &refs_l1, r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, &motion, true, + ); + blit( + &mut pred_y, + CTB, + r.x_pb - x0, + r.y_pb - y0, + &p.luma, + r.n_pb_w, + r.n_pb_h, + ); + blit( + &mut pred_cb, + 8, + (r.x_pb - x0) / 2, + (r.y_pb - y0) / 2, + &p.cb, + r.n_pb_w / 2, + r.n_pb_h / 2, + ); + blit( + &mut pred_cr, + 8, + (r.x_pb - x0) / 2, + (r.y_pb - y0) / 2, + &p.cr, + r.n_pb_w / 2, + r.n_pb_h / 2, + ); + pus[k] = pu_syntax; + motions_r.push(motion); + motion_rate_r += rate_k; + } + // §7.4.9.8 interSplitFlag: forced depth-1 tree — four + // z-order 8x8 luma + 4x4 chroma TBs. + let mut luma_l: [Vec; 4] = Default::default(); + let mut cb_l: [Vec; 4] = Default::default(); + let mut cr_l: [Vec; 4] = Default::default(); + let mut recon_r = [vec![0u8; CTB * CTB], vec![0u8; 64], vec![0u8; 64]]; + let mut rate_r = 0u64; + for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() { + let (lx, ly8) = (zx * 8, zy * 8); + let s_y = sub_block(&src[0], CTB, lx, ly8, 8); + let p_y = sub_block(&pred_y, CTB, lx, ly8, 8); + let (lv, rc) = code_tb(&s_y, &p_y, 8, qp_y, Component::Luma, PredMode::Inter); + for j in 0..8 { + recon_r[0][(ly8 + j) * CTB + lx..(ly8 + j) * CTB + lx + 8] + .copy_from_slice(&rc[j * 8..(j + 1) * 8]); + } + rate_r += levels_rate(&lv); + luma_l[k] = lv; + for (plane, src_c, pred_c, out) in [ + (1usize, &src[1], &pred_cb, &mut cb_l), + (2usize, &src[2], &pred_cr, &mut cr_l), + ] { + let s_c = sub_block(src_c, 8, zx * 4, zy * 4, 4); + let p_c = sub_block(pred_c, 8, zx * 4, zy * 4, 4); + let comp = if plane == 1 { + Component::Cb + } else { + Component::Cr + }; + let (lv_c, rc_c) = code_tb(&s_c, &p_c, 4, qp_c, comp, PredMode::Inter); + for j in 0..4 { + recon_r[plane] + [(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4] + .copy_from_slice(&rc_c[j * 4..(j + 1) * 4]); + } + rate_r += levels_rate(&lv_c); + out[k] = lv_c; + } + } + let any_nonzero = luma_l + .iter() + .chain(cb_l.iter()) + .chain(cr_l.iter()) + .any(|l| l.iter().any(|&v| v != 0)); + let (levels_r, recon_final, dist_r) = if any_nonzero { + let d = ssd(&recon_r[0], &src[0]) + + ssd(&recon_r[1], &src[1]) + + ssd(&recon_r[2], &src[2]); + ( + Some(CuLevels::Depth1(Box::new(Depth1Levels { + luma: luma_l, + cb: cb_l, + cr: cr_l, + }))), + recon_r, + d + lambda * rate_r, + ) + } else { + // rqt_root_cbf == 0: prediction-only reconstruction. + let clip = |v: &[i32]| -> Vec { + v.iter().map(|&p| p.clamp(0, 255) as u8).collect() + }; + let rec = [clip(&pred_y), clip(&pred_cb), clip(&pred_cr)]; + let d = ssd(&rec[0], &src[0]) + ssd(&rec[1], &src[1]) + ssd(&rec[2], &src[2]); + (None, rec, d) + }; + cands.push(CuCandidate { + kind: CuKind::TwoPu { part, pus }, + motions: motions_r, + levels: levels_r, + recon: recon_final, + cost: dist_r + lambda * (motion_rate_r + 1), + }); + } + + // ---- intra 2Nx2N fallback (§8.4 against our own recon) ---- + { + let read_y = |x: usize, yy: usize| i32::from(recon.y[yy * width + x]); + let avail_y = + |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read_y, &avail_y, x0, y0, CTB); + let (mode, pred_y) = search_best_mode(&marked, &src[0]); + let (ly, ry) = code_tb( + &src[0], + &pred_y, + CTB, + qp_y, + Component::Luma, + PredMode::Intra, + ); + let code_c = |plane: &[u8], comp: Component, pc: PredComponent| { + let read = |x: usize, yy: usize| i32::from(plane[yy * cw + x]); + let avail = + |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0); + let marked_c = gather_refs(&read, &avail, cx0, cy0, 8); + let pred = intra_predict_with_substitution(&marked_c, &pred_params(mode, pc)) + .expect("legal prediction params"); + let src_c = match comp { + Component::Cb => &src[1], + _ => &src[2], + }; + code_tb(src_c, &pred, 8, qp_c, comp, PredMode::Intra) + }; + let (lcb, rcb) = code_c(&recon.cb, Component::Cb, PredComponent::Cb); + let (lcr, rcr) = code_c(&recon.cr, Component::Cr, PredComponent::Cr); + let dist = ssd(&ry, &src[0]) + ssd(&rcb, &src[1]) + ssd(&rcr, &src[2]); + let rate = levels_rate(&ly) + levels_rate(&lcb) + levels_rate(&lcr) + 8; + cands.push(CuCandidate { + kind: CuKind::Intra { mode }, + motions: Vec::new(), + levels: Some(CuLevels::Depth0([ly, lcb, lcr])), + recon: [ry, rcb, rcr], + cost: dist + lambda * rate, + }); + } + + cands + .into_iter() + .min_by_key(|c| c.cost) + .expect("at least the skip candidate") + }; + + // ---- state update (eqs 8-80..8-85 + mode fields + recon) ---- + let is_skip = matches!(chosen.kind, CuKind::Skip { .. }); + skip_grid[ctb] = is_skip; + match &chosen.kind { + CuKind::Intra { mode } => { + stats.intra += 1; + // The decoder stamps intra CUs into the motion field so + // a later CU's §6.4.2 availability denies them. + field.fill_rect( + x0, + y0, + CTB, + CTB, + MotionCell { + is_intra: true, + ..MotionCell::default() + }, + ); + modes.record_intra_pb(x0, y0, CTB, *mode, false); + } + kind => { + match kind { + CuKind::Skip { .. } => stats.skip += 1, + CuKind::Merge { .. } => stats.merge += 1, + CuKind::TwoPu { part, pus } => { + if pus.iter().any(|p| matches!(p, PuSyntax::Amvp { .. })) { + stats.amvp += 1; + } else { + stats.merge += 1; + } + if part_is_amp(*part) { + stats.amp += 1; + } else { + stats.rect += 1; + } + } + _ => stats.amvp += 1, + } + if chosen + .motions + .iter() + .any(|m| m.pred_flag_l0 && m.pred_flag_l1) + { + stats.bi += 1; + } + if chosen.motions.iter().any(|m| { + (m.pred_flag_l0 && m.ref_idx_l0 > 0) || (m.pred_flag_l1 && m.ref_idx_l1 > 0) + }) { + stats.ref1 += 1; + } + // eqs 8-80..8-85: one motion cell per PU rectangle, the + // stored identity being the referenced picture's POC. + let part = match kind { + CuKind::TwoPu { part, .. } => *part, + _ => PartMode::Part2Nx2N, + }; + let rects = crate::pu_mv::pu_partitions(x0, y0, CTB, part); + for (r, m) in rects.iter().zip(chosen.motions.iter()) { + field.fill_rect(r.x_pb, r.y_pb, r.n_pb_w, r.n_pb_h, { + let (p0, p1) = cell_pocs(m); + m.to_cell(p0, p1) + }); + } + let cu_mode = if is_skip { + CuPredMode::Skip + } else { + CuPredMode::Inter + }; + modes.record_non_intra_cu(x0, y0, CTB, cu_mode); + // §8.7.2.4 — mark each luma TRANSFORM BLOCK carrying a + // coded coefficient (the decoder marks per tree leaf, + // not per CU; intra CUs are never marked — their edges + // are bS 2 regardless). + match &chosen.levels { + Some(CuLevels::Depth0(l)) if l[0].iter().any(|&v| v != 0) => { + field.mark_nonzero_coeff(x0, y0, CTB, CTB); + } + Some(CuLevels::Depth1(d)) => { + for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() { + if d.luma[k].iter().any(|&v| v != 0) { + field.mark_nonzero_coeff(x0 + zx * 8, y0 + zy * 8, 8, 8); + } + } + } + _ => {} + } + } + } + store(&mut recon.y, width, x0, y0, CTB, &chosen.recon[0]); + store(&mut recon.cb, cw, cx0, cy0, 8, &chosen.recon[1]); + store(&mut recon.cr, cw, cx0, cy0, 8, &chosen.recon[2]); + plans.push(chosen); + } + + // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ---- + let mut lf_sig = SliceLfSignalling { + cfg: lf, + deblock_on: false, + beta_offset_div2: 0, + tc_offset_div2: 0, + sao_luma: false, + sao_chroma: false, + }; + let mut sao_ctbs: Vec = Vec::new(); + if lf.any() { + let shapes: Vec = plans + .iter() + .map(|c| CtbShape { + part_mode: match &c.kind { + CuKind::TwoPu { part, .. } => bin_part_mode(*part), + _ => crate::binarization::PartMode::Part2Nx2N, + }, + split_depth1: matches!(c.levels, Some(CuLevels::Depth1(_))), + }) + .collect(); + let out = filter_frame( + &FilterInput { + width, + height, + qp, + lambda, + recon: [&recon.y, &recon.cb, &recon.cr], + src: [frame.y, frame.cb, frame.cr], + field: &field, + shapes: &shapes, + }, + lf, + ); + lf_sig.deblock_on = out.deblock_on; + lf_sig.beta_offset_div2 = out.beta_offset_div2; + lf_sig.tc_offset_div2 = out.tc_offset_div2; + lf_sig.sao_luma = out.slice_sao_luma; + lf_sig.sao_chroma = out.slice_sao_chroma; + sao_ctbs = out.sao_ctbs; + recon.y = out.y; + recon.cb = out.cb; + recon.cr = out.cr; + } + + // ---- slice_segment_header( ) ---- + let mut w = BitWriter::new(); + write_inter_slice_header(&mut w, spec, &lf_sig); + + // ---- slice_segment_data( ) — pass 2: syntax emission ---- + let mut cabac = CabacEncoder::new(); + // Table 9-4: cabac_init_flag 0 ⇒ initType 1 (P) / 2 (B). + let raw_slice_type = if b_slice { 0 } else { 1 }; + let mut ctxs = SliceContexts::init(init_type(raw_slice_type, false), qp); + for (ctb, chosen) in plans.iter().enumerate() { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + if lf_sig.sao_luma || lf_sig.sao_chroma { + // §7.3.8.3 sao( rx, ry ) ahead of the coding quadtree. + encode_sao_ctb( + &mut w, + &mut cabac, + &mut ctxs, + &sao_ctbs[ctb], + ctb % ctbs_x, + ctb / ctbs_x, + lf_sig.sao_luma, + lf_sig.sao_chroma, + ); + } + + if spec.big_cu { + // §7.3.8.4: log2CbSize (4) > MinCbLog2SizeY (3) — + // split_cu_flag is coded and 0 (one unsplit 16x16 CU per + // CTB; all CtDepth 0 ⇒ both §9.3.4.2.2 conds 0 ⇒ ctxInc 0). + cabac.encode_decision(&mut w, &mut ctxs.split_cu_flag[0], 0); + } + + // ---- emit the §7.3.8.5 coding_unit( ) syntax ---- + let is_skip = matches!(chosen.kind, CuKind::Skip { .. }); + { + // cu_skip_flag with the §9.3.4.2.2 left/above ctxInc (CU == + // CTB: the neighbour is the raster-preceding CTB, available + // iff in-picture — single slice, single tile). + let (l_avail, l_skip) = if x0 > 0 { + (true, skip_grid[ctb - 1]) + } else { + (false, false) + }; + let (a_avail, a_skip) = if y0 > 0 { + (true, skip_grid[ctb - ctbs_x]) + } else { + (false, false) + }; + let inc = cu_skip_flag_ctx_inc(u8::from(l_skip), l_avail, u8::from(a_skip), a_avail); + cabac.encode_decision( + &mut w, + &mut ctxs.cu_skip_flag[inc as usize], + u8::from(is_skip), + ); + } + + match &chosen.kind { + CuKind::Skip { merge_idx } => { + encode_merge_idx(&mut w, &mut cabac, &mut ctxs, *merge_idx); + } + CuKind::Merge { merge_idx } => { + // pred_mode_flag = 0 (MODE_INTER), part_mode "1" (2Nx2N). + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); + encode_pu_syntax( + &mut w, + &mut cabac, + &mut ctxs, + &PuSyntax::Merge { + merge_idx: *merge_idx, + }, + b_slice, + n_l0 as usize, + n_l1 as usize, + ); + // rqt_root_cbf not present (2Nx2N merge ⇒ inferred 1). + } + CuKind::Amvp { pu } => { + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); + encode_pu_syntax( + &mut w, + &mut cabac, + &mut ctxs, + pu, + b_slice, + n_l0 as usize, + n_l1 as usize, + ); + cabac.encode_decision( + &mut w, + &mut ctxs.rqt_root_cbf[0], + u8::from(chosen.levels.is_some()), + ); + } + CuKind::TwoPu { part, pus } => { + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); + // §9.3.3.7 inter part_mode (bin 0 ctx 0, bin 1 ctx 1): + // * at MinCb (log2CbSize == MinCbLog2SizeY > 3): + // "01" = PART_2NxN, "001" = PART_Nx2N (bin 2 the + // MinCb ctx slot 2); + // * above MinCb with amp_enabled_flag: "011" = + // PART_2NxN, "001" = PART_Nx2N (bin 2 = 1 selects + // the symmetric form, ctx slot 3), and the AMP + // forms "0100" = PART_2NxnU, "0101" = PART_2NxnD, + // "0000" = PART_nLx2N, "0001" = PART_nRx2N (bin 2 = + // 0, bin 3 bypass picking the second-quarter side). + let horizontal = part_is_horizontal(*part); + let amp_shape = part_is_amp(*part); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 0); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[1], u8::from(horizontal)); + if spec.big_cu { + cabac.encode_decision(&mut w, &mut ctxs.part_mode[3], u8::from(!amp_shape)); + if amp_shape { + let second = matches!(part, PartMode::Part2NxnD | PartMode::PartNRx2N); + cabac.encode_bypass(&mut w, u8::from(second)); + } + } else if !horizontal { + cabac.encode_decision(&mut w, &mut ctxs.part_mode[2], 1); + } + for pu in pus { + encode_pu_syntax( + &mut w, + &mut cabac, + &mut ctxs, + pu, + b_slice, + n_l0 as usize, + n_l1 as usize, + ); + } + // rqt_root_cbf: present (PartMode != PART_2Nx2N). + cabac.encode_decision( + &mut w, + &mut ctxs.rqt_root_cbf[0], + u8::from(chosen.levels.is_some()), + ); + } + CuKind::Intra { mode } => { + // pred_mode_flag = 1 (MODE_INTRA), part_mode "1" + // (2Nx2N) at MinCb — NOT present above MinCb + // (§7.3.8.5, inferred PART_2Nx2N); PCM disabled in + // the SPS. + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 1); + if !spec.big_cu { + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); + } + // §7.3.8.5 luma-mode group (single PB): the §8.4.2 + // candidate list against the recorded neighbour modes + // (inter / skip neighbours contribute INTRA_DC), with + // the §6.4.1 z-scan availability. + let avail_l = + zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0); + let avail_a = + zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0); + let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + match list.iter().position(|&m| m == *mode) { + Some(k) => { + cabac.encode_decision(&mut w, &mut ctxs.prev_intra_luma_pred_flag[0], 1); + // mpm_idx: TR cMax 2, all bypass. + match k { + 0 => cabac.encode_bypass(&mut w, 0), + 1 => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 0); + } + _ => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 1); + } + } + } + None => { + cabac.encode_decision(&mut w, &mut ctxs.prev_intra_luma_pred_flag[0], 0); + // §8.4.2: rem = mode minus each smaller candidate. + let mut rem = u32::from(*mode); + for &c in &list { + if u32::from(*mode) > u32::from(c) { + rem -= 1; + } + } + cabac.encode_bypass_bits(&mut w, rem, 5); // FL cMax 31 + } + } + // intra_chroma_pred_mode = 4 (derived from luma). + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); + } + } + + // ---- §7.3.8.8 transform_tree + §7.3.8.10 transform_unit ---- + let cu_is_intra = matches!(chosen.kind, CuKind::Intra { .. }); + // §7.4.9.11: inter TBs use the up-right diagonal scan; the + // TB geometries the intra fallback emits are not + // mode-dependent-scan eligible so they come back diagonal + // through the same derivation. + let intra_mode = match &chosen.kind { + CuKind::Intra { mode } => u32::from(*mode), + _ => 0, + }; + let rc_params = |log2: u32, c_idx: u8| ResidualCodingParams { + log2_trafo_size: log2, + is_chroma: c_idx != 0, + scan_idx: residual_coding_scan_idx(cu_is_intra, log2, c_idx, 1, intra_mode), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + match &chosen.levels { + Some(CuLevels::Depth0(levels)) => { + // Depth-0 16x16 TU (split_transform_flag not present, + // inferred 0: 2Nx2N at MaxTrafoDepth 0). + let cbf_cb = levels[1].iter().any(|&v| v != 0); + let cbf_cr = levels[2].iter().any(|&v| v != 0); + let cbf_luma = levels[0].iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr), + ); + // §7.3.8.8: an intra CU always signals cbf_luma; an + // inter depth-0 TU signals it only when a chroma cbf is + // set (otherwise it is inferred 1). + if cu_is_intra || cbf_cb || cbf_cr { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + } else { + debug_assert!(cbf_luma, "all-zero transform tree must not be coded"); + } + if cbf_luma { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(4, 0), + &levels[0], + ) + .expect("validated luma levels"); + } + if cbf_cb { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, 1), + &levels[1], + ) + .expect("validated cb levels"); + } + if cbf_cr { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, 2), + &levels[2], + ) + .expect("validated cr levels"); + } + } + Some(CuLevels::Depth1(d)) => { + let Depth1Levels { luma, cb, cr } = d.as_ref(); + // §7.4.9.8 interSplitFlag == 1: split_transform_flag + // inferred 1 at depth 0; four 8x8 leaves at depth 1. + // Root cbf_cb / cbf_cr gate the per-leaf chroma flags + // (§7.3.8.8 inheritance); cbf_luma is signalled at + // every depth-1 leaf (trafoDepth != 0). + let leaf_nz = |lv: &Vec| lv.iter().any(|&v| v != 0); + let root_cb = cb.iter().any(&leaf_nz); + let root_cr = cr.iter().any(&leaf_nz); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(root_cb), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(root_cr), + ); + for k in 0..4 { + let cbf_cb_k = leaf_nz(&cb[k]); + let cbf_cr_k = leaf_nz(&cr[k]); + let cbf_luma_k = leaf_nz(&luma[k]); + if root_cb { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(1) as usize], + u8::from(cbf_cb_k), + ); + } + if root_cr { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(1) as usize], + u8::from(cbf_cr_k), + ); + } + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(1) as usize], + u8::from(cbf_luma_k), + ); + if cbf_luma_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, 0), + &luma[k], + ) + .expect("validated luma levels"); + } + if root_cb && cbf_cb_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(2, 1), + &cb[k], + ) + .expect("validated cb levels"); + } + if root_cr && cbf_cr_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(2, 2), + &cr[k], + ) + .expect("validated cr levels"); + } + } + } + None => {} + } + + // end_of_slice_segment_flag. + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + (w.finish(), recon, stats) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::encoder::intra::encode_idr_intra_au_cfg; + use crate::sequence::decode_annexb_sequence; + + /// A deterministic scene: a textured background with a moving + /// bright square (sub-pel-friendly gradients) — motion vectors and + /// residuals both get exercised. + fn scene(w: usize, h: usize, n_frames: usize) -> Vec<(Vec, Vec, Vec)> { + (0..n_frames) + .map(|t| { + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + let base = (x * 2 + yy * 3) % 200; + // A 12x12 square moving 3 px right / 1 px down + // per frame. + let (sx, sy) = (4 + t * 3, 6 + t); + let inside = x >= sx && x < sx + 12 && yy >= sy && yy < sy + 12; + if inside { + (base + 55) as u8 + } else { + base as u8 + } + }) + .collect(); + let cb: Vec = (0..w * h / 4) + .map(|i| (100 + (i % (w / 2)) * 2 % 60 + t) as u8) + .collect(); + let cr: Vec = (0..w * h / 4) + .map(|i| { + (160u32.wrapping_sub((i / (w / 2)) as u32 * 2 % 50) as u8) + .wrapping_sub(t as u8) + }) + .collect(); + (y, cb, cr) + }) + .collect() + } + + fn as_frames(planes: &[(Vec, Vec, Vec)]) -> Vec> { + planes + .iter() + .map(|(y, cb, cr)| YuvFrame { y, cb, cr }) + .collect() + } + + fn assert_gop_roundtrip(w: usize, h: usize, n: usize, qp: i32) { + let planes = scene(w, h, n); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, w, h, qp).expect("encode"); + assert_eq!(enc.recon.len(), n); + let decoded = decode_annexb_sequence(&enc.stream).expect("decode"); + assert_eq!(decoded.len(), n, "{w}x{h} qp{qp}: frame count"); + for (i, (dec, rec)) in decoded.iter().zip(enc.recon.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "{w}x{h} qp{qp}: frame {i} decoder output == encoder recon" + ); + } + } + + /// The core contract: our decoder reproduces every frame of the + /// low-delay P GOP bit-exactly, across sizes and QPs. + #[test] + fn p_gop_decodes_to_encoder_recon_exactly() { + assert_gop_roundtrip(64, 64, 4, 22); + assert_gop_roundtrip(64, 48, 3, 32); + assert_gop_roundtrip(48, 80, 3, 10); + assert_gop_roundtrip(16, 16, 2, 26); + } + + /// High QP drives most CTUs to skip; the stream stays decodable + /// and P frames get much smaller than the IDR. + #[test] + fn p_frames_compress_against_reference() { + let planes = scene(64, 64, 5); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, 64, 64, 30).expect("encode"); + // Rough split: IDR AU ends where the first TRAIL_R start code + // begins. P payload = total − IDR. + let idr = encode_idr_intra_au_cfg(&planes[0].0, &planes[0].1, &planes[0].2, 64, 64, 30, 2) + .expect("intra encode"); + let p_bytes = enc.stream.len() - idr.au.len(); + let p_avg = p_bytes / 4; + assert!( + p_avg * 3 < idr.au.len(), + "P frames ({p_avg} B avg) should be much smaller than the IDR ({} B)", + idr.au.len() + ); + } + + /// A static scene (all frames identical) should code P frames as + /// (almost) all-skip: tiny payloads, bit-exact reconstruction. + #[test] + fn static_scene_is_skip_coded() { + let one = scene(64, 64, 1).remove(0); + let planes = vec![one.clone(), one.clone(), one]; + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, 64, 64, 26).expect("encode"); + let decoded = decode_annexb_sequence(&enc.stream).expect("decode"); + assert_eq!(decoded.len(), 3); + // Frames 1 and 2 must reproduce frame 0's reconstruction + // exactly (skip copies the reference). + let f0 = decoded[0].picture.to_planar_u8().expect("8-bit"); + for d in &decoded[1..] { + assert_eq!(d.picture.to_planar_u8().expect("8-bit"), f0); + } + // Each all-skip P slice is a handful of bytes. + let idr_len = + encode_idr_intra_au_cfg(&planes[0].0, &planes[0].1, &planes[0].2, 64, 64, 26, 2) + .expect("intra") + .au + .len(); + let p_bytes = enc.stream.len() - idr_len; + assert!( + p_bytes < 80, + "two all-skip 64x64 P frames should be tiny, got {p_bytes} B" + ); + } + + /// Motion estimation actually finds the moving square: at a + /// moderate QP the P-frame quality stays close to the intra + /// quality while spending far fewer bits. + #[test] + fn motion_estimation_tracks_translation() { + let planes = scene(64, 64, 4); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, 64, 64, 22).expect("encode"); + for (t, rec) in enc.recon.iter().enumerate() { + let mse: f64 = rec + .y + .iter() + .zip(planes[t].0.iter()) + .map(|(&a, &b)| { + let d = f64::from(a) - f64::from(b); + d * d + }) + .sum::() + / rec.y.len() as f64; + let psnr = 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(); + assert!(psnr > 33.0, "frame {t} luma PSNR {psnr:.1} dB too low"); + } + } + + /// Validation of the shared input contract. + #[test] + fn rejects_bad_inputs() { + let planes = scene(16, 16, 1); + let frames = as_frames(&planes); + assert!(matches!( + encode_low_delay_p(&frames, 20, 16, 26), + Err(IntraEncodeError::BadDimensions { .. }) + )); + assert!(matches!( + encode_low_delay_p(&frames, 16, 16, 52), + Err(IntraEncodeError::BadQp(52)) + )); + assert!(matches!( + encode_low_delay_p(&frames, 32, 32, 26), + Err(IntraEncodeError::PlaneSize { .. }) + )); + let empty = encode_low_delay_p(&[], 16, 16, 26).expect("empty ok"); + assert!(empty.stream.is_empty() && empty.recon.is_empty()); + } + + /// A hard scene change (unrelated content mid-GOP) drives the + /// per-CTU decision to the intra fallback — and the stream still + /// decodes bit-exactly to the encoder reconstruction. + #[test] + fn scene_change_selects_intra_cus_in_p_slice() { + let (w, h) = (64usize, 64usize); + // Frames 0..2: the moving-square scene. Frame 2: a completely + // different high-detail pattern (uncorrelated with frame 1). + let mut planes = scene(w, h, 2); + let y2: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + (((x * 13) ^ (yy * 7)) % 251) as u8 + }) + .collect(); + let cb2 = vec![60u8; w * h / 4]; + let cr2 = vec![200u8; w * h / 4]; + planes.push((y2, cb2, cr2)); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, w, h, 27).expect("encode"); + + // The scene-change P frame elects intra for a meaningful share + // of its CTBs (the depth-1 rectangular-inter trees legitimately + // take the rest — the residual does the work there). + let st = enc.stats[2]; + assert!( + st.intra >= (w / 16) * (h / 16) / 4, + "scene change should elect intra CUs, got {st:?}" + ); + assert_eq!(st.skip, 0, "nothing to skip across a scene change: {st:?}"); + // The steady frame before it stays inter-dominated (the CTBs + // around the moving square may still legitimately elect intra + // on the covered / uncovered texture). + let st1 = enc.stats[1]; + assert!( + st1.intra < (w / 16) * (h / 16) / 2, + "steady frame should be inter-dominated, got {st1:?}" + ); + assert!( + st.intra > st1.intra, + "the scene change should elect more intra than the steady frame: {st:?} vs {st1:?}" + ); + + // And the whole stream still decodes to the encoder recon. + let decoded = decode_annexb_sequence(&enc.stream).expect("decode"); + assert_eq!(decoded.len(), 3); + for (i, (dec, rec)) in decoded.iter().zip(enc.recon.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "frame {i}" + ); + } + } + + /// Rectangular partitions are actually elected on content with + /// per-half motion (a horizontal boundary moving through CTBs), + /// and the streams stay bit-exact through our decoder — including + /// the §8.5.3.2 second-PU derivation reading the first PU. + #[test] + fn rect_partitions_are_selected_and_roundtrip() { + // Two texture fields moving in opposite directions: the top + // half scrolls right, the bottom half scrolls left, with the + // boundary offset from the CTB grid so 2NxN splits pay off. + let (w, h) = (64usize, 64usize); + let planes: Vec<(Vec, Vec, Vec)> = (0..4usize) + .map(|t| { + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + if yy < 24 { + (((x + w - 2 * t) * 5 + yy * 3) % 220) as u8 + } else { + (((x + 2 * t) * 7 + yy) % 220) as u8 + } + }) + .collect(); + let cb = vec![110u8; w * h / 4]; + let cr = vec![150u8; w * h / 4]; + (y, cb, cr) + }) + .collect(); + let frames = as_frames(&planes); + for (qp, b) in [(24i32, false), (30, true)] { + let mut enc = LowDelayPEncoder::new(w, h, qp, 0) + .expect("encoder") + .with_b_slices(b); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + let mut rect_total = 0usize; + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + rect_total += out.stats.rect; + } + assert!( + rect_total > 0, + "qp{qp} b={b}: expected rectangular partitions on split-motion content" + ); + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 4, "qp{qp} b={b}"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "qp{qp} b={b} frame {i}" + ); + } + } + } + + /// Flickering content (even frames match even frames) drives the + /// per-reference AMVP search to the POC − 2 reference — `ref_idx + /// == 1` is elected and signalled, and the stream decodes + /// bit-exactly. + #[test] + fn second_reference_is_elected_on_flicker() { + let (w, h) = (64usize, 64usize); + // Two alternating texture phases + a moving square so pure + // skip cannot win everywhere. + let planes: Vec<(Vec, Vec, Vec)> = (0..5usize) + .map(|t| { + let phase = (t % 2) * 97; + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + let base = ((x * 7) ^ (yy * 5)) % 180 + phase; + let (sx, sy) = (8 + t * 2, 20); + if x >= sx && x < sx + 10 && yy >= sy && yy < sy + 10 { + (base + 60).min(255) as u8 + } else { + base as u8 + } + }) + .collect(); + let cb = vec![(90 + phase / 2) as u8; w * h / 4]; + let cr = vec![(170 - phase / 2) as u8; w * h / 4]; + (y, cb, cr) + }) + .collect(); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, w, h, 24).expect("encode"); + let ref1_total: usize = enc.stats.iter().map(|s| s.ref1).sum(); + assert!( + ref1_total > 0, + "flicker content should elect the POC-2 reference: {:?}", + enc.stats + ); + let decoded = decode_annexb_sequence(&enc.stream).expect("decode"); + assert_eq!(decoded.len(), 5); + for (i, (dec, rec)) in decoded.iter().zip(enc.recon.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "frame {i}" + ); + } + // Every frame ends up visually faithful despite the flicker. + for (t, rec) in enc.recon.iter().enumerate() { + let mse: f64 = rec + .y + .iter() + .zip(planes[t].0.iter()) + .map(|(&a, &b)| { + let d = f64::from(a) - f64::from(b); + d * d + }) + .sum::() + / rec.y.len() as f64; + let psnr = 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10(); + assert!(psnr > 30.0, "frame {t} luma PSNR {psnr:.1} dB"); + } + } + + /// The mode-decision stats add up to the CTB count on every frame. + #[test] + fn stats_cover_every_ctb() { + let planes = scene(48, 32, 3); + let frames = as_frames(&planes); + let enc = encode_low_delay_p(&frames, 48, 32, 30).expect("encode"); + assert_eq!(enc.stats.len(), 3); + let ctbs = (48 / 16) * (32 / 16); + for (i, st) in enc.stats.iter().enumerate() { + assert_eq!( + st.skip + st.merge + st.amvp + st.intra, + ctbs, + "frame {i}: {st:?}" + ); + } + assert_eq!(enc.stats[0].intra, ctbs, "IDR counts as all-intra"); + } + + /// Low-delay B slices: both reference lists resolve to the + /// previous picture; the whole GOP decodes bit-exactly and the + /// zero-merge / combined candidates actually exercise + /// bi-prediction. + #[test] + fn b_gop_decodes_to_encoder_recon_exactly() { + let planes = scene(64, 64, 4); + let frames = as_frames(&planes); + for qp in [14i32, 27, 39] { + let mut enc = LowDelayPEncoder::new(64, 64, qp, 0) + .expect("encoder") + .with_b_slices(true); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + let mut bi_total = 0usize; + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + bi_total += out.stats.bi; + } + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 4, "qp{qp}"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "qp{qp} frame {i}: decoder output == encoder recon" + ); + } + assert!( + bi_total > 0, + "qp{qp}: expected some bi-predicted CUs in the B GOP" + ); + } + } + + /// B slices with an IDR-refreshing GOP also roundtrip (initType 2 + /// contexts + POC reset + both-list handling across the wrap). + #[test] + fn b_gop_with_idr_refresh_roundtrips() { + let planes = scene(48, 48, 5); + let frames = as_frames(&planes); + let mut enc = LowDelayPEncoder::new(48, 48, 24, 3) + .expect("encoder") + .with_b_slices(true); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + for (i, f) in frames.iter().enumerate() { + let out = enc.encode_frame(f).expect("encode"); + assert_eq!(out.keyframe, i % 3 == 0, "frame {i} keyframe"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + } + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 5); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "frame {i}" + ); + } + } + + /// Encode a whole GOP with a given filter cfg and assert every + /// frame decodes bit-exactly to the encoder's (filtered) recon + /// through the crate's own decoder. Returns the per-frame recons. + fn assert_filtered_gop_roundtrip( + planes: &[(Vec, Vec, Vec)], + w: usize, + h: usize, + qp: i32, + b: bool, + gop: usize, + cfg: LoopFilterCfg, + ) -> Vec { + let frames = as_frames(planes); + let mut enc = LowDelayPEncoder::new(w, h, qp, gop) + .expect("encoder") + .with_b_slices(b) + .with_loop_filters(cfg); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + } + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), planes.len(), "qp{qp} b={b} {cfg:?}"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "qp{qp} b={b} {cfg:?} frame {i}: decoder output == filtered recon" + ); + } + recons + } + + /// Filtered low-delay GOPs (deblocking, SAO, and both — P and B + /// slices, multiple QPs) stay bit-exact through the crate's own + /// decoder, with the filtered pictures serving as the references + /// of every following frame. + #[test] + fn filtered_gops_decode_to_encoder_recon_exactly() { + let planes = scene(64, 64, 4); + let cfgs = [ + LoopFilterCfg { + deblocking: true, + sao_luma: false, + sao_chroma: false, + }, + LoopFilterCfg { + deblocking: false, + sao_luma: true, + sao_chroma: true, + }, + LoopFilterCfg::all(), + ]; + for cfg in cfgs { + for (qp, b) in [(22i32, false), (32, false), (32, true), (40, true)] { + assert_filtered_gop_roundtrip(&planes, 64, 64, qp, b, 0, cfg); + } + } + // Non-square geometry. + let planes = scene(48, 32, 3); + assert_filtered_gop_roundtrip(&planes, 48, 32, 30, false, 0, LoopFilterCfg::all()); + } + + /// Mid-stream IDR refreshes inside a filtered GOP: the filtered + /// IDR reconstruction is the reference of the following P frames, + /// and the whole stream stays bit-exact. + #[test] + fn filtered_gop_with_idr_refresh_roundtrips() { + let planes = scene(48, 48, 5); + assert_filtered_gop_roundtrip(&planes, 48, 48, 33, true, 3, LoopFilterCfg::all()); + } + + /// The filters actually engage on a real GOP at high QP: the + /// filtered reconstruction differs from the unfiltered encode and + /// is never further from the source (the elections are + /// distortion-driven per frame). + #[test] + fn filtered_gop_engages_and_never_hurts() { + let (w, h, n) = (64usize, 64usize, 4usize); + let planes = scene(w, h, n); + let frames = as_frames(&planes); + let qp = 38; + let run = |cfg: LoopFilterCfg| -> Vec { + let mut enc = LowDelayPEncoder::new(w, h, qp, 0) + .expect("encoder") + .with_loop_filters(cfg); + frames + .iter() + .map(|f| enc.encode_frame(f).expect("encode").recon) + .collect() + }; + let plain = run(LoopFilterCfg::off()); + let filtered = run(LoopFilterCfg::all()); + assert!( + plain + .iter() + .zip(filtered.iter()) + .any(|(p, f)| p.y != f.y || p.cb != f.cb || p.cr != f.cr), + "qp{qp}: the loop filters should engage on some frame" + ); + // Frame 0 (the IDR) shares its pre-filter reconstruction with + // the unfiltered run, so the distortion-driven elections can + // only improve it. (Later frames predict from different + // references, so only the IDR comparison is deterministic.) + let ssd = |a: &[u8], b: &[u8]| -> u64 { + a.iter() + .zip(b.iter()) + .map(|(&x, &y)| { + let d = i64::from(x) - i64::from(y); + (d * d) as u64 + }) + .sum() + }; + let d = |r: &FrameRecon, t: usize| { + ssd(&r.y, &planes[t].0) + ssd(&r.cb, &planes[t].1) + ssd(&r.cr, &planes[t].2) + }; + assert!( + d(&filtered[0], 0) <= d(&plain[0], 0), + "IDR: filtered distortion must not exceed unfiltered" + ); + } + + /// The AMP stream configuration (`MinCbSizeY == 8`, an explicit + /// `split_cu_flag == 0` per CTB, the Table 9-45 big-CU part_mode + /// column) roundtrips bit-exactly through the crate's own decoder + /// on P and B GOPs, with and without the in-loop filters — and the + /// SPS actually signals the geometry. + #[test] + fn amp_geometry_gops_decode_to_encoder_recon_exactly() { + let planes = scene(64, 64, 4); + let frames = as_frames(&planes); + for (qp, b, lf) in [ + (22i32, false, LoopFilterCfg::off()), + (32, true, LoopFilterCfg::off()), + (35, true, LoopFilterCfg::all()), + ] { + let mut enc = LowDelayPEncoder::new(64, 64, qp, 0) + .expect("encoder") + .with_b_slices(b) + .with_amp(true) + .with_loop_filters(lf); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + } + // The SPS carries the AMP geometry. + let units = crate::nal::collect_nal_units(&stream).expect("walk"); + let sps = crate::sps::SeqParameterSet::parse(&units[1].rbsp).expect("sps"); + assert!(sps.amp_enabled_flag, "qp{qp} b={b}"); + assert_eq!(sps.log2_min_luma_coding_block_size_minus3, 0); + assert_eq!(sps.log2_diff_max_min_luma_coding_block_size, 1); + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 4, "qp{qp} b={b}"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "qp{qp} b={b} frame {i}: decoder output == encoder recon" + ); + } + } + } + + /// A scene change inside an AMP-geometry GOP drives the intra + /// fallback — whose CU syntax above MinCb carries NO part_mode + /// (§7.3.8.5) — and the stream still decodes bit-exactly. + #[test] + fn amp_geometry_intra_fallback_roundtrips() { + let (w, h) = (64usize, 64usize); + let mut planes = scene(w, h, 2); + let y2: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + (((x * 13) ^ (yy * 7)) % 251) as u8 + }) + .collect(); + planes.push((y2, vec![60u8; w * h / 4], vec![200u8; w * h / 4])); + let frames = as_frames(&planes); + let mut enc = LowDelayPEncoder::new(w, h, 27, 0) + .expect("encoder") + .with_amp(true); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + let mut intra_total = 0usize; + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + if !out.keyframe { + intra_total += out.stats.intra; + } + } + assert!( + intra_total > 0, + "the scene change should elect intra CUs in the AMP-geometry P slice" + ); + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 3); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "frame {i}" + ); + } + } + + /// Banded scenes whose motion boundaries sit at QUARTER offsets + /// inside the CTB rows / columns (where no symmetric split + /// aligns): the AMP shapes are actually elected, signalled on the + /// wire, and the streams decode bit-exactly — P and B, plain and + /// filtered. + #[test] + fn amp_shapes_are_elected_and_roundtrip() { + let (w, h) = (64usize, 64usize); + // Horizontal bands split at y = 20 (CTB row 1, local offset 4 + // ⇒ PART_2NxnU) and y = 44 (row 2, local offset 12 ⇒ + // PART_2NxnD); `transpose` yields the vertical analogues. + let banded = |transpose: bool| -> Vec<(Vec, Vec, Vec)> { + (0..4usize) + .map(|t| { + let y: Vec = (0..w * h) + .map(|i| { + let (mut x, mut yy) = (i % w, i / w); + if transpose { + core::mem::swap(&mut x, &mut yy); + } + let (shift, phase) = if yy < 20 { + (2 * t, 0usize) + } else if yy < 44 { + (w - 2 * t, 60) + } else { + (2 * t + 1, 120) + }; + (((x + shift) * 7 + yy * 3 + phase) % 240) as u8 + }) + .collect(); + (y, vec![110u8; w * h / 4], vec![140u8; w * h / 4]) + }) + .collect() + }; + for (transpose, b, lf) in [ + (false, false, LoopFilterCfg::off()), + (true, false, LoopFilterCfg::off()), + (false, true, LoopFilterCfg::all()), + ] { + let planes = banded(transpose); + let frames = as_frames(&planes); + let mut enc = LowDelayPEncoder::new(w, h, 30, 0) + .expect("encoder") + .with_b_slices(b) + .with_amp(true) + .with_loop_filters(lf); + let mut stream = Vec::new(); + let mut recons = Vec::new(); + let mut amp_total = 0usize; + for f in &frames { + let out = enc.encode_frame(f).expect("encode"); + stream.extend_from_slice(&out.au); + recons.push(out.recon); + amp_total += out.stats.amp; + } + assert!( + amp_total > 0, + "transpose={transpose} b={b}: quarter-offset motion boundaries \ + should elect AMP shapes" + ); + // (The bit-exact roundtrip below IS the wire-level truth: + // a part_mode mismatch would desynchronize CABAC.) + let decoded = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(decoded.len(), 4, "transpose={transpose} b={b}"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "transpose={transpose} b={b} frame {i}" + ); + } + } + } + + /// The §7.3.8.9 `mvd_coding( )` encoder is the exact bin-level + /// dual of the decoder's `decode_mvd_pair` (context flags, the EG1 + /// escape, and signs), across a signed sweep including the EG1 + /// prefix growth points. + #[test] + fn mvd_pair_roundtrips_through_cabac() { + use crate::binarization::decode_mvd_pair; + use crate::bitreader::BitReader; + use crate::cabac::CabacEngine; + let values = [ + 0, 1, -1, 2, -2, 3, -3, 4, 5, -6, 7, 9, -12, 17, 33, -64, 129, -300, + ]; + for &vx in &values { + for &vy in &values { + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let mut ectx = SliceContexts::init(1, 26); + encode_mvd_pair(&mut w, &mut enc, &mut ectx, [vx, vy]); + enc.encode_terminate(&mut w, 1); + let bytes = w.finish(); + + let mut engine = CabacEngine::new(BitReader::new(&bytes)).expect("engine init"); + let mut dctx = SliceContexts::init(1, 26); + let got = decode_mvd_pair( + &mut engine, + &mut dctx.abs_mvd_greater0_flag[0], + &mut dctx.abs_mvd_greater1_flag[0], + ) + .expect("decode"); + assert_eq!(got[0].value, vx, "x component of ({vx}, {vy})"); + assert_eq!(got[1].value, vy, "y component of ({vx}, {vy})"); + } + } + } +} diff --git a/vendor/oxideav-h265/src/encoder/intra.rs b/vendor/oxideav-h265/src/encoder/intra.rs new file mode 100644 index 0000000..1db110b --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/intra.rs @@ -0,0 +1,1514 @@ +//! Real CABAC intra encoder — I-slice IDR access units with §8.4 +//! intra prediction, forward transform + quantization, and full +//! §7.3.8 CABAC syntax emission (no PCM). +//! +//! Geometry (this bootstrap's fixed shape, mirroring the PCM +//! encoder): `CtbSizeY == MinCbSizeY == 16`, so every CTB is one +//! unsplit intra CU. Two partition modes compete per CU +//! (rate-distortion heuristic): +//! +//! * `PART_2Nx2N` — one 16x16 luma PB/TB + two 8x8 chroma TBs; +//! * `PART_NxN` — four 8x8 luma PBs, each its own mode; the §7.4.9.8 +//! `IntraSplitFlag` forces the transform tree to depth 1 (four +//! 8x8 luma TBs + four 4x4 chroma TBs per plane), the 8x8 luma and +//! 4x4 chroma TBs picking their §7.4.9.11 mode-dependent scans. +//! +//! Per CTU the encoder: +//! +//! 1. gathers the §8.4.4.2.1 reference samples from its own +//! reconstruction buffer, marking availability per the §6.4.1 +//! z-scan decode order (CTB raster + TU z-order within the CTB), +//! and runs the decode-side [`crate::intra_pred`] pipeline +//! (§8.4.4.2.2 substitution + §8.4.4.2.3 filtering + planar / DC / +//! angular prediction) for every candidate mode, picking the +//! SAD-best per PB; +//! 2. forward-transforms the prediction residual (the transpose of +//! the §8.6.4.2 DCT-II basis) and quantizes against the §8.6.3 +//! `levelScale`-derived reciprocal at the slice QP (chroma via the +//! Table 8-10 QP mapping); +//! 3. reconstructs through the crate's own DECODE-side §8.6.2 +//! scaling/transform ([`crate::transform::residual_block`]) so the +//! encoder's reference buffer is bit-identical to what a +//! conforming decoder reconstructs, and picks the partition with +//! the smaller SSD + partition-cost heuristic; +//! 4. emits the §7.3.8.5 coding-unit syntax (`part_mode`, the +//! §7.3.8.5 two-loop `prev_intra_luma_pred_flag[]` then +//! `mpm_idx` / `rem_intra_luma_pred_mode` group against the +//! §8.4.2 candidate lists, `intra_chroma_pred_mode` = +//! derived-from-luma), the §7.3.8.8 transform tree with its cbf +//! inheritance, and the §7.3.8.11 residual blocks through +//! [`crate::encoder::residual::encode_residual_coding`]. +//! +//! In-loop filters are off (SAO off in the SPS, deblocking disabled +//! in the PPS), so a conforming decoder's output equals the encoder's +//! reconstruction exactly — pinned by the roundtrip tests. + +use crate::binarization::intra_luma_cand_mode_list; +use crate::binarization::PartMode; +use crate::binarization::{cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::loopfilter::{ + encode_sao_ctb, filter_frame, CtbShape, FilterInput, LoopFilterCfg, +}; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::pcm::{level_idc_for, write_pps_lf, write_ptl, write_vps, write_vps_cfg}; +use crate::encoder::residual::encode_residual_coding; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{ + intra_predict_with_substitution, Component as PredComponent, IntraPredParams, + MarkedReferenceSamples, +}; +use crate::motion::MotionField; +use crate::residual::{residual_coding_scan_idx, ResidualCodingParams}; +use crate::slice_data::SaoCtbParams; +use crate::transform::{forward_dct_1d, residual_block, BlockParams, Component, PredMode}; + +/// The fixed CTB / coding-block log2 size (16x16). +const CTB_LOG2: u32 = 4; +/// The fixed CTB size. +const CTB: usize = 1 << CTB_LOG2; +/// Fixed 8-bit depth. +const BIT_DEPTH: u32 = 8; +/// The z-order offsets of the four NxN prediction blocks / depth-1 +/// transform units within a CTB (§6.5.2 z-scan of the four halves). +const Z_OFFSETS: [(usize, usize); 4] = [(0, 0), (1, 0), (0, 1), (1, 1)]; + +/// Errors from the intra encoder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IntraEncodeError { + /// Width or height is zero or not a multiple of the 16-sample CTB. + BadDimensions { + /// Requested luma width. + width: usize, + /// Requested luma height. + height: usize, + }, + /// A supplied plane's length does not match the 4:2:0 geometry. + PlaneSize { + /// Which plane (`"y"`, `"cb"`, `"cr"`). + plane: &'static str, + /// Required sample count. + expected: usize, + /// Supplied sample count. + got: usize, + }, + /// `SliceQpY` outside 0..=51. + BadQp(i32), +} + +impl core::fmt::Display for IntraEncodeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::BadDimensions { width, height } => write!( + f, + "intra encoder requires nonzero dimensions that are multiples of 16, got {width}x{height}" + ), + Self::PlaneSize { + plane, + expected, + got, + } => write!(f, "{plane} plane has {got} samples, expected {expected}"), + Self::BadQp(qp) => write!(f, "slice QP {qp} outside 0..=51"), + } + } +} + +impl std::error::Error for IntraEncodeError {} + +/// The encoded access unit plus the encoder's own reconstruction +/// (what a conforming decoder outputs — in-loop filters are off). +#[derive(Debug, Clone)] +pub struct IntraEncodedAu { + /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP`). + pub au: Vec, + /// Reconstructed luma plane (`width * height`). + pub recon_y: Vec, + /// Reconstructed Cb plane (`width/2 * height/2`). + pub recon_cb: Vec, + /// Reconstructed Cr plane. + pub recon_cr: Vec, +} + +/// The stream-level geometry / buffering knobs of the shared SPS +/// (everything the intra, low-delay and hierarchical-B encoders vary +/// between them; the rest of the SPS is fixed 4:2:0 8-bit CTB-16). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) struct SpsCfg { + /// `sps_max_dec_pic_buffering_minus1[0]`. + pub max_dec_pic_buffering_minus1: u32, + /// `sps_max_num_reorder_pics[0]` (nonzero for the out-of-order + /// hierarchical-B GOPs). + pub max_num_reorder_pics: u32, + /// `MinCbLog2SizeY` (4 for the legacy CTB == CU geometry; 3 for + /// the AMP-enabled geometry, where every CTB is an UNSPLIT 16x16 + /// CU with `log2CbSize > MinCbLog2SizeY`). + pub min_cb_log2: u32, + /// `amp_enabled_flag` (requires `min_cb_log2 == 3` — Table 9-45 + /// only reaches the AMP bin strings when `log2CbSize > + /// MinCbLog2SizeY`). + pub amp: bool, + // --- edith patch (see the crate-level note in vendor/) --- + /// `conf_win_right_offset` / `conf_win_bottom_offset`, in + /// **chroma** units (§7.4.3.2.1: the luma crop is these times + /// `SubWidthC`/`SubHeightC`, i.e. 2 at 4:2:0). `(0, 0)` writes + /// `conformance_window_flag = 0`, which is what upstream always + /// wrote. + pub conf_win: (u32, u32), + // --- end edith patch --- +} + +impl SpsCfg { + /// The legacy fixed geometry: `MinCbSizeY == CtbSizeY == 16`, no + /// AMP, no output reordering. + pub(crate) fn legacy(max_dec_pic_buffering_minus1: u32) -> Self { + Self { + max_dec_pic_buffering_minus1, + max_num_reorder_pics: 0, + min_cb_log2: CTB_LOG2, + amp: false, + conf_win: (0, 0), + } + } +} + +/// §7.3.2.2 — the fixed-geometry SPS (4:2:0, 8-bit, CTB 16, PCM off, +/// SAO per `sao_enabled`) with the [`SpsCfg`] knob set (coding-block +/// geometry, `amp_enabled_flag`, DPB / reorder bounds). Shared by the +/// intra, low-delay and hierarchical-B encoders (nothing in it is +/// slice-type specific: the P / B slices code their §7.4.8 short-term +/// RPS inline and `sps_temporal_mvp_enabled_flag` is 0). +pub(crate) fn write_sps_cfg( + width: usize, + height: usize, + level_idc: u8, + cfg: &SpsCfg, + sao_enabled: bool, +) -> Vec { + debug_assert!( + !cfg.amp || cfg.min_cb_log2 < CTB_LOG2, + "AMP requires log2CbSize > MinCbLog2SizeY (Table 9-45)" + ); + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl(&mut w, level_idc); + w.ue(0); // sps_seq_parameter_set_id + w.ue(1); // chroma_format_idc = 4:2:0 + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + // --- edith patch: conformance window (upstream always wrote 0) --- + match cfg.conf_win { + (0, 0) => w.put_bit(0), // conformance_window_flag + (right, bottom) => { + w.put_bit(1); // conformance_window_flag + w.ue(0); // conf_win_left_offset + w.ue(right); // conf_win_right_offset + w.ue(0); // conf_win_top_offset + w.ue(bottom); // conf_win_bottom_offset + } + } + // --- end edith patch --- + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(cfg.max_dec_pic_buffering_minus1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(cfg.max_num_reorder_pics); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(cfg.min_cb_log2 - 3); // log2_min_luma_coding_block_size_minus3 + w.ue(CTB_LOG2 - cfg.min_cb_log2); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(u8::from(cfg.amp)); // amp_enabled_flag + w.put_bit(u8::from(sao_enabled)); // sample_adaptive_offset_enabled_flag + w.put_bit(0); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(0); // sps_extension_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// Table 8-10 — the `ChromaArrayType == 1` chroma QP mapping +/// `qPC = f(qPi)` (§8.6.1; `QpBdOffsetC == 0` at 8-bit). +pub(crate) fn chroma_qp_420(qp_y: i32) -> u32 { + let qpi = qp_y.clamp(0, 57); + (match qpi { + x if x < 30 => x, + 30..=33 => qpi - 1, // 30..=33 -> 29, 30, 31, 32 + 34..=43 => 33 + (qpi - 34) / 2, // 34..=43 -> 33, 33, 34, 34 .. 37, 37 + x => x - 6, + }) as u32 +} + +/// §8.6.3-derived reciprocal quantizer scale: `levelScale[qP % 6]` is +/// `{40, 45, 51, 57, 64, 72}`; the forward reciprocal is +/// `round(2^20 / levelScale)` so `quant ∘ dequant` has unity gain. +fn quant_scale(qp_rem: u32) -> i64 { + let ls = i64::from(crate::transform::LEVEL_SCALE[qp_rem as usize]); + ((1i64 << 20) + ls / 2) / ls +} + +/// Forward 2-D DCT-II (the transpose of the §8.6.4 inverse): stage 1 +/// over rows with `shift1 = log2TbS + BitDepth − 9`, stage 2 over +/// columns with `shift2 = log2TbS + 6` — the normalization that makes +/// the §8.6.3 dequant + §8.6.4 inverse reproduce the residual. +fn forward_transform(res: &[i32], n: usize) -> Vec { + let log2 = n.trailing_zeros(); + let shift1 = log2 + BIT_DEPTH - 9; + let shift2 = log2 + 6; + let r1 = 1i64 << (shift1 - 1); + let r2 = 1i64 << (shift2 - 1); + // Stage 1: horizontal analysis per row y -> a[y][u]. + let mut a = vec![0i64; n * n]; + for y in 0..n { + let row: Vec = (0..n).map(|x| i64::from(res[y * n + x])).collect(); + let t = forward_dct_1d(&row, n); + for (u, &v) in t.iter().enumerate() { + a[y * n + u] = (v + r1) >> shift1; + } + } + // Stage 2: vertical analysis per column u -> coef[v][u]. + let mut coef = vec![0i32; n * n]; + for u in 0..n { + let col: Vec = (0..n).map(|y| a[y * n + u]).collect(); + let t = forward_dct_1d(&col, n); + for (v, &val) in t.iter().enumerate() { + coef[v * n + u] = ((val + r2) >> shift2) as i32; + } + } + coef +} + +/// Scalar quantization to `TransCoeffLevel`: `level = sign · +/// (|coef| · quantScale + offset) >> qBits` with `qBits = 14 + qP/6 + +/// (15 − BitDepth − log2TbS)` (the inverse of the §8.6.3 eq. 8-309 +/// scaling chain) and a one-third rounding offset; clamped to the +/// §7.4.9.11 CoeffMax. +fn quantize(coef: &[i32], n: usize, qp: u32) -> Vec { + let log2 = n.trailing_zeros(); + let qbits = 14 + qp / 6 + (15 - BIT_DEPTH - log2); + let scale = quant_scale(qp % 6); + let offset = (1i64 << qbits) / 3; + coef.iter() + .map(|&c| { + let level = ((i64::from(c.unsigned_abs()) * scale + offset) >> qbits).min(0x7FFF); + (level as i32) * c.signum() + }) + .collect() +} + +/// §6.4.1-shaped z-scan availability of the sample at `(nx, ny)` +/// relative to the block being decoded: available iff inside the +/// plane AND its covering coding block precedes in decode order — +/// an earlier CTB (raster), or the same CTB with a smaller depth-1 +/// z-order quadrant index (`cur_z`; pass 0 when the current TB is the +/// whole CTB, making every same-CTB neighbour unavailable). +#[allow(clippy::too_many_arguments)] +pub(crate) fn zscan_avail( + nx: i64, + ny: i64, + plane_w: usize, + plane_h: usize, + blk: usize, + ctbs_x: usize, + cur_ctb: usize, + cur_z: u32, +) -> bool { + if nx < 0 || ny < 0 || nx >= plane_w as i64 || ny >= plane_h as i64 { + return false; + } + let (nx, ny) = (nx as usize, ny as usize); + let nctb = (ny / blk) * ctbs_x + nx / blk; + match nctb.cmp(&cur_ctb) { + core::cmp::Ordering::Less => true, + core::cmp::Ordering::Greater => false, + core::cmp::Ordering::Equal => { + let half = blk / 2; + let z = ((ny % blk) / half) * 2 + ((nx % blk) / half); + (z as u32) < cur_z + } + } +} + +/// Gather the §8.4.4.2.1 marked reference array for an `n`-sample TB +/// at `(x0, y0)`: values through `read`, availability through `avail`. +pub(crate) fn gather_refs( + read: &dyn Fn(usize, usize) -> i32, + avail: &dyn Fn(i64, i64) -> bool, + x0: usize, + y0: usize, + n: usize, +) -> MarkedReferenceSamples { + let get = |x: i64, y: i64| -> (i32, bool) { + if avail(x, y) { + (read(x as usize, y as usize), true) + } else { + (0, false) + } + }; + let corner = get(x0 as i64 - 1, y0 as i64 - 1); + let left: Vec<(i32, bool)> = (0..2 * n) + .map(|k| get(x0 as i64 - 1, (y0 + k) as i64)) + .collect(); + let top: Vec<(i32, bool)> = (0..2 * n) + .map(|k| get((x0 + k) as i64, y0 as i64 - 1)) + .collect(); + MarkedReferenceSamples::new(n, corner, left, top).expect("legal TB geometry") +} + +pub(crate) fn pred_params(mode: u8, cidx: PredComponent) -> IntraPredParams { + IntraPredParams { + pred_mode_intra: mode, + cidx, + bit_depth: BIT_DEPTH as u8, + bit_depth_luma: BIT_DEPTH as u8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: false, + chroma_array_type_3: false, + disable_boundary_filter: false, + } +} + +/// SAD-search all 35 §8.4.2 modes; returns `(mode, prediction)`. +pub(crate) fn search_best_mode(marked: &MarkedReferenceSamples, src: &[i32]) -> (u8, Vec) { + let mut best = (0u8, Vec::new()); + let mut best_cost = u64::MAX; + for mode in 0..=34u8 { + let pred = intra_predict_with_substitution(marked, &pred_params(mode, PredComponent::Luma)) + .expect("legal prediction params"); + let cost: u64 = src + .iter() + .zip(pred.iter()) + .map(|(&s, &p)| u64::from(s.abs_diff(p))) + .sum(); + if cost < best_cost { + best_cost = cost; + best = (mode, pred); + } + } + best +} + +/// Transform + quantize one component TB and reconstruct it through +/// the DECODE-side §8.6.2 path. Returns `(levels, recon_samples)`; +/// `levels` all-zero ⇔ cbf 0 (recon = clipped prediction). +/// +/// `pred_mode` selects the §8.6.4 transform family exactly as the +/// decoder does (the intra-luma 4x4 DST case; every TB the intra and +/// low-delay-P encoders emit at other geometries is DCT either way). +pub(crate) fn code_tb( + src: &[i32], + pred: &[i32], + n: usize, + qp: u32, + component: Component, + pred_mode: PredMode, +) -> (Vec, Vec) { + let res: Vec = src.iter().zip(pred.iter()).map(|(&s, &p)| s - p).collect(); + let coef = forward_transform(&res, n); + let levels = quantize(&coef, n, qp); + let recon: Vec = if levels.iter().all(|&v| v == 0) { + pred.iter().map(|&p| p.clamp(0, 255) as u8).collect() + } else { + let r = residual_block( + &levels, + None, + BlockParams { + n_tbs: n, + q_p: qp, + component, + pred_mode, + bit_depth: BIT_DEPTH as u8, + extended_precision: false, + transquant_bypass: false, + transform_skip: false, + transform_skip_rotation_enabled: false, + }, + ) + .expect("legal block params"); + pred.iter() + .zip(r.iter()) + .map(|(&p, &d)| (p + d).clamp(0, 255) as u8) + .collect() + }; + (levels, recon) +} + +pub(crate) fn ssd(a: &[u8], b: &[i32]) -> u64 { + a.iter() + .zip(b.iter()) + .map(|(&x, &y)| { + let d = i64::from(x) - i64::from(y); + (d * d) as u64 + }) + .sum() +} + +/// Crude bit-cost proxy for one TB's quantized levels: each nonzero +/// coefficient costs roughly its magnitude's bit length (sig flag + +/// sign + level bins); a coded-but-empty TB is nearly free, a coded +/// TB pays a small last-sig overhead. +fn rate_proxy(levels: &[i32]) -> u64 { + let bits: u64 = levels + .iter() + .filter(|&&l| l != 0) + .map(|&l| 3 + 2 * u64::from(32 - l.unsigned_abs().leading_zeros())) + .sum(); + if bits == 0 { + 1 + } else { + bits + 8 + } +} + +/// One coded luma partition candidate for a CTB. +struct LumaPlan { + /// `PART_NxN`? + nxn: bool, + /// PB modes (1 used for 2Nx2N, 4 for NxN, z-order). + modes: [u8; 4], + /// TB level arrays (1 x 16x16 or 4 x 8x8, z-order). + levels: Vec>, + /// The CTB's 16x16 luma reconstruction, row-major. + recon: Vec, +} + +/// One CTB's pass-1 coding decisions (pass 2 emits the syntax after +/// the in-loop filter elections are known). +struct CtbPlan { + /// The elected luma partition + levels. + plan: LumaPlan, + /// Chroma Cb TB levels (1 x 8x8 or 4 x 4x4, z-order). + cb_levels: Vec>, + /// Chroma Cr TB levels. + cr_levels: Vec>, +} + +/// Encode one 4:2:0 8-bit frame as a self-contained intra IDR access +/// unit at `SliceQpY == qp` and return it with the reconstruction a +/// conforming decoder produces. +/// +/// # Errors +/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP. +#[allow(clippy::too_many_lines)] +pub fn encode_idr_intra_au( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + qp: i32, +) -> Result { + // A standalone intra AU needs one reference slot beyond the + // current picture (`sps_max_dec_pic_buffering_minus1 == 1`). + encode_idr_intra_au_cfg(y, cb, cr, width, height, qp, 1) +} + +// --- edith patch --- +/// [`encode_idr_intra_au`] for a picture whose display size is not a +/// multiple of the 16-sample CTB: the planes handed over are the +/// **padded** ones (`width`/`height`, both multiples of 16) and the SPS +/// carries a §7.4.3.2.1 conformance window cropping `crop_right` / +/// `crop_bottom` **luma** samples off, so a decoder outputs the display +/// size. Both crops must be even (4:2:0 addresses the window in chroma +/// units) and smaller than 16. +/// +/// # Errors +/// [`IntraEncodeError`] as [`encode_idr_intra_au`], plus +/// [`IntraEncodeError::BadDimensions`] for an odd or oversized crop. +pub fn encode_idr_intra_au_cropped( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + qp: i32, + crop_right: usize, + crop_bottom: usize, +) -> Result { + if crop_right % 2 != 0 || crop_bottom % 2 != 0 || crop_right >= CTB || crop_bottom >= CTB { + return Err(IntraEncodeError::BadDimensions { + width: width - crop_right, + height: height - crop_bottom, + }); + } + let mut cfg = SpsCfg::legacy(1); + cfg.conf_win = ((crop_right / 2) as u32, (crop_bottom / 2) as u32); + encode_idr_intra_au_full(y, cb, cr, width, height, qp, &cfg, &LoopFilterCfg::off()) +} +// --- end edith patch --- + +/// [`encode_idr_intra_au`] with the §8.7 in-loop filters enabled per +/// `lf`: the reconstruction runs through the crate's decode-side +/// deblocking (per-slice on/off elected against distortion) and SAO +/// (per-CTB §7.3.8.3 parameters from statistics-driven offset +/// estimation), and the returned `recon_*` planes are the *filtered* +/// picture — still exactly what a conforming decoder outputs. +/// +/// # Errors +/// [`IntraEncodeError`] on bad dimensions / plane sizes / QP. +pub fn encode_idr_intra_au_lf( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + qp: i32, + lf: &LoopFilterCfg, +) -> Result { + encode_idr_intra_au_full(y, cb, cr, width, height, qp, &SpsCfg::legacy(1), lf) +} + +/// [`encode_idr_intra_au`] with an explicit +/// `sps_max_dec_pic_buffering_minus1` — the low-delay GOP encoder +/// passes 2 so a conforming decoder keeps BOTH short-term references +/// alive alongside the current picture. +pub(crate) fn encode_idr_intra_au_cfg( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + qp: i32, + max_dec_pic_buffering_minus1: u32, +) -> Result { + encode_idr_intra_au_full( + y, + cb, + cr, + width, + height, + qp, + &SpsCfg::legacy(max_dec_pic_buffering_minus1), + &LoopFilterCfg::off(), + ) +} + +/// The full-configuration intra encode: two passes (per-CTB mode +/// decision + reconstruction, then syntax emission) around the §8.7 +/// in-loop filter stage, so the per-CTB §7.3.8.3 SAO parameters and +/// the slice-header filter elections are known before the slice is +/// written. +#[allow(clippy::too_many_lines, clippy::too_many_arguments)] +pub(crate) fn encode_idr_intra_au_full( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + qp: i32, + cfg: &SpsCfg, + lf: &LoopFilterCfg, +) -> Result { + if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 { + return Err(IntraEncodeError::BadDimensions { width, height }); + } + if !(0..=51).contains(&qp) { + return Err(IntraEncodeError::BadQp(qp)); + } + let check = |plane: &'static str, buf: &[u8], expected: usize| { + if buf.len() != expected { + Err(IntraEncodeError::PlaneSize { + plane, + expected, + got: buf.len(), + }) + } else { + Ok(()) + } + }; + check("y", y, width * height)?; + check("cb", cb, width * height / 4)?; + check("cr", cr, width * height / 4)?; + + let (cw, ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let qp_y = qp as u32; + let qp_c = chroma_qp_420(qp); + // Rate-distortion tradeoff for the partition decision: SSD per + // estimated bit, doubling every 3 QP (integer, deterministic). + let lambda: u64 = 1u64 << (qp.unsigned_abs().saturating_sub(9) / 3); + + let mut recon_y = vec![0u8; width * height]; + let mut recon_cb = vec![0u8; cw * ch]; + let mut recon_cr = vec![0u8; cw * ch]; + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + let mut plans: Vec = Vec::with_capacity(ctbs_x * ctbs_y); + + let extract = |plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize| -> Vec { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + out.push(i32::from(plane[(y0 + j) * pw + x0 + i])); + } + } + out + }; + let store = |plane: &mut [u8], pw: usize, x0: usize, y0: usize, n: usize, s: &[u8]| { + for j in 0..n { + plane[(y0 + j) * pw + x0..(y0 + j) * pw + x0 + n] + .copy_from_slice(&s[j * n..(j + 1) * n]); + } + }; + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let src16 = extract(y, width, x0, y0, CTB); + + // ---- candidate PART_2Nx2N: one 16x16 PB/TB ---- + let plan_2n = { + let read = |x: usize, yy: usize| i32::from(recon_y[yy * width + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read, &avail, x0, y0, CTB); + let (mode, pred) = search_best_mode(&marked, &src16); + let (levels, recon) = + code_tb(&src16, &pred, CTB, qp_y, Component::Luma, PredMode::Intra); + LumaPlan { + nxn: false, + modes: [mode; 4], + levels: vec![levels], + recon, + } + }; + + // ---- candidate PART_NxN: four 8x8 PBs/TBs, z-order ---- + // Only at the legacy MinCb geometry: at `log2CbSize > + // MinCbLog2SizeY` an intra CU's `part_mode` is not present + // (§7.3.8.5), so PART_NxN cannot be signalled. + let plan_nxn = if cfg.min_cb_log2 < CTB_LOG2 { + None + } else { + let mut scratch = vec![0u8; CTB * CTB]; // in-progress CTB recon + let mut pb_modes = [0u8; 4]; + let mut pb_levels: Vec> = Vec::with_capacity(4); + for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() { + let (px, py) = (x0 + zx * 8, y0 + zy * 8); + let read = |x: usize, yy: usize| -> i32 { + if (x0..x0 + CTB).contains(&x) && (y0..y0 + CTB).contains(&yy) { + i32::from(scratch[(yy - y0) * CTB + (x - x0)]) + } else { + i32::from(recon_y[yy * width + x]) + } + }; + let avail = |nx: i64, ny: i64| { + zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, k as u32) + }; + let marked = gather_refs(&read, &avail, px, py, 8); + let src8 = extract(y, width, px, py, 8); + let (mode, pred) = search_best_mode(&marked, &src8); + let (levels, recon8) = + code_tb(&src8, &pred, 8, qp_y, Component::Luma, PredMode::Intra); + for j in 0..8 { + scratch[(zy * 8 + j) * CTB + zx * 8..(zy * 8 + j) * CTB + zx * 8 + 8] + .copy_from_slice(&recon8[j * 8..(j + 1) * 8]); + } + pb_modes[k] = mode; + pb_levels.push(levels); + } + Some(LumaPlan { + nxn: true, + modes: pb_modes, + levels: pb_levels, + recon: scratch, + }) + }; + + // Luma-only rate-distortion comparison: SSD of the coded + // reconstruction + lambda times a bit proxy (residual levels + + // mode signalling: ~6 bits per PB). + let cost = |plan: &LumaPlan| -> u64 { + let rate: u64 = plan.levels.iter().map(|lv| rate_proxy(lv)).sum::() + + plan.levels.len() as u64 * 6; + ssd(&plan.recon, &src16) + lambda * rate + }; + let plan = match plan_nxn { + Some(nxn) if cost(&nxn) < cost(&plan_2n) => nxn, + _ => plan_2n, + }; + store(&mut recon_y, width, x0, y0, CTB, &plan.recon); + // §8.4.3: IntraPredModeC derives from the CU's first PB. + let mode_c = plan.modes[0]; + + // ---- chroma: 8x8 TBs (2Nx2N) or four 4x4 TBs (NxN) ---- + let (cx0, cy0) = (x0 / 2, y0 / 2); + let code_chroma = |plane: &[u8], + recon: &mut Vec, + comp: Component, + pc: PredComponent| + -> Vec> { + if !plan.nxn { + let read = |x: usize, yy: usize| i32::from(recon[yy * cw + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0); + let marked = gather_refs(&read, &avail, cx0, cy0, 8); + let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc)) + .expect("legal prediction params"); + let src = extract(plane, cw, cx0, cy0, 8); + let (levels, rec) = code_tb(&src, &pred, 8, qp_c, comp, PredMode::Intra); + store(recon, cw, cx0, cy0, 8, &rec); + vec![levels] + } else { + let mut out = Vec::with_capacity(4); + let mut scratch = vec![0u8; 64]; // 8x8 chroma CTB recon + for (k, &(zx, zy)) in Z_OFFSETS.iter().enumerate() { + let (px, py) = (cx0 + zx * 4, cy0 + zy * 4); + let read = |x: usize, yy: usize| -> i32 { + if (cx0..cx0 + 8).contains(&x) && (cy0..cy0 + 8).contains(&yy) { + i32::from(scratch[(yy - cy0) * 8 + (x - cx0)]) + } else { + i32::from(recon[yy * cw + x]) + } + }; + let avail = |nx: i64, ny: i64| { + zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, k as u32) + }; + let marked = gather_refs(&read, &avail, px, py, 4); + let pred = intra_predict_with_substitution(&marked, &pred_params(mode_c, pc)) + .expect("legal prediction params"); + let src = extract(plane, cw, px, py, 4); + let (levels, rec) = code_tb(&src, &pred, 4, qp_c, comp, PredMode::Intra); + for j in 0..4 { + scratch[(zy * 4 + j) * 8 + zx * 4..(zy * 4 + j) * 8 + zx * 4 + 4] + .copy_from_slice(&rec[j * 4..(j + 1) * 4]); + } + out.push(levels); + } + store(recon, cw, cx0, cy0, 8, &scratch); + out + } + }; + let cb_levels = code_chroma(cb, &mut recon_cb, Component::Cb, PredComponent::Cb); + let cr_levels = code_chroma(cr, &mut recon_cr, Component::Cr, PredComponent::Cr); + + plans.push(CtbPlan { + plan, + cb_levels, + cr_levels, + }); + } + + // ---- §8.7 in-loop filters (deblocking + SAO) on the recon ---- + let mut deblock_on = false; + let mut beta_offset_div2 = 0i32; + let mut tc_offset_div2 = 0i32; + let mut slice_sao_luma = false; + let mut slice_sao_chroma = false; + let mut sao_ctbs: Vec = Vec::new(); + if lf.any() { + let shapes: Vec = plans + .iter() + .map(|p| CtbShape { + part_mode: if p.plan.nxn { + PartMode::PartNxN + } else { + PartMode::Part2Nx2N + }, + split_depth1: p.plan.nxn, + }) + .collect(); + // Every CU is intra: the fresh motion field's all-intra + // background is exactly the decoder's state (bS == 2 at every + // filtered edge). + let field = MotionField::new(width, height); + let out = filter_frame( + &FilterInput { + width, + height, + qp, + lambda, + recon: [&recon_y, &recon_cb, &recon_cr], + src: [y, cb, cr], + field: &field, + shapes: &shapes, + }, + lf, + ); + deblock_on = out.deblock_on; + beta_offset_div2 = out.beta_offset_div2; + tc_offset_div2 = out.tc_offset_div2; + slice_sao_luma = out.slice_sao_luma; + slice_sao_chroma = out.slice_sao_chroma; + sao_ctbs = out.sao_ctbs; + recon_y = out.y; + recon_cb = out.cb; + recon_cr = out.cr; + } + + // ---- slice_segment_header( ) ---- + let mut w = BitWriter::new(); + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(2); // slice_type = I + if lf.sao() { + // SPS SAO enabled: the per-slice component gates are present. + w.put_bit(u8::from(slice_sao_luma)); // slice_sao_luma_flag + w.put_bit(u8::from(slice_sao_chroma)); // slice_sao_chroma_flag + } + w.se(qp - 26); // slice_qp_delta (init_qp_minus26 == 0) + if lf.deblocking { + // §7.3.6.1 deblocking override group (the PPS signals + // override-enabled + deblocking disabled; an electing slice + // overrides to enabled with zero β/tC offsets). + w.put_bit(u8::from(deblock_on)); // deblocking_filter_override_flag + if deblock_on { + w.put_bit(0); // slice_deblocking_filter_disabled_flag + w.se(beta_offset_div2); // slice_beta_offset_div2 + w.se(tc_offset_div2); // slice_tc_offset_div2 + } + } + if slice_sao_luma || slice_sao_chroma || deblock_on { + // §7.3.6.1: present iff pps_loop_filter_across_slices (1) and + // some in-loop filter is active for this slice. + w.put_bit(1); // slice_loop_filter_across_slices_enabled_flag + } + w.rbsp_trailing_bits(); // byte_alignment() + + // ---- slice_segment_data( ) — pass 2: syntax emission ---- + let mut cabac = CabacEncoder::new(); + // Table 9-4: I slice => initType 0 (raw slice_type 2). + let mut ctxs = SliceContexts::init(init_type(2, false), qp); + for (ctb, ctb_plan) in plans.iter().enumerate() { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + if slice_sao_luma || slice_sao_chroma { + // §7.3.8.3 sao( rx, ry ) ahead of the coding quadtree. + encode_sao_ctb( + &mut w, + &mut cabac, + &mut ctxs, + &sao_ctbs[ctb], + ctb % ctbs_x, + ctb / ctbs_x, + slice_sao_luma, + slice_sao_chroma, + ); + } + let plan = &ctb_plan.plan; + let cb_levels = &ctb_plan.cb_levels; + let cr_levels = &ctb_plan.cr_levels; + // §8.4.3: IntraPredModeC derives from the CU's first PB. + let mode_c = plan.modes[0]; + + // ---- §7.3.8.5 coding_unit( ) syntax ---- + if cfg.min_cb_log2 < CTB_LOG2 { + // §7.3.8.4: log2CbSize (4) > MinCbLog2SizeY — split_cu_flag + // is coded, and every CTB stays one UNSPLIT 16x16 CU. All + // CtDepth values are 0, so both §9.3.4.2.2 conds are 0 and + // the ctxInc is 0. part_mode is then NOT present for an + // intra CU at log2CbSize > MinCbLog2SizeY (§7.3.8.5; + // inferred PART_2Nx2N). + cabac.encode_decision(&mut w, &mut ctxs.split_cu_flag[0], 0); + debug_assert!(!plan.nxn, "PART_NxN cannot be signalled above MinCb"); + } else { + // part_mode: §9.3.3.7 intra at MinCb — "1" = PART_2Nx2N, + // "0" = PART_NxN. + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], u8::from(!plan.nxn)); + } + // §7.3.8.5 two-loop luma mode group: all + // prev_intra_luma_pred_flag bins first, then the mpm_idx / + // rem_intra_luma_pred_mode group. The §8.4.2 candidate list of + // PB k sees the recorded modes of PBs < k, so record as we go + // through the SECOND loop (derivation order). + let n_pb = if plan.nxn { 4 } else { 1 }; + let pb_size = if plan.nxn { 8 } else { CTB }; + let pb_pos = |k: usize| (x0 + Z_OFFSETS[k].0 * 8, y0 + Z_OFFSETS[k].1 * 8); + let mut selections: Vec> = Vec::with_capacity(n_pb); + { + // The candidate list depends only on ALREADY-decoded PBs, + // which are identical in both loop passes; precompute the + // per-PB MPM position by simulating the record order. + for k in 0..n_pb { + let (px, py) = pb_pos(k); + let avail_l = zscan_avail( + px as i64 - 1, + py as i64, + width, + height, + CTB, + ctbs_x, + ctb, + k as u32, + ); + let avail_a = zscan_avail( + px as i64, + py as i64 - 1, + width, + height, + CTB, + ctbs_x, + ctb, + k as u32, + ); + let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + selections.push(list.iter().position(|&m| m == plan.modes[k])); + // Loop 1: prev_intra_luma_pred_flag[k]. + cabac.encode_decision( + &mut w, + &mut ctxs.prev_intra_luma_pred_flag[0], + u8::from(selections[k].is_some()), + ); + // Record now: the next PB's candidates must see this + // one (§8.4.2 derivation order). + modes.record_intra_pb(px, py, pb_size, plan.modes[k], false); + } + // Loop 2: mpm_idx / rem_intra_luma_pred_mode. + for (k, sel) in selections.iter().enumerate() { + match *sel { + Some(0) => cabac.encode_bypass(&mut w, 0), + Some(1) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 0); + } + Some(_) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 1); + } + None => { + // §8.4.2: rem = mode with each smaller + // candidate removed. Recompute the list the + // same way the decoder will (earlier PBs + // recorded). + let (px, py) = pb_pos(k); + let avail_l = zscan_avail( + px as i64 - 1, + py as i64, + width, + height, + CTB, + ctbs_x, + ctb, + k as u32, + ); + let avail_a = zscan_avail( + px as i64, + py as i64 - 1, + width, + height, + CTB, + ctbs_x, + ctb, + k as u32, + ); + let cand_a = modes.cand_intra_pred_mode(px, py, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(px, py, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + let mut rem = u32::from(plan.modes[k]); + for &c in &list { + if u32::from(plan.modes[k]) > u32::from(c) { + rem -= 1; + } + } + cabac.encode_bypass_bits(&mut w, rem, 5); // FL cMax 31 + } + } + } + } + // intra_chroma_pred_mode = 4 (derived from luma): bin "0". + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); + + // ---- §7.3.8.8 transform_tree + §7.3.8.10 transform_unit ---- + let rc_params = |log2: u32, is_chroma: bool, mode: u8| ResidualCodingParams { + log2_trafo_size: log2, + is_chroma, + // §7.4.9.11 mode-dependent scan (only 4x4 / 8x8-luma TBs + // are eligible; larger TBs come back Diagonal). + scan_idx: residual_coding_scan_idx(true, log2, u8::from(is_chroma), 1, u32::from(mode)), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + if !plan.nxn { + // Single 16x16 TU at depth 0. + let cbf_cb = cb_levels[0].iter().any(|&v| v != 0); + let cbf_cr = cr_levels[0].iter().any(|&v| v != 0); + let cbf_luma = plan.levels[0].iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + if cbf_luma { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(4, false, plan.modes[0]), + &plan.levels[0], + ) + .expect("validated luma levels"); + } + if cbf_cb { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, true, mode_c), + &cb_levels[0], + ) + .expect("validated cb levels"); + } + if cbf_cr { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, true, mode_c), + &cr_levels[0], + ) + .expect("validated cr levels"); + } + } else { + // IntraSplitFlag == 1: split_transform_flag inferred 1 at + // depth 0 (§7.4.9.8); four 8x8 leaves at depth 1. Root + // cbf_cb / cbf_cr gate the per-leaf chroma flags + // (§7.3.8.8 inheritance). + let leaf_cbf = |lv: &Vec| lv.iter().any(|&v| v != 0); + let root_cb = cb_levels.iter().any(&leaf_cbf); + let root_cr = cr_levels.iter().any(&leaf_cbf); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(root_cb), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(root_cr), + ); + for k in 0..4 { + let cbf_cb_k = leaf_cbf(&cb_levels[k]); + let cbf_cr_k = leaf_cbf(&cr_levels[k]); + let cbf_luma_k = leaf_cbf(&plan.levels[k]); + if root_cb { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(1) as usize], + u8::from(cbf_cb_k), + ); + } + if root_cr { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(1) as usize], + u8::from(cbf_cr_k), + ); + } + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(1) as usize], + u8::from(cbf_luma_k), + ); + if cbf_luma_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(3, false, plan.modes[k]), + &plan.levels[k], + ) + .expect("validated luma levels"); + } + if root_cb && cbf_cb_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(2, true, mode_c), + &cb_levels[k], + ) + .expect("validated cb levels"); + } + if root_cr && cbf_cr_k { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc_params(2, true, mode_c), + &cr_levels[k], + ) + .expect("validated cr levels"); + } + } + } + + // end_of_slice_segment_flag. + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + // The final terminate-1 flush wrote the rbsp_stop_one_bit; + // rbsp_slice_segment_trailing_bits() is alignment zeros from here. + w.align_zero(); + let slice_rbsp = w.finish(); + + let level_idc = level_idc_for(width * height); + // The reorder-free streams keep the historical VPS bounds (1, 0) + // so every golden pin stays byte-stable; a reordering + // (hierarchical-B) stream signals its honest DPB bounds. + let vps = if cfg.max_num_reorder_pics == 0 { + write_vps(level_idc) + } else { + write_vps_cfg( + level_idc, + cfg.max_dec_pic_buffering_minus1, + cfg.max_num_reorder_pics, + ) + }; + let units = vec![ + nal_unit(32, 0, 0, &vps), // VPS_NUT + nal_unit( + 33, + 0, + 0, + &write_sps_cfg(width, height, level_idc, cfg, lf.sao()), + ), // SPS_NUT + nal_unit(34, 0, 0, &write_pps_lf(false, false, lf.deblocking, None)), // PPS_NUT + nal_unit(20, 0, 0, &slice_rbsp), // IDR_N_LP + ]; + Ok(IntraEncodedAu { + au: annexb(&units), + recon_y, + recon_cb, + recon_cr, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::binarization::PartMode; + use crate::sequence::{decode_annexb_sequence, decode_annexb_sequence_debug}; + use crate::slice_data::CodingQuadtree; + + /// Deterministic test content: smooth gradients + a diagonal + /// texture component so directional modes and residuals both work. + fn planes(w: usize, h: usize) -> (Vec, Vec, Vec) { + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + ((x * 3 + yy * 2 + (x * yy / 7) % 31) % 256) as u8 + }) + .collect(); + let cb: Vec = (0..w * h / 4) + .map(|i| ((i % (w / 2)) * 4 % 200 + 20) as u8) + .collect(); + let cr: Vec = (0..w * h / 4) + .map(|i| (240 - (i / (w / 2)) * 3 % 200) as u8) + .collect(); + (y, cb, cr) + } + + /// Content with per-8x8 alternating strong directions: drives the + /// partition decision toward PART_NxN. + fn blocky_planes(w: usize, h: usize) -> (Vec, Vec, Vec) { + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + let (bx, by) = (x / 8, yy / 8); + match (bx + by) % 3 { + 0 => ((x % 8) * 30) as u8, + 1 => ((yy % 8) * 30) as u8, + _ => (((x + yy) % 16) * 15) as u8, + } + }) + .collect(); + let cb = vec![100u8; w * h / 4]; + let cr = vec![160u8; w * h / 4]; + (y, cb, cr) + } + + fn psnr(a: &[u8], b: &[u8]) -> f64 { + let mse: f64 = a + .iter() + .zip(b.iter()) + .map(|(&x, &y)| { + let d = f64::from(x) - f64::from(y); + d * d + }) + .sum::() + / a.len() as f64; + if mse == 0.0 { + f64::INFINITY + } else { + 10.0 * (255.0f64 * 255.0 / mse).log10() + } + } + + fn assert_roundtrip_exact(y: &[u8], cb: &[u8], cr: &[u8], w: usize, h: usize, qp: i32) { + let enc = encode_idr_intra_au(y, cb, cr, w, h, qp).expect("encode"); + let frames = decode_annexb_sequence(&enc.au).expect("decode"); + assert_eq!(frames.len(), 1, "{w}x{h} qp{qp}"); + let mut recon = Vec::new(); + recon.extend_from_slice(&enc.recon_y); + recon.extend_from_slice(&enc.recon_cb); + recon.extend_from_slice(&enc.recon_cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + recon, + "{w}x{h} qp{qp}: decoder output == encoder reconstruction" + ); + } + + /// The core contract: the crate's own decoder reproduces the + /// encoder's reconstruction EXACTLY (dual-decoder bit-exactness), + /// on both smooth and NxN-inducing content. + #[test] + fn intra_au_decodes_to_encoder_recon_exactly() { + for (w, h) in [(16usize, 16usize), (64, 48), (48, 80)] { + let (y, cb, cr) = planes(w, h); + for qp in [4i32, 22, 32, 45] { + assert_roundtrip_exact(&y, &cb, &cr, w, h, qp); + } + let (y, cb, cr) = blocky_planes(w, h); + for qp in [10i32, 27, 38] { + assert_roundtrip_exact(&y, &cb, &cr, w, h, qp); + } + } + } + + /// The partition decision really selects PART_NxN on content with + /// per-8x8 directional structure (and the stream decodes exactly). + #[test] + fn nxn_partition_is_selected_and_decodes() { + let (w, h) = (64usize, 64usize); + let (y, cb, cr) = blocky_planes(w, h); + let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 27).expect("encode"); + let ctus = decode_annexb_sequence_debug(&enc.au).expect("walk"); + let mut nxn = 0usize; + let mut two_n = 0usize; + for (_, _, ctu) in &ctus { + if let CodingQuadtree::Leaf(cu) = &ctu.quadtree { + match cu.part_mode { + PartMode::PartNxN => nxn += 1, + PartMode::Part2Nx2N => two_n += 1, + other => panic!("unexpected part mode {other:?}"), + } + } + } + assert!(nxn > 0, "no PART_NxN CU selected ({two_n} 2Nx2N)"); + } + + /// Rate/distortion sanity: low QP is near-transparent, and + /// quality degrades monotonically-ish while staying decodable. + #[test] + fn intra_quality_tracks_qp() { + let (w, h) = (64usize, 64usize); + let (y, cb, cr) = planes(w, h); + let at = |qp: i32| { + let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("encode"); + (psnr(&enc.recon_y, &y), enc.au.len()) + }; + let (p4, s4) = at(4); + let (p22, s22) = at(22); + let (p40, s40) = at(40); + assert!(p4 > 45.0, "qp4 luma PSNR {p4:.1} dB"); + assert!(p22 > 33.0, "qp22 luma PSNR {p22:.1} dB"); + assert!(p40 > 22.0, "qp40 luma PSNR {p40:.1} dB"); + assert!(p4 > p22 && p22 > p40, "PSNR decreases with QP"); + assert!( + s4 > s22 && s22 > s40, + "bytes decrease with QP ({s4} > {s22} > {s40})" + ); + } + + /// QP 22 on this content should be visually transparent while far + /// smaller than the PCM (raw) coding — i.e. the transform path + /// actually compresses. + #[test] + fn intra_beats_pcm_size_at_high_quality() { + let (w, h) = (64usize, 64usize); + let (y, cb, cr) = planes(w, h); + let enc = encode_idr_intra_au(&y, &cb, &cr, w, h, 22).expect("encode"); + let raw = w * h * 3 / 2; + assert!( + enc.au.len() < raw / 2, + "compressed {} bytes vs raw {raw}", + enc.au.len() + ); + } + + #[test] + fn rejects_bad_inputs() { + let (y, cb, cr) = planes(16, 16); + assert!(matches!( + encode_idr_intra_au(&y, &cb, &cr, 20, 16, 26), + Err(IntraEncodeError::BadDimensions { .. }) + )); + assert!(matches!( + encode_idr_intra_au(&y, &cb, &cr, 16, 16, 52), + Err(IntraEncodeError::BadQp(52)) + )); + assert!(matches!( + encode_idr_intra_au(&y, &cb, &cr, 32, 16, 26), + Err(IntraEncodeError::PlaneSize { .. }) + )); + } + + /// Filtered intra AUs (§8.7.2 deblocking / §8.7.3 SAO, alone and + /// combined) decode bit-exactly to the encoder's filtered + /// reconstruction through the crate's own decoder, across + /// geometries and QPs. + #[test] + fn filtered_intra_au_decodes_to_encoder_recon_exactly() { + let cfgs = [ + LoopFilterCfg { + deblocking: true, + sao_luma: false, + sao_chroma: false, + }, + LoopFilterCfg { + deblocking: false, + sao_luma: true, + sao_chroma: true, + }, + LoopFilterCfg { + deblocking: false, + sao_luma: true, + sao_chroma: false, + }, + LoopFilterCfg::all(), + ]; + for (w, h) in [(32usize, 32usize), (64, 48)] { + for planes_fn in [planes, blocky_planes] { + let (y, cb, cr) = planes_fn(w, h); + for qp in [27i32, 38] { + for cfg in &cfgs { + let enc = + encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, cfg).expect("encode"); + let frames = decode_annexb_sequence(&enc.au).expect("decode"); + assert_eq!(frames.len(), 1, "{w}x{h} qp{qp} {cfg:?}"); + let mut recon = enc.recon_y.clone(); + recon.extend_from_slice(&enc.recon_cb); + recon.extend_from_slice(&enc.recon_cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + recon, + "{w}x{h} qp{qp} {cfg:?}: decoder output == filtered recon" + ); + } + } + } + } + } + + /// The filter elections are distortion-driven, so a filtered + /// encode is never further from the source than the unfiltered + /// one — and on smooth content at high QP (where quantization + /// manufactures block edges the source never had) the filters + /// actually engage (the reconstruction changes and the slice + /// header signals them). + #[test] + fn filters_never_hurt_and_engage_on_smooth_content() { + let (w, h) = (64usize, 64usize); + let (y, cb, cr) = planes(w, h); + let qp = 40; + let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, qp).expect("plain"); + let filtered = + encode_idr_intra_au_lf(&y, &cb, &cr, w, h, qp, &LoopFilterCfg::all()).expect("lf"); + let ssd = |a: &[u8], b: &[u8]| -> u64 { + a.iter() + .zip(b.iter()) + .map(|(&p, &q)| { + let d = i64::from(p) - i64::from(q); + (d * d) as u64 + }) + .sum() + }; + let d_plain = + ssd(&plain.recon_y, &y) + ssd(&plain.recon_cb, &cb) + ssd(&plain.recon_cr, &cr); + let d_filt = ssd(&filtered.recon_y, &y) + + ssd(&filtered.recon_cb, &cb) + + ssd(&filtered.recon_cr, &cr); + assert!( + d_filt <= d_plain, + "filters must not hurt: filtered {d_filt} vs plain {d_plain}" + ); + assert_ne!( + filtered.recon_y, plain.recon_y, + "high-QP blocky content should engage the loop filters" + ); + + // The written headers carry the filter signalling: SAO enabled + // in the SPS, the deblocking override chain in the PPS, and + // the elected per-slice flags in the slice header. + let units = crate::nal::collect_nal_units(&filtered.au).expect("walk"); + let sps = crate::sps::SeqParameterSet::parse(&units[1].rbsp).expect("sps"); + assert!(sps.sample_adaptive_offset_enabled_flag); + let pps = crate::pps::PicParameterSet::parse(&units[2].rbsp).expect("pps"); + assert!(pps.deblocking_filter_control_present_flag); + assert!(pps.deblocking.override_enabled_flag); + assert!(pps.deblocking.disabled_flag, "PPS default stays disabled"); + let header = crate::slice::SliceSegmentHeader::parse( + &units[3].rbsp, + units[3].header.nal_unit_type, + &sps, + &pps, + ) + .expect("slice header"); + assert!( + header.slice_sao_luma_flag + || header.slice_sao_chroma_flag + || header.deblocking.is_some_and(|d| !d.disabled_flag), + "some in-loop filter is elected in the slice header" + ); + } + + /// `LoopFilterCfg::off()` reproduces the legacy unfiltered stream + /// byte for byte (headers included) — the golden interop pins stay + /// valid. + #[test] + fn lf_off_is_byte_identical_to_legacy_encode() { + let (w, h) = (48usize, 32usize); + let (y, cb, cr) = planes(w, h); + let plain = encode_idr_intra_au(&y, &cb, &cr, w, h, 24).expect("plain"); + let off = + encode_idr_intra_au_lf(&y, &cb, &cr, w, h, 24, &LoopFilterCfg::off()).expect("off"); + assert_eq!(plain.au, off.au); + assert_eq!(plain.recon_y, off.recon_y); + } + + /// Table 8-10 spot pins. + #[test] + fn chroma_qp_mapping_matches_table_8_10() { + assert_eq!(chroma_qp_420(0), 0); + assert_eq!(chroma_qp_420(29), 29); + assert_eq!(chroma_qp_420(30), 29); + assert_eq!(chroma_qp_420(33), 32); + assert_eq!(chroma_qp_420(34), 33); + assert_eq!(chroma_qp_420(35), 33); + assert_eq!(chroma_qp_420(36), 34); + assert_eq!(chroma_qp_420(37), 34); + assert_eq!(chroma_qp_420(38), 35); + assert_eq!(chroma_qp_420(43), 37); + assert_eq!(chroma_qp_420(44), 38); + assert_eq!(chroma_qp_420(51), 45); + } +} diff --git a/vendor/oxideav-h265/src/encoder/loopfilter.rs b/vendor/oxideav-h265/src/encoder/loopfilter.rs new file mode 100644 index 0000000..924c863 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/loopfilter.rs @@ -0,0 +1,1308 @@ +//! Encoder-side §8.7 in-loop filters — deblocking + SAO on the +//! encoder's reconstruction path. +//! +//! A conforming decoder's reference pictures are the *filtered* +//! reconstructions, so an encoder that signals the loop filters must +//! run the very same §8.7.2 deblocking and §8.7.3 SAO over its own +//! reconstruction before using it as a reference (and before claiming +//! it as "what the decoder outputs"). This module drives the crate's +//! DECODE-side filter implementations ([`crate::deblock`] / +//! [`crate::sao`]) over an encoder frame: +//! +//! * **Deblocking** (§8.7.2) — applied through +//! [`crate::deblock::deblock_picture_full`] with per-CTB +//! [`DeblockCuDesc`]s built from the encoder's coding decisions +//! (partition mode + transform-split topology) and the same +//! [`MotionField`] the mode decisions maintained. The per-frame +//! election is distortion-driven over off + a 3x3 +//! `slice_beta_offset_div2` / `slice_tc_offset_div2` sweep +//! ({−2, 0, 2}²): the slice signals +//! `deblocking_filter_override_flag == 1` / +//! `slice_deblocking_filter_disabled_flag == 0` with the winning +//! offsets only when some filtered picture is closer to the source. +//! * **SAO** (§8.7.3) — per-CTB statistics-driven offset estimation +//! (the derivation of the offsets is encoder freedom; the *applied* +//! modification is the decoder's own +//! [`crate::sao::apply_sao_ctb_full`], so every candidate's +//! distortion is measured with the exact decode-side arithmetic). +//! Candidates per component: off, band offset (best +//! `sao_band_position` by per-band gain), and the four edge-offset +//! classes; chroma obeys the §7.4.9.3 shared-type rule (`SaoTypeIdx +//! [2]` / `SaoEoClass[2]` inherit cIdx 1). Whole-CTB +//! `sao_merge_left_flag` / `sao_merge_up_flag` candidates are priced +//! too. The elected parameters are applied with +//! [`crate::sao::apply_sao_picture_full`] — the same picture-level +//! driver the decoder runs. +//! * **Syntax** — [`encode_sao_ctb`] is the bin-exact §7.3.8.3 +//! `sao( rx, ry )` dual of [`crate::slice_data::decode_sao`]. +//! +//! Geometry contract (shared with the intra / low-delay encoders): +//! `CtbSizeY == 16`, one coding unit per CTB, 4:2:0 8-bit, a single +//! slice and tile per picture, constant QP (no `cu_qp_delta`), no PCM +//! / transquant-bypass CUs (so the §8.7 `NoFilterMap` is empty). + +use crate::binarization::PartMode; +use crate::ctx_init::SliceContexts; +use crate::deblock::{deblock_picture_full, DeblockCu, DeblockCuDesc, DeblockCuParams}; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::motion::MotionField; +use crate::picture::{Picture, Plane}; +use crate::sao::{apply_sao_ctb_full, apply_sao_picture_full, ResolvedSao, ResolvedSaoComponent}; +use crate::slice_data::{SaoComponent, SaoCtbParams}; + +/// The fixed CTB log2 size of the bootstrap encoders (16x16). +const CTB_LOG2: u32 = 4; +/// The fixed CTB size. +const CTB: usize = 1 << CTB_LOG2; +/// §7.3.8.3 `sao_offset_abs` cMax at 8-bit: +/// `(1 << (Min(bitDepth, 10) − 5)) − 1`. +const SAO_OFFSET_MAX: i32 = 7; + +/// Which in-loop filters the encoder signals and applies. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct LoopFilterCfg { + /// Enable the §8.7.2 deblocking filter (PPS + /// `deblocking_filter_override_enabled_flag == 1`; each slice + /// elects on/off against distortion). + pub deblocking: bool, + /// Enable luma SAO (SPS `sample_adaptive_offset_enabled_flag == 1` + /// + per-slice `slice_sao_luma_flag` election). + pub sao_luma: bool, + /// Enable chroma SAO (`slice_sao_chroma_flag` election). + pub sao_chroma: bool, +} + +impl LoopFilterCfg { + /// No in-loop filters (the pre-round-429 encoder behaviour). + #[must_use] + pub fn off() -> Self { + Self::default() + } + + /// Deblocking + luma and chroma SAO. + #[must_use] + pub fn all() -> Self { + Self { + deblocking: true, + sao_luma: true, + sao_chroma: true, + } + } + + /// `true` when SAO is enabled for any component (drives the SPS + /// `sample_adaptive_offset_enabled_flag`). + #[must_use] + pub fn sao(&self) -> bool { + self.sao_luma || self.sao_chroma + } + + /// `true` when any filter is enabled. + #[must_use] + pub fn any(&self) -> bool { + self.deblocking || self.sao() + } +} + +/// One CTB-sized coding unit's deblocking shape (the encoder-side +/// counterpart of what the decoder reads off the parsed CU). +#[derive(Debug, Clone, Copy)] +pub struct CtbShape { + /// The CU's prediction partition mode. + pub part_mode: PartMode, + /// `true` when the CU's transform tree is the single-level split + /// (four depth-1 leaves: the §7.4.9.8 `IntraSplitFlag` / + /// `interSplitFlag` forced split); `false` for a whole-CB leaf + /// (depth-0 TU, skip, or `rqt_root_cbf == 0`). + pub split_depth1: bool, +} + +/// Build the per-CTB [`DeblockCuDesc`] list for a fixed-geometry +/// encoder picture (CTB == CU == 16, raster order, single slice / +/// tile, constant QP) at the given slice β/tC offsets. +#[must_use] +pub(crate) fn ctb_deblock_descs( + shapes: &[CtbShape], + width: usize, + height: usize, + qp: i32, + beta_offset_div2: i32, + tc_offset_div2: i32, +) -> Vec { + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + debug_assert_eq!(shapes.len(), ctbs_x * ctbs_y); + let params = DeblockCuParams { + qp_y: qp, + beta_offset_div2, + tc_offset_div2, + cb_qp_offset: 0, + cr_qp_offset: 0, + bit_depth_luma: 8, + bit_depth_chroma: 8, + chroma_array_type: 1, + }; + shapes + .iter() + .enumerate() + .map(|(ctb, shape)| { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + DeblockCuDesc { + cu: DeblockCu { + x_cb: x0, + y_cb: y0, + log2_cb_size: CTB_LOG2, + params, + // Constant QP: the p-side scalars equal the CU QP. + qp_y_p_left: qp, + qp_y_p_top: qp, + }, + transform_split: if shape.split_depth1 { + crate::deblock::TransformSplit::split_once() + } else { + crate::deblock::TransformSplit::leaf() + }, + part_mode: shape.part_mode, + // §8.7.2.1: picture-boundary edges are never filtered; + // single slice / tile, so no other exclusions. + filter_left: x0 > 0, + filter_top: y0 > 0, + } + }) + .collect() +} + +/// The borrowed inputs of one frame's filter pass. +pub(crate) struct FilterInput<'a> { + /// Picture width in luma samples (multiple of 16). + pub width: usize, + /// Picture height in luma samples. + pub height: usize, + /// `SliceQpY`. + pub qp: i32, + /// The SSD-per-bin λ of the slice's mode decisions. + pub lambda: u64, + /// Pre-filter reconstruction planes `[y, cb, cr]`. + pub recon: [&'a [u8]; 3], + /// Source planes `[y, cb, cr]`. + pub src: [&'a [u8]; 3], + /// The picture's motion / mode field (§8.7.2.4 bS input). + pub field: &'a MotionField, + /// Per-CTB coding shapes (raster order). + pub shapes: &'a [CtbShape], +} + +/// One frame's elected filter signalling + the filtered reconstruction. +pub(crate) struct FilteredFrame { + /// The slice's deblocking election + /// (`slice_deblocking_filter_disabled_flag == !deblock_on`). + pub deblock_on: bool, + /// Elected `slice_beta_offset_div2` (meaningful iff + /// [`Self::deblock_on`]). + pub beta_offset_div2: i32, + /// Elected `slice_tc_offset_div2`. + pub tc_offset_div2: i32, + /// Elected `slice_sao_luma_flag`. + pub slice_sao_luma: bool, + /// Elected `slice_sao_chroma_flag`. + pub slice_sao_chroma: bool, + /// Per-CTB §7.3.8.3 syntax values (raster order; empty when both + /// slice SAO flags are 0). + pub sao_ctbs: Vec, + /// The filtered reconstruction (what a conforming decoder outputs + /// and stores as a reference). + pub y: Vec, + /// Filtered Cb plane. + pub cb: Vec, + /// Filtered Cr plane. + pub cr: Vec, +} + +/// Pack three u8 planes into a [`Picture`]. +fn planes_to_picture(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Picture { + let mut pic = Picture::new(width, height, 1, 8, 8); + for (plane, data) in [(Plane::Luma, y), (Plane::Cb, cb), (Plane::Cr, cr)] { + let (buf, _stride) = pic.plane_mut(plane); + debug_assert_eq!(buf.len(), data.len()); + for (dst, &src) in buf.iter_mut().zip(data.iter()) { + *dst = i32::from(src); + } + } + pic +} + +/// SSD of one whole plane against a u8 source plane. +fn plane_ssd(pic: &Picture, plane: Plane, src: &[u8]) -> u64 { + pic.plane(plane) + .iter() + .zip(src.iter()) + .map(|(&a, &b)| { + let d = a - i32::from(b); + (d * d) as u64 + }) + .sum() +} + +/// SSD of a `w`x`h` region of a picture plane against the matching +/// region of a u8 source plane (`plane_w` wide). +#[allow(clippy::too_many_arguments)] +fn region_ssd( + pic: &Picture, + plane: Plane, + src: &[u8], + plane_w: usize, + x0: usize, + y0: usize, + w: usize, + h: usize, +) -> u64 { + let mut acc = 0u64; + for j in 0..h { + for i in 0..w { + let d = pic.sample(plane, x0 + i, y0 + j) - i32::from(src[(y0 + j) * plane_w + x0 + i]); + acc += (d * d) as u64; + } + } + acc +} + +/// Copy a `w`x`h` region of `from` into `to` (same plane geometry). +fn restore_region( + to: &mut Picture, + from: &Picture, + plane: Plane, + x0: usize, + y0: usize, + w: usize, + h: usize, +) { + for j in 0..h { + for i in 0..w { + to.set_sample(plane, x0 + i, y0 + j, from.sample(plane, x0 + i, y0 + j)); + } + } +} + +/// Round-half-away-from-zero integer division for the offset means. +fn round_div(sum: i64, cnt: i64) -> i32 { + if cnt == 0 { + 0 + } else { + let bias = if sum >= 0 { cnt } else { -cnt }; + ((2 * sum + bias) / (2 * cnt)) as i32 + } +} + +/// §9.3.3 TR (cMax 7, bypass) bin count of one `sao_offset_abs` value. +fn tr7_bins(v: u32) -> u64 { + if v as i32 >= SAO_OFFSET_MAX { + SAO_OFFSET_MAX as u64 + } else { + u64::from(v) + 1 + } +} + +/// Rate proxy (bins) of one component's §7.3.8.3 fields. `with_shared` +/// counts the `sao_type_idx_*` (and, for edge offset, `sao_eo_class_*`) +/// bins — true for cIdx 0 / 1, false for cIdx 2 (which inherits both +/// per §7.4.9.3). +fn component_rate(comp: &SaoComponent, with_shared: bool) -> u64 { + match comp.sao_type_idx { + 0 => u64::from(with_shared), + 1 => { + let offs: u64 = comp.offset_abs.iter().map(|&a| tr7_bins(a)).sum(); + let signs = comp.offset_abs.iter().filter(|&&a| a != 0).count() as u64; + u64::from(with_shared) * 2 + offs + signs + 5 + } + _ => { + let offs: u64 = comp.offset_abs.iter().map(|&a| tr7_bins(a)).sum(); + u64::from(with_shared) * 2 + offs + u64::from(with_shared) * 2 + } + } +} + +/// Exact distortion of applying `comp` (already §7.4.9.3-resolved) to +/// one CTB region of one plane: runs the decoder's own +/// [`apply_sao_ctb_full`] into `scratch` (which must equal `base` +/// outside the region on entry) and restores the region afterwards. +#[allow(clippy::too_many_arguments)] +fn eval_component( + base: &Picture, + scratch: &mut Picture, + plane: Plane, + comp: &ResolvedSaoComponent, + src: &[u8], + plane_w: usize, + x0: usize, + y0: usize, + n: usize, +) -> u64 { + if comp.sao_type_idx == 0 { + return region_ssd(base, plane, src, plane_w, x0, y0, n, n); + } + apply_sao_ctb_full(base, scratch, plane, comp, x0, y0, n, n, None, None); + let d = region_ssd(scratch, plane, src, plane_w, x0, y0, n, n); + restore_region(scratch, base, plane, x0, y0, n, n); + d +} + +/// Statistics-driven §8.7.3.2 edge-offset candidate for one component +/// region: classify every sample against the pre-SAO picture (the +/// §8.7.3.2 picture-boundary guard included), then derive the four +/// per-category offsets from the src−rec means (categories 0/1 +/// non-negative, 2/3 non-positive per the §7.4.9.3 inferred signs). +#[allow(clippy::too_many_arguments)] +fn edge_candidate( + base: &Picture, + plane: Plane, + src: &[u8], + plane_w: usize, + x0: usize, + y0: usize, + n: usize, + eo_class: u8, +) -> SaoComponent { + let (h0, v0, h1, v1) = crate::sao::eo_pos(eo_class); + let (pw, ph) = base.plane_dims(plane); + let mut cnt = [0i64; 5]; + let mut sum = [0i64; 5]; + for j in 0..n { + for i in 0..n { + let (x, y) = ((x0 + i) as i32, (y0 + j) as i32); + let in_pic = + |xx: i32, yy: i32| xx >= 0 && yy >= 0 && (xx as usize) < pw && (yy as usize) < ph; + if !in_pic(x + h0, y + v0) || !in_pic(x + h1, y + v1) { + continue; + } + let cur = base.sample(plane, x as usize, y as usize); + let s0 = base.sample(plane, (x + h0) as usize, (y + v0) as usize); + let s1 = base.sample(plane, (x + h1) as usize, (y + v1) as usize); + let sign = |v: i32| -> i32 { + match v.cmp(&0) { + core::cmp::Ordering::Greater => 1, + core::cmp::Ordering::Equal => 0, + core::cmp::Ordering::Less => -1, + } + }; + let mut edge_idx = 2 + sign(cur - s0) + sign(cur - s1); + if edge_idx <= 2 { + edge_idx = if edge_idx == 2 { 0 } else { edge_idx + 1 }; + } + if edge_idx == 0 { + continue; + } + cnt[edge_idx as usize] += 1; + sum[edge_idx as usize] += + i64::from(src[(y as usize) * plane_w + x as usize]) - i64::from(cur); + } + } + let mut offset_abs = [0u32; 4]; + for i in 0..4 { + let raw = round_div(sum[i + 1], cnt[i + 1]); + // §7.4.9.3 inferred signs: categories 1/2 add, 3/4 subtract. + let clamped = if i < 2 { + raw.clamp(0, SAO_OFFSET_MAX) + } else { + raw.clamp(-SAO_OFFSET_MAX, 0) + }; + offset_abs[i] = clamped.unsigned_abs(); + } + SaoComponent { + sao_type_idx: 2, + offset_abs, + offset_sign: [0; 4], + band_position: 0, + eo_class, + } +} + +/// Statistics-driven §8.7.3.2 band-offset candidate: per-band src−rec +/// means, then the `sao_band_position` whose four consecutive bands +/// carry the largest estimated SSD gain. +#[allow(clippy::too_many_arguments)] +fn band_candidate( + base: &Picture, + plane: Plane, + src: &[u8], + plane_w: usize, + x0: usize, + y0: usize, + n: usize, +) -> SaoComponent { + let mut cnt = [0i64; 32]; + let mut sum = [0i64; 32]; + for j in 0..n { + for i in 0..n { + let cur = base.sample(plane, x0 + i, y0 + j); + let band = (cur >> 3) as usize & 31; + cnt[band] += 1; + sum[band] += i64::from(src[(y0 + j) * plane_w + x0 + i]) - i64::from(cur); + } + } + let mut offset = [0i32; 32]; + let mut gain = [0i64; 32]; + for b in 0..32 { + let o = round_div(sum[b], cnt[b]).clamp(-SAO_OFFSET_MAX, SAO_OFFSET_MAX); + // Estimated SSD reduction: 2·o·Σdiff − o²·N (clipping ignored — + // the exact election re-measures with the decode-side apply). + let g = 2 * i64::from(o) * sum[b] - i64::from(o) * i64::from(o) * cnt[b]; + if g > 0 { + offset[b] = o; + gain[b] = g; + } + } + let best_pos = (0..32u8) + .max_by_key(|&p| (0..4).map(|k| gain[(p as usize + k) & 31]).sum::()) + .unwrap_or(0); + let mut offset_abs = [0u32; 4]; + let mut offset_sign = [0u8; 4]; + for k in 0..4 { + let o = offset[(best_pos as usize + k) & 31]; + offset_abs[k] = o.unsigned_abs(); + offset_sign[k] = u8::from(o < 0); + } + SaoComponent { + sao_type_idx: 1, + offset_abs, + offset_sign, + band_position: best_pos, + eo_class: 0, + } +} + +/// Resolve a syntax component into the applied form (8-bit: no +/// range-extension offset scale). +fn resolved(comp: &SaoComponent) -> ResolvedSaoComponent { + ResolvedSaoComponent::from_decoded(comp, 0) +} + +/// Elect one CTB's luma SAO parameters: off vs band vs the four edge +/// classes, each measured with the decode-side apply. Returns the +/// syntax component and its `dist + λ·rate` cost (rate including the +/// component's own §7.3.8.3 bins). +#[allow(clippy::too_many_arguments)] +fn choose_luma( + base: &Picture, + scratch: &mut Picture, + src: &[u8], + width: usize, + x0: usize, + y0: usize, + lambda: u64, +) -> (SaoComponent, u64) { + let off = SaoComponent::default(); + let mut best = ( + off, + region_ssd(base, Plane::Luma, src, width, x0, y0, CTB, CTB) + lambda, + ); + let mut consider = |comp: SaoComponent, scratch: &mut Picture| { + let d = eval_component( + base, + scratch, + Plane::Luma, + &resolved(&comp), + src, + width, + x0, + y0, + CTB, + ); + let cost = d + lambda * component_rate(&comp, true); + if cost < best.1 { + best = (comp, cost); + } + }; + consider( + band_candidate(base, Plane::Luma, src, width, x0, y0, CTB), + scratch, + ); + for eo_class in 0..4u8 { + consider( + edge_candidate(base, Plane::Luma, src, width, x0, y0, CTB, eo_class), + scratch, + ); + } + best +} + +/// Elect one CTB's chroma SAO parameters under the §7.4.9.3 shared +/// type / eo-class rule: one `SaoTypeIdx` (and edge class) for both +/// Cb and Cr, per-component offsets / band positions. +#[allow(clippy::too_many_arguments)] +fn choose_chroma( + base: &Picture, + scratch: &mut Picture, + src_cb: &[u8], + src_cr: &[u8], + cw: usize, + cx0: usize, + cy0: usize, + lambda: u64, +) -> ([SaoComponent; 2], u64) { + let n = CTB / 2; + let dist_pair = |cb: &SaoComponent, cr: &SaoComponent, scratch: &mut Picture| -> u64 { + eval_component( + base, + scratch, + Plane::Cb, + &resolved(cb), + src_cb, + cw, + cx0, + cy0, + n, + ) + eval_component( + base, + scratch, + Plane::Cr, + &resolved(cr), + src_cr, + cw, + cx0, + cy0, + n, + ) + }; + let off = SaoComponent::default(); + let mut best = ([off, off], dist_pair(&off, &off, scratch) + lambda); + let mut consider = |cb: SaoComponent, cr: SaoComponent, scratch: &mut Picture| { + let d = dist_pair(&cb, &cr, scratch); + let rate = component_rate(&cb, true) + component_rate(&cr, false); + let cost = d + lambda * rate; + if cost < best.1 { + best = ([cb, cr], cost); + } + }; + consider( + band_candidate(base, Plane::Cb, src_cb, cw, cx0, cy0, n), + band_candidate(base, Plane::Cr, src_cr, cw, cx0, cy0, n), + scratch, + ); + for eo_class in 0..4u8 { + consider( + edge_candidate(base, Plane::Cb, src_cb, cw, cx0, cy0, n, eo_class), + edge_candidate(base, Plane::Cr, src_cr, cw, cx0, cy0, n, eo_class), + scratch, + ); + } + best +} + +/// Distortion of applying a fully-resolved CTB parameter set (all +/// three components) — the merge-candidate measurement. +#[allow(clippy::too_many_arguments)] +fn resolved_ctb_dist( + base: &Picture, + scratch: &mut Picture, + r: &ResolvedSao, + input: &FilterInput<'_>, + x0: usize, + y0: usize, + sao_luma: bool, + sao_chroma: bool, +) -> u64 { + let (cw, cx0, cy0, n) = (input.width / 2, x0 / 2, y0 / 2, CTB / 2); + let mut d = 0u64; + let luma = if sao_luma { + &r.components[0] + } else { + &ResolvedSaoComponent::off() + }; + d += eval_component( + base, + scratch, + Plane::Luma, + luma, + input.src[0], + input.width, + x0, + y0, + CTB, + ); + let (cbc, crc) = if sao_chroma { + (&r.components[1], &r.components[2]) + } else { + (&ResolvedSaoComponent::off(), &ResolvedSaoComponent::off()) + }; + d += eval_component(base, scratch, Plane::Cb, cbc, input.src[1], cw, cx0, cy0, n); + d += eval_component(base, scratch, Plane::Cr, crc, input.src[2], cw, cx0, cy0, n); + d +} + +/// Run the elected in-loop filters over one encoder frame. +/// +/// Returns the filter signalling (per-slice deblocking election, the +/// slice SAO flags, per-CTB SAO syntax) and the filtered +/// reconstruction — exactly what a conforming decoder reconstructs +/// from that signalling. +pub(crate) fn filter_frame(input: &FilterInput<'_>, cfg: &LoopFilterCfg) -> FilteredFrame { + let (width, height) = (input.width, input.height); + let pre = planes_to_picture( + input.recon[0], + input.recon[1], + input.recon[2], + width, + height, + ); + + // ---- §8.7.2 deblocking: per-slice on/off + β/tC election ---- + let mut deblock_on = false; + let mut beta_offset_div2 = 0i32; + let mut tc_offset_div2 = 0i32; + let base = if cfg.deblocking { + let ssd = |p: &Picture| { + plane_ssd(p, Plane::Luma, input.src[0]) + + plane_ssd(p, Plane::Cb, input.src[1]) + + plane_ssd(p, Plane::Cr, input.src[2]) + }; + // se(v) bin-length proxy of one slice offset field. + let se_bits = |v: i32| -> u64 { + match v.unsigned_abs() { + 0 => 1, + n => 2 * u64::from(32 - n.leading_zeros()) + 1, + } + }; + // Off (override_flag 0: one bit) vs each (β, tC) offset pair + // (override group: ~3 bits + the two se(v) fields). + let mut best_pic = pre.clone(); + let mut best_cost = ssd(&pre) + input.lambda; + for beta in [-2i32, 0, 2] { + for tc in [-2i32, 0, 2] { + let mut filtered = pre.clone(); + let descs = ctb_deblock_descs(input.shapes, width, height, input.qp, beta, tc); + deblock_picture_full(&mut filtered, input.field, &descs, None, None); + let cost = ssd(&filtered) + input.lambda * (3 + se_bits(beta) + se_bits(tc)); + if cost < best_cost { + best_cost = cost; + best_pic = filtered; + deblock_on = true; + beta_offset_div2 = beta; + tc_offset_div2 = tc; + } + } + } + best_pic + } else { + pre + }; + + // ---- §8.7.3 SAO estimation (per CTB, on the deblocked picture) ---- + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let mut sao_ctbs: Vec = Vec::new(); + let mut grid: Vec = Vec::new(); + if cfg.sao() { + let mut scratch = base.clone(); + sao_ctbs.reserve(ctbs_x * ctbs_y); + grid.reserve(ctbs_x * ctbs_y); + for ctb in 0..ctbs_x * ctbs_y { + let (rx, ry) = (ctb % ctbs_x, ctb / ctbs_x); + let (x0, y0) = (rx * CTB, ry * CTB); + let (cx0, cy0) = (x0 / 2, y0 / 2); + + // Explicit candidate: per-component election. + let mut comps = [SaoComponent::default(); 3]; + let mut explicit_cost = 0u64; + if cfg.sao_luma { + let (c, cost) = choose_luma( + &base, + &mut scratch, + input.src[0], + width, + x0, + y0, + input.lambda, + ); + comps[0] = c; + explicit_cost += cost; + } else { + explicit_cost += + region_ssd(&base, Plane::Luma, input.src[0], width, x0, y0, CTB, CTB); + } + if cfg.sao_chroma { + let ([cb, cr], cost) = choose_chroma( + &base, + &mut scratch, + input.src[1], + input.src[2], + width / 2, + cx0, + cy0, + input.lambda, + ); + comps[1] = cb; + comps[2] = cr; + explicit_cost += cost; + } else { + let (cw, n) = (width / 2, CTB / 2); + explicit_cost += region_ssd(&base, Plane::Cb, input.src[1], cw, cx0, cy0, n, n) + + region_ssd(&base, Plane::Cr, input.src[2], cw, cx0, cy0, n, n); + } + // Declining the available merges costs one bin each. + let decline_bins = u64::from(rx > 0) + u64::from(ry > 0); + explicit_cost += input.lambda * decline_bins; + + let explicit_params = SaoCtbParams { + merge_left: false, + merge_up: false, + components: comps, + }; + let explicit_resolved = ResolvedSao::resolve(&explicit_params, None, None, 0, 0); + + // Whole-CTB merge candidates (inherit ALL components). + let mut best = (explicit_params, explicit_resolved, explicit_cost); + if rx > 0 { + let left = grid[ctb - 1]; + let d = resolved_ctb_dist( + &base, + &mut scratch, + &left, + input, + x0, + y0, + cfg.sao_luma, + cfg.sao_chroma, + ); + let cost = d + input.lambda; + if cost < best.2 { + best = ( + SaoCtbParams { + merge_left: true, + merge_up: false, + components: [SaoComponent::default(); 3], + }, + left, + cost, + ); + } + } + if ry > 0 { + let above = grid[ctb - ctbs_x]; + let d = resolved_ctb_dist( + &base, + &mut scratch, + &above, + input, + x0, + y0, + cfg.sao_luma, + cfg.sao_chroma, + ); + let cost = d + input.lambda * (1 + u64::from(rx > 0)); + if cost < best.2 { + best = ( + SaoCtbParams { + merge_left: false, + merge_up: true, + components: [SaoComponent::default(); 3], + }, + above, + cost, + ); + } + } + + sao_ctbs.push(best.0); + grid.push(best.1); + } + } + + // ---- slice-flag election + the decode-side picture apply ---- + let slice_sao_luma = cfg.sao_luma && grid.iter().any(|r| r.components[0].sao_type_idx != 0); + let slice_sao_chroma = cfg.sao_chroma && grid.iter().any(|r| r.components[1].sao_type_idx != 0); + let out = if slice_sao_luma || slice_sao_chroma { + apply_sao_picture_full( + &base, + &grid, + CTB_LOG2, + 1, + slice_sao_luma, + slice_sao_chroma, + None, + None, + ) + } else { + sao_ctbs.clear(); + base + }; + + let planar = out.to_planar_u8().expect("8-bit planes"); + let (cw, ch) = (width / 2, height / 2); + let y = planar[..width * height].to_vec(); + let cb = planar[width * height..width * height + cw * ch].to_vec(); + let cr = planar[width * height + cw * ch..].to_vec(); + FilteredFrame { + deblock_on, + beta_offset_div2, + tc_offset_div2, + slice_sao_luma, + slice_sao_chroma, + sao_ctbs, + y, + cb, + cr, + } +} + +/// §7.3.8.3 `sao( rx, ry )` — the bin-exact dual of +/// [`crate::slice_data::decode_sao`] for a single-slice, single-tile +/// picture (merge-left available iff `rx > 0`, merge-up iff `ry > 0`). +#[allow(clippy::too_many_arguments)] +pub(crate) fn encode_sao_ctb( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + params: &SaoCtbParams, + rx: usize, + ry: usize, + slice_sao_luma: bool, + slice_sao_chroma: bool, +) { + if rx > 0 { + cabac.encode_decision(w, &mut ctxs.sao_merge_flag[0], u8::from(params.merge_left)); + if params.merge_left { + return; + } + } + if ry > 0 { + cabac.encode_decision(w, &mut ctxs.sao_merge_flag[0], u8::from(params.merge_up)); + if params.merge_up { + return; + } + } + for c_idx in 0..3usize { + let read = (slice_sao_luma && c_idx == 0) || (slice_sao_chroma && c_idx > 0); + if !read { + continue; + } + let comp = ¶ms.components[c_idx]; + if c_idx < 2 { + // sao_type_idx_luma / _chroma: TR cMax 2 — bin 0 + // context-coded, bin 1 bypass. + cabac.encode_decision( + w, + &mut ctxs.sao_type_idx[0], + u8::from(comp.sao_type_idx > 0), + ); + if comp.sao_type_idx > 0 { + cabac.encode_bypass(w, u8::from(comp.sao_type_idx == 2)); + } + } else { + debug_assert_eq!( + comp.sao_type_idx, params.components[1].sao_type_idx, + "SaoTypeIdx[2] inherits cIdx 1 (§7.4.9.3)" + ); + } + if comp.sao_type_idx != 0 { + for &abs in &comp.offset_abs { + // sao_offset_abs: TR cMax 7 (8-bit), all bypass. + for _ in 0..abs.min(SAO_OFFSET_MAX as u32) { + cabac.encode_bypass(w, 1); + } + if (abs as i32) < SAO_OFFSET_MAX { + cabac.encode_bypass(w, 0); + } + } + if comp.sao_type_idx == 1 { + for i in 0..4 { + if comp.offset_abs[i] != 0 { + cabac.encode_bypass(w, comp.offset_sign[i]); + } + } + cabac.encode_bypass_bits(w, u32::from(comp.band_position), 5); + } else if c_idx < 2 { + cabac.encode_bypass_bits(w, u32::from(comp.eo_class), 2); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + use crate::cabac::CabacEngine; + use crate::slice_data::{decode_sao, SliceDataParams}; + + fn sao_params(sao_luma: bool, sao_chroma: bool) -> SliceDataParams { + SliceDataParams { + ctb_log2_size_y: 4, + min_cb_log2_size_y: 4, + max_tb_log2_size_y: 4, + min_tb_log2_size_y: 2, + pic_width_in_luma_samples: 64, + pic_height_in_luma_samples: 64, + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + slice_type_is_i: true, + slice_type_is_b: false, + slice_sao_luma_flag: sao_luma, + slice_sao_chroma_flag: sao_chroma, + transquant_bypass_enabled_flag: false, + cu_qp_delta_enabled_flag: false, + log2_min_cu_qp_delta_size: 4, + cu_chroma_qp_offset_enabled_flag: false, + log2_min_cu_chroma_qp_offset_size: 4, + chroma_qp_offset_list_len_minus1: 0, + amp_enabled_flag: false, + pcm_enabled_flag: false, + log2_min_ipcm_cb_size_y: 3, + log2_max_ipcm_cb_size_y: 5, + pcm_bit_depth_luma: 8, + pcm_bit_depth_chroma: 8, + max_transform_hierarchy_depth_intra: 0, + max_transform_hierarchy_depth_inter: 0, + max_num_merge_cand: 5, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + mvd_l1_zero_flag: false, + sign_data_hiding_enabled_flag: false, + cross_component_prediction_enabled_flag: false, + residual_adaptive_colour_transform_enabled_flag: false, + transform_skip_enabled_flag: false, + log2_max_transform_skip_size: 2, + implicit_rdpcm_enabled_flag: false, + explicit_rdpcm_enabled_flag: false, + transform_skip_context_enabled_flag: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + palette_mode_enabled_flag: false, + palette_max_size: 0, + palette_max_predictor_size: 0, + } + } + + fn band(pos: u8, abs: [u32; 4], sign: [u8; 4]) -> SaoComponent { + SaoComponent { + sao_type_idx: 1, + offset_abs: abs, + offset_sign: sign, + band_position: pos, + eo_class: 0, + } + } + + fn edge(class: u8, abs: [u32; 4]) -> SaoComponent { + SaoComponent { + sao_type_idx: 2, + offset_abs: abs, + offset_sign: [0; 4], + band_position: 0, + eo_class: class, + } + } + + /// Round-trip one CTB's syntax through the write-side dual and the + /// decode-side `decode_sao`, comparing the decoded fields. + fn assert_sao_roundtrip( + params: &SaoCtbParams, + rx: usize, + ry: usize, + sao_luma: bool, + sao_chroma: bool, + ) { + let mut w = BitWriter::new(); + let mut enc = CabacEncoder::new(); + let mut ectx = SliceContexts::init(0, 26); + encode_sao_ctb( + &mut w, &mut enc, &mut ectx, params, rx, ry, sao_luma, sao_chroma, + ); + enc.encode_terminate(&mut w, 1); + let bytes = w.finish(); + + let mut engine = CabacEngine::new(BitReader::new(&bytes)).expect("engine"); + let mut dctx = SliceContexts::init(0, 26); + let got = decode_sao( + &mut engine, + &mut dctx, + &sao_params(sao_luma, sao_chroma), + rx > 0, + ry > 0, + ) + .expect("decode_sao"); + + assert_eq!(got.merge_left, params.merge_left, "merge_left"); + assert_eq!(got.merge_up, params.merge_up, "merge_up"); + if params.merge_left || params.merge_up { + return; + } + for c in 0..3 { + let read = (sao_luma && c == 0) || (sao_chroma && c > 0); + if !read { + continue; + } + assert_eq!(got.components[c], params.components[c], "component {c}"); + } + } + + /// The §7.3.8.3 writer is the exact dual of `decode_sao` across + /// off / band / edge / merge shapes, all flag combinations, and + /// the offset extremes (incl. the TR cMax 7 no-terminator case). + #[test] + fn sao_syntax_roundtrips_through_decode_sao() { + let shapes: Vec<[SaoComponent; 3]> = vec![ + [SaoComponent::default(); 3], + [ + band(8, [1, 2, 3, 4], [0, 1, 0, 1]), + SaoComponent::default(), + SaoComponent::default(), + ], + [ + edge(1, [7, 0, 2, 7]), + edge(3, [1, 1, 1, 1]), + edge(3, [0, 7, 3, 0]), + ], + [ + band(31, [7, 7, 7, 7], [1, 1, 1, 1]), + band(0, [0, 0, 0, 0], [0, 0, 0, 0]), + band(29, [4, 0, 1, 7], [0, 0, 1, 1]), + ], + [ + SaoComponent::default(), + edge(0, [2, 1, 0, 3]), + edge(0, [5, 4, 3, 2]), + ], + ]; + for comps in &shapes { + for (sao_luma, sao_chroma) in [(true, true), (true, false), (false, true)] { + for (rx, ry) in [(0usize, 0usize), (1, 0), (0, 1), (2, 3)] { + let params = SaoCtbParams { + merge_left: false, + merge_up: false, + components: *comps, + }; + assert_sao_roundtrip(¶ms, rx, ry, sao_luma, sao_chroma); + } + } + } + // Merge shapes. + for (ml, mu, rx, ry) in [ + (true, false, 1, 1), + (false, true, 1, 1), + (false, true, 0, 1), + ] { + let params = SaoCtbParams { + merge_left: ml, + merge_up: mu, + components: [SaoComponent::default(); 3], + }; + assert_sao_roundtrip(¶ms, rx, ry, true, true); + } + } + + /// Band estimation on a constant-shift region recovers the shift + /// (a flat +4 error in one band ⇒ offset +4 in that band). + #[test] + fn band_candidate_recovers_flat_shift() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 100); // band 12 + } + } + let src = vec![104u8; 256]; + let cand = band_candidate(&pic, Plane::Luma, &src, 16, 0, 0, 16); + assert_eq!(cand.sao_type_idx, 1); + // Band 12 must be one of the four covered bands, with offset +4. + let covered: Vec = (0..4) + .map(|k| (cand.band_position as usize + k) & 31) + .collect(); + let pos = covered + .iter() + .position(|&b| b == 12) + .expect("band 12 covered"); + assert_eq!(cand.offset_abs[pos], 4); + assert_eq!(cand.offset_sign[pos], 0); + } + + /// Edge estimation classifies against the pre-SAO neighbours and + /// clamps to the §7.4.9.3 inferred signs (categories 3/4 never + /// positive). + #[test] + fn edge_candidate_derives_clamped_offsets() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + // A horizontal comb: odd columns are local minima (category 1 + // for eo_class 0), even columns local maxima (category 4). + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, if x % 2 == 0 { 110 } else { 90 }); + } + } + // Source: flatten toward 100 ⇒ minima want +10 (clamped 7), + // maxima want −10 (clamped −7 ⇒ abs 7). + let src = vec![100u8; 256]; + let cand = edge_candidate(&pic, Plane::Luma, &src, 16, 0, 0, 16, 0); + assert_eq!(cand.sao_type_idx, 2); + assert_eq!(cand.eo_class, 0); + assert_eq!(cand.offset_abs[0], 7, "category 1 (local min) clamped +7"); + assert_eq!(cand.offset_abs[3], 7, "category 4 (local max) clamped −7"); + } + + /// The whole-frame SAO election never worsens the reconstruction: + /// on content with a systematic band error the filtered output is + /// strictly closer to the source, and re-applying the elected + /// parameters through the decode-side picture driver reproduces + /// the returned planes exactly. + #[test] + fn filter_frame_sao_improves_and_matches_decoder_apply() { + let (w, h) = (32usize, 32usize); + // Recon: gradient. Source: recon + 3 (a flat band-offset-able + // error), chroma constant. + let recon_y: Vec = (0..w * h).map(|i| ((i % w) * 4) as u8).collect(); + let src_y: Vec = recon_y.iter().map(|&v| v.saturating_add(3)).collect(); + let recon_c = vec![100u8; w * h / 4]; + let src_c: Vec = vec![102u8; w * h / 4]; + let field = MotionField::new(w, h); + let shapes = vec![ + CtbShape { + part_mode: PartMode::Part2Nx2N, + split_depth1: false, + }; + (w / 16) * (h / 16) + ]; + let input = FilterInput { + width: w, + height: h, + qp: 30, + lambda: 4, + recon: [&recon_y, &recon_c, &recon_c], + src: [&src_y, &src_c, &src_c], + field: &field, + shapes: &shapes, + }; + let out = filter_frame(&input, &LoopFilterCfg::all()); + assert!(out.slice_sao_luma || out.slice_sao_chroma, "SAO elected"); + + let ssd = |a: &[u8], b: &[u8]| -> u64 { + a.iter() + .zip(b.iter()) + .map(|(&x, &y)| { + let d = i64::from(x) - i64::from(y); + (d * d) as u64 + }) + .sum() + }; + let before = ssd(&recon_y, &src_y) + 2 * ssd(&recon_c, &src_c); + let after = ssd(&out.y, &src_y) + ssd(&out.cb, &src_c) + ssd(&out.cr, &src_c); + assert!(after < before, "SAO improves SSD ({after} < {before})"); + + // Decoder-side re-application: resolve the emitted syntax with + // merge inheritance and run the picture driver — byte-exact + // against the returned planes. + let ctbs_x = w / 16; + let mut grid = vec![ResolvedSao::off(); out.sao_ctbs.len()]; + for (i, p) in out.sao_ctbs.iter().enumerate() { + let left = (i % ctbs_x > 0).then(|| grid[i - 1]); + let above = (i / ctbs_x > 0).then(|| grid[i - ctbs_x]); + grid[i] = ResolvedSao::resolve(p, left.as_ref(), above.as_ref(), 0, 0); + } + let pre = planes_to_picture(&recon_y, &recon_c, &recon_c, w, h); + let applied = apply_sao_picture_full( + &pre, + &grid, + 4, + 1, + out.slice_sao_luma, + out.slice_sao_chroma, + None, + None, + ); + let planar = applied.to_planar_u8().expect("8-bit"); + let mut expect = out.y.clone(); + expect.extend_from_slice(&out.cb); + expect.extend_from_slice(&out.cr); + assert_eq!(planar, expect, "decode-side apply reproduces filter_frame"); + } + + /// Deblocking election: on a blocky reconstruction of smooth + /// source content the filter is elected (and the output differs); + /// on a perfect reconstruction it is declined. + #[test] + fn deblock_election_is_distortion_driven() { + let (w, h) = (32usize, 32usize); + // Source: smooth horizontal ramp. + let src_y: Vec = (0..w * h).map(|i| ((i % w) * 3 + 40) as u8).collect(); + // Recon: the ramp quantized to per-16 blocks (strong blocking). + let recon_y: Vec = (0..w * h) + .map(|i| { + let x = (i % w) / 16 * 16 + 8; + (x * 3 + 40) as u8 + }) + .collect(); + let cpl = vec![128u8; w * h / 4]; + let field = MotionField::new(w, h); // all intra ⇒ bS 2 at CB edges + let shapes = vec![ + CtbShape { + part_mode: PartMode::Part2Nx2N, + split_depth1: false, + }; + (w / 16) * (h / 16) + ]; + let input = FilterInput { + width: w, + height: h, + qp: 37, + lambda: 1, + recon: [&recon_y, &cpl, &cpl], + src: [&src_y, &cpl, &cpl], + field: &field, + shapes: &shapes, + }; + let cfg = LoopFilterCfg { + deblocking: true, + sao_luma: false, + sao_chroma: false, + }; + let out = filter_frame(&input, &cfg); + assert!(out.deblock_on, "blocky recon elects deblocking"); + assert_ne!(out.y, recon_y, "deblocking modified the luma plane"); + assert!( + (-2..=2).contains(&out.beta_offset_div2) && (-2..=2).contains(&out.tc_offset_div2), + "elected offsets stay in the swept range" + ); + + // The election is optimal over its candidate set: brute-force + // every (β, tC) pair through the decode-side driver and check + // the elected pair's distortion is the minimum. + let ssd = |a: &[u8], b: &[u8]| -> u64 { + a.iter() + .zip(b.iter()) + .map(|(&x, &y)| { + let d = i64::from(x) - i64::from(y); + (d * d) as u64 + }) + .sum() + }; + let dist_at = |beta: i32, tc: i32| -> u64 { + let mut pic = planes_to_picture(&recon_y, &cpl, &cpl, w, h); + let descs = ctb_deblock_descs(&shapes, w, h, 37, beta, tc); + deblock_picture_full(&mut pic, &field, &descs, None, None); + let planar = pic.to_planar_u8().expect("8-bit"); + ssd(&planar[..w * h], &src_y) + }; + let elected = dist_at(out.beta_offset_div2, out.tc_offset_div2); + for beta in [-2i32, 0, 2] { + for tc in [-2i32, 0, 2] { + // λ == 1 makes the rate term negligible against the + // luma SSD scale of this content. + assert!( + elected <= dist_at(beta, tc) + 16, + "({beta},{tc}) beats the elected pair" + ); + } + } + + // Perfect reconstruction: filtering can only hurt ⇒ declined. + let input2 = FilterInput { + recon: [&src_y, &cpl, &cpl], + src: [&src_y, &cpl, &cpl], + ..input + }; + let out2 = filter_frame(&input2, &cfg); + assert!(!out2.deblock_on, "perfect recon declines deblocking"); + assert_eq!(out2.y, src_y); + } +} diff --git a/vendor/oxideav-h265/src/encoder/nal.rs b/vendor/oxideav-h265/src/encoder/nal.rs new file mode 100644 index 0000000..39456d3 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/nal.rs @@ -0,0 +1,114 @@ +//! NAL-unit encapsulation — the write-side dual of [`crate::nal`]. +//! +//! Wraps an RBSP into a complete NAL unit (the two-byte §7.3.1.2 +//! header + the §7.4.1.1 emulation-prevention escaped payload) and +//! frames NAL units into an Annex B byte stream. + +/// §7.4.1.1 — insert `emulation_prevention_three_byte`s: within the +/// payload, any `00 00` followed by a byte `<= 0x03` becomes +/// `00 00 03 xx` so no start-code prefix can appear inside a NAL unit. +#[must_use] +pub fn escape_rbsp(rbsp: &[u8]) -> Vec { + let mut out = Vec::with_capacity(rbsp.len() + rbsp.len() / 64 + 4); + let mut zero_run = 0usize; + for &b in rbsp { + if zero_run >= 2 && b <= 0x03 { + out.push(0x03); + zero_run = 0; + } + out.push(b); + if b == 0 { + zero_run += 1; + } else { + zero_run = 0; + } + } + out +} + +/// Build a complete coded NAL unit: the §7.3.1.2 two-byte header +/// (`forbidden_zero_bit == 0`, `nal_unit_type`, `nuh_layer_id`, +/// `nuh_temporal_id_plus1 = temporal_id + 1`) followed by the escaped +/// RBSP. +#[must_use] +pub fn nal_unit(nal_unit_type: u8, nuh_layer_id: u8, temporal_id: u8, rbsp: &[u8]) -> Vec { + debug_assert!(nal_unit_type < 64 && nuh_layer_id < 64 && temporal_id < 7); + let b0 = (nal_unit_type << 1) | (nuh_layer_id >> 5); + let b1 = ((nuh_layer_id & 0x1F) << 3) | (temporal_id + 1); + let mut out = vec![b0, b1]; + out.extend(escape_rbsp(rbsp)); + out +} + +/// Frame complete coded NAL units into an Annex B byte stream: a +/// four-byte start code (`00 00 00 01`) before parameter-set / +/// first-of-AU units keeps players happy; this writer simply uses the +/// four-byte form everywhere (§B.1.2 permits leading zeros). +#[must_use] +pub fn annexb(units: &[Vec]) -> Vec { + let mut out = Vec::new(); + for u in units { + out.extend_from_slice(&[0x00, 0x00, 0x00, 0x01]); + out.extend_from_slice(u); + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::nal::{collect_nal_units, strip_emulation_prevention}; + + #[test] + fn escape_inserts_before_low_bytes() { + // 00 00 00 -> 00 00 03 00; 00 00 01 -> 00 00 03 01; 00 00 04 stays. + assert_eq!( + escape_rbsp(&[0, 0, 0, 0, 1]), + vec![0, 0, 3, 0, 0, 3, 1], + "double escape over a zero run" + ); + assert_eq!(escape_rbsp(&[0, 0, 4]), vec![0, 0, 4]); + assert_eq!(escape_rbsp(&[0, 0, 2]), vec![0, 0, 3, 2]); + } + + #[test] + fn escape_roundtrips_through_reader_strip() { + let payloads: [&[u8]; 5] = [ + &[], + &[0, 0, 0, 0, 0, 0], + &[0, 0, 1, 0, 0, 2, 0, 0, 3], + &[0xFF, 0, 0, 0, 0xFF], + &[0, 0], + ]; + for p in payloads { + let escaped = escape_rbsp(p); + assert_eq!(strip_emulation_prevention(&escaped), p, "{p:02x?}"); + // No start code may survive inside the escaped payload. + assert!(!escaped.windows(3).any(|w| w == [0, 0, 1] || w == [0, 0, 0])); + } + } + + #[test] + fn nal_unit_header_roundtrips_through_walker() { + let rbsp = vec![0xAA, 0x00, 0x00, 0x00, 0xBB]; + let unit = nal_unit(19, 0, 0, &rbsp); // IDR_W_RADL + let stream = annexb(&[unit]); + let units = collect_nal_units(&stream).expect("walk"); + assert_eq!(units.len(), 1); + assert_eq!(units[0].header.nal_unit_type, 19); + assert_eq!(units[0].header.nuh_layer_id, 0); + assert_eq!(units[0].header.temporal_id, 0); + assert_eq!(units[0].rbsp, rbsp); + } + + #[test] + fn annexb_frames_multiple_units() { + let a = nal_unit(32, 0, 0, &[0x01]); + let b = nal_unit(33, 0, 0, &[0x02]); + let stream = annexb(&[a, b]); + let units = collect_nal_units(&stream).expect("walk"); + assert_eq!(units.len(), 2); + assert_eq!(units[0].header.nal_unit_type, 32); + assert_eq!(units[1].header.nal_unit_type, 33); + } +} diff --git a/vendor/oxideav-h265/src/encoder/palette_streams.rs b/vendor/oxideav-h265/src/encoder/palette_streams.rs new file mode 100644 index 0000000..43f3aae --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/palette_streams.rs @@ -0,0 +1,1130 @@ +//! Self-built §7.3.8.13 palette-mode conformance stream (test-only). +//! +//! No black-box encoder binary exposes the Screen Content Coding +//! tools, so this module assembles a tiny all-palette Annex B +//! bitstream from this crate's own header writers and CABAC encoder: +//! every 16x16 CTB is one `palette_mode_flag == 1` coding unit, and +//! the per-CTB plans exercise new-entry signalling, predictor reuse +//! (`palette_predictor_run`), explicit-index and copy-above runs, the +//! run-to-end inference, `MaxPaletteIndex == 0` degenerate blocks, +//! `palette_transpose_flag`, and escape samples in BOTH forms — +//! transquant-bypass (FL) and quantized (EG3, at `SliceQpY == 4` +//! where the eq. 8-77 dequantization is exact, keeping the whole +//! stream lossless). +//! +//! The checked-in copy under `tests/fixture_bytes/` is pinned by the +//! tests here: the builder must reproduce its exact bytes and this +//! crate's decoder must reconstruct the planned source planes +//! losslessly (reference-decoder validation notes live in +//! `tests/fixture_bytes/r413-generation-notes.md`). + +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::rdpcm_streams::{write_pps_bypass, write_ptl_rext}; +use crate::palette::{PaletteCu, PalettePredictor}; + +/// One picture's `(Y, Cb, Cr)` planes. +type Planes = (Vec, Vec, Vec); +use crate::scan::traverse; + +/// CTB / coding-block size (16x16, `MinCbSizeY == CtbSizeY`). +const CTB: usize = 16; +/// `SliceQpY` — 4, where escape dequantization (eq. 8-77) is exact: +/// `levelScale[4 % 6] = 64`, shift `4 / 6 = 0`, so +/// `((v * 64) + 32) >> 6 == v`. +const SLICE_QP: i32 = 4; +/// `palette_max_size` signalled in the SPS SCC extension. +const PALETTE_MAX_SIZE: u32 = 7; +/// `delta_palette_max_predictor_size`. +const DELTA_MAX_PREDICTOR: u32 = 9; + +/// §7.3.2.2 — 4:2:0 8-bit SPS (CTB 16, no PCM, SAO off) with an +/// `sps_scc_extension()` enabling palette mode. +fn write_sps_scc(width: usize, height: usize, level_idc: u8, initializers: &[[u16; 3]]) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl_rext(&mut w, level_idc); + w.ue(0); // sps_seq_parameter_set_id + w.ue(1); // chroma_format_idc = 4:2:0 + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + w.put_bit(0); // conformance_window_flag + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(0); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(1); // log2_min_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(0); // amp_enabled_flag + w.put_bit(0); // sample_adaptive_offset_enabled_flag + w.put_bit(0); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(1); // sps_extension_present_flag + w.put_bit(0); // sps_range_extension_flag + w.put_bit(0); // sps_multilayer_extension_flag + w.put_bit(0); // sps_3d_extension_flag + w.put_bit(1); // sps_scc_extension_flag + w.put_bits(0, 4); // sps_extension_4bits + // sps_scc_extension() — §7.3.2.2.3. + w.put_bit(0); // sps_curr_pic_ref_enabled_flag + w.put_bit(1); // palette_mode_enabled_flag + w.ue(PALETTE_MAX_SIZE); // palette_max_size + w.ue(DELTA_MAX_PREDICTOR); // delta_palette_max_predictor_size + if initializers.is_empty() { + w.put_bit(0); // sps_palette_predictor_initializers_present_flag + } else { + w.put_bit(1); // sps_palette_predictor_initializers_present_flag + w.ue(initializers.len() as u32 - 1); // sps_num_..._minus1 + // §7.3.2.2.3: component-major, u(BitDepth) each (8 bits here). + for c in 0..3 { + for e in initializers { + w.put_bits(u32::from(e[c]), 8); + } + } + } + w.put_bits(0, 2); // motion_vector_resolution_control_idc + w.put_bit(0); // intra_boundary_filtering_disabled_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// One planned palette CU: the palette (per component), the target +/// index map (coded coordinates), transpose, bypass and the escape +/// samples (`Some(values per component)` at positions whose index is +/// `MaxPaletteIndex`). +struct CuPlan { + /// Reuse flags into the CURRENT predictor (length = + /// `PredictorPaletteSize` at this CU). + reuse: Vec, + /// Explicitly signalled new entries (per component). + new_entries: [Vec; 3], + /// Escape samples present. + escape_present: bool, + /// `palette_transpose_flag`. + transpose: bool, + /// `cu_transquant_bypass_flag`. + bypass: bool, + /// Target `PaletteIndexMap` (coded coords, `CTB * CTB`). + index_map: Vec, + /// Escape values per component at coded luma coords (only + /// positions whose index equals `MaxPaletteIndex` and pass the + /// §7.3.8.13 4:2:0 phase gate are consulted). + escape_vals: [Vec; 3], +} + +/// Bypass-encode an EG0 value. +fn encode_eg0(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32) { + encode_eg_k(cabac, w, v, 0); +} + +/// §9.3.3.3 dual of `decode_eg_k`. +fn encode_eg_k(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32, k: u32) { + let mut prefix_ones = 0u32; + while (((1u64 << (prefix_ones + 1)) - 1) << k) <= u64::from(v) { + prefix_ones += 1; + } + for _ in 0..prefix_ones { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + let base = ((1u64 << prefix_ones) - 1) << k; + let suffix = u64::from(v) - base; + let bits = prefix_ones + k; + for i in (0..bits).rev() { + cabac.encode_bypass(w, ((suffix >> i) & 1) as u8); + } +} + +/// §9.3.3.6 dual of `decode_tb`. +fn encode_tb(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32, c_max: u32) { + if c_max == 0 { + return; + } + let n = c_max + 1; + let k = 31 - n.leading_zeros(); + let u = (1u32 << (k + 1)) - n; + if v < u { + for i in (0..k).rev() { + cabac.encode_bypass(w, ((v >> i) & 1) as u8); + } + } else { + let val = v + u; + for i in (0..=k).rev() { + cabac.encode_bypass(w, ((val >> i) & 1) as u8); + } + } +} + +/// §9.3.3.14 dual. +fn encode_num_palette_indices_minus1( + cabac: &mut CabacEncoder, + w: &mut BitWriter, + v: u32, + max_palette_index: u32, +) { + let k = 3 + ((max_palette_index + 1) >> 3); + let c_max = 4u32 << k; + if v < c_max { + let q = v >> k; + for _ in 0..q { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + for i in (0..k).rev() { + cabac.encode_bypass(w, ((v >> i) & 1) as u8); + } + } else { + for _ in 0..4 { + cabac.encode_bypass(w, 1); + } + encode_eg_k(cabac, w, v - c_max, k + 1); + } +} + +/// The run segmentation of a target index map: `(copy_above, explicit +/// index or 0, run_minus1)` per run, in scan order. +struct Run { + copy: bool, + index: u8, + len: usize, // PaletteRunMinus1 + 1 +} + +/// Greedy §7.3.8.13-compatible segmentation: maximal runs, preferring +/// copy-above when it is at least as long as the explicit run (and +/// syntactically expressible). +fn segment_runs(index_map: &[u8], n: usize) -> Vec { + let scan = traverse(n); + let area = n * n; + let mut runs: Vec = Vec::new(); + let mut pos = 0usize; + while pos < area { + let at = |p: usize| { + let s = &scan[p]; + index_map[s.y as usize * n + s.x as usize] + }; + let above = |p: usize| { + let s = &scan[p]; + debug_assert!(s.y > 0); + index_map[(s.y as usize - 1) * n + s.x as usize] + }; + let prev_copy = runs.last().is_some_and(|r| r.copy); + // Maximal explicit run of the current index. + let idx = at(pos); + let mut exp_len = 1usize; + while pos + exp_len < area && at(pos + exp_len) == idx { + exp_len += 1; + } + // Maximal copy-above run (when expressible here). + let mut copy_len = 0usize; + if pos >= n && !prev_copy { + while pos + copy_len < area + && scan[pos + copy_len].y > 0 + && at(pos + copy_len) == above(pos + copy_len) + { + copy_len += 1; + } + } + if copy_len >= exp_len && copy_len > 0 { + runs.push(Run { + copy: true, + index: 0, + len: copy_len, + }); + pos += copy_len; + } else { + runs.push(Run { + copy: false, + index: idx, + len: exp_len, + }); + pos += exp_len; + } + } + runs +} + +/// Encode one `palette_coding( )` body for `plan`, mirroring the +/// §7.3.8.13 parse gate-for-gate (panicking if the plan is not +/// syntactically representable), and apply the eq. 8-79 predictor +/// update to `predictor`. +#[allow(clippy::too_many_lines)] +fn encode_palette_cu( + cabac: &mut CabacEncoder, + w: &mut BitWriter, + ctx: &mut SliceContexts, + predictor: &mut PalettePredictor, + plan: &CuPlan, +) -> PaletteCu { + let n = CTB; + let area = n * n; + let predictor_size = predictor.size(); + assert_eq!(plan.reuse.len(), predictor_size); + + // ---- palette_predictor_run ---- + let num_predicted = plan.reuse.iter().filter(|&&r| r).count(); + { + let mut last = -1i64; + let mut emitted = 0usize; + for (i, &r) in plan.reuse.iter().enumerate() { + if !r { + continue; + } + let run = if emitted == 0 { + i as u32 + } else { + (i as i64 - last) as u32 + }; + // run semantics: 0 = reuse at current cursor; >1 = skip + // run-1 then reuse; the value 1 is the terminator, so a + // gap of exactly one entry is encoded as run = 2, etc. + let wire = if emitted == 0 { + if i == 0 { + 0 + } else { + i as u32 + 1 + } + } else { + let gap = (i as i64 - last - 1) as u32; + if gap == 0 { + 0 + } else { + gap + 1 + } + }; + let _ = run; + encode_eg0(cabac, w, wire); + emitted += 1; + last = i as i64; + } + // Terminator when the loop would otherwise continue. + if predictor_size > 0 + && num_predicted < PALETTE_MAX_SIZE as usize + && (emitted == 0 || (last as usize) < predictor_size - 1) + { + encode_eg0(cabac, w, 1); + } + } + + // ---- num_signalled_palette_entries + new entries ---- + let num_signalled = plan.new_entries[0].len(); + if num_predicted < PALETTE_MAX_SIZE as usize { + encode_eg0(cabac, w, num_signalled as u32); + } else { + assert_eq!(num_signalled, 0); + } + for c in 0..3 { + for &v in &plan.new_entries[c] { + cabac.encode_bypass_bits(w, u32::from(v), 8); + } + } + + // ---- CurrentPaletteEntries (eq. 7-82) ---- + let mut palette: [Vec; 3] = Default::default(); + for (c, pal) in palette.iter_mut().enumerate() { + for (i, &r) in plan.reuse.iter().enumerate() { + if r { + pal.push(predictor.entries[c][i]); + } + } + pal.extend_from_slice(&plan.new_entries[c]); + } + let current_size = palette[0].len(); + + // ---- palette_escape_val_present_flag ---- + if current_size != 0 { + cabac.encode_bypass(w, u8::from(plan.escape_present)); + } else { + assert!(plan.escape_present, "empty palette requires escapes"); + } + let max_index = current_size as u32 + u32::from(plan.escape_present) - 1; + + // ---- run segmentation, explicit index list ---- + let runs = segment_runs(&plan.index_map, n); + let explicit: Vec<&Run> = runs.iter().filter(|r| !r.copy).collect(); + let num_indices = explicit.len(); + let final_copy = runs.last().map(|r| r.copy).unwrap_or(false); + // Per-run RAW `palette_idx_idc` values (0 for copy-above runs): + // §9.3.4.2.8 derives the `palette_run_prefix` ctxInc from the + // signalled syntax element, so the run loop below needs the + // pre-eq.-7-84 value, not the plan's final index. + let mut idc_by_run: Vec = vec![0; runs.len()]; + + if max_index > 0 { + encode_num_palette_indices_minus1(cabac, w, num_indices as u32 - 1, max_index); + // The idc list needs the eq. 7-83/7-84 INVERSE adjustment, + // which depends on scan state; walk the runs to derive each + // adjusted idc. + let scan = traverse(n); + let mut adjust = 0u32; + let mut pos = 0usize; + let mut prev_copy = false; + for (run_i, r) in runs.iter().enumerate() { + if !r.copy { + let adjusted_ref = if pos > 0 { + let p = &scan[pos - 1]; + if !prev_copy { + u32::from(plan.index_map[p.y as usize * n + p.x as usize]) + } else { + let c = &scan[pos]; + u32::from(plan.index_map[(c.y as usize - 1) * n + c.x as usize]) + } + } else { + max_index + 1 + }; + let target = u32::from(r.index); + assert_ne!( + target, adjusted_ref, + "explicit index equal to adjustedRefPaletteIndex is not encodable" + ); + let idc = if target > adjusted_ref { + target - 1 + } else { + target + }; + idc_by_run[run_i] = idc; + let c_max = max_index - adjust; + if c_max > 0 { + encode_tb(cabac, w, idc, c_max); + } else { + assert_eq!(idc, 0); + } + adjust = 1; + } + prev_copy = r.copy; + pos += r.len; + } + // copy_above_indices_for_final_run_flag + transpose. + let ctxm = &mut ctx.palette_copy_above_flag[0]; + cabac.encode_decision(w, ctxm, u8::from(final_copy)); + cabac.encode_decision( + w, + &mut ctx.palette_transpose_flag[0], + u8::from(plan.transpose), + ); + } else { + assert_eq!(num_indices, 1, "MaxPaletteIndex 0 has one inferred index"); + assert!(!plan.transpose); + } + + // (delta_qp: cu_qp_delta_enabled == 0 in this stream ⇒ no bins.) + + // ---- run loop ---- + let mut remaining = num_indices; + let mut pos = 0usize; + let mut prev_copy = false; + for (run_i, r) in runs.iter().enumerate() { + // Mirror the parse-side flag presence gates. + if max_index > 0 && pos >= n && !prev_copy { + if remaining > 0 && pos < area - 1 { + cabac.encode_decision(w, &mut ctx.palette_copy_above_flag[0], u8::from(r.copy)); + } else { + let inferred = !(pos == area - 1 && remaining > 0); + assert_eq!(r.copy, inferred, "inferred copy flag must match the plan"); + } + } else { + assert!(!r.copy, "copy-above not expressible at pos {pos}"); + } + // §9.3.4.2.8: the run-prefix ctxInc consumes the RAW + // signalled `palette_idx_idc`, not the final palette index. + let idc_for_ctx = if r.copy { 0 } else { idc_by_run[run_i] }; + if max_index > 0 { + if !r.copy { + remaining -= 1; + } + if remaining > 0 || r.copy != final_copy { + let max_run_minus1 = + area as i64 - pos as i64 - 1 - remaining as i64 - i64::from(final_copy); + assert!(max_run_minus1 >= 0); + let run_minus1 = (r.len - 1) as u32; + assert!(i64::from(run_minus1) <= max_run_minus1); + if max_run_minus1 > 0 { + // palette_run_prefix / suffix. + let c_max = + crate::binarization::palette_run_prefix_tr_cmax(max_run_minus1 as u32); + let (prefix, suffix) = if run_minus1 < 2 { + (run_minus1, None) + } else { + let p = 32 - run_minus1.leading_zeros(); // floor(log2(v)) + 1 + let prefix_offset = 1u32 << (p - 1); + debug_assert!(prefix_offset <= run_minus1); + (p, Some(run_minus1 - prefix_offset)) + }; + // TR prefix: `prefix` ones then a terminating zero + // (omitted at cMax). + for bin_idx in 0..prefix { + emit_run_prefix_bin(cabac, w, ctx, bin_idx, r.copy, idc_for_ctx, 1); + } + if prefix < c_max { + emit_run_prefix_bin(cabac, w, ctx, prefix, r.copy, idc_for_ctx, 0); + } + if let Some(sfx) = suffix { + let prefix_offset = 1u32 << (prefix - 1); + if max_run_minus1 as u32 != prefix_offset { + let c_max_tb = if (prefix_offset << 1) > max_run_minus1 as u32 { + max_run_minus1 as u32 - prefix_offset + } else { + prefix_offset - 1 + }; + encode_tb(cabac, w, sfx, c_max_tb); + } else { + assert_eq!(sfx, 0); + } + } + } else { + assert_eq!(run_minus1, 0); + } + } else { + // RunToEnd inference: the run must actually reach the + // block end. + assert_eq!(pos + r.len, area, "final run must cover the tail"); + } + } + prev_copy = r.copy; + pos += r.len; + } + + // ---- escape values ---- + if plan.escape_present { + let scan = traverse(n); + for c in 0..3usize { + for p in &scan { + let (x, y) = (p.x as usize, p.y as usize); + if u32::from(plan.index_map[y * n + x]) != max_index { + continue; + } + let present = c == 0 || (x % 2 == 0 && y % 2 == 0); + if !present { + continue; + } + let v = u32::from(plan.escape_vals[c][y * n + x]); + if plan.bypass { + cabac.encode_bypass_bits(w, v, 8); + } else { + encode_eg_k(cabac, w, v, 3); + } + } + } + } + + // ---- eq. 8-79 predictor update ---- + let max_pred = (PALETTE_MAX_SIZE + DELTA_MAX_PREDICTOR) as usize; + let mut new_pred: [Vec; 3] = palette.clone(); + let mut new_size = current_size; + for (i, &r) in plan.reuse.iter().enumerate() { + if new_size >= max_pred { + break; + } + if !r { + for (c, np) in new_pred.iter_mut().enumerate() { + np.push(predictor.entries[c][i]); + } + new_size += 1; + } + } + *predictor = PalettePredictor { entries: new_pred }; + + PaletteCu { + n_cbs: n, + palette, + escape_present: plan.escape_present, + transpose: plan.transpose, + index_map: plan.index_map.clone(), + escape_vals: plan.escape_vals.clone(), + cu_qp_delta: None, + cu_chroma_qp_offset: None, + } +} + +fn emit_run_prefix_bin( + cabac: &mut CabacEncoder, + w: &mut BitWriter, + ctx: &mut SliceContexts, + bin_idx: u32, + copy: bool, + idc: u32, + bin: u8, +) { + match crate::binarization::palette_run_prefix_ctx_inc(bin_idx, copy, idc) { + Some(inc) => cabac.encode_decision(w, &mut ctx.palette_run_prefix[inc as usize], bin), + None => cabac.encode_bypass(w, bin), + } +} + +/// The per-CTB plans for a 64x48 picture (4x3 CTBs). +fn cu_plans(predictor_snapshots: &mut Vec) -> Vec { + let n = CTB; + let _ = predictor_snapshots; + let mut plans = Vec::new(); + + // CTB 0: four new colours, horizontal bands (explicit runs only). + plans.push(CuPlan { + reuse: vec![], + new_entries: [ + vec![30, 90, 160, 220], + vec![60, 100, 150, 200], + vec![200, 150, 100, 50], + ], + escape_present: false, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = (y / 4) as u8; + } + } + m + }, + escape_vals: Default::default(), + }); + + // CTB 1: reuse predictor entries 0 and 2, one new colour; + // vertical stripes (row 0 explicit, the rest copy-above runs). + plans.push(CuPlan { + reuse: vec![true, false, true, false], + new_entries: [vec![120], vec![130], vec![140]], + escape_present: false, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = ((x / 2) % 3) as u8; + } + } + m + }, + escape_vals: Default::default(), + }); + + // CTB 2: single colour (MaxPaletteIndex == 0 degenerate: no index + // list, no run coding). + plans.push(CuPlan { + reuse: vec![false, false, true, false, false], + new_entries: [vec![], vec![], vec![]], + escape_present: false, + transpose: false, + bypass: true, + index_map: vec![0u8; n * n], + escape_vals: Default::default(), + }); + + // CTB 3: two colours + BYPASS escapes on a sparse grid. + plans.push(CuPlan { + reuse: vec![true, true, false, false, false], + new_entries: [vec![], vec![], vec![]], + escape_present: true, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = u8::from(y >= 8); + } + } + // Escape index = MaxPaletteIndex = 2, at even positions. + m[2 * n + 2] = 2; + m[2 * n + 3] = 2; // odd x: luma escape only (4:2:0 gate) + m[10 * n + 6] = 2; + m + }, + escape_vals: { + let mut y_v = vec![0u16; n * n]; + let mut cb_v = vec![0u16; n * n]; + let mut cr_v = vec![0u16; n * n]; + y_v[2 * n + 2] = 250; + y_v[2 * n + 3] = 17; + y_v[10 * n + 6] = 3; + cb_v[2 * n + 2] = 77; + cr_v[2 * n + 2] = 99; + cb_v[10 * n + 6] = 5; + cr_v[10 * n + 6] = 240; + [y_v, cb_v, cr_v] + }, + }); + + // CTB 4: transpose stripes (coded rows become picture columns). + plans.push(CuPlan { + reuse: vec![true, true, true, false, false], + new_entries: [vec![], vec![], vec![]], + escape_present: false, + transpose: true, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = ((y / 3) % 3) as u8; + } + } + m + }, + escape_vals: Default::default(), + }); + + // CTB 5: QUANTIZED escapes (non-bypass CU at SliceQpY 4 — exact). + plans.push(CuPlan { + reuse: vec![true, false, false, false, false], + new_entries: [vec![10], vec![20], vec![30]], + escape_present: true, + transpose: false, + bypass: false, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = u8::from((x + y) % 4 == 0); + } + } + // A 2x2-aligned escape block. + m[4 * n + 4] = 2; + m[12 * n + 8] = 2; + m + }, + escape_vals: { + let mut y_v = vec![0u16; n * n]; + let mut cb_v = vec![0u16; n * n]; + let mut cr_v = vec![0u16; n * n]; + y_v[4 * n + 4] = 133; + y_v[12 * n + 8] = 255; + cb_v[4 * n + 4] = 44; + cr_v[4 * n + 4] = 211; + cb_v[12 * n + 8] = 0; + cr_v[12 * n + 8] = 128; + [y_v, cb_v, cr_v] + }, + }); + + // CTBs 6..11: diagonal two-colour texture cycling reuse patterns + // (keeps the predictor evolving). + for k in 0..6usize { + plans.push(CuPlan { + reuse: vec![], // filled at build time (reuse first two) + new_entries: Default::default(), + escape_present: false, + transpose: k % 2 == 1, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = u8::from((x + y + k) % 8 < 4); + } + } + m + }, + escape_vals: Default::default(), + }); + } + + plans +} + +/// Build the palette conformance stream: VPS + SPS(SCC) + PPS + one +/// all-palette IDR picture (64x48). Returns the Annex B bytes and the +/// expected (lossless) decoded planes. +pub(crate) fn build_palette_stream() -> (Vec, Planes) { + let (width, height) = (64usize, 48usize); + let (cw, ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + + let mut w = BitWriter::new(); + // ---- slice_segment_header( ) ---- + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(2); // slice_type = I + w.se(SLICE_QP - 26); // slice_qp_delta + w.rbsp_trailing_bits(); + + let mut cabac = CabacEncoder::new(); + let mut ctx = SliceContexts::init(init_type(2, false), SLICE_QP); + let mut predictor = PalettePredictor::default(); + + let mut y_plane = vec![0u8; width * height]; + let mut cb_plane = vec![0u8; cw * ch]; + let mut cr_plane = vec![0u8; cw * ch]; + + let mut snapshots = Vec::new(); + let mut plans = cu_plans(&mut snapshots); + for (ctb, plan) in plans.iter_mut().enumerate() { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + + // Late-bound reuse vectors for the tail CTBs: reuse the first + // two predictor entries. + if ctb >= 6 { + let mut reuse = vec![false; predictor.size()]; + if reuse.len() >= 2 { + reuse[0] = true; + reuse[1] = true; + } + plan.reuse = reuse; + } + + // ---- coding_unit( ) prelude ---- + cabac.encode_decision( + &mut w, + &mut ctx.cu_transquant_bypass_flag[0], + u8::from(plan.bypass), + ); + // palette_mode_flag = 1. + cabac.encode_decision(&mut w, &mut ctx.palette_mode_flag[0], 1); + + let cu = encode_palette_cu(&mut cabac, &mut w, &mut ctx, &mut predictor, plan); + + // Reference reconstruction into the expected planes (§8.4.4.2.7 + // with the exact-at-QP-4 escape dequantization). + crate::palette::reconstruct_palette_component( + &cu, + 0, + 1, + 1, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + y_plane[(y0 + y) * width + x0 + x] = v as u8; + }, + ); + crate::palette::reconstruct_palette_component( + &cu, + 1, + 2, + 2, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + cb_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8; + }, + ); + crate::palette::reconstruct_palette_component( + &cu, + 2, + 2, + 2, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + cr_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8; + }, + ); + + cabac.encode_terminate(&mut w, u8::from(ctb == 11)); + } + w.align_zero(); + let slice = w.finish(); + + let units = vec![ + nal_unit(32, 0, 0, &{ + // Reuse the Rext VPS shape (PTL profile bits are opaque to + // the decode path). + let mut vw = BitWriter::new(); + vw.put_bits(0, 4); + vw.put_bit(1); + vw.put_bit(1); + vw.put_bits(0, 6); + vw.put_bits(0, 3); + vw.put_bit(1); + vw.put_bits(0xFFFF, 16); + write_ptl_rext(&mut vw, 30); + vw.put_bit(1); + vw.ue(1); + vw.ue(0); + vw.ue(0); + vw.put_bits(0, 6); + vw.ue(0); + vw.put_bit(0); + vw.put_bit(0); + vw.rbsp_trailing_bits(); + vw.finish() + }), + nal_unit(33, 0, 0, &write_sps_scc(width, height, 30, &[])), + nal_unit(34, 0, 0, &write_pps_bypass()), + nal_unit(20, 0, 0, &slice), // IDR_N_LP + ]; + (annexb(&units), (y_plane, cb_plane, cr_plane)) +} + +/// Second pin: §9.3.2.3 SPS palette predictor INITIALIZERS + per- +/// independent-slice predictor re-initialization. A 32x32 picture +/// (2x2 CTBs) in TWO independent slices; the SPS carries four +/// predictor initializer entries, so every slice starts with a +/// four-entry predictor. CU plans: reuse-only palettes from the +/// initializers, a MaxPaletteIndex-0 block at the second slice's +/// start (proving the re-init), and a 256-run diagonal block whose +/// index count exercises the §9.3.3.14 all-ones escape suffix. +pub(crate) fn build_palette_init_stream() -> (Vec, Planes) { + const INIT: [[u16; 3]; 4] = [[25, 60, 190], [80, 90, 100], [140, 120, 70], [200, 180, 40]]; + let (width, height) = (32usize, 32usize); + let (cw, ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let n = CTB; + + let base_predictor = PalettePredictor { + entries: [ + INIT.iter().map(|e| e[0]).collect(), + INIT.iter().map(|e| e[1]).collect(), + INIT.iter().map(|e| e[2]).collect(), + ], + }; + + let plans: Vec = vec![ + // CTB 0 (slice 1): reuse initializer entries 0 and 2; stripes. + CuPlan { + reuse: vec![true, false, true, false], + new_entries: Default::default(), + escape_present: false, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = u8::from((x / 4) % 2 == 1); + } + } + m + }, + escape_vals: Default::default(), + }, + // CTB 1 (slice 1): predictor evolved to [i0, i2, i1, i3]; + // reuse the outer two; horizontal bands. + CuPlan { + reuse: vec![true, false, false, true], + new_entries: Default::default(), + escape_present: false, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = u8::from(y >= 8); + } + } + m + }, + escape_vals: Default::default(), + }, + // CTB 2 (slice 2, FIRST CU): the predictor must be the + // re-initialized four initializer entries again — reuse entry + // 1 only (MaxPaletteIndex == 0 degenerate block). + CuPlan { + reuse: vec![false, true, false, false], + new_entries: Default::default(), + escape_present: false, + transpose: false, + bypass: true, + index_map: vec![0u8; n * n], + escape_vals: Default::default(), + }, + // CTB 3 (slice 2): reuse all four evolved entries; diagonal + // (x + y) % 4 texture — 256 single-sample explicit runs, so + // num_palette_indices_minus1 = 255 takes the §9.3.3.14 + // all-ones prefix + EGk escape. + CuPlan { + reuse: vec![true, true, true, true], + new_entries: Default::default(), + escape_present: false, + transpose: false, + bypass: true, + index_map: { + let mut m = vec![0u8; n * n]; + for y in 0..n { + for x in 0..n { + m[y * n + x] = ((x + y) % 4) as u8; + } + } + m + }, + escape_vals: Default::default(), + }, + ]; + + let mut y_plane = vec![0u8; width * height]; + let mut cb_plane = vec![0u8; cw * ch]; + let mut cr_plane = vec![0u8; cw * ch]; + + // Two independent slices: CTBs [0, 1] and [2, 3]. + let mut slice_rbsps: Vec> = Vec::new(); + for (slice_idx, ctbs) in [[0usize, 1], [2, 3]].iter().enumerate() { + let mut w = BitWriter::new(); + let first = slice_idx == 0; + w.put_bit(u8::from(first)); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + if !first { + // slice_segment_address: Ceil(Log2(4)) = 2 bits. + w.put_bits(ctbs[0] as u32, 2); + } + w.ue(2); // slice_type = I + w.se(SLICE_QP - 26); // slice_qp_delta + w.rbsp_trailing_bits(); + + let mut cabac = CabacEncoder::new(); + let mut ctx = SliceContexts::init(init_type(2, false), SLICE_QP); + // §9.3.2.3 — every independent slice re-initializes the + // predictor from the SPS initializers. + let mut predictor = base_predictor.clone(); + + for &ctb in ctbs { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let plan = &plans[ctb]; + cabac.encode_decision( + &mut w, + &mut ctx.cu_transquant_bypass_flag[0], + u8::from(plan.bypass), + ); + cabac.encode_decision(&mut w, &mut ctx.palette_mode_flag[0], 1); + let cu = encode_palette_cu(&mut cabac, &mut w, &mut ctx, &mut predictor, plan); + crate::palette::reconstruct_palette_component( + &cu, + 0, + 1, + 1, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + y_plane[(y0 + y) * width + x0 + x] = v as u8; + }, + ); + crate::palette::reconstruct_palette_component( + &cu, + 1, + 2, + 2, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + cb_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8; + }, + ); + crate::palette::reconstruct_palette_component( + &cu, + 2, + 2, + 2, + SLICE_QP, + 8, + plan.bypass, + |x, y, v| { + cr_plane[(y0 / 2 + y) * cw + x0 / 2 + x] = v as u8; + }, + ); + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs[1])); + } + w.align_zero(); + slice_rbsps.push(w.finish()); + } + + let mut units = vec![ + nal_unit(32, 0, 0, &{ + let mut vw = BitWriter::new(); + vw.put_bits(0, 4); + vw.put_bit(1); + vw.put_bit(1); + vw.put_bits(0, 6); + vw.put_bits(0, 3); + vw.put_bit(1); + vw.put_bits(0xFFFF, 16); + write_ptl_rext(&mut vw, 30); + vw.put_bit(1); + vw.ue(1); + vw.ue(0); + vw.ue(0); + vw.put_bits(0, 6); + vw.ue(0); + vw.put_bit(0); + vw.put_bit(0); + vw.rbsp_trailing_bits(); + vw.finish() + }), + nal_unit(33, 0, 0, &write_sps_scc(width, height, 30, &INIT)), + nal_unit(34, 0, 0, &write_pps_bypass()), + ]; + for rbsp in &slice_rbsps { + units.push(nal_unit(20, 0, 0, rbsp)); // IDR_N_LP + } + (annexb(&units), (y_plane, cb_plane, cr_plane)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sequence::decode_annexb_sequence; + + /// SPS predictor initializers + two independent slices: the + /// second slice's first CU must see the re-initialized + /// four-entry predictor (§9.3.2.3), not the first slice's + /// evolved one. + #[test] + fn palette_initializer_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_palette_init_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r413-palette-init.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit planes"), + expected, + "lossless palette decode with SPS initializers" + ); + } + + /// The checked-in stream bytes are exactly what the builder + /// produces, and this crate's decoder reconstructs the planned + /// palette content losslessly (predictor reuse, explicit / + /// copy-above runs, run-to-end, MaxPaletteIndex 0, transpose, and + /// bypass + quantized escapes). + #[test] + fn palette_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_palette_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r413-palette.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit planes"), + expected, + "lossless palette decode" + ); + } +} diff --git a/vendor/oxideav-h265/src/encoder/pcm.rs b/vendor/oxideav-h265/src/encoder/pcm.rs new file mode 100644 index 0000000..5dd84f3 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/pcm.rs @@ -0,0 +1,1150 @@ +//! PCM-only IDR encoder — the crate's encoder bootstrap. +//! +//! Emits fully conformant Main-profile Annex B access units in which +//! every coding unit is a `pcm_flag == 1` PCM block (§7.3.8.7): the +//! samples ride uncompressed inside the slice data, so the decode is +//! exactly lossless. The geometry is fixed at the simplest legal +//! shape: `CtbSizeY == MinCbSizeY == 16` with the PCM size range +//! pinned to 16 (`Log2MinIpcmCbSizeY == Log2MaxIpcmCbSizeY == 4`), so +//! every CTB is one unsplit coding unit and the whole §7.3.8 syntax +//! walk per CTB is: `part_mode` (one context-coded bin, `PART_2Nx2N`), +//! `pcm_flag` (a §9.3.5.6 terminate bin), the `pcm_alignment_zero_bit` +//! run, the raw §7.3.8.7 sample payload, the §9.3.5.2 engine re-init, +//! and `end_of_slice_segment_flag`. +//! +//! Every picture is an IDR (`IDR_N_LP`) with in-band VPS/SPS/PPS, so +//! the stream is seekable anywhere and decoder-stateless. 4:2:0 8-bit +//! only; picture dimensions must be multiples of 16 (the CTB size — +//! this bootstrap writes no conformance-window cropping). +//! +//! In-loop filters are neutralized the conformant way: SAO off in the +//! SPS, deblocking disabled in the PPS, and +//! `pcm_loop_filter_disabled_flag == 1` — a PCM-only picture +//! reconstructs to the raw samples bit for bit. + +use crate::availability::{PictureTiling, TilingParams}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::nal::{annexb, nal_unit}; + +/// The fixed CTB / coding-block / PCM-block log2 size of this encoder. +const CTB_LOG2: u32 = 4; +/// The fixed CTB size (16). +const CTB: usize = 1 << CTB_LOG2; +/// `SliceQpY` written in every slice header (`slice_qp_delta == 0` +/// over `init_qp_minus26 == 0`). PCM blocks carry no residual, so the +/// QP only seeds context initialization. +const SLICE_QP: i32 = 26; + +/// Per-AU shape options for the PCM encoder. +#[derive(Debug, Clone)] +pub struct PcmAuOptions { + /// Number of slice segments (1 = a single independent segment; + /// more = one independent + N−1 dependent segments). Ignored when + /// [`Self::independent_slices`] is non-empty. + pub segments: usize, + /// Independent slices as `(start_ctb, slice_loop_filter_across_ + /// slices_enabled_flag)` pairs (sorted, first start 0). Empty = + /// the [`Self::segments`] split. Heterogeneous per-slice flags + /// exercise the §8.7.2.1 / §8.7.3.2 per-slice boundary gates. + pub independent_slices: Vec<(usize, bool)>, + /// Enable the §8.7.2 deblocking filter (PPS + /// `pps_deblocking_filter_disabled_flag == 0`). With every CU a + /// PCM block and `pcm_loop_filter_disabled_flag == 1`, a + /// conforming decoder must leave all samples untouched — this + /// exercises the §8.7.2.5.4 `nDp`/`nDq` PCM suppression. + pub deblocking: bool, + /// Enable luma band-offset SAO (SPS SAO on, + /// `slice_sao_luma_flag == 1`, per-CTB §7.3.8.3 band parameters + /// with non-zero offsets). + pub sao_luma_band: bool, + /// Enable luma vertical-class edge-offset SAO (`sao_type_idx_luma + /// == 2`, `sao_eo_class_luma == 1`): the classification reads + /// above / below neighbours, exercising the §8.7.3.2 cross-slice + /// availability at horizontal slice boundaries. Mutually exclusive + /// with [`Self::sao_luma_band`]. + pub sao_luma_eo_vertical: bool, + /// `pcm_loop_filter_disabled_flag` (§7.4.3.2.1). `false` lets the + /// enabled loop filters modify the PCM samples like any other CU's. + pub pcm_loop_filter_disabled: bool, + /// Tile grid as `(columns, rows)` — `tiles_enabled_flag == 1` with + /// `uniform_spacing_flag == 1` and + /// `loop_filter_across_tiles_enabled_flag == 0`. The picture is + /// coded as ONE slice segment whose CTBs walk the §6.5.1 tile scan: + /// every tile is its own §7.3.8.1 subset (`end_of_subset_one_bit` + + /// byte alignment between tiles, §9.3.2.2 context re-initialization + /// at each tile start) and the slice header carries the §7.4.7.1 + /// `entry_point_offset_minus1[]` block. Requires `columns * rows >= + /// 2`; incompatible with multi-segment / SAO options. + pub tiles: Option<(u32, u32)>, +} + +impl Default for PcmAuOptions { + fn default() -> Self { + Self { + segments: 1, + independent_slices: Vec::new(), + deblocking: false, + sao_luma_band: false, + sao_luma_eo_vertical: false, + pcm_loop_filter_disabled: true, + tiles: None, + } + } +} + +/// Errors from the PCM encoder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PcmEncodeError { + /// Width or height is zero or not a multiple of the 16-sample CTB. + BadDimensions { + /// Requested luma width. + width: usize, + /// Requested luma height. + height: usize, + }, + /// A supplied plane's length does not match the 4:2:0 geometry. + PlaneSize { + /// Which plane (`"y"`, `"cb"`, `"cr"`). + plane: &'static str, + /// Required sample count. + expected: usize, + /// Supplied sample count. + got: usize, + }, +} + +impl core::fmt::Display for PcmEncodeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::BadDimensions { width, height } => write!( + f, + "PCM encoder requires nonzero dimensions that are multiples of 16, got {width}x{height}" + ), + Self::PlaneSize { + plane, + expected, + got, + } => write!(f, "{plane} plane has {got} samples, expected {expected}"), + } + } +} + +impl std::error::Error for PcmEncodeError {} + +/// Table A.8 — pick the smallest `general_level_idc` whose `MaxLumaPs` +/// covers the picture. (A PCM payload can exceed a level's bit-rate +/// ceilings for large / high-rate content; this bootstrap levels by +/// luma picture size, the binding constraint for its intended +/// small-picture use.) +pub(crate) fn level_idc_for(luma_ps: usize) -> u8 { + const LEVELS: [(usize, u8); 9] = [ + (36_864, 30), // 1 + (122_880, 60), // 2 + (245_760, 63), // 2.1 + (552_960, 90), // 3 + (983_040, 93), // 3.1 + (2_228_224, 120), // 4 + (8_912_896, 150), // 5 + (35_651_584, 180), // 6 + (usize::MAX, 186), // 6.2 + ]; + LEVELS + .iter() + .find(|(max_ps, _)| luma_ps <= *max_ps) + .map(|&(_, idc)| idc) + .unwrap_or(186) +} + +/// Table A.8 — the smallest `general_level_idc` whose `MaxTileCols` / +/// `MaxTileRows` cover the requested tile grid (§A.4.2 item f: +/// `num_tile_columns_minus1 < MaxTileCols`, `num_tile_rows_minus1 < +/// MaxTileRows`). This bootstrap's tiny tiles can undercut the +/// 256-sample minimum tile-column width; the level is chosen by tile +/// count, the constraint a decoder actually dispatches on. +fn level_idc_for_tiles(cols: u32, rows: u32) -> u8 { + const LEVELS: [(u32, u32, u8); 6] = [ + (1, 1, 30), // 1 .. 2.1 + (2, 2, 90), // 3 + (3, 3, 93), // 3.1 + (5, 5, 120), // 4 / 4.1 + (10, 11, 150), // 5 .. 5.2 + (20, 22, 180), // 6 .. 6.2 + ]; + LEVELS + .iter() + .find(|&&(c, r, _)| cols <= c && rows <= r) + .map(|&(_, _, idc)| idc) + .unwrap_or(180) +} + +/// §7.3.3 `profile_tier_level( 1, 0 )` — Main profile, Main tier. +pub(crate) fn write_ptl(w: &mut BitWriter, level_idc: u8) { + w.put_bits(0, 2); // general_profile_space + w.put_bit(0); // general_tier_flag + w.put_bits(1, 5); // general_profile_idc = 1 (Main) + // general_profile_compatibility_flag[0..32]: Main (1) is also + // decodable by Main 10 (2) decoders. + let mut compat: u32 = 0; + compat |= 1 << (31 - 1); // flag[1] — Main + compat |= 1 << (31 - 2); // flag[2] — Main 10 + w.put_bits(compat, 32); + w.put_bit(1); // general_progressive_source_flag + w.put_bit(0); // general_interlaced_source_flag + w.put_bit(1); // general_non_packed_constraint_flag + w.put_bit(1); // general_frame_only_constraint_flag + // Main profile: general_reserved_zero_43bits. + w.put_bits(0, 32); + w.put_bits(0, 11); + // Profile 1: general_inbld_flag = 0. + w.put_bit(0); + w.put_bits(u32::from(level_idc), 8); // general_level_idc + // max_sub_layers_minus1 == 0: no sub-layer PTL syntax. +} + +/// §7.3.2.1 — the minimal single-layer VPS. +pub(crate) fn write_vps(level_idc: u8) -> Vec { + write_vps_cfg(level_idc, 1, 0) +} + +/// [`write_vps`] with explicit `vps_max_dec_pic_buffering_minus1[0]` / +/// `vps_max_num_reorder_pics[0]` (the hierarchical-B encoder holds +/// more references and reorders output). +pub(crate) fn write_vps_cfg( + level_idc: u8, + max_dec_pic_buffering_minus1: u32, + max_num_reorder_pics: u32, +) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // vps_video_parameter_set_id + w.put_bit(1); // vps_base_layer_internal_flag + w.put_bit(1); // vps_base_layer_available_flag + w.put_bits(0, 6); // vps_max_layers_minus1 + w.put_bits(0, 3); // vps_max_sub_layers_minus1 + w.put_bit(1); // vps_temporal_id_nesting_flag + w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits + write_ptl(&mut w, level_idc); + w.put_bit(1); // vps_sub_layer_ordering_info_present_flag + w.ue(max_dec_pic_buffering_minus1); // vps_max_dec_pic_buffering_minus1[0] + w.ue(max_num_reorder_pics); // vps_max_num_reorder_pics[0] + w.ue(0); // vps_max_latency_increase_plus1[0] + w.put_bits(0, 6); // vps_max_layer_id + w.ue(0); // vps_num_layer_sets_minus1 + w.put_bit(0); // vps_timing_info_present_flag + w.put_bit(0); // vps_extension_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.2 — the fixed-geometry SPS (4:2:0, 8-bit, CTB 16, PCM on). +fn write_sps( + width: usize, + height: usize, + level_idc: u8, + sao_enabled: bool, + pcm_loop_filter_disabled: bool, +) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl(&mut w, level_idc); + w.ue(0); // sps_seq_parameter_set_id + w.ue(1); // chroma_format_idc = 4:2:0 + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + w.put_bit(0); // conformance_window_flag + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(0); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(0); // amp_enabled_flag + w.put_bit(u8::from(sao_enabled)); // sample_adaptive_offset_enabled_flag + w.put_bit(1); // pcm_enabled_flag + w.put_bits(7, 4); // pcm_sample_bit_depth_luma_minus1 (8-bit) + w.put_bits(7, 4); // pcm_sample_bit_depth_chroma_minus1 + w.ue(CTB_LOG2 - 3); // log2_min_pcm_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_pcm_luma_coding_block_size + w.put_bit(u8::from(pcm_loop_filter_disabled)); // pcm_loop_filter_disabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(0); // sps_extension_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.3 — the all-defaults PPS (deblocking disabled), optionally +/// with a uniform tile grid (`tiles_enabled_flag == 1`, +/// `uniform_spacing_flag == 1`, +/// `loop_filter_across_tiles_enabled_flag == 0`). +pub(crate) fn write_pps( + dependent_slice_segments_enabled: bool, + deblocking_enabled: bool, + tiles: Option<(u32, u32)>, +) -> Vec { + write_pps_lf( + dependent_slice_segments_enabled, + deblocking_enabled, + false, + tiles, + ) +} + +/// [`write_pps`] with `deblocking_filter_override_enabled_flag` +/// control: the loop-filter encoders write the PPS with +/// `pps_deblocking_filter_disabled_flag == 1` + +/// `deblocking_filter_override_enabled_flag == 1` so every slice +/// elects deblocking on/off itself (§7.3.6.1 override group). +pub(crate) fn write_pps_lf( + dependent_slice_segments_enabled: bool, + deblocking_enabled: bool, + deblocking_override_enabled: bool, + tiles: Option<(u32, u32)>, +) -> Vec { + let mut w = BitWriter::new(); + w.ue(0); // pps_pic_parameter_set_id + w.ue(0); // pps_seq_parameter_set_id + w.put_bit(u8::from(dependent_slice_segments_enabled)); // dependent_slice_segments_enabled_flag + w.put_bit(0); // output_flag_present_flag + w.put_bits(0, 3); // num_extra_slice_header_bits + w.put_bit(0); // sign_data_hiding_enabled_flag + w.put_bit(0); // cabac_init_present_flag + w.ue(0); // num_ref_idx_l0_default_active_minus1 + w.ue(0); // num_ref_idx_l1_default_active_minus1 + w.se(SLICE_QP - 26); // init_qp_minus26 + w.put_bit(0); // constrained_intra_pred_flag + w.put_bit(0); // transform_skip_enabled_flag + w.put_bit(0); // cu_qp_delta_enabled_flag + w.se(0); // pps_cb_qp_offset + w.se(0); // pps_cr_qp_offset + w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag + w.put_bit(0); // weighted_pred_flag + w.put_bit(0); // weighted_bipred_flag + w.put_bit(0); // transquant_bypass_enabled_flag + w.put_bit(u8::from(tiles.is_some())); // tiles_enabled_flag + w.put_bit(0); // entropy_coding_sync_enabled_flag + if let Some((cols, rows)) = tiles { + w.ue(cols - 1); // num_tile_columns_minus1 + w.ue(rows - 1); // num_tile_rows_minus1 + w.put_bit(1); // uniform_spacing_flag + w.put_bit(0); // loop_filter_across_tiles_enabled_flag + } + w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag + w.put_bit(1); // deblocking_filter_control_present_flag + w.put_bit(u8::from(deblocking_override_enabled)); // deblocking_filter_override_enabled_flag + w.put_bit(u8::from(!deblocking_enabled)); // pps_deblocking_filter_disabled_flag + if deblocking_enabled { + w.se(0); // pps_beta_offset_div2 + w.se(0); // pps_tc_offset_div2 + } + w.put_bit(0); // pps_scaling_list_data_present_flag + w.put_bit(0); // lists_modification_present_flag + w.ue(0); // log2_parallel_merge_level_minus2 + w.put_bit(0); // slice_segment_header_extension_present_flag + w.put_bit(0); // pps_extension_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.6.1 + §7.3.8.1 — the picture's slice segments: one +/// independent I-slice segment followed by `segments − 1` dependent +/// slice segments (§7.4.7.1 inheritance), every CTB a PCM coding +/// unit. Returns one RBSP per segment. +/// +/// The CABAC context variables carry across the segment boundary per +/// §9.3.1 / §9.3.2.4 (`TableStateIdxDs` storage at each segment's +/// `end_of_slice_segment_flag == 1`, §9.3.2.5 synchronization at the +/// next dependent segment's start) — each segment gets a fresh +/// §9.3.5.2 arithmetic engine over the shared context state. +fn write_idr_slice_segments( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + opts: &PcmAuOptions, +) -> Vec> { + let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical; + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let total = ctbs_x * ctbs_y; + // Ceil(Log2(PicSizeInCtbsY)) — the slice_segment_address width. + let addr_bits = (usize::BITS - (total - 1).leading_zeros()).max(1) as u8; + + // Segment plan: (start_ctb, Some(across_flag) for an independent + // slice header / None for a dependent segment). + let plan: Vec<(usize, Option)> = if opts.independent_slices.is_empty() { + // Even split; segment 0 independent, the rest dependent. + let seg_len = total.div_ceil(opts.segments); + (0..opts.segments) + .map(|i| (i * seg_len, (i == 0).then_some(true))) + .collect() + } else { + opts.independent_slices + .iter() + .map(|&(start, across)| (start, Some(across))) + .collect() + }; + let dependent_mode = opts.independent_slices.is_empty() && opts.segments > 1; + + // initType 0 (I slice, equation 9-7), SliceQpY = 26. Carried across + // dependent segments (§9.3.2.4 / §9.3.2.5); re-initialized at each + // independent slice. + let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + // Start CTB of the current independent slice (SAO merge / left + // availability is denied across independent slices). + let mut cur_slice_start = 0usize; + + let mut out = Vec::with_capacity(plan.len()); + for (seg_idx, &(start, indep)) in plan.iter().enumerate() { + let end = plan.get(seg_idx + 1).map_or(total, |&(next, _)| next); + let mut w = BitWriter::new(); + + // ---- slice_segment_header() ---- + let first = seg_idx == 0; + w.put_bit(u8::from(first)); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + if !first { + if dependent_mode { + w.put_bit(1); // dependent_slice_segment_flag + } + w.put_bits(start as u32, addr_bits); // slice_segment_address + } + if let Some(across) = indep { + // Independent slice: fresh CABAC contexts (§9.3.2.2) and a + // full slice-level header. + ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + cur_slice_start = start; + w.ue(2); // slice_type = I + if sao { + // SPS SAO enabled: the slice SAO flags are present. + w.put_bit(1); // slice_sao_luma_flag + w.put_bit(0); // slice_sao_chroma_flag (4:2:0 present) + } + w.se(SLICE_QP - 26); // slice_qp_delta + if opts.deblocking || sao { + // §7.3.6.1 gate: pps_loop_filter_across_slices == 1 and + // (SAO on or deblocking not disabled). + w.put_bit(u8::from(across)); // slice_loop_filter_across_slices_enabled_flag + } + } + // No tiles / WPP: no entry points. No header extension. + w.rbsp_trailing_bits(); // byte_alignment() before slice data + + // ---- slice_segment_data() ---- + let mut cabac = CabacEncoder::new(); + for addr in start..end { + let x0 = (addr % ctbs_x) * CTB; + let y0 = (addr / ctbs_x) * CTB; + if sao { + // §7.3.8.3 sao( rx, ry ): decline the available merges + // (left / above must lie in the same slice + tile), + // then explicit luma parameters. + let (rx, ry) = (addr % ctbs_x, addr / ctbs_x); + if rx > 0 && addr > cur_slice_start { + cabac.encode_decision(&mut w, &mut ctxs.sao_merge_flag[0], 0); + } + if ry > 0 && addr - ctbs_x >= cur_slice_start { + cabac.encode_decision(&mut w, &mut ctxs.sao_merge_flag[0], 0); + } + if opts.sao_luma_band { + // sao_type_idx_luma = 1 (band): TR bins "1" (ctx), + // "0" (bypass). + cabac.encode_decision(&mut w, &mut ctxs.sao_type_idx[0], 1); + cabac.encode_bypass(&mut w, 0); + // sao_offset_abs[0][i] — TR(cMax 7, bypass): values + // 1, 2, 3, 4. + for v in 1..=4u32 { + for _ in 0..v { + cabac.encode_bypass(&mut w, 1); + } + cabac.encode_bypass(&mut w, 0); // v < cMax terminator + } + // sao_offset_sign[0][i]: +, −, +, −. + for sign in [0u8, 1, 0, 1] { + cabac.encode_bypass(&mut w, sign); + } + // sao_band_position[0]: FL(5) = 8. + cabac.encode_bypass_bits(&mut w, 8, 5); + } else { + // sao_type_idx_luma = 2 (edge): TR bins "1" (ctx), + // "1" (bypass). + cabac.encode_decision(&mut w, &mut ctxs.sao_type_idx[0], 1); + cabac.encode_bypass(&mut w, 1); + // sao_offset_abs[0][i]: 1, 2, 1, 2 (edge offsets + // carry implicit signs per §7.4.9.3). + for v in [1u32, 2, 1, 2] { + for _ in 0..v { + cabac.encode_bypass(&mut w, 1); + } + cabac.encode_bypass(&mut w, 0); + } + // sao_eo_class_luma: FL(2) = 1 (vertical — reads + // the above / below neighbours). + cabac.encode_bypass_bits(&mut w, 1, 2); + } + } + write_pcm_ctu(&mut w, &mut cabac, &mut ctxs, y, cb, cr, width, x0, y0); + // end_of_slice_segment_flag: 1 only at the segment's last CTB. + cabac.encode_terminate(&mut w, u8::from(addr == end - 1)); + } + // The final terminate-1 flush wrote the rbsp_stop_one_bit; + // rbsp_slice_segment_trailing_bits() is alignment zeros from here. + w.align_zero(); + out.push(w.finish()); + } + out +} + +/// §7.3.8.2 + §7.3.8.5 — one all-PCM CTB (`CtbLog2SizeY == +/// MinCbLog2SizeY`, so the coding quadtree is the single unsplit CU): +/// `part_mode` (§9.3.3.7 bin "1" = `PART_2Nx2N`), `pcm_flag` (a +/// §9.3.5.6 terminate bin — value 1 flushes the codeword), the +/// `pcm_alignment_zero_bit` run, the raw §7.3.8.7 samples (luma then +/// Cb, Cr), and the §9.3.5.2 engine re-initialization. +#[allow(clippy::too_many_arguments)] +fn write_pcm_ctu( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + x0: usize, + y0: usize, +) { + let cw = width / 2; + cabac.encode_decision(w, &mut ctxs.part_mode[0], 1); + cabac.encode_terminate(w, 1); + w.align_zero(); + for j in 0..CTB { + for i in 0..CTB { + w.put_bits(u32::from(y[(y0 + j) * width + x0 + i]), 8); + } + } + let (cx, cy) = (x0 / 2, y0 / 2); + for plane in [cb, cr] { + for j in 0..CTB / 2 { + for i in 0..CTB / 2 { + w.put_bits(u32::from(plane[(cy + j) * cw + cx + i]), 8); + } + } + } + cabac.reinit(); +} + +/// §7.4.1.1 — the coded (emulation-prevention-escaped) byte length of +/// `bytes`, given the zero-run carried in from the preceding coded +/// bytes. Returns the length and the carry-out zero run. The dual of +/// the counting the §7.4.7.1 `entry_point_offset_minus1[i]` values +/// perform over the coded slice-segment data. +fn escaped_len(bytes: &[u8], mut zero_run: u32) -> (usize, u32) { + let mut len = 0usize; + for &b in bytes { + if zero_run >= 2 && b <= 0x03 { + len += 1; // emulation_prevention_three_byte + zero_run = 0; + } + len += 1; + if b == 0 { + zero_run += 1; + } else { + zero_run = 0; + } + } + (len, zero_run) +} + +/// §7.3.6.1 + §7.3.8.1 — the tiled picture as ONE independent I-slice +/// segment whose CTBs walk the §6.5.1 tile scan. Every tile is its own +/// subset: fresh §9.3.2.2 contexts and a fresh §9.3.5.2 arithmetic +/// engine at each tile start, `end_of_subset_one_bit` + byte alignment +/// after every tile but the last, and the §7.4.7.1 +/// `entry_point_offset_minus1[]` block (offsets in CODED bytes, +/// emulation-prevention included) in the slice header. +fn write_tiled_idr_slice( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + opts: &PcmAuOptions, +) -> Vec { + let (cols, rows) = opts.tiles.expect("caller checked the tile grid"); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let total = ctbs_x * ctbs_y; + let tiling = PictureTiling::new( + ctbs_x as u32, + ctbs_y as u32, + width as u32, + height as u32, + CTB_LOG2, + 2, // MinTbLog2SizeY (SPS: log2_min_luma_transform_block_size = 4) + &TilingParams { + num_tile_columns_minus1: cols - 1, + num_tile_rows_minus1: rows - 1, + uniform_spacing_flag: true, + column_width_minus1: Vec::new(), + row_height_minus1: Vec::new(), + }, + ) + .expect("validated tile geometry"); + + // ---- slice_segment_data( ), one coded subset per tile ---- + let mut subsets: Vec> = Vec::new(); + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + for ts in 0..total as u32 { + let rs = tiling.ctb_addr_ts_to_rs(ts) as usize; + let x0 = (rs % ctbs_x) * CTB; + let y0 = (rs / ctbs_x) * CTB; + write_pcm_ctu(&mut w, &mut cabac, &mut ctxs, y, cb, cr, width, x0, y0); + let last_of_pic = ts == total as u32 - 1; + // end_of_slice_segment_flag: 1 only at the picture's last CTB. + cabac.encode_terminate(&mut w, u8::from(last_of_pic)); + let last_of_tile = last_of_pic || tiling.tile_id(ts + 1) != tiling.tile_id(ts); + if last_of_tile { + if !last_of_pic { + // §7.3.8.1 end_of_subset_one_bit (terminate-1 flush). + cabac.encode_terminate(&mut w, 1); + } + // byte_alignment( ) — the flush wrote the trailing one bit. + w.align_zero(); + subsets.push(std::mem::take(&mut w).finish()); + // §9.3.2.2 — fresh contexts + engine at the next tile start. + cabac = CabacEncoder::new(); + ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + } + } + + // §7.4.7.1 — entry_point_offset_minus1[i] counts CODED bytes; the + // emulation-prevention zero-run threads across subset boundaries + // (the slice header's byte_alignment one-bit makes its last byte + // nonzero, so the first subset starts with a zero run of 0). + let mut offsets: Vec = Vec::new(); + let mut zero_run = 0u32; + for s in &subsets[..subsets.len() - 1] { + let (len, zr) = escaped_len(s, zero_run); + zero_run = zr; + offsets.push(len as u32 - 1); + } + let offset_len = offsets + .iter() + .map(|&o| 32 - o.leading_zeros()) + .max() + .unwrap_or(1) + .max(1) as u8; + + // ---- slice_segment_header( ) ---- + let mut h = BitWriter::new(); + h.put_bit(1); // first_slice_segment_in_pic_flag + h.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + h.ue(0); // slice_pic_parameter_set_id + h.ue(2); // slice_type = I + h.se(SLICE_QP - 26); // slice_qp_delta + if opts.deblocking { + // §7.3.6.1 gate: pps_loop_filter_across_slices == 1 and + // deblocking not disabled. + h.put_bit(1); // slice_loop_filter_across_slices_enabled_flag + } + // tiles_enabled_flag == 1: the entry-point block is present. + h.ue(offsets.len() as u32); // num_entry_point_offsets + if !offsets.is_empty() { + h.ue(u32::from(offset_len) - 1); // offset_len_minus1 + for &o in &offsets { + h.put_bits(o, offset_len); // entry_point_offset_minus1[i] + } + } + h.rbsp_trailing_bits(); // byte_alignment() before slice data + debug_assert_ne!(h.as_bytes().last(), Some(&0), "aligned header byte"); + for s in &subsets { + for &b in s { + h.put_bits(u32::from(b), 8); + } + } + h.finish() +} + +/// Encode one 4:2:0 8-bit frame as a self-contained IDR access unit +/// (`VPS + SPS + PPS + IDR_N_LP` in Annex B form). The decode is +/// bit-exact lossless: every coding unit is a §7.3.8.7 PCM block. +/// +/// # Errors +/// [`PcmEncodeError`] when the dimensions are not nonzero multiples of +/// 16 or a plane buffer has the wrong length. +pub fn encode_idr_pcm_au( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, +) -> Result, PcmEncodeError> { + encode_au(y, cb, cr, width, height, PcmAuOptions::default()) +} + +/// As [`encode_idr_pcm_au`], with the picture split into `segments` +/// slice segments: the first independent, the rest §7.3.6.1 +/// *dependent* slice segments (`dependent_slice_segment_flag == 1`, +/// header inherited per §7.4.7.1, CABAC contexts carried across the +/// boundary per §9.3.2.4 / §9.3.2.5). +/// +/// # Errors +/// [`PcmEncodeError`] as for [`encode_idr_pcm_au`], or +/// [`PcmEncodeError::BadDimensions`] when `segments` is 0 or exceeds +/// the picture's CTB count. +pub fn encode_idr_pcm_au_segmented( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + segments: usize, +) -> Result, PcmEncodeError> { + encode_au( + y, + cb, + cr, + width, + height, + PcmAuOptions { + segments, + ..PcmAuOptions::default() + }, + ) +} + +/// As [`encode_idr_pcm_au`], with the full [`PcmAuOptions`] shape +/// control (slice segmentation, deblocking on, luma band-offset SAO). +/// +/// # Errors +/// [`PcmEncodeError`] as for [`encode_idr_pcm_au_segmented`]. +pub fn encode_idr_pcm_au_opts( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + opts: PcmAuOptions, +) -> Result, PcmEncodeError> { + encode_au(y, cb, cr, width, height, opts) +} + +fn encode_au( + y: &[u8], + cb: &[u8], + cr: &[u8], + width: usize, + height: usize, + opts: PcmAuOptions, +) -> Result, PcmEncodeError> { + let segments = opts.segments; + if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 { + return Err(PcmEncodeError::BadDimensions { width, height }); + } + let total_ctbs = (width / CTB) * (height / CTB); + if segments == 0 || segments > total_ctbs { + return Err(PcmEncodeError::BadDimensions { width, height }); + } + // Independent-slice plans must be sorted, start at CTB 0 and stay + // in range; band and edge SAO are mutually exclusive. + if !opts.independent_slices.is_empty() { + let starts: Vec = opts.independent_slices.iter().map(|&(s, _)| s).collect(); + if starts[0] != 0 + || starts.windows(2).any(|w| w[1] <= w[0]) + || starts.iter().any(|&s| s >= total_ctbs) + { + return Err(PcmEncodeError::BadDimensions { width, height }); + } + } + if opts.sao_luma_band && opts.sao_luma_eo_vertical { + return Err(PcmEncodeError::BadDimensions { width, height }); + } + // Tile grid: at least two tiles, each column/row at least one CTB + // wide/tall; the tiled picture is a single slice segment with SAO + // off (the tile-scan SAO merge availability is out of this + // bootstrap's scope). + if let Some((cols, rows)) = opts.tiles { + let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical; + if cols == 0 + || rows == 0 + || cols * rows < 2 + || cols as usize > width / CTB + || rows as usize > height / CTB + || segments != 1 + || !opts.independent_slices.is_empty() + || sao + { + return Err(PcmEncodeError::BadDimensions { width, height }); + } + } + let check = |plane: &'static str, buf: &[u8], expected: usize| { + if buf.len() != expected { + Err(PcmEncodeError::PlaneSize { + plane, + expected, + got: buf.len(), + }) + } else { + Ok(()) + } + }; + check("y", y, width * height)?; + check("cb", cb, width * height / 4)?; + check("cr", cr, width * height / 4)?; + + let level_idc = opts.tiles.map_or_else( + || level_idc_for(width * height), + |(c, r)| level_idc_for(width * height).max(level_idc_for_tiles(c, r)), + ); + let dependent_mode = opts.independent_slices.is_empty() && segments > 1; + let sao = opts.sao_luma_band || opts.sao_luma_eo_vertical; + let mut units = vec![ + nal_unit(32, 0, 0, &write_vps(level_idc)), // VPS_NUT + nal_unit( + 33, + 0, + 0, + &write_sps(width, height, level_idc, sao, opts.pcm_loop_filter_disabled), + ), // SPS_NUT + nal_unit( + 34, + 0, + 0, + &write_pps(dependent_mode, opts.deblocking, opts.tiles), + ), // PPS_NUT + ]; + if opts.tiles.is_some() { + let rbsp = write_tiled_idr_slice(y, cb, cr, width, height, &opts); + units.push(nal_unit(20, 0, 0, &rbsp)); // IDR_N_LP + } else { + for rbsp in write_idr_slice_segments(y, cb, cr, width, height, &opts) { + units.push(nal_unit(20, 0, 0, &rbsp)); // IDR_N_LP + } + } + Ok(annexb(&units)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pps::PicParameterSet; + use crate::sps::SeqParameterSet; + + fn gradient_planes(w: usize, h: usize) -> (Vec, Vec, Vec) { + let y: Vec = (0..w * h).map(|i| (i * 7 % 251) as u8).collect(); + let cb: Vec = (0..w * h / 4).map(|i| (i * 3 % 240 + 8) as u8).collect(); + let cr: Vec = (0..w * h / 4).map(|i| (255 - i * 5 % 250) as u8).collect(); + (y, cb, cr) + } + + #[test] + fn rejects_bad_geometry() { + let (y, cb, cr) = gradient_planes(16, 16); + assert!(matches!( + encode_idr_pcm_au(&y, &cb, &cr, 20, 16), + Err(PcmEncodeError::BadDimensions { .. }) + )); + assert!(matches!( + encode_idr_pcm_au(&y, &cb, &cr, 32, 16), + Err(PcmEncodeError::PlaneSize { .. }) + )); + } + + /// The whole bootstrap contract: encode → decode with the crate's + /// own end-to-end driver → bit-exact planes (PCM is lossless). + #[test] + fn pcm_au_roundtrips_losslessly_through_the_decoder() { + for (w, h) in [(16usize, 16usize), (48, 32), (32, 64)] { + let (y, cb, cr) = gradient_planes(w, h); + let au = encode_idr_pcm_au(&y, &cb, &cr, w, h).expect("encode"); + let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode"); + assert_eq!(frames.len(), 1, "{w}x{h}: one IDR frame"); + let mut expected = Vec::new(); + expected.extend_from_slice(&y); + expected.extend_from_slice(&cb); + expected.extend_from_slice(&cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + expected, + "{w}x{h}: lossless PCM roundtrip" + ); + } + } + + /// Two frames form two self-contained IDR AUs; both decode losslessly + /// and in order. + #[test] + fn multi_frame_pcm_stream_decodes_in_order() { + let (y0, cb0, cr0) = gradient_planes(32, 32); + let y1: Vec = y0.iter().map(|&v| v ^ 0x5A).collect(); + let mut stream = encode_idr_pcm_au(&y0, &cb0, &cr0, 32, 32).expect("au0"); + stream.extend(encode_idr_pcm_au(&y1, &cb0, &cr0, 32, 32).expect("au1")); + let frames = crate::sequence::decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 2); + let p0 = frames[0].picture.to_planar_u8().unwrap(); + let p1 = frames[1].picture.to_planar_u8().unwrap(); + assert_eq!(&p0[..y0.len()], &y0[..]); + assert_eq!(&p1[..y1.len()], &y1[..]); + assert_ne!(p0, p1); + } + + /// Dependent slice segments: the picture splits into an independent + /// segment + dependent segments whose CABAC contexts continue + /// across the NAL boundary (§9.3.2.4 / §9.3.2.5) and whose header + /// values inherit per §7.4.7.1 — still bit-exact lossless. + #[test] + fn dependent_slice_segments_roundtrip_losslessly() { + let (w, h) = (48usize, 48usize); // 9 CTBs + let (y, cb, cr) = gradient_planes(w, h); + for segments in [2usize, 3, 9] { + let au = encode_idr_pcm_au_segmented(&y, &cb, &cr, w, h, segments).expect("encode"); + // One IDR NAL per segment behind the parameter sets. + let units = crate::nal::collect_nal_units(&au).expect("walk"); + assert_eq!(units.len(), 3 + segments, "{segments} segments"); + assert!(units[4..].iter().all(|u| u.header.nal_unit_type == 20)); + let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = Vec::new(); + expected.extend_from_slice(&y); + expected.extend_from_slice(&cb); + expected.extend_from_slice(&cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + expected, + "{segments}-segment lossless roundtrip" + ); + } + } + + /// A dependent segment decoded WITHOUT the preceding segment's + /// stored context state is rejected, not misdecoded. + #[test] + fn dependent_segment_without_predecessor_is_rejected() { + let (y, cb, cr) = gradient_planes(32, 32); + let au = encode_idr_pcm_au_segmented(&y, &cb, &cr, 32, 32, 2).expect("encode"); + let units = crate::nal::collect_nal_units(&au).expect("walk"); + // Drop the independent slice segment (unit 3), keep the + // dependent one: the driver must refuse. + let mut broken = Vec::new(); + for (i, u) in units.iter().enumerate() { + if i == 3 { + continue; + } + let mut coded = vec![0, 0, 0, 1]; + coded.extend(crate::encoder::nal::nal_unit( + u.header.nal_unit_type, + u.header.nuh_layer_id, + u.header.temporal_id, + &u.rbsp, + )); + broken.extend(coded); + } + assert!(crate::sequence::decode_annexb_sequence(&broken).is_err()); + } + + /// §8.7.2.5.4 / §8.7.3.1 — with deblocking and luma band-offset + /// SAO ENABLED over an all-PCM picture and + /// `pcm_loop_filter_disabled_flag == 1`, a conforming decoder must + /// leave every reconstructed sample untouched. This pins the + /// per-CU loop-filter suppression map end to end (a decoder that + /// filtered the PCM samples would corrupt the smooth gradient). + #[test] + fn pcm_loop_filter_suppression_keeps_samples_exact() { + let (w, h) = (48usize, 32usize); + let (y, cb, cr) = gradient_planes(w, h); + for (deblocking, sao_luma_band) in [(true, false), (false, true), (true, true)] { + let opts = PcmAuOptions { + segments: 1, + deblocking, + sao_luma_band, + ..PcmAuOptions::default() + }; + let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode"); + let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = Vec::new(); + expected.extend_from_slice(&y); + expected.extend_from_slice(&cb); + expected.extend_from_slice(&cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + expected, + "deblocking={deblocking} sao={sao_luma_band}: PCM samples survive the loop filters" + ); + } + } + + /// Independent multi-slice pictures with heterogeneous per-slice + /// `slice_loop_filter_across_slices_enabled_flag` values roundtrip + /// through the crate's own decoder (which implements the §8.7.2.1 + /// per-slice gate), and the opposite flag layouts produce + /// different pictures (the boundary edge filters on exactly one + /// side of the pair). + #[test] + fn independent_slices_with_heterogeneous_across_flags() { + let (w, h) = (48usize, 32usize); + let (y, cb, cr) = gradient_planes(w, h); + let mut decoded = Vec::new(); + for flags in [(true, false), (false, true)] { + let opts = PcmAuOptions { + independent_slices: vec![(0, flags.0), (3, flags.1)], + deblocking: true, + pcm_loop_filter_disabled: false, + ..PcmAuOptions::default() + }; + let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode"); + let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode"); + assert_eq!(frames.len(), 1); + decoded.push(frames[0].picture.to_planar_u8().expect("8-bit")); + } + assert_ne!( + decoded[0], decoded[1], + "opposite per-slice flags gate the boundary deblocking differently" + ); + } + + /// True multi-tile single-slice streams: the picture walks the + /// §6.5.1 tile scan inside ONE slice segment, every tile its own + /// §7.3.8.1 subset behind a §7.4.7.1 entry-point offset, with the + /// §9.3.2.2 per-tile CABAC context re-initialization on both the + /// encode and decode sides — bit-exact lossless through the + /// crate's own decoder. + #[test] + fn tiled_pcm_au_roundtrips_losslessly() { + for (w, h, cols, rows) in [ + (64usize, 48usize, 2u32, 2u32), // uneven rows: 4x3 CTBs / 2x2 + (96, 64, 3, 2), // 6x4 CTBs / 3x2 + (32, 16, 2, 1), // single tile row + (80, 80, 5, 5), // one CTB per tile + ] { + let (y, cb, cr) = gradient_planes(w, h); + let opts = PcmAuOptions { + tiles: Some((cols, rows)), + ..PcmAuOptions::default() + }; + let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode"); + let frames = crate::sequence::decode_annexb_sequence(&au).expect("decode"); + assert_eq!(frames.len(), 1, "{cols}x{rows}: one IDR frame"); + let mut expected = Vec::new(); + expected.extend_from_slice(&y); + expected.extend_from_slice(&cb); + expected.extend_from_slice(&cr); + assert_eq!( + frames[0].picture.to_planar_u8().expect("8-bit"), + expected, + "{w}x{h} {cols}x{rows} tiles: lossless roundtrip" + ); + } + } + + /// The tiled stream's parameter sets and slice header really carry + /// the tile syntax: `tiles_enabled_flag == 1`, the uniform 2x2 + /// grid, and `num_entry_point_offsets == 3` with offsets that + /// partition the coded slice data. + #[test] + fn tiled_pcm_au_signals_tiles_and_entry_points() { + let (w, h) = (64usize, 64usize); + let (y, cb, cr) = gradient_planes(w, h); + let opts = PcmAuOptions { + tiles: Some((2, 2)), + ..PcmAuOptions::default() + }; + let au = encode_idr_pcm_au_opts(&y, &cb, &cr, w, h, opts).expect("encode"); + let units = crate::nal::collect_nal_units(&au).expect("walk"); + assert_eq!(units.len(), 4); + let sps = SeqParameterSet::parse(&units[1].rbsp).expect("sps"); + let pps = PicParameterSet::parse(&units[2].rbsp).expect("pps"); + assert!(pps.tiles_enabled_flag); + assert_eq!(pps.tiles.num_tile_columns_minus1, 1); + assert_eq!(pps.tiles.num_tile_rows_minus1, 1); + assert!(pps.tiles.uniform_spacing_flag); + assert!(!pps.loop_filter_across_tiles_enabled_flag); + let header = crate::slice::SliceSegmentHeader::parse( + &units[3].rbsp, + units[3].header.nal_unit_type, + &sps, + &pps, + ) + .expect("slice header"); + let eps = header.entry_point_offsets.expect("entry points present"); + assert_eq!(eps.num_entry_point_offsets, 3); + assert_eq!(eps.entry_point_offset_minus1.len(), 3); + } + + /// Tile-option validation: zero-sized grids, single-tile grids, + /// grids finer than the CTB grid, and combinations with + /// multi-segment or SAO options are rejected. + #[test] + fn tiled_pcm_au_rejects_bad_grids() { + let (y, cb, cr) = gradient_planes(32, 32); + for opts in [ + PcmAuOptions { + tiles: Some((1, 1)), + ..PcmAuOptions::default() + }, + PcmAuOptions { + tiles: Some((0, 2)), + ..PcmAuOptions::default() + }, + PcmAuOptions { + tiles: Some((3, 1)), // 2x2 CTBs: only 2 columns exist + ..PcmAuOptions::default() + }, + PcmAuOptions { + tiles: Some((2, 2)), + segments: 2, + ..PcmAuOptions::default() + }, + PcmAuOptions { + tiles: Some((2, 2)), + sao_luma_band: true, + ..PcmAuOptions::default() + }, + ] { + assert!( + matches!( + encode_idr_pcm_au_opts(&y, &cb, &cr, 32, 32, opts.clone()), + Err(PcmEncodeError::BadDimensions { .. }) + ), + "{opts:?}" + ); + } + } + + #[test] + fn written_sps_pps_parse_back() { + let (y, cb, cr) = gradient_planes(48, 32); + let au = encode_idr_pcm_au(&y, &cb, &cr, 48, 32).expect("encode"); + let units = crate::nal::collect_nal_units(&au).expect("walk"); + assert_eq!(units.len(), 4); + let sps = SeqParameterSet::parse(&units[1].rbsp).expect("sps parses"); + assert_eq!(sps.pic_width_in_luma_samples, 48); + assert_eq!(sps.pic_height_in_luma_samples, 32); + assert_eq!(sps.chroma_format_idc, 1); + let pcm = sps.pcm.as_ref().expect("pcm block present"); + assert_eq!(pcm.bit_depth_luma_minus1, 7); + assert!(pcm.loop_filter_disabled_flag); + let pps = PicParameterSet::parse(&units[2].rbsp).expect("pps parses"); + assert!(pps.deblocking_filter_control_present_flag); + assert!(pps.deblocking.disabled_flag); + } +} diff --git a/vendor/oxideav-h265/src/encoder/pyramid.rs b/vendor/oxideav-h265/src/encoder/pyramid.rs new file mode 100644 index 0000000..e97fd1b --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/pyramid.rs @@ -0,0 +1,718 @@ +//! Hierarchical-B GOP encoder — dyadic B pyramids over the §8.5 +//! inter machinery of [`crate::encoder::inter`]. +//! +//! The sequence shape is one leading IDR followed by dyadic mini-GOPs +//! of `gop` frames (a power of two). Within a mini-GOP anchored at +//! POC `a`: +//! +//! * the next anchor `a + gop` is coded FIRST as a P slice (layer 0) +//! referencing `a`; +//! * every interval `(lo, hi)` then codes its midpoint as a B slice +//! whose `RefPicList0` holds the past boundary `lo` and whose +//! `RefPicList1` holds the FUTURE boundary `hi` (out-of-order +//! coding, decode order ≠ output order), recursing into the two +//! halves one pyramid layer deeper. +//! +//! Every B slice's AMVP election therefore searches L0, L1 and the +//! bi combination (see [`crate::encoder::inter`]'s two-sided search), +//! and the §8.5.3.2.2 merge candidates carry genuinely bi-directional +//! motion. Deeper layers ride a per-layer QP offset (`qp + layer` +//! by default) — the classic pyramid rate allocation: the pictures +//! referenced most are coded best. +//! +//! Stream-level signalling: +//! +//! * `slice_pic_order_cnt_lsb` carries the DISPLAY order; the SPS +//! signals `sps_max_num_reorder_pics = log2(gop)` and a DPB bound +//! of `log2(gop) + 2` pictures so a conforming decoder reorders +//! output correctly; +//! * each slice's inline §7.4.8 short-term RPS lists every picture a +//! later slice (in decode order) still references — negative AND +//! positive pictures — with `used_by_curr_pic` flags marking this +//! slice's own active references; +//! * reference-list sizes stay 1/1 (the PPS defaults), so no +//! `num_ref_idx` override is signalled on the pyramid slices. +//! +//! Reconstruction stays the decode-side truth: every slice +//! reconstructs through the shared [`encode_inter_slice`] pass +//! (decode-side prediction, transform and §8.7 in-loop filters), so +//! a conforming decoder's output is bit-identical to the encoder's +//! per-frame reconstruction — pinned by the roundtrip tests in +//! DISPLAY order against [`crate::sequence::decode_annexb_sequence`] +//! (which itself outputs §C.5.2.2 output order). +//! +//! The trailing frames that do not fill a final mini-GOP are coded at +//! [`PyramidEncoder::flush`] as a low-delay P chain from the last +//! anchor (decode order == display order again). + +use std::collections::BTreeMap; + +use crate::encoder::inter::{encode_inter_slice, FrameRecon, FrameStats, SliceSpec, YuvFrame}; +use crate::encoder::intra::{encode_idr_intra_au_full, IntraEncodeError, SpsCfg}; +use crate::encoder::loopfilter::LoopFilterCfg; +use crate::encoder::nal::{annexb, nal_unit}; + +/// The fixed CTB size shared with the intra / low-delay encoders. +const CTB: usize = 16; + +/// One encoded access unit of the pyramid stream, in DECODE order. +#[derive(Debug, Clone)] +pub struct PyramidAu { + /// The Annex B access unit (`VPS + SPS + PPS + IDR_N_LP` for the + /// leading IDR, one `TRAIL_R` slice otherwise). + pub au: Vec, + /// `true` for the leading IDR. + pub keyframe: bool, + /// The frame's DISPLAY index (== its `PicOrderCntVal`). + pub display_order: usize, + /// The pyramid layer (0 = the IDR / anchors, deeper B layers up + /// to `log2(gop)`). + pub layer: u8, + /// The frame's reconstruction (== a conforming decoder's output). + pub recon: FrameRecon, + /// The frame's CU mode-decision counters. + pub stats: FrameStats, +} + +/// An owned 4:2:0 frame buffered until its mini-GOP completes. +#[derive(Debug)] +struct OwnedFrame { + y: Vec, + cb: Vec, + cr: Vec, +} + +impl OwnedFrame { + fn as_yuv(&self) -> YuvFrame<'_> { + YuvFrame { + y: &self.y, + cb: &self.cb, + cr: &self.cr, + } + } +} + +/// One scheduled slice of a mini-GOP, in decode order. +struct Sched { + poc: i32, + /// `RefPicList0[0]` (the past boundary). + l0: i32, + /// `RefPicList1[0]` (the future boundary) — `None` for the anchor + /// P slice. + l1: Option, + layer: u8, +} + +/// The dyadic decode-order schedule of one mini-GOP `(a, a + g]`: +/// the anchor P first, then the midpoint recursion. +fn build_schedule(a: i32, g: i32) -> Vec { + fn rec(v: &mut Vec, lo: i32, hi: i32, layer: u8) { + if hi - lo < 2 { + return; + } + let mid = (lo + hi) / 2; + v.push(Sched { + poc: mid, + l0: lo, + l1: Some(hi), + layer, + }); + rec(v, lo, mid, layer + 1); + rec(v, mid, hi, layer + 1); + } + let mut v = vec![Sched { + poc: a + g, + l0: a, + l1: None, + layer: 0, + }]; + rec(&mut v, a, a + g, 1); + v +} + +/// The streaming hierarchical-B encoder: display-order frames in, +/// decode-order access units out (buffered per mini-GOP). +#[derive(Debug)] +pub struct PyramidEncoder { + width: usize, + height: usize, + qp: i32, + /// Mini-GOP length (a power of two, 2..=16). + gop: usize, + /// Per-layer QP step (`SliceQpY = qp + layer * step`, clamped). + layer_qp_step: i32, + filters: LoopFilterCfg, + amp: bool, + /// Display index of the next frame pushed. + next_display: usize, + /// Frames after the last anchor, awaiting their mini-GOP. + pending: Vec, + /// The retained reference reconstructions, keyed by POC. + refs: BTreeMap, + /// POC of the last coded anchor (`None` before the IDR). + anchor: Option, +} + +impl PyramidEncoder { + /// Construct a hierarchical-B encoder for `width`x`height` 4:2:0 + /// 8-bit content at base `SliceQpY == qp` with dyadic mini-GOPs + /// of `gop` frames (a power of two in 2..=16). + /// + /// # Errors + /// [`PyramidError::Encode`] on bad dimensions / QP, + /// [`PyramidError::BadGop`] on a non-power-of-two or out-of-range + /// `gop`. + pub fn new(width: usize, height: usize, qp: i32, gop: usize) -> Result { + if width == 0 || height == 0 || width % CTB != 0 || height % CTB != 0 { + return Err(PyramidError::Encode(IntraEncodeError::BadDimensions { + width, + height, + })); + } + if !(0..=51).contains(&qp) { + return Err(PyramidError::Encode(IntraEncodeError::BadQp(qp))); + } + if !(2..=16).contains(&gop) || !gop.is_power_of_two() { + return Err(PyramidError::BadGop(gop)); + } + Ok(Self { + width, + height, + qp, + gop, + layer_qp_step: 1, + filters: LoopFilterCfg::off(), + amp: false, + next_display: 0, + pending: Vec::new(), + refs: BTreeMap::new(), + anchor: None, + }) + } + + /// Set the per-layer QP step (default 1): a slice on pyramid + /// layer `l` codes at `SliceQpY = clamp(qp + l * step, 0, 51)`. + #[must_use] + pub fn with_layer_qp_step(mut self, step: i32) -> Self { + self.layer_qp_step = step; + self + } + + /// Enable the §8.7 in-loop filters on every slice's + /// reconstruction path (see + /// [`crate::encoder::inter::LowDelayPEncoder::with_loop_filters`]). + #[must_use] + pub fn with_loop_filters(mut self, filters: LoopFilterCfg) -> Self { + self.filters = filters; + self + } + + /// Switch the stream to the AMP configuration (see + /// [`crate::encoder::inter::LowDelayPEncoder::with_amp`]). + #[must_use] + pub fn with_amp(mut self, on: bool) -> Self { + self.amp = on; + self + } + + /// The number of pyramid layers below the anchors + /// (`log2(gop)`). + fn depth(&self) -> u32 { + self.gop.trailing_zeros() + } + + /// The stream's [`SpsCfg`]: DPB bound `log2(gop) + 2` pictures + /// (the deepest recursion retains `log2(gop) + 1` references + /// beside the current picture), reorder bound `log2(gop)`. + fn sps_cfg(&self) -> SpsCfg { + SpsCfg { + max_dec_pic_buffering_minus1: self.depth() + 1, + max_num_reorder_pics: self.depth(), + min_cb_log2: if self.amp { 3 } else { 4 }, + amp: self.amp, + conf_win: (0, 0), // edith patch: no crop on the inter paths + } + } + + /// The layer-`l` slice QP. + fn layer_qp(&self, layer: u8) -> i32 { + (self.qp + i32::from(layer) * self.layer_qp_step).clamp(0, 51) + } + + /// Push the next DISPLAY-order frame; returns every access unit + /// that became codable (none until the current mini-GOP fills, + /// then the whole mini-GOP in decode order). + /// + /// # Errors + /// [`PyramidError::Encode`] on plane-size mismatches. + pub fn encode_frame(&mut self, frame: &YuvFrame<'_>) -> Result, PyramidError> { + let (cw, ch) = (self.width / 2, self.height / 2); + for (plane, buf, expected) in [ + ("y", frame.y, self.width * self.height), + ("cb", frame.cb, cw * ch), + ("cr", frame.cr, cw * ch), + ] { + if buf.len() != expected { + return Err(PyramidError::Encode(IntraEncodeError::PlaneSize { + plane, + expected, + got: buf.len(), + })); + } + } + + if self.anchor.is_none() { + // The leading IDR (POC 0, layer 0). + let idr = encode_idr_intra_au_full( + frame.y, + frame.cb, + frame.cr, + self.width, + self.height, + self.qp, + &self.sps_cfg(), + &self.filters, + )?; + let recon = FrameRecon { + y: idr.recon_y, + cb: idr.recon_cb, + cr: idr.recon_cr, + }; + self.refs.insert(0, recon.clone()); + self.anchor = Some(0); + self.next_display = 1; + return Ok(vec![PyramidAu { + au: idr.au, + keyframe: true, + display_order: 0, + layer: 0, + recon, + stats: FrameStats { + intra: (self.width / CTB) * (self.height / CTB), + ..FrameStats::default() + }, + }]); + } + + self.pending.push(OwnedFrame { + y: frame.y.to_vec(), + cb: frame.cb.to_vec(), + cr: frame.cr.to_vec(), + }); + self.next_display += 1; + if self.pending.len() == self.gop { + Ok(self.code_mini_gop()) + } else { + Ok(Vec::new()) + } + } + + /// Code the buffered complete mini-GOP in decode order and drain + /// it. The pending buffer holds displays `a+1 ..= a+gop`. + fn code_mini_gop(&mut self) -> Vec { + let a = self.anchor.expect("mini-GOP needs an anchor"); + let g = self.gop as i32; + let sched = build_schedule(a, g); + let mut out = Vec::with_capacity(sched.len()); + for (i, s) in sched.iter().enumerate() { + // Retained set for THIS slice's RPS: every already-coded + // picture that this or a LATER slice of the schedule + // still references. + let retained: Vec = { + let mut keep: Vec = self + .refs + .keys() + .copied() + .filter(|&p| { + sched[i..].iter().any(|t| { + t.l0 == p || t.l1 == Some(p) // still referenced + }) + }) + .collect(); + keep.sort_unstable(); + keep + }; + // Drop reconstructions nothing references any more. + self.refs.retain(|p, _| retained.contains(p)); + + let frame = &self.pending[(s.poc - a - 1) as usize]; + let au = self.code_slice(frame.as_yuv(), s, &retained); + self.refs.insert(s.poc, au.recon.clone()); + out.push(au); + } + // Only the new anchor survives into the next mini-GOP. + let new_anchor = a + g; + self.refs.retain(|&p, _| p == new_anchor); + self.anchor = Some(new_anchor); + self.pending.clear(); + out + } + + /// Encode one scheduled P / B slice against the retained + /// reconstructions. + fn code_slice(&self, frame: YuvFrame<'_>, s: &Sched, retained: &[i32]) -> PyramidAu { + let b_slice = s.l1.is_some(); + let rec_of = |p: i32| -> &FrameRecon { self.refs.get(&p).expect("retained recon") }; + let l0 = vec![(s.l0, rec_of(s.l0))]; + let l1: Vec<(i32, &FrameRecon)> = s.l1.map(|p| (p, rec_of(p))).into_iter().collect(); + // Inline §7.4.8 RPS: negative pics closest-first, positive + // pics closest-first; used flags mark the active references. + let rps_neg: Vec<(u32, bool)> = retained + .iter() + .rev() + .filter(|&&p| p < s.poc) + .map(|&p| ((s.poc - p) as u32, p == s.l0)) + .collect(); + let rps_pos: Vec<(u32, bool)> = retained + .iter() + .filter(|&&p| p > s.poc) + .map(|&p| ((p - s.poc) as u32, Some(p) == s.l1)) + .collect(); + let spec = SliceSpec { + poc: s.poc, + qp: self.layer_qp(s.layer), + b_slice, + rps_neg, + rps_pos, + l0, + l1, + lf: &self.filters, + big_cu: self.amp, + }; + let (rbsp, recon, stats) = encode_inter_slice(&frame, &spec, self.width, self.height); + PyramidAu { + au: annexb(&[nal_unit(1, 0, 0, &rbsp)]), // TRAIL_R + keyframe: false, + display_order: s.poc as usize, + layer: s.layer, + recon, + stats, + } + } + + /// Flush the trailing frames that never filled a mini-GOP: a + /// low-delay P chain from the last anchor (decode order == + /// display order). Returns their access units; the encoder is + /// ready for more input afterwards (the last tail frame becomes + /// the new anchor). + pub fn flush(&mut self) -> Vec { + let Some(a) = self.anchor else { + return Vec::new(); + }; + let mut out = Vec::with_capacity(self.pending.len()); + let pending = std::mem::take(&mut self.pending); + for (k, frame) in pending.iter().enumerate() { + let poc = a + 1 + k as i32; + let s = Sched { + poc, + l0: poc - 1, + l1: None, + layer: 0, + }; + let retained = vec![poc - 1]; + self.refs.retain(|&p, _| p == poc - 1); + let au = self.code_slice(frame.as_yuv(), &s, &retained); + self.refs.insert(poc, au.recon.clone()); + out.push(au); + } + if let Some(last) = out.last() { + let new_anchor = last.display_order as i32; + self.refs.retain(|&p, _| p == new_anchor); + self.anchor = Some(new_anchor); + } + out + } +} + +/// Errors from the pyramid encoder. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PyramidError { + /// The shared input-validation contract (dimensions, planes, QP). + Encode(IntraEncodeError), + /// `gop` is not a power of two in 2..=16. + BadGop(usize), +} + +impl From for PyramidError { + fn from(e: IntraEncodeError) -> Self { + Self::Encode(e) + } +} + +impl core::fmt::Display for PyramidError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Encode(e) => e.fmt(f), + Self::BadGop(g) => write!(f, "pyramid gop must be a power of two in 2..=16, got {g}"), + } + } +} + +impl std::error::Error for PyramidError {} + +/// The encoded hierarchical-B sequence, with the per-frame outputs in +/// DISPLAY order (the stream itself is decode-ordered). +#[derive(Debug, Clone)] +pub struct PyramidEncoded { + /// The whole Annex B byte stream (decode order). + pub stream: Vec, + /// Per-frame reconstruction, display order. + pub recon: Vec, + /// Per-frame CU mode-decision counters, display order. + pub stats: Vec, + /// Per-frame pyramid layer, display order. + pub layers: Vec, + /// The display order of each access unit of `stream`, in decode + /// order (the coding schedule, for inspection). + pub decode_order: Vec, +} + +/// Encode a whole sequence through a [`PyramidEncoder`] (leading IDR, +/// dyadic mini-GOPs, low-delay tail) and return the stream plus the +/// display-ordered per-frame outputs. +/// +/// # Errors +/// [`PyramidError`] on bad dimensions / planes / QP / GOP length. +pub fn encode_pyramid( + frames: &[YuvFrame<'_>], + width: usize, + height: usize, + qp: i32, + gop: usize, +) -> Result { + encode_pyramid_with(PyramidEncoder::new(width, height, qp, gop)?, frames) +} + +/// [`encode_pyramid`] over a pre-configured encoder (filters, AMP, +/// layer QP step). +/// +/// # Errors +/// [`PyramidError`] on bad plane geometry. +pub fn encode_pyramid_with( + mut enc: PyramidEncoder, + frames: &[YuvFrame<'_>], +) -> Result { + let n = frames.len(); + let mut out = PyramidEncoded { + stream: Vec::new(), + recon: vec![FrameRecon::default(); n], + stats: vec![FrameStats::default(); n], + layers: vec![0; n], + decode_order: Vec::with_capacity(n), + }; + let push = |out: &mut PyramidEncoded, aus: Vec| { + for au in aus { + out.stream.extend_from_slice(&au.au); + out.decode_order.push(au.display_order); + out.recon[au.display_order] = au.recon; + out.stats[au.display_order] = au.stats; + out.layers[au.display_order] = au.layer; + } + }; + for f in frames { + let aus = enc.encode_frame(f)?; + push(&mut out, aus); + } + push(&mut out, enc.flush()); + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::encoder::inter::encode_low_delay_p; + use crate::sequence::decode_annexb_sequence; + + /// A deterministic "camera-noise" scene: a static textured + /// background under small temporally-independent sensor noise, + /// with a small bright square drifting 1 px per frame. Motion + /// prediction cancels everything except the noise — the content + /// class where the pyramid's per-layer QP allocation wins (the + /// top layers spend fewer bits on noise nobody references). + fn pan_scene(w: usize, h: usize, n: usize) -> Vec<(Vec, Vec, Vec)> { + let tex = |u: usize, v: usize| -> i32 { ((u * 3 + v * 5 + (u / 9) * 7) % 200) as i32 }; + let noise = |x: usize, yy: usize, t: usize| -> i32 { + let h32 = (x + .wrapping_mul(73_856_093) + .wrapping_add(yy.wrapping_mul(19_349_663)) + .wrapping_add(t.wrapping_mul(83_492_791))) as u32; + ((h32 >> 13) % 9) as i32 - 4 + }; + (0..n) + .map(|t| { + let y: Vec = (0..w * h) + .map(|i| { + let (x, yy) = (i % w, i / w); + let (sx, sy) = (10 + t, 24); + let obj = x >= sx && x < sx + 8 && yy >= sy && yy < sy + 8; + let base = tex(x, yy) + if obj { 45 } else { 0 }; + (base + 8 + noise(x, yy, t)).clamp(0, 255) as u8 + }) + .collect(); + let cb: Vec = (0..w * h / 4) + .map(|i| (90 + (i % (w / 2)) % 70) as u8) + .collect(); + let cr: Vec = (0..w * h / 4) + .map(|i| (180 - (i / (w / 2)) % 60) as u8) + .collect(); + (y, cb, cr) + }) + .collect() + } + + fn as_frames(planes: &[(Vec, Vec, Vec)]) -> Vec> { + planes + .iter() + .map(|(y, cb, cr)| YuvFrame { y, cb, cr }) + .collect() + } + + fn assert_display_order_exact(stream: &[u8], recons: &[FrameRecon], label: &str) { + let decoded = decode_annexb_sequence(stream).expect("decode"); + assert_eq!(decoded.len(), recons.len(), "{label}: frame count"); + for (i, (dec, rec)) in decoded.iter().zip(recons.iter()).enumerate() { + assert_eq!(dec.poc, i as i32, "{label}: display order POC {i}"); + let mut expect = rec.y.clone(); + expect.extend_from_slice(&rec.cb); + expect.extend_from_slice(&rec.cr); + assert_eq!( + dec.picture.to_planar_u8().expect("8-bit"), + expect, + "{label} frame {i}: decoder output == encoder recon" + ); + } + } + + /// The core contract across GOP shapes: out-of-order coded + /// pyramids decode (through the crate's own §C.5.2.2 + /// output-ordering) bit-exactly to the encoder's display-order + /// reconstructions — including a non-filling low-delay tail. + #[test] + fn pyramid_gops_decode_to_encoder_recon_exactly() { + let planes = pan_scene(64, 64, 10); + let frames = as_frames(&planes); + for (gop, qp) in [(2usize, 24i32), (4, 30), (8, 27)] { + let enc = encode_pyramid(&frames, 64, 64, qp, gop).expect("encode"); + assert_display_order_exact(&enc.stream, &enc.recon, &format!("gop{gop} qp{qp}")); + } + } + + /// The decode-order schedule is the dyadic pyramid, the layers + /// are the recursion depths, and the mid slices really code + /// bi-predictively (past L0 + future L1). + #[test] + fn pyramid_schedule_layers_and_bi_usage() { + let planes = pan_scene(64, 64, 9); + let frames = as_frames(&planes); + let enc = encode_pyramid(&frames, 64, 64, 26, 8).expect("encode"); + // IDR, then the mini-GOP in dyadic decode order. + assert_eq!(enc.decode_order, vec![0, 8, 4, 2, 1, 3, 6, 5, 7]); + assert_eq!( + enc.layers, + vec![0, 3, 2, 3, 1, 3, 2, 3, 0], + "display-order layers of a GOP-8 pyramid" + ); + // Every B layer >= 1 frame elects some bi-predicted CUs on + // smooth translation. + let bi_frames = (0..9) + .filter(|&i| enc.layers[i] >= 1 && enc.stats[i].bi > 0) + .count(); + assert!( + bi_frames >= 4, + "expected widespread bi-prediction, stats: {:?}", + enc.stats + ); + } + + /// Pyramid coding beats the low-delay chain on smooth motion at + /// the same base QP: fewer bytes for comparable quality. + #[test] + fn pyramid_beats_low_delay_on_smooth_motion() { + let (w, h, n) = (64usize, 64usize, 9usize); + let planes = pan_scene(w, h, n); + let frames = as_frames(&planes); + let qp = 30; + let low = encode_low_delay_p(&frames, w, h, qp).expect("low-delay"); + let pyr = encode_pyramid(&frames, w, h, qp, 8).expect("pyramid"); + assert!( + pyr.stream.len() < low.stream.len(), + "pyramid ({} B) should undercut low-delay ({} B) on smooth motion", + pyr.stream.len(), + low.stream.len() + ); + // Quality stays in the same class (the per-layer QP offsets + // trade a little PSNR on the top layers for the rate win). + let psnr = |rec: &FrameRecon, t: usize| -> f64 { + let mse: f64 = rec + .y + .iter() + .zip(planes[t].0.iter()) + .map(|(&a, &b)| { + let d = f64::from(a) - f64::from(b); + d * d + }) + .sum::() + / rec.y.len() as f64; + 10.0 * (255.0f64 * 255.0 / mse.max(1e-9)).log10() + }; + for t in 0..n { + assert!( + psnr(&pyr.recon[t], t) > 30.0, + "frame {t}: pyramid luma PSNR too low" + ); + } + } + + /// Pyramids compose with the AMP configuration and the §8.7 + /// in-loop filters — everything still decodes bit-exactly. + #[test] + fn pyramid_composes_with_amp_and_filters() { + let planes = pan_scene(64, 48, 9); + let frames = as_frames(&planes); + for (amp, lf) in [ + (true, LoopFilterCfg::off()), + (false, LoopFilterCfg::all()), + (true, LoopFilterCfg::all()), + ] { + let enc = PyramidEncoder::new(64, 48, 32, 4) + .expect("encoder") + .with_amp(amp) + .with_loop_filters(lf); + let out = encode_pyramid_with(enc, &frames).expect("encode"); + assert_display_order_exact(&out.stream, &out.recon, &format!("amp={amp} {lf:?}")); + } + } + + /// Successive mini-GOPs chain across anchors, and flushing midway + /// (a 6-frame sequence at GOP 4: IDR + one mini-GOP + 1-frame + /// tail) stays bit-exact. + #[test] + fn pyramid_multi_gop_and_tail_roundtrip() { + let planes = pan_scene(48, 32, 6); + let frames = as_frames(&planes); + let enc = encode_pyramid(&frames, 48, 32, 22, 4).expect("encode"); + assert_eq!(enc.decode_order, vec![0, 4, 2, 1, 3, 5]); + assert_display_order_exact(&enc.stream, &enc.recon, "gop4 tail"); + } + + /// Input validation. + #[test] + fn rejects_bad_configs() { + assert!(matches!( + PyramidEncoder::new(64, 64, 26, 3), + Err(PyramidError::BadGop(3)) + )); + assert!(matches!( + PyramidEncoder::new(64, 64, 26, 32), + Err(PyramidError::BadGop(32)) + )); + assert!(matches!( + PyramidEncoder::new(20, 64, 26, 4), + Err(PyramidError::Encode(IntraEncodeError::BadDimensions { .. })) + )); + assert!(matches!( + PyramidEncoder::new(64, 64, 99, 4), + Err(PyramidError::Encode(IntraEncodeError::BadQp(99))) + )); + } +} diff --git a/vendor/oxideav-h265/src/encoder/rdpcm_streams.rs b/vendor/oxideav-h265/src/encoder/rdpcm_streams.rs new file mode 100644 index 0000000..ccc0d44 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/rdpcm_streams.rs @@ -0,0 +1,772 @@ +//! Self-built §8.6.5 RDPCM conformance streams (test-only). +//! +//! No black-box encoder binary exposes the range-extension RDPCM +//! tools, so these tests assemble tiny lossless (transquant-bypass) +//! Annex B bitstreams from this crate's own header writers and CABAC +//! encoder: +//! +//! * an all-intra stream whose SPS signals +//! `implicit_rdpcm_enabled_flag == 1` and whose bypass CUs cycle +//! through predModeIntra 26 / 10 / DC / PLANAR — the mode-26/10 CUs +//! carry §8.6.5-DPCM-differenced residuals (and their DM chroma +//! blocks likewise), the DC / PLANAR CUs raw residuals; +//! * an IDR + P stream whose P-slice merge CUs signal +//! `explicit_rdpcm_flag` per component (§7.3.8.11) with both +//! directions, plus flag-0 control CUs and an all-skip CU. +//! +//! Both reconstruct losslessly, so a conforming decoder must emit the +//! procedural source planes exactly. The checked-in copies under +//! `tests/fixture_bytes/` were validated against a black-box reference +//! decoder (byte-exact; SHA-256 sums in +//! `tests/fixture_bytes/r413-generation-notes.md`), and the tests here +//! pin (a) that the builder still produces those exact bytes and +//! (b) that this crate's decoder reconstructs them losslessly. + +use crate::binarization::{ + cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, intra_luma_cand_mode_list, +}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::intra::{gather_refs, zscan_avail}; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::residual::encode_residual_coding; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{ + intra_predict_with_substitution, Component as PredComponent, IntraPredParams, +}; +use crate::residual::{residual_coding_scan_idx, ResidualCodingParams}; + +/// One picture's `(Y, Cb, Cr)` planes. +type Planes = (Vec, Vec, Vec); + +/// CTB / coding-block log2 size (16x16, `MinCbSizeY == CtbSizeY`). +const CTB_LOG2: u32 = 4; +const CTB: usize = 1 << CTB_LOG2; +/// SliceQpY (immaterial — every CU is transquant-bypassed). +const SLICE_QP: i32 = 26; + +/// Deterministic 4:2:0 source planes: smooth gradients plus a coarse +/// checker texture, phase-shifted per frame. +fn source_planes(w: usize, h: usize, frame: usize) -> (Vec, Vec, Vec) { + // The bottom-right CTB is static across frames so the P slice + // exercises a genuine skip CU. + let static_corner = + |x: i32, y: i32, pw: i32, ph: i32, blk: i32| -> bool { x >= pw - blk && y >= ph - blk }; + let lum = |x: i32, y: i32, f: i32| -> u8 { + let g = (x * 3 + y * 5 + f * 17) % 197; + let t = ((x / 4 + y / 4 + f) % 3) * 23; + (16 + g + t).clamp(0, 255) as u8 + }; + let chr = |x: i32, y: i32, ph: i32, f: i32| -> u8 { + let g = (x * 7 + y * 2 + f * 29 + ph) % 151; + let t = ((x / 4 + y / 8) % 2) * 31; + (40 + g + t).clamp(0, 255) as u8 + }; + let f = frame as i32; + let mut y_p = Vec::with_capacity(w * h); + for yy in 0..h as i32 { + for xx in 0..w as i32 { + let ef = if static_corner(xx, yy, w as i32, h as i32, 16) { + 0 + } else { + f + }; + y_p.push(lum(xx, yy, ef)); + } + } + let (cw, ch) = (w / 2, h / 2); + let mut cb_p = Vec::with_capacity(cw * ch); + let mut cr_p = Vec::with_capacity(cw * ch); + for yy in 0..ch as i32 { + for xx in 0..cw as i32 { + let ef = if static_corner(xx, yy, cw as i32, ch as i32, 8) { + 0 + } else { + f + }; + cb_p.push(chr(xx, yy, 0, ef)); + cr_p.push(chr(xx, yy, 61, ef)); + } + } + (y_p, cb_p, cr_p) +} + +/// §7.3.3 — profile tier level for Format Range Extensions +/// (`general_profile_idc == 4`) at the given level. +pub(crate) fn write_ptl_rext(w: &mut BitWriter, level_idc: u8) { + w.put_bits(0, 2); // general_profile_space + w.put_bit(0); // general_tier_flag + w.put_bits(4, 5); // general_profile_idc = 4 (Range Extensions) + let mut compat: u32 = 0; + compat |= 1 << (31 - 4); // flag[4] — Range Extensions + w.put_bits(compat, 32); + w.put_bit(1); // general_progressive_source_flag + w.put_bit(0); // general_interlaced_source_flag + w.put_bit(1); // general_non_packed_constraint_flag + w.put_bit(1); // general_frame_only_constraint_flag + // profile_idc 4: max_12bit / max_10bit / max_8bit / + // max_422chroma / max_420chroma constraint flags set + // (4:2:0 8-bit), then max_monochrome / intra / + // one_picture_only / lossless 0 + 34 reserved bits. + w.put_bit(1); // general_max_12bit_constraint_flag + w.put_bit(1); // general_max_10bit_constraint_flag + w.put_bit(1); // general_max_8bit_constraint_flag + w.put_bit(1); // general_max_422chroma_constraint_flag + w.put_bit(1); // general_max_420chroma_constraint_flag + w.put_bit(0); // general_max_monochrome_constraint_flag + w.put_bit(0); // general_intra_constraint_flag + w.put_bit(0); // general_one_picture_only_constraint_flag + w.put_bit(0); // general_lossless_constraint_flag + w.put_bits(0, 32); // general_reserved_zero_34bits... + w.put_bits(0, 2); + w.put_bit(0); // general_inbld_flag + w.put_bits(u32::from(level_idc), 8); // general_level_idc +} + +/// §7.3.2.1 — single-layer VPS with the Range-Extensions PTL. +fn write_vps_rext(level_idc: u8) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // vps_video_parameter_set_id + w.put_bit(1); // vps_base_layer_internal_flag + w.put_bit(1); // vps_base_layer_available_flag + w.put_bits(0, 6); // vps_max_layers_minus1 + w.put_bits(0, 3); // vps_max_sub_layers_minus1 + w.put_bit(1); // vps_temporal_id_nesting_flag + w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits + write_ptl_rext(&mut w, level_idc); + w.put_bit(1); // vps_sub_layer_ordering_info_present_flag + w.ue(1); // vps_max_dec_pic_buffering_minus1[0] + w.ue(0); // vps_max_num_reorder_pics[0] + w.ue(0); // vps_max_latency_increase_plus1[0] + w.put_bits(0, 6); // vps_max_layer_id + w.ue(0); // vps_num_layer_sets_minus1 + w.put_bit(0); // vps_timing_info_present_flag + w.put_bit(0); // vps_extension_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.2 — 4:2:0 8-bit SPS (CTB 16, no PCM, SAO off) carrying an +/// `sps_range_extension()` with `implicit_rdpcm_enabled_flag` and +/// `explicit_rdpcm_enabled_flag` both set. +fn write_sps_rext(width: usize, height: usize, level_idc: u8) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl_rext(&mut w, level_idc); + w.ue(0); // sps_seq_parameter_set_id + w.ue(1); // chroma_format_idc = 4:2:0 + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + w.put_bit(0); // conformance_window_flag + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(0); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(0); // amp_enabled_flag + w.put_bit(0); // sample_adaptive_offset_enabled_flag + w.put_bit(0); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(1); // sps_extension_present_flag + w.put_bit(1); // sps_range_extension_flag + w.put_bit(0); // sps_multilayer_extension_flag + w.put_bit(0); // sps_3d_extension_flag + w.put_bit(0); // sps_scc_extension_flag + w.put_bits(0, 4); // sps_extension_4bits + // sps_range_extension() — §7.3.2.2.2. + w.put_bit(0); // transform_skip_rotation_enabled_flag + w.put_bit(0); // transform_skip_context_enabled_flag + w.put_bit(1); // implicit_rdpcm_enabled_flag + w.put_bit(1); // explicit_rdpcm_enabled_flag + w.put_bit(0); // extended_precision_processing_flag + w.put_bit(0); // intra_smoothing_disabled_flag + w.put_bit(0); // high_precision_offsets_enabled_flag + w.put_bit(0); // persistent_rice_adaptation_enabled_flag + w.put_bit(0); // cabac_bypass_alignment_enabled_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.3 — PPS with `transquant_bypass_enabled_flag == 1`, +/// deblocking disabled, sign hiding off. +pub(crate) fn write_pps_bypass() -> Vec { + let mut w = BitWriter::new(); + w.ue(0); // pps_pic_parameter_set_id + w.ue(0); // pps_seq_parameter_set_id + w.put_bit(0); // dependent_slice_segments_enabled_flag + w.put_bit(0); // output_flag_present_flag + w.put_bits(0, 3); // num_extra_slice_header_bits + w.put_bit(0); // sign_data_hiding_enabled_flag + w.put_bit(0); // cabac_init_present_flag + w.ue(0); // num_ref_idx_l0_default_active_minus1 + w.ue(0); // num_ref_idx_l1_default_active_minus1 + w.se(SLICE_QP - 26); // init_qp_minus26 + w.put_bit(0); // constrained_intra_pred_flag + w.put_bit(0); // transform_skip_enabled_flag + w.put_bit(0); // cu_qp_delta_enabled_flag + w.se(0); // pps_cb_qp_offset + w.se(0); // pps_cr_qp_offset + w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag + w.put_bit(0); // weighted_pred_flag + w.put_bit(0); // weighted_bipred_flag + w.put_bit(1); // transquant_bypass_enabled_flag + w.put_bit(0); // tiles_enabled_flag + w.put_bit(0); // entropy_coding_sync_enabled_flag + w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag + w.put_bit(1); // deblocking_filter_control_present_flag + w.put_bit(0); // deblocking_filter_override_enabled_flag + w.put_bit(1); // pps_deblocking_filter_disabled_flag + w.put_bit(0); // pps_scaling_list_data_present_flag + w.put_bit(0); // lists_modification_present_flag + w.ue(0); // log2_parallel_merge_level_minus2 + w.put_bit(0); // slice_segment_header_extension_present_flag + w.put_bit(0); // pps_extension_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §8.6.5 in the ENCODE direction: difference the residual along the +/// DPCM direction so the decoder's accumulation restores it exactly. +fn dpcm_difference(res: &[i32], n: usize, vertical: bool) -> Vec { + let mut out = res.to_vec(); + if vertical { + for y in (1..n).rev() { + for x in 0..n { + out[y * n + x] -= res[(y - 1) * n + x]; + } + } + } else { + for y in 0..n { + for x in (1..n).rev() { + out[y * n + x] -= res[y * n + x - 1]; + } + } + } + out +} + +fn extract(plane: &[u8], pw: usize, x0: usize, y0: usize, n: usize) -> Vec { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + out.push(i32::from(plane[(y0 + j) * pw + x0 + i])); + } + } + out +} + +/// The intra prediction params mirroring the stream's SPS: smoothing +/// on (no rext disable), no strong smoothing, and — because every CU +/// is transquant-bypassed under `implicit_rdpcm_enabled_flag == 1` — +/// the §8.4.4.2.6 `disableIntraBoundaryFilter` (angular 10/26 filters +/// only; the §8.4.4.2.5 DC gate is the SCC flag, which is 0). +fn ip_params(mode: u8, cidx: PredComponent) -> IntraPredParams { + IntraPredParams { + pred_mode_intra: mode, + cidx, + bit_depth: 8, + bit_depth_luma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: false, + chroma_array_type_3: false, + disable_boundary_filter: mode != crate::intra_pred::INTRA_DC, + } +} + +/// Per-CTB intra plan: `(luma_mode, intra_chroma_pred_mode_raw)`. +/// +/// The §8.4.4.2.6 mode-26 (left-column) / mode-10 (top-row) boundary +/// filters are disabled by `disableIntraBoundaryFilter` under implicit +/// RDPCM with transquant bypass; a surveyed black-box reference +/// decoder applies them regardless, so luma DPCM modes are placed +/// where the relevant reference edge is a picture boundary (the +/// §8.4.4.2.2 substitution makes the filter a no-op there): mode 10 +/// on the top CTB row, mode 26 down the left CTB column. Interior CUs +/// carry DC / PLANAR luma (non-DPCM controls) while their CHROMA +/// blocks — never boundary-filtered — take mode 26 / 10 through +/// `intra_chroma_pred_mode` 1 / 2 (Table 8-3), keeping implicit RDPCM +/// dense across the picture. +fn intra_plan(col: usize, row: usize, ctb: usize) -> (u8, u8) { + if row == 0 { + if col == 0 { + (26, 4) // both edges are picture boundaries + } else { + (10, 4) // DM ⇒ chroma 10 + } + } else if col == 0 { + (26, 4) // DM ⇒ chroma 26 + } else { + // Interior: luma control mode (no DPCM), chroma 26 / 10. + let luma = if ctb % 2 == 0 { 1 } else { 0 }; + let chroma_raw = if ctb % 4 < 2 { 1 } else { 2 }; + (luma, chroma_raw) + } +} + +/// Table 8-3 — `IntraPredModeC` from `intra_chroma_pred_mode` and the +/// luma mode (the collision row maps to 34; the plan never collides). +fn mode_c_of(raw: u8, luma: u8) -> u8 { + let base = match raw { + 0 => 0u8, + 1 => 26, + 2 => 10, + 3 => 1, + _ => return luma, + }; + if base == luma { + 34 + } else { + base + } +} + +/// Encode the all-intra bypass slice: one 16x16 `PART_2Nx2N` CU per +/// CTB, `cu_transquant_bypass_flag == 1`, modes per [`intra_plan`]. +/// Lossless: the reconstruction equals the source, so reference +/// samples read the source planes directly. +fn encode_bypass_idr_slice(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Vec { + let (cw, ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + + let mut w = BitWriter::new(); + // ---- slice_segment_header( ) ---- + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(2); // slice_type = I + w.se(0); // slice_qp_delta + w.rbsp_trailing_bits(); // byte_alignment() + + // ---- slice_segment_data( ) ---- + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let (mode, chroma_raw) = intra_plan(ctb % ctbs_x, ctb / ctbs_x, ctb); + let mode_c = mode_c_of(chroma_raw, mode); + + // Luma prediction + residual (lossless recon == source). + let read_y = |x: usize, yy: usize| i32::from(y[yy * width + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read_y, &avail, x0, y0, CTB); + let pred = intra_predict_with_substitution(&marked, &ip_params(mode, PredComponent::Luma)) + .expect("legal prediction"); + let src = extract(y, width, x0, y0, CTB); + let mut res_l: Vec = src.iter().zip(&pred).map(|(s, p)| s - p).collect(); + if mode == 26 || mode == 10 { + res_l = dpcm_difference(&res_l, CTB, mode == 26); + } + + // Chroma 8x8 TBs at (x0/2, y0/2), mode `mode_c`. + let (cx0, cy0) = (x0 / 2, y0 / 2); + let code_chroma = |plane: &[u8], pc: PredComponent| -> Vec { + let read = |x: usize, yy: usize| i32::from(plane[yy * cw + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, cw, ch, CTB / 2, ctbs_x, ctb, 0); + let marked = gather_refs(&read, &avail, cx0, cy0, 8); + let pred = intra_predict_with_substitution(&marked, &ip_params(mode_c, pc)) + .expect("legal prediction"); + let src = extract(plane, cw, cx0, cy0, 8); + let mut res: Vec = src.iter().zip(&pred).map(|(s, p)| s - p).collect(); + if mode_c == 26 || mode_c == 10 { + res = dpcm_difference(&res, 8, mode_c == 26); + } + res + }; + let res_cb = code_chroma(cb, PredComponent::Cb); + let res_cr = code_chroma(cr, PredComponent::Cr); + + // ---- §7.3.8.5 coding_unit( ) ---- + cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1); + // part_mode (intra at MinCb): "1" = PART_2Nx2N. + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); + // Luma mode signalling against the §8.4.2 candidate list. + let avail_l = zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0); + let avail_a = zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0); + let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + let sel = list.iter().position(|&m| m == mode); + cabac.encode_decision( + &mut w, + &mut ctxs.prev_intra_luma_pred_flag[0], + u8::from(sel.is_some()), + ); + modes.record_intra_pb(x0, y0, CTB, mode, false); + match sel { + Some(0) => cabac.encode_bypass(&mut w, 0), + Some(1) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 0); + } + Some(_) => { + cabac.encode_bypass(&mut w, 1); + cabac.encode_bypass(&mut w, 1); + } + None => { + let mut rem = u32::from(mode); + for &c in &list { + if u32::from(mode) > u32::from(c) { + rem -= 1; + } + } + cabac.encode_bypass_bits(&mut w, rem, 5); + } + } + // intra_chroma_pred_mode: 4 (derived) is the single ctx bin + // "0"; values 0..3 are ctx bin "1" plus two FL bypass bits. + if chroma_raw == 4 { + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); + } else { + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 1); + cabac.encode_bypass_bits(&mut w, u32::from(chroma_raw), 2); + } + + // ---- transform_tree / transform_unit ---- + let cbf_cb_f = res_cb.iter().any(|&v| v != 0); + let cbf_cr_f = res_cr.iter().any(|&v| v != 0); + let cbf_luma = res_l.iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + let rc = |log2: u32, is_chroma: bool| ResidualCodingParams { + log2_trafo_size: log2, + is_chroma, + scan_idx: residual_coding_scan_idx( + true, + log2, + u8::from(is_chroma), + 1, + u32::from(if is_chroma { mode_c } else { mode }), + ), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + if cbf_luma { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc(4, false), + &res_l, + ) + .expect("valid luma levels"); + } + if cbf_cb_f { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc(3, true), + &res_cb, + ) + .expect("valid cb levels"); + } + if cbf_cr_f { + encode_residual_coding( + &mut w, + &mut cabac, + &mut ctxs.residual, + &rc(3, true), + &res_cr, + ) + .expect("valid cr levels"); + } + + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + w.finish() +} + +/// Encode the P slice: every CTB one 16x16 CU predicting from the +/// previous picture at MV (0, 0) — `MaxNumMergeCand == 1`, so both +/// merge and skip resolve to the zero candidate. CUs with residual are +/// bypass merge CUs whose per-component `residual_coding( )` signals +/// `explicit_rdpcm_flag` (cycling direction, with flag-0 controls); +/// all-zero CTBs are skip CUs. +#[allow(clippy::too_many_arguments)] +fn encode_bypass_p_slice( + y: &[u8], + cb: &[u8], + cr: &[u8], + ry: &[u8], + rcb: &[u8], + rcr: &[u8], + width: usize, + height: usize, +) -> Vec { + let (cw, _ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + + let mut w = BitWriter::new(); + // ---- slice_segment_header( ) ---- + w.put_bit(1); // first_slice_segment_in_pic_flag + w.ue(0); // slice_pic_parameter_set_id + w.ue(1); // slice_type = P + w.put_bits(1, 8); // slice_pic_order_cnt_lsb (log2 max = 8 bits) + w.put_bit(0); // short_term_ref_pic_set_sps_flag + // st_ref_pic_set( 0 ): one negative reference at −1. + w.ue(1); // num_negative_pics + w.ue(0); // num_positive_pics + w.ue(0); // delta_poc_s0_minus1[0] + w.put_bit(1); // used_by_curr_pic_s0_flag[0] + w.put_bit(0); // num_ref_idx_active_override_flag + w.ue(4); // five_minus_max_num_merge_cand (MaxNumMergeCand = 1) + w.se(0); // slice_qp_delta + w.rbsp_trailing_bits(); // byte_alignment() + + // ---- slice_segment_data( ) ---- + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(1, false), SLICE_QP); + let mut skip_flags = vec![false; ctbs_x * ctbs_y]; + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let col = ctb % ctbs_x; + let row = ctb / ctbs_x; + + // MV (0, 0) prediction from the reference picture: the + // residual is the plane difference. + let diff = |cur: &[u8], refp: &[u8], pw: usize, bx: usize, by: usize, n: usize| { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + let idx = (by + j) * pw + bx + i; + out.push(i32::from(cur[idx]) - i32::from(refp[idx])); + } + } + out + }; + let res_l = diff(y, ry, width, x0, y0, CTB); + let res_cb = diff(cb, rcb, cw, x0 / 2, y0 / 2, 8); + let res_cr = diff(cr, rcr, cw, x0 / 2, y0 / 2, 8); + let all_zero = res_l.iter().all(|&v| v == 0) + && res_cb.iter().all(|&v| v == 0) + && res_cr.iter().all(|&v| v == 0); + + // §7.3.8.5: cu_transquant_bypass_flag precedes cu_skip_flag. + cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1); + // cu_skip_flag with the §9.3.4.2.2 neighbour ctxInc. + let ctx_inc = usize::from(col > 0 && skip_flags[ctb - 1]) + + usize::from(row > 0 && skip_flags[ctb - ctbs_x]); + cabac.encode_decision(&mut w, &mut ctxs.cu_skip_flag[ctx_inc], u8::from(all_zero)); + skip_flags[ctb] = all_zero; + if all_zero { + // Skip CU: MaxNumMergeCand == 1 ⇒ no merge_idx bins. + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + continue; + } + + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); // MODE_INTER + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N + cabac.encode_decision(&mut w, &mut ctxs.merge_flag[0], 1); // merge_flag + // merge_idx absent (MaxNumMergeCand == 1); + // rqt_root_cbf inferred 1 (2Nx2N merge). + + // Per-CTB explicit-RDPCM plan: two of three CUs signal the + // flag (alternating direction), the third is a flag-0 control. + let flag = ctb % 3 != 2; + let vertical = ctb % 2 == 0; + + let cbf_cb_f = res_cb.iter().any(|&v| v != 0); + let cbf_cr_f = res_cr.iter().any(|&v| v != 0); + let cbf_luma = res_l.iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr_f), + ); + // §7.3.8.10: inter at depth 0 with no chroma cbf ⇒ cbf_luma + // inferred 1; otherwise signalled. + if cbf_cb_f || cbf_cr_f { + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + } else { + assert!(cbf_luma, "all-zero CU must have been a skip CU"); + } + + let emit = |cabac: &mut CabacEncoder, + wtr: &mut BitWriter, + ctxs: &mut SliceContexts, + res: &[i32], + log2: u32, + is_chroma: bool| { + // §7.3.8.11 prelude: explicit_rdpcm_flag / dir (inter + + // enabled + bypass; Table 9-32 / 9-33 slot by component). + let slot = usize::from(is_chroma); + cabac.encode_decision(wtr, &mut ctxs.explicit_rdpcm_flag[slot], u8::from(flag)); + let levels = if flag { + cabac.encode_decision( + wtr, + &mut ctxs.explicit_rdpcm_dir_flag[slot], + u8::from(vertical), + ); + dpcm_difference(res, 1 << log2, vertical) + } else { + res.to_vec() + }; + let rc = ResidualCodingParams { + log2_trafo_size: log2, + is_chroma, + scan_idx: residual_coding_scan_idx(false, log2, u8::from(is_chroma), 1, 0), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + encode_residual_coding(wtr, cabac, &mut ctxs.residual, &rc, &levels) + .expect("valid inter levels"); + }; + if cbf_luma { + emit(&mut cabac, &mut w, &mut ctxs, &res_l, 4, false); + } + if cbf_cb_f { + emit(&mut cabac, &mut w, &mut ctxs, &res_cb, 3, true); + } + if cbf_cr_f { + emit(&mut cabac, &mut w, &mut ctxs, &res_cr, 3, true); + } + + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + w.finish() +} + +/// The implicit-RDPCM conformance stream: VPS + SPS(rext) + PPS + +/// one all-intra bypass IDR picture (64x48). +pub(crate) fn build_implicit_stream() -> (Vec, Planes) { + let (w, h) = (64usize, 48usize); + let (y, cb, cr) = source_planes(w, h, 0); + let slice = encode_bypass_idr_slice(&y, &cb, &cr, w, h); + let units = vec![ + nal_unit(32, 0, 0, &write_vps_rext(30)), + nal_unit(33, 0, 0, &write_sps_rext(w, h, 30)), + nal_unit(34, 0, 0, &write_pps_bypass()), + nal_unit(20, 0, 0, &slice), // IDR_N_LP + ]; + (annexb(&units), (y, cb, cr)) +} + +/// The explicit-RDPCM conformance stream: the implicit IDR picture +/// followed by a P picture whose merge CUs carry per-component +/// explicit-RDPCM residuals (64x48, 2 frames). +pub(crate) fn build_explicit_stream() -> (Vec, Planes, Planes) { + let (w, h) = (64usize, 48usize); + let (y0, cb0, cr0) = source_planes(w, h, 0); + let (y1, cb1, cr1) = source_planes(w, h, 1); + let idr = encode_bypass_idr_slice(&y0, &cb0, &cr0, w, h); + let p = encode_bypass_p_slice(&y1, &cb1, &cr1, &y0, &cb0, &cr0, w, h); + let units = vec![ + nal_unit(32, 0, 0, &write_vps_rext(30)), + nal_unit(33, 0, 0, &write_sps_rext(w, h, 30)), + nal_unit(34, 0, 0, &write_pps_bypass()), + nal_unit(20, 0, 0, &idr), // IDR_N_LP + nal_unit(1, 0, 0, &p), // TRAIL_R + ]; + (annexb(&units), (y0, cb0, cr0), (y1, cb1, cr1)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sequence::decode_annexb_sequence; + + fn planes_of(frame: &crate::sequence::DecodedFrame) -> Vec { + frame.picture.to_planar_u8().expect("8-bit planes") + } + + /// The checked-in stream bytes (black-box-reference-validated; + /// see `tests/fixture_bytes/r413-generation-notes.md`) are exactly + /// what the builder produces, and this crate's decoder + /// reconstructs the procedural source losslessly through the + /// §8.4.4.1 implicit-RDPCM path. + #[test] + fn implicit_rdpcm_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_implicit_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r413-rdpcm-implicit.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!(planes_of(&frames[0]), expected, "lossless implicit RDPCM"); + } + + /// Same pin for the explicit-RDPCM P picture (§8.5.4.2 step 3 / + /// §8.5.4.3 step 4 with both mDir values plus flag-0 controls). + #[test] + fn explicit_rdpcm_stream_decodes_lossless() { + let (stream, f0, f1) = build_explicit_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r413-rdpcm-explicit.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 2); + for (frame, (y, cb, cr)) in frames.iter().zip([f0, f1]) { + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!(planes_of(frame), expected, "lossless explicit RDPCM"); + } + } +} diff --git a/vendor/oxideav-h265/src/encoder/residual.rs b/vendor/oxideav-h265/src/encoder/residual.rs new file mode 100644 index 0000000..2f7744c --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/residual.rs @@ -0,0 +1,641 @@ +//! §7.3.8.11 `residual_coding( )` *encoding* — the bin-exact dual of +//! [`crate::residual::decode_residual_coding_with`]. +//! +//! Walks the coefficient array in the same reverse §6.5 scan the +//! decoder uses, emitting `last_sig_coeff_{x,y}_{prefix,suffix}`, +//! `coded_sub_block_flag`, `sig_coeff_flag`, +//! `coeff_abs_level_greater1_flag`, `coeff_abs_level_greater2_flag`, +//! `coeff_sign_flag` and `coeff_abs_level_remaining` through the +//! §9.3.5 arithmetic encoding engine, using the *same* §9.3.4.2 +//! ctxInc derivation helpers as the decoder — so any block this +//! module emits decodes back to the identical `TransCoeffLevel` +//! array with identical context-state evolution (pinned by the +//! differential tests below). +//! +//! Scope bounds (the emitting encoder's fixed configuration, not +//! §7.3.8.11 limits): `sign_data_hiding_enabled_flag == 0` (a hidden +//! sign would require parity-forcing the quantized levels) and no +//! transform-skip / transquant-bypass residual rewrites. + +use crate::binarization::{ + coded_sub_block_flag_ctx_inc_with_edge, coeff_abs_level_greater2_flag_ctx_inc, + coeff_abs_level_remaining_c_max_eq_9_26, coeff_abs_level_remaining_c_rice_param_eq_9_24, + last_sig_coeff_position, last_sig_coeff_prefix_cmax, last_sig_coeff_prefix_ctx_inc, + last_sig_coeff_prefix_ctx_offset_shift, last_sig_coeff_suffix_n_bits, + sig_coeff_flag_ctx_inc_from_sig_ctx, sig_coeff_flag_sig_ctx_dc, sig_coeff_flag_sig_ctx_general, + sig_coeff_flag_sig_ctx_log2_2, sig_coeff_flag_sig_ctx_transform_skip, Greater1State, +}; +use crate::cabac::ContextModel; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::residual::{ResidualCodingParams, ResidualContexts, ResidualElement}; +use crate::scan::{scan_order, ScanIdx}; + +/// Errors from [`encode_residual_coding`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResidualEncodeError { + /// `log2TrafoSize` outside 2..=5. + UnsupportedLog2TrafoSize(u32), + /// A scan §7.4.9.11 never selects. + UnsupportedScanIdx(ScanIdx), + /// `levels.len() != (1 << log2TrafoSize)²`. + LengthMismatch { + /// Required level count. + expected: usize, + /// Supplied level count. + got: usize, + }, + /// Every level is zero — the caller must signal `cbf == 0` + /// instead of invoking `residual_coding( )`. + AllZero, + /// A |level| exceeds the §7.4.9.11 CoeffMax bound for the + /// non-extended-precision profiles (`2^15 − 1`). + LevelOutOfRange(i32), + /// `sign_data_hiding_enabled_flag == 1` — this encoder does not + /// parity-force levels for hidden signs. + SignHidingUnsupported, +} + +impl core::fmt::Display for ResidualEncodeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::UnsupportedLog2TrafoSize(v) => { + write!(f, "residual encode: log2TrafoSize {v} outside 2..=5") + } + Self::UnsupportedScanIdx(s) => { + write!(f, "residual encode: scanIdx {s:?} not reachable") + } + Self::LengthMismatch { expected, got } => { + write!(f, "residual encode: {got} levels, expected {expected}") + } + Self::AllZero => write!(f, "residual encode: all-zero block (cbf must be 0)"), + Self::LevelOutOfRange(v) => write!(f, "residual encode: level {v} out of range"), + Self::SignHidingUnsupported => { + write!(f, "residual encode: sign data hiding not supported") + } + } + } +} + +impl std::error::Error for ResidualEncodeError {} + +/// Bank dispatch — the encode dual of the decoder's +/// `EngineResidualBinSource` element→bank mapping. +fn bank(contexts: &mut ResidualContexts, element: ResidualElement) -> &mut [ContextModel] { + match element { + ResidualElement::LastSigCoeffXPrefix => &mut contexts.last_sig_coeff_x_prefix, + ResidualElement::LastSigCoeffYPrefix => &mut contexts.last_sig_coeff_y_prefix, + ResidualElement::CodedSubBlockFlag => &mut contexts.coded_sub_block_flag, + ResidualElement::SigCoeffFlag => &mut contexts.sig_coeff_flag, + ResidualElement::CoeffAbsLevelGreater1Flag => &mut contexts.coeff_abs_level_greater1_flag, + ResidualElement::CoeffAbsLevelGreater2Flag => &mut contexts.coeff_abs_level_greater2_flag, + } +} + +/// Invert §7.4.9.11 eqs. 7-74..7-77: split a `LastSignificantCoeff*` +/// position into its `(prefix, suffix)` wire pair. +fn split_last_sig_position(v: u32, c_max: u32) -> (u32, Option<(u32, u32)>) { + for prefix in 0..=c_max { + let n_bits = last_sig_coeff_suffix_n_bits(prefix); + if n_bits == 0 { + if last_sig_coeff_position(prefix, None) == v { + return (prefix, None); + } + } else { + let base = last_sig_coeff_position(prefix, Some(0)); + if v >= base && v < base + (1u32 << n_bits) { + return (prefix, Some((v - base, n_bits))); + } + } + } + unreachable!("last-sig position exceeds the TB (caller bounds it)") +} + +/// Emit one `last_sig_coeff_*_prefix` as its §9.3.3.2 TR bin string +/// (unary ones, a terminating zero unless `prefix == cMax`), each bin +/// context-coded with the §9.3.4.2.3 ctxInc. +fn encode_last_sig_prefix( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + contexts: &mut ResidualContexts, + element: ResidualElement, + log2_trafo_size: u32, + is_chroma: bool, + prefix: u32, +) { + let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size); + let (ctx_offset, ctx_shift) = + last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma); + for bin_idx in 0..prefix { + let inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift); + cabac.encode_decision(w, &mut bank(contexts, element)[inc as usize], 1); + } + if prefix < c_max { + let inc = last_sig_coeff_prefix_ctx_inc(prefix, ctx_offset, ctx_shift); + cabac.encode_decision(w, &mut bank(contexts, element)[inc as usize], 0); + } +} + +/// §9.3.3.11 — emit one `coeff_abs_level_remaining` value as the TR +/// prefix (escape at 4 ones) + conditional EGk(`cRiceParam + 1`) +/// suffix, all bypass-coded. The bin-exact dual of +/// [`crate::binarization::decode_coeff_abs_level_remaining_with`]. +fn encode_coeff_abs_level_remaining( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + c_rice_param: u32, + value: u32, +) { + let c_max = coeff_abs_level_remaining_c_max_eq_9_26(c_rice_param); + if value < c_max { + // TR shape: `value >> cRiceParam` ones + terminating zero + + // `cRiceParam` suffix bits. + let prefix_len = value >> c_rice_param; + for _ in 0..prefix_len { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + if c_rice_param > 0 { + cabac.encode_bypass_bits(w, value & ((1 << c_rice_param) - 1), c_rice_param as u8); + } + return; + } + // Escape: 4 ones (no terminator), then EGk with k = cRiceParam+1 + // over `value − cMax`: `prefix_ones` ones + one zero + + // `prefix_ones + k` suffix bits of `v' − ((1 << prefix_ones) − 1) + // << k`. + for _ in 0..4 { + cabac.encode_bypass(w, 1); + } + let k = c_rice_param + 1; + let v = value - c_max; + let mut prefix_ones = 0u32; + while (((1u64 << (prefix_ones + 1)) - 1) << k) <= u64::from(v) { + prefix_ones += 1; + } + let base = ((1u64 << prefix_ones) - 1) << k; + let suffix = u64::from(v) - base; + for _ in 0..prefix_ones { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + let n_bits = prefix_ones + k; + for i in (0..n_bits).rev() { + cabac.encode_bypass(w, ((suffix >> i) & 1) as u8); + } +} + +/// §7.3.8.11 — encode one `residual_coding( )` body from the +/// row-major `TransCoeffLevel` array (`levels[yC * size + xC]`), +/// following the decoder's control flow exactly (same inference +/// rules, same ctxInc derivations, same §9.3.4.2.6 greater-1 state +/// machine). +/// +/// # Errors +/// [`ResidualEncodeError`] on out-of-scope parameters or an all-zero +/// / out-of-range level array. +pub fn encode_residual_coding( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + contexts: &mut ResidualContexts, + params: &ResidualCodingParams, + levels: &[i32], +) -> Result<(), ResidualEncodeError> { + let log2 = params.log2_trafo_size; + if !(2..=5).contains(&log2) { + return Err(ResidualEncodeError::UnsupportedLog2TrafoSize(log2)); + } + let scan_idx_num = u32::from(params.scan_idx.index()); + if scan_idx_num > 2 { + return Err(ResidualEncodeError::UnsupportedScanIdx(params.scan_idx)); + } + if params.sign_data_hiding_enabled_flag { + return Err(ResidualEncodeError::SignHidingUnsupported); + } + let size = 1usize << log2; + if levels.len() != size * size { + return Err(ResidualEncodeError::LengthMismatch { + expected: size * size, + got: levels.len(), + }); + } + if let Some(&bad) = levels.iter().find(|&&v| v.unsigned_abs() > 0x7FFF) { + return Err(ResidualEncodeError::LevelOutOfRange(bad)); + } + let is_chroma = params.is_chroma; + + let pos_scan = scan_order(2, params.scan_idx) + .map_err(|_| ResidualEncodeError::UnsupportedScanIdx(params.scan_idx))?; + let sub_scan = scan_order((log2 - 2) as u8, params.scan_idx) + .map_err(|_| ResidualEncodeError::UnsupportedScanIdx(params.scan_idx))?; + let num_sb_1d = 1usize << (log2 - 2); + + // Locate the last significant coefficient in scan order. + let coeff_at = |sb_i: usize, n: usize| -> i32 { + let sb = sub_scan[sb_i]; + let xc = ((sb.x as usize) << 2) + pos_scan[n].x as usize; + let yc = ((sb.y as usize) << 2) + pos_scan[n].y as usize; + levels[yc * size + xc] + }; + let mut last_sub_block: i32 = -1; + let mut last_scan_pos: i32 = -1; + for i in 0..num_sb_1d * num_sb_1d { + for n in 0..16 { + if coeff_at(i, n) != 0 { + last_sub_block = i as i32; + last_scan_pos = n as i32; + } + } + } + if last_sub_block < 0 { + return Err(ResidualEncodeError::AllZero); + } + + // §7.4.9.11 LastSignificantCoeff{X,Y} (+ the eq.-7-78 swap for the + // vertical scan), split into prefix/suffix wire pairs. + let sb = sub_scan[last_sub_block as usize]; + let last_x = ((sb.x as u32) << 2) + u32::from(pos_scan[last_scan_pos as usize].x); + let last_y = ((sb.y as u32) << 2) + u32::from(pos_scan[last_scan_pos as usize].y); + let (wire_x, wire_y) = if params.scan_idx == ScanIdx::Vertical { + (last_y, last_x) + } else { + (last_x, last_y) + }; + let c_max = last_sig_coeff_prefix_cmax(log2); + let (prefix_x, suffix_x) = split_last_sig_position(wire_x, c_max); + let (prefix_y, suffix_y) = split_last_sig_position(wire_y, c_max); + // §7.3.8.11 bin order: both context-coded prefixes, then both + // bypass suffixes. + encode_last_sig_prefix( + w, + cabac, + contexts, + ResidualElement::LastSigCoeffXPrefix, + log2, + is_chroma, + prefix_x, + ); + encode_last_sig_prefix( + w, + cabac, + contexts, + ResidualElement::LastSigCoeffYPrefix, + log2, + is_chroma, + prefix_y, + ); + if let Some((suffix, n_bits)) = suffix_x { + cabac.encode_bypass_bits(w, suffix, n_bits as u8); + } + if let Some((suffix, n_bits)) = suffix_y { + cabac.encode_bypass_bits(w, suffix, n_bits as u8); + } + + // coded_sub_block_flag grid, filled progressively in reverse scan + // order exactly as the decoder builds it. + let mut csbf = vec![0u8; num_sb_1d * num_sb_1d]; + let csbf_at = |grid: &[u8], xs: usize, ys: usize| -> u8 { + if xs < num_sb_1d && ys < num_sb_1d { + grid[ys * num_sb_1d + xs] + } else { + 0 + } + }; + + let mut g1_state = Greater1State::new(); + let mut last_g1_bin: u8 = 0; + + for i in (0..=last_sub_block).rev() { + let sb = sub_scan[i as usize]; + let (xs, ys) = (u32::from(sb.x), u32::from(sb.y)); + let is_last_sb = i == last_sub_block; + let any_nonzero = (0..16).any(|n| coeff_at(i as usize, n) != 0); + + // coded_sub_block_flag: coded for 0 < i < lastSubBlock, + // inferred 1 otherwise. + let mut infer_sb_dc_sig = false; + let sb_coded: u8 = if i < last_sub_block && i > 0 { + let right = csbf_at(&csbf, xs as usize + 1, ys as usize); + let below = csbf_at(&csbf, xs as usize, ys as usize + 1); + let ctx_inc = + coded_sub_block_flag_ctx_inc_with_edge(is_chroma, xs, ys, log2, right, below); + let bin = u8::from(any_nonzero); + cabac.encode_decision( + w, + &mut bank(contexts, ResidualElement::CodedSubBlockFlag)[ctx_inc as usize], + bin, + ); + infer_sb_dc_sig = true; + bin + } else { + 1 + }; + csbf[ys as usize * num_sb_1d + xs as usize] = sb_coded; + if sb_coded == 0 { + continue; + } + + // sig_coeff_flag pass (same coding/inference split as decode). + let mut sig = [0u8; 16]; + if is_last_sb { + sig[last_scan_pos as usize] = 1; + } + let start_n: i32 = if is_last_sb { last_scan_pos - 1 } else { 15 }; + for n in (0..=start_n).rev() { + let significant = u8::from(coeff_at(i as usize, n as usize) != 0); + let xc = (xs << 2) + u32::from(pos_scan[n as usize].x); + let yc = (ys << 2) + u32::from(pos_scan[n as usize].y); + if n > 0 || !infer_sb_dc_sig { + let sig_ctx = if params.transform_skip_sig_ctx { + sig_coeff_flag_sig_ctx_transform_skip(is_chroma) + } else if log2 == 2 { + sig_coeff_flag_sig_ctx_log2_2(xc & 3, yc & 3) + } else if xc + yc == 0 { + sig_coeff_flag_sig_ctx_dc(is_chroma, log2, scan_idx_num) + } else { + let right = csbf_at(&csbf, xs as usize + 1, ys as usize); + let below = csbf_at(&csbf, xs as usize, ys as usize + 1); + sig_coeff_flag_sig_ctx_general( + is_chroma, + log2, + xc, + yc, + xs, + ys, + right, + below, + scan_idx_num, + ) + }; + let ctx_inc = sig_coeff_flag_ctx_inc_from_sig_ctx(sig_ctx, is_chroma); + cabac.encode_decision( + w, + &mut bank(contexts, ResidualElement::SigCoeffFlag)[ctx_inc as usize], + significant, + ); + sig[n as usize] = significant; + if significant == 1 { + infer_sb_dc_sig = false; + } + } else { + // n == 0 with the DC inference alive: the decoder + // infers sig[0] = 1; a conforming encoder only reaches + // here when the DC coefficient IS significant (a coded + // sub-block cannot be all-zero). + debug_assert_eq!(significant, 1, "coded sub-block with only a zero DC"); + sig[0] = 1; + } + } + + // greater-1 pass: the first 8 significant positions carry a + // coded flag; the §9.3.4.2.6 state machine advances on the + // encoder's own bins. + let mut first_sig_scan_pos: i32 = 16; + let mut last_sig_scan_pos: i32 = -1; + let mut num_greater1: u32 = 0; + let mut last_greater1_scan_pos: i32 = -1; + let mut g1 = [0u8; 16]; + let mut entered_subblock = false; + for n in (0..16usize).rev() { + if sig[n] == 1 { + let abs = coeff_at(i as usize, n).unsigned_abs(); + if num_greater1 < 8 { + if !entered_subblock { + g1_state.on_subblock_entry(i as u32, is_chroma, last_g1_bin); + entered_subblock = true; + } + let ctx_inc = g1_state.current_ctx_inc(is_chroma); + let bin = u8::from(abs > 1); + cabac.encode_decision( + w, + &mut bank(contexts, ResidualElement::CoeffAbsLevelGreater1Flag) + [ctx_inc as usize], + bin, + ); + g1_state.on_coeff_abs_level_greater1_flag(bin); + last_g1_bin = bin; + g1[n] = bin; + num_greater1 += 1; + if bin == 1 && last_greater1_scan_pos == -1 { + last_greater1_scan_pos = n as i32; + } + } + if last_sig_scan_pos == -1 { + last_sig_scan_pos = n as i32; + } + first_sig_scan_pos = n as i32; + } + } + let _ = (first_sig_scan_pos, last_sig_scan_pos); // sign hiding off + + // greater-2 flag — at most once per sub-block. + let mut g2 = [0u8; 16]; + if last_greater1_scan_pos != -1 { + let ctx_inc = coeff_abs_level_greater2_flag_ctx_inc(g1_state.ctx_set(), is_chroma); + let abs = coeff_at(i as usize, last_greater1_scan_pos as usize).unsigned_abs(); + let bin = u8::from(abs > 2); + cabac.encode_decision( + w, + &mut bank(contexts, ResidualElement::CoeffAbsLevelGreater2Flag)[ctx_inc as usize], + bin, + ); + g2[last_greater1_scan_pos as usize] = bin; + } + + // coeff_sign_flag pass (bypass; sign hiding disabled). + for n in (0..16usize).rev() { + if sig[n] == 1 { + let sign = u8::from(coeff_at(i as usize, n) < 0); + cabac.encode_bypass(w, sign); + } + } + + // level pass: coeff_abs_level_remaining with the §9.3.3.11 + // per-sub-block Rice adaptation. + let mut num_sig_coeff: u32 = 0; + let mut c_last_abs_level: u32 = 0; + let mut c_last_rice_param: u32 = 0; + for n in (0..16usize).rev() { + if sig[n] != 1 { + continue; + } + let abs = coeff_at(i as usize, n).unsigned_abs(); + let base_level = 1 + u32::from(g1[n]) + u32::from(g2[n]); + let threshold = if num_sig_coeff < 8 { + if n as i32 == last_greater1_scan_pos { + 3 + } else { + 2 + } + } else { + 1 + }; + if base_level == threshold { + let remaining = abs - base_level; + let c_rice_param = coeff_abs_level_remaining_c_rice_param_eq_9_24( + c_last_abs_level, + c_last_rice_param, + ); + encode_coeff_abs_level_remaining(w, cabac, c_rice_param, remaining); + c_last_abs_level = abs; + c_last_rice_param = c_rice_param; + } else { + // The flag pass fully determines the level here. + debug_assert_eq!(abs, base_level, "level not representable without remaining"); + } + num_sig_coeff += 1; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + use crate::cabac::CabacEngine; + use crate::residual::{decode_residual_coding, ResidualContexts}; + + /// Differential harness: encode `levels` (row-major), terminate, + /// then decode with the crate's §7.3.8.11 decoder from identically + /// initialized contexts — levels AND context states must match. + fn roundtrip(params: &ResidualCodingParams, levels: &[i32]) { + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + let mut enc_ctx = ResidualContexts::init(0, 26); + encode_residual_coding(&mut w, &mut cabac, &mut enc_ctx, params, levels).expect("encode"); + cabac.encode_terminate(&mut w, 1); + w.align_zero(); + let bytes = w.finish(); + + let mut engine = CabacEngine::new(BitReader::new(&bytes)).expect("init"); + let mut dec_ctx = ResidualContexts::init(0, 26); + let block = decode_residual_coding(&mut engine, &mut dec_ctx, params).expect("decode"); + assert_eq!(block.levels, levels, "decoded levels"); + assert_eq!(engine.decode_terminate().unwrap(), 1, "terminator"); + assert_eq!(enc_ctx, dec_ctx, "context state evolution"); + } + + fn params(log2: u32, is_chroma: bool, scan: ScanIdx) -> ResidualCodingParams { + ResidualCodingParams { + log2_trafo_size: log2, + is_chroma, + scan_idx: scan, + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + } + } + + #[test] + fn single_dc_coefficient_roundtrips() { + for log2 in 2..=5u32 { + let size = 1usize << log2; + let mut levels = vec![0i32; size * size]; + levels[0] = -3; + roundtrip(¶ms(log2, false, ScanIdx::Diagonal), &levels); + roundtrip(¶ms(log2, true, ScanIdx::Diagonal), &levels); + } + } + + #[test] + fn single_far_coefficient_exercises_last_sig_suffix() { + // 32x32: position (25, 30) needs prefix > 3 + suffix bits. + let size = 32usize; + let mut levels = vec![0i32; size * size]; + levels[30 * size + 25] = 7; + levels[0] = 1; + roundtrip(¶ms(5, false, ScanIdx::Diagonal), &levels); + } + + #[test] + fn dense_blocks_roundtrip_all_sizes_and_scans() { + let mut x = 0x2468_ACE1u32; + let mut rand = move || { + x = x.wrapping_mul(1_103_515_245).wrapping_add(12_345); + x >> 16 + }; + for log2 in 2..=5u32 { + let size = 1usize << log2; + let scans: &[ScanIdx] = if log2 <= 3 { + &[ScanIdx::Diagonal, ScanIdx::Horizontal, ScanIdx::Vertical] + } else { + &[ScanIdx::Diagonal] + }; + for &scan in scans { + for density in [2u32, 6, 16] { + for chroma in [false, true] { + let levels: Vec = (0..size * size) + .map(|_| { + let r = rand(); + if r % 16 < density { + let mag = (r >> 8) % 200; + let v = mag as i32 + 1; + if r & 1 == 0 { + v + } else { + -v + } + } else { + 0 + } + }) + .collect(); + if levels.iter().all(|&v| v == 0) { + continue; + } + roundtrip(¶ms(log2, chroma, scan), &levels); + } + } + } + } + } + + #[test] + fn large_escape_levels_roundtrip() { + // Rice escapes deep into EGk territory + the CoeffMax edge. + let size = 8usize; + let mut levels = vec![0i32; size * size]; + levels[0] = 32767; + levels[1] = -32768 + 1; // -32767 + levels[8] = 1000; + levels[9] = -1; + roundtrip(¶ms(3, false, ScanIdx::Diagonal), &levels); + } + + #[test] + fn dc_only_middle_subblock_uses_inferred_sig() { + // A middle sub-block whose only significant coefficient is its + // DC cell: the decoder infers sig[0] without a bin — the + // encoder must skip it symmetrically. + let size = 16usize; + let mut levels = vec![0i32; size * size]; + levels[15 * size + 15] = 2; // last sub-block (3,3) + levels[4 * size + 4] = 5; // sub-block (1,1) DC only + levels[0] = -9; + roundtrip(¶ms(4, false, ScanIdx::Diagonal), &levels); + } + + #[test] + fn rejects_all_zero_and_out_of_range() { + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + let mut ctx = ResidualContexts::init(0, 26); + let p = params(2, false, ScanIdx::Diagonal); + assert_eq!( + encode_residual_coding(&mut w, &mut cabac, &mut ctx, &p, &[0i32; 16]), + Err(ResidualEncodeError::AllZero) + ); + let mut levels = [0i32; 16]; + levels[0] = 40000; + assert_eq!( + encode_residual_coding(&mut w, &mut cabac, &mut ctx, &p, &levels), + Err(ResidualEncodeError::LevelOutOfRange(40000)) + ); + } +} diff --git a/vendor/oxideav-h265/src/encoder/scc_streams.rs b/vendor/oxideav-h265/src/encoder/scc_streams.rs new file mode 100644 index 0000000..5159e89 --- /dev/null +++ b/vendor/oxideav-h265/src/encoder/scc_streams.rs @@ -0,0 +1,936 @@ +//! Self-built SCC conformance streams (test-only): §8.6.8 adaptive +//! colour transform and current-picture referencing (intra block +//! copy). +//! +//! No black-box encoder binary in this workspace's toolchain emits the +//! screen-content-coding extensions, so these streams are assembled by +//! this crate's own header writers and CABAC encoder (the round-413 +//! RDPCM / round-416 CCP methodology): +//! +//! * an **ACT stream** — 4:4:4 lossless (transquant-bypass) all-intra +//! IDR whose CUs alternate `tu_residual_act_flag` 1 / 0; act-1 CUs +//! carry forward-lifted (YCgCo-R-shaped, eqs 8-336..8-339 inverse) +//! residual triples so the §8.6.8.2 inverse restores the source +//! exactly, act-0 CUs are plain controls; +//! * an **IBC stream** — a 4:2:0 IDR picture whose slices are +//! `slice_type == P` with `pps_curr_pic_ref_enabled_flag == 1` +//! (`RefPicList0 == [ currPic ]`): CTB 0 is an intra CU, every +//! other CTB an AMVP coding unit whose motion vector points at the +//! already-decoded CTB to the left (or above, for the first +//! column), with a bypass residual correcting the copy to the +//! source — the eqs 8-98..8-101 integer path and the §8.5.3.1 +//! current-picture prediction reconstruct losslessly. +//! +//! The checked-in copies under `tests/fixture_bytes/` are pinned by +//! the tests here: (a) the builders still produce those exact bytes, +//! (b) this crate's decoder reconstructs the procedural source +//! planes. Black-box validation status is recorded in +//! `tests/fixture_bytes/r416-generation-notes.md`. + +use crate::binarization::{ + cbf_cb_ctx_inc, cbf_cr_ctx_inc, cbf_luma_ctx_inc, intra_luma_cand_mode_list, +}; +use crate::cabac::init_type; +use crate::ctx_init::SliceContexts; +use crate::encoder::bitwriter::BitWriter; +use crate::encoder::cabac::CabacEncoder; +use crate::encoder::ccp_streams::{extract, ip_params_444, source_planes_444, Planes}; +use crate::encoder::intra::{gather_refs, zscan_avail}; +use crate::encoder::nal::{annexb, nal_unit}; +use crate::encoder::residual::encode_residual_coding; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{intra_predict_with_substitution, Component as PredComponent}; +use crate::motion::MotionField; +use crate::pu_mv::{resolve_pu_motion, PartMode, PuGeometry, PuMvContext}; +use crate::residual::{residual_coding_scan_idx, ResidualCodingParams}; +use crate::slice_data::PredictionUnit; + +/// CTB / coding-block log2 size (16x16, `MinCbSizeY == CtbSizeY`). +const CTB_LOG2: u32 = 4; +const CTB: usize = 1 << CTB_LOG2; +/// SliceQpY (immaterial — every CU is transquant-bypassed). +const SLICE_QP: i32 = 26; + +/// §7.3.3 — profile tier level for Screen Content Coding extensions +/// (`general_profile_idc == 9`); `chroma444` selects the 4:4:4 vs +/// 4:2:0 constraint-flag pattern. Profile 9 carries +/// `general_max_14bit_constraint_flag` + 33 reserved bits. +fn write_ptl_scc(w: &mut BitWriter, level_idc: u8, chroma444: bool) { + w.put_bits(0, 2); // general_profile_space + w.put_bit(0); // general_tier_flag + w.put_bits(9, 5); // general_profile_idc = 9 (SCC) + let mut compat: u32 = 0; + compat |= 1 << (31 - 9); // flag[9] — SCC + w.put_bits(compat, 32); + w.put_bit(1); // general_progressive_source_flag + w.put_bit(0); // general_interlaced_source_flag + w.put_bit(1); // general_non_packed_constraint_flag + w.put_bit(1); // general_frame_only_constraint_flag + w.put_bit(1); // general_max_12bit_constraint_flag + w.put_bit(1); // general_max_10bit_constraint_flag + w.put_bit(1); // general_max_8bit_constraint_flag + w.put_bit(u8::from(!chroma444)); // general_max_422chroma_constraint_flag + w.put_bit(u8::from(!chroma444)); // general_max_420chroma_constraint_flag + w.put_bit(0); // general_max_monochrome_constraint_flag + w.put_bit(0); // general_intra_constraint_flag + w.put_bit(0); // general_one_picture_only_constraint_flag + w.put_bit(0); // general_lower_bit_rate_constraint_flag + w.put_bit(1); // general_max_14bit_constraint_flag + // general_reserved_zero_33bits + w.put_bits(0, 32); + w.put_bit(0); + w.put_bit(0); // general_inbld_flag (reserved zero) + w.put_bits(level_idc as u32, 8); // general_level_idc +} + +/// §7.3.2.1 — minimal single-layer VPS carrying the SCC PTL. +fn write_vps_scc(level_idc: u8, chroma444: bool) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // vps_video_parameter_set_id + w.put_bit(1); // vps_base_layer_internal_flag + w.put_bit(1); // vps_base_layer_available_flag + w.put_bits(0, 6); // vps_max_layers_minus1 + w.put_bits(0, 3); // vps_max_sub_layers_minus1 + w.put_bit(1); // vps_temporal_id_nesting_flag + w.put_bits(0xFFFF, 16); // vps_reserved_0xffff_16bits + write_ptl_scc(&mut w, level_idc, chroma444); + w.put_bit(1); // vps_sub_layer_ordering_info_present_flag + w.ue(1); // vps_max_dec_pic_buffering_minus1[0] + w.ue(0); // vps_max_num_reorder_pics[0] + w.ue(0); // vps_max_latency_increase_plus1[0] + w.put_bits(0, 6); // vps_max_layer_id + w.ue(0); // vps_num_layer_sets_minus1 + w.put_bit(0); // vps_timing_info_present_flag + w.put_bit(0); // vps_extension_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.2 — SCC SPS (CTB 16, no PCM, SAO off) carrying an +/// `sps_scc_extension()`; `chroma444` selects the chroma format and +/// `curr_pic_ref` sets `sps_curr_pic_ref_enabled_flag`. +fn write_sps_scc( + width: usize, + height: usize, + level_idc: u8, + chroma444: bool, + curr_pic_ref: bool, +) -> Vec { + let mut w = BitWriter::new(); + w.put_bits(0, 4); // sps_video_parameter_set_id + w.put_bits(0, 3); // sps_max_sub_layers_minus1 + w.put_bit(1); // sps_temporal_id_nesting_flag + write_ptl_scc(&mut w, level_idc, chroma444); + w.ue(0); // sps_seq_parameter_set_id + w.ue(if chroma444 { 3 } else { 1 }); // chroma_format_idc + if chroma444 { + w.put_bit(0); // separate_colour_plane_flag + } + w.ue(width as u32); // pic_width_in_luma_samples + w.ue(height as u32); // pic_height_in_luma_samples + w.put_bit(0); // conformance_window_flag + w.ue(0); // bit_depth_luma_minus8 + w.ue(0); // bit_depth_chroma_minus8 + w.ue(4); // log2_max_pic_order_cnt_lsb_minus4 + w.put_bit(1); // sps_sub_layer_ordering_info_present_flag + w.ue(1); // sps_max_dec_pic_buffering_minus1[0] + w.ue(0); // sps_max_num_reorder_pics[0] + w.ue(0); // sps_max_latency_increase_plus1[0] + w.ue(CTB_LOG2 - 3); // log2_min_luma_coding_block_size_minus3 (16) + w.ue(0); // log2_diff_max_min_luma_coding_block_size (CTB 16) + w.ue(0); // log2_min_luma_transform_block_size_minus2 (4) + w.ue(2); // log2_diff_max_min_luma_transform_block_size (16) + w.ue(0); // max_transform_hierarchy_depth_inter + w.ue(0); // max_transform_hierarchy_depth_intra + w.put_bit(0); // scaling_list_enabled_flag + w.put_bit(0); // amp_enabled_flag + w.put_bit(0); // sample_adaptive_offset_enabled_flag + w.put_bit(0); // pcm_enabled_flag + w.ue(0); // num_short_term_ref_pic_sets + w.put_bit(0); // long_term_ref_pics_present_flag + w.put_bit(0); // sps_temporal_mvp_enabled_flag + w.put_bit(0); // strong_intra_smoothing_enabled_flag + w.put_bit(0); // vui_parameters_present_flag + w.put_bit(1); // sps_extension_present_flag + w.put_bit(0); // sps_range_extension_flag + w.put_bit(0); // sps_multilayer_extension_flag + w.put_bit(0); // sps_3d_extension_flag + w.put_bit(1); // sps_scc_extension_flag + w.put_bits(0, 4); // sps_extension_4bits + // sps_scc_extension() — §7.3.2.2.3. + w.put_bit(u8::from(curr_pic_ref)); // sps_curr_pic_ref_enabled_flag + w.put_bit(0); // palette_mode_enabled_flag + w.put_bits(0, 2); // motion_vector_resolution_control_idc + w.put_bit(0); // intra_boundary_filtering_disabled_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// §7.3.2.3 — bypass PPS carrying a `pps_scc_extension()` with the +/// given `pps_curr_pic_ref_enabled_flag` / ACT flags. +fn write_pps_scc(curr_pic_ref: bool, act: bool, ccp: bool) -> Vec { + let mut w = BitWriter::new(); + w.ue(0); // pps_pic_parameter_set_id + w.ue(0); // pps_seq_parameter_set_id + w.put_bit(0); // dependent_slice_segments_enabled_flag + w.put_bit(0); // output_flag_present_flag + w.put_bits(0, 3); // num_extra_slice_header_bits + w.put_bit(0); // sign_data_hiding_enabled_flag + w.put_bit(0); // cabac_init_present_flag + w.ue(0); // num_ref_idx_l0_default_active_minus1 + w.ue(0); // num_ref_idx_l1_default_active_minus1 + w.se(SLICE_QP - 26); // init_qp_minus26 + w.put_bit(0); // constrained_intra_pred_flag + w.put_bit(0); // transform_skip_enabled_flag + w.put_bit(0); // cu_qp_delta_enabled_flag + w.se(0); // pps_cb_qp_offset + w.se(0); // pps_cr_qp_offset + w.put_bit(0); // pps_slice_chroma_qp_offsets_present_flag + w.put_bit(0); // weighted_pred_flag + w.put_bit(0); // weighted_bipred_flag + w.put_bit(1); // transquant_bypass_enabled_flag + w.put_bit(0); // tiles_enabled_flag + w.put_bit(0); // entropy_coding_sync_enabled_flag + w.put_bit(1); // pps_loop_filter_across_slices_enabled_flag + w.put_bit(1); // deblocking_filter_control_present_flag + w.put_bit(0); // deblocking_filter_override_enabled_flag + w.put_bit(1); // pps_deblocking_filter_disabled_flag + w.put_bit(0); // pps_scaling_list_data_present_flag + w.put_bit(0); // lists_modification_present_flag + w.ue(0); // log2_parallel_merge_level_minus2 + w.put_bit(0); // slice_segment_header_extension_present_flag + w.put_bit(1); // pps_extension_present_flag + w.put_bit(u8::from(ccp)); // pps_range_extension_flag + w.put_bit(0); // pps_multilayer_extension_flag + w.put_bit(0); // pps_3d_extension_flag + w.put_bit(1); // pps_scc_extension_flag + w.put_bits(0, 4); // pps_extension_4bits + if ccp { + // pps_range_extension() — §7.3.2.3.2 (transform_skip off). + w.put_bit(1); // cross_component_prediction_enabled_flag + w.put_bit(0); // chroma_qp_offset_list_enabled_flag + w.ue(0); // log2_sao_offset_scale_luma + w.ue(0); // log2_sao_offset_scale_chroma + } + // pps_scc_extension() — §7.3.2.3.3. + w.put_bit(u8::from(curr_pic_ref)); // pps_curr_pic_ref_enabled_flag + w.put_bit(u8::from(act)); // residual_adaptive_colour_transform_enabled_flag + if act { + w.put_bit(0); // pps_slice_act_qp_offsets_present_flag + w.se(5); // pps_act_y_qp_offset_plus5 (PpsActQpOffsetY = 0) + w.se(5); // pps_act_cb_qp_offset_plus5 (PpsActQpOffsetCb = 0) + w.se(3); // pps_act_cr_qp_offset_plus3 (PpsActQpOffsetCr = 0) + } + w.put_bit(0); // pps_palette_predictor_initializers_present_flag + w.rbsp_trailing_bits(); + w.finish() +} + +/// The forward lifting matching the §8.6.8.2 lossless inverse: given +/// the wanted post-inverse triple `(c0, c1, c2)` = (rY, rCb, rCr), +/// produce the coded triple. +fn act_forward(c0: i32, c1: i32, c2: i32) -> (i32, i32, i32) { + let co = c2 - c1; + let t = c1 + (co >> 1); + let cg = c0 - t; + let y = t + (cg >> 1); + (y, cg, co) +} + +/// Encode the luma-mode signalling of one intra 16x16 PART_2Nx2N CU +/// against the §8.4.2 candidate list, recording the mode. +#[allow(clippy::too_many_arguments)] +fn encode_intra_luma_mode( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + modes: &mut IntraModeField, + x0: usize, + y0: usize, + mode: u8, + avail_l: bool, + avail_a: bool, +) { + let cand_a = modes.cand_intra_pred_mode(x0, y0, Neighbour::Left, avail_l); + let cand_b = modes.cand_intra_pred_mode(x0, y0, Neighbour::Above, avail_a); + let list = intra_luma_cand_mode_list(cand_a, cand_b); + let sel = list.iter().position(|&m| m == mode); + cabac.encode_decision( + w, + &mut ctxs.prev_intra_luma_pred_flag[0], + u8::from(sel.is_some()), + ); + modes.record_intra_pb(x0, y0, CTB, mode, false); + match sel { + Some(0) => cabac.encode_bypass(w, 0), + Some(1) => { + cabac.encode_bypass(w, 1); + cabac.encode_bypass(w, 0); + } + Some(_) => { + cabac.encode_bypass(w, 1); + cabac.encode_bypass(w, 1); + } + None => { + let mut rem = u32::from(mode); + for &c in &list { + if u32::from(mode) > u32::from(c) { + rem -= 1; + } + } + cabac.encode_bypass_bits(w, rem, 5); + } + } +} + +// --------------------------------------------------------------------------- +// ACT stream (4:4:4 all-intra) +// --------------------------------------------------------------------------- + +/// Per-CTB ACT plan: `(luma_mode, tu_residual_act_flag, cb_scale, +/// cr_scale)` — DM chroma throughout; the act flag alternates so +/// plain CUs interleave as controls, and the cross-component +/// prediction scales cycle so CCP applies BOTH under and without the +/// colour transform (the §8.4.4.1 step-8 before §8.6.8 ordering). +fn act_plan(ctb: usize) -> (u8, bool, i32, i32) { + const MODES: [u8; 6] = [0, 1, 26, 10, 18, 34]; + const SCALES: [i32; 5] = [0, 1, -2, 4, -8]; + ( + MODES[ctb % MODES.len()], + ctb % 2 == 0, + SCALES[ctb % SCALES.len()], + SCALES[(ctb + 2) % SCALES.len()], + ) +} + +/// Encode the all-intra 4:4:4 bypass ACT slice: one 16x16 PART_2Nx2N +/// CU per CTB, DM chroma, `tu_residual_act_flag` per [`act_plan`]. +fn encode_act_idr_slice(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Vec { + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + + let mut w = BitWriter::new(); + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(2); // slice_type = I + w.se(0); // slice_qp_delta + w.rbsp_trailing_bits(); // byte_alignment() + + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(2, false), SLICE_QP); + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let (mode, act, cb_scale, cr_scale) = act_plan(ctb); + + // Component residuals (lossless recon == source). + let residual = |plane: &[u8], pc: PredComponent| -> Vec { + let read = |x: usize, yy: usize| i32::from(plane[yy * width + x]); + let avail = |nx: i64, ny: i64| zscan_avail(nx, ny, width, height, CTB, ctbs_x, ctb, 0); + let marked = gather_refs(&read, &avail, x0, y0, CTB); + let pred = intra_predict_with_substitution(&marked, &ip_params_444(mode, pc)) + .expect("legal prediction"); + let src = extract(plane, width, x0, y0, CTB); + src.iter().zip(&pred).map(|(s, p)| s - p).collect() + }; + let r_y = residual(y, PredComponent::Luma); + let r_cb = residual(cb, PredComponent::Cb); + let r_cr = residual(cr, PredComponent::Cr); + + // act == 1: code the forward-lifted triples; the decoder + // applies §8.4.4.1 step-8 CCP BEFORE the §8.6.8 inverse, so + // the CCP term is subtracted from the post-lifting chroma. + let (res_l, res_cb, res_cr) = if act { + let mut cl = Vec::with_capacity(r_y.len()); + let mut ccb = Vec::with_capacity(r_y.len()); + let mut ccr = Vec::with_capacity(r_y.len()); + for k in 0..r_y.len() { + let (a, b, c) = act_forward(r_y[k], r_cb[k], r_cr[k]); + cl.push(a); + ccb.push(b); + ccr.push(c); + } + (cl, ccb, ccr) + } else { + (r_y, r_cb, r_cr) + }; + let cbf_luma_pre = res_l.iter().any(|&v| v != 0); + // §7.3.8.10: cross_comp_pred needs cbf_luma. + let (cb_scale, cr_scale) = if cbf_luma_pre { + (cb_scale, cr_scale) + } else { + (0, 0) + }; + let ccp_sub = |res: &[i32], scale: i32| -> Vec { + res.iter() + .zip(&res_l) + .map(|(&v, &ry)| v - ((scale * ry) >> 3)) + .collect() + }; + let res_cb = ccp_sub(&res_cb, cb_scale); + let res_cr = ccp_sub(&res_cr, cr_scale); + + // ---- coding_unit( ) ---- + cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1); + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N + let avail_l = zscan_avail(x0 as i64 - 1, y0 as i64, width, height, CTB, ctbs_x, ctb, 0); + let avail_a = zscan_avail(x0 as i64, y0 as i64 - 1, width, height, CTB, ctbs_x, ctb, 0); + encode_intra_luma_mode( + &mut w, &mut cabac, &mut ctxs, &mut modes, x0, y0, mode, avail_l, avail_a, + ); + // intra_chroma_pred_mode = 4 (derived / DM): single ctx bin 0. + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); + + // ---- transform_tree / transform_unit ---- + let cbf_cb_f = res_cb.iter().any(|&v| v != 0); + let cbf_cr_f = res_cr.iter().any(|&v| v != 0); + let cbf_luma = res_l.iter().any(|&v| v != 0); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr_f), + ); + cabac.encode_decision( + &mut w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + // §7.3.8.10: tu_residual_act_flag leads the transform unit + // (2Nx2N + DM ⇒ the intra gate holds) when any cbf is set. + if cbf_luma || cbf_cb_f || cbf_cr_f { + cabac.encode_decision(&mut w, &mut ctxs.tu_residual_act_flag[0], u8::from(act)); + } + let rc = |is_chroma: bool| ResidualCodingParams { + log2_trafo_size: 4, + is_chroma, + scan_idx: residual_coding_scan_idx(true, 4, u8::from(is_chroma), 3, u32::from(mode)), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + if cbf_luma { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(false), &res_l) + .expect("valid luma levels"); + } + // §7.3.8.10 in-place chroma: cross_comp_pred precedes each + // chroma residual_coding (gate: enabled && cbf_luma && DM). + if cbf_luma { + crate::encoder::ccp_streams::encode_cross_comp_pred( + &mut w, &mut cabac, &mut ctxs, 0, cb_scale, + ); + } + if cbf_cb_f { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cb) + .expect("valid cb levels"); + } + if cbf_luma { + crate::encoder::ccp_streams::encode_cross_comp_pred( + &mut w, &mut cabac, &mut ctxs, 1, cr_scale, + ); + } + if cbf_cr_f { + encode_residual_coding(&mut w, &mut cabac, &mut ctxs.residual, &rc(true), &res_cr) + .expect("valid cr levels"); + } + + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + w.finish() +} + +/// The ACT conformance stream: VPS + SPS(scc, 4:4:4) + PPS(scc, ACT) + +/// one all-intra bypass IDR picture (64x48). +pub(crate) fn build_act_stream() -> (Vec, Planes) { + let (w, h) = (64usize, 48usize); + let (y, cb, cr) = source_planes_444(w, h); + let slice = encode_act_idr_slice(&y, &cb, &cr, w, h); + let units = vec![ + nal_unit(32, 0, 0, &write_vps_scc(30, true)), + nal_unit(33, 0, 0, &write_sps_scc(w, h, 30, true, false)), + nal_unit(34, 0, 0, &write_pps_scc(false, true, true)), + nal_unit(20, 0, 0, &slice), // IDR_N_LP + ]; + (annexb(&units), (y, cb, cr)) +} + +// --------------------------------------------------------------------------- +// IBC stream (4:2:0 IDR with P slice referencing the current picture) +// --------------------------------------------------------------------------- + +/// Deterministic 4:2:0 source planes for the IBC picture: a repeating +/// texture with per-CTB perturbation (so IBC copies are close but the +/// residual is never all-zero). +fn source_planes_420(w: usize, h: usize) -> Planes { + let lum = |x: i32, y: i32| -> u8 { + let g = ((x % 16) * 9 + (y % 16) * 4) % 128; + let p = (x / 16 + y / 16) * 5 % 31; + (32 + g + p).clamp(0, 255) as u8 + }; + let chr = |x: i32, y: i32, ph: i32| -> u8 { + let g = ((x % 8) * 11 + (y % 8) * 6 + ph) % 100; + let p = (x / 8 + y / 8) * 3 % 17; + (60 + g + p).clamp(0, 255) as u8 + }; + let mut y_p = Vec::with_capacity(w * h); + for yy in 0..h as i32 { + for xx in 0..w as i32 { + y_p.push(lum(xx, yy)); + } + } + let (cw, ch) = (w / 2, h / 2); + let mut cb_p = Vec::with_capacity(cw * ch); + let mut cr_p = Vec::with_capacity(cw * ch); + for yy in 0..ch as i32 { + for xx in 0..cw as i32 { + cb_p.push(chr(xx, yy, 0)); + cr_p.push(chr(xx, yy, 47)); + } + } + (y_p, cb_p, cr_p) +} + +/// Encode the IBC P slice of the IDR picture: CTB 0 intra (DC), every +/// other CTB an AMVP CU referencing the current picture at an +/// integer MV of one CTB left (or one CTB up in column 0), with the +/// bypass residual correcting the copy. +fn encode_ibc_p_slice(y: &[u8], cb: &[u8], cr: &[u8], width: usize, height: usize) -> Vec { + let (cw, _ch) = (width / 2, height / 2); + let ctbs_x = width / CTB; + let ctbs_y = height / CTB; + let mut modes = IntraModeField::new(width, height, CTB_LOG2); + let mut field = MotionField::new(width, height); + + let mut w = BitWriter::new(); + // ---- slice_segment_header( ) ---- (IDR: no POC / RPS fields) + w.put_bit(1); // first_slice_segment_in_pic_flag + w.put_bit(0); // no_output_of_prior_pics_flag (IRAP NAL) + w.ue(0); // slice_pic_parameter_set_id + w.ue(1); // slice_type = P + w.put_bit(0); // num_ref_idx_active_override_flag (1 active ref) + w.ue(4); // five_minus_max_num_merge_cand (MaxNumMergeCand = 1) + // use_integer_mv_flag absent (motion_vector_resolution_control_idc 0) + w.se(0); // slice_qp_delta + w.rbsp_trailing_bits(); // byte_alignment() + + // ---- slice_segment_data( ) ---- + let mut cabac = CabacEncoder::new(); + let mut ctxs = SliceContexts::init(init_type(1, false), SLICE_QP); + let mut skip_flags = vec![false; ctbs_x * ctbs_y]; + + // §8.5.3.2 context mirroring the decoder: RefPicList0 = [currPic] + // (POC 0, long-term, is_curr_pic). + let ref_poc = |_l: usize, r: i32| if r == 0 { 0 } else { i32::MIN }; + let ref_long = |_l: usize, r: i32| r == 0; + let ref_short = |_l: usize, _r: i32| false; + let col_long = |_p: i32| false; + let is_curr = |l: usize, r: i32| l == 0 && r == 0; + let mv_ctx = PuMvContext { + curr_poc: 0, + slice_is_b: false, + ctb_log2_size_y: CTB_LOG2, + pic_width_luma: width as u32, + pic_height_luma: height as u32, + max_num_merge_cand: 1, + num_ref_idx_l0_active: 1, + num_ref_idx_l1_active: 0, + log2_par_mrg_level: 2, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + col_poc: 0, + no_backward_pred: true, + ref_poc: &ref_poc, + ref_long_term: &ref_long, + ref_short_term: &ref_short, + col_field: None, + col_ref_long_term: &col_long, + use_integer_mv: false, + two_versions_curr_pic: false, + is_curr_pic: &is_curr, + }; + + for ctb in 0..ctbs_x * ctbs_y { + let x0 = (ctb % ctbs_x) * CTB; + let y0 = (ctb / ctbs_x) * CTB; + let col = ctb % ctbs_x; + let row = ctb / ctbs_x; + + cabac.encode_decision(&mut w, &mut ctxs.cu_transquant_bypass_flag[0], 1); + // cu_skip_flag = 0 always (§9.3.4.2.2 neighbour ctxInc). + let ctx_inc = usize::from(col > 0 && skip_flags[ctb - 1]) + + usize::from(row > 0 && skip_flags[ctb - ctbs_x]); + cabac.encode_decision(&mut w, &mut ctxs.cu_skip_flag[ctx_inc], 0); + skip_flags[ctb] = false; + + if ctb == 0 { + // Intra DC seed CU (no neighbours: prediction = 128). + let mode = 1u8; // INTRA_DC + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 1); // MODE_INTRA + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N + encode_intra_luma_mode( + &mut w, &mut cabac, &mut ctxs, &mut modes, x0, y0, mode, false, false, + ); + cabac.encode_decision(&mut w, &mut ctxs.intra_chroma_pred_mode[0], 0); // DM + + let res_from = |plane: &[u8], pw: usize, bx: usize, by: usize, n: usize| -> Vec { + let src = extract(plane, pw, bx, by, n); + src.iter().map(|s| s - 128).collect() + }; + let res_l = res_from(y, width, x0, y0, CTB); + let res_cb = res_from(cb, cw, x0 / 2, y0 / 2, 8); + let res_cr = res_from(cr, cw, x0 / 2, y0 / 2, 8); + emit_tu_420( + &mut w, &mut cabac, &mut ctxs, &res_l, &res_cb, &res_cr, true, mode, + ); + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + continue; + } + + // IBC AMVP CU: MV one CTB left, or one CTB up for column 0. + let (dx, dy): (i32, i32) = if col > 0 { + (-(CTB as i32), 0) + } else { + (0, -(CTB as i32)) + }; + let target: [i32; 2] = [dx * 4, dy * 4]; + + // Derive both MVP candidates through the decoder's own + // §8.5.3.2.6 process (mvd = 0 probes), then signal the mvd on + // the eq. 8-98 integer path: mvd = (target>>2) − (mvp>>2). + let geom = PuGeometry { + x_cb: x0, + y_cb: y0, + n_cb_s: CTB, + x_pb: x0, + y_pb: y0, + n_pb_w: CTB, + n_pb_h: CTB, + part_mode: PartMode::Part2Nx2N, + part_idx: 0, + }; + let available = |nx: i32, ny: i32| { + zscan_avail( + i64::from(nx), + i64::from(ny), + width, + height, + CTB, + ctbs_x, + ctb, + 0, + ) + }; + let probe = |mvd: [i32; 2], flag: u8| -> [i32; 2] { + let pu = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(crate::binarization::InterPredIdc::PredL0), + ref_idx_l0: Some(0), + mvd_l0: Some([mvd_comp(mvd[0]), mvd_comp(mvd[1])]), + mvp_l0_flag: Some(flag), + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + resolve_pu_motion(&field, &geom, &pu, &mv_ctx, &available).mv_l0 + }; + let mvp0 = probe([0, 0], 0); + let mvd = [ + (target[0] >> 2) - (mvp0[0] >> 2), + (target[1] >> 2) - (mvp0[1] >> 2), + ]; + debug_assert_eq!( + probe(mvd, 0), + target, + "integer-path mvd must land on target" + ); + + // Residual = source − copied block (lossless). + let diff = |plane: &[u8], pw: usize, bx: usize, by: usize, n: usize, mx: i32, my: i32| { + let mut out = Vec::with_capacity(n * n); + for j in 0..n { + for i in 0..n { + let sx = (bx + i) as i32 + mx; + let sy = (by + j) as i32 + my; + let refv = i32::from(plane[sy as usize * pw + sx as usize]); + out.push(i32::from(plane[(by + j) * pw + bx + i]) - refv); + } + } + out + }; + let res_l = diff(y, width, x0, y0, CTB, dx, dy); + let res_cb = diff(cb, cw, x0 / 2, y0 / 2, 8, dx / 2, dy / 2); + let res_cr = diff(cr, cw, x0 / 2, y0 / 2, 8, dx / 2, dy / 2); + let any_res = res_l.iter().any(|&v| v != 0) + || res_cb.iter().any(|&v| v != 0) + || res_cr.iter().any(|&v| v != 0); + + // Interior CUs whose left neighbour already carries the + // (−CTB, 0) IBC vector use MERGE (candidate A1, the + // eqs 8-124/8-125 rounding on the current-picture reference); + // the rest are AMVP CUs on the eq. 8-98 integer path. + let use_merge = col >= 2; + cabac.encode_decision(&mut w, &mut ctxs.pred_mode_flag[0], 0); // MODE_INTER + cabac.encode_decision(&mut w, &mut ctxs.part_mode[0], 1); // PART_2Nx2N + if use_merge { + let merge_probe = resolve_pu_motion( + &field, + &geom, + &PredictionUnit { + merge_flag: true, + merge_idx: Some(0), + inter_pred_idc: None, + ref_idx_l0: None, + mvd_l0: None, + mvp_l0_flag: None, + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }, + &mv_ctx, + &available, + ); + assert_eq!(merge_probe.mv_l0, target, "A1 merge must copy the IBC MV"); + assert!(any_res, "merge (non-skip) TU needs a coded residual"); + cabac.encode_decision(&mut w, &mut ctxs.merge_flag[0], 1); // merge + // merge_idx absent (MaxNumMergeCand == 1); rqt_root_cbf + // inferred 1 for a 2Nx2N merge CU. + emit_tu_420( + &mut w, &mut cabac, &mut ctxs, &res_l, &res_cb, &res_cr, false, 0, + ); + } else { + cabac.encode_decision(&mut w, &mut ctxs.merge_flag[0], 0); // AMVP + // ref_idx_l0 absent (one active reference). + encode_mvd_pair(&mut w, &mut cabac, &mut ctxs, mvd); + cabac.encode_decision(&mut w, &mut ctxs.mvp_flag[0], 0); // mvp_l0_flag + // rqt_root_cbf (non-merge inter CU). + cabac.encode_decision(&mut w, &mut ctxs.rqt_root_cbf[0], u8::from(any_res)); + if any_res { + emit_tu_420( + &mut w, &mut cabac, &mut ctxs, &res_l, &res_cb, &res_cr, false, 0, + ); + } + } + + // Mirror the decoder's motion-field store for later MVPs. + let motion = probe(mvd, 0); + let cell = crate::pu_mv::PuMotion { + pred_flag_l0: true, + pred_flag_l1: false, + ref_idx_l0: 0, + ref_idx_l1: -1, + mv_l0: motion, + mv_l1: [0, 0], + } + .to_cell(0, i32::MIN); + field.fill_rect(x0, y0, CTB, CTB, cell); + + cabac.encode_terminate(&mut w, u8::from(ctb == ctbs_x * ctbs_y - 1)); + } + w.align_zero(); + w.finish() +} + +/// One §7.3.8.9 `mvd_coding` component wrapper for the probe PUs. +fn mvd_comp(v: i32) -> crate::binarization::MvdComponent { + crate::binarization::MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + } +} + +/// §7.3.8.9 mvd_coding( x0, y0, 0 ) — the two-component encode. +fn encode_mvd_pair( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + mvd: [i32; 2], +) { + // abs_mvd_greater0_flag[ 0 / 1 ] then abs_mvd_greater1_flag pair, + // then per-component EG1 remainder + sign (§9.3.3.5). + let gt0 = [mvd[0] != 0, mvd[1] != 0]; + let gt1 = [mvd[0].unsigned_abs() > 1, mvd[1].unsigned_abs() > 1]; + for &g in >0 { + cabac.encode_decision(w, &mut ctxs.abs_mvd_greater0_flag[0], u8::from(g)); + } + for c in 0..2 { + if gt0[c] { + cabac.encode_decision(w, &mut ctxs.abs_mvd_greater1_flag[0], u8::from(gt1[c])); + } + } + for c in 0..2 { + if gt0[c] { + let abs = mvd[c].unsigned_abs(); + if gt1[c] { + // abs_mvd_minus2: EG1 bypass. + encode_eg1(w, cabac, abs - 2); + } + cabac.encode_bypass(w, u8::from(mvd[c] < 0)); // mvd_sign_flag + } + } +} + +/// EG1 (§9.3.3.3 k = 1) bypass encode. +fn encode_eg1(w: &mut BitWriter, cabac: &mut CabacEncoder, mut value: u32) { + let mut k = 1u32; + // Prefix: unary count of exp levels. + while value >= (1 << k) { + cabac.encode_bypass(w, 1); + value -= 1 << k; + k += 1; + } + cabac.encode_bypass(w, 0); + // Suffix: k fixed bits. + for bit in (0..k).rev() { + cabac.encode_bypass(w, ((value >> bit) & 1) as u8); + } +} + +/// Emit one 4:2:0 transform unit (16 luma / two 8x8 chroma) with +/// bypass residuals: cbf flags per §7.3.8.8 order, then the +/// `residual_coding( )` bodies. `intra` selects the scan derivation; +/// `mode` is the intra prediction mode (ignored for inter). +#[allow(clippy::too_many_arguments)] +fn emit_tu_420( + w: &mut BitWriter, + cabac: &mut CabacEncoder, + ctxs: &mut SliceContexts, + res_l: &[i32], + res_cb: &[i32], + res_cr: &[i32], + intra: bool, + mode: u8, +) { + let cbf_cb_f = res_cb.iter().any(|&v| v != 0); + let cbf_cr_f = res_cr.iter().any(|&v| v != 0); + let cbf_luma = res_l.iter().any(|&v| v != 0); + cabac.encode_decision( + w, + &mut ctxs.cbf_chroma[cbf_cb_ctx_inc(0) as usize], + u8::from(cbf_cb_f), + ); + cabac.encode_decision( + w, + &mut ctxs.cbf_chroma[cbf_cr_ctx_inc(0) as usize], + u8::from(cbf_cr_f), + ); + // §7.3.8.8: an intra leaf always signals cbf_luma; an inter depth-0 + // leaf with no chroma cbf infers cbf_luma = 1. + if intra || cbf_cb_f || cbf_cr_f { + cabac.encode_decision( + w, + &mut ctxs.cbf_luma[cbf_luma_ctx_inc(0) as usize], + u8::from(cbf_luma), + ); + } else { + assert!(cbf_luma, "all-zero inter TU must use rqt_root_cbf = 0"); + } + let rc = |log2: u32, is_chroma: bool| ResidualCodingParams { + log2_trafo_size: log2, + is_chroma, + scan_idx: residual_coding_scan_idx(intra, log2, u8::from(is_chroma), 1, u32::from(mode)), + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + }; + if cbf_luma { + encode_residual_coding(w, cabac, &mut ctxs.residual, &rc(4, false), res_l) + .expect("valid luma levels"); + } + if cbf_cb_f { + encode_residual_coding(w, cabac, &mut ctxs.residual, &rc(3, true), res_cb) + .expect("valid cb levels"); + } + if cbf_cr_f { + encode_residual_coding(w, cabac, &mut ctxs.residual, &rc(3, true), res_cr) + .expect("valid cr levels"); + } +} + +/// The IBC conformance stream: VPS + SPS(scc, 4:2:0, curr-pic-ref) + +/// PPS(scc, curr-pic-ref) + one IDR picture whose single slice is a P +/// slice referencing only the current picture (64x48). +pub(crate) fn build_ibc_stream() -> (Vec, Planes) { + let (w, h) = (64usize, 48usize); + let (y, cb, cr) = source_planes_420(w, h); + let slice = encode_ibc_p_slice(&y, &cb, &cr, w, h); + let units = vec![ + nal_unit(32, 0, 0, &write_vps_scc(30, false)), + nal_unit(33, 0, 0, &write_sps_scc(w, h, 30, false, true)), + nal_unit(34, 0, 0, &write_pps_scc(true, false, false)), + nal_unit(20, 0, 0, &slice), // IDR_N_LP + ]; + (annexb(&units), (y, cb, cr)) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sequence::decode_annexb_sequence; + + fn planes_of(frame: &crate::sequence::DecodedFrame) -> Vec { + frame.picture.to_planar_u8().expect("8-bit planes") + } + + /// The checked-in ACT stream bytes are exactly what the builder + /// produces, and this crate's decoder reconstructs the procedural + /// source losslessly through the §8.6.8.2 inverse colour + /// transform (act-1 CUs) with interleaved act-0 controls. + #[test] + fn act_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_act_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r416-act.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!(planes_of(&frames[0]), expected, "lossless ACT decode"); + } + + /// The checked-in IBC stream bytes are exactly what the builder + /// produces, and this crate's decoder reconstructs the procedural + /// source losslessly through the current-picture-referencing path + /// (an IDR whose P slice lists only currPic; per-CTB integer MVs + /// copying the left / above CTB). + #[test] + fn ibc_stream_decodes_lossless() { + let (stream, (y, cb, cr)) = build_ibc_stream(); + let pinned: &[u8] = include_bytes!(concat!( + env!("CARGO_MANIFEST_DIR"), + "/tests/fixture_bytes/r416-ibc.hevc" + )); + assert_eq!(stream, pinned, "builder must reproduce the validated bytes"); + let frames = decode_annexb_sequence(&stream).expect("decode"); + assert_eq!(frames.len(), 1); + let mut expected = y; + expected.extend(cb); + expected.extend(cr); + assert_eq!(planes_of(&frames[0]), expected, "lossless IBC decode"); + } +} diff --git a/vendor/oxideav-h265/src/hrd.rs b/vendor/oxideav-h265/src/hrd.rs new file mode 100644 index 0000000..50bbf1a --- /dev/null +++ b/vendor/oxideav-h265/src/hrd.rs @@ -0,0 +1,1044 @@ +//! HRD parameters parser per ITU-T Rec. H.265 §E.2.2 / §E.2.3. +//! +//! Implements the `hrd_parameters( commonInfPresentFlag, +//! maxNumSubLayersMinus1 )` and `sub_layer_hrd_parameters( subLayerId )` +//! syntax structures. The semantics (§E.3.2 / §E.3.3) govern the +//! permitted ranges that are enforced inline as +//! [`HrdError::ValueOutOfRange`]. +//! +//! The struct is reused by every HRD callsite: the VPS RBSP +//! (`hrd_parameters( cprms_present_flag[i], vps_max_sub_layers_minus1 )`, +//! §7.3.2.1) and the SPS VUI block (`hrd_parameters( 1, +//! sps_max_sub_layers_minus1 )`, §E.2.1). The VPS wraps a sequence of +//! these (one per `vps_num_hrd_parameters`); §7.3.2.1 prefixes each +//! entry with a `hrd_layer_set_idx[i]` `ue(v)` plus, for `i > 0`, +//! `cprms_present_flag[i]` `u(1)` — see [`VpsHrdEntry`]. +//! +//! ## §E.2.2 layout summary +//! +//! ```text +//! hrd_parameters( commonInfPresentFlag, maxNumSubLayersMinus1 ) { +//! if( commonInfPresentFlag ) { // CommonInf +//! nal_hrd_parameters_present_flag u(1) +//! vcl_hrd_parameters_present_flag u(1) +//! if( nal | vcl ) { +//! sub_pic_hrd_params_present_flag u(1) +//! if( sub_pic_hrd_params_present_flag ) { +//! tick_divisor_minus2 u(8) +//! du_cpb_removal_delay_increment_length_minus1 u(5) +//! sub_pic_cpb_params_in_pic_timing_sei_flag u(1) +//! dpb_output_delay_du_length_minus1 u(5) +//! } +//! bit_rate_scale u(4) +//! cpb_size_scale u(4) +//! if( sub_pic_hrd_params_present_flag ) +//! cpb_size_du_scale u(4) +//! initial_cpb_removal_delay_length_minus1 u(5) +//! au_cpb_removal_delay_length_minus1 u(5) +//! dpb_output_delay_length_minus1 u(5) +//! } +//! } +//! for( i = 0; i <= maxNumSubLayersMinus1; i++ ) { // SubLayer +//! fixed_pic_rate_general_flag[i] u(1) +//! if( !general_flag ) +//! fixed_pic_rate_within_cvs_flag[i] u(1) +//! if( fixed_pic_rate_within_cvs_flag[i] ) +//! elemental_duration_in_tc_minus1[i] ue(v) // 0..=2047 +//! else +//! low_delay_hrd_flag[i] u(1) +//! if( !low_delay_hrd_flag[i] ) +//! cpb_cnt_minus1[i] ue(v) // 0..=31 +//! if( nal_hrd_parameters_present_flag ) +//! sub_layer_hrd_parameters( i ) // §E.2.3 +//! if( vcl_hrd_parameters_present_flag ) +//! sub_layer_hrd_parameters( i ) +//! } +//! } +//! ``` +//! +//! ## §E.2.3 layout summary +//! +//! ```text +//! sub_layer_hrd_parameters( subLayerId ) { +//! for( i = 0; i < CpbCnt; i++ ) { +//! bit_rate_value_minus1[i] ue(v) // 0..=2^32-2 +//! cpb_size_value_minus1[i] ue(v) // 0..=2^32-2 +//! if( sub_pic_hrd_params_present_flag ) { +//! cpb_size_du_value_minus1[i] ue(v) // 0..=2^32-2 +//! bit_rate_du_value_minus1[i] ue(v) // 0..=2^32-2 +//! } +//! cbr_flag[i] u(1) +//! } +//! } +//! ``` + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::vps::HEVC_MAX_SUB_LAYERS; + +/// Upper bound on `cpb_cnt_minus1[i]`. §E.3.2 mandates the range +/// 0..=31, so a CPB array has at most 32 entries. +pub const HEVC_MAX_CPB_CNT: usize = 32; + +/// Upper bound on `elemental_duration_in_tc_minus1[i]`. §E.3.2 mandates +/// the range 0..=2047. +pub const HEVC_MAX_ELEMENTAL_DURATION_IN_TC_MINUS1: u32 = 2047; + +/// Errors that can arise while parsing an `hrd_parameters()` body. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HrdError { + /// The RBSP ran out of bits before the structure was fully parsed. + Truncated, + /// An Exp-Golomb code's `codeNum` exceeded the legal range of the + /// containing syntax element. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value read. + got: u32, + }, + /// `maxNumSubLayersMinus1` supplied by the caller exceeded the + /// §A.4 / `u(3)` ceiling of 6. Guarded so a malformed parent does + /// not push the per-sub-layer array past `HEVC_MAX_SUB_LAYERS`. + InvalidMaxNumSubLayers { + /// The (out-of-range) value supplied by the caller. + got: u8, + }, + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), +} + +impl core::fmt::Display for HrdError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("hrd_parameters() RBSP truncated"), + Self::ValueOutOfRange { field, got } => { + write!(f, "syntax element {field} out of range: {got}") + } + Self::InvalidMaxNumSubLayers { got } => write!( + f, + "maxNumSubLayersMinus1 = {got} exceeds the HEVC u(3) ceiling of 6" + ), + Self::Bitstream(e) => write!(f, "bitstream error during hrd_parameters() parse: {e}"), + } + } +} + +impl std::error::Error for HrdError {} + +impl From for HrdError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +/// "Common information" block from §E.2.2, present when +/// `commonInfPresentFlag` is 1. Encapsulates the conditional sub-pic +/// HRD block and the four common length fields. `None` on a per-HRD +/// entry whose `cprms_present_flag` is 0 — the caller is then +/// responsible for inheriting the value from the previous entry per +/// §7.4.3.1 (the `( i − 1 )-th hrd_parameters( )` inheritance rule). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct HrdCommonInfo { + /// `nal_hrd_parameters_present_flag` (`u(1)`). + pub nal_hrd_parameters_present_flag: bool, + /// `vcl_hrd_parameters_present_flag` (`u(1)`). + pub vcl_hrd_parameters_present_flag: bool, + /// `sub_pic_hrd_params_present_flag` (`u(1)`). Only signalled when + /// at least one of `nal_hrd_parameters_present_flag` or + /// `vcl_hrd_parameters_present_flag` is 1; inferred to be 0 + /// otherwise per §E.3.2. + pub sub_pic_hrd_params_present_flag: bool, + /// `tick_divisor_minus2` (`u(8)`); only present when + /// `sub_pic_hrd_params_present_flag` is 1. + pub tick_divisor_minus2: u8, + /// `du_cpb_removal_delay_increment_length_minus1` (`u(5)`); only + /// present when `sub_pic_hrd_params_present_flag` is 1. + pub du_cpb_removal_delay_increment_length_minus1: u8, + /// `sub_pic_cpb_params_in_pic_timing_sei_flag` (`u(1)`); only + /// present when `sub_pic_hrd_params_present_flag` is 1. Inferred + /// to 0 otherwise per §E.3.2. + pub sub_pic_cpb_params_in_pic_timing_sei_flag: bool, + /// `dpb_output_delay_du_length_minus1` (`u(5)`); only present when + /// `sub_pic_hrd_params_present_flag` is 1. + pub dpb_output_delay_du_length_minus1: u8, + /// `bit_rate_scale` (`u(4)`). + pub bit_rate_scale: u8, + /// `cpb_size_scale` (`u(4)`). + pub cpb_size_scale: u8, + /// `cpb_size_du_scale` (`u(4)`); only present when + /// `sub_pic_hrd_params_present_flag` is 1. + pub cpb_size_du_scale: u8, + /// `initial_cpb_removal_delay_length_minus1` (`u(5)`). Inferred + /// to 23 when absent per §E.3.2 — the parser reports the signalled + /// value; the §E.3.2 inference is the caller's responsibility. + pub initial_cpb_removal_delay_length_minus1: u8, + /// `au_cpb_removal_delay_length_minus1` (`u(5)`). Inferred to 23 + /// when absent per §E.3.2. + pub au_cpb_removal_delay_length_minus1: u8, + /// `dpb_output_delay_length_minus1` (`u(5)`). Inferred to 23 when + /// absent per §E.3.2. + pub dpb_output_delay_length_minus1: u8, +} + +impl HrdCommonInfo { + /// `nal_hrd_parameters_present_flag` OR `vcl_hrd_parameters_present_flag` + /// — gates the §E.2.2 inner block and the per-sub-layer + /// `sub_layer_hrd_parameters()` invocations. + pub fn has_any_hrd(&self) -> bool { + self.nal_hrd_parameters_present_flag || self.vcl_hrd_parameters_present_flag + } + + fn parse(br: &mut BitReader<'_>) -> Result { + let nal_hrd_parameters_present_flag = br.u1()? != 0; + let vcl_hrd_parameters_present_flag = br.u1()? != 0; + let mut info = Self { + nal_hrd_parameters_present_flag, + vcl_hrd_parameters_present_flag, + sub_pic_hrd_params_present_flag: false, + tick_divisor_minus2: 0, + du_cpb_removal_delay_increment_length_minus1: 0, + sub_pic_cpb_params_in_pic_timing_sei_flag: false, + dpb_output_delay_du_length_minus1: 0, + bit_rate_scale: 0, + cpb_size_scale: 0, + cpb_size_du_scale: 0, + initial_cpb_removal_delay_length_minus1: 0, + au_cpb_removal_delay_length_minus1: 0, + dpb_output_delay_length_minus1: 0, + }; + if nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag { + info.sub_pic_hrd_params_present_flag = br.u1()? != 0; + if info.sub_pic_hrd_params_present_flag { + info.tick_divisor_minus2 = br.u(8)? as u8; + info.du_cpb_removal_delay_increment_length_minus1 = br.u(5)? as u8; + info.sub_pic_cpb_params_in_pic_timing_sei_flag = br.u1()? != 0; + info.dpb_output_delay_du_length_minus1 = br.u(5)? as u8; + } + info.bit_rate_scale = br.u(4)? as u8; + info.cpb_size_scale = br.u(4)? as u8; + if info.sub_pic_hrd_params_present_flag { + info.cpb_size_du_scale = br.u(4)? as u8; + } + info.initial_cpb_removal_delay_length_minus1 = br.u(5)? as u8; + info.au_cpb_removal_delay_length_minus1 = br.u(5)? as u8; + info.dpb_output_delay_length_minus1 = br.u(5)? as u8; + } + Ok(info) + } +} + +/// One per-CPB entry from §E.2.3 (`sub_layer_hrd_parameters()`). +/// +/// The four `*_minus1` fields are stored as `u32` because §E.3.3 +/// mandates the range 0..=2^32 − 2, which would overflow a `u16` and +/// fits exactly in a `u32` `ue(v)` `codeNum`. The legality bounds +/// (`bit_rate_value_minus1[i]` strictly increases, `cpb_size_value_minus1[i]` +/// monotonically non-increases, and so on for the sub-pic variants) are +/// enforced by [`SubLayerHrdParameters::parse`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct CpbEntry { + /// `bit_rate_value_minus1[i]` (`ue(v)`, range 0..=2^32 − 2). + pub bit_rate_value_minus1: u32, + /// `cpb_size_value_minus1[i]` (`ue(v)`, range 0..=2^32 − 2). + pub cpb_size_value_minus1: u32, + /// `cpb_size_du_value_minus1[i]` (`ue(v)`, range 0..=2^32 − 2); + /// `None` when the parent's `sub_pic_hrd_params_present_flag == 0`. + pub cpb_size_du_value_minus1: Option, + /// `bit_rate_du_value_minus1[i]` (`ue(v)`, range 0..=2^32 − 2); + /// `None` when the parent's `sub_pic_hrd_params_present_flag == 0`. + pub bit_rate_du_value_minus1: Option, + /// `cbr_flag[i]` (`u(1)`). + pub cbr_flag: bool, +} + +/// Per-sub-layer HRD payload from §E.2.3 +/// (`sub_layer_hrd_parameters( subLayerId )`). +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SubLayerHrdParameters { + /// One entry per `i` in `0..CpbCnt` (i.e. `cpb_cnt_minus1 + 1` + /// entries). Bounded at [`HEVC_MAX_CPB_CNT`]. + pub cpb: Vec, +} + +impl SubLayerHrdParameters { + /// Parse a `sub_layer_hrd_parameters( subLayerId )` body. The + /// caller passes the active `cpb_cnt = cpb_cnt_minus1 + 1` and the + /// containing `sub_pic_hrd_params_present_flag` (which gates the + /// per-CPB `cpb_size_du_value_minus1[i]` / `bit_rate_du_value_minus1[i]` + /// pair). + pub fn parse( + br: &mut BitReader<'_>, + cpb_cnt: u32, + sub_pic_hrd_params_present: bool, + ) -> Result { + // cpb_cnt = cpb_cnt_minus1 + 1; cpb_cnt_minus1 is in 0..=31, so + // cpb_cnt is in 1..=32. Bound for safety against a corrupt + // parent that supplies a larger value. + if cpb_cnt == 0 || cpb_cnt as usize > HEVC_MAX_CPB_CNT { + return Err(HrdError::ValueOutOfRange { + field: "CpbCnt", + got: cpb_cnt, + }); + } + let mut cpb = Vec::with_capacity(cpb_cnt as usize); + let mut prev_bit_rate: Option = None; + let mut prev_cpb_size: Option = None; + let mut prev_cpb_size_du: Option = None; + let mut prev_bit_rate_du: Option = None; + for _ in 0..cpb_cnt { + let bit_rate_value_minus1 = br.ue()?; + // §E.3.3: "For any i > 0, bit_rate_value_minus1[ i ] shall + // be greater than bit_rate_value_minus1[ i − 1 ]." + if let Some(prev) = prev_bit_rate { + if bit_rate_value_minus1 <= prev { + return Err(HrdError::ValueOutOfRange { + field: "bit_rate_value_minus1", + got: bit_rate_value_minus1, + }); + } + } + prev_bit_rate = Some(bit_rate_value_minus1); + + let cpb_size_value_minus1 = br.ue()?; + // §E.3.3: "For any i greater than 0, cpb_size_value_minus1[ i ] + // shall be less than or equal to cpb_size_value_minus1[ i − 1 ]." + if let Some(prev) = prev_cpb_size { + if cpb_size_value_minus1 > prev { + return Err(HrdError::ValueOutOfRange { + field: "cpb_size_value_minus1", + got: cpb_size_value_minus1, + }); + } + } + prev_cpb_size = Some(cpb_size_value_minus1); + + let (cpb_size_du_value_minus1, bit_rate_du_value_minus1) = if sub_pic_hrd_params_present + { + let du_cpb = br.ue()?; + // §E.3.3: "For any i greater than 0, + // cpb_size_du_value_minus1[ i ] shall be less than or + // equal to cpb_size_du_value_minus1[ i − 1 ]." + if let Some(prev) = prev_cpb_size_du { + if du_cpb > prev { + return Err(HrdError::ValueOutOfRange { + field: "cpb_size_du_value_minus1", + got: du_cpb, + }); + } + } + prev_cpb_size_du = Some(du_cpb); + let du_bit = br.ue()?; + // §E.3.3: "For any i > 0, bit_rate_du_value_minus1[ i ] + // shall be greater than bit_rate_du_value_minus1[ i − 1 ]." + if let Some(prev) = prev_bit_rate_du { + if du_bit <= prev { + return Err(HrdError::ValueOutOfRange { + field: "bit_rate_du_value_minus1", + got: du_bit, + }); + } + } + prev_bit_rate_du = Some(du_bit); + (Some(du_cpb), Some(du_bit)) + } else { + (None, None) + }; + + let cbr_flag = br.u1()? != 0; + + cpb.push(CpbEntry { + bit_rate_value_minus1, + cpb_size_value_minus1, + cpb_size_du_value_minus1, + bit_rate_du_value_minus1, + cbr_flag, + }); + } + Ok(Self { cpb }) + } +} + +/// One per-sub-layer entry of the §E.2.2 outer loop. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SubLayerHrd { + /// `fixed_pic_rate_general_flag[i]` (`u(1)`). + pub fixed_pic_rate_general_flag: bool, + /// `fixed_pic_rate_within_cvs_flag[i]` (`u(1)`); only signalled + /// when `fixed_pic_rate_general_flag[i] == 0`. When + /// `fixed_pic_rate_general_flag[i] == 1`, §E.3.2 infers this to 1 + /// — the parser pre-fills the inferred value rather than leaving an + /// `Option`. + pub fixed_pic_rate_within_cvs_flag: bool, + /// `elemental_duration_in_tc_minus1[i]` (`ue(v)`, range 0..=2047); + /// only signalled when `fixed_pic_rate_within_cvs_flag[i] == 1`. + pub elemental_duration_in_tc_minus1: Option, + /// `low_delay_hrd_flag[i]` (`u(1)`); only signalled when + /// `fixed_pic_rate_within_cvs_flag[i] == 0`. §E.3.2 infers 0 + /// otherwise — pre-filled. + pub low_delay_hrd_flag: bool, + /// `cpb_cnt_minus1[i]` (`ue(v)`, range 0..=31); inferred to 0 when + /// `low_delay_hrd_flag[i] == 1` (the syntax skips the `ue(v)` — + /// pre-filled to match the spec text's "When not present, the value + /// of cpb_cnt_minus1[ i ] is inferred to be equal to 0"). + pub cpb_cnt_minus1: u32, + /// `sub_layer_hrd_parameters( i )` for the NAL HRD path; populated + /// when the parent's `nal_hrd_parameters_present_flag == 1`. + pub nal_hrd: Option, + /// `sub_layer_hrd_parameters( i )` for the VCL HRD path; populated + /// when the parent's `vcl_hrd_parameters_present_flag == 1`. + pub vcl_hrd: Option, +} + +/// Parsed `hrd_parameters( commonInfPresentFlag, maxNumSubLayersMinus1 )` +/// body per §E.2.2. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HrdParameters { + /// `maxNumSubLayersMinus1` echoed back so consumers can iterate + /// [`Self::sub_layers`] without re-deriving the bound. Capped at 6 + /// (the `u(3)` ceiling). + pub max_num_sub_layers_minus1: u8, + /// "Common information" block — present iff `commonInfPresentFlag` + /// was 1 at this call site. When `None`, the caller must inherit + /// the previous HRD entry's common info per §7.4.3.1. + pub common: Option, + /// Per-sub-layer payload — one [`SubLayerHrd`] per `i` in + /// `0..=maxNumSubLayersMinus1`. Length is therefore + /// `max_num_sub_layers_minus1 + 1`, bounded at + /// [`HEVC_MAX_SUB_LAYERS`]. + pub sub_layers: Vec, +} + +impl HrdParameters { + /// Parse `hrd_parameters( commonInfPresentFlag, maxNumSubLayersMinus1 )` + /// starting at the current `br` position. + /// + /// `prev_common` is consulted when `common_inf_present == false`: + /// the gates (`nal_hrd_parameters_present_flag`, + /// `vcl_hrd_parameters_present_flag`, + /// `sub_pic_hrd_params_present_flag`) drive the per-sub-layer + /// branches even though no common-info bits are read at this call + /// site. This matches the §7.4.3.1 contract: when + /// `cprms_present_flag[i] == 0` the HRD parameters that are common + /// for all sub-layers "are derived to be the same as the + /// (i − 1)-th hrd_parameters( ) syntax structure". + pub fn parse( + br: &mut BitReader<'_>, + common_inf_present: bool, + max_num_sub_layers_minus1: u8, + prev_common: Option<&HrdCommonInfo>, + ) -> Result { + if max_num_sub_layers_minus1 as usize > HEVC_MAX_SUB_LAYERS { + return Err(HrdError::InvalidMaxNumSubLayers { + got: max_num_sub_layers_minus1, + }); + } + let common = if common_inf_present { + Some(HrdCommonInfo::parse(br)?) + } else { + None + }; + // Pick the effective common info: the freshly-parsed block if + // present, else the inherited one from prev_common. When neither + // is available, sub-layer parsing falls back to "no HRD gates", + // which matches the spec's silent-default behaviour. + let effective = common.as_ref().or(prev_common); + let nal_hrd_present = effective.is_some_and(|c| c.nal_hrd_parameters_present_flag); + let vcl_hrd_present = effective.is_some_and(|c| c.vcl_hrd_parameters_present_flag); + let sub_pic_present = effective.is_some_and(|c| c.sub_pic_hrd_params_present_flag); + + let count = max_num_sub_layers_minus1 as usize + 1; + let mut sub_layers = Vec::with_capacity(count); + for _ in 0..count { + let fixed_pic_rate_general_flag = br.u1()? != 0; + // §E.3.2: when fixed_pic_rate_general_flag[i] == 1, the + // value of fixed_pic_rate_within_cvs_flag[i] is inferred to + // be equal to 1. Otherwise we read the explicit bit. + let fixed_pic_rate_within_cvs_flag = if fixed_pic_rate_general_flag { + true + } else { + br.u1()? != 0 + }; + let mut sl = SubLayerHrd { + fixed_pic_rate_general_flag, + fixed_pic_rate_within_cvs_flag, + ..SubLayerHrd::default() + }; + if fixed_pic_rate_within_cvs_flag { + let v = br.ue()?; + // §E.3.2: "elemental_duration_in_tc_minus1[ i ] shall + // be in the range of 0 to 2 047, inclusive." + if v > HEVC_MAX_ELEMENTAL_DURATION_IN_TC_MINUS1 { + return Err(HrdError::ValueOutOfRange { + field: "elemental_duration_in_tc_minus1", + got: v, + }); + } + sl.elemental_duration_in_tc_minus1 = Some(v); + } else { + sl.low_delay_hrd_flag = br.u1()? != 0; + } + if !sl.low_delay_hrd_flag { + let v = br.ue()?; + // §E.3.2: "cpb_cnt_minus1[ i ] shall be in the range + // of 0 to 31, inclusive." + if v as usize >= HEVC_MAX_CPB_CNT { + return Err(HrdError::ValueOutOfRange { + field: "cpb_cnt_minus1", + got: v, + }); + } + sl.cpb_cnt_minus1 = v; + } else { + // §E.3.2: "When not present, the value of + // cpb_cnt_minus1[ i ] is inferred to be equal to 0." + sl.cpb_cnt_minus1 = 0; + } + if nal_hrd_present { + sl.nal_hrd = Some(SubLayerHrdParameters::parse( + br, + sl.cpb_cnt_minus1 + 1, + sub_pic_present, + )?); + } + if vcl_hrd_present { + sl.vcl_hrd = Some(SubLayerHrdParameters::parse( + br, + sl.cpb_cnt_minus1 + 1, + sub_pic_present, + )?); + } + sub_layers.push(sl); + } + Ok(Self { + max_num_sub_layers_minus1, + common, + sub_layers, + }) + } +} + +/// One entry of the VPS `for( i = 0; i < vps_num_hrd_parameters; i++ )` +/// loop in §7.3.2.1: the `hrd_layer_set_idx[i]` reference, the per-entry +/// `cprms_present_flag[i]` (`u(1)`, only present when `i > 0`), and the +/// parsed [`HrdParameters`] body. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VpsHrdEntry { + /// `hrd_layer_set_idx[i]` (`ue(v)`). §7.4.3.1 constrains this to + /// `0..=vps_num_layer_sets_minus1` for `vps_base_layer_internal_flag == 1`, + /// and `0..=vps_num_layer_sets_minus1 - 1` otherwise; the caller + /// validates against the active VPS context. + pub hrd_layer_set_idx: u32, + /// `cprms_present_flag[i]` (`u(1)`). Inferred to 1 for `i == 0` + /// per §7.4.3.1; this field carries the effective value either way. + pub cprms_present_flag: bool, + /// Parsed `hrd_parameters( cprms_present_flag[i], vps_max_sub_layers_minus1 )` + /// body. + pub hrd: HrdParameters, +} + +impl VpsHrdEntry { + /// Parse one entry of the VPS HRD loop. `index` is `i` (so the + /// `cprms_present_flag[i]` `u(1)` is only consumed when `i > 0`), + /// and `vps_max_sub_layers_minus1` plumbs through the + /// `maxNumSubLayersMinus1` argument to `hrd_parameters()`. + /// `prev` is the previous [`VpsHrdEntry`] (or `None` for `i == 0`) + /// — its [`HrdCommonInfo`] is inherited when this entry's + /// `cprms_present_flag[i] == 0`. + pub fn parse( + br: &mut BitReader<'_>, + index: u32, + vps_max_sub_layers_minus1: u8, + prev: Option<&VpsHrdEntry>, + ) -> Result { + let hrd_layer_set_idx = br.ue()?; + // Spec-side allocation safety: hrd_layer_set_idx is bounded by + // vps_num_layer_sets_minus1 + 1 (= 1024). Anything larger is + // guaranteed-out-of-range regardless of VPS context; cap here + // so the cross-check against the active VPS in §7.4.3.1 is + // free to look at a believable value. + if hrd_layer_set_idx > crate::vps::HEVC_VPS_MAX_NUM_LAYER_SETS as u32 { + return Err(HrdError::ValueOutOfRange { + field: "hrd_layer_set_idx", + got: hrd_layer_set_idx, + }); + } + let cprms_present_flag = if index > 0 { br.u1()? != 0 } else { true }; + let hrd = HrdParameters::parse( + br, + cprms_present_flag, + vps_max_sub_layers_minus1, + prev.map(|p| &p.hrd).and_then(|h| h.common.as_ref()), + )?; + Ok(Self { + hrd_layer_set_idx, + cprms_present_flag, + hrd, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Helper that turns a sequence of `'0'`/`'1'` bit strings into a + /// packed RBSP byte buffer. Bits run MSB-first per H.265 §7.2. + fn bits_to_bytes(parts: &[&str]) -> Vec { + let mut bits = Vec::::new(); + for s in parts { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + } + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + bytes + } + + /// 0-th-order unsigned Exp-Golomb encoder per ITU-T Rec. H.265 + /// §9.2: emit `leading_zero_bits` zeros followed by `binary(code + + /// 1)` on `leading_zero_bits + 1` bits. Returns the bit string + /// (each char `'0'` or `'1'`) so [`bits_to_bytes`] can pack it. + fn ue(code: u32) -> String { + let v = code as u64 + 1; + let bits_in_v = 64 - v.leading_zeros(); + let leading_zeros = bits_in_v - 1; + let mut s = String::new(); + for _ in 0..leading_zeros { + s.push('0'); + } + for i in (0..bits_in_v).rev() { + s.push(if (v >> i) & 1 == 1 { '1' } else { '0' }); + } + s + } + + /// Fixed-width binary string (`u(n)` literal) — `width` bits of + /// `value`, MSB-first. + fn ub(value: u32, width: u8) -> String { + let mut s = String::new(); + for i in (0..width).rev() { + s.push(if (value >> i) & 1 == 1 { '1' } else { '0' }); + } + s + } + + /// Minimal payload: commonInfPresentFlag = 1, every common gate 0, + /// one sub-layer with general fixed-pic-rate flag set and inferred + /// within-CVS flag, elemental_duration_in_tc_minus1 = 0, no per-CPB + /// data. Tests the all-flags-off short path through §E.2.2. + #[test] + fn parses_minimal_common_info_one_sub_layer() { + let bytes = bits_to_bytes(&[ + "0", // nal_hrd_parameters_present_flag = 0 + "0", // vcl_hrd_parameters_present_flag = 0 + // (nal | vcl) == 0 → no sub_pic_hrd_params block, no + // bit_rate_scale / cpb_size_scale / lengths. + "1", // fixed_pic_rate_general_flag[0] = 1 + // within_cvs_flag inferred = 1, so elemental_duration_in_tc_minus1[0] ue(v) + "1", // ue(v) = 0 + // low_delay_hrd_flag not signalled (within_cvs == 1); inferred 0. + // cpb_cnt_minus1 IS read because !low_delay_hrd_flag. + "1", // cpb_cnt_minus1 ue(v) = 0 + // no NAL/VCL HRD bodies (gates = 0) + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, true, 0, None).expect("parse"); + let common = hrd.common.expect("common present"); + assert!(!common.nal_hrd_parameters_present_flag); + assert!(!common.vcl_hrd_parameters_present_flag); + assert!(!common.has_any_hrd()); + assert_eq!(hrd.sub_layers.len(), 1); + let sl = &hrd.sub_layers[0]; + assert!(sl.fixed_pic_rate_general_flag); + assert!(sl.fixed_pic_rate_within_cvs_flag); + assert_eq!(sl.elemental_duration_in_tc_minus1, Some(0)); + assert_eq!(sl.cpb_cnt_minus1, 0); + assert!(sl.nal_hrd.is_none()); + assert!(sl.vcl_hrd.is_none()); + } + + /// `nal_hrd_parameters_present_flag = 1` plus + /// `sub_pic_hrd_params_present_flag = 1`: walks every common-info + /// branch and one per-sub-layer NAL HRD body with two CPBs. + #[test] + fn parses_nal_hrd_with_sub_pic_and_two_cpbs() { + // Plan: + // - common: nal = 1, vcl = 0, sub_pic = 1 + // - tick_divisor_minus2 = 3 (u(8) = 00000011) + // - du_cpb_removal_delay_increment_length_minus1 = 4 (u(5) = 00100) + // - sub_pic_cpb_params_in_pic_timing_sei_flag = 1 + // - dpb_output_delay_du_length_minus1 = 5 (u(5) = 00101) + // - bit_rate_scale = 2 (u(4) = 0010) + // - cpb_size_scale = 3 (u(4) = 0011) + // - cpb_size_du_scale = 1 (u(4) = 0001) + // - initial_cpb_removal_delay_length_minus1 = 23 (u(5) = 10111) + // - au_cpb_removal_delay_length_minus1 = 23 (10111) + // - dpb_output_delay_length_minus1 = 23 (10111) + // - one sub-layer: + // - fixed_pic_rate_general_flag = 0 + // - fixed_pic_rate_within_cvs_flag = 1 → elemental_duration_in_tc_minus1 ue(v) = 0 + // - cpb_cnt_minus1 = 1 (ue(v) for 1 → "010") + // - NAL HRD body with 2 CPBs (CpbCnt = 2): + // - cpb[0]: bit_rate_value_minus1 = 0 (ue "1"), cpb_size_value_minus1 = 100 (ue 100), cpb_size_du = 200, bit_rate_du = 50, cbr = 1 + // - cpb[1]: bit_rate_value_minus1 = 1 (ue 1 → "010"), cpb_size_value_minus1 = 50, cpb_size_du = 100, bit_rate_du = 100, cbr = 0 + let nal_cpb0_brv = ue(0); + let nal_cpb0_cpb = ue(100); + let nal_cpb0_cpb_du = ue(200); + let nal_cpb0_brv_du = ue(50); + let nal_cpb1_brv = ue(1); + let nal_cpb1_cpb = ue(50); + let nal_cpb1_cpb_du = ue(100); + let nal_cpb1_brv_du = ue(100); + let bytes = bits_to_bytes(&[ + "1", // nal_hrd_parameters_present_flag = 1 + "0", // vcl_hrd_parameters_present_flag = 0 + "1", // sub_pic_hrd_params_present_flag = 1 + &ub(3, 8), // tick_divisor_minus2 = 3 + &ub(4, 5), // du_cpb_removal_delay_increment_length_minus1 = 4 + "1", // sub_pic_cpb_params_in_pic_timing_sei_flag = 1 + &ub(5, 5), // dpb_output_delay_du_length_minus1 = 5 + &ub(2, 4), // bit_rate_scale = 2 + &ub(3, 4), // cpb_size_scale = 3 + &ub(1, 4), // cpb_size_du_scale = 1 + &ub(23, 5), // initial_cpb_removal_delay_length_minus1 = 23 + &ub(23, 5), // au_cpb_removal_delay_length_minus1 = 23 + &ub(23, 5), // dpb_output_delay_length_minus1 = 23 + "0", // fixed_pic_rate_general_flag = 0 + "1", // fixed_pic_rate_within_cvs_flag = 1 + &ue(0), // elemental_duration_in_tc_minus1 = 0 + // low_delay_hrd_flag not signalled (within_cvs == 1) + &ue(1), // cpb_cnt_minus1 = 1 + &nal_cpb0_brv, + &nal_cpb0_cpb, + &nal_cpb0_cpb_du, + &nal_cpb0_brv_du, + "1", // cbr_flag[0] + &nal_cpb1_brv, + &nal_cpb1_cpb, + &nal_cpb1_cpb_du, + &nal_cpb1_brv_du, + "0", // cbr_flag[1] + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, true, 0, None).expect("parse"); + let common = hrd.common.expect("common present"); + assert!(common.nal_hrd_parameters_present_flag); + assert!(!common.vcl_hrd_parameters_present_flag); + assert!(common.sub_pic_hrd_params_present_flag); + assert_eq!(common.tick_divisor_minus2, 3); + assert_eq!(common.du_cpb_removal_delay_increment_length_minus1, 4); + assert!(common.sub_pic_cpb_params_in_pic_timing_sei_flag); + assert_eq!(common.dpb_output_delay_du_length_minus1, 5); + assert_eq!(common.bit_rate_scale, 2); + assert_eq!(common.cpb_size_scale, 3); + assert_eq!(common.cpb_size_du_scale, 1); + assert_eq!(common.initial_cpb_removal_delay_length_minus1, 23); + assert_eq!(common.au_cpb_removal_delay_length_minus1, 23); + assert_eq!(common.dpb_output_delay_length_minus1, 23); + assert_eq!(hrd.sub_layers.len(), 1); + let sl = &hrd.sub_layers[0]; + assert!(!sl.fixed_pic_rate_general_flag); + assert!(sl.fixed_pic_rate_within_cvs_flag); + assert_eq!(sl.elemental_duration_in_tc_minus1, Some(0)); + assert!(!sl.low_delay_hrd_flag); + assert_eq!(sl.cpb_cnt_minus1, 1); + assert!(sl.vcl_hrd.is_none()); + let nal = sl.nal_hrd.as_ref().expect("nal hrd present"); + assert_eq!(nal.cpb.len(), 2); + assert_eq!(nal.cpb[0].bit_rate_value_minus1, 0); + assert_eq!(nal.cpb[0].cpb_size_value_minus1, 100); + assert_eq!(nal.cpb[0].cpb_size_du_value_minus1, Some(200)); + assert_eq!(nal.cpb[0].bit_rate_du_value_minus1, Some(50)); + assert!(nal.cpb[0].cbr_flag); + assert_eq!(nal.cpb[1].bit_rate_value_minus1, 1); + assert_eq!(nal.cpb[1].cpb_size_value_minus1, 50); + assert_eq!(nal.cpb[1].cpb_size_du_value_minus1, Some(100)); + assert_eq!(nal.cpb[1].bit_rate_du_value_minus1, Some(100)); + assert!(!nal.cpb[1].cbr_flag); + } + + /// Reject bit_rate_value_minus1[1] <= bit_rate_value_minus1[0] per + /// §E.3.3. + #[test] + fn rejects_non_increasing_bit_rate_value() { + // common: nal=1, vcl=0, sub_pic=0; one sub-layer with cpb_cnt=2. + // Both bit_rate_value_minus1 = 5 → second entry violates strict-increase. + let bytes = bits_to_bytes(&[ + "1", // nal_hrd_parameters_present_flag + "0", // vcl_hrd_parameters_present_flag + "0", // sub_pic_hrd_params_present_flag + &ub(0, 4), // bit_rate_scale + &ub(0, 4), // cpb_size_scale + &ub(23, 5), // initial_cpb_removal_delay_length_minus1 + &ub(23, 5), // au_cpb_removal_delay_length_minus1 + &ub(23, 5), // dpb_output_delay_length_minus1 + "1", // fixed_pic_rate_general_flag = 1 + // within_cvs inferred = 1 + &ue(0), // elemental_duration_in_tc_minus1 = 0 + &ue(1), // cpb_cnt_minus1 = 1 (CpbCnt = 2) + &ue(5), // bit_rate_value_minus1[0] = 5 + &ue(10), // cpb_size_value_minus1[0] + "1", // cbr_flag[0] + &ue(5), // bit_rate_value_minus1[1] = 5 (NOT > previous) → reject + ]); + let mut br = BitReader::new(&bytes); + let err = HrdParameters::parse(&mut br, true, 0, None).unwrap_err(); + assert_eq!( + err, + HrdError::ValueOutOfRange { + field: "bit_rate_value_minus1", + got: 5 + } + ); + } + + /// Reject elemental_duration_in_tc_minus1 > 2047 per §E.3.2. + #[test] + fn rejects_elemental_duration_above_2047() { + let bytes = bits_to_bytes(&[ + "0", // nal=0 + "0", // vcl=0 + "0", // fixed_pic_rate_general_flag = 0 + "1", // fixed_pic_rate_within_cvs_flag = 1 + &ue(2048), // elemental_duration_in_tc_minus1 = 2048 → out of range + ]); + let mut br = BitReader::new(&bytes); + let err = HrdParameters::parse(&mut br, true, 0, None).unwrap_err(); + assert_eq!( + err, + HrdError::ValueOutOfRange { + field: "elemental_duration_in_tc_minus1", + got: 2048 + } + ); + } + + /// Reject cpb_cnt_minus1 > 31 per §E.3.2. + #[test] + fn rejects_cpb_cnt_above_31() { + let bytes = bits_to_bytes(&[ + "0", // nal + "0", // vcl + "1", // fixed_pic_rate_general_flag = 1 + // within_cvs inferred = 1 + &ue(0), // elemental_duration_in_tc_minus1 = 0 + &ue(32), // cpb_cnt_minus1 = 32 → out of range + ]); + let mut br = BitReader::new(&bytes); + let err = HrdParameters::parse(&mut br, true, 0, None).unwrap_err(); + assert_eq!( + err, + HrdError::ValueOutOfRange { + field: "cpb_cnt_minus1", + got: 32 + } + ); + } + + /// `low_delay_hrd_flag = 1` skips `cpb_cnt_minus1` and infers it to + /// 0, but still drives the NAL sub-layer HRD body with CpbCnt = 1. + #[test] + fn low_delay_infers_cpb_cnt_zero() { + let bytes = bits_to_bytes(&[ + "1", // nal_hrd_parameters_present_flag = 1 + "0", // vcl + "0", // sub_pic + &ub(0, 4), // bit_rate_scale + &ub(0, 4), // cpb_size_scale + &ub(23, 5), // initial + &ub(23, 5), // au + &ub(23, 5), // dpb_output + "0", // fixed_pic_rate_general_flag = 0 + "0", // fixed_pic_rate_within_cvs_flag = 0 + "1", // low_delay_hrd_flag = 1 → cpb_cnt_minus1 inferred 0 + &ue(7), // sub_layer NAL: bit_rate_value_minus1[0] = 7 + &ue(15), // cpb_size_value_minus1[0] = 15 + "0", // cbr_flag[0] + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, true, 0, None).expect("parse"); + let sl = &hrd.sub_layers[0]; + assert!(!sl.fixed_pic_rate_general_flag); + assert!(!sl.fixed_pic_rate_within_cvs_flag); + assert!(sl.low_delay_hrd_flag); + assert_eq!(sl.cpb_cnt_minus1, 0); + let nal = sl.nal_hrd.as_ref().expect("nal"); + assert_eq!(nal.cpb.len(), 1); + assert_eq!(nal.cpb[0].bit_rate_value_minus1, 7); + assert_eq!(nal.cpb[0].cpb_size_value_minus1, 15); + assert!(!nal.cpb[0].cbr_flag); + } + + /// `commonInfPresentFlag = 0` inherits the previous entry's common + /// info gates — when the previous entry's NAL flag was 1, the + /// per-sub-layer NAL HRD body is still expected. + #[test] + fn cprms_zero_inherits_previous_common_info() { + let prev = HrdCommonInfo { + nal_hrd_parameters_present_flag: true, + vcl_hrd_parameters_present_flag: false, + sub_pic_hrd_params_present_flag: false, + tick_divisor_minus2: 0, + du_cpb_removal_delay_increment_length_minus1: 0, + sub_pic_cpb_params_in_pic_timing_sei_flag: false, + dpb_output_delay_du_length_minus1: 0, + bit_rate_scale: 0, + cpb_size_scale: 0, + cpb_size_du_scale: 0, + initial_cpb_removal_delay_length_minus1: 23, + au_cpb_removal_delay_length_minus1: 23, + dpb_output_delay_length_minus1: 23, + }; + // Parse the per-sub-layer block only; commonInfPresentFlag = 0. + let bytes = bits_to_bytes(&[ + "1", // fixed_pic_rate_general_flag = 1, within_cvs inferred = 1 + &ue(0), // elemental_duration_in_tc_minus1 = 0 + &ue(0), // cpb_cnt_minus1 = 0 (CpbCnt = 1) + &ue(11), // NAL sub_layer_hrd: bit_rate_value_minus1[0] = 11 + &ue(22), // cpb_size_value_minus1[0] = 22 + "1", // cbr_flag[0] + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, false, 0, Some(&prev)).expect("parse"); + assert!(hrd.common.is_none()); + let sl = &hrd.sub_layers[0]; + let nal = sl.nal_hrd.as_ref().expect("nal inherited"); + assert_eq!(nal.cpb[0].bit_rate_value_minus1, 11); + assert_eq!(nal.cpb[0].cpb_size_value_minus1, 22); + assert!(nal.cpb[0].cbr_flag); + } + + /// VPS-wrapper entry parses hrd_layer_set_idx + cprms_present_flag + /// (when i > 0) ahead of the body. + #[test] + fn vps_hrd_entry_skips_cprms_for_index_zero() { + let bytes = bits_to_bytes(&[ + "1", // hrd_layer_set_idx = 0 ue(v) + // cprms_present_flag not signalled (i == 0); inferred 1 + "0", // nal = 0 + "0", // vcl = 0 + "1", // fixed_pic_rate_general = 1 → within_cvs inferred 1 + "1", // elemental_duration_in_tc_minus1 = 0 + "1", // cpb_cnt_minus1 = 0 + ]); + let mut br = BitReader::new(&bytes); + let entry = VpsHrdEntry::parse(&mut br, 0, 0, None).expect("parse"); + assert_eq!(entry.hrd_layer_set_idx, 0); + assert!(entry.cprms_present_flag); + assert!(entry.hrd.common.is_some()); + } + + /// For `i > 0`, the `cprms_present_flag[i]` `u(1)` is read; setting + /// it to 0 inherits the previous entry's common info. + #[test] + fn vps_hrd_entry_reads_cprms_for_nonzero_index() { + let prev = VpsHrdEntry { + hrd_layer_set_idx: 0, + cprms_present_flag: true, + hrd: HrdParameters { + max_num_sub_layers_minus1: 0, + common: Some(HrdCommonInfo { + nal_hrd_parameters_present_flag: false, + vcl_hrd_parameters_present_flag: false, + sub_pic_hrd_params_present_flag: false, + tick_divisor_minus2: 0, + du_cpb_removal_delay_increment_length_minus1: 0, + sub_pic_cpb_params_in_pic_timing_sei_flag: false, + dpb_output_delay_du_length_minus1: 0, + bit_rate_scale: 0, + cpb_size_scale: 0, + cpb_size_du_scale: 0, + initial_cpb_removal_delay_length_minus1: 0, + au_cpb_removal_delay_length_minus1: 0, + dpb_output_delay_length_minus1: 0, + }), + sub_layers: Vec::new(), + }, + }; + let bytes = bits_to_bytes(&[ + &ue(1), // hrd_layer_set_idx = 1 + "0", // cprms_present_flag[1] = 0 + "1", // fixed_pic_rate_general = 1 + &ue(0), // elemental_duration_in_tc_minus1 = 0 + &ue(0), // cpb_cnt_minus1 = 0 + ]); + let mut br = BitReader::new(&bytes); + let entry = VpsHrdEntry::parse(&mut br, 1, 0, Some(&prev)).expect("parse"); + assert_eq!(entry.hrd_layer_set_idx, 1); + assert!(!entry.cprms_present_flag); + assert!(entry.hrd.common.is_none()); + // Inherited gates were both 0 → no NAL/VCL sub-layer bodies. + assert!(entry.hrd.sub_layers[0].nal_hrd.is_none()); + assert!(entry.hrd.sub_layers[0].vcl_hrd.is_none()); + } + + /// `commonInfPresentFlag = 0` with no `prev_common` results in no + /// NAL/VCL bodies being parsed regardless of subsequent state — the + /// spec's silent-default behaviour when no prior context exists. + #[test] + fn cprms_zero_without_previous_yields_no_hrd_bodies() { + let bytes = bits_to_bytes(&[ + "1", // fixed_pic_rate_general_flag = 1 + "1", // elemental_duration_in_tc_minus1 = 0 + "1", // cpb_cnt_minus1 = 0 + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, false, 0, None).expect("parse"); + assert!(hrd.common.is_none()); + let sl = &hrd.sub_layers[0]; + assert!(sl.nal_hrd.is_none()); + assert!(sl.vcl_hrd.is_none()); + } + + /// Multi-sub-layer payload (`maxNumSubLayersMinus1 = 2`) iterates + /// the per-sub-layer block three times. + #[test] + fn parses_three_sub_layers() { + let bytes = bits_to_bytes(&[ + "0", + "0", // no HRD bodies + // sub-layer 0 + "1", // fixed_pic_rate_general + &ue(0), // elemental_duration_in_tc_minus1 = 0 + &ue(0), // cpb_cnt_minus1 = 0 (low_delay inferred 0) + // sub-layer 1 + "0", // general = 0 + "0", // within_cvs = 0 + "1", // low_delay = 1 + // cpb_cnt_minus1 skipped (low_delay = 1) + // sub-layer 2 + "0", // general = 0 + "1", // within_cvs = 1 + &ue(7), // elemental_duration_in_tc_minus1 = 7 + &ue(0), // cpb_cnt_minus1 = 0 + ]); + let mut br = BitReader::new(&bytes); + let hrd = HrdParameters::parse(&mut br, true, 2, None).expect("parse"); + assert_eq!(hrd.sub_layers.len(), 3); + assert!(hrd.sub_layers[0].fixed_pic_rate_general_flag); + assert!(hrd.sub_layers[0].fixed_pic_rate_within_cvs_flag); + assert_eq!(hrd.sub_layers[0].elemental_duration_in_tc_minus1, Some(0)); + assert!(!hrd.sub_layers[1].fixed_pic_rate_general_flag); + assert!(!hrd.sub_layers[1].fixed_pic_rate_within_cvs_flag); + assert!(hrd.sub_layers[1].low_delay_hrd_flag); + assert_eq!(hrd.sub_layers[1].cpb_cnt_minus1, 0); + assert!(!hrd.sub_layers[2].fixed_pic_rate_general_flag); + assert!(hrd.sub_layers[2].fixed_pic_rate_within_cvs_flag); + assert_eq!(hrd.sub_layers[2].elemental_duration_in_tc_minus1, Some(7)); + } +} diff --git a/vendor/oxideav-h265/src/hvcc.rs b/vendor/oxideav-h265/src/hvcc.rs new file mode 100644 index 0000000..5eebf49 --- /dev/null +++ b/vendor/oxideav-h265/src/hvcc.rs @@ -0,0 +1,408 @@ +//! `HEVCDecoderConfigurationRecord` (`hvcC`) extradata parse. +//! +//! ISO-BMFF tracks carry the HEVC parameter sets out of band, inside +//! the sample entry's `hvcC` box, and frame the in-band NAL units with +//! big-endian length prefixes instead of Annex B start codes. The +//! record layout implemented here is the `aligned(8)` class of +//! ISO/IEC 14496-15 §8.3.3.1.2 (`HEVCDecoderConfigurationRecord`): +//! +//! ```text +//! unsigned int(8) configurationVersion = 1; +//! unsigned int(2) general_profile_space; +//! unsigned int(1) general_tier_flag; +//! unsigned int(5) general_profile_idc; +//! unsigned int(32) general_profile_compatibility_flags; +//! unsigned int(48) general_constraint_indicator_flags; +//! unsigned int(8) general_level_idc; +//! bit(4) reserved; unsigned int(12) min_spatial_segmentation_idc; +//! bit(6) reserved; unsigned int(2) parallelismType; +//! bit(6) reserved; unsigned int(2) chroma_format_idc; +//! bit(5) reserved; unsigned int(3) bit_depth_luma_minus8; +//! bit(5) reserved; unsigned int(3) bit_depth_chroma_minus8; +//! unsigned int(16) avgFrameRate; +//! unsigned int(2) constantFrameRate; +//! unsigned int(3) numTemporalLayers; +//! unsigned int(1) temporalIdNested; +//! unsigned int(2) lengthSizeMinusOne; +//! unsigned int(8) numOfArrays; +//! for (j = 0; j < numOfArrays; j++) { +//! unsigned int(1) array_completeness; +//! bit(1) reserved; +//! unsigned int(6) NAL_unit_type; +//! unsigned int(16) numNalus; +//! for (i = 0; i < numNalus; i++) { +//! unsigned int(16) nalUnitLength; +//! bit(8*nalUnitLength) nalUnit; +//! } +//! } +//! ``` +//! +//! The NAL units inside the arrays are complete coded NAL units +//! (two-byte §7.3.1.2 header plus the emulation-escaped payload) — +//! exactly what an Annex B start code would delimit. §8.3.3.1.3 +//! restricts the array `NAL_unit_type` values to VPS / SPS / PPS and +//! prefix / suffix SEI; readers ignore arrays with any other type. +//! +//! [`split_length_prefixed`] performs the companion sample-data +//! re-framing: each in-band access unit is a run of +//! `lengthSizeMinusOne + 1`-byte big-endian sizes, each followed by +//! that many coded NAL bytes. + +use crate::nal::{strip_emulation_prevention, NalError, NalHeader, NalUnit}; + +/// Errors from the `hvcC` record parse or the length-prefixed +/// sample-data split. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum HvccError { + /// The record is shorter than the fixed 23-byte prefix, or an + /// array / NAL-unit length points past the end of the record. + Truncated, + /// `configurationVersion` was not 1 (the only value ISO/IEC + /// 14496-15 defines; incompatible records must change it). + BadVersion(u8), + /// `lengthSizeMinusOne` was 2 — §8.3.3.1.3 allows only 0, 1 + /// and 3 (1-, 2- and 4-byte length prefixes). + BadLengthSize, + /// A carried NAL unit failed the §7.3.1.2 header parse. + Nal(NalError), + /// A sample-data buffer ended in the middle of a length prefix + /// or of the NAL bytes the prefix promised. + TruncatedSample, +} + +impl core::fmt::Display for HvccError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("hvcC record truncated"), + Self::BadVersion(v) => write!(f, "hvcC configurationVersion {v} (expected 1)"), + Self::BadLengthSize => f.write_str("hvcC lengthSizeMinusOne 2 is reserved"), + Self::Nal(e) => write!(f, "hvcC-carried NAL unit: {e}"), + Self::TruncatedSample => f.write_str("length-prefixed sample data truncated"), + } + } +} + +impl std::error::Error for HvccError {} + +impl From for HvccError { + fn from(e: NalError) -> Self { + Self::Nal(e) + } +} + +/// Parsed `HEVCDecoderConfigurationRecord` (ISO/IEC 14496-15 +/// §8.3.3.1.2). The profile / level mirror fields carry the §7.3.3 +/// `profile_tier_level` values of the stream's parameter sets; the +/// decoder proper re-derives everything from the carried VPS / SPS / +/// PPS, so they are surfaced for inspection only. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HvccRecord { + /// `general_profile_space` (2 bits). + pub general_profile_space: u8, + /// `general_tier_flag`. + pub general_tier_flag: bool, + /// `general_profile_idc` (5 bits). + pub general_profile_idc: u8, + /// `general_profile_compatibility_flags` (32 bits; bit 31 is + /// `general_profile_compatibility_flag[0]`). + pub general_profile_compatibility_flags: u32, + /// `general_constraint_indicator_flags` (48 bits, in the low bits). + pub general_constraint_indicator_flags: u64, + /// `general_level_idc`. + pub general_level_idc: u8, + /// `min_spatial_segmentation_idc` (12 bits). + pub min_spatial_segmentation_idc: u16, + /// `parallelismType` (2 bits): 0 unknown / mixed, 1 slices, + /// 2 tiles, 3 entropy-coding sync. + pub parallelism_type: u8, + /// `chroma_format_idc` mirror (2 bits). + pub chroma_format_idc: u8, + /// `bit_depth_luma_minus8` mirror (3 bits). + pub bit_depth_luma_minus8: u8, + /// `bit_depth_chroma_minus8` mirror (3 bits). + pub bit_depth_chroma_minus8: u8, + /// `avgFrameRate` in frames per 256 seconds (0 = unspecified). + pub avg_frame_rate: u16, + /// `constantFrameRate` (2 bits). + pub constant_frame_rate: u8, + /// `numTemporalLayers` (3 bits). + pub num_temporal_layers: u8, + /// `temporalIdNested`. + pub temporal_id_nested: bool, + /// Byte width of every in-band NAL length prefix + /// (`lengthSizeMinusOne + 1`): 1, 2 or 4. + pub length_size: usize, + /// The carried parameter-set / SEI NAL units, in array order, + /// parsed exactly as an Annex B walker would surface them. + /// Arrays with a reserved / unpermitted `NAL_unit_type` are + /// skipped per §8.3.3.1.3. + pub nal_units: Vec, +} + +/// The array `NAL_unit_type` values §8.3.3.1.3 permits: VPS (32), +/// SPS (33), PPS (34), prefix SEI (39), suffix SEI (40). +fn array_type_permitted(nal_unit_type: u8) -> bool { + matches!(nal_unit_type, 32..=34 | 39 | 40) +} + +/// Reconstruct a [`NalUnit`] from a complete coded NAL unit (two-byte +/// header + emulation-escaped payload) — the framing-free form both +/// the `hvcC` arrays and length-prefixed sample data carry. +pub fn nal_unit_from_coded(coded: &[u8]) -> Result { + let unescaped = strip_emulation_prevention(coded); + let header = NalHeader::parse(&unescaped)?; + Ok(NalUnit { + header, + rbsp: unescaped[2..].to_vec(), + escaped: coded[2..].to_vec(), + }) +} + +/// Quick extradata-form probe: an `hvcC` record always starts with +/// `configurationVersion == 1` and is at least 23 bytes, while Annex B +/// extradata starts with a `00 00 01` / `00 00 00 01` start code. +pub fn extradata_is_hvcc(data: &[u8]) -> bool { + data.len() >= 23 && data[0] == 1 +} + +/// Parse an `HEVCDecoderConfigurationRecord` per ISO/IEC 14496-15 +/// §8.3.3.1.2. +/// +/// # Errors +/// [`HvccError`] on truncation, a version other than 1, the reserved +/// length size, or an undecodable carried NAL unit. +pub fn parse_hvcc(data: &[u8]) -> Result { + if data.len() < 23 { + return Err(HvccError::Truncated); + } + if data[0] != 1 { + return Err(HvccError::BadVersion(data[0])); + } + let length_size_minus_one = (data[21] & 0x03) as usize; + if length_size_minus_one == 2 { + return Err(HvccError::BadLengthSize); + } + + let mut nal_units = Vec::new(); + let num_of_arrays = data[22] as usize; + let mut pos = 23; + for _ in 0..num_of_arrays { + if pos + 3 > data.len() { + return Err(HvccError::Truncated); + } + let nal_unit_type = data[pos] & 0x3F; + let num_nalus = u16::from_be_bytes([data[pos + 1], data[pos + 2]]) as usize; + pos += 3; + for _ in 0..num_nalus { + if pos + 2 > data.len() { + return Err(HvccError::Truncated); + } + let len = u16::from_be_bytes([data[pos], data[pos + 1]]) as usize; + pos += 2; + if pos + len > data.len() { + return Err(HvccError::Truncated); + } + if array_type_permitted(nal_unit_type) { + nal_units.push(nal_unit_from_coded(&data[pos..pos + len])?); + } + pos += len; + } + } + + Ok(HvccRecord { + general_profile_space: data[1] >> 6, + general_tier_flag: data[1] & 0x20 != 0, + general_profile_idc: data[1] & 0x1F, + general_profile_compatibility_flags: u32::from_be_bytes([ + data[2], data[3], data[4], data[5], + ]), + general_constraint_indicator_flags: u64::from_be_bytes([ + 0, 0, data[6], data[7], data[8], data[9], data[10], data[11], + ]), + general_level_idc: data[12], + min_spatial_segmentation_idc: u16::from_be_bytes([data[13] & 0x0F, data[14]]), + parallelism_type: data[15] & 0x03, + chroma_format_idc: data[16] & 0x03, + bit_depth_luma_minus8: data[17] & 0x07, + bit_depth_chroma_minus8: data[18] & 0x07, + avg_frame_rate: u16::from_be_bytes([data[19], data[20]]), + constant_frame_rate: data[21] >> 6, + num_temporal_layers: (data[21] >> 3) & 0x07, + temporal_id_nested: data[21] & 0x04 != 0, + length_size: length_size_minus_one + 1, + nal_units, + }) +} + +/// Split a length-prefixed sample buffer (ISO-BMFF `mdat` payload for +/// one or more access units) into its coded NAL units, `length_size` +/// bytes of big-endian size before each unit. +/// +/// # Errors +/// [`HvccError::TruncatedSample`] when the buffer ends mid-prefix or +/// mid-unit; [`HvccError::Nal`] when a unit's header is malformed. +pub fn split_length_prefixed(data: &[u8], length_size: usize) -> Result, HvccError> { + debug_assert!(matches!(length_size, 1 | 2 | 4)); + let mut out = Vec::new(); + let mut pos = 0; + while pos < data.len() { + if pos + length_size > data.len() { + return Err(HvccError::TruncatedSample); + } + let mut len = 0usize; + for &b in &data[pos..pos + length_size] { + len = (len << 8) | b as usize; + } + pos += length_size; + if pos + len > data.len() { + return Err(HvccError::TruncatedSample); + } + out.push(nal_unit_from_coded(&data[pos..pos + len])?); + pos += len; + } + Ok(out) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Build a minimal record: fixed 23-byte prefix + one SPS array + /// with one 3-byte NAL (header 0x42 0x01 = SPS, + 1 payload byte). + fn tiny_record(version: u8, length_size_code: u8) -> Vec { + let mut r = vec![ + version, // configurationVersion + 0x21, // space 0, tier 1, profile_idc 1 + 0x60, + 0x00, + 0x00, + 0x00, // compatibility flags + 0x90, + 0x00, + 0x00, + 0x00, + 0x00, + 0x00, // constraint flags + 0x5D, // level 93 + 0xF0, + 0x07, // min_spatial_segmentation_idc = 7 + 0xFC | 0x01, // parallelismType 1 + 0xFC | 0x01, // chroma_format_idc 1 + 0xF8 | 0x02, // bit_depth_luma_minus8 = 2 + 0xF8 | 0x02, // bit_depth_chroma_minus8 = 2 + 0x00, + 0x19, // avgFrameRate 25 + (1 << 3) | 0x04 | length_size_code, // 1 layer, nested, length size + 0x01, // numOfArrays + ]; + // Array: SPS (33), 1 NAL of 3 bytes. + r.extend_from_slice(&[0x21, 0x00, 0x01, 0x00, 0x03, 0x42, 0x01, 0xAA]); + r + } + + #[test] + fn parses_fixed_fields_and_array() { + let rec = parse_hvcc(&tiny_record(1, 3)).expect("parse"); + assert_eq!(rec.general_profile_space, 0); + assert!(rec.general_tier_flag); + assert_eq!(rec.general_profile_idc, 1); + assert_eq!(rec.general_profile_compatibility_flags, 0x6000_0000); + assert_eq!(rec.general_constraint_indicator_flags, 0x9000_0000_0000); + assert_eq!(rec.general_level_idc, 93); + assert_eq!(rec.min_spatial_segmentation_idc, 7); + assert_eq!(rec.parallelism_type, 1); + assert_eq!(rec.chroma_format_idc, 1); + assert_eq!(rec.bit_depth_luma_minus8, 2); + assert_eq!(rec.bit_depth_chroma_minus8, 2); + assert_eq!(rec.avg_frame_rate, 25); + assert_eq!(rec.num_temporal_layers, 1); + assert!(rec.temporal_id_nested); + assert_eq!(rec.length_size, 4); + assert_eq!(rec.nal_units.len(), 1); + assert_eq!(rec.nal_units[0].header.nal_unit_type, 33); + assert_eq!(rec.nal_units[0].rbsp, vec![0xAA]); + } + + #[test] + fn rejects_bad_version_and_reserved_length_size() { + assert_eq!( + parse_hvcc(&tiny_record(0, 3)).unwrap_err(), + HvccError::BadVersion(0) + ); + assert_eq!( + parse_hvcc(&tiny_record(1, 2)).unwrap_err(), + HvccError::BadLengthSize + ); + } + + #[test] + fn truncation_at_every_seam_is_an_error() { + let full = tiny_record(1, 3); + for cut in [10, 22, 24, 26, full.len() - 1] { + assert_eq!( + parse_hvcc(&full[..cut]).unwrap_err(), + HvccError::Truncated, + "cut at {cut}" + ); + } + } + + #[test] + fn skips_reserved_array_types() { + let mut r = tiny_record(1, 3); + r[22] = 2; // numOfArrays = 2 + // Second array with reserved type 41: one 3-byte NAL. + r.extend_from_slice(&[0x29, 0x00, 0x01, 0x00, 0x03, 0x42, 0x01, 0xBB]); + let rec = parse_hvcc(&r).expect("parse"); + assert_eq!(rec.nal_units.len(), 1, "reserved-type array ignored"); + } + + #[test] + fn probe_distinguishes_hvcc_from_annexb() { + assert!(extradata_is_hvcc(&tiny_record(1, 3))); + let annexb = [ + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0C, 0x01, 0xFF, 0xFF, 0x04, 0x08, 0x00, 0x00, + 0x03, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1E, + ]; + assert!(!extradata_is_hvcc(&annexb)); + assert!(!extradata_is_hvcc(&[1, 2, 3])); + } + + #[test] + fn splits_length_prefixed_sample_data() { + // Two NAL units behind 4-byte prefixes: SPS (3 bytes) and an + // IDR_W_RADL slice (4 bytes) with an emulation escape. + let sample = [ + 0x00, 0x00, 0x00, 0x03, 0x42, 0x01, 0xAA, // SPS + 0x00, 0x00, 0x00, 0x06, 0x26, 0x01, 0x00, 0x00, 0x03, 0x00, // IDR + ]; + let units = split_length_prefixed(&sample, 4).expect("split"); + assert_eq!(units.len(), 2); + assert_eq!(units[0].header.nal_unit_type, 33); + assert_eq!(units[1].header.nal_unit_type, 19); + // The escape 00 00 03 00 unstripped in `escaped`, stripped in rbsp. + assert_eq!(units[1].escaped, vec![0x00, 0x00, 0x03, 0x00]); + assert_eq!(units[1].rbsp, vec![0x00, 0x00, 0x00]); + } + + #[test] + fn sample_truncation_is_an_error() { + let sample = [0x00, 0x00, 0x00, 0x05, 0x42, 0x01]; + assert_eq!( + split_length_prefixed(&sample, 4).unwrap_err(), + HvccError::TruncatedSample + ); + assert_eq!( + split_length_prefixed(&[0x00, 0x00], 4).unwrap_err(), + HvccError::TruncatedSample + ); + } + + #[test] + fn two_byte_prefix_form() { + let sample = [0x00, 0x03, 0x42, 0x01, 0xAA]; + let units = split_length_prefixed(&sample, 2).expect("split"); + assert_eq!(units.len(), 1); + assert_eq!(units[0].header.nal_unit_type, 33); + } +} diff --git a/vendor/oxideav-h265/src/inter_pred.rs b/vendor/oxideav-h265/src/inter_pred.rs new file mode 100644 index 0000000..99f3531 --- /dev/null +++ b/vendor/oxideav-h265/src/inter_pred.rs @@ -0,0 +1,1385 @@ +//! §8.5.3.3.3 — fractional sample interpolation, plus the §8.5.3.3.4 +//! weighted sample prediction combines (default and explicit). +//! +//! This module turns a reference-picture sample plane and a motion vector +//! into an `(nPbW)x(nPbH)` array of inter-predicted samples. Four ITU-T +//! H.265 subclauses are implemented, in the order §8.5.3.3.3.1 invokes +//! them: +//! +//! * §8.5.3.3.3.2 **luma sample interpolation** ([`interp_luma_block`]) — +//! the separable 8-tap quarter-pel filter of equations 8-224..8-238, +//! with the Table 8-8 phase selection. `shift1 = Min(4, BitDepthY − 8)`, +//! `shift2 = 6`, `shift3 = Max(2, 14 − BitDepthY)`; the full-pel case is +//! `A << shift3`. +//! * §8.5.3.3.3.3 **chroma sample interpolation** ([`interp_chroma_block`]) +//! — the separable 4-tap eighth-pel filter of equations 8-241..8-261, +//! with the Table 8-9 phase selection. `shift1 = Min(4, BitDepthC − 8)`, +//! `shift2 = 6`, `shift3 = Max(2, 14 − BitDepthC)`. +//! * §8.5.3.3.4.2 **default weighted sample prediction** +//! ([`default_weighted_pred`]) — the uni- / bi-predictive combine of +//! equations 8-262..8-264 (`weightedPredFlag == 0`), with +//! `shift1 = Max(2, 14 − bitDepth)`, `shift2 = Max(3, 15 − bitDepth)`. +//! * §8.5.3.3.4.3 **explicit weighted sample prediction** +//! ([`explicit_weighted_pred`]) — the per-reference weight / offset +//! combine of equations 8-265..8-277 (`weightedPredFlag == 1`, i.e. +//! `weighted_pred_flag` for P slices / `weighted_bipred_flag` for B +//! slices), with `log2Wd = log2WeightDenom + shift1`. +//! +//! The interpolation processes emit *intermediate* sample values at the +//! `14 − BitDepth`-bit internal precision the spec carries between +//! §8.5.3.3.3 and §8.5.3.3.4 (i.e. the `>> shift1` / `>> shift2` outputs, +//! `A << shift3` for full-pel — they are **not** yet clipped to the +//! sample range). The weighted combines consume those intermediate +//! arrays and produce the final `[0, (1 << bitDepth) − 1]` prediction +//! samples. +//! +//! ## Scope +//! +//! The numerics are self-contained. The §8.5.3.2 merge / §8.5.3.1 MV +//! derivation that produces `mvLX`, the §8.5.3.3.1 driver that splits a +//! motion vector into its integer / fractional parts and walks the +//! prediction block, and the §8.6.5 picture-construction step that adds +//! the residual are the caller's responsibility — this module starts at +//! a `(xInt, yInt, xFrac, yFrac)` location and a reference plane, and +//! stops at the prediction sample arrays. + +/// A reference-picture luma / chroma sample plane with the §8.5.3.3.3 +/// `Clip3( 0, dim − 1, … )` edge-extension border (equations 8-222 / +/// 8-223 for luma, 8-239 / 8-240 for chroma). +/// +/// The interpolation filters read samples at negative and past-the-edge +/// coordinates; this type clamps every access into the valid plane so the +/// callers can index with the raw `xInt + i` / `yInt + j` offsets the +/// equations use. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RefPlane<'a> { + /// Row-major samples, `width * height` of them. `sample[ y * width + x ]` + /// is the plane sample at full-sample location `( x, y )`. + samples: &'a [i32], + /// Plane width in samples (`pic_width_in_luma_samples` for luma, or + /// `pic_width_in_luma_samples / SubWidthC` for chroma). + width: usize, + /// Plane height in samples. + height: usize, +} + +impl<'a> RefPlane<'a> { + /// Wraps a row-major `width * height` sample plane. + /// + /// # Errors + /// + /// [`InterPredError::PlaneLengthMismatch`] if `samples.len()` is not + /// exactly `width * height`, or [`InterPredError::EmptyPlane`] if + /// either dimension is zero. + pub fn new(samples: &'a [i32], width: usize, height: usize) -> Result { + if width == 0 || height == 0 { + return Err(InterPredError::EmptyPlane); + } + let expected = width + .checked_mul(height) + .ok_or(InterPredError::EmptyPlane)?; + if samples.len() != expected { + return Err(InterPredError::PlaneLengthMismatch { + expected, + got: samples.len(), + }); + } + Ok(Self { + samples, + width, + height, + }) + } + + /// The plane width in samples. + #[inline] + #[must_use] + pub fn width(&self) -> usize { + self.width + } + + /// The plane height in samples. + #[inline] + #[must_use] + pub fn height(&self) -> usize { + self.height + } + + /// Sample at full-sample location `( x, y )` with the §8.5.3.3.3 + /// `Clip3( 0, dim − 1, … )` edge extension (equations 8-222 / 8-223 / + /// 8-239 / 8-240). `x` and `y` may be negative or past the edge. + #[inline] + #[must_use] + pub fn at(&self, x: i32, y: i32) -> i32 { + let xc = x.clamp(0, self.width as i32 - 1) as usize; + let yc = y.clamp(0, self.height as i32 - 1) as usize; + self.samples[yc * self.width + xc] + } +} + +/// Errors from the §8.5.3.3 inter-prediction processes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum InterPredError { + /// A reference plane had a zero width or height. + EmptyPlane, + /// A reference plane's sample count did not equal `width * height`. + PlaneLengthMismatch { + /// The `width * height` count the plane requires. + expected: usize, + /// The element count actually supplied. + got: usize, + }, + /// A prediction-block dimension (`nPbW` or `nPbH`) was zero. + EmptyBlock, + /// `xFracL` / `yFracL` was outside the `0..=3` quarter-pel range, or + /// `xFracC` / `yFracC` was outside the `0..=7` eighth-pel range. + InvalidFraction(i32), + /// `bitDepth` was outside the 8..=16 range the equations are + /// dimensioned for. + InvalidBitDepth(u8), + /// The two `predSamplesLX` arrays handed to the weighted combine did + /// not have matching `nPbW * nPbH` lengths. + ArrayLengthMismatch { + /// The `nPbW * nPbH` count both arrays require. + expected: usize, + /// The element count actually supplied. + got: usize, + }, +} + +impl core::fmt::Display for InterPredError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::EmptyPlane => write!(f, "reference plane has zero width or height"), + Self::PlaneLengthMismatch { expected, got } => { + write!( + f, + "reference plane length {got} != width*height = {expected}" + ) + } + Self::EmptyBlock => write!(f, "prediction block dimension nPbW/nPbH is zero"), + Self::InvalidFraction(v) => { + write!( + f, + "invalid fractional offset {v} (luma 0..=3, chroma 0..=7)" + ) + } + Self::InvalidBitDepth(b) => write!(f, "invalid bitDepth {b} (expected 8..=16)"), + Self::ArrayLengthMismatch { expected, got } => { + write!(f, "prediction array length {got} != nPbW*nPbH = {expected}") + } + } + } +} + +impl std::error::Error for InterPredError {} + +/// `shift1` for luma / chroma interpolation: `Min( 4, BitDepth − 8 )`. +#[inline] +fn interp_shift1(bit_depth: u8) -> i32 { + core::cmp::min(4, bit_depth as i32 - 8) +} + +/// `shift3` for luma / chroma interpolation: `Max( 2, 14 − BitDepth )`. +#[inline] +fn interp_shift3(bit_depth: u8) -> i32 { + core::cmp::max(2, 14 - bit_depth as i32) +} + +// --------------------------------------------------------------------------- +// §8.5.3.3.3.2 — luma sample interpolation +// --------------------------------------------------------------------------- + +/// The §8.5.3.3.3.2 horizontal 8-tap luma filters, indexed by `xFracL`. +/// +/// Row 0 (`xFracL == 0`) is the identity (the spec leaves the integer +/// sample untouched on the horizontal pass); rows 1/2/3 are the `a`/`b`/`c` +/// kernels of equations 8-224 / 8-225 / 8-226, each over the eight taps +/// `A[−3..4]`. +const LUMA_FILTER: [[i32; 8]; 4] = [ + [0, 0, 0, 64, 0, 0, 0, 0], + [-1, 4, -10, 58, 17, -5, 1, 0], + [-1, 4, -11, 40, 40, -11, 4, -1], + [0, 1, -5, 17, 58, -10, 4, -1], +]; + +/// One separable 8-tap luma sample at fractional offset `( x_frac, y_frac )`, +/// centred on integer location `( x_int, y_int )` (§8.5.3.3.3.2). +/// +/// Returns the intermediate sample value (`>> shift1` / `>> shift2`, or +/// `A << shift3` for the full-pel `( 0, 0 )` corner) at the +/// `14 − BitDepthY`-bit internal precision — not yet clipped. +#[inline] +fn interp_luma_sample( + plane: &RefPlane<'_>, + x_int: i32, + y_int: i32, + x_frac: i32, + y_frac: i32, + bit_depth: u8, +) -> i32 { + let shift1 = interp_shift1(bit_depth); + let shift3 = interp_shift3(bit_depth); + + // Full-pel: A << shift3 (Table 8-8, xFracL == yFracL == 0). + if x_frac == 0 && y_frac == 0 { + return plane.at(x_int, y_int) << shift3; + } + + let hk = &LUMA_FILTER[x_frac as usize]; + let vk = &LUMA_FILTER[y_frac as usize]; + + if y_frac == 0 { + // Horizontal-only (a / b / c): >> shift1. + let mut acc = 0i32; + for (t, &c) in hk.iter().enumerate() { + acc += c * plane.at(x_int - 3 + t as i32, y_int); + } + return acc >> shift1; + } + + if x_frac == 0 { + // Vertical-only (d / h / n): >> shift1. + let mut acc = 0i32; + for (t, &c) in vk.iter().enumerate() { + acc += c * plane.at(x_int, y_int - 3 + t as i32); + } + return acc >> shift1; + } + + // Two-dimensional (e/i/p, f/j/q, g/k/r): horizontal pass at >> shift1 + // over rows j = −3..4, then a vertical pass at >> shift2 = 6. + let mut acc = 0i32; + for (vt, &cv) in vk.iter().enumerate() { + let row = y_int - 3 + vt as i32; + let mut h = 0i32; + for (ht, &ch) in hk.iter().enumerate() { + h += ch * plane.at(x_int - 3 + ht as i32, row); + } + acc += cv * (h >> shift1); + } + acc >> 6 +} + +/// §8.5.3.3.3.2 — fill an `(nPbW)x(nPbH)` luma prediction block. +/// +/// `( x_int, y_int )` is the integer part of the motion-compensated +/// top-left location (`xPb + ( mvLX[0] >> 2 )`, `yPb + ( mvLX[1] >> 2 )` +/// per equations 8-214 / 8-215) and `( x_frac, y_frac )` the +/// quarter-pel remainder (`mvLX[..] & 3`, equations 8-216 / 8-217). The +/// output is row-major, `predSamples[ y * nPbW + x ]`, holding the +/// intermediate-precision values §8.5.3.3.4 consumes. +/// +/// # Errors +/// +/// [`InterPredError::EmptyBlock`] for a zero block dimension, +/// [`InterPredError::InvalidFraction`] for a fraction outside `0..=3`, and +/// [`InterPredError::InvalidBitDepth`] for a bit depth outside `8..=16`. +// The §8.5.3.3.3.2 location / fraction / dimension / bit-depth inputs are +// each distinct spec quantities; bundling them would obscure the mapping. +#[allow(clippy::too_many_arguments)] +pub fn interp_luma_block( + plane: &RefPlane<'_>, + x_int: i32, + y_int: i32, + x_frac: i32, + y_frac: i32, + n_pb_w: usize, + n_pb_h: usize, + bit_depth: u8, +) -> Result, InterPredError> { + if n_pb_w == 0 || n_pb_h == 0 { + return Err(InterPredError::EmptyBlock); + } + if !(0..=3).contains(&x_frac) { + return Err(InterPredError::InvalidFraction(x_frac)); + } + if !(0..=3).contains(&y_frac) { + return Err(InterPredError::InvalidFraction(y_frac)); + } + if !(8..=16).contains(&bit_depth) { + return Err(InterPredError::InvalidBitDepth(bit_depth)); + } + + let mut out = vec![0i32; n_pb_w * n_pb_h]; + for yl in 0..n_pb_h as i32 { + for xl in 0..n_pb_w as i32 { + out[(yl as usize) * n_pb_w + xl as usize] = + interp_luma_sample(plane, x_int + xl, y_int + yl, x_frac, y_frac, bit_depth); + } + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// §8.5.3.3.3.3 — chroma sample interpolation +// --------------------------------------------------------------------------- + +/// The §8.5.3.3.3.3 4-tap chroma filters, indexed by the eighth-pel phase. +/// +/// Row 0 (phase 0) is the identity; rows 1..7 are the `ab`/`ac`/`ad`/`ae`/ +/// `af`/`ag`/`ah` kernels of equations 8-241..8-247, each over the four +/// taps `B[−1..2]`. +const CHROMA_FILTER: [[i32; 4]; 8] = [ + [0, 64, 0, 0], + [-2, 58, 10, -2], + [-4, 54, 16, -2], + [-6, 46, 28, -4], + [-4, 36, 36, -4], + [-4, 28, 46, -6], + [-2, 16, 54, -4], + [-2, 10, 58, -2], +]; + +/// One separable 4-tap chroma sample at eighth-pel offset +/// `( x_frac, y_frac )`, centred on integer location `( x_int, y_int )` +/// (§8.5.3.3.3.3). Returns the intermediate-precision value (not clipped). +#[inline] +fn interp_chroma_sample( + plane: &RefPlane<'_>, + x_int: i32, + y_int: i32, + x_frac: i32, + y_frac: i32, + bit_depth: u8, +) -> i32 { + let shift1 = interp_shift1(bit_depth); + let shift3 = interp_shift3(bit_depth); + + if x_frac == 0 && y_frac == 0 { + return plane.at(x_int, y_int) << shift3; + } + + let hk = &CHROMA_FILTER[x_frac as usize]; + let vk = &CHROMA_FILTER[y_frac as usize]; + + if y_frac == 0 { + // Horizontal-only (aX, equations 8-241..8-247): >> shift1. + let mut acc = 0i32; + for (t, &c) in hk.iter().enumerate() { + acc += c * plane.at(x_int - 1 + t as i32, y_int); + } + return acc >> shift1; + } + + if x_frac == 0 { + // Vertical-only (Xa, equations 8-248..8-254): >> shift1. + let mut acc = 0i32; + for (t, &c) in vk.iter().enumerate() { + acc += c * plane.at(x_int, y_int - 1 + t as i32); + } + return acc >> shift1; + } + + // Two-dimensional (XY, equations 8-255..8-261): horizontal pass at + // >> shift1 over rows i = −1..2, then a vertical pass at >> shift2 = 6. + let mut acc = 0i32; + for (vt, &cv) in vk.iter().enumerate() { + let row = y_int - 1 + vt as i32; + let mut h = 0i32; + for (ht, &ch) in hk.iter().enumerate() { + h += ch * plane.at(x_int - 1 + ht as i32, row); + } + acc += cv * (h >> shift1); + } + acc >> 6 +} + +/// §8.5.3.3.3.3 — fill an `(nPbW / SubWidthC)x(nPbH / SubHeightC)` chroma +/// prediction block. +/// +/// `( x_int, y_int )` is the integer chroma location and +/// `( x_frac, y_frac )` the eighth-pel remainder (`mvCLX[..] & 7`, +/// equations 8-220 / 8-221). `block_w` / `block_h` are the chroma block +/// dimensions. Output is row-major intermediate-precision values. +/// +/// # Errors +/// +/// [`InterPredError::EmptyBlock`] for a zero block dimension, +/// [`InterPredError::InvalidFraction`] for a fraction outside `0..=7`, and +/// [`InterPredError::InvalidBitDepth`] for a bit depth outside `8..=16`. +// The §8.5.3.3.3.3 location / fraction / dimension / bit-depth inputs are +// each distinct spec quantities; bundling them would obscure the mapping. +#[allow(clippy::too_many_arguments)] +pub fn interp_chroma_block( + plane: &RefPlane<'_>, + x_int: i32, + y_int: i32, + x_frac: i32, + y_frac: i32, + block_w: usize, + block_h: usize, + bit_depth: u8, +) -> Result, InterPredError> { + if block_w == 0 || block_h == 0 { + return Err(InterPredError::EmptyBlock); + } + if !(0..=7).contains(&x_frac) { + return Err(InterPredError::InvalidFraction(x_frac)); + } + if !(0..=7).contains(&y_frac) { + return Err(InterPredError::InvalidFraction(y_frac)); + } + if !(8..=16).contains(&bit_depth) { + return Err(InterPredError::InvalidBitDepth(bit_depth)); + } + + let mut out = vec![0i32; block_w * block_h]; + for yc in 0..block_h as i32 { + for xc in 0..block_w as i32 { + out[(yc as usize) * block_w + xc as usize] = + interp_chroma_sample(plane, x_int + xc, y_int + yc, x_frac, y_frac, bit_depth); + } + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// §8.5.3.3.4.2 — default weighted sample prediction +// --------------------------------------------------------------------------- + +/// §8.5.3.3.4.2 — combine the L0 / L1 intermediate prediction arrays into +/// the final `(nPbW)x(nPbH)` prediction samples (the +/// `weighted_pred_flag == 0` path, equations 8-262..8-264). +/// +/// `pred_l0` / `pred_l1` are the intermediate-precision arrays produced by +/// [`interp_luma_block`] / [`interp_chroma_block`]; `pred_flag_l0` / +/// `pred_flag_l1` are the §8.5.3.2.1 prediction-list utilisation flags. At +/// least one flag must be set (the spec only invokes this process for a +/// predicted block). Output is the clipped `[0, (1 << bitDepth) − 1]` +/// sample array. +/// +/// Unused arrays may be empty when their `pred_flag` is `false`; only the +/// array(s) whose flag is set are read and length-checked. +/// +/// # Errors +/// +/// [`InterPredError::EmptyBlock`] for a zero block dimension, +/// [`InterPredError::InvalidBitDepth`] for a bit depth outside `8..=16`, +/// [`InterPredError::EmptyPlane`] (re-used as "no list selected") when +/// both flags are `false`, and [`InterPredError::ArrayLengthMismatch`] +/// when a selected array is not `nPbW * nPbH` long. +pub fn default_weighted_pred( + pred_l0: &[i32], + pred_l1: &[i32], + pred_flag_l0: bool, + pred_flag_l1: bool, + n_pb_w: usize, + n_pb_h: usize, + bit_depth: u8, +) -> Result, InterPredError> { + if n_pb_w == 0 || n_pb_h == 0 { + return Err(InterPredError::EmptyBlock); + } + if !(8..=16).contains(&bit_depth) { + return Err(InterPredError::InvalidBitDepth(bit_depth)); + } + let count = n_pb_w * n_pb_h; + if pred_flag_l0 && pred_l0.len() != count { + return Err(InterPredError::ArrayLengthMismatch { + expected: count, + got: pred_l0.len(), + }); + } + if pred_flag_l1 && pred_l1.len() != count { + return Err(InterPredError::ArrayLengthMismatch { + expected: count, + got: pred_l1.len(), + }); + } + + let shift1 = core::cmp::max(2, 14 - bit_depth as i32); + let shift2 = core::cmp::max(3, 15 - bit_depth as i32); + let offset1 = 1i32 << (shift1 - 1); + let offset2 = 1i32 << (shift2 - 1); + let max_val = (1i32 << bit_depth) - 1; + + let mut out = vec![0i32; count]; + match (pred_flag_l0, pred_flag_l1) { + // Uni-predictive from L0 (equation 8-262). + (true, false) => { + for (o, &p0) in out.iter_mut().zip(pred_l0) { + *o = ((p0 + offset1) >> shift1).clamp(0, max_val); + } + } + // Uni-predictive from L1 (equation 8-263). + (false, true) => { + for (o, &p1) in out.iter_mut().zip(pred_l1) { + *o = ((p1 + offset1) >> shift1).clamp(0, max_val); + } + } + // Bi-predictive (equation 8-264). + (true, true) => { + for ((o, &p0), &p1) in out.iter_mut().zip(pred_l0).zip(pred_l1) { + *o = ((p0 + p1 + offset2) >> shift2).clamp(0, max_val); + } + } + (false, false) => return Err(InterPredError::EmptyPlane), + } + Ok(out) +} + +// --------------------------------------------------------------------------- +// §8.5.3.3.4.3 — explicit weighted sample prediction +// --------------------------------------------------------------------------- + +/// §8.5.3.3.4.3 — combine the L0 / L1 intermediate prediction arrays with +/// per-reference explicit weights and offsets (the `weightedPredFlag == 1` +/// path, equations 8-265..8-277). +/// +/// `log2_weight_denom` is the component's raw denominator +/// (`luma_log2_weight_denom` for luma, `ChromaLog2WeightDenom` for +/// chroma); the process adds `shift1 = Max(2, 14 − bitDepth)` internally +/// (equations 8-265 / 8-270). `w0` / `w1` are `LumaWeightLX[refIdxLX]` or +/// `ChromaWeightLX[refIdxLX][cIdx−1]`; `o0` / `o1` are the offsets +/// **already scaled** by `WpOffsetBdShiftY` / `WpOffsetBdShiftC` +/// (equations 8-268 / 8-269 / 8-273 / 8-274). An unused list's weight / +/// offset values are ignored. +/// +/// # Errors +/// Same contract as [`default_weighted_pred`]. +#[allow(clippy::too_many_arguments)] +pub fn explicit_weighted_pred( + pred_l0: &[i32], + pred_l1: &[i32], + pred_flag_l0: bool, + pred_flag_l1: bool, + n_pb_w: usize, + n_pb_h: usize, + log2_weight_denom: u8, + w0: i32, + o0: i32, + w1: i32, + o1: i32, + bit_depth: u8, +) -> Result, InterPredError> { + if n_pb_w == 0 || n_pb_h == 0 { + return Err(InterPredError::EmptyBlock); + } + if !(8..=16).contains(&bit_depth) { + return Err(InterPredError::InvalidBitDepth(bit_depth)); + } + let count = n_pb_w * n_pb_h; + if pred_flag_l0 && pred_l0.len() != count { + return Err(InterPredError::ArrayLengthMismatch { + expected: count, + got: pred_l0.len(), + }); + } + if pred_flag_l1 && pred_l1.len() != count { + return Err(InterPredError::ArrayLengthMismatch { + expected: count, + got: pred_l1.len(), + }); + } + + // Equations 8-265 / 8-270: log2Wd = log2WeightDenom + shift1. + let shift1 = core::cmp::max(2, 14 - i64::from(bit_depth)); + let log2_wd = i64::from(log2_weight_denom) + shift1; + let max_val = (1i64 << bit_depth) - 1; + let (w0, o0, w1, o1) = (i64::from(w0), i64::from(o0), i64::from(w1), i64::from(o1)); + + let mut out = vec![0i32; count]; + match (pred_flag_l0, pred_flag_l1) { + // Uni-predictive from L0 (equation 8-275). + (true, false) => { + let round = 1i64 << (log2_wd - 1); + for (o, &p0) in out.iter_mut().zip(pred_l0) { + *o = ((((i64::from(p0) * w0 + round) >> log2_wd) + o0).clamp(0, max_val)) as i32; + } + } + // Uni-predictive from L1 (equation 8-276). + (false, true) => { + let round = 1i64 << (log2_wd - 1); + for (o, &p1) in out.iter_mut().zip(pred_l1) { + *o = ((((i64::from(p1) * w1 + round) >> log2_wd) + o1).clamp(0, max_val)) as i32; + } + } + // Bi-predictive (equation 8-277). + (true, true) => { + let round = (o0 + o1 + 1) << log2_wd; + for ((o, &p0), &p1) in out.iter_mut().zip(pred_l0).zip(pred_l1) { + *o = (((i64::from(p0) * w0 + i64::from(p1) * w1 + round) >> (log2_wd + 1)) + .clamp(0, max_val)) as i32; + } + } + (false, false) => return Err(InterPredError::EmptyPlane), + } + Ok(out) +} + +/// One reference list's §8.5.3.3.4.3 weights / offsets for one PU, +/// resolved for its `refIdxLX`: `w` is `LumaWeightLX[refIdx]` / +/// `ChromaWeightLX[refIdx][j]`; `o` is the corresponding offset already +/// scaled by `WpOffsetBdShiftY` / `WpOffsetBdShiftC` (equations +/// 8-268 / 8-269 / 8-273 / 8-274). +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct WpListWeights { + /// `LumaWeightLX[refIdxLX]` (equations 8-266 / 8-267). + pub w_luma: i32, + /// `luma_offset_lX[refIdxLX] << WpOffsetBdShiftY`. + pub o_luma: i32, + /// `ChromaWeightLX[refIdxLX][0]` (Cb). + pub w_cb: i32, + /// `ChromaOffsetLX[refIdxLX][0] << WpOffsetBdShiftC` (Cb). + pub o_cb: i32, + /// `ChromaWeightLX[refIdxLX][1]` (Cr). + pub w_cr: i32, + /// `ChromaOffsetLX[refIdxLX][1] << WpOffsetBdShiftC` (Cr). + pub o_cr: i32, +} + +/// The complete §8.5.3.3.4.3 inputs for one PU's weighted combine: the +/// two log2 denominators plus each list's per-component weights, already +/// resolved for the PU's reference indices. +#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] +pub struct PuWeights { + /// `luma_log2_weight_denom` (§7.4.7.3). + pub luma_log2_weight_denom: u8, + /// `ChromaLog2WeightDenom` (§7.4.7.3). + pub chroma_log2_weight_denom: u8, + /// L0 weights (ignored when `predFlagL0 == 0`). + pub l0: WpListWeights, + /// L1 weights (ignored when `predFlagL1 == 0`). + pub l1: WpListWeights, +} + +// --------------------------------------------------------------------------- +// §8.5.3.3.1 — inter prediction sample block-walk driver +// --------------------------------------------------------------------------- + +/// A `[mvLX[0], mvLX[1]]` motion vector in quarter-luma-sample units +/// (the §8.5.3 luma MV) — the integer / fractional split of equations +/// 8-214..8-217 is performed by the driver. +pub type MotionVector = [i32; 2]; + +/// One reference list's prediction inputs for a prediction unit: the +/// reference picture planes selected by §8.5.3.3.2 plus the luma motion +/// vector mvLX (quarter-pel) and chroma motion vector mvCLX (eighth-pel, +/// already derived per §8.5.3.2.10). `pred_flag == false` means the list +/// is not used and the planes / vectors are ignored. +#[derive(Debug, Clone, Copy)] +pub struct ListPrediction<'a> { + /// `predFlagLX` — whether reference list X contributes to this PU. + pub pred_flag: bool, + /// `refPicLXL` — the §8.5.3.3.2 luma reference plane. + pub luma: RefPlane<'a>, + /// `refPicLXCb` — the §8.5.3.3.2 Cb reference plane (ignored when + /// `chroma_array_type == 0`). + pub cb: Option>, + /// `refPicLXCr` — the §8.5.3.3.2 Cr reference plane. + pub cr: Option>, + /// `mvLX` in quarter-luma-sample units (equations 8-214..8-217). + pub mv_l: MotionVector, + /// `mvCLX` in eighth-chroma-sample units (equations 8-218..8-221, + /// derived from `mvLX` by §8.5.3.2.10). + pub mv_c: MotionVector, +} + +/// The reconstructed prediction-sample planes for one inter prediction +/// block, produced by [`predict_inter_pu`]. Each plane is row-major and +/// holds the final clipped `[0, (1 << bitDepth) − 1]` prediction samples. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct InterPrediction { + /// `predSamplesL` — `nPbW * nPbH` luma prediction samples. + pub luma: Vec, + /// `predSamplesCb` — `(nPbW / SubWidthC) * (nPbH / SubHeightC)` Cb + /// prediction samples, empty when `chroma_array_type == 0`. + pub cb: Vec, + /// `predSamplesCr` — Cr prediction samples, empty when monochrome. + pub cr: Vec, +} + +/// §8.5.3.3.1 — geometry / format inputs constant for one PU prediction. +#[derive(Debug, Clone, Copy)] +pub struct InterPredGeometry { + /// `xPb = xCb + xBl` (equation 8-212) — the PU's luma top-left x. + pub x_pb: i32, + /// `yPb = yCb + yBl` (equation 8-213) — the PU's luma top-left y. + pub y_pb: i32, + /// `nPbW` — luma prediction-block width. + pub n_pb_w: usize, + /// `nPbH` — luma prediction-block height. + pub n_pb_h: usize, + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, 3 = 4:4:4). + pub chroma_array_type: u8, + /// `BitDepthY`. + pub bit_depth_luma: u8, + /// `BitDepthC`. + pub bit_depth_chroma: u8, +} + +/// `(SubWidthC, SubHeightC)` from Table 6-1 (mirrors +/// [`crate::picture::sub_wh_c`] without the cross-module dependency). +#[inline] +fn sub_wh_c_local(chroma_array_type: u8) -> (i32, i32) { + match chroma_array_type { + 1 => (2, 2), + 2 => (2, 1), + 3 => (1, 1), + _ => (2, 2), + } +} + +/// Fill one list's intermediate luma prediction array for a PU +/// (§8.5.3.3.3.1 equations 8-214..8-217 + the §8.5.3.3.3.2 per-sample +/// interpolation). `xPb`/`yPb` are added inside the integer split. +fn list_luma_pred( + list: &ListPrediction<'_>, + geom: &InterPredGeometry, +) -> Result, InterPredError> { + // §8.5.3.3.3.1: xIntL = xPb + (mvLX[0] >> 2), xFracL = mvLX[0] & 3. + let x_int = geom.x_pb + (list.mv_l[0] >> 2); + let y_int = geom.y_pb + (list.mv_l[1] >> 2); + let x_frac = list.mv_l[0] & 3; + let y_frac = list.mv_l[1] & 3; + interp_luma_block( + &list.luma, + x_int, + y_int, + x_frac, + y_frac, + geom.n_pb_w, + geom.n_pb_h, + geom.bit_depth_luma, + ) +} + +/// Fill one list's intermediate chroma prediction array for a PU +/// (§8.5.3.3.3.1 equations 8-218..8-221 + §8.5.3.3.3.3 interpolation). +fn list_chroma_pred( + plane: &RefPlane<'_>, + list: &ListPrediction<'_>, + geom: &InterPredGeometry, + sub_w: i32, + sub_h: i32, +) -> Result, InterPredError> { + // §8.5.3.3.3.1: xIntC = (xPb / SubWidthC) + (mvCLX[0] >> 3), + // xFracC = mvCLX[0] & 7. + let x_int = geom.x_pb / sub_w + (list.mv_c[0] >> 3); + let y_int = geom.y_pb / sub_h + (list.mv_c[1] >> 3); + let x_frac = list.mv_c[0] & 7; + let y_frac = list.mv_c[1] & 7; + interp_chroma_block( + plane, + x_int, + y_int, + x_frac, + y_frac, + geom.n_pb_w / sub_w as usize, + geom.n_pb_h / sub_h as usize, + geom.bit_depth_chroma, + ) +} + +/// §8.5.3.3.1 — drive the inter-prediction sample process for one +/// prediction block: split each used list's motion vector into its +/// integer / fractional parts, run the §8.5.3.3.3 fractional-sample +/// interpolation over the whole block for luma and (when chroma is +/// present) Cb / Cr, then combine the L0 / L1 intermediate arrays with +/// the §8.5.3.3.4.2 default weighted sample prediction. +/// +/// This is the `weightedPredFlag == 0` path of §8.5.3.3.4.1; see +/// [`predict_inter_pu_weighted`] for the full dispatch including the +/// §8.5.3.3.4.3 explicit-weighting path. +/// +/// # Errors +/// +/// [`InterPredError::EmptyBlock`] for a zero PU dimension, +/// [`InterPredError::EmptyPlane`] when neither list is used, and the +/// interpolation / combine errors propagated from the primitives. +pub fn predict_inter_pu( + l0: &ListPrediction<'_>, + l1: &ListPrediction<'_>, + geom: &InterPredGeometry, +) -> Result { + predict_inter_pu_weighted(l0, l1, geom, None) +} + +/// §8.5.3.3.1 + §8.5.3.3.4.1 — as [`predict_inter_pu`], with the +/// weighted-sample-prediction dispatch: `weights == None` is the +/// `weightedPredFlag == 0` default combine (§8.5.3.3.4.2); +/// `weights == Some(..)` is the explicit per-reference combine +/// (§8.5.3.3.4.3), with the PU's `refIdxLX`-resolved weights carried in +/// the [`PuWeights`]. +/// +/// # Errors +/// Same contract as [`predict_inter_pu`]. +pub fn predict_inter_pu_weighted( + l0: &ListPrediction<'_>, + l1: &ListPrediction<'_>, + geom: &InterPredGeometry, + weights: Option<&PuWeights>, +) -> Result { + if geom.n_pb_w == 0 || geom.n_pb_h == 0 { + return Err(InterPredError::EmptyBlock); + } + if !l0.pred_flag && !l1.pred_flag { + return Err(InterPredError::EmptyPlane); + } + + // Luma: interpolate each used list, then combine per §8.5.3.3.4.1. + let pred_l0_luma = if l0.pred_flag { + list_luma_pred(l0, geom)? + } else { + Vec::new() + }; + let pred_l1_luma = if l1.pred_flag { + list_luma_pred(l1, geom)? + } else { + Vec::new() + }; + let luma = match weights { + None => default_weighted_pred( + &pred_l0_luma, + &pred_l1_luma, + l0.pred_flag, + l1.pred_flag, + geom.n_pb_w, + geom.n_pb_h, + geom.bit_depth_luma, + )?, + Some(wp) => explicit_weighted_pred( + &pred_l0_luma, + &pred_l1_luma, + l0.pred_flag, + l1.pred_flag, + geom.n_pb_w, + geom.n_pb_h, + wp.luma_log2_weight_denom, + wp.l0.w_luma, + wp.l0.o_luma, + wp.l1.w_luma, + wp.l1.o_luma, + geom.bit_depth_luma, + )?, + }; + + let (mut cb, mut cr) = (Vec::new(), Vec::new()); + if geom.chroma_array_type != 0 { + let (sub_w, sub_h) = sub_wh_c_local(geom.chroma_array_type); + let wp_cb = weights.map(|wp| { + ( + wp.chroma_log2_weight_denom, + wp.l0.w_cb, + wp.l0.o_cb, + wp.l1.w_cb, + wp.l1.o_cb, + ) + }); + let wp_cr = weights.map(|wp| { + ( + wp.chroma_log2_weight_denom, + wp.l0.w_cr, + wp.l0.o_cr, + wp.l1.w_cr, + wp.l1.o_cr, + ) + }); + cb = combine_chroma(l0, l1, geom, sub_w, sub_h, wp_cb, |lp| lp.cb)?; + cr = combine_chroma(l0, l1, geom, sub_w, sub_h, wp_cr, |lp| lp.cr)?; + } + + Ok(InterPrediction { luma, cb, cr }) +} + +/// Interpolate and §8.5.3.3.4-combine one chroma component for a PU. +/// `select` picks the Cb or Cr reference plane from a [`ListPrediction`]; +/// `wp` is `Some((ChromaLog2WeightDenom, w0, o0, w1, o1))` for the +/// §8.5.3.3.4.3 explicit path, `None` for the §8.5.3.3.4.2 default. +fn combine_chroma<'a>( + l0: &ListPrediction<'a>, + l1: &ListPrediction<'a>, + geom: &InterPredGeometry, + sub_w: i32, + sub_h: i32, + wp: Option<(u8, i32, i32, i32, i32)>, + select: impl Fn(&ListPrediction<'a>) -> Option>, +) -> Result, InterPredError> { + let cw = geom.n_pb_w / sub_w as usize; + let ch = geom.n_pb_h / sub_h as usize; + let p0 = if l0.pred_flag { + let plane = select(l0).ok_or(InterPredError::EmptyPlane)?; + list_chroma_pred(&plane, l0, geom, sub_w, sub_h)? + } else { + Vec::new() + }; + let p1 = if l1.pred_flag { + let plane = select(l1).ok_or(InterPredError::EmptyPlane)?; + list_chroma_pred(&plane, l1, geom, sub_w, sub_h)? + } else { + Vec::new() + }; + match wp { + None => default_weighted_pred( + &p0, + &p1, + l0.pred_flag, + l1.pred_flag, + cw, + ch, + geom.bit_depth_chroma, + ), + Some((denom, w0, o0, w1, o1)) => explicit_weighted_pred( + &p0, + &p1, + l0.pred_flag, + l1.pred_flag, + cw, + ch, + denom, + w0, + o0, + w1, + o1, + geom.bit_depth_chroma, + ), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A flat plane interpolates to the constant sample value scaled to + /// the internal precision: every tap kernel sums to 64, so + /// `64 * v >> shift1` at 8-bit (`shift1 == 0`) is `64 * v`, matching + /// the `v << shift3` (`shift3 == 6`) full-pel value. + #[test] + fn luma_flat_plane_constant() { + let plane_samples = vec![100i32; 16 * 16]; + let plane = RefPlane::new(&plane_samples, 16, 16).unwrap(); + for xf in 0..=3 { + for yf in 0..=3 { + let blk = interp_luma_block(&plane, 5, 5, xf, yf, 4, 4, 8).unwrap(); + for &s in &blk { + assert_eq!(s, 100 << 6, "xf={xf} yf={yf}"); + } + } + } + } + + /// Full-pel luma is `A << shift3`; at 8-bit `shift3 == 6`. + #[test] + fn luma_full_pel_shift3() { + let mut s = vec![0i32; 8 * 8]; + for (i, v) in s.iter_mut().enumerate() { + *v = i as i32; + } + let plane = RefPlane::new(&s, 8, 8).unwrap(); + let blk = interp_luma_block(&plane, 2, 3, 0, 0, 2, 2, 8).unwrap(); + // predSamples[0][0] = A(2,3) << 6 = (3*8 + 2) << 6 = 26 << 6. + assert_eq!(blk[0], (3 * 8 + 2) << 6); + // predSamples[1][1] = A(3,4) << 6 = (4*8 + 3) << 6 = 35 << 6. + assert_eq!(blk[3], (4 * 8 + 3) << 6); + } + + /// The luma `a` kernel (xFracL == 1) on a known column reproduces + /// equation 8-224 hand-computed. + #[test] + fn luma_a_kernel_hand_value() { + // A row of samples; pick a center so the 8 taps land inside. + // Coords x = −3..4 around x_int = 5 -> indices 2..9. + let mut s = vec![0i32; 16]; + let vals = [ + 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150, 160, + ]; + s.copy_from_slice(&vals); + let plane = RefPlane::new(&s, 16, 1).unwrap(); + let blk = interp_luma_block(&plane, 5, 0, 1, 0, 1, 1, 8).unwrap(); + // a = −A−3 + 4A−2 − 10A−1 + 58A0 + 17A1 − 5A2 + A3, >> shift1(=0). + // A−3..A3 = x=2..8 = 30,40,50,60,70,80,90. + let expected = -30 + 4 * 40 - 10 * 50 + 58 * 60 + 17 * 70 - 5 * 80 + 90; + assert_eq!(blk[0], expected); + } + + /// Chroma flat plane interpolates to the constant value (each 4-tap + /// kernel sums to 64) for all 8x8 eighth-pel phases. + #[test] + fn chroma_flat_plane_constant() { + let plane_samples = vec![77i32; 12 * 12]; + let plane = RefPlane::new(&plane_samples, 12, 12).unwrap(); + for xf in 0..=7 { + for yf in 0..=7 { + let blk = interp_chroma_block(&plane, 4, 4, xf, yf, 3, 3, 8).unwrap(); + for &s in &blk { + assert_eq!(s, 77 << 6, "xf={xf} yf={yf}"); + } + } + } + } + + /// Chroma `ab` kernel (xFracC == 1) reproduces equation 8-241. + #[test] + fn chroma_ab_kernel_hand_value() { + let s = vec![10, 20, 30, 40, 50, 60, 70, 80]; + let plane = RefPlane::new(&s, 8, 1).unwrap(); + // x_int = 3, taps x = −1..2 -> x=2,3,4,5 = 30,40,50,60. + let blk = interp_chroma_block(&plane, 3, 0, 1, 0, 1, 1, 8).unwrap(); + // ab = −2B−1 + 58B0 + 10B1 − 2B2, >> shift1(=0). + let expected = -2 * 30 + 58 * 40 + 10 * 50 - 2 * 60; + assert_eq!(blk[0], expected); + } + + /// Edge extension clamps negative / past-edge coordinates. + #[test] + fn ref_plane_edge_extension() { + let s = vec![1, 2, 3, 4, 5, 6]; // 3x2 + let plane = RefPlane::new(&s, 3, 2).unwrap(); + assert_eq!(plane.at(-5, -5), 1); // top-left corner + assert_eq!(plane.at(99, 99), 6); // bottom-right corner + assert_eq!(plane.at(1, -1), 2); // clamp y to row 0 + assert_eq!(plane.at(99, 1), 6); // clamp x to col 2, row 1 + } + + /// Uni-predictive L0 default weight: (p + offset1) >> shift1, clipped. + #[test] + fn weighted_uni_l0() { + // 8-bit: shift1 = Max(2, 6) = 6, offset1 = 32. + let p0 = vec![100 << 6, 0, 200 << 6, 255 << 6]; + let out = default_weighted_pred(&p0, &[], true, false, 2, 2, 8).unwrap(); + assert_eq!(out[0], ((100 << 6) + 32) >> 6); // = 100 + assert_eq!(out[1], 32 >> 6); // = 0 + assert_eq!(out[2], ((200 << 6) + 32) >> 6); // = 200 + assert_eq!(out[3], ((255 << 6) + 32) >> 6); // = 255 + } + + /// Bi-predictive default weight: (p0 + p1 + offset2) >> shift2. + #[test] + fn weighted_bi() { + // 8-bit: shift2 = Max(3, 7) = 7, offset2 = 64. + let p0 = vec![100 << 6]; + let p1 = vec![140 << 6]; + let out = default_weighted_pred(&p0, &p1, true, true, 1, 1, 8).unwrap(); + // ((100<<6) + (140<<6) + 64) >> 7 = (6400 + 8960 + 64) >> 7 = 15424>>7 = 120. + assert_eq!(out[0], ((100 << 6) + (140 << 6) + 64) >> 7); + assert_eq!(out[0], 120); + } + + /// Default weight clips to the sample range. + #[test] + fn weighted_clips() { + let p0 = vec![-50 << 6, 1000 << 6]; + let out = default_weighted_pred(&p0, &[], true, false, 2, 1, 8).unwrap(); + assert_eq!(out[0], 0); + assert_eq!(out[1], 255); + } + + /// Explicit uni-predictive L0 weight (equation 8-275): 8-bit, + /// denom 3 → log2Wd = 9, w0 = 7, o0 = 2: + /// `((100·64·7 + 256) >> 9) + 2 = 88 + 2`. + #[test] + fn explicit_weighted_uni_l0() { + let p0 = vec![100 << 6]; + let out = explicit_weighted_pred(&p0, &[], true, false, 1, 1, 3, 7, 2, 0, 0, 8).unwrap(); + assert_eq!(out[0], 90); + } + + /// Explicit uni-predictive L1 weight (equation 8-276) mirrors L0. + #[test] + fn explicit_weighted_uni_l1() { + let p1 = vec![100 << 6]; + let out = explicit_weighted_pred(&[], &p1, false, true, 1, 1, 3, 0, 0, 7, 2, 8).unwrap(); + assert_eq!(out[0], 90); + } + + /// Explicit bi-predictive combine (equation 8-277): denom 0 → + /// log2Wd = 6, w0 = 1, w1 = 3, zero offsets: + /// `(50·64 + 100·64·3 + 64) >> 7 = 175`. + #[test] + fn explicit_weighted_bi() { + let p0 = vec![50 << 6]; + let p1 = vec![100 << 6]; + let out = explicit_weighted_pred(&p0, &p1, true, true, 1, 1, 0, 1, 0, 3, 0, 8).unwrap(); + assert_eq!(out[0], 175); + // Bi offsets enter as ((o0 + o1 + 1) << log2Wd) >> (log2Wd + 1) + // ≈ (o0 + o1 + 1) / 2 added to the weighted mean. + let out = explicit_weighted_pred(&p0, &p1, true, true, 1, 1, 0, 1, 10, 3, 9, 8).unwrap(); + assert_eq!(out[0], 175 + 10); + } + + /// The explicit combine clips to the sample range on both sides. + #[test] + fn explicit_weighted_clips() { + let p0 = vec![100 << 6, 200 << 6]; + // Large negative offset floors at 0; weight 127 saturates at 255. + let out = explicit_weighted_pred(&p0, &[], true, false, 2, 1, 0, 1, -128, 0, 0, 8).unwrap(); + assert_eq!(out[0], 0); + let out = explicit_weighted_pred(&p0, &[], true, false, 2, 1, 0, 127, 0, 0, 0, 8).unwrap(); + assert_eq!(out[1], 255); + } + + /// With weight `1 << denom` and zero offset, the explicit combine + /// degenerates to the default uni combine (§7.4.7.3 inferred values). + #[test] + fn explicit_default_weights_match_default_combine() { + let p0: Vec = (0..16).map(|v| v << 6).collect(); + for denom in 0..=7u8 { + let explicit = + explicit_weighted_pred(&p0, &[], true, false, 4, 4, denom, 1 << denom, 0, 0, 0, 8) + .unwrap(); + let default = default_weighted_pred(&p0, &[], true, false, 4, 4, 8).unwrap(); + assert_eq!(explicit, default, "denom={denom}"); + } + } + + /// Explicit-combine argument validation matches the default combine. + #[test] + fn explicit_weighted_errors() { + assert_eq!( + explicit_weighted_pred(&[], &[], false, false, 1, 1, 0, 1, 0, 1, 0, 8), + Err(InterPredError::EmptyPlane) + ); + assert_eq!( + explicit_weighted_pred(&[1, 2], &[], true, false, 1, 1, 0, 1, 0, 1, 0, 8), + Err(InterPredError::ArrayLengthMismatch { + expected: 1, + got: 2 + }) + ); + assert_eq!( + explicit_weighted_pred(&[1], &[], true, false, 0, 1, 0, 1, 0, 1, 0, 8), + Err(InterPredError::EmptyBlock) + ); + assert_eq!( + explicit_weighted_pred(&[1], &[], true, false, 1, 1, 0, 1, 0, 1, 0, 7), + Err(InterPredError::InvalidBitDepth(7)) + ); + } + + /// 10-bit full-pel luma uses shift3 = Max(2, 4) = 4. + #[test] + fn luma_full_pel_10bit() { + let s = vec![500i32; 8 * 8]; + let plane = RefPlane::new(&s, 8, 8).unwrap(); + let blk = interp_luma_block(&plane, 2, 2, 0, 0, 1, 1, 10).unwrap(); + assert_eq!(blk[0], 500 << 4); + } + + /// Error surface: zero block, bad fraction, bad bit depth, bad plane. + #[test] + fn errors() { + let s = vec![0i32; 4]; + let plane = RefPlane::new(&s, 2, 2).unwrap(); + assert_eq!( + interp_luma_block(&plane, 0, 0, 0, 0, 0, 1, 8), + Err(InterPredError::EmptyBlock) + ); + assert_eq!( + interp_luma_block(&plane, 0, 0, 4, 0, 1, 1, 8), + Err(InterPredError::InvalidFraction(4)) + ); + assert_eq!( + interp_chroma_block(&plane, 0, 0, 8, 0, 1, 1, 8), + Err(InterPredError::InvalidFraction(8)) + ); + assert_eq!( + interp_luma_block(&plane, 0, 0, 0, 0, 1, 1, 7), + Err(InterPredError::InvalidBitDepth(7)) + ); + assert!(matches!( + RefPlane::new(&[0, 1, 2], 2, 2), + Err(InterPredError::PlaneLengthMismatch { .. }) + )); + assert_eq!(RefPlane::new(&[], 0, 2), Err(InterPredError::EmptyPlane)); + assert_eq!( + default_weighted_pred(&[], &[], false, false, 1, 1, 8), + Err(InterPredError::EmptyPlane) + ); + assert!(matches!( + default_weighted_pred(&[1, 2], &[], true, false, 1, 1, 8), + Err(InterPredError::ArrayLengthMismatch { .. }) + )); + } + + /// End-to-end: interpolate two reference blocks and bi-combine. + #[test] + fn pipeline_luma_bi() { + let a = vec![80i32; 16 * 16]; + let b = vec![120i32; 16 * 16]; + let pa = RefPlane::new(&a, 16, 16).unwrap(); + let pb = RefPlane::new(&b, 16, 16).unwrap(); + let l0 = interp_luma_block(&pa, 4, 4, 2, 2, 4, 4, 8).unwrap(); + let l1 = interp_luma_block(&pb, 4, 4, 1, 3, 4, 4, 8).unwrap(); + let out = default_weighted_pred(&l0, &l1, true, true, 4, 4, 8).unwrap(); + // Flat planes: l0 == 80<<6 everywhere, l1 == 120<<6; bi-combine + // = ((80+120)<<6 + 64) >> 7 = (12800 + 64) >> 7 = 100. + for &s in &out { + assert_eq!(s, 100); + } + } + + // -- §8.5.3.3.1 driver tests ------------------------------------------- + + /// A full-pel uni-L0 PU on a flat luma plane reproduces the reference + /// sample value (full-pel: `A << shift3`, then default-weight + /// `(p + offset1) >> shift1` recovers `A`). + #[test] + fn driver_uni_l0_full_pel_flat() { + let luma = vec![130i32; 32 * 32]; + let cb = vec![70i32; 16 * 16]; + let cr = vec![200i32; 16 * 16]; + let lp = RefPlane::new(&luma, 32, 32).unwrap(); + let cbp = RefPlane::new(&cb, 16, 16).unwrap(); + let crp = RefPlane::new(&cr, 16, 16).unwrap(); + let l0 = ListPrediction { + pred_flag: true, + luma: lp, + cb: Some(cbp), + cr: Some(crp), + mv_l: [0, 0], + mv_c: [0, 0], + }; + // Unused L1: a dummy (1x1) plane that is never read. + let dummy = vec![0i32; 1]; + let dp = RefPlane::new(&dummy, 1, 1).unwrap(); + let l1 = ListPrediction { + pred_flag: false, + luma: dp, + cb: None, + cr: None, + mv_l: [0, 0], + mv_c: [0, 0], + }; + let geom = InterPredGeometry { + x_pb: 4, + y_pb: 4, + n_pb_w: 8, + n_pb_h: 8, + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + }; + let pred = predict_inter_pu(&l0, &l1, &geom).unwrap(); + assert_eq!(pred.luma.len(), 64); + assert_eq!(pred.cb.len(), 16); + assert_eq!(pred.cr.len(), 16); + assert!(pred.luma.iter().all(|&v| v == 130)); + assert!(pred.cb.iter().all(|&v| v == 70)); + assert!(pred.cr.iter().all(|&v| v == 200)); + } + + /// A full-pel motion vector shifts the reference window: a ramp plane + /// predicted with `mvL = [4, 0]` (one full luma sample right) reads + /// the column one to the right of `xPb`. + #[test] + fn driver_full_pel_mv_shifts_window() { + // 16-wide luma ramp where sample(x,y) == x. + let mut luma = vec![0i32; 16 * 16]; + for y in 0..16 { + for x in 0..16 { + luma[y * 16 + x] = x as i32; + } + } + let lp = RefPlane::new(&luma, 16, 16).unwrap(); + let dummy = vec![0i32; 1]; + let dp = RefPlane::new(&dummy, 1, 1).unwrap(); + let l0 = ListPrediction { + pred_flag: true, + luma: lp, + cb: None, + cr: None, + mv_l: [4, 0], // +1 full luma sample horizontally. + mv_c: [0, 0], + }; + let l1 = ListPrediction { + pred_flag: false, + luma: dp, + cb: None, + cr: None, + mv_l: [0, 0], + mv_c: [0, 0], + }; + let geom = InterPredGeometry { + x_pb: 2, + y_pb: 2, + n_pb_w: 4, + n_pb_h: 4, + chroma_array_type: 0, + bit_depth_luma: 8, + bit_depth_chroma: 8, + }; + let pred = predict_inter_pu(&l0, &l1, &geom).unwrap(); + // predSamples[xL] reads ref column xPb + 1 + xL = 3 + xL. + for yl in 0..4 { + for xl in 0..4 { + assert_eq!(pred.luma[yl * 4 + xl], 3 + xl as i32, "xl={xl}"); + } + } + assert!(pred.cb.is_empty(), "monochrome PU has no chroma"); + } + + /// Bi-prediction on two flat planes averages the two reference values. + #[test] + fn driver_bi_averages() { + let a = vec![60i32; 16 * 16]; + let b = vec![100i32; 16 * 16]; + let pa = RefPlane::new(&a, 16, 16).unwrap(); + let pb = RefPlane::new(&b, 16, 16).unwrap(); + let l0 = ListPrediction { + pred_flag: true, + luma: pa, + cb: None, + cr: None, + mv_l: [0, 0], + mv_c: [0, 0], + }; + let l1 = ListPrediction { + pred_flag: true, + luma: pb, + cb: None, + cr: None, + mv_l: [2, 1], // quarter-pel; flat plane is unaffected. + mv_c: [0, 0], + }; + let geom = InterPredGeometry { + x_pb: 4, + y_pb: 4, + n_pb_w: 4, + n_pb_h: 4, + chroma_array_type: 0, + bit_depth_luma: 8, + bit_depth_chroma: 8, + }; + let pred = predict_inter_pu(&l0, &l1, &geom).unwrap(); + // ((60 + 100) >> 1) == 80. + assert!(pred.luma.iter().all(|&v| v == 80)); + } + + /// The driver rejects a PU with no list selected and a zero block. + #[test] + fn driver_errors() { + let dummy = vec![0i32; 1]; + let dp = RefPlane::new(&dummy, 1, 1).unwrap(); + let none = ListPrediction { + pred_flag: false, + luma: dp, + cb: None, + cr: None, + mv_l: [0, 0], + mv_c: [0, 0], + }; + let geom = InterPredGeometry { + x_pb: 0, + y_pb: 0, + n_pb_w: 4, + n_pb_h: 4, + chroma_array_type: 0, + bit_depth_luma: 8, + bit_depth_chroma: 8, + }; + assert_eq!( + predict_inter_pu(&none, &none, &geom), + Err(InterPredError::EmptyPlane) + ); + let l0 = ListPrediction { + pred_flag: true, + ..none + }; + let zero = InterPredGeometry { n_pb_w: 0, ..geom }; + assert_eq!( + predict_inter_pu(&l0, &none, &zero), + Err(InterPredError::EmptyBlock) + ); + } +} diff --git a/vendor/oxideav-h265/src/inter_recon.rs b/vendor/oxideav-h265/src/inter_recon.rs new file mode 100644 index 0000000..4ea13b0 --- /dev/null +++ b/vendor/oxideav-h265/src/inter_recon.rs @@ -0,0 +1,1933 @@ +//! §8.5 picture-level inter reconstruction driver. +//! +//! This module is the rung between the §7.3.8 slice-data parse tree (the +//! decoded [`crate::slice_data::CodingTreeUnit`] structures, with their +//! inter coding units carrying §7.3.8.6 prediction units) and the per-PU +//! §8.5.3.3 motion-compensated prediction + §8.6.2 residual reconstruction +//! already implemented in [`crate::inter_pred`] and [`crate::recon`]. It +//! walks a picture's decoded CTUs in tile-scan (decode) order and, for each +//! inter coding unit: +//! +//! 1. §8.5.3.2.1 — resolve every prediction unit's motion vectors, +//! reference indices and `predFlagLX` from the parsed syntax, gathering +//! the spatial merge / MVP neighbours from the *current* picture's +//! motion field (built up by the earlier CUs) and the temporal `Col` +//! candidate from the collocated picture's motion field +//! ([`crate::pu_mv::resolve_cu_motion`]). +//! 2. §8.5.3.3 — for each PU, build the §8.5.3.3.2 reference planes from the +//! resolved `RefPicListX[ refIdxLX ]` pictures, interpolate + combine, +//! add the §8.6.2 residual sliced from the CU residual planes +//! ([`crate::recon::extract_cu_residual`]) and clip into the target +//! picture ([`crate::recon::reconstruct_inter_pu`]). +//! +//! Intra coding units inside a P / B slice are reconstructed by the §8.4 +//! intra path; the motion field records them as intra so a later inter CU's +//! §6.4.2 prediction-block availability denies them as motion neighbours. + +use crate::dpb::{DpbEntry, RefPicLists}; +use crate::inter_pred::{PuWeights, WpListWeights}; +use crate::motion::{derive_chroma_mv, MotionField}; +use crate::picture::{sub_wh_c, Picture}; +use crate::pu_mv::{resolve_cu_motion, InterCuDesc, PuMotion, PuMvContext, PuRect}; +use crate::recon::{ + extract_cu_residual, reconstruct_inter_pu_weighted, CuResidual, ReconError, ReconParams, + ResolvedList, +}; +use crate::slice_data::{CodingUnit, PredictionUnit}; + +/// The slice's §7.4.7.3-derived weighted-prediction tables, resolved +/// from the parsed `pred_weight_table()` into the per-reference values +/// the §8.5.3.3.4.3 combine reads: `LumaWeightLX[i]`, +/// `luma_offset_lX[i] << WpOffsetBdShiftY` (equations 8-268 / 8-269), +/// `ChromaWeightLX[i][j]` and `ChromaOffsetLX[i][j] << WpOffsetBdShiftC` +/// (equations 8-273 / 8-274). +/// +/// Present on an [`InterSliceContext`] exactly when `weightedPredFlag` +/// (§8.5.3.3.4.1: `weighted_pred_flag` for P slices, +/// `weighted_bipred_flag` for B slices) is 1 — `None` selects the +/// §8.5.3.3.4.2 default combine. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct SliceWpTables { + /// `luma_log2_weight_denom` (§7.4.7.3). + pub luma_log2_weight_denom: u8, + /// `ChromaLog2WeightDenom` (§7.4.7.3). + pub chroma_log2_weight_denom: u8, + /// Per-`refIdxL0` weights, length `num_ref_idx_l0_active`. + pub l0: Vec, + /// Per-`refIdxL1` weights, length `num_ref_idx_l1_active` (empty + /// for P slices). + pub l1: Vec, +} + +impl SliceWpTables { + /// Resolve one PU's [`PuWeights`] from its reference indices. An + /// unused list (or an index past the table, which a conforming + /// stream never produces) falls back to the §7.4.7.3 inferred + /// values `w = 1 << denom, o = 0` — the identity weighting. + #[must_use] + pub fn resolve_pu(&self, motion: &PuMotion) -> PuWeights { + let identity = |denom: u8| WpListWeights { + w_luma: 1 << self.luma_log2_weight_denom, + o_luma: 0, + w_cb: 1 << denom, + o_cb: 0, + w_cr: 1 << denom, + o_cr: 0, + }; + let pick = |list: &[WpListWeights], used: bool, idx: i32| { + if used { + list.get(idx.max(0) as usize) + .copied() + .unwrap_or_else(|| identity(self.chroma_log2_weight_denom)) + } else { + identity(self.chroma_log2_weight_denom) + } + }; + PuWeights { + luma_log2_weight_denom: self.luma_log2_weight_denom, + chroma_log2_weight_denom: self.chroma_log2_weight_denom, + l0: pick(&self.l0, motion.pred_flag_l0, motion.ref_idx_l0), + l1: pick(&self.l1, motion.pred_flag_l1, motion.ref_idx_l1), + } + } +} + +/// The resolved reference-picture access an inter CU reconstruction needs: +/// `RefPicListX[ refIdx ]` → a borrowed reference [`Picture`] and its POC. +/// +/// The picture-level driver binds this to the §8.3.4 [`RefPicLists`] + the +/// [`crate::dpb::Dpb`] entries; the per-CU reconstruction reads it through +/// the [`PuMvContext`] resolvers (for the candidate derivation) and to +/// fetch each used list's reference planes (for the interpolation). +#[derive(Debug)] +pub struct RefListAccess<'a> { + /// `RefPicList0` / `RefPicList1` as DPB entry indices. + pub lists: &'a RefPicLists, + /// The DPB entries the indices point into. + pub entries: &'a [DpbEntry], +} + +impl<'a> RefListAccess<'a> { + /// Borrow `RefPicListX[ ref_idx ]`'s reconstructed picture, or `None` + /// when the list slot is "no reference picture" / out of range. + #[must_use] + pub fn ref_pic(&self, list: usize, ref_idx: i32) -> Option<&'a Picture> { + self.entry(list, ref_idx).map(|e| &e.picture) + } + + /// `PicOrderCnt( RefPicListX[ ref_idx ] )`, or `i32::MIN` when absent. + #[must_use] + pub fn ref_poc(&self, list: usize, ref_idx: i32) -> i32 { + self.entry(list, ref_idx).map_or(i32::MIN, |e| e.poc) + } + + /// Borrow `RefPicListX[ ref_idx ]`'s DPB entry, or `None` when the + /// list slot is "no reference picture", out of range, or the + /// current picture ([`crate::dpb::CURR_PIC`] — resolved by the + /// reconstruction driver, not the DPB). + #[must_use] + pub fn entry(&self, list: usize, ref_idx: i32) -> Option<&'a DpbEntry> { + let idx = self.slot(list, ref_idx)?; + if idx == crate::dpb::CURR_PIC { + return None; + } + self.entries.get(idx) + } + + /// `true` when `RefPicListX[ ref_idx ]` is the CURRENT picture (the + /// §8.3.4 currPic append — intra block copy). + #[must_use] + pub fn is_curr_pic(&self, list: usize, ref_idx: i32) -> bool { + self.slot(list, ref_idx) == Some(crate::dpb::CURR_PIC) + } + + /// The raw `RefPicListX[ ref_idx ]` slot value. + fn slot(&self, list: usize, ref_idx: i32) -> Option { + if ref_idx < 0 { + return None; + } + let slot = if list == 0 { + self.lists.list0.get(ref_idx as usize) + } else { + self.lists.list1.as_ref()?.get(ref_idx as usize) + }; + *slot? + } +} + +/// §8.5 — reconstruct one inter coding unit into `pic`. +/// +/// `motions` are the §8.5.3.2.1-resolved per-PU motions (same order as the +/// CU's §7.3.8.6 prediction units), already written into the picture's +/// motion field by [`resolve_cu_motion`]. `residual` is the CU's +/// per-component residual planes ([`extract_cu_residual`]). `refs` resolves +/// each list's reference picture. Each PU's covering residual is sliced from +/// the CU residual planes and added onto the motion-compensated prediction. +/// +/// `wp` carries the slice's §8.5.3.3.4.3 weighted-prediction tables when +/// `weightedPredFlag == 1`; `None` selects the §8.5.3.3.4.2 default +/// combine. +/// +/// # Errors +/// Propagates [`ReconError`] from the §8.5.3.3 interpolation / combine. +#[allow(clippy::too_many_arguments)] +pub fn reconstruct_inter_cu( + pic: &mut Picture, + params: &ReconParams, + cu: &CodingUnit, + rects: &[PuRect], + motions: &[PuMotion], + residual: &CuResidual, + refs: &RefListAccess, + wp: Option<&SliceWpTables>, +) -> Result<(), ReconError> { + let cat = params.chroma_array_type; + let (sub_w, sub_h) = if cat != 0 { sub_wh_c(cat) } else { (1, 1) }; + + // §8.5.3.1: a prediction from the current picture (intra block + // copy) reads the current decoded samples before in-loop + // filtering. The §8.5.3.1 availability constraints guarantee every + // referenced sample precedes this coding block in z-scan order, so + // one snapshot at CU entry is exact. + let needs_curr = refs.lists.list0.contains(&Some(crate::dpb::CURR_PIC)) + || refs + .lists + .list1 + .as_ref() + .is_some_and(|l| l.contains(&Some(crate::dpb::CURR_PIC))); + let needs_curr = needs_curr + && motions.iter().any(|m| { + (m.pred_flag_l0 && refs.is_curr_pic(0, m.ref_idx_l0)) + || (m.pred_flag_l1 && refs.is_curr_pic(1, m.ref_idx_l1)) + }); + let snapshot: Option = needs_curr.then(|| pic.clone()); + + for (rect, motion) in rects.iter().zip(motions.iter()) { + let l0 = resolve_list( + params, + refs, + snapshot.as_ref(), + 0, + motion.pred_flag_l0, + motion.ref_idx_l0, + motion.mv_l0, + )?; + let l1 = resolve_list( + params, + refs, + snapshot.as_ref(), + 1, + motion.pred_flag_l1, + motion.ref_idx_l1, + motion.mv_l1, + )?; + + // Slice the PU's covering residual out of the CU residual planes. + let res_luma = residual + .luma + .slice_region(rect.x_pb, rect.y_pb, rect.n_pb_w, rect.n_pb_h); + let (res_cb, res_cr) = if cat != 0 { + let (cx, cy) = (rect.x_pb / sub_w, rect.y_pb / sub_h); + let (cw, ch) = (rect.n_pb_w / sub_w, rect.n_pb_h / sub_h); + ( + residual.cb.as_ref().map(|p| p.slice_region(cx, cy, cw, ch)), + residual.cr.as_ref().map(|p| p.slice_region(cx, cy, cw, ch)), + ) + } else { + (None, None) + }; + + // §8.5.3.3.4.1 — resolve the PU's explicit weights from its + // reference indices when the slice's weightedPredFlag is 1. + let pu_weights = wp.map(|t| t.resolve_pu(motion)); + reconstruct_inter_pu_weighted( + pic, + params, + rect.x_pb, + rect.y_pb, + rect.n_pb_w, + rect.n_pb_h, + l0, + l1, + Some(res_luma.as_slice()), + res_cb.as_deref(), + res_cr.as_deref(), + pu_weights.as_ref(), + )?; + } + let _ = cu; + Ok(()) +} + +/// Build a [`ResolvedList`] for one reference list, deriving the §8.5.3.2.10 +/// chroma MV and fetching `RefPicListX[ refIdx ]`. An unused list (or a +/// list whose reference resolves to "no reference picture") becomes a +/// `pred_flag == false` entry pointing at a fallback picture (never read). +/// +/// `curr_snapshot` is the pre-in-loop-filter copy of the current +/// picture (`Some` exactly when the CU references the §8.3.4 currPic — +/// intra block copy). +fn resolve_list<'a, 'b>( + params: &ReconParams, + refs: &'b RefListAccess<'a>, + curr_snapshot: Option<&'b Picture>, + list: usize, + pred_flag: bool, + ref_idx: i32, + mv_l: [i32; 2], +) -> Result, ReconError> +where + 'a: 'b, +{ + let (sw, sh) = if params.chroma_array_type != 0 { + sub_wh_c(params.chroma_array_type) + } else { + (1, 1) + }; + if pred_flag { + let ref_pic: Option<&'b Picture> = if refs.is_curr_pic(list, ref_idx) { + curr_snapshot + } else { + refs.ref_pic(list, ref_idx) + }; + if let Some(ref_pic) = ref_pic { + let mv_c = derive_chroma_mv(mv_l, sw as i32, sh as i32); + return Ok(ResolvedList { + pred_flag: true, + mv_l, + mv_c, + ref_pic, + }); + } + // A used list with an unresolvable reference is a malformed stream; + // surface it rather than silently dropping the prediction. + return Err(ReconError::InterNotSupported); + } + // Unused list: point at any available picture (the prediction skips it). + let fallback = refs + .ref_pic(0, 0) + .or_else(|| refs.ref_pic(1, 0)) + .or(curr_snapshot) + .ok_or(ReconError::InterNotSupported)?; + Ok(ResolvedList { + pred_flag: false, + mv_l: [0, 0], + mv_c: [0, 0], + ref_pic: fallback, + }) +} + +/// §8.5.3.2.1 — resolve one inter CU's per-PU motion and write it into +/// `field`, then reconstruct its samples into `pic`. +/// +/// This composes [`resolve_cu_motion`] (the candidate derivation reading the +/// in-progress `field`) with [`extract_cu_residual`] + [`reconstruct_inter_cu`]. +/// `pus` are the parsed §7.3.8.6 prediction units; `ctx` carries the +/// reference-picture resolvers + slice context; `available` is the §6.4.2 +/// prediction-block availability test; `wp` the slice's §8.5.3.3.4.3 +/// weighted-prediction tables (`None` for the default combine). +/// +/// # Errors +/// Propagates [`ReconError`] from the residual extraction / reconstruction. +#[allow(clippy::too_many_arguments)] +pub fn resolve_and_reconstruct_inter_cu( + pic: &mut Picture, + field: &mut MotionField, + params: &ReconParams, + cu: &CodingUnit, + pus: &[PredictionUnit], + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, + refs: &RefListAccess, + qp_y: i32, + wp: Option<&SliceWpTables>, +) -> Result<(), ReconError> { + let n_cb_s = 1usize << cu.log2_cb_size; + let desc = InterCuDesc { + x0: cu.x0 as usize, + y0: cu.y0 as usize, + n_cb_s, + part_mode: cu.part_mode.into(), + }; + let motions = resolve_cu_motion(field, desc, pus, ctx, available); + let rects = + crate::pu_mv::pu_partitions(cu.x0 as usize, cu.y0 as usize, n_cb_s, cu.part_mode.into()); + + let residual = extract_cu_residual( + params, + cu.transform_tree.as_ref(), + cu.x0 as usize, + cu.y0 as usize, + n_cb_s, + qp_y, + cu.cu_transquant_bypass_flag, + )?; + + // §8.7.2.4 — mark the per-4×4 cells covered by a transform block with a + // coded luma coefficient so the deblocking boundary-strength `cbf` test + // (bS = 1 at a transform-block edge with a non-zero coefficient) reads + // them. + if let Some(tree) = cu.transform_tree.as_ref() { + mark_nonzero_luma(field, tree, cu.x0 as usize, cu.y0 as usize, cu.log2_cb_size); + } + + reconstruct_inter_cu(pic, params, cu, &rects, &motions, &residual, refs, wp) +} + +/// Walk an inter CU's transform tree and mark each leaf transform block that +/// carries a non-zero luma coefficient into the motion field +/// ([`MotionField::mark_nonzero_coeff`]). +fn mark_nonzero_luma( + field: &mut MotionField, + tree: &crate::transform_tree::TransformTree, + x0: usize, + y0: usize, + log2_trafo_size: u32, +) { + use crate::transform_tree::TransformTree; + let n = 1usize << log2_trafo_size; + match tree { + TransformTree::Leaf { cbf_luma, unit } => { + let has_coeff = *cbf_luma + && unit + .residual_luma + .as_ref() + .is_some_and(|rb| rb.levels.iter().any(|&l| l != 0)); + if has_coeff { + field.mark_nonzero_coeff(x0, y0, n, n); + } + } + TransformTree::Split { children, .. } => { + let half = n / 2; + let offsets = [(0, 0), (half, 0), (0, half), (half, half)]; + for (child, (dx, dy)) in children.iter().zip(offsets) { + mark_nonzero_luma(field, child, x0 + dx, y0 + dy, log2_trafo_size - 1); + } + } + } +} + +/// Slice-level inputs constant across one P / B slice's inter +/// reconstruction — every field a §8.5.3.2 / §8.3 input that does not vary +/// per coding unit. The picture-level driver +/// ([`reconstruct_inter_picture`]) binds the [`PuMvContext`] reference +/// resolvers to the [`RefListAccess`] + collocated field internally. +#[derive(Debug, Clone)] +pub struct InterSliceContext { + /// `PicOrderCntVal` of the current picture. + pub curr_poc: i32, + /// `true` for a B slice (enables L1 + the §8.5.3.2.4 combined step). + pub slice_is_b: bool, + /// `CtbLog2SizeY`. + pub ctb_log2_size_y: u32, + /// `pic_width_in_luma_samples`. + pub pic_width_luma: u32, + /// `pic_height_in_luma_samples`. + pub pic_height_luma: u32, + /// `MaxNumMergeCand` (§7.4.7.1). + pub max_num_merge_cand: usize, + /// `num_ref_idx_l0_active`. + pub num_ref_idx_l0_active: i32, + /// `num_ref_idx_l1_active`. + pub num_ref_idx_l1_active: i32, + /// `Log2ParMrgLevel` (§7.4.3.3.1). + pub log2_par_mrg_level: u32, + /// `slice_temporal_mvp_enabled_flag`. + pub temporal_mvp_enabled: bool, + /// `collocated_from_l0_flag`. + pub collocated_from_l0_flag: bool, + /// `PicOrderCnt( ColPic )` (§8.5.3.2.9). + pub col_poc: i32, + /// `NoBackwardPredFlag` (§8.3.5). + pub no_backward_pred: bool, + /// `MinTbLog2SizeY` (the transform-block grid base). + pub min_tb_log2_size_y: u32, + /// `Log2MinCuQpDeltaSize` (§7.4.3.3.1) — the §8.6.1 + /// quantization-group size. + pub log2_min_cu_qp_delta_size: u32, + /// `entropy_coding_sync_enabled_flag` — the §8.6.1 third bullet + /// resets `qPY_PREV` to `SliceQpY` at the first quantization group + /// of each CTB row. + pub wpp_qp_row_reset: bool, + /// `slice_loop_filter_across_slices_enabled_flag` (§8.7.2.1 / + /// §8.7.3.2 — slice-boundary edges are filtered only when set). + pub filter_across_slices: bool, + /// `loop_filter_across_tiles_enabled_flag`. + pub filter_across_tiles: bool, + /// `slice_deblocking_filter_disabled_flag == 0` — run the §8.7.2 + /// in-loop deblocking pass after reconstruction. + pub deblock_enabled: bool, + /// `slice_beta_offset_div2` (§8.7.2.5.3). + pub beta_offset_div2: i32, + /// `slice_tc_offset_div2` (§8.7.2.5.3). + pub tc_offset_div2: i32, + /// `SliceQpY` — the per-CU QP for the single-quantization-group case + /// (the deblocking β/tC derivation reads it). + pub slice_qp_y: i32, + /// `pps_cb_qp_offset + slice_cb_qp_offset`. + pub cb_qp_offset: i32, + /// `pps_cr_qp_offset + slice_cr_qp_offset`. + pub cr_qp_offset: i32, + /// `pps_cb_qp_offset` alone — the §8.7.2.5.1/.2 `cQpPicOffset` + /// input to chroma deblocking, which per the invocation text + /// excludes the slice-level and CU-level chroma QP adjustments. + pub pps_cb_qp_offset: i32, + /// `pps_cr_qp_offset` alone (chroma deblocking `cQpPicOffset`). + pub pps_cr_qp_offset: i32, + /// `slice_sao_luma_flag` (§8.7.3.1 luma gate). + pub slice_sao_luma_flag: bool, + /// `slice_sao_chroma_flag` (§8.7.3.1 chroma gate). + pub slice_sao_chroma_flag: bool, + /// `log2_sao_offset_scale_luma` (§7.4.3.3.2; 0 for 8-bit Main). + pub log2_sao_offset_scale_luma: u8, + /// `log2_sao_offset_scale_chroma`. + pub log2_sao_offset_scale_chroma: u8, + /// `constrained_intra_pred_flag` (§8.4.4.2.1) — intra prediction + /// inside this picture may not reference non-intra coding units. + pub constrained_intra_pred: bool, + /// The slice's §8.5.3.3.4.3 explicit weighted-prediction tables — + /// `Some` exactly when `weightedPredFlag` (§8.5.3.3.4.1) is 1. + pub wp: Option, + /// `pcm_loop_filter_disabled_flag` (§7.4.3.2.1) — with it set, the + /// §8.7 loop filters must not modify the reconstructed samples of + /// `pcm_flag == 1` coding units. + pub pcm_loop_filter_disabled: bool, + /// `use_integer_mv_flag` (§7.4.7.1) — the eqs 8-98..8-101 / + /// 8-124..8-125 integer motion-vector resolution. + pub use_integer_mv: bool, + /// `TwoVersionsOfCurrDecPicFlag` (§7.4.3.3.3 eq. 7-40) — gates the + /// §8.5.3.2.1 eqs 8-102/8-103 8×8 bi→uni reduction. + pub two_versions_curr_pic: bool, +} + +/// One placed coding tree unit for the §8.5 picture-level inter driver. +#[derive(Debug)] +pub struct PlacedInterCtu<'a> { + /// CTB luma top-left x. + pub x_ctb: u32, + /// CTB luma top-left y. + pub y_ctb: u32, + /// `SliceAddrRs` of the independent slice segment owning this CTB. + pub slice_addr_rs: u32, + /// `slice_loop_filter_across_slices_enabled_flag` of the slice + /// owning this CTB (§7.4.7.1 — per-slice, not per-picture). + pub filter_across_slices: bool, + /// The decoded coding tree unit. + pub ctu: &'a crate::slice_data::CodingTreeUnit, +} + +/// §8.5 — reconstruct a full P / B picture from its decoded CTUs. +/// +/// Walks the placed CTUs in decode order, dispatching each leaf coding unit: +/// an intra CU goes through the §8.4 intra path +/// ([`crate::recon::reconstruct_intra_cu_ctx`]), an inter CU through +/// [`resolve_and_reconstruct_inter_cu`] (§8.5.3.2 candidate derivation from +/// the in-progress motion field + the collocated `col_field`, then §8.5.3.3 +/// motion-compensated reconstruction). The §6.4.2 prediction-block +/// availability the candidate derivation needs is evaluated against the +/// shared [`crate::recon::ReconCtx`] tiling + the per-cell intra / inter +/// flag of the motion field built up so far. +/// +/// Returns the reconstructed picture and its per-PU motion field (the +/// §8.5.3.2.9 collocated arrays a later picture's temporal MVP reads). The +/// returned picture is the full in-loop-filtered output: when +/// `slice.deblock_enabled` the §8.7.2 deblocking pass runs first, then the +/// §8.7.3 SAO pass (a no-op when both slice SAO flags are clear). +/// +/// # Errors +/// Propagates [`ReconError`] from the per-CU reconstruction. +#[allow(clippy::too_many_arguments)] +pub fn reconstruct_inter_picture( + pic_width_luma: usize, + pic_height_luma: usize, + params: &ReconParams, + slice: &InterSliceContext, + tiles: &crate::availability::TilingParams, + ctus: &[PlacedInterCtu<'_>], + refs: &RefListAccess, + col_field: Option<&MotionField>, +) -> Result<(Picture, MotionField), ReconError> { + let mut pic = Picture::new( + pic_width_luma, + pic_height_luma, + params.chroma_array_type, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + let mut ctx = crate::recon::ReconCtx::new( + pic_width_luma, + pic_height_luma, + slice.ctb_log2_size_y, + slice.min_tb_log2_size_y, + tiles, + )?; + // §8.6.1 QP-derivation state (QpBdOffsetY = 6 * bit_depth_minus8). + ctx.init_qp_state( + slice.slice_qp_y, + slice.log2_min_cu_qp_delta_size, + 6 * (i32::from(params.bit_depth_luma) - 8), + ); + ctx.set_constrained_intra(slice.constrained_intra_pred); + let mut field = MotionField::new(pic_width_luma, pic_height_luma); + + let ctb_size = 1usize << slice.ctb_log2_size_y; + let pic_w_ctbs = pic_width_luma.div_ceil(ctb_size); + let pic_h_ctbs = pic_height_luma.div_ceil(ctb_size); + let mut slice_addr_map = vec![0u32; pic_w_ctbs * pic_h_ctbs]; + // Per-CTB slice_loop_filter_across_slices_enabled_flag (§7.4.7.1 — + // a per-slice value; the §8.7.2.1 / §8.7.3.2 boundary gates consult + // the owning slice's flag, not a picture-level one). + let mut filter_across_map = vec![true; pic_w_ctbs * pic_h_ctbs]; + for placed in ctus { + let rx = (placed.x_ctb as usize) >> slice.ctb_log2_size_y; + let ry = (placed.y_ctb as usize) >> slice.ctb_log2_size_y; + slice_addr_map[ry * pic_w_ctbs + rx] = placed.slice_addr_rs; + filter_across_map[ry * pic_w_ctbs + rx] = placed.filter_across_slices; + } + ctx.set_slice_addr_rs(slice_addr_map.clone()); + + // §8.5.3.2 reference-picture resolvers, bound to the §8.3.4 ref lists. + // The CURR_PIC sentinel resolves to the current POC and — per the + // §8.3.1 "the current decoded picture is marked as used for + // long-term reference" clause — reads as a long-term reference. + let ref_poc = |list: usize, ref_idx: i32| { + if refs.is_curr_pic(list, ref_idx) { + slice.curr_poc + } else { + refs.ref_poc(list, ref_idx) + } + }; + let ref_long_term = |list: usize, ref_idx: i32| { + refs.is_curr_pic(list, ref_idx) + || refs + .entry(list, ref_idx) + .is_some_and(|e| e.marking == crate::dpb::Marking::LongTerm) + }; + let ref_short_term = |list: usize, ref_idx: i32| { + refs.entry(list, ref_idx) + .is_some_and(|e| e.marking == crate::dpb::Marking::ShortTerm) + }; + let col_ref_long_term = |_poc: i32| false; + let is_curr_pic = |list: usize, ref_idx: i32| refs.is_curr_pic(list, ref_idx); + + let mv_ctx = PuMvContext { + curr_poc: slice.curr_poc, + slice_is_b: slice.slice_is_b, + ctb_log2_size_y: slice.ctb_log2_size_y, + pic_width_luma: slice.pic_width_luma, + pic_height_luma: slice.pic_height_luma, + max_num_merge_cand: slice.max_num_merge_cand, + num_ref_idx_l0_active: slice.num_ref_idx_l0_active, + num_ref_idx_l1_active: slice.num_ref_idx_l1_active, + log2_par_mrg_level: slice.log2_par_mrg_level, + temporal_mvp_enabled: slice.temporal_mvp_enabled, + collocated_from_l0_flag: slice.collocated_from_l0_flag, + col_poc: slice.col_poc, + no_backward_pred: slice.no_backward_pred, + ref_poc: &ref_poc, + ref_long_term: &ref_long_term, + ref_short_term: &ref_short_term, + col_field, + col_ref_long_term: &col_ref_long_term, + use_integer_mv: slice.use_integer_mv, + two_versions_curr_pic: slice.two_versions_curr_pic, + is_curr_pic: &is_curr_pic, + }; + + let mut deblock_cus: Vec = Vec::new(); + // §8.7.2.5.4 / §8.7.3.1 — per-4×4-cell loop-filter suppression for + // PCM (`pcm_loop_filter_disabled_flag`) / transquant-bypass CUs. + let (w4, h4) = (pic_width_luma.div_ceil(4), pic_height_luma.div_ceil(4)); + let mut no_filter_cells = vec![false; w4 * h4]; + let mut prev_slice_addr: Option = None; + let mut prev_tile: Option = None; + for placed in ctus { + // §8.6.1 step-1 — qPY_PREV resets to SliceQpY at the first + // quantization group of a slice, of a tile, and (with + // entropy_coding_sync) of each CTB row of a tile. + let rx = (placed.x_ctb as usize) >> slice.ctb_log2_size_y; + let ry = (placed.y_ctb as usize) >> slice.ctb_log2_size_y; + let rs = (ry * pic_w_ctbs + rx) as u32; + let tiling = ctx.tiling(); + let tile = tiling.tile_id(tiling.ctb_addr_rs_to_ts(rs)); + let tile_row_start = rx == 0 || tiling.tile_id(tiling.ctb_addr_rs_to_ts(rs - 1)) != tile; + if prev_slice_addr != Some(placed.slice_addr_rs) + || prev_tile != Some(tile) + || (slice.wpp_qp_row_reset && tile_row_start) + { + ctx.reset_qp_prev(); + } + // §7.4.7.1 — CuQpOffsetCb / CuQpOffsetCr reset to 0 at each + // slice start (unlike qPY_PREV they do NOT reset at tile / + // WPP-row boundaries). + if prev_slice_addr != Some(placed.slice_addr_rs) { + params.cu_qp_offset_c.set((0, 0)); + } + prev_slice_addr = Some(placed.slice_addr_rs); + prev_tile = Some(tile); + reconstruct_inter_quadtree( + &mut pic, + &mut ctx, + &mut field, + params, + &mv_ctx, + refs, + slice, + &mut deblock_cus, + &mut no_filter_cells, + w4, + &filter_across_map, + &placed.ctu.quadtree, + )?; + } + let no_filter_map = no_filter_cells + .iter() + .any(|&b| b) + .then_some(crate::deblock::NoFilterMap { + cells: &no_filter_cells, + w_cells: w4, + }); + + // §8.7.2 — in-loop deblocking (all vertical edges, then horizontal), + // ahead of the §8.7.3 SAO pass. + if slice.deblock_enabled { + let qp_map = ctx + .qp_cells() + .map(|(cells, w_cells)| crate::deblock::QpMap { cells, w_cells }); + crate::deblock::deblock_picture_full( + &mut pic, + &field, + &deblock_cus, + qp_map, + no_filter_map.as_ref(), + ); + } + + // §8.7.3 — sample-adaptive offset (on the deblocked samples). Resolve + // each CTB's §7.4.9.3 SAO parameters with left / above merge (denied + // across slice boundaries), then run the picture-level filter. + let mut sao_grid = vec![crate::sao::ResolvedSao::off(); pic_w_ctbs * pic_h_ctbs]; + for placed in ctus { + let rx = (placed.x_ctb as usize) >> slice.ctb_log2_size_y; + let ry = (placed.y_ctb as usize) >> slice.ctb_log2_size_y; + let here = slice_addr_map[ry * pic_w_ctbs + rx]; + if let Some(sao_params) = &placed.ctu.sao { + let left = (rx > 0 && slice_addr_map[ry * pic_w_ctbs + (rx - 1)] == here) + .then(|| sao_grid[ry * pic_w_ctbs + (rx - 1)]); + let above = (ry > 0 && slice_addr_map[(ry - 1) * pic_w_ctbs + rx] == here) + .then(|| sao_grid[(ry - 1) * pic_w_ctbs + rx]); + sao_grid[ry * pic_w_ctbs + rx] = crate::sao::ResolvedSao::resolve( + sao_params, + left.as_ref(), + above.as_ref(), + slice.log2_sao_offset_scale_luma, + slice.log2_sao_offset_scale_chroma, + ); + } + } + let sao_boundaries = crate::sao::SaoBoundaries { + slice_addr_of_ctb: slice_addr_map.clone(), + tile_id_of_ctb: (0..(pic_w_ctbs * pic_h_ctbs) as u32) + .map(|rs| { + let tiling = ctx.tiling(); + tiling.tile_id(tiling.ctb_addr_rs_to_ts(rs)) + }) + .collect(), + pic_w_ctbs, + ctb_log2_size_y: slice.ctb_log2_size_y, + across_slices: slice.filter_across_slices, + across_tiles: slice.filter_across_tiles, + filter_across_of_ctb: Some(filter_across_map.clone()), + ctb_ts_of_rs: Some( + (0..(pic_w_ctbs * pic_h_ctbs) as u32) + .map(|rs| ctx.tiling().ctb_addr_rs_to_ts(rs)) + .collect(), + ), + }; + let filtered = crate::sao::apply_sao_picture_full( + &pic, + &sao_grid, + slice.ctb_log2_size_y, + params.chroma_array_type, + slice.slice_sao_luma_flag, + slice.slice_sao_chroma_flag, + Some(&sao_boundaries), + no_filter_map.as_ref(), + ); + + Ok((filtered, field)) +} + +/// Walk one §7.3.8.4 coding quadtree, dispatching each leaf coding unit to +/// the intra or inter reconstruction path. +#[allow(clippy::too_many_arguments)] +fn reconstruct_inter_quadtree( + pic: &mut Picture, + ctx: &mut crate::recon::ReconCtx, + field: &mut MotionField, + params: &ReconParams, + mv_ctx: &PuMvContext, + refs: &RefListAccess, + slice: &InterSliceContext, + deblock_cus: &mut Vec, + no_filter_cells: &mut [bool], + w4: usize, + filter_across_of_ctb: &[bool], + qt: &crate::slice_data::CodingQuadtree, +) -> Result<(), ReconError> { + use crate::slice_data::CodingQuadtree; + match qt { + CodingQuadtree::Split(children) => { + for child in children { + reconstruct_inter_quadtree( + pic, + ctx, + field, + params, + mv_ctx, + refs, + slice, + deblock_cus, + no_filter_cells, + w4, + filter_across_of_ctb, + child, + )?; + } + Ok(()) + } + CodingQuadtree::Leaf(cu) => { + // §8.7.2.5.4 / §8.7.3.1 — mark the CU's cells when the loop + // filters must leave its reconstructed samples untouched. + if (cu.pcm_flag && slice.pcm_loop_filter_disabled) || cu.cu_transquant_bypass_flag { + let n = 1usize << cu.log2_cb_size; + for j in (0..n).step_by(4) { + for i in (0..n).step_by(4) { + let (gx, gy) = ((cu.x0 as usize + i) >> 2, (cu.y0 as usize + j) >> 2); + if let Some(cell) = no_filter_cells.get_mut(gy * w4 + gx) { + *cell = true; + } + } + } + } + reconstruct_inter_leaf_cu( + pic, + ctx, + field, + params, + mv_ctx, + refs, + slice, + deblock_cus, + filter_across_of_ctb, + cu, + ) + } + } +} + +/// Build the §8.7.2 [`crate::deblock::DeblockCuDesc`] for one coding unit +/// (its geometry, transform-split topology, partition mode, QP context, and +/// the CB-boundary edge-flag gates) and append it to `deblock_cus`. +#[allow(clippy::too_many_arguments)] +fn collect_deblock_cu( + cu: &CodingUnit, + slice: &InterSliceContext, + chroma_array_type: u8, + bit_depth_luma: u8, + bit_depth_chroma: u8, + qp_y: i32, + qp_y_p_left: i32, + qp_y_p_top: i32, + filter_left: bool, + filter_top: bool, + deblock_cus: &mut Vec, +) { + let cu_params = crate::deblock::DeblockCuParams { + qp_y, + beta_offset_div2: slice.beta_offset_div2, + tc_offset_div2: slice.tc_offset_div2, + cb_qp_offset: slice.pps_cb_qp_offset, + cr_qp_offset: slice.pps_cr_qp_offset, + bit_depth_luma, + bit_depth_chroma, + chroma_array_type, + }; + deblock_cus.push(crate::deblock::DeblockCuDesc { + cu: crate::deblock::DeblockCu { + x_cb: cu.x0 as usize, + y_cb: cu.y0 as usize, + log2_cb_size: cu.log2_cb_size, + params: cu_params, + qp_y_p_left, + qp_y_p_top, + }, + transform_split: crate::deblock::TransformSplit::from_tree(cu.transform_tree.as_ref()), + part_mode: cu.part_mode, + // §8.7.2.1 — the CB-boundary edges are filtered except at the + // picture's left / top border (the single-slice / single-tile case; + // a slice / tile boundary with loop-filter-across disabled would + // additionally clear these, threaded by the caller). + filter_left, + filter_top, + }); +} + +/// Reconstruct one leaf coding unit (intra → §8.4 path + intra-stamp the +/// motion field; inter → §8.5 path), and collect its deblocking descriptor. +#[allow(clippy::too_many_arguments)] +fn reconstruct_inter_leaf_cu( + pic: &mut Picture, + ctx: &mut crate::recon::ReconCtx, + field: &mut MotionField, + params: &ReconParams, + mv_ctx: &PuMvContext, + refs: &RefListAccess, + slice: &InterSliceContext, + deblock_cus: &mut Vec, + filter_across_of_ctb: &[bool], + cu: &CodingUnit, +) -> Result<(), ReconError> { + use crate::binarization::CuPredMode; + let n_cb_s = 1usize << cu.log2_cb_size; + // §8.6.1 — the CU's QpY (in decode order, before anything reads the + // QP map for this CU). + let cu_delta = cu + .transform_tree + .as_ref() + .and_then(crate::recon::first_tree_cu_qp_delta); + let qp_y = ctx.derive_cu_qp( + params, + cu.x0 as usize, + cu.y0 as usize, + cu.log2_cb_size, + cu_delta, + ); + if slice.deblock_enabled { + // Deblocking p-side QPs from the already-stamped neighbour map + // (§8.7.2.5.3 QpP); the picture boundary rows fall back to the + // CU's own QP (those edges are not filtered). + let x0 = cu.x0 as usize; + let y0 = cu.y0 as usize; + let qp_p_left = if x0 > 0 { + ctx.qp_y_at(x0 - 1, y0).unwrap_or(slice.slice_qp_y) + } else { + qp_y + }; + let qp_p_top = if y0 > 0 { + ctx.qp_y_at(x0, y0 - 1).unwrap_or(slice.slice_qp_y) + } else { + qp_y + }; + // §8.7.2.1 filterLeftCbEdgeFlag / filterTopCbEdgeFlag: a + // picture-boundary edge is never filtered; a slice / tile + // boundary edge only when filtering across it is enabled. + // §8.7.2.1 — the slice-boundary gate consults the CURRENT + // slice's slice_loop_filter_across_slices_enabled_flag (the + // slice containing this coding block), a per-slice value. + let pic_w_ctbs = (slice.pic_width_luma as usize).div_ceil(1 << slice.ctb_log2_size_y); + let cu_across = { + let rs = (y0 >> slice.ctb_log2_size_y) * pic_w_ctbs + (x0 >> slice.ctb_log2_size_y); + filter_across_of_ctb.get(rs).copied().unwrap_or(true) + }; + let boundary_ok = |x_nb: usize, y_nb: usize| -> bool { + let same_slice = + ctx.slice_addr_rs_of_luma(x0, y0) == ctx.slice_addr_rs_of_luma(x_nb, y_nb); + let same_tile = ctx.tile_id_of_luma(x0, y0) == ctx.tile_id_of_luma(x_nb, y_nb); + (same_slice || cu_across) && (same_tile || slice.filter_across_tiles) + }; + let filter_left = x0 != 0 && boundary_ok(x0 - 1, y0); + let filter_top = y0 != 0 && boundary_ok(x0, y0 - 1); + collect_deblock_cu( + cu, + slice, + params.chroma_array_type, + params.bit_depth_luma, + params.bit_depth_chroma, + qp_y, + qp_p_left, + qp_p_top, + filter_left, + filter_top, + deblock_cus, + ); + } + if matches!(cu.cu_pred_mode, CuPredMode::Intra) { + // §8.4 intra reconstruction; stamp the motion field intra so a + // later inter CU's §6.4.2 availability denies it as a candidate. + crate::recon::reconstruct_intra_cu_ctx(pic, params, ctx, cu)?; + field.fill_rect( + cu.x0 as usize, + cu.y0 as usize, + n_cb_s, + n_cb_s, + crate::motion::MotionCell { + is_intra: true, + ..crate::motion::MotionCell::default() + }, + ); + // §8.7.2.4 — mark the intra CU's coded transform blocks (intra + // neighbours give bS = 2 regardless, but the cbf flag is read for + // an inter-side q neighbour at the shared edge). + if let Some(tree) = cu.transform_tree.as_ref() { + mark_nonzero_luma(field, tree, cu.x0 as usize, cu.y0 as usize, cu.log2_cb_size); + } + return Ok(()); + } + + // §6.4.2 prediction-block availability against the shared tiling + the + // per-cell intra / inter flag of the motion field. The candidate + // derivation also *mutates* `field` (writing each PU's resolved motion), + // so the closure cannot borrow `field` directly; snapshot the per-4×4 + // intra-flag grid up front. A neighbour outside the current CU was + // decoded before it, so its intra flag is already final; positions + // inside the current CU are excluded by the §6.4.2 z-scan test. + let x_cb = cu.x0; + let y_cb = cu.y0; + let w4 = field.width_4(); + let h4 = field.height_4(); + let mut intra_grid = vec![false; w4 * h4]; + for (gy, row) in intra_grid.chunks_mut(w4).enumerate() { + for (gx, cell) in row.iter_mut().enumerate() { + *cell = field.cell_at(gx * 4, gy * 4).is_intra; + } + } + let tiling = ctx.tiling(); + let available = |x_nb: i32, y_nb: i32| -> bool { + let cu_pred_mode = |x: u32, y: u32| -> u8 { + // §6.4.2 final mask reads CuPredMode[ xNbY ][ yNbY ]. A + // location covered by the CURRENT (inter) coding block has + // CuPredMode == MODE_INTER by definition; the z-scan / + // sameCb steps already guard decode order, so only the + // earlier-partition region of this CU is ever consulted + // (e.g. the §8.5.3.2.7 AMVP neighbours of a 2NxN / Nx2N + // second partition read the first partition's motion). The + // pre-CU snapshot below would otherwise report the + // motion-field background (intra) there. + if (x_cb..x_cb + n_cb_s as u32).contains(&x) + && (y_cb..y_cb + n_cb_s as u32).contains(&y) + { + return 0; + } + let (gx, gy) = ((x as usize) / 4, (y as usize) / 4); + if gx < w4 && gy < h4 && intra_grid[gy * w4 + gx] { + crate::availability::MODE_INTRA + } else { + 0 + } + }; + tiling.prediction_block_availability( + x_cb, + y_cb, + n_cb_s as u32, + x_cb, + y_cb, + n_cb_s as u32, + n_cb_s as u32, + 0, + x_nb, + y_nb, + |ctb_rs| ctx.slice_addr_rs_of(ctb_rs), + cu_pred_mode, + ) + }; + + resolve_and_reconstruct_inter_cu( + pic, + field, + params, + cu, + &cu.prediction_units, + mv_ctx, + &available, + refs, + qp_y, + slice.wp.as_ref(), + ) +} + +/// §8.3 + §8.5 — decode one inter (P / B) picture end to end against the +/// decoded-picture buffer, completing the per-picture reference cycle. +/// +/// Ties the §8.3.1 → §8.3.2 → §8.3.4 → §8.3.5 reference derivation +/// ([`crate::decode::PictureSequenceState::begin_picture`]) to the +/// picture-level inter reconstruction: it resolves `RefPicList0` / +/// `RefPicList1` + `ColPic` into the [`RefListAccess`] + collocated motion +/// field the inter driver reads, runs [`reconstruct_inter_picture`] (recon → +/// deblock → SAO), then inserts the reconstructed picture + its motion field +/// into the DPB ([`crate::decode::PictureSequenceState::store_picture`]) as a +/// short-term reference for the next picture. +/// +/// `header` / `slice_ref` carry the §8.3 inputs; `slice` the §8.5.3.2 / +/// §8.7 slice-constant inputs; `ctus` the decoded CTUs in decode order. +/// Returns the (output) reconstructed picture. +/// +/// # Errors +/// [`ReconError::InterNotSupported`] when the picture is an I picture (no +/// reference lists were built — use the intra driver instead) or a used +/// reference resolves to "no reference picture"; otherwise the per-CU +/// reconstruction errors. +#[allow(clippy::too_many_arguments)] +pub fn decode_inter_picture( + seq: &mut crate::decode::PictureSequenceState, + header: &crate::decode::PictureHeaderInfo, + slice_ref: &crate::decode::SliceRefParams, + pic_width_luma: usize, + pic_height_luma: usize, + params: &ReconParams, + slice: &InterSliceContext, + tiles: &crate::availability::TilingParams, + ctus: &[PlacedInterCtu<'_>], +) -> Result { + // §8.3.1 → §8.3.5 — POC, RPS marking, reference lists, ColPic. + let ref_state = seq.begin_picture(header, slice_ref); + let lists = ref_state + .ref_pic_lists + .clone() + .ok_or(ReconError::InterNotSupported)?; + let layer_id = header.layer_id; + let poc = ref_state.poc; + + // The collocated picture's motion field for the §8.5.3.2.9 temporal MVP. + let col_field = ref_state + .col_pic + .map(|idx| &seq.dpb().entries()[idx].motion); + + let refs = RefListAccess { + lists: &lists, + entries: seq.dpb().entries(), + }; + + let (picture, motion) = reconstruct_inter_picture( + pic_width_luma, + pic_height_luma, + params, + slice, + tiles, + ctus, + &refs, + col_field, + )?; + + // §8.3.2 — insert as a short-term reference for the following pictures. + // (The output picture is returned to the caller before the move.) + let output = picture.clone(); + seq.store_picture(poc, layer_id, picture, motion); + Ok(output) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::binarization::{CuPredMode, PartMode}; + use crate::dpb::{Marking, RefPicLists}; + use crate::motion::MotionField; + use crate::picture::{Picture, Plane}; + use crate::pu_mv::PuMvContext; + use crate::residual::ResidualBlock; + use crate::slice_data::{CodingUnit, PredictionUnit}; + use crate::transform_tree::TransformTree; + use crate::transform_unit::TransformUnit; + + fn p_params() -> ReconParams { + ReconParams { + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: true, + slice_qp_y: 25, + cb_qp_offset: 0, + cr_qp_offset: 0, + act_y_qp_offset: 0, + act_cb_qp_offset: 0, + act_cr_qp_offset: 0, + transform_skip_rotation_enabled: false, + implicit_rdpcm_enabled: false, + intra_boundary_filtering_disabled: false, + extended_precision: false, + scaling: None, + chroma_qp_offset_list: Vec::new(), + cu_qp_offset_c: core::cell::Cell::new((0, 0)), + } + } + + /// A 32×32 reference picture with a flat luma + chroma value. + fn flat_ref(luma: i32, chroma: i32) -> Picture { + let mut p = Picture::new(32, 32, 1, 8, 8); + for y in 0..32 { + for x in 0..32 { + p.set_sample(Plane::Luma, x, y, luma); + } + } + for y in 0..16 { + for x in 0..16 { + p.set_sample(Plane::Cb, x, y, chroma); + p.set_sample(Plane::Cr, x, y, chroma); + } + } + p + } + + fn dpb_entry(poc: i32, pic: Picture) -> DpbEntry { + DpbEntry { + poc, + layer_id: 0, + marking: Marking::ShortTerm, + picture: pic, + motion: MotionField::new(32, 32), + } + } + + /// A merge-mode P prediction unit selecting merge candidate `idx`. + fn merge_pu(idx: u8) -> PredictionUnit { + PredictionUnit { + merge_flag: true, + merge_idx: Some(idx), + inter_pred_idc: None, + ref_idx_l0: None, + mvd_l0: None, + mvp_l0_flag: None, + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + } + } + + /// A 16×16 inter CU at (0,0), PART_2Nx2N, with one prediction unit and + /// an optional flat luma DC residual. + fn inter_cu_16(pu: PredictionUnit, luma_dc: Option) -> CodingUnit { + let tree = luma_dc.map(|dc| { + let mut levels = vec![0i32; 16 * 16]; + levels[0] = dc; + TransformTree::Leaf { + cbf_luma: true, + unit: TransformUnit { + residual_luma: Some(ResidualBlock { + log2_trafo_size: 4, + last_sig_coeff_x: 0, + last_sig_coeff_y: 0, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }), + ..Default::default() + }, + } + }); + CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Inter, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![pu], + intra_luma: vec![], + intra_chroma_pred_mode: vec![], + rqt_root_cbf: luma_dc.is_some(), + transform_tree: tree, + } + } + + /// Build a single-reference P-slice context: one short-term reference at + /// POC 0, current picture at POC 4, temporal MVP disabled. + fn p_ctx<'a>( + ref_poc: &'a dyn Fn(usize, i32) -> i32, + long: &'a dyn Fn(usize, i32) -> bool, + short: &'a dyn Fn(usize, i32) -> bool, + col_long: &'a dyn Fn(i32) -> bool, + ) -> PuMvContext<'a> { + PuMvContext { + curr_poc: 4, + slice_is_b: false, + ctb_log2_size_y: 4, + pic_width_luma: 32, + pic_height_luma: 32, + max_num_merge_cand: 5, + num_ref_idx_l0_active: 1, + num_ref_idx_l1_active: 0, + log2_par_mrg_level: 2, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + col_poc: 0, + no_backward_pred: true, + ref_poc, + ref_long_term: long, + ref_short_term: short, + col_field: None, + col_ref_long_term: col_long, + use_integer_mv: false, + two_versions_curr_pic: false, + is_curr_pic: &|_, _| false, + } + } + + /// §8.5.3.1 intra block copy: a CU whose L0 reference is the + /// CURRENT picture (CURR_PIC) copies already-reconstructed samples + /// of the same picture. The 16×16 CU at (16, 0) signals an AMVP MV + /// of −16 luma samples (mvd −16 on the eq. 8-98 integer path), so + /// it reconstructs to a copy of the (0, 0) block — luma and both + /// chroma planes. + #[test] + fn ibc_cu_copies_current_picture_block() { + let params = p_params(); + let entries: Vec = Vec::new(); + let lists = RefPicLists { + list0: vec![Some(crate::dpb::CURR_PIC)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + let ref_poc = |_l: usize, _r: i32| 4i32; + let long = |_l: usize, _r: i32| true; + let short = |_l: usize, _r: i32| false; + let col_long = |_p: i32| false; + let is_curr = |l: usize, r: i32| l == 0 && r == 0; + let mut ctx = p_ctx(&ref_poc, &long, &short, &col_long); + ctx.is_curr_pic = &is_curr; + + let mvd = |v: i32| crate::binarization::MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + }; + let pu = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(crate::binarization::InterPredIdc::PredL0), + ref_idx_l0: Some(0), + mvd_l0: Some([mvd(-16), mvd(0)]), + mvp_l0_flag: Some(0), + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + let mut cu = inter_cu_16(pu, None); + cu.x0 = 16; + + let mut field = MotionField::new(32, 32); + // Seed the current picture with a distinct pattern; the CU + // region starts at the 8-bit mid-level. + let mut pic = Picture::new(32, 32, 1, 8, 8); + for y in 0..32usize { + for x in 0..32usize { + pic.set_sample(Plane::Luma, x, y, ((x * 7 + y * 3) % 200) as i32); + } + } + for y in 0..16usize { + for x in 0..16usize { + pic.set_sample(Plane::Cb, x, y, ((x * 5 + y * 11) % 180) as i32); + pic.set_sample(Plane::Cr, x, y, ((x * 13 + y * 2) % 160) as i32); + } + } + let available = |_x: i32, _y: i32| false; + resolve_and_reconstruct_inter_cu( + &mut pic, + &mut field, + ¶ms, + &cu, + &cu.prediction_units, + &ctx, + &available, + &refs, + 25, + None, + ) + .unwrap(); + + for y in 0..16usize { + for x in 0..16usize { + assert_eq!( + pic.sample(Plane::Luma, 16 + x, y), + pic.sample(Plane::Luma, x, y), + "luma ({x},{y})" + ); + } + } + for y in 0..8usize { + for x in 0..8usize { + assert_eq!( + pic.sample(Plane::Cb, 8 + x, y), + pic.sample(Plane::Cb, x, y), + "cb ({x},{y})" + ); + assert_eq!( + pic.sample(Plane::Cr, 8 + x, y), + pic.sample(Plane::Cr, x, y), + "cr ({x},{y})" + ); + } + } + } + + /// A merge PU with no spatial / temporal neighbours falls through to the + /// §8.5.3.2.5 zero-MV candidate (mvL0 = 0, refIdxL0 = 0), so the PU + /// reconstructs to the reference picture's co-located samples. + #[test] + fn merge_zero_mv_p_cu_reconstructs_reference() { + let params = p_params(); + let refpic = flat_ref(100, 120); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + let ref_poc = |_l: usize, _r: i32| 0i32; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = p_ctx(&ref_poc, &long, &short, &col_long); + + let cu = inter_cu_16(merge_pu(0), None); + let mut field = MotionField::new(32, 32); + let mut pic = Picture::new(32, 32, 1, 8, 8); + // No neighbours available (single isolated CU at picture origin). + let available = |_x: i32, _y: i32| false; + resolve_and_reconstruct_inter_cu( + &mut pic, + &mut field, + ¶ms, + &cu, + &cu.prediction_units, + &ctx, + &available, + &refs, + 25, + None, + ) + .unwrap(); + + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 100, "luma ({x},{y})"); + } + } + for y in 0..8 { + for x in 0..8 { + assert_eq!(pic.sample(Plane::Cb, x, y), 120, "cb ({x},{y})"); + assert_eq!(pic.sample(Plane::Cr, x, y), 120, "cr ({x},{y})"); + } + } + // eqs 8-80..8-85: the CU's motion is written into the field. + let cell = field.cell_at(0, 0); + assert!(!cell.is_intra); + assert!(cell.pred_flag_l0 && !cell.pred_flag_l1); + assert_eq!(cell.mv_l0, [0, 0]); + } + + /// The CU residual is dequantized + inverse-transformed and added onto + /// the motion-compensated prediction. + #[test] + fn merge_zero_mv_p_cu_adds_residual() { + let params = p_params(); + let refpic = flat_ref(100, 120); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + let ref_poc = |_l: usize, _r: i32| 0i32; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = p_ctx(&ref_poc, &long, &short, &col_long); + + // A DC luma residual produces a uniform offset over the 16×16 block. + let cu = inter_cu_16(merge_pu(0), Some(40)); + let mut field = MotionField::new(32, 32); + let mut pic = Picture::new(32, 32, 1, 8, 8); + let available = |_x: i32, _y: i32| false; + resolve_and_reconstruct_inter_cu( + &mut pic, + &mut field, + ¶ms, + &cu, + &cu.prediction_units, + &ctx, + &available, + &refs, + 25, + None, + ) + .unwrap(); + + // Uniform DC residual ⇒ every luma sample is prediction(100) + r for + // the same r; assert the block is uniform and offset from 100. + let v = pic.sample(Plane::Luma, 0, 0); + assert_ne!(v, 100, "residual shifts the prediction"); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), v, "uniform at ({x},{y})"); + } + } + } + + fn p_slice_ctx() -> InterSliceContext { + InterSliceContext { + log2_min_cu_qp_delta_size: 4, + wpp_qp_row_reset: false, + filter_across_slices: true, + filter_across_tiles: true, + curr_poc: 4, + constrained_intra_pred: false, + slice_is_b: false, + ctb_log2_size_y: 5, + pic_width_luma: 32, + pic_height_luma: 32, + max_num_merge_cand: 5, + num_ref_idx_l0_active: 1, + num_ref_idx_l1_active: 0, + log2_par_mrg_level: 2, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + col_poc: 0, + no_backward_pred: true, + min_tb_log2_size_y: 2, + deblock_enabled: false, + beta_offset_div2: 0, + tc_offset_div2: 0, + slice_qp_y: 25, + cb_qp_offset: 0, + cr_qp_offset: 0, + slice_sao_luma_flag: false, + slice_sao_chroma_flag: false, + log2_sao_offset_scale_luma: 0, + log2_sao_offset_scale_chroma: 0, + wp: None, + pcm_loop_filter_disabled: false, + use_integer_mv: false, + two_versions_curr_pic: false, + pps_cb_qp_offset: 0, + pps_cr_qp_offset: 0, + } + } + + /// The §8.5 picture-level driver reconstructs a single-CTU P picture + /// whose one 32×32 inter merge CU (zero-MV fallback) copies the flat + /// reference samples, and records the CU's motion into the returned + /// field. + #[test] + fn picture_driver_single_inter_ctu_copies_reference() { + let params = p_params(); + let refpic = flat_ref(77, 99); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + // One 32×32 inter merge CU at (0,0) — a single coding tree unit + // covering the whole picture. + let mut cu = inter_cu_16(merge_pu(0), None); + cu.log2_cb_size = 5; + let ctu = crate::slice_data::CodingTreeUnit { + sao: None, + quadtree: crate::slice_data::CodingQuadtree::Leaf(Box::new(cu)), + }; + let placed = vec![PlacedInterCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + filter_across_slices: true, + ctu: &ctu, + }]; + + let slice = p_slice_ctx(); + let tiles = crate::availability::TilingParams::single_tile(); + let (pic, field) = + reconstruct_inter_picture(32, 32, ¶ms, &slice, &tiles, &placed, &refs, None) + .unwrap(); + + for y in 0..32 { + for x in 0..32 { + assert_eq!(pic.sample(Plane::Luma, x, y), 77, "luma ({x},{y})"); + } + } + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Cb, x, y), 99, "cb ({x},{y})"); + } + } + let cell = field.cell_at(16, 16); + assert!(!cell.is_intra && cell.pred_flag_l0); + assert_eq!(cell.mv_l0, [0, 0]); + } + + /// A mixed P picture: an intra CU and an inter CU side by side both + /// reconstruct, and the intra CU is stamped intra in the motion field. + #[test] + fn picture_driver_mixed_intra_inter() { + let params = p_params(); + let refpic = flat_ref(60, 90); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + // CTU split into four 16×16 quadrants: top-left intra (DC), the + // other three inter merge. + let intra_cu = CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![crate::slice_data::IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: false, + unit: TransformUnit::default(), + }), + }; + let mut inter_tr = inter_cu_16(merge_pu(0), None); + inter_tr.x0 = 16; + let mut inter_bl = inter_cu_16(merge_pu(0), None); + inter_bl.y0 = 16; + let mut inter_br = inter_cu_16(merge_pu(0), None); + inter_br.x0 = 16; + inter_br.y0 = 16; + + let ctu = crate::slice_data::CodingTreeUnit { + sao: None, + quadtree: crate::slice_data::CodingQuadtree::Split(vec![ + crate::slice_data::CodingQuadtree::Leaf(Box::new(intra_cu)), + crate::slice_data::CodingQuadtree::Leaf(Box::new(inter_tr)), + crate::slice_data::CodingQuadtree::Leaf(Box::new(inter_bl)), + crate::slice_data::CodingQuadtree::Leaf(Box::new(inter_br)), + ]), + }; + let placed = vec![PlacedInterCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + filter_across_slices: true, + ctu: &ctu, + }]; + + let slice = p_slice_ctx(); + let tiles = crate::availability::TilingParams::single_tile(); + let (pic, field) = + reconstruct_inter_picture(32, 32, ¶ms, &slice, &tiles, &placed, &refs, None) + .unwrap(); + + // The three inter quadrants copy the reference value 60. + assert_eq!(pic.sample(Plane::Luma, 24, 8), 60, "top-right inter"); + assert_eq!(pic.sample(Plane::Luma, 8, 24), 60, "bottom-left inter"); + assert_eq!(pic.sample(Plane::Luma, 24, 24), 60, "bottom-right inter"); + // The intra quadrant is stamped intra; the inter quadrants are not. + assert!(field.cell_at(0, 0).is_intra, "TL intra-stamped"); + assert!(!field.cell_at(16, 0).is_intra, "TR inter"); + assert!(!field.cell_at(16, 16).is_intra, "BR inter"); + } + + /// With deblocking enabled, the §8.7.2 in-loop pass runs as part of the + /// picture driver: a strong luma step at the intra/inter CU boundary + /// (bS = 2) is smoothed, so the boundary samples differ from the + /// undeblocked reconstruction. + #[test] + fn picture_driver_deblock_smooths_cu_boundary() { + let params = p_params(); + // Reference for the inter CUs: flat 140 — a modest step from the + // intra DC (128) so the §8.7.2.5.3 dE decision classifies the + // boundary as a blocking artifact (small gradient) rather than a + // true edge, and the weak filter engages. + let refpic = flat_ref(140, 128); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + // CTU split into four 16×16 quadrants: the two left quadrants intra + // (DC ⇒ mid-grey 128, no neighbours), the two right inter (copy 200). + let intra = |x0: u32, y0: u32| CodingUnit { + x0, + y0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![crate::slice_data::IntraLumaMode { + prev_intra_luma_pred_flag: false, + mpm_idx: None, + rem_intra_luma_pred_mode: Some(1), + }], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: false, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: false, + unit: TransformUnit::default(), + }), + }; + let inter = |x0: u32, y0: u32| { + let mut c = inter_cu_16(merge_pu(0), None); + c.x0 = x0; + c.y0 = y0; + c + }; + let ctu = crate::slice_data::CodingTreeUnit { + sao: None, + quadtree: crate::slice_data::CodingQuadtree::Split(vec![ + crate::slice_data::CodingQuadtree::Leaf(Box::new(intra(0, 0))), + crate::slice_data::CodingQuadtree::Leaf(Box::new(inter(16, 0))), + crate::slice_data::CodingQuadtree::Leaf(Box::new(intra(0, 16))), + crate::slice_data::CodingQuadtree::Leaf(Box::new(inter(16, 16))), + ]), + }; + let placed = vec![PlacedInterCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + filter_across_slices: true, + ctu: &ctu, + }]; + + let tiles = crate::availability::TilingParams::single_tile(); + // Undeblocked baseline. + let mut undeb = p_slice_ctx(); + undeb.deblock_enabled = false; + let (plain, _) = + reconstruct_inter_picture(32, 32, ¶ms, &undeb, &tiles, &placed, &refs, None) + .unwrap(); + // Deblocked. + let mut deb = p_slice_ctx(); + deb.deblock_enabled = true; + let (filtered, _) = + reconstruct_inter_picture(32, 32, ¶ms, &deb, &tiles, &placed, &refs, None).unwrap(); + + // The vertical boundary at x == 16 separates intra (128) from inter + // (200); the deblock pass adjusts samples on at least one side, so + // the filtered picture differs from the plain one near the edge. + let mut changed = false; + for y in 0..32 { + for x in 13..19 { + if filtered.sample(Plane::Luma, x, y) != plain.sample(Plane::Luma, x, y) { + changed = true; + } + } + } + assert!(changed, "deblocking modifies samples at the CU boundary"); + // Far-from-edge interior samples are untouched. + assert_eq!(filtered.sample(Plane::Luma, 28, 8), 140, "inter interior"); + } + + /// With `slice_sao_luma_flag` set and a band-offset SAO on the CTB, the + /// §8.7.3 SAO pass runs as part of the picture driver: the inter CU's + /// flat luma is shifted by the band offset covering its value. + #[test] + fn picture_driver_applies_sao() { + let params = p_params(); + // Inter reference flat 100. Luma 100 is in band 100 >> 3 == 12. + let refpic = flat_ref(100, 128); + let entries = vec![dpb_entry(0, refpic)]; + let lists = RefPicLists { + list0: vec![Some(0)], + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &entries, + }; + + let mut cu = inter_cu_16(merge_pu(0), None); + cu.log2_cb_size = 5; + // Band-offset SAO on luma: band_position 12 (covers value 100), + // first offset +5 ⇒ luma 100 → 105. + let sao = crate::slice_data::SaoCtbParams { + merge_left: false, + merge_up: false, + components: [ + crate::slice_data::SaoComponent { + sao_type_idx: 1, + offset_abs: [5, 0, 0, 0], + offset_sign: [0, 0, 0, 0], + band_position: 12, + eo_class: 0, + }, + crate::slice_data::SaoComponent::default(), + crate::slice_data::SaoComponent::default(), + ], + }; + let ctu = crate::slice_data::CodingTreeUnit { + sao: Some(sao), + quadtree: crate::slice_data::CodingQuadtree::Leaf(Box::new(cu)), + }; + let placed = vec![PlacedInterCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + filter_across_slices: true, + ctu: &ctu, + }]; + + let mut slice = p_slice_ctx(); + slice.slice_sao_luma_flag = true; + let tiles = crate::availability::TilingParams::single_tile(); + let (pic, _) = + reconstruct_inter_picture(32, 32, ¶ms, &slice, &tiles, &placed, &refs, None) + .unwrap(); + // The reconstructed inter samples (100) fall in SAO band 12 and get + // the +5 offset. + assert_eq!( + pic.sample(Plane::Luma, 8, 8), + 105, + "SAO band offset applied" + ); + } + + /// §8.3 + §8.5 end-to-end inter picture cycle: an IDR reference picture + /// is stored in the DPB, then a P picture (one 32×32 inter merge CU) + /// decodes against it via `decode_inter_picture` — resolving + /// RefPicList0[0] → the IDR, copying its samples, and landing in the DPB + /// as a short-term reference. + #[test] + fn decode_inter_picture_full_cycle() { + use crate::poc::NalKind; + use crate::sps::MaterializedShortTermRefPicSet; + + let params = p_params(); + let mut seq = crate::decode::PictureSequenceState::new(); + + // IDR (POC 0): a flat-110 reference picture stored directly. + let idr_header = crate::decode::PictureHeaderInfo { + nal_kind: NalKind::new(NalKind::IDR_N_LP), + temporal_id: 0, + layer_id: 0, + no_rasl_output: true, + poc_lsb: 0, + max_poc_lsb: 256, + short_term_rps: MaterializedShortTermRefPicSet { + delta_poc_s0: vec![], + used_by_curr_pic_s0: vec![], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }, + long_term: vec![], + }; + let i_slice = crate::decode::SliceRefParams { + is_inter: false, + is_b: false, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + num_pic_total_curr: 0, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + collocated_ref_idx: 0, + curr_pic_ref_enabled: false, + }; + let idr = seq.begin_picture(&idr_header, &i_slice); + seq.store_picture(idr.poc, 0, flat_ref(110, 128), MotionField::new(32, 32)); + + // P picture (POC 1): one short-term-before reference at POC 0. + let p_header = crate::decode::PictureHeaderInfo { + nal_kind: NalKind::new(NalKind::TRAIL_R), + no_rasl_output: false, + poc_lsb: 1, + short_term_rps: MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }, + ..idr_header.clone() + }; + let p_slice_ref = crate::decode::SliceRefParams { + is_inter: true, + num_pic_total_curr: 1, + ..i_slice + }; + + let mut cu = inter_cu_16(merge_pu(0), None); + cu.log2_cb_size = 5; + let ctu = crate::slice_data::CodingTreeUnit { + sao: None, + quadtree: crate::slice_data::CodingQuadtree::Leaf(Box::new(cu)), + }; + let placed = vec![PlacedInterCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + filter_across_slices: true, + ctu: &ctu, + }]; + let slice = p_slice_ctx(); + let tiles = crate::availability::TilingParams::single_tile(); + + let out = decode_inter_picture( + &mut seq, + &p_header, + &p_slice_ref, + 32, + 32, + ¶ms, + &slice, + &tiles, + &placed, + ) + .unwrap(); + + // The P picture copies the IDR reference's flat 110. + for y in 0..32 { + for x in 0..32 { + assert_eq!(out.sample(Plane::Luma, x, y), 110, "P luma ({x},{y})"); + } + } + // The DPB now holds two pictures (IDR POC 0 + P POC 1), both + // short-term references. + assert_eq!(seq.dpb().entries().len(), 2); + assert_eq!(seq.dpb().entries()[1].poc, 1); + assert_eq!( + seq.dpb().entries()[1].marking, + crate::dpb::Marking::ShortTerm + ); + // The P picture's motion field records the inter CU (for a future + // picture's temporal MVP). + assert!(!seq.dpb().entries()[1].motion.cell_at(16, 16).is_intra); + } +} diff --git a/vendor/oxideav-h265/src/intra_mode_field.rs b/vendor/oxideav-h265/src/intra_mode_field.rs new file mode 100644 index 0000000..5f66cf4 --- /dev/null +++ b/vendor/oxideav-h265/src/intra_mode_field.rs @@ -0,0 +1,371 @@ +//! §8.4.2 luma-intra-mode neighbour state — the `IntraPredModeY` +//! prediction-block field consulted by the candidate-mode derivation. +//! +//! The §8.4.2 derivation of `IntraPredModeY[ xPb ][ yPb ]` needs, for each +//! prediction block, the `IntraPredModeY` of the left neighbour +//! `( xPb − 1, yPb )` and the above neighbour `( xPb, yPb − 1 )`, together +//! with each neighbour's `CuPredMode` and `pcm_flag` and its z-scan +//! availability. This module stores those three per-block facts on a +//! minimum-block (4×4 luma sample) grid so the [`crate::recon`] driver can +//! reconstruct a multi-coding-unit / multi-prediction-block intra picture +//! with the spec-exact most-probable-mode derivation instead of the +//! flat-single-CU `INTRA_DC` neighbour assumption. +//! +//! The field is luma-only: §8.4.2 operates on luma prediction-block +//! locations, and §8.4.3 derives `IntraPredModeC` from the co-located +//! `IntraPredModeY` (already threaded through [`crate::recon`]). + +use crate::binarization::CuPredMode; +use crate::intra_pred::INTRA_DC; + +/// `Log2MinTbSizeY` is at most 2 across all profiles (a 4×4 minimum +/// transform / prediction block), so the §8.4.2 neighbour grid is keyed +/// at the 4×4 luma min-block granularity. Every coding/prediction block +/// is an integer number of these cells on a side. +pub const MIN_BLOCK_LOG2: u32 = 2; + +/// The 4×4 luma min-block side in samples. +pub const MIN_BLOCK_SIZE: usize = 1 << MIN_BLOCK_LOG2; + +/// One min-block's §8.4.2 neighbour facts. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct Cell { + /// `IntraPredModeY[ x ][ y ]` (0..=34); only meaningful when + /// `pred_mode == MODE_INTRA`. + intra_pred_mode_y: u8, + /// `CuPredMode[ x ][ y ]`. + pred_mode: CuPredMode, + /// `pcm_flag[ x ][ y ]`. + pcm_flag: bool, + /// Whether this cell has been written (a still-unwritten cell is + /// treated as not-yet-decoded → unavailable by the z-scan test). + written: bool, +} + +impl Default for Cell { + fn default() -> Self { + Self { + intra_pred_mode_y: INTRA_DC, + pred_mode: CuPredMode::Intra, + pcm_flag: false, + written: false, + } + } +} + +/// Which §8.4.2 neighbour a candidate mode is being derived for. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Neighbour { + /// `A` — the left neighbour `( xPb − 1, yPb )`. + Left, + /// `B` — the above neighbour `( xPb, yPb − 1 )`. + Above, +} + +/// A per-picture luma `IntraPredModeY` field on the 4×4 min-block grid. +/// +/// The grid is sized to the picture (in min blocks) and records, for every +/// decoded luma prediction block, the three §8.4.2 candidate-derivation +/// inputs. Reconstruction writes a coding unit's cells before the next +/// coding unit's prediction-block modes are derived, so the left / above +/// neighbour lookups always see already-decoded state. +#[derive(Debug, Clone)] +pub struct IntraModeField { + /// Width / height of the grid in 4×4 min blocks. + w_blocks: usize, + h_blocks: usize, + /// `CtbLog2SizeY` — the §8.4.2 step-2 CTB-row test for neighbour `B`. + ctb_log2_size_y: u32, + cells: Vec, +} + +impl IntraModeField { + /// Grid width in 4×4 min blocks. + #[must_use] + pub fn w_blocks(&self) -> usize { + self.w_blocks + } + + /// Grid height in 4×4 min blocks. + #[must_use] + pub fn h_blocks(&self) -> usize { + self.h_blocks + } + + /// `CtbLog2SizeY` the field was allocated with. + #[must_use] + pub fn ctb_log2(&self) -> u32 { + self.ctb_log2_size_y + } + + /// Allocate the field for a picture `pic_width_in_luma_samples` × + /// `pic_height_in_luma_samples` with the given `CtbLog2SizeY`. All + /// cells start unwritten (every neighbour lookup before a write + /// reports `INTRA_DC` per the §8.4.2 unavailable branch). + #[must_use] + pub fn new(pic_width_luma: usize, pic_height_luma: usize, ctb_log2_size_y: u32) -> Self { + let w_blocks = pic_width_luma.div_ceil(MIN_BLOCK_SIZE); + let h_blocks = pic_height_luma.div_ceil(MIN_BLOCK_SIZE); + Self { + w_blocks, + h_blocks, + ctb_log2_size_y, + cells: vec![Cell::default(); w_blocks * h_blocks], + } + } + + #[inline] + fn cell_index(&self, x_luma: usize, y_luma: usize) -> usize { + let bx = x_luma >> MIN_BLOCK_LOG2; + let by = y_luma >> MIN_BLOCK_LOG2; + by * self.w_blocks + bx + } + + /// Record an intra prediction block's `IntraPredModeY` across the + /// `n_pb` × `n_pb` luma samples at `( x_pb, y_pb )`. `pcm_flag` and the + /// `MODE_INTRA` `CuPredMode` are stamped on every covered min block. + pub fn record_intra_pb( + &mut self, + x_pb: usize, + y_pb: usize, + n_pb: usize, + intra_pred_mode_y: u8, + pcm_flag: bool, + ) { + self.fill( + x_pb, + y_pb, + n_pb, + n_pb, + Cell { + intra_pred_mode_y, + pred_mode: CuPredMode::Intra, + pcm_flag, + written: true, + }, + ); + } + + /// §8.4.4.2.1 constrained-intra gate — whether the recorded + /// `CuPredMode[ x ][ y ]` at the luma location is `MODE_INTRA`. + /// Unwritten (not-yet-decoded) cells report `false`; the §6.4.1 + /// z-scan availability independently denies those. + #[must_use] + pub fn is_intra_at(&self, x_luma: usize, y_luma: usize) -> bool { + let c = &self.cells[self.cell_index(x_luma, y_luma)]; + c.written && matches!(c.pred_mode, CuPredMode::Intra) + } + + /// Record a non-intra coding unit (`MODE_INTER` / `MODE_SKIP`) across + /// its `n_cb` × `n_cb` luma samples. The §8.4.2 candidate derivation + /// maps such a neighbour to `INTRA_DC`, but the cell must be marked + /// written so the z-scan availability test sees a decoded neighbour. + pub fn record_non_intra_cu(&mut self, x_cb: usize, y_cb: usize, n_cb: usize, mode: CuPredMode) { + self.fill( + x_cb, + y_cb, + n_cb, + n_cb, + Cell { + intra_pred_mode_y: INTRA_DC, + pred_mode: mode, + pcm_flag: false, + written: true, + }, + ); + } + + fn fill(&mut self, x: usize, y: usize, w: usize, h: usize, cell: Cell) { + let bx0 = x >> MIN_BLOCK_LOG2; + let by0 = y >> MIN_BLOCK_LOG2; + let bx1 = ((x + w).min(self.w_blocks << MIN_BLOCK_LOG2)).div_ceil(MIN_BLOCK_SIZE); + let by1 = ((y + h).min(self.h_blocks << MIN_BLOCK_LOG2)).div_ceil(MIN_BLOCK_SIZE); + for by in by0..by1 { + for bx in bx0..bx1 { + self.cells[by * self.w_blocks + bx] = cell; + } + } + } + + /// §8.4.2 step 2 — derive `candIntraPredModeX` for the neighbour `X` + /// of the prediction block at `( x_pb, y_pb )`. + /// + /// `available` is the §6.4.1 z-scan availability of the neighbour + /// location, supplied by the caller (the [`crate::availability`] + /// `z_scan_availability` consults the picture tiling / slice map the + /// driver owns). The remaining branches — the not-`MODE_INTRA` / + /// `pcm_flag` mask, the neighbour-`B` CTB-row test, and the + /// `IntraPredModeY[ xNb ][ yNb ]` lookup — are evaluated here against + /// the recorded field. + /// + /// Returns `INTRA_DC` whenever the spec's step-2 ordered conditions + /// select it, and the recorded neighbour mode otherwise. + #[must_use] + pub fn cand_intra_pred_mode( + &self, + x_pb: usize, + y_pb: usize, + neighbour: Neighbour, + available: bool, + ) -> u8 { + // Neighbour location ( xNbX, yNbX ) — step 1. + let (x_nb, y_nb) = match neighbour { + Neighbour::Left => (x_pb as i64 - 1, y_pb as i64), + Neighbour::Above => (x_pb as i64, y_pb as i64 - 1), + }; + // availableX == FALSE ⇒ INTRA_DC. + if !available || x_nb < 0 || y_nb < 0 { + return INTRA_DC; + } + let x_nb = x_nb as usize; + let y_nb = y_nb as usize; + if x_nb >= (self.w_blocks << MIN_BLOCK_LOG2) || y_nb >= (self.h_blocks << MIN_BLOCK_LOG2) { + return INTRA_DC; + } + let cell = self.cells[self.cell_index(x_nb, y_nb)]; + // An unwritten neighbour cannot have been decoded → INTRA_DC. (The + // z-scan availability test should already exclude it, but a + // single-slice driver that passes `available = true` for all + // in-picture neighbours relies on this guard.) + if !cell.written { + return INTRA_DC; + } + // CuPredMode[ xNbX ][ yNbX ] != MODE_INTRA || pcm_flag ⇒ INTRA_DC. + if cell.pred_mode != CuPredMode::Intra || cell.pcm_flag { + return INTRA_DC; + } + // X == B and yPb − 1 < ( ( yPb >> CtbLog2SizeY ) << CtbLog2SizeY ) + // ⇒ INTRA_DC (the above neighbour is in the CTB row above). + if neighbour == Neighbour::Above { + let ctb_row_top = (y_pb >> self.ctb_log2_size_y) << self.ctb_log2_size_y; + if y_pb >= 1 && (y_pb - 1) < ctb_row_top { + return INTRA_DC; + } + } + cell.intra_pred_mode_y + } + + /// The recorded `IntraPredModeY` at a luma location (or `None` if + /// no block covering it has been written yet). + #[must_use] + pub fn recorded_mode(&self, x_luma: usize, y_luma: usize) -> Option { + let cell = self.cells[self.cell_index(x_luma, y_luma)]; + cell.written.then_some(cell.intra_pred_mode_y) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn fresh_field_reports_dc_for_all_neighbours() { + let f = IntraModeField::new(64, 64, 6); + // No cell written yet ⇒ both candidates are INTRA_DC. + assert_eq!( + f.cand_intra_pred_mode(8, 8, Neighbour::Left, true), + INTRA_DC + ); + assert_eq!( + f.cand_intra_pred_mode(8, 8, Neighbour::Above, true), + INTRA_DC + ); + } + + #[test] + fn out_of_picture_neighbour_is_dc() { + let f = IntraModeField::new(64, 64, 6); + // ( -1, 0 ) left of the picture origin. + assert_eq!( + f.cand_intra_pred_mode(0, 0, Neighbour::Left, true), + INTRA_DC + ); + // ( 0, -1 ) above the picture origin. + assert_eq!( + f.cand_intra_pred_mode(0, 0, Neighbour::Above, true), + INTRA_DC + ); + } + + #[test] + fn unavailable_neighbour_is_dc_even_if_written() { + let mut f = IntraModeField::new(64, 64, 6); + f.record_intra_pb(0, 8, 8, 26, false); + // The left neighbour ( -1+8 ... ) carries mode 26 but availability + // is forced FALSE by the caller (e.g. slice boundary). + assert_eq!( + f.cand_intra_pred_mode(8, 8, Neighbour::Left, false), + INTRA_DC + ); + } + + #[test] + fn left_neighbour_returns_recorded_intra_mode() { + let mut f = IntraModeField::new(64, 64, 6); + // Record an 8×8 intra PB at ( 0, 8 ) with angular mode 18. + f.record_intra_pb(0, 8, 8, 18, false); + // Current PB at ( 8, 8 ): left neighbour ( 7, 8 ) is inside the PB. + assert_eq!(f.cand_intra_pred_mode(8, 8, Neighbour::Left, true), 18); + } + + #[test] + fn above_neighbour_in_same_ctb_row_returns_mode() { + // CtbLog2SizeY = 5 ⇒ 32-sample CTB. A PB at ( 0, 8 ) whose above + // neighbour ( 0, 7 ) is in the same CTB row keeps the mode. + let mut f = IntraModeField::new(64, 64, 5); + f.record_intra_pb(0, 0, 8, 22, false); + // PB at ( 0, 8 ): above is ( 0, 7 ); ctb_row_top = 0; 7 >= 0 so the + // neighbour is in-row, mode preserved. + assert_eq!(f.cand_intra_pred_mode(0, 8, Neighbour::Above, true), 22); + } + + #[test] + fn above_neighbour_in_ctb_row_above_is_dc() { + // CtbLog2SizeY = 5 (32). A PB whose top is on a CTB-row boundary + // ( yPb = 32 ) has its above neighbour ( yPb - 1 = 31 ) in the CTB + // row above ⇒ candIntraPredModeB = INTRA_DC. + let mut f = IntraModeField::new(64, 64, 5); + f.record_intra_pb(0, 28, 4, 30, false); + // ctb_row_top for yPb=32 is 32; 31 < 32 ⇒ DC. + assert_eq!( + f.cand_intra_pred_mode(0, 32, Neighbour::Above, true), + INTRA_DC + ); + // The left neighbour has no such CTB-row restriction. + } + + #[test] + fn non_intra_neighbour_is_dc() { + let mut f = IntraModeField::new(64, 64, 6); + f.record_non_intra_cu(0, 8, 8, CuPredMode::Inter); + assert_eq!( + f.cand_intra_pred_mode(8, 8, Neighbour::Left, true), + INTRA_DC + ); + } + + #[test] + fn pcm_neighbour_is_dc() { + let mut f = IntraModeField::new(64, 64, 6); + f.record_intra_pb(0, 8, 8, 18, true); + assert_eq!( + f.cand_intra_pred_mode(8, 8, Neighbour::Left, true), + INTRA_DC + ); + } + + #[test] + fn record_fills_every_covered_min_block() { + let mut f = IntraModeField::new(64, 64, 6); + // A 16×16 intra PB at ( 16, 16 ), mode 10. + f.record_intra_pb(16, 16, 16, 10, false); + // The bottom-right min block ( 28, 28 ) is covered; a PB to its + // right at ( 32, 28 ) sees mode 10 on its left neighbour ( 31, 28 ). + assert_eq!(f.cand_intra_pred_mode(32, 28, Neighbour::Left, true), 10); + // A min block one past the PB ( 32, 16 ) is NOT covered. + assert_eq!( + f.cand_intra_pred_mode(36, 16, Neighbour::Left, true), + INTRA_DC + ); + } +} diff --git a/vendor/oxideav-h265/src/intra_pred.rs b/vendor/oxideav-h265/src/intra_pred.rs new file mode 100644 index 0000000..8531495 --- /dev/null +++ b/vendor/oxideav-h265/src/intra_pred.rs @@ -0,0 +1,1230 @@ +//! §8.4.4.2 — intra sample prediction (reference-sample substitution, +//! neighbour-sample filtering, and the planar / DC / angular predictors). +//! +//! This module turns the `nTbS * 4 + 1` neighbouring samples +//! `p[ x ][ y ]` (with `x = −1, y = −1..nTbS * 2 − 1` and +//! `x = 0..nTbS * 2 − 1, y = −1`) of one transform block — the +//! constructed samples *prior to* the deblocking filter, together with +//! their per-sample "available for intra prediction" markings — into the +//! `(nTbS)x(nTbS)` predicted sample array `predSamples[ x ][ y ]`. +//! +//! Four ITU-T H.265 (01/2026) subclauses are implemented, in the +//! dependency order §8.4.4.2.1 invokes them: +//! +//! * §8.4.4.2.2 **reference sample substitution** +//! ([`substitute_reference_samples`]) — fills every sample marked "not +//! available for intra prediction" from its neighbours (the +//! bottom-left-to-top-right sweep of the ordered steps), substituting +//! the mid-level `1 << ( bitDepth − 1 )` only when *every* neighbour is +//! unavailable. +//! * §8.4.4.2.3 **filtering of neighbouring samples** +//! ([`filter_reference_samples`]) — the `[1 2 1] >> 2` smoothing of +//! equations 8-41..8-45, gated by `filterFlag` (Table 8-4) and, for the +//! `nTbS == 32` luma case, the bi-linear `biIntFlag` interpolation of +//! equations 8-36..8-40. +//! * §8.4.4.2.4 **`INTRA_PLANAR`** ([`predict_planar`]) — equation 8-46. +//! * §8.4.4.2.5 **`INTRA_DC`** ([`predict_dc`]) — `dcVal` (equation +//! 8-47) plus the `cIdx == 0`, `nTbS < 32` boundary smoothing of +//! equations 8-48..8-51. +//! * §8.4.4.2.6 **`INTRA_ANGULAR2..INTRA_ANGULAR34`** +//! ([`predict_angular`]) — the `intraPredAngle` / `invAngle` +//! (Tables 8-5 / 8-6) reference-array projection of equations +//! 8-53..8-68, including the vertical (26) / horizontal (10) boundary +//! filter. +//! +//! The top-level [`intra_predict`] applies §8.4.4.2.1 steps 1 and 2 +//! (filtering selection + predictor dispatch) given an already-substituted +//! reference array, and [`intra_predict_with_substitution`] runs the full +//! §8.4.4.2.1 pipeline from a raw availability-marked array. +//! +//! ## Scope +//! +//! The numerics are self-contained. The §6.4.1 z-scan availability +//! derivation that produces the per-sample "available" markings, the +//! `constrained_intra_pred_flag` masking of §8.4.4.2.1, and the §8.6.7 +//! picture-construction step that adds the residual to `predSamples` are +//! the caller's / follow-ups' responsibility — this module starts at the +//! marked reference array and stops at `predSamples`. + +/// Table 8-1 mode index `0` — the planar predictor (§8.4.4.2.4). +pub const INTRA_PLANAR: u8 = 0; +/// Table 8-1 mode index `1` — the DC predictor (§8.4.4.2.5). +pub const INTRA_DC: u8 = 1; +/// Table 8-1 mode index `10` — the horizontal angular predictor; named +/// for the §8.4.4.2.6 step-2c boundary-filter special case. +pub const INTRA_ANGULAR_HOR: u8 = 10; +/// Table 8-1 mode index `26` — the vertical angular predictor; named for +/// the §8.4.4.2.6 step-2c boundary-filter special case. +pub const INTRA_ANGULAR_VER: u8 = 26; + +/// §8.4.4.2.1 colour-component selector (`cIdx`). Only the bit-depth and +/// the luma-only boundary-filter / strong-smoothing gates branch on it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Component { + /// `cIdx == 0` — luma. Uses `BitDepthY`; enables the §8.4.4.2.5 / + /// §8.4.4.2.6 boundary filters and §8.4.4.2.3 strong smoothing. + Luma, + /// `cIdx == 1` — Cb chroma. Uses `BitDepthC`. + Cb, + /// `cIdx == 2` — Cr chroma. Uses `BitDepthC`. + Cr, +} + +impl Component { + /// `true` for the luma component (`cIdx == 0`). + #[inline] + #[must_use] + pub fn is_luma(self) -> bool { + matches!(self, Component::Luma) + } +} + +/// Errors from the §8.4.4.2 intra-prediction processes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum IntraPredError { + /// `nTbS` (the `1 << log2TrafoSize` block side) was not one of the + /// four legal transform-block sizes (4, 8, 16, 32). + InvalidBlockSize(usize), + /// A neighbour-sample array did not hold exactly `4 * nTbS + 1` + /// elements (the count the spec dimensions `p[ ][ ]` for). + LengthMismatch { + /// The `4 * nTbS + 1` count the block requires. + expected: usize, + /// The element count actually supplied. + got: usize, + }, + /// `predModeIntra` was outside the Table 8-1 range `0..=34`. + InvalidMode(u8), + /// `bitDepth` was outside the 8..=16 range the equations are + /// dimensioned for. + InvalidBitDepth(u8), +} + +impl core::fmt::Display for IntraPredError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::InvalidBlockSize(n) => { + write!( + f, + "invalid transform block size nTbS = {n} (expected 4/8/16/32)" + ) + } + Self::LengthMismatch { expected, got } => { + write!(f, "neighbour array length {got} != 4*nTbS+1 = {expected}") + } + Self::InvalidMode(m) => { + write!(f, "invalid predModeIntra {m} (expected 0..=34)") + } + Self::InvalidBitDepth(b) => write!(f, "invalid bitDepth {b} (expected 8..=16)"), + } + } +} + +impl std::error::Error for IntraPredError {} + +/// `true` for the four legal transform-block sides (4, 8, 16, 32). +#[inline] +fn is_legal_tbs(n_tbs: usize) -> bool { + matches!(n_tbs, 4 | 8 | 16 | 32) +} + +/// `log2( nTbS )` for a legal transform-block side. +#[inline] +fn log2_tbs(n_tbs: usize) -> u32 { + n_tbs.trailing_zeros() +} + +/// The `nTbS * 4 + 1` neighbouring reference samples `p[ x ][ y ]` of one +/// transform block, addressed by the spec coordinates `x = −1, +/// y = −1..nTbS * 2 − 1` (the left column, including the `(−1,−1)` +/// corner) and `x = 0..nTbS * 2 − 1, y = −1` (the top row). +/// +/// The samples are stored as two slices plus the shared corner so the +/// spec accessors `p( x, y )` map onto contiguous memory: +/// +/// * `corner` is `p[ −1 ][ −1 ]`. +/// * `left[ i ]` is `p[ −1 ][ i ]` for `i = 0..2 * nTbS − 1`. +/// * `top[ i ]` is `p[ i ][ −1 ]` for `i = 0..2 * nTbS − 1`. +/// +/// `available` mirrors the same layout (`corner`, then the `left` run, +/// then the `top` run) and records the §8.4.4.2.1 "available for intra +/// prediction" marking of each sample. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ReferenceSamples { + /// `nTbS`, the transform-block side. + n_tbs: usize, + /// `p[ −1 ][ −1 ]`. + corner: i32, + /// `p[ −1 ][ 0..2*nTbS−1 ]`, the left column. + left: Vec, + /// `p[ 0..2*nTbS−1 ][ −1 ]`, the top row. + top: Vec, +} + +impl ReferenceSamples { + /// Build a reference array from the corner, left-column and top-row + /// sample values. `left` and `top` must each hold `2 * nTbS` + /// elements; `n_tbs` must be 4 / 8 / 16 / 32. + /// + /// This constructor takes samples that are already substituted (all + /// available); use [`MarkedReferenceSamples`] when some neighbours + /// are unavailable. + pub fn new( + n_tbs: usize, + corner: i32, + left: Vec, + top: Vec, + ) -> Result { + if !is_legal_tbs(n_tbs) { + return Err(IntraPredError::InvalidBlockSize(n_tbs)); + } + let want = 2 * n_tbs; + if left.len() != want { + return Err(IntraPredError::LengthMismatch { + expected: want, + got: left.len(), + }); + } + if top.len() != want { + return Err(IntraPredError::LengthMismatch { + expected: want, + got: top.len(), + }); + } + Ok(Self { + n_tbs, + corner, + left, + top, + }) + } + + /// `nTbS`. + #[inline] + #[must_use] + pub fn n_tbs(&self) -> usize { + self.n_tbs + } + + /// `p[ −1 ][ y ]` for `y = −1..2 * nTbS − 1`. + /// + /// `y == -1` is the corner; `y` in `0..2*nTbS-1` indexes the left + /// column. + #[inline] + #[must_use] + pub fn left(&self, y: i32) -> i32 { + if y < 0 { + self.corner + } else { + self.left[y as usize] + } + } + + /// `p[ x ][ −1 ]` for `x = −1..2 * nTbS − 1`. + /// + /// `x == -1` is the corner; `x` in `0..2*nTbS-1` indexes the top row. + #[inline] + #[must_use] + pub fn top(&self, x: i32) -> i32 { + if x < 0 { + self.corner + } else { + self.top[x as usize] + } + } + + /// `p[ −1 ][ −1 ]`. + #[inline] + #[must_use] + pub fn corner(&self) -> i32 { + self.corner + } +} + +/// A reference array whose samples carry the §8.4.4.2.1 "available for +/// intra prediction" marking. Feeds the §8.4.4.2.2 substitution process +/// ([`substitute_reference_samples`]). +/// +/// The layout mirrors [`ReferenceSamples`]: a corner, a left column of +/// `2 * nTbS` samples, and a top row of `2 * nTbS` samples, each paired +/// with its availability flag. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MarkedReferenceSamples { + /// `nTbS`, the transform-block side. + n_tbs: usize, + /// `p[ −1 ][ −1 ]` and its availability. + corner: (i32, bool), + /// `p[ −1 ][ 0..2*nTbS−1 ]` and their availability. + left: Vec<(i32, bool)>, + /// `p[ 0..2*nTbS−1 ][ −1 ]` and their availability. + top: Vec<(i32, bool)>, +} + +impl MarkedReferenceSamples { + /// Build a marked reference array. `left` and `top` must each hold + /// `2 * nTbS` `(value, available)` pairs; `n_tbs` must be 4/8/16/32. + pub fn new( + n_tbs: usize, + corner: (i32, bool), + left: Vec<(i32, bool)>, + top: Vec<(i32, bool)>, + ) -> Result { + if !is_legal_tbs(n_tbs) { + return Err(IntraPredError::InvalidBlockSize(n_tbs)); + } + let want = 2 * n_tbs; + if left.len() != want { + return Err(IntraPredError::LengthMismatch { + expected: want, + got: left.len(), + }); + } + if top.len() != want { + return Err(IntraPredError::LengthMismatch { + expected: want, + got: top.len(), + }); + } + Ok(Self { + n_tbs, + corner, + left, + top, + }) + } + + /// `nTbS`. + #[inline] + #[must_use] + pub fn n_tbs(&self) -> usize { + self.n_tbs + } +} + +/// §8.4.4.2.2 — reference sample substitution process. +/// +/// Returns a fully-available [`ReferenceSamples`] derived from the +/// availability-marked `marked` input. `bit_depth` is `BitDepthY` for +/// luma or `BitDepthC` for chroma; it supplies the mid-level fallback +/// `1 << ( bitDepth − 1 )` used when no neighbour is available. +/// +/// The substitution sweep visits the samples in the spec's reverse +/// raster order — `p[ −1 ][ 2*nTbS−1 ]` down to `p[ −1 ][ −1 ]`, then +/// `p[ 0 ][ −1 ]` to `p[ 2*nTbS−1 ][ −1 ]` — filling each unavailable +/// sample from the previously-visited neighbour. +pub fn substitute_reference_samples( + marked: &MarkedReferenceSamples, + bit_depth: u8, +) -> Result { + if !(8..=16).contains(&bit_depth) { + return Err(IntraPredError::InvalidBitDepth(bit_depth)); + } + let n = marked.n_tbs; + let len = 2 * n; // length of each of the left / top runs + + // Flatten into a single sequence indexed by the substitution sweep + // order: index 0 = p[ −1 ][ 2*nTbS−1 ] (the bottom of the left + // column), descending the left column to index (len−1) = + // p[ −1 ][ 0 ], index `len` = p[ −1 ][ −1 ] (the corner), then + // ascending the top row index (len+1) = p[ 0 ][ −1 ] to index + // (2*len) = p[ 2*nTbS−1 ][ −1 ]. + // + // Equivalently this is "start at bottom-left, walk to the corner, + // walk to top-right" — the order in which step 1's search and + // step 2/3's propagation both proceed. + let total = 2 * len + 1; + let mut val = vec![0i32; total]; + let mut avail = vec![false; total]; + for i in 0..len { + // left[ 2*nTbS−1−i ] sits at sweep index i. + let (v, a) = marked.left[len - 1 - i]; + val[i] = v; + avail[i] = a; + } + val[len] = marked.corner.0; + avail[len] = marked.corner.1; + for i in 0..len { + let (v, a) = marked.top[i]; + val[len + 1 + i] = v; + avail[len + 1 + i] = a; + } + + if avail.iter().all(|&a| !a) { + // All neighbours unavailable: substitute the mid-level value. + let mid = 1i32 << (bit_depth - 1); + val.iter_mut().for_each(|v| *v = mid); + } else { + // Step 1: when the first sweep sample (p[ −1 ][ 2*nTbS−1 ]) is + // unavailable, seed it from the first available sample found by + // sweeping forward. + if !avail[0] { + if let Some(first) = (0..total).find(|&i| avail[i]) { + val[0] = val[first]; + } + avail[0] = true; + } + // Steps 2 & 3: propagate forward — each unavailable sample takes + // its predecessor's value. (Step 2 climbs the left column toward + // the corner; step 3 walks the top row; both are this single + // forward pass in sweep order.) + for i in 1..total { + if !avail[i] { + val[i] = val[i - 1]; + avail[i] = true; + } + } + } + + // Un-flatten back into corner / left / top. + let mut left = vec![0i32; len]; + for i in 0..len { + left[len - 1 - i] = val[i]; + } + let corner = val[len]; + let mut top = vec![0i32; len]; + top[..len].copy_from_slice(&val[len + 1..len + 1 + len]); + + Ok(ReferenceSamples { + n_tbs: n, + corner, + left, + top, + }) +} + +/// Table 8-4 — `intraHorVerDistThres[ nTbS ]`. Returns `None` for +/// `nTbS == 4` (the §8.4.4.2.3 `filterFlag` is unconditionally 0 there). +#[inline] +fn intra_hor_ver_dist_thres(n_tbs: usize) -> Option { + match n_tbs { + 8 => Some(7), + 16 => Some(1), + 32 => Some(0), + _ => None, + } +} + +/// §8.4.4.2.3 `filterFlag` derivation (without applying the filter). +/// +/// `true` when the `[1 2 1]` / bi-linear neighbour smoothing must run for +/// the given mode and block size; `false` for `INTRA_DC`, `nTbS == 4`, or +/// when `minDistVerHor` does not exceed `intraHorVerDistThres[ nTbS ]`. +#[must_use] +pub fn reference_filter_flag(pred_mode_intra: u8, n_tbs: usize) -> bool { + if pred_mode_intra == INTRA_DC || n_tbs == 4 { + return false; + } + let thres = match intra_hor_ver_dist_thres(n_tbs) { + Some(t) => t, + None => return false, + }; + let m = i32::from(pred_mode_intra); + let min_dist_ver_hor = (m - 26).abs().min((m - 10).abs()); + min_dist_ver_hor > thres +} + +/// §8.4.4.2.3 — filtering process of neighbouring samples. +/// +/// Returns the filtered reference array `pF`. The caller is responsible +/// for the §8.4.4.2.1 step-1 gate (`intra_smoothing_disabled_flag == 0` +/// and `cIdx == 0 || ChromaArrayType == 3`); this routine applies the +/// `filterFlag` (Table 8-4) and `biIntFlag` (strong-smoothing) tests +/// internally and returns the input unchanged when `filterFlag == 0`. +/// +/// `bit_depth_luma` is `BitDepthY` (the §8.4.4.2.3 `biIntFlag` +/// `1 << ( BitDepthY − 5 )` threshold reads it, but `biIntFlag` itself is +/// gated on `cIdx == 0`). +#[must_use] +pub fn filter_reference_samples( + p: &ReferenceSamples, + pred_mode_intra: u8, + strong_intra_smoothing_enabled: bool, + cidx: Component, + bit_depth_luma: u8, +) -> ReferenceSamples { + let n = p.n_tbs; + if !reference_filter_flag(pred_mode_intra, n) { + return p.clone(); + } + + // biIntFlag (equations 8-36..8-40 gate). + let bi_int = strong_intra_smoothing_enabled + && cidx.is_luma() + && n == 32 + && (p.top(-1) + p.top(2 * n as i32 - 1) - 2 * p.top(n as i32 - 1)).abs() + < (1i32 << (bit_depth_luma - 5)) + && (p.left(-1) + p.left(2 * n as i32 - 1) - 2 * p.left(n as i32 - 1)).abs() + < (1i32 << (bit_depth_luma - 5)); + + let len = 2 * n; + let mut left = vec![0i32; len]; + let mut top = vec![0i32; len]; + let corner; + + if bi_int { + // n == 32, so 2*n-1 == 63. Equations 8-36..8-40. + corner = p.corner(); + let p_left_63 = p.left(63); + let p_top_63 = p.top(63); + let p_corner = p.corner(); + for y in 0..=62 { + // pF[ −1 ][ y ] = ((63−y)*p[−1][−1] + (y+1)*p[−1][63] + 32) >> 6 + // (eq 8-37, y = 0..62 INCLUSIVE — 63 interpolated samples). + left[y as usize] = ((63 - y) * p_corner + (y + 1) * p_left_63 + 32) >> 6; + } + left[63] = p_left_63; + for x in 0..=62 { + // eq 8-39, x = 0..62 inclusive. + top[x as usize] = ((63 - x) * p_corner + (x + 1) * p_top_63 + 32) >> 6; + } + top[63] = p_top_63; + } else { + // Equations 8-41..8-45, the [1 2 1] >> 2 smoothing. + corner = (p.left(0) + 2 * p.corner() + p.top(0) + 2) >> 2; + let last = 2 * n as i32 - 1; + for y in 0..=(last - 1) { + // pF[ −1 ][ y ] = (p[−1][y+1] + 2*p[−1][y] + p[−1][y−1] + 2) >> 2 + left[y as usize] = (p.left(y + 1) + 2 * p.left(y) + p.left(y - 1) + 2) >> 2; + } + left[last as usize] = p.left(last); + for x in 0..=(last - 1) { + top[x as usize] = (p.top(x - 1) + 2 * p.top(x) + p.top(x + 1) + 2) >> 2; + } + top[last as usize] = p.top(last); + } + + ReferenceSamples { + n_tbs: n, + corner, + left, + top, + } +} + +/// §8.4.4.2.4 — `INTRA_PLANAR` predictor (equation 8-46). +/// +/// Returns the `(nTbS)x(nTbS)` predicted samples in row-major order +/// (`pred[ y * nTbS + x ]` is `predSamples[ x ][ y ]`). +#[must_use] +pub fn predict_planar(p: &ReferenceSamples) -> Vec { + let n = p.n_tbs; + let ni = n as i32; + let shift = log2_tbs(n) + 1; + let p_top_n = p.top(ni); // p[ nTbS ][ −1 ] + let p_left_n = p.left(ni); // p[ −1 ][ nTbS ] + let mut pred = vec![0i32; n * n]; + for y in 0..ni { + let p_left_y = p.left(y); // p[ −1 ][ y ] + for x in 0..ni { + let p_top_x = p.top(x); // p[ x ][ −1 ] + let v = (ni - 1 - x) * p_left_y + + (x + 1) * p_top_n + + (ni - 1 - y) * p_top_x + + (y + 1) * p_left_n + + ni; + pred[(y * ni + x) as usize] = v >> shift; + } + } + pred +} + +/// §8.4.4.2.5 — `INTRA_DC` predictor (equations 8-47..8-52). +/// +/// `disable_boundary_filter` is `intra_boundary_filtering_disabled_flag`; +/// when it is set, the equation 8-48..8-51 boundary smoothing is skipped +/// (equation 8-52 applies for all samples). The boundary smoothing +/// additionally only runs for luma blocks smaller than 32. +/// +/// Returns the `(nTbS)x(nTbS)` predicted samples row-major. +#[must_use] +pub fn predict_dc( + p: &ReferenceSamples, + cidx: Component, + disable_boundary_filter: bool, +) -> Vec { + let n = p.n_tbs; + let ni = n as i32; + let k = log2_tbs(n); + + // dcVal (equation 8-47): sum of the first nTbS top + nTbS left + // samples, plus nTbS, then >> (k + 1). + let mut sum = 0i32; + for x in 0..ni { + sum += p.top(x); + } + for y in 0..ni { + sum += p.left(y); + } + let dc_val = (sum + ni) >> (k + 1); + + let mut pred = vec![dc_val; n * n]; + + if cidx.is_luma() && !disable_boundary_filter && n < 32 { + // Equation 8-48: predSamples[0][0] + pred[0] = (p.left(0) + 2 * dc_val + p.top(0) + 2) >> 2; + // Equation 8-49: predSamples[x][0] for x = 1..nTbS−1 + for x in 1..ni { + pred[x as usize] = (p.top(x) + 3 * dc_val + 2) >> 2; + } + // Equation 8-50: predSamples[0][y] for y = 1..nTbS−1 + for y in 1..ni { + pred[(y * ni) as usize] = (p.left(y) + 3 * dc_val + 2) >> 2; + } + // Equation 8-51 (predSamples[x][y] = dcVal for x,y = 1..) already + // holds from the dc_val fill. + } + + pred +} + +/// Table 8-5 — `intraPredAngle[ predModeIntra ]` for the angular modes +/// `2..=34`. +#[inline] +fn intra_pred_angle(pred_mode_intra: u8) -> i32 { + // Index 2 maps to the first entry; modes 0/1 are not angular. + const ANGLE: [i32; 35] = [ + 0, 0, // 0,1 unused (planar / DC) + 32, 26, 21, 17, 13, 9, 5, 2, 0, // 2..10 + -2, -5, -9, -13, -17, -21, -26, -32, // 11..18 + -26, -21, -17, -13, -9, -5, -2, 0, // 19..26 + 2, 5, 9, 13, 17, 21, 26, 32, // 27..34 + ]; + ANGLE[pred_mode_intra as usize] +} + +/// Table 8-6 — `invAngle[ predModeIntra ]` for the modes `11..=25` (the +/// negative-angle band that extends the main reference array). +#[inline] +fn inv_angle(pred_mode_intra: u8) -> i32 { + match pred_mode_intra { + 11 | 25 => -4096, + 12 | 24 => -1638, + 13 | 23 => -910, + 14 | 22 => -630, + 15 | 21 => -482, + 16 | 20 => -390, + 17 | 19 => -315, + 18 => -256, + _ => 0, + } +} + +/// Clip a value to the `[ 0, ( 1 << bitDepth ) − 1 ]` sample range +/// (`Clip1Y` / `Clip1C` of equations 5-5 / 5-6). +#[inline] +fn clip1(v: i32, bit_depth: u8) -> i32 { + v.clamp(0, (1i32 << bit_depth) - 1) +} + +/// §8.4.4.2.6 — angular predictor for `INTRA_ANGULAR2..INTRA_ANGULAR34`. +/// +/// `bit_depth` is `BitDepthY` for luma (used by the equation 8-60 / 8-68 +/// `Clip1Y` boundary filter; for chroma the filter does not run). +/// `disable_boundary_filter` is the §8.4.4.2.6 `disableIntraBoundaryFilter` +/// derived variable. Returns the `(nTbS)x(nTbS)` predicted samples +/// row-major. +/// +/// Returns [`IntraPredError::InvalidMode`] for non-angular modes. +pub fn predict_angular( + p: &ReferenceSamples, + pred_mode_intra: u8, + cidx: Component, + bit_depth: u8, + disable_boundary_filter: bool, +) -> Result, IntraPredError> { + if !(2..=34).contains(&pred_mode_intra) { + return Err(IntraPredError::InvalidMode(pred_mode_intra)); + } + let n = p.n_tbs; + let ni = n as i32; + let angle = intra_pred_angle(pred_mode_intra); + let mut pred = vec![0i32; n * n]; + + if pred_mode_intra >= 18 { + // Vertical-ish: main reference is the top row. + // ref index range: −nTbS..2*nTbS (negative side filled via invAngle). + let off = (2 * n) as i32; // bias so ref index 0 lands here + let ref_len = 4 * n + 1; + let mut refa = vec![0i32; ref_len]; + + // ref[ x ] = p[ −1 + x ][ −1 ], x = 0..nTbS (equation 8-53) + for x in 0..=ni { + refa[(x + off) as usize] = p.top(-1 + x); + } + if angle < 0 { + let limit = (ni * angle) >> 5; + if limit < -1 { + // equation 8-54 + let ia = inv_angle(pred_mode_intra); + for x in (limit..=-1).rev() { + refa[(x + off) as usize] = p.top_negative_extend_vertical(ia, x); + } + } + } else { + // equation 8-55: ref[ x ] = p[ −1 + x ][ −1 ], x = nTbS+1..2*nTbS + for x in (ni + 1)..=(2 * ni) { + refa[(x + off) as usize] = p.top(-1 + x); + } + } + + for y in 0..ni { + let i_idx = ((y + 1) * angle) >> 5; // equation 8-56 + let i_fact = ((y + 1) * angle) & 31; // equation 8-57 + for x in 0..ni { + let v = if i_fact != 0 { + // equation 8-58 + let a = refa[(x + i_idx + 1 + off) as usize]; + let b = refa[(x + i_idx + 2 + off) as usize]; + ((32 - i_fact) * a + i_fact * b + 16) >> 5 + } else { + // equation 8-59 + refa[(x + i_idx + 1 + off) as usize] + }; + pred[(y * ni + x) as usize] = v; + } + } + + // equation 8-60: vertical (mode 26) boundary filter, luma, nTbS<32. + if pred_mode_intra == INTRA_ANGULAR_VER + && cidx.is_luma() + && n < 32 + && !disable_boundary_filter + { + for y in 0..ni { + let v = clip1(p.top(0) + ((p.left(y) - p.corner()) >> 1), bit_depth); + pred[(y * ni) as usize] = v; + } + } + } else { + // Horizontal-ish (mode < 18): main reference is the left column. + let off = (2 * n) as i32; + let ref_len = 4 * n + 1; + let mut refa = vec![0i32; ref_len]; + + // ref[ x ] = p[ −1 ][ −1 + x ], x = 0..nTbS (equation 8-61) + for x in 0..=ni { + refa[(x + off) as usize] = p.left(-1 + x); + } + if angle < 0 { + let limit = (ni * angle) >> 5; + if limit < -1 { + let ia = inv_angle(pred_mode_intra); + for x in (limit..=-1).rev() { + // equation 8-62 + refa[(x + off) as usize] = p.left_negative_extend_horizontal(ia, x); + } + } + } else { + // equation 8-63 + for x in (ni + 1)..=(2 * ni) { + refa[(x + off) as usize] = p.left(-1 + x); + } + } + + for x in 0..ni { + let i_idx = ((x + 1) * angle) >> 5; // equation 8-64 + let i_fact = ((x + 1) * angle) & 31; // equation 8-65 + for y in 0..ni { + let v = if i_fact != 0 { + // equation 8-66 + let a = refa[(y + i_idx + 1 + off) as usize]; + let b = refa[(y + i_idx + 2 + off) as usize]; + ((32 - i_fact) * a + i_fact * b + 16) >> 5 + } else { + // equation 8-67 + refa[(y + i_idx + 1 + off) as usize] + }; + pred[(y * ni + x) as usize] = v; + } + } + + // equation 8-68: horizontal (mode 10) boundary filter, luma, nTbS<32. + if pred_mode_intra == INTRA_ANGULAR_HOR + && cidx.is_luma() + && n < 32 + && !disable_boundary_filter + { + for x in 0..ni { + let v = clip1(p.left(0) + ((p.top(x) - p.corner()) >> 1), bit_depth); + pred[x as usize] = v; + } + } + } + + Ok(pred) +} + +impl ReferenceSamples { + /// equation 8-54 negative-extend sample for the vertical band: + /// `p[ −1 ][ −1 + ( ( x * invAngle + 128 ) >> 8 ) ]`. + #[inline] + fn top_negative_extend_vertical(&self, inv_angle: i32, x: i32) -> i32 { + let y = -1 + ((x * inv_angle + 128) >> 8); + self.left(y) + } + + /// equation 8-62 negative-extend sample for the horizontal band: + /// `p[ −1 + ( ( x * invAngle + 128 ) >> 8 ) ][ −1 ]`. + #[inline] + fn left_negative_extend_horizontal(&self, inv_angle: i32, x: i32) -> i32 { + let xn = -1 + ((x * inv_angle + 128) >> 8); + self.top(xn) + } +} + +/// Per-block parameters for the top-level §8.4.4.2.1 intra-prediction +/// pipeline. +#[derive(Debug, Clone, Copy)] +pub struct IntraPredParams { + /// `predModeIntra` — the Table 8-1 mode index (0..=34). + pub pred_mode_intra: u8, + /// `cIdx` — the colour component. + pub cidx: Component, + /// `BitDepthY` (luma) or `BitDepthC` (chroma) of the component. + pub bit_depth: u8, + /// `BitDepthY` — read by the §8.4.4.2.3 `biIntFlag` threshold even + /// for the chroma path. Set equal to `bit_depth` for luma. + pub bit_depth_luma: u8, + /// `intra_smoothing_disabled_flag` (§8.4.4.2.1 step 1 gate). + pub intra_smoothing_disabled: bool, + /// `strong_intra_smoothing_enabled_flag` (§8.4.4.2.3 `biIntFlag`). + pub strong_intra_smoothing_enabled: bool, + /// `ChromaArrayType == 3` — needed for the step-1 filtering gate on + /// the chroma path. + pub chroma_array_type_3: bool, + /// `disableIntraBoundaryFilter` (§8.4.4.2.5 / §8.4.4.2.6). + pub disable_boundary_filter: bool, +} + +/// §8.4.4.2.1 steps 1 and 2 — given an already-substituted reference +/// array `p`, applies the §8.4.4.2.3 filtering (when the step-1 gate +/// holds) and dispatches to the planar / DC / angular predictor. +/// +/// Returns the `(nTbS)x(nTbS)` predicted samples row-major +/// (`pred[ y * nTbS + x ]` is `predSamples[ x ][ y ]`). +pub fn intra_predict( + p: &ReferenceSamples, + params: &IntraPredParams, +) -> Result, IntraPredError> { + if params.pred_mode_intra > 34 { + return Err(IntraPredError::InvalidMode(params.pred_mode_intra)); + } + if !(8..=16).contains(¶ms.bit_depth) { + return Err(IntraPredError::InvalidBitDepth(params.bit_depth)); + } + + // Step 1: filtering gate — intra_smoothing_disabled_flag == 0 AND + // (cIdx == 0 OR ChromaArrayType == 3). + let filter_gate = + !params.intra_smoothing_disabled && (params.cidx.is_luma() || params.chroma_array_type_3); + let filtered; + let pp: &ReferenceSamples = if filter_gate { + filtered = filter_reference_samples( + p, + params.pred_mode_intra, + params.strong_intra_smoothing_enabled, + params.cidx, + params.bit_depth_luma, + ); + &filtered + } else { + p + }; + + // Step 2: predictor dispatch. + let pred = match params.pred_mode_intra { + INTRA_PLANAR => predict_planar(pp), + INTRA_DC => predict_dc(pp, params.cidx, params.disable_boundary_filter), + m => predict_angular( + pp, + m, + params.cidx, + params.bit_depth, + params.disable_boundary_filter, + )?, + }; + Ok(pred) +} + +/// Full §8.4.4.2.1 pipeline from an availability-marked array: runs the +/// §8.4.4.2.2 substitution, then [`intra_predict`]. +pub fn intra_predict_with_substitution( + marked: &MarkedReferenceSamples, + params: &IntraPredParams, +) -> Result, IntraPredError> { + let p = substitute_reference_samples(marked, params.bit_depth)?; + intra_predict(&p, params) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Helper: build a constant-valued (all-available) reference array. + fn const_ref(n: usize, v: i32) -> ReferenceSamples { + ReferenceSamples::new(n, v, vec![v; 2 * n], vec![v; 2 * n]).unwrap() + } + + // ---- §8.4.4.2.2 reference sample substitution ---- + + #[test] + fn substitution_all_unavailable_yields_midlevel() { + // Every neighbour marked not-available -> 1 << (bitDepth − 1). + let n = 4; + let m = MarkedReferenceSamples::new( + n, + (0, false), + vec![(0, false); 2 * n], + vec![(0, false); 2 * n], + ) + .unwrap(); + let p = substitute_reference_samples(&m, 8).unwrap(); + assert_eq!(p.corner(), 128); + for y in 0..(2 * n as i32) { + assert_eq!(p.left(y), 128); + } + for x in 0..(2 * n as i32) { + assert_eq!(p.top(x), 128); + } + // 10-bit -> 512. + let p10 = substitute_reference_samples(&m, 10).unwrap(); + assert_eq!(p10.corner(), 512); + } + + #[test] + fn substitution_partial_sweep_propagates_from_bottom_left() { + // nTbS = 4: left run length 8, top run length 8. + // Mark only one available sample at the bottom of the left column + // (left[7] = p[−1][7], the sweep start). Everything else copies it. + let n = 4; + let mut left = vec![(0, false); 2 * n]; + left[7] = (77, true); + let top = vec![(0, false); 2 * n]; + let m = MarkedReferenceSamples::new(n, (0, false), left, top).unwrap(); + let p = substitute_reference_samples(&m, 8).unwrap(); + // Whole array becomes 77. + assert_eq!(p.corner(), 77); + for y in 0..(2 * n as i32) { + assert_eq!(p.left(y), 77); + } + for x in 0..(2 * n as i32) { + assert_eq!(p.top(x), 77); + } + } + + #[test] + fn substitution_step1_seed_from_first_available_when_start_unavail() { + // Start sample p[−1][7] unavailable; first available is top[3]. + // Step 1 seeds p[−1][7] from that, then forward propagation fills. + let n = 4; + let left = vec![(0, false); 2 * n]; + let mut top = vec![(0, false); 2 * n]; + top[3] = (42, true); + let m = MarkedReferenceSamples::new(n, (0, false), left, top).unwrap(); + let p = substitute_reference_samples(&m, 8).unwrap(); + // Sweep: left[7..0] (=p[−1][7..0]), corner, top[0..7]. + // left all unavail -> seeded 42 at start, propagate 42 forward. + // corner unavail -> 42. top[0..2] unavail -> 42. top[3]=42. + // top[4..7] copy 42. + assert_eq!(p.corner(), 42); + assert_eq!(p.left(0), 42); + assert_eq!(p.left(7), 42); + assert_eq!(p.top(3), 42); + assert_eq!(p.top(7), 42); + } + + #[test] + fn substitution_preserves_available_values() { + // Available samples must be left untouched; only gaps fill. + let n = 4; + // left[i] = p[−1][i]; mark all left available with distinct values. + let left: Vec<(i32, bool)> = (0..2 * n).map(|i| (i as i32 + 1, true)).collect(); + // top all unavailable -> fill from the corner direction. + let top = vec![(0, false); 2 * n]; + let m = MarkedReferenceSamples::new(n, (99, true), left, top).unwrap(); + let p = substitute_reference_samples(&m, 8).unwrap(); + assert_eq!(p.corner(), 99); + for i in 0..(2 * n) { + assert_eq!(p.left(i as i32), i as i32 + 1); + } + // top[0] copies p[−1][−1] = corner = 99 (step 3 from x−1). + assert_eq!(p.top(0), 99); + assert_eq!(p.top(7), 99); + } + + // ---- §8.4.4.2.3 filter flag (Table 8-4) ---- + + #[test] + fn filter_flag_table_8_4() { + // nTbS == 4 -> never filter. + assert!(!reference_filter_flag(2, 4)); + // INTRA_DC -> never filter. + assert!(!reference_filter_flag(INTRA_DC, 16)); + // nTbS == 8, thres = 7: planar minDist = min(|0−26|,|0−10|)=10 > 7. + assert!(reference_filter_flag(INTRA_PLANAR, 8)); + // mode 26 (vertical): minDist = 0, not > 7 -> no filter. + assert!(!reference_filter_flag(26, 8)); + // mode 18 (the diagonal): |18−26|=8, |18−10|=8 -> 8 > 7 -> filter. + assert!(reference_filter_flag(18, 8)); + // nTbS == 32, thres = 0: mode 25 minDist = min(1,15)=1 > 0 -> filter. + assert!(reference_filter_flag(25, 32)); + // mode 26 minDist=0, not > 0 -> no filter even at 32. + assert!(!reference_filter_flag(26, 32)); + } + + #[test] + fn filter_constant_array_is_idempotent() { + // [1 2 1]>>2 of a constant returns the constant (boundary terms + // copy through unchanged). + let n = 8; + let p = const_ref(n, 100); + let f = filter_reference_samples(&p, INTRA_PLANAR, false, Component::Luma, 8); + for y in 0..(2 * n as i32) { + assert_eq!(f.left(y), 100); + } + for x in 0..(2 * n as i32) { + assert_eq!(f.top(x), 100); + } + assert_eq!(f.corner(), 100); + } + + #[test] + fn strong_smoothing_bilinear_covers_every_index() { + // §8.4.4.2.3 eqs 8-36..8-40: a perfectly linear 32-block ramp + // trips biIntFlag (second differences are 0), and the bi-linear + // interpolation of a linear ramp reproduces the ramp EXACTLY at + // every index 0..=63 — including index 62, which eq 8-37/8-39 + // covers (the spec's "y = 0..62" is inclusive). + let n = 32usize; + // corner 64; left[y] = 65 + y; top[x] = 65 + x (slope 1). + let left: Vec = (0..2 * n as i32).map(|y| 65 + y).collect(); + let top: Vec = (0..2 * n as i32).map(|x| 65 + x).collect(); + let p = ReferenceSamples::new(n, 64, left, top).unwrap(); + // Mode 2 (angular, far from H/V) ⇒ filterFlag = 1 at nTbS 32. + let f = filter_reference_samples(&p, 2, true, Component::Luma, 8); + assert_eq!(f.corner(), 64); + for i in 0..64i32 { + // ((63−i)*64 + (i+1)*128 + 32) >> 6 == 65 + i for a slope-1 + // ramp (and index 63 copies p[63] = 128 directly). + assert_eq!(f.left(i), 65 + i, "pF[-1][{i}]"); + assert_eq!(f.top(i), 65 + i, "pF[{i}][-1]"); + } + } + + // ---- §8.4.4.2.4 planar ---- + + #[test] + fn planar_constant_neighbours() { + // All neighbours = 50 -> every predicted sample = 50. + let n = 8; + let p = const_ref(n, 50); + let pred = predict_planar(&p); + assert!(pred.iter().all(|&v| v == 50)); + } + + #[test] + fn planar_equation_8_46_handworked() { + // 4x4. Set distinctive boundaries and verify eq 8-46 at one cell. + // p[−1][y] (left): index y. p[x][−1] (top): index x. + // p[nTbS][−1] = top(4); p[−1][nTbS] = left(4). + let n = 4; + let left: Vec = vec![10, 20, 30, 40, 50, 60, 70, 80]; // y=0..7 + let top: Vec = vec![11, 21, 31, 41, 51, 61, 71, 81]; // x=0..7 + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + let pred = predict_planar(&p); + // predSamples[2][1] (x=2, y=1): + // ((4−1−2)*p[−1][1] + (2+1)*p[4][−1] + // + (4−1−1)*p[2][−1] + (1+1)*p[−1][4] + 4) >> 3 + // = (1*20 + 3*51 + 2*31 + 2*50 + 4) >> 3 + // = (20 + 153 + 62 + 100 + 4) >> 3 = 339 >> 3 = 42 + assert_eq!(pred[4 + 2], 42); + } + + // ---- §8.4.4.2.5 DC ---- + + #[test] + fn dc_constant_neighbours_luma_boundary() { + // All neighbours 100; dcVal = 100; boundary filter keeps 100. + let n = 8; + let p = const_ref(n, 100); + let pred = predict_dc(&p, Component::Luma, false); + assert!(pred.iter().all(|&v| v == 100)); + } + + #[test] + fn dc_value_equation_8_47() { + // 4x4. top = 8,8,8,8 (first 4), left = 16,16,16,16. + // dcVal = (sum_top4 + sum_left4 + nTbS) >> (k+1) + // = (32 + 64 + 4) >> 3 = 100 >> 3 = 12. + let n = 4; + let top = vec![8, 8, 8, 8, 0, 0, 0, 0]; + let left = vec![16, 16, 16, 16, 0, 0, 0, 0]; + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + // Chroma path: no boundary filter, all samples = dcVal. + let pred = predict_dc(&p, Component::Cb, false); + assert!(pred.iter().all(|&v| v == 12)); + } + + #[test] + fn dc_boundary_filter_luma_small_block() { + // dcVal as above = 12 (use 4x4 luma). Verify eqs 8-48..8-50. + let n = 4; + let top = vec![8, 8, 8, 8, 0, 0, 0, 0]; + let left = vec![16, 16, 16, 16, 0, 0, 0, 0]; + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + let pred = predict_dc(&p, Component::Luma, false); + // pred[0][0] = (p[−1][0] + 2*dc + p[0][−1] + 2) >> 2 + // = (16 + 24 + 8 + 2) >> 2 = 50 >> 2 = 12 + assert_eq!(pred[0], 12); + // pred[1][0] = (p[1][−1] + 3*dc + 2) >> 2 = (8 + 36 + 2) >> 2 = 11 + assert_eq!(pred[1], 11); + // pred[0][1] = (p[−1][1] + 3*dc + 2) >> 2 = (16 + 36 + 2) >> 2 = 13 + assert_eq!(pred[4], 13); + // interior stays dcVal. + assert_eq!(pred[4 + 1], 12); + } + + #[test] + fn dc_boundary_filter_skipped_when_disabled() { + let n = 4; + let top = vec![8, 8, 8, 8, 0, 0, 0, 0]; + let left = vec![16, 16, 16, 16, 0, 0, 0, 0]; + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + let pred = predict_dc(&p, Component::Luma, true); + assert!(pred.iter().all(|&v| v == 12)); + } + + // ---- §8.4.4.2.6 angular ---- + + #[test] + fn angular_vertical_angle_zero_copies_top_row() { + // Mode 26, angle 0: predSamples[x][y] = p[x][−1] for all y. + // Use chroma to bypass the eq 8-60 boundary filter. + let n = 4; + let top = vec![10, 20, 30, 40, 0, 0, 0, 0]; + let left = vec![0; 8]; + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + let pred = predict_angular(&p, 26, Component::Cb, 8, false).unwrap(); + for y in 0usize..4 { + assert_eq!(pred[y * 4], 10); + assert_eq!(pred[y * 4 + 1], 20); + assert_eq!(pred[y * 4 + 2], 30); + assert_eq!(pred[y * 4 + 3], 40); + } + } + + #[test] + fn angular_horizontal_angle_zero_copies_left_column() { + // Mode 10, angle 0: predSamples[x][y] = p[−1][y] for all x. + let n = 4; + let left = vec![10, 20, 30, 40, 0, 0, 0, 0]; + let top = vec![0; 8]; + let p = ReferenceSamples::new(n, 0, left, top).unwrap(); + let pred = predict_angular(&p, 10, Component::Cb, 8, false).unwrap(); + for x in 0usize..4 { + assert_eq!(pred[x], 10); + assert_eq!(pred[4 + x], 20); + assert_eq!(pred[8 + x], 30); + assert_eq!(pred[12 + x], 40); + } + } + + #[test] + fn angular_positive_angle_pure_index_no_frac() { + // Mode 34, angle 32: iIdx = ((y+1)*32)>>5 = y+1, iFact = 0. + // predSamples[x][y] = ref[x + (y+1) + 1] = ref[x+y+2]. + // ref[k] = p[−1+k][−1] for k=0..2*nTbS. Make top row a ramp so + // ref[k] = k (with p[k−1][−1] = k−1+1). Set top[i] = i+1 so + // p[i][−1] = i+1, ref[k]=p[k−1][−1]=k. + let n = 4; + let top: Vec = (0..8).map(|i| i + 1).collect(); // p[i][−1] = i+1 + let left = vec![top[0]; 8]; // corner-ish; not read for mode 34 vertical + let p = ReferenceSamples::new(n, top[0], left, top).unwrap(); + let pred = predict_angular(&p, 34, Component::Cb, 8, false).unwrap(); + // ref[k] = p[k−1][−1]; p[−1][−1]=corner=1, p[i][−1]=i+1. + // ref[0]=p[−1][−1]=1, ref[k]=k for k>=1. + for y in 0..4 { + for x in 0..4 { + let k = x + y + 2; + let expect = if k == 0 { 1 } else { k }; + assert_eq!(pred[(y * 4 + x) as usize], expect, "x={x} y={y}"); + } + } + } + + #[test] + fn angular_invalid_mode_rejected() { + let p = const_ref(4, 50); + assert_eq!( + predict_angular(&p, 1, Component::Luma, 8, false), + Err(IntraPredError::InvalidMode(1)) + ); + assert_eq!( + predict_angular(&p, 35, Component::Luma, 8, false), + Err(IntraPredError::InvalidMode(35)) + ); + } + + // ---- §8.4.4.2.1 top-level pipeline ---- + + #[test] + fn pipeline_dispatch_matches_subprocess() { + let n = 8; + let p = const_ref(n, 130); + let params = IntraPredParams { + pred_mode_intra: INTRA_PLANAR, + cidx: Component::Luma, + bit_depth: 8, + bit_depth_luma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: false, + chroma_array_type_3: false, + disable_boundary_filter: false, + }; + let pred = intra_predict(&p, ¶ms).unwrap(); + // Constant neighbours -> planar yields the constant; filtering of + // a constant is idempotent so the value is unchanged. + assert!(pred.iter().all(|&v| v == 130)); + } + + #[test] + fn pipeline_with_substitution_runs_end_to_end() { + let n = 4; + let m = MarkedReferenceSamples::new( + n, + (0, false), + vec![(0, false); 2 * n], + vec![(0, false); 2 * n], + ) + .unwrap(); + let params = IntraPredParams { + pred_mode_intra: INTRA_DC, + cidx: Component::Luma, + bit_depth: 8, + bit_depth_luma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: false, + chroma_array_type_3: false, + disable_boundary_filter: false, + }; + // All neighbours unavailable -> substituted to 128; DC of 128 is + // 128; boundary filter of constant keeps 128. + let pred = intra_predict_with_substitution(&m, ¶ms).unwrap(); + assert!(pred.iter().all(|&v| v == 128)); + } + + #[test] + fn invalid_block_size_and_lengths_rejected() { + assert_eq!( + ReferenceSamples::new(6, 0, vec![0; 12], vec![0; 12]).unwrap_err(), + IntraPredError::InvalidBlockSize(6) + ); + assert_eq!( + ReferenceSamples::new(4, 0, vec![0; 7], vec![0; 8]).unwrap_err(), + IntraPredError::LengthMismatch { + expected: 8, + got: 7 + } + ); + } +} diff --git a/vendor/oxideav-h265/src/lib.rs b/vendor/oxideav-h265/src/lib.rs new file mode 100644 index 0000000..ca83dd3 --- /dev/null +++ b/vendor/oxideav-h265/src/lib.rs @@ -0,0 +1,616 @@ +//! # oxideav-h265 +//! +//! Pure-Rust H.265 / HEVC (ITU-T H.265 | ISO/IEC 23008-2) parser and +//! decoder, for the [oxideav](https://github.com/OxideAV/oxideav) +//! framework. +//! +//! **Status:** the decoder is end-to-end. [`decode_annexb_sequence`] / +//! [`SequenceDecoder`] decode whole Annex B byte streams to +//! output-order pictures, and [`make_decoder`] exposes the same driver +//! through the [`oxideav_core::Decoder`] registry contract (registered +//! by [`register`] under `"h265"` / `"hevc"`, accepting Annex B and +//! `hvcC` / length-prefixed transport). Every Annex B bitstream in the +//! staged 16-fixture conformance corpus decodes byte-exact, plus +//! self-built pins for explicit weighted prediction, PCM, dependent +//! slice segments and per-slice loop-filter flags. [`make_encoder`] is +//! the PCM-only IDR encoder bootstrap (lossless, conformant, every +//! packet a random access point) over the write-side stack in +//! [`encoder`] (bit writer, NAL encapsulation, the §9.3.5 CABAC +//! encoding engine, parameter-set / slice writers). See `README.md` +//! for coverage and the remaining gaps (true multi-tile fixtures, +//! encoder beyond the PCM bootstrap). +//! +//! The sections below record the per-round rebuild history of the +//! subsystems the driver composes. +//! +//! **History:** clean-room rebuild (post 2026-05-18 audit). +//! The latest round adds the §8.6.2 / §8.6.3 / §8.6.4 scaling, +//! transformation and residual-array construction step — the new +//! [`transform`] module. [`transform::scale_coefficients`] implements +//! the §8.6.3 dequantization (the `levelScale` / `m[x][y]` / +//! `1 << (qP/6)` product, `bdShift` offset-round and +//! `[coeffMin, coeffMax]` clip of equations 8-300..8-309); +//! [`transform::inverse_transform`] implements the §8.6.4 separable +//! inverse transform (the equation-8-316 4x4 DST-VII for `MODE_INTRA` +//! 4x4 luma and the equations-8-318..8-321 32x32 DCT-II with the +//! equation-8-317 column subsampling for every other block, plus the +//! equation-8-314 intermediate offset-round); and +//! [`transform::residual_block`] orchestrates the §8.6.2 dispatch over +//! `cu_transquant_bypass_flag` (the equation-8-297 `rotateCoeffs` +//! pass-through), `transform_skip_flag` (the equation-8-298 `tsShift` +//! left-shift), and the full scale-then-transform path, applying the +//! equation-8-299 final `bdShift` offset-round. +//! +//! Round 12 finishes the §7.3.2.1 VPS tail through the optional VPS +//! timing-info block ([`vps::HevcVps`] now carries `max_layer_id`, +//! `num_layer_sets_minus1`, the `layer_id_included_flag[][]` +//! inclusion matrix as [`vps::LayerIdInclusionRow`] rows, the +//! `vps_timing_info_present_flag` block as [`vps::VpsTimingInfo`] — +//! `u(32)` `num_units_in_tick` / `time_scale`, +//! `poc_proportional_to_timing_flag` + +//! `num_ticks_poc_diff_one_minus1`, and `num_hrd_parameters` — plus +//! `vps_extension_flag`); per-HRD `hrd_parameters()` bodies and the +//! extension-data payload are surfaced as +//! [`vps::HevcVps::opaque_tail`]. +//! +//! Round 11 landed the §9.3 CABAC arithmetic decoding engine +//! ([`cabac::CabacEngine`] / [`cabac::ContextModel`] / [`cabac::init_type`]): +//! the §9.3.2.6 engine-register init, the §9.3.2.2 context-variable init +//! (equations 9-4..9-7), the §9.3.4.3.2 DecodeDecision primitive (with +//! the Table 9-52 / Table 9-53 LPS-range / state-transition tables), the +//! §9.3.4.3.3 RenormD loop, the §9.3.4.3.4 DecodeBypass primitive (with +//! an MSB-first `decode_bypass_bits(n)` helper), the §9.3.4.3.5 +//! DecodeTerminate primitive, and the §9.3.4.3.6 aligned-bypass +//! alignment hook. The engine ships standalone — independent of the +//! §9.3.4.2 per-syntax-element binarization / context-index derivation +//! that the slice-data parser still needs. +//! +//! Rounds 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 land the Annex B NAL-unit +//! byte-stream walker, the §7.3.1.2 NAL header parse, the §7.3.2.1 +//! VPS structural parse (with a §7.3.3 profile_tier_level walk), the +//! full §7.3.2.2 SPS parse (through the `vui_parameters_present_flag` +//! / `sps_extension_present_flag` gates, with the VUI body and any +//! extension payload surfaced as an opaque-bytes tail), the +//! §7.3.2.3.1 PPS parse (full general body through +//! `pps_extension_present_flag`, including the tiles and +//! deblocking-control blocks; the PPS extension bodies are surfaced as +//! an opaque tail), the §7.3.6.1 slice-segment-header parse — +//! independent I-slice IDR segments end to end (round 6), and +//! independent **non-IDR I-slice** segments through the §7.3.6.1 POC + +//! short-term-RPS + long-term-RPS block end to end (round 7) — and +//! now (round 8) the §7.3.4 `scaling_list_data()` parse with the +//! §7.4.5 `ScalingList[sizeId][matrixId][i]` derivation, wired into +//! both the SPS (`sps_scaling_list_data_present_flag`) and PPS +//! (`pps_scaling_list_data_present_flag`) paths. The P/B +//! reference-list / weighted-prediction sub-structures are still +//! surfaced as an opaque tail. +//! +//! ## What works today +//! +//! * Annex B byte-stream splitting (3- and 4-byte start codes, +//! trailing-zero padding tolerance). +//! * §7.3.1.2 NAL header parse: `forbidden_zero_bit`, +//! `nal_unit_type`, `nuh_layer_id`, and `TemporalId` (derived +//! from `nuh_temporal_id_plus1`). +//! * §7.4.1.1 emulation-prevention byte strip (`0x00 0x00 0x03` → +//! `0x00 0x00`). +//! * MSB-first bit reader with `u(n)` and 0-th-order +//! unsigned-Exp-Golomb `ue(v)` (§9.2) descriptors. +//! * §7.3.2.1 [`vps::HevcVps`] — vps_id, base-layer / max-layers / +//! sub-layers / temporal-nesting flags, reserved-0xFFFF validation, +//! the §7.3.3 profile_tier_level walk (general profile + level + +//! per-sub-layer present-flag gates and `sub_layer_level_idc`), and +//! the per-sub-layer DPB / reorder / latency triple loop. +//! * §7.3.2.2 [`sps::SeqParameterSet`] — vps-id back-reference, +//! max-sub-layers / nesting flag, the §7.3.3 PTL re-walk, +//! `chroma_format_idc` / `separate_colour_plane_flag`, +//! `pic_width_in_luma_samples` / `pic_height_in_luma_samples`, +//! conformance-window quad, `bit_depth_{luma,chroma}_minus8`, +//! `log2_max_pic_order_cnt_lsb_minus4`, the per-sub-layer +//! DPB / reorder / latency triple loop, the four +//! `log2_*_block_size{_minus_2,_minus_3,_diff_max_min}` fields, +//! `max_transform_hierarchy_depth_{inter,intra}`, +//! `scaling_list_enabled_flag` (with the nested +//! `sps_scaling_list_data_present_flag` / [`scaling_list::ScalingListData`] +//! §7.3.4 block), `amp_enabled_flag`, +//! `sample_adaptive_offset_enabled_flag`, the [`sps::PcmInfo`] block +//! gated by `pcm_enabled_flag`, the +//! `num_short_term_ref_pic_sets` ue(v) + per-set +//! [`sps::ShortTermRefPicSet`] (§7.3.7, both explicit and +//! inter-RPS-prediction forms), the +//! `long_term_ref_pics_present_flag` block plus +//! [`sps::LongTermRefPicEntry`] table, the +//! `sps_temporal_mvp_enabled_flag` / +//! `strong_intra_smoothing_enabled_flag` pair, the +//! `vui_parameters_present_flag` gate whose §E.2.1 +//! `vui_parameters()` body is decoded into [`vui::VuiParameters`] +//! (aspect-ratio / EXTENDED_SAR, overscan, video-signal-type + +//! colour-description, chroma-loc, default-display-window, the +//! `vui_timing_info` block — `u(32)` num_units_in_tick / time_scale +//! plus the nested §E.2.3 `hrd_parameters()` call — and +//! bitstream-restriction), and the `sps_extension_present_flag` +//! gate whose extension body is surfaced as [`sps::OpaqueTail`]. +//! The §7.3.4 `scaling_list_data()` block — when +//! `sps_scaling_list_data_present_flag == 1` — is parsed and the +//! §7.4.5 `ScalingList[sizeId][matrixId][i]` coefficient arrays are +//! derived (default tables + prediction inference); see +//! [`scaling_list::ScalingListData`]. +//! * §6.5 [`scan`] — all four scan-order initialization processes plus +//! the §7.4.2 [`scan::scan_order`] `ScanOrder[log2BlockSize][scanIdx]` +//! accessor: [`scan::up_right_diagonal`] (§6.5.3, equation 6-11), +//! [`scan::horizontal`] (§6.5.4, equation 6-12), +//! [`scan::vertical`] (§6.5.5, equation 6-13), and +//! [`scan::traverse`] (§6.5.6, equation 6-14, the boustrophedon +//! raster). [`scan::scan_order`] enforces §7.4.2's populated ranges +//! (`log2BlockSize` 0..=3 for diagonal / horizontal / vertical, 2..=5 +//! for traverse). §7.4.5 +//! [`scaling_list::ScalingListData::scaling_factors`] expands the +//! flat scaling lists into the two-dimensional +//! `ScalingFactor[sizeId][matrixId][x][y]` quantization matrices +//! (equations 7-44..7-51: the diagonal scatter, the 2x / 4x block +//! replication, the DC `[0][0]` override, and the +//! `ChromaArrayType == 3` 32x32-chroma derivation). +//! * §7.3.2.3.1 [`pps::PicParameterSet`] — the full general +//! `pic_parameter_set_rbsp()` body: the `pps_*_id` pair, the +//! slice-header gates, `init_qp_minus26` (`se(v)`), the chroma QP +//! offsets, the tiles block ([`pps::TileInfo`] — column/row counts +//! plus the explicit `column_width_minus1[]` / `row_height_minus1[]` +//! arrays when `uniform_spacing_flag == 0`), the +//! deblocking-filter-control block ([`pps::DeblockingFilterControl`]), +//! `lists_modification_present_flag`, +//! `log2_parallel_merge_level_minus2`, and the +//! `pps_extension_present_flag` gate. When +//! `pps_extension_present_flag == 1` the eight bits of typed +//! extension flags are decoded into [`pps::PpsExtensionFlags`] +//! (`pps_range_extension_flag`, `pps_multilayer_extension_flag`, +//! `pps_3d_extension_flag`, `pps_scc_extension_flag`, and the +//! reserved `pps_extension_4bits`); any extension body whose flag +//! is set is surfaced as a shared [`sps::OpaqueTail`] starting at +//! the first body's bit position. When +//! `pps_scaling_list_data_present_flag == 1` the §7.3.4 +//! `scaling_list_data()` block is parsed into +//! [`scaling_list::ScalingListData`]. The §7.4.3.3.1 inference rules +//! are applied so absent conditional fields carry their effective +//! value. +//! * §7.3.6.1 [`slice::SliceSegmentHeader`] — the +//! `slice_segment_header()` parse for an independent slice segment, +//! taking the activated SPS + PPS as context (the +//! `slice_segment_address` and `slice_pic_order_cnt_lsb` widths plus +//! the SAO / MVP / tiles gates are SPS/PPS-derived). Independent +//! **I-slice** segments — both IDR and non-IDR — parse end to end +//! through `byte_alignment()`, including the §7.3.6.1 non-IDR POC +//! (`slice_pic_order_cnt_lsb`) + short-term-RPS +//! (`short_term_ref_pic_set_sps_flag` / +//! in-line `st_ref_pic_set(num_short_term_ref_pic_sets)` via +//! [`sps::ShortTermRefPicSet::parse_slice_inline`] / +//! `short_term_ref_pic_set_idx`) + long-term-RPS block (per-entry +//! SPS-indexed vs in-slice + `delta_poc_msb_present_flag` / +//! `delta_poc_msb_cycle_lt`, surfaced as +//! [`slice::SliceLongTermRefPic`]). The P/B reference-list / +//! weighted-prediction sub-structures are still surfaced as an +//! [`sps::OpaqueTail`]. The §7.4.7.1 inference rules are applied to +//! absent fields. +//! * §7.3.6.2 [`slice::RefPicListsModification`] — the +//! `ref_pic_lists_modification()` syntax structure as a standalone +//! parser. The parser walks the +//! `ref_pic_list_modification_flag_lX` `u(1)` gates and the +//! `list_entry_lX[]` `u(v)` loops (each entry +//! `Ceil( Log2( NumPicTotalCurr ) )` bits wide and range-checked +//! per §7.4.7.2); the implicit `RefPicListTempX` derivation of +//! §8.3.4 stays the consumer's responsibility. +//! * §7.4.7.2 [`slice::NumPicTotalCurrInputs`] — the +//! `NumPicTotalCurr` derivation (equation 7-57) as a small typed +//! builder taking the per-position `UsedByCurrPicS0` / +//! `UsedByCurrPicS1` / `UsedByCurrPicLt` flags from the active +//! short-term RPS + the slice's long-term ref list and the +//! `pps_curr_pic_ref_enabled_flag` closing-clause flag, returning +//! the typed `NumPicTotalCurr: u32`. A +//! [`slice::NumPicTotalCurrInputs::from_explicit_short_term_rps`] +//! convenience constructor sources `S0` / `S1` straight off an +//! explicit-form [`sps::ShortTermRefPicSet`]; the +//! inter-RPS-prediction form needs the §7.4.8 derivation to run +//! first. +//! [`slice::SliceLongTermRefPic::used_by_curr_pic_lt`] resolves +//! each long-term entry's `UsedByCurrPicLt[i]` per §7.4.7.1 +//! (SPS-table lookup for SPS-resident entries, direct flag for +//! in-slice entries). The F.7.4.7.2 multilayer-extension form +//! (equation F-56) is reachable through +//! [`slice::NumPicTotalCurrInputs::with_multilayer_extension`]. +//! * §7.3.6.3 [`slice::PredWeightTable`] — the +//! `pred_weight_table()` syntax structure as a standalone parser. +//! The parser walks the `luma_log2_weight_denom` / +//! `delta_chroma_log2_weight_denom` denominators, the two flag passes +//! (`luma_weight_lX_flag[i]` + `chroma_weight_lX_flag[i]`), and the +//! per-reference delta block (`delta_luma_weight_lX[i]` / +//! `luma_offset_lX[i]` / `delta_chroma_weight_lX[i][j]` / +//! `delta_chroma_offset_lX[i][j]`), applying the §7.4.7.3 range +//! bounds + the per-i §7.3.6.3 outer-gate (`pic_layer_id != +//! nuh_layer_id || PicOrderCnt(RefPicListX[i]) != +//! PicOrderCnt(CurrPic)`) decision supplied by the caller, the +//! `ChromaLog2WeightDenom ∈ 0..=7` derived range, and the +//! `sumWeightLXFlags ≤ 24` conformance cap. +//! [`slice::PredWeightTable::luma_weight_l0`] / +//! [`slice::PredWeightTable::chroma_weight_l0`] (mirrored for L1) +//! resolve each derived `LumaWeightLX[i]` / +//! `ChromaWeightLX[i][j]`; [`slice::PredWeightTable::chroma_offset_l0`] +//! (mirrored) applies equation 7-58 for `ChromaOffsetLX[i][j]`. +//! +//! See [`nal`] for the byte-stream walker entry points, [`vps`] for +//! the parsed VPS structure, [`sps`] for the parsed SPS, [`pps`] +//! for the parsed PPS, and [`crate::slice`] for the parsed slice +//! header. + +#![warn(missing_debug_implementations)] + +use oxideav_core::RuntimeContext; + +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod availability; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod binarization; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod bitreader; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod cabac; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod ctx_init; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod deblock; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod decode; +pub mod decoder; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod dpb; +pub mod encoder; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod hrd; +pub mod hvcc; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod inter_pred; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod inter_recon; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod intra_mode_field; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod intra_pred; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod motion; +pub mod nal; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod palette; +pub mod picture; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod poc; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod pps; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod pu_mv; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod recon; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod residual; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod sao; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod scaling_list; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod scan; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod sei; +pub mod sequence; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod slice; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod slice_data; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod sps; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod transform; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod transform_tree; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod transform_unit; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod vps; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub mod vui; + +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use availability::{AvailabilityError, PictureTiling, TilingParams}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use bitreader::{BitReader, BitReaderError}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use cabac::{init_type, CabacEngine, CabacError, ContextModel}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use ctx_init::SliceContexts; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use deblock::{ + deblock_picture, deblock_picture_full, derive_boundary_strength, derive_edge_flags, + filter_cu_edges, filter_cu_edges_full, BoundaryStrength, DeblockCu, DeblockCuDesc, + DeblockCuParams, EdgeFlags, EdgeType, NoFilterMap, TransformSplit, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use decode::{PictureHeaderInfo, PictureRefState, PictureSequenceState, SliceRefParams}; +pub use decoder::{make_decoder, H265Decoder}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use dpb::{ + build_rps_poc_lists, no_backward_pred_flag, select_col_pic, Dpb, DpbEntry, LongTermEntry, + Marking, RefPicListParams, RefPicLists, ResolvedRps, RpsPocLists, +}; +pub use encoder::{make_encoder, H265Encoder, H265PcmEncoder}; +pub use hrd::HrdError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use hrd::{ + CpbEntry, HrdCommonInfo, HrdParameters, SubLayerHrd, SubLayerHrdParameters, VpsHrdEntry, + HEVC_MAX_CPB_CNT, HEVC_MAX_ELEMENTAL_DURATION_IN_TC_MINUS1, +}; +pub use hvcc::{ + extradata_is_hvcc, nal_unit_from_coded, parse_hvcc, split_length_prefixed, HvccError, + HvccRecord, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use inter_pred::{ + default_weighted_pred, explicit_weighted_pred, interp_chroma_block, interp_luma_block, + predict_inter_pu, predict_inter_pu_weighted, InterPredError, InterPredGeometry, + InterPrediction, ListPrediction, MotionVector, PuWeights, RefPlane, WpListWeights, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use inter_recon::SliceWpTables; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use intra_mode_field::{IntraModeField, Neighbour, MIN_BLOCK_LOG2, MIN_BLOCK_SIZE}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use motion::{ + append_combined_bi_candidates, append_zero_merge_candidates, build_merge_candidate, + derive_chroma_mv, derive_mvp_candidate, derive_spatial_merge_candidates, derive_temporal_mv, + reconstruct_mv, MergeCandidate, MergeListParams, MotionCell, MotionField, Mv, MvpContext, + NeighbourPu, PartitionContext, RefPicId, SpatialMergeCandidates, SpatialMergeNeighbours, + TemporalMvContext, +}; +pub use nal::{collect_nal_units, NalError, NalHeader, NalIter, NalUnit}; +pub use picture::{clip1, sub_wh_c, Picture, Plane}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use poc::{diff_pic_order_cnt, NalKind, PicOrderCnt, PocState}; +pub use pps::PpsError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use pps::{ + ChromaQpOffsetListEntry, DeblockingFilterControl, PicParameterSet, PpsRangeExtension, TileInfo, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use pu_mv::{ + pu_partitions, resolve_cu_motion, resolve_pu_motion, InterCuDesc, PartMode as PuPartMode, + PuGeometry, PuMotion, PuMvContext, PuRect, +}; +pub use recon::ReconError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use recon::{ + build_slice_addr_map, reconstruct_inter_pu, reconstruct_inter_pu_weighted, + reconstruct_intra_ctu, reconstruct_intra_ctu_ctx, reconstruct_intra_picture, + IntraPictureParams, PlacedCtu, ReconCtx, ReconParams, ResolvedList, SliceSegmentBoundary, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use sao::{ + apply_sao_ctb, apply_sao_picture, apply_sao_picture_full, ResolvedSao, ResolvedSaoComponent, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use scaling_list::{ + ScalingFactorMatrix, ScalingFactors, ScalingListData, ScalingListError, ScalingListMatrix, + MAX_COEF_NUM, NUM_MATRIX_IDS, NUM_SIZE_IDS, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use scan::{ + horizontal, scan_order, traverse, up_right_diagonal, vertical, ScanIdx, ScanOrderError, ScanPos, +}; +pub use sequence::{decode_annexb_sequence, DecodedFrame, SequenceDecoder, SequenceError}; +pub use slice::SliceError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use slice::{ + EntryPointOffsets, NumPicTotalCurrInputs, PredWeightEntry, PredWeightTable, + PredWeightTableInputs, RefPicListsModification, SliceDeblocking, SliceLongTermRefPic, + SliceLongTermRefPicSource, SliceSegmentHeader, SliceType, BLA_W_LP, IDR_N_LP, IDR_W_RADL, + RSV_IRAP_VCL23, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use slice_data::{ + decode_coding_quadtree, decode_coding_tree_unit, decode_coding_tree_unit_in_picture, + decode_sao, CodingQuadtree, CodingTreeUnit, CodingUnit, IntraLumaMode, PcmSamples, + PictureParseState, PredictionUnit, SaoComponent, SaoCtbParams, SliceDataParams, +}; +pub use sps::{ShortTermRefPicSetMaterializeError, SpsError}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use sps::{ + ConformanceWindow, LongTermRefPicEntry, MaterializedShortTermRefPicSet, OpaqueTail, PcmInfo, + SeqParameterSet, ShortTermRefPicSet, SpsExtensionFlags, SpsRangeExtension, + HEVC_MAX_NUM_LONG_TERM_RPS, HEVC_MAX_NUM_SHORT_TERM_RPS, HEVC_MAX_RPS_PICS, +}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use transform_tree::{decode_transform_tree, TransformTree, TransformTreeParams}; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use transform_unit::{ + decode_transform_unit, CuPredMode, QuantGroupState, TransformUnit, TransformUnitParams, +}; +pub use vps::VpsError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use vps::{ + HevcVps, LayerIdInclusionRow, ProfileTierLevel, SubLayerOrderingInfo, VpsTimingInfo, + HEVC_MAX_SUB_LAYERS, HEVC_VPS_MAX_NUM_LAYERS, HEVC_VPS_MAX_NUM_LAYER_SETS, +}; +pub use vui::VuiError; +// internal — exposed for tests/fuzz; not part of the stable API +#[doc(hidden)] +pub use vui::{ + BitstreamRestriction, ColourDescription, DefaultDisplayWindow, VideoSignalType, VuiParameters, + VuiTimingInfo, EXTENDED_SAR, +}; + +/// Crate-local error type for the structural utilities (the NAL +/// walker and parameter-set parsers surface their own [`NalError`] / +/// [`VpsError`] types directly; the decode drivers use +/// [`sequence::SequenceError`] and the registry decoder maps into +/// [`oxideav_core::Error`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Error { + /// The requested functionality is not implemented (the encoder, + /// and the remaining decoder gaps listed in `README.md`). + NotImplemented, + /// A NAL-walker error surfaced through the top-level entry + /// points. + Nal(NalError), + /// A VPS-parser error surfaced through the top-level entry + /// points. + Vps(VpsError), + /// An SPS-parser error surfaced through the top-level entry + /// points. + Sps(SpsError), + /// A PPS-parser error surfaced through the top-level entry + /// points. + Pps(PpsError), + /// A slice-segment-header-parser error surfaced through the + /// top-level entry points. + Slice(SliceError), + /// An `hrd_parameters()` parser error surfaced through the + /// top-level entry points. + Hrd(HrdError), + /// A `vui_parameters()` parser error surfaced through the + /// top-level entry points. + Vui(VuiError), +} + +impl core::fmt::Display for Error { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::NotImplemented => f.write_str("oxideav-h265: decoder/encoder not wired up yet"), + Self::Nal(e) => write!(f, "oxideav-h265 NAL error: {e}"), + Self::Vps(e) => write!(f, "oxideav-h265 VPS error: {e}"), + Self::Sps(e) => write!(f, "oxideav-h265 SPS error: {e}"), + Self::Pps(e) => write!(f, "oxideav-h265 PPS error: {e}"), + Self::Slice(e) => write!(f, "oxideav-h265 slice header error: {e}"), + Self::Hrd(e) => write!(f, "oxideav-h265 hrd error: {e}"), + Self::Vui(e) => write!(f, "oxideav-h265 vui error: {e}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(e: NalError) -> Self { + Self::Nal(e) + } +} + +impl From for Error { + fn from(e: VpsError) -> Self { + Self::Vps(e) + } +} + +impl From for Error { + fn from(e: SpsError) -> Self { + Self::Sps(e) + } +} + +impl From for Error { + fn from(e: PpsError) -> Self { + Self::Pps(e) + } +} + +impl From for Error { + fn from(e: SliceError) -> Self { + Self::Slice(e) + } +} + +impl From for Error { + fn from(e: HrdError) -> Self { + Self::Hrd(e) + } +} + +impl From for Error { + fn from(e: VuiError) -> Self { + Self::Vui(e) + } +} + +/// Codec registration: the software H.265 / HEVC decoder under the +/// `"h265"` id (aliased `"hevc"`), claiming the common container tags +/// (`hvc1` / `hev1` sample entries, the MP4 ObjectTypeIndication for +/// HEVC, and the `HEVC` FourCC). +pub fn register(ctx: &mut RuntimeContext) { + use oxideav_core::{CodecInfo, CodecTag}; + for id in ["h265", "hevc"] { + ctx.codecs.register( + CodecInfo::new(id.into()) + .decoder(decoder::make_decoder) + .encoder(encoder::make_encoder) + .tags([ + CodecTag::fourcc(b"hvc1"), + CodecTag::fourcc(b"hev1"), + CodecTag::fourcc(b"HEVC"), + CodecTag::mp4_object_type(0x23), + CodecTag::matroska("V_MPEGH/ISO/HEVC"), + ]), + ); + } +} + +oxideav_core::register!("h265", register); diff --git a/vendor/oxideav-h265/src/motion.rs b/vendor/oxideav-h265/src/motion.rs new file mode 100644 index 0000000..e222686 --- /dev/null +++ b/vendor/oxideav-h265/src/motion.rs @@ -0,0 +1,1826 @@ +//! §8.5.3.2 — motion-vector reconstruction, chroma MV derivation, the +//! zero-MV merge fallback, and the per-block motion field. +//! +//! This module turns the §7.3.8.6 `prediction_unit()` syntax (the +//! signalled `mvd`, `mvp_lX_flag`, `ref_idx`, `inter_pred_idc` / +//! `merge_idx`) into the resolved per-PU motion data the §8.5.3.3.1 +//! block-walk driver ([`crate::inter_pred::predict_inter_pu`]) consumes, +//! and stores it in a per-4×4-block [`MotionField`] that the §8.7.2.4 +//! boundary-filtering-strength derivation reads. +//! +//! Three numeric §8.5.3.2 sub-processes are self-contained and live here: +//! +//! * §8.5.3.2.1 step 4 / 5 — [`reconstruct_mv`]: the +//! `uLX = (mvpLX + mvdLX + 2^16) % 2^16` wrap of equations 8-94..8-101, +//! for both the fractional-MV path (eqs 8-94..8-97) and the +//! integer-MV path (eqs 8-98..8-101, used when the reference picture is +//! the current picture or `use_integer_mv_flag == 1`). +//! * §8.5.3.2.10 — [`derive_chroma_mv`]: `mvCLX = mvLX * 2 / SubWidthC` +//! (equations 8-210 / 8-211). +//! * §8.5.3.2.5 — [`append_zero_merge_candidates`]: the zero-MV merge +//! fallback (equations 8-152..8-169) that pads the merge candidate +//! list out to `MaxNumMergeCand` when the spatial / temporal / combined +//! candidates do not fill it. +//! +//! The §8.5.3.2.3 spatial-merge candidate derivation +//! ([`derive_spatial_merge_candidates`]), the §8.5.3.2.4 combined +//! bi-predictive step ([`append_combined_bi_candidates`]), the §8.5.3.2.2 +//! merge-list driver ([`build_merge_candidate`]), and the §8.5.3.2.6 / +//! §8.5.3.2.7 luma-MVP candidate derivation ([`derive_mvp_candidate`]) +//! also live here. They take the neighbour PU motion as data ([`NeighbourPu`] +//! snapshots gathered by the picture driver from the per-block motion +//! field) plus closures resolving a `(list, ref_idx)` to its POC / +//! long-term flag, so the arithmetic stays self-contained and unit-tested +//! while the picture driver owns the neighbour-location plumbing. +//! +//! The §8.5.3.2.8 temporal (collocated-picture) candidate is still the +//! picture-driver's follow-up — its `Col` candidate is passed in as an +//! `Option` (`None` until the collocated-MV path lands). + +/// A `[mv[0], mv[1]]` motion vector. Luma MVs are in quarter-luma-sample +/// units; chroma MVs are in eighth-chroma-sample units. +pub type Mv = [i32; 2]; + +/// `2^16` — the §8.5.3.2.1 motion-vector wrap modulus (eqs 8-94..8-101). +const MV_WRAP: i32 = 1 << 16; +/// `2^15` — the §8.5.3.2.1 wrap threshold; values `>= 2^15` fold to the +/// negative half so the result lands in `[−2^15, 2^15 − 1]`. +const MV_HALF: i32 = 1 << 15; + +/// §8.5.3.2.1 step 4 / 5 — reconstruct one luma motion-vector component +/// from its predictor and delta with the `2^16` wrap. +/// +/// `integer_mv` selects between the fractional path (eqs 8-94..8-97, +/// `integer_mv == false`) and the integer-MV path (eqs 8-98..8-101, +/// `integer_mv == true`), the latter applying when the reference picture +/// is the current picture or `use_integer_mv_flag == 1`. +#[inline] +#[must_use] +fn reconstruct_component(mvp: i32, mvd: i32, integer_mv: bool) -> i32 { + // eq 8-94 / 8-98: uLX = (mvpLX + mvdLX + 2^16) % 2^16, with the + // integer path first quantizing the predictor to full-sample units + // ( (mvp >> 2) + mvd ) << 2. + let sum = if integer_mv { + (((mvp >> 2) + mvd) << 2) + MV_WRAP + } else { + mvp + mvd + MV_WRAP + }; + let u = sum.rem_euclid(MV_WRAP); + // eq 8-95 / 8-99: fold the upper half to the negative range. + if u >= MV_HALF { + u - MV_WRAP + } else { + u + } +} + +/// §8.5.3.2.1 step 4 / 5 — reconstruct a luma motion vector `mvLX` from +/// the motion-vector predictor `mvpLX` and the decoded delta `mvdLX` +/// (equations 8-94..8-101), with the `2^16` wrap on each component. +/// +/// `integer_mv` is `true` for the §8.5.3.2.1 step-5 integer path +/// (reference picture is the current picture, or `use_integer_mv_flag`), +/// `false` for the step-4 fractional path. The result is guaranteed to +/// lie in `[−2^15, 2^15 − 1]` per spec NOTE 1 / NOTE 2. +#[must_use] +pub fn reconstruct_mv(mvp: Mv, mvd: Mv, integer_mv: bool) -> Mv { + [ + reconstruct_component(mvp[0], mvd[0], integer_mv), + reconstruct_component(mvp[1], mvd[1], integer_mv), + ] +} + +/// §8.5.3.2.10 — derive the chroma motion vector `mvCLX` from the luma +/// motion vector `mvLX` (equations 8-210 / 8-211): +/// `mvCLX[0] = mvLX[0] * 2 / SubWidthC`, `mvCLX[1] = mvLX[1] * 2 / SubHeightC`. +/// +/// `(sub_w, sub_h)` are `(SubWidthC, SubHeightC)` from Table 6-1. The +/// spec division is signed integer division (truncation toward zero); +/// `i32::wrapping_div` is exact here because the operands never overflow. +#[must_use] +pub fn derive_chroma_mv(mv_l: Mv, sub_w: i32, sub_h: i32) -> Mv { + [mv_l[0] * 2 / sub_w, mv_l[1] * 2 / sub_h] +} + +/// One merge candidate's motion data — the per-list reference index, +/// utilization flag and motion vector (§8.5.3.2.x candidate lists). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct MergeCandidate { + /// `refIdxL0N` (−1 when L0 is unused). + pub ref_idx_l0: i32, + /// `refIdxL1N` (−1 when L1 is unused). + pub ref_idx_l1: i32, + /// `predFlagL0N`. + pub pred_flag_l0: bool, + /// `predFlagL1N`. + pub pred_flag_l1: bool, + /// `mvL0N`. + pub mv_l0: Mv, + /// `mvL1N`. + pub mv_l1: Mv, +} + +/// A spatial neighbour prediction unit's motion data, as read out of the +/// per-block motion field at a neighbour sample location for the +/// §8.5.3.2.3 spatial-merge / §8.5.3.2.7 MVP-candidate derivations. +/// +/// This is the `(MvLX, RefIdxLX, PredFlagLX)` tuple the spec reads at +/// `[ xNbN ][ yNbN ]`. Two merge candidates "have the same motion vectors +/// and the same reference indices" (the §8.5.3.2.3 pruning test) iff their +/// `pred_flag`/`ref_idx`/`mv` for both lists are equal — i.e. iff their +/// [`NeighbourPu`] values compare equal. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct NeighbourPu { + /// `PredFlagL0[ xNb ][ yNb ]`. + pub pred_flag_l0: bool, + /// `PredFlagL1[ xNb ][ yNb ]`. + pub pred_flag_l1: bool, + /// `RefIdxL0[ xNb ][ yNb ]` (−1 when L0 unused). + pub ref_idx_l0: i32, + /// `RefIdxL1[ xNb ][ yNb ]` (−1 when L1 unused). + pub ref_idx_l1: i32, + /// `MvL0[ xNb ][ yNb ]`. + pub mv_l0: Mv, + /// `MvL1[ xNb ][ yNb ]`. + pub mv_l1: Mv, +} + +impl NeighbourPu { + /// The §8.5.3.2.3 candidate built from this neighbour PU's motion + /// (eqs 8-128..8-130 and the B0/A0/B1/B2 analogues): the neighbour's + /// per-list MV / refIdx / predFlag, copied verbatim into a + /// [`MergeCandidate`]. + #[inline] + #[must_use] + fn to_candidate(self) -> MergeCandidate { + MergeCandidate { + ref_idx_l0: self.ref_idx_l0, + ref_idx_l1: self.ref_idx_l1, + pred_flag_l0: self.pred_flag_l0, + pred_flag_l1: self.pred_flag_l1, + mv_l0: self.mv_l0, + mv_l1: self.mv_l1, + } + } +} + +/// The five §8.5.3.2.3 spatial neighbour positions, in the order the +/// availability tests reference them. Each carries the neighbour sample +/// location `(xNbN, yNbN)` relative to the picture and the neighbour's +/// motion data when the §6.4.2 prediction-block availability test passed +/// (`None` when the neighbour is unavailable). +/// +/// Positions (eqs in §8.5.3.2.3), with `(xPb, yPb)` the PB top-left and +/// `nPbW`/`nPbH` its width/height: +/// * `A1` = `(xPb − 1, yPb + nPbH − 1)` +/// * `B1` = `(xPb + nPbW − 1, yPb − 1)` +/// * `B0` = `(xPb + nPbW, yPb − 1)` +/// * `A0` = `(xPb − 1, yPb + nPbH)` +/// * `B2` = `(xPb − 1, yPb − 1)` +#[derive(Debug, Clone, Copy, Default)] +pub struct SpatialMergeNeighbours { + /// Neighbour `A1` motion (`None` when §6.4.2-unavailable). + pub a1: Option, + /// Neighbour `B1` motion. + pub b1: Option, + /// Neighbour `B0` motion. + pub b0: Option, + /// Neighbour `A0` motion. + pub a0: Option, + /// Neighbour `B2` motion. + pub b2: Option, +} + +/// §8.5.3.2.3 PartMode-dependent partition exclusion for the current PU. +/// +/// The spatial-merge derivation forces `availableA1` / `availableB1` to +/// FALSE for the second partition of certain `PartMode`s so the two PUs of +/// a split CU don't merge into one another (which would defeat the split). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PartitionContext { + /// `partIdx` of the current PU within its CU (0 or 1 for two-PU modes). + pub part_idx: u32, + /// `true` when `PartMode ∈ {PART_Nx2N, PART_nLx2N, PART_nRx2N}` — the + /// vertical-split modes that exclude `A1` at `partIdx == 1`. + pub part_mode_vertical_split: bool, + /// `true` when `PartMode ∈ {PART_2NxN, PART_2NxnU, PART_2NxnD}` — the + /// horizontal-split modes that exclude `B1` at `partIdx == 1`. + pub part_mode_horizontal_split: bool, +} + +/// §8.5.3.2.3 — derive the up-to-five spatial merging candidates and their +/// availability flags from the neighbouring prediction units. +/// +/// `neigh` carries each neighbour position's §6.4.2 availability (as +/// `Some`/`None`) plus its motion data; `part` carries the current PU's +/// `partIdx` + `PartMode` split class for the A1/B1 partition-exclusion +/// rules; `same_par_mrg` is `true` when the neighbour falls in the *same* +/// `Log2ParMrgLevel` parallel-merge region as the current PB (the +/// `xPb >> L == xNb >> L && yPb >> L == yNb >> L` test that forces a +/// neighbour unavailable). The five returned `Option`s are the available +/// candidates A1/B1/B0/A0/B2 (eqs 8-128..8-142), already pruned against the +/// earlier-derived neighbours exactly as the spec's redundancy checks +/// require. +/// +/// `same_par_mrg` is a 5-tuple `(a1, b1, b0, a0, b2)` of the per-neighbour +/// parallel-merge-region tests. +#[must_use] +pub fn derive_spatial_merge_candidates( + neigh: &SpatialMergeNeighbours, + part: PartitionContext, + same_par_mrg: (bool, bool, bool, bool, bool), +) -> SpatialMergeCandidates { + let (smrg_a1, smrg_b1, smrg_b0, smrg_a0, smrg_b2) = same_par_mrg; + + // §8.5.3.2.3 distinguishes `availableN` (the §6.4.2 result, forced + // FALSE by the parallel-merge-region / partition exclusions) from + // `availableFlagN` (additionally cleared by the redundancy tests). + // Every "the prediction units covering ( xNbN, yNbN ) ... have the + // same motion" comparison is gated on the *raw* `availableN` of the + // earlier position, NOT its post-redundancy flag — a B1 pruned as a + // duplicate of A1 still prunes an identical B0. + + // --- A1 (eqs 8-128..8-130) --- + // availableA1 starts from §6.4.2, then is forced FALSE when the + // neighbour is in the same parallel-merge region, or for the second + // partition of a vertical-split PartMode. + let a1_excluded = smrg_a1 || (part.part_mode_vertical_split && part.part_idx == 1); + let raw_a1 = if a1_excluded { None } else { neigh.a1 }; + let cand_a1 = raw_a1; + + // --- B1 (eqs 8-131..8-133) --- + // availableB1 is forced FALSE in the same-region case and for the + // second partition of a horizontal-split PartMode; availableFlagB1 + // is additionally 0 when A1 is available with identical motion. + let b1_excluded = smrg_b1 || (part.part_mode_horizontal_split && part.part_idx == 1); + let raw_b1 = if b1_excluded { None } else { neigh.b1 }; + let cand_b1 = if same_motion(raw_a1, raw_b1) { + None + } else { + raw_b1 + }; + + // --- B0 (eqs 8-134..8-136) --- + // availableFlagB0 is 0 in the same-region case or when the raw B1 + // is available with identical motion. + let b0_excluded = smrg_b0 || same_motion(raw_b1, neigh.b0); + let cand_b0 = if b0_excluded { None } else { neigh.b0 }; + + // --- A0 (eqs 8-137..8-139) --- + // availableFlagA0 is 0 in the same-region case or when the raw A1 + // is available with identical motion. + let a0_excluded = smrg_a0 || same_motion(raw_a1, neigh.a0); + let cand_a0 = if a0_excluded { None } else { neigh.a0 }; + + // --- B2 (eqs 8-140..8-142) --- + // availableFlagB2 is 0 in the same-region case, when the raw A1 or + // raw B1 is available with identical motion, or when all four of + // A0/A1/B0/B1 already have availableFlag == 1 (the list is full + // before B2). + let four_available = + cand_a0.is_some() && cand_a1.is_some() && cand_b0.is_some() && cand_b1.is_some(); + let b2_excluded = + smrg_b2 || four_available || same_motion(raw_a1, neigh.b2) || same_motion(raw_b1, neigh.b2); + let cand_b2 = if b2_excluded { None } else { neigh.b2 }; + + SpatialMergeCandidates { + a1: cand_a1.map(NeighbourPu::to_candidate), + b1: cand_b1.map(NeighbourPu::to_candidate), + b0: cand_b0.map(NeighbourPu::to_candidate), + a0: cand_a0.map(NeighbourPu::to_candidate), + b2: cand_b2.map(NeighbourPu::to_candidate), + } +} + +/// The §8.5.3.2.3 "have the same motion vectors and the same reference +/// indices" redundancy test: `true` iff `earlier` is available and equal +/// (per-list predFlag / refIdx / MV) to `candidate`. +#[inline] +#[must_use] +fn same_motion(earlier: Option, candidate: Option) -> bool { + match (earlier, candidate) { + (Some(e), Some(c)) => e == c, + _ => false, + } +} + +/// The five §8.5.3.2.3 spatial merging candidates, in their named slots. +/// A slot is `Some` iff its availability flag is 1 after the redundancy / +/// partition-exclusion checks. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SpatialMergeCandidates { + /// Candidate A1 (`availableFlagA1`). + pub a1: Option, + /// Candidate B1 (`availableFlagB1`). + pub b1: Option, + /// Candidate B0 (`availableFlagB0`). + pub b0: Option, + /// Candidate A0 (`availableFlagA0`). + pub a0: Option, + /// Candidate B2 (`availableFlagB2`). + pub b2: Option, +} + +impl SpatialMergeCandidates { + /// §8.5.3.2.2 step 5 — append the available spatial candidates into a + /// `mergeCandList` in the spec order A1, B1, B0, A0, B2 (eq 8-119, + /// minus the temporal `Col` candidate, which the driver inserts after + /// these). The list is grown in place. + pub fn append_to(&self, list: &mut Vec) { + for c in [self.a1, self.b1, self.b0, self.a0, self.b2] + .into_iter() + .flatten() + { + list.push(c); + } + } +} + +/// §8.5.3.2.5 — append zero-motion-vector merge candidates to a partial +/// merge candidate list until it holds `max_num_merge_cand` entries +/// (equations 8-152..8-169). +/// +/// `cand_list` is the list after the spatial / temporal / combined +/// candidates (`numCurrMergeCand` entries); `slice_is_b` selects the B +/// (bi-predictive zero candidate, eqs 8-161..8-168) versus P +/// (uni-L0 zero candidate, eqs 8-152..8-159) form. `num_ref_idx` is the +/// §8.5.3.2.5 `numRefIdx` (P: `num_ref_idx_l0_active`; B: +/// `Min(l0_active, l1_active)`). The list is grown in place. +pub fn append_zero_merge_candidates( + cand_list: &mut Vec, + slice_is_b: bool, + num_ref_idx: i32, + max_num_merge_cand: usize, +) { + let mut zero_idx = 0i32; + while cand_list.len() < max_num_merge_cand { + // eq 8-152 / 8-161: refIdxL0 = (zeroIdx < numRefIdx) ? zeroIdx : 0. + let ref_idx = if zero_idx < num_ref_idx { zero_idx } else { 0 }; + let cand = if slice_is_b { + MergeCandidate { + ref_idx_l0: ref_idx, + ref_idx_l1: ref_idx, + pred_flag_l0: true, + pred_flag_l1: true, + mv_l0: [0, 0], + mv_l1: [0, 0], + } + } else { + MergeCandidate { + ref_idx_l0: ref_idx, + ref_idx_l1: -1, + pred_flag_l0: true, + pred_flag_l1: false, + mv_l0: [0, 0], + mv_l1: [0, 0], + } + }; + cand_list.push(cand); + zero_idx += 1; + } +} + +/// Table 8-7 — `(l0CandIdx, l1CandIdx)` for `combIdx = 0..11`, the source +/// candidate positions the §8.5.3.2.4 combined bi-predictive candidate +/// pairs draw its L0 motion and L1 motion from. +const COMB_CAND_IDX: [(usize, usize); 12] = [ + (0, 1), + (1, 0), + (0, 2), + (2, 0), + (1, 2), + (2, 1), + (0, 3), + (3, 0), + (1, 3), + (3, 1), + (2, 3), + (3, 2), +]; + +/// §8.5.3.2.4 — append combined bi-predictive merging candidates to the +/// `mergeCandList`, drawing each new candidate's L0 motion from one +/// existing candidate and its L1 motion from another per Table 8-7. +/// +/// `list` is the merge list after the spatial + temporal candidates +/// (`numOrigMergeCand` entries on entry); it is grown in place up to +/// `max_num_merge_cand`. `ref_poc` resolves `(list_x, ref_idx)` to the +/// picture order count of `RefPicListX[ ref_idx ]` so the eq 8-143 +/// `DiffPicOrderCnt(...) != 0 || mvL0 != mvL1` distinctness test can run +/// (the candidate is only added when its L0 and L1 motion are not the +/// identical-picture/identical-MV degenerate case). +/// +/// Per the spec this process only runs for B slices, and only when +/// `numOrigMergeCand` is in `2..MaxNumMergeCand`; the driver gates on +/// those before calling. The loop stops at +/// `combIdx == numOrig * (numOrig − 1)` or when the list is full. +pub fn append_combined_bi_candidates( + list: &mut Vec, + num_orig_merge_cand: usize, + max_num_merge_cand: usize, + mut ref_poc: F, +) where + F: FnMut(usize, i32) -> i32, +{ + if !(num_orig_merge_cand > 1 && num_orig_merge_cand < max_num_merge_cand) { + return; + } + let comb_limit = num_orig_merge_cand * (num_orig_merge_cand - 1); + let mut comb_idx = 0usize; + while comb_idx < comb_limit && list.len() < max_num_merge_cand { + let (l0_idx, l1_idx) = COMB_CAND_IDX[comb_idx]; + comb_idx += 1; + // The source candidates are positions in the *original* part of + // the list (both < numOrigMergeCand by Table 8-7's range when + // numOrig <= 5, which it always is: 5 spatial + 1 temporal). + let l0_cand = list[l0_idx]; + let l1_cand = list[l1_idx]; + // eq 8-143 conditions: L0 of l0Cand and L1 of l1Cand both used, + // and not the degenerate same-picture+same-MV pair. + if !(l0_cand.pred_flag_l0 && l1_cand.pred_flag_l1) { + continue; + } + let poc_l0 = ref_poc(0, l0_cand.ref_idx_l0); + let poc_l1 = ref_poc(1, l1_cand.ref_idx_l1); + let distinct = poc_l0 != poc_l1 || l0_cand.mv_l0 != l1_cand.mv_l1; + if !distinct { + continue; + } + list.push(MergeCandidate { + ref_idx_l0: l0_cand.ref_idx_l0, + ref_idx_l1: l1_cand.ref_idx_l1, + pred_flag_l0: true, + pred_flag_l1: true, + mv_l0: l0_cand.mv_l0, + mv_l1: l1_cand.mv_l1, + }); + } +} + +/// Inputs that vary per slice / SPS for the §8.5.3.2.2 merge-list build. +#[derive(Debug, Clone, Copy)] +pub struct MergeListParams { + /// `true` for a B slice (enables the §8.5.3.2.4 combined step and the + /// bi-predictive §8.5.3.2.5 zero candidates). + pub slice_is_b: bool, + /// `MaxNumMergeCand` (§7.4.7.1; `5 − five_minus_max_num_merge_cand`). + pub max_num_merge_cand: usize, + /// `numRefIdx` for §8.5.3.2.5 — P: `num_ref_idx_l0_active`; + /// B: `Min(l0_active, l1_active)`. + pub zero_num_ref_idx: i32, +} + +/// §8.5.3.2.2 steps 5–10 — assemble the full `mergeCandList` and select the +/// candidate at `merge_idx`. +/// +/// `spatial` is the §8.5.3.2.3 output; `col` is the §8.5.3.2.8 temporal +/// candidate (`None` when `availableFlagCol == 0` — e.g. +/// `slice_temporal_mvp_enabled_flag == 0`, which is the present decoder +/// state until the collocated-picture path lands). `ref_poc` resolves +/// `(list_x, ref_idx)` to a POC for the §8.5.3.2.4 distinctness test. +/// +/// The returned [`MergeCandidate`] is `mergeCandList[ merge_idx ]` after +/// step 9, with the step-10 `(nOrigPbW + nOrigPbH == 12)` bi→uni-L0 +/// reduction applied when `pb_w_plus_h == 12`. +/// +/// `merge_idx` is clamped into the assembled list; a conformant bitstream +/// always indexes a valid entry because the zero-candidate padding fills +/// the list to `MaxNumMergeCand`. +#[must_use] +pub fn build_merge_candidate( + spatial: &SpatialMergeCandidates, + col: Option, + params: MergeListParams, + merge_idx: usize, + pb_w_plus_h: u32, + ref_poc: F, +) -> MergeCandidate +where + F: FnMut(usize, i32) -> i32, +{ + // Step 5: spatial candidates in A1,B1,B0,A0,B2 order, then Col. + let mut list: Vec = Vec::with_capacity(params.max_num_merge_cand); + spatial.append_to(&mut list); + if let Some(c) = col { + list.push(c); + } + // Step 6: numOrigMergeCand snapshot (after spatial + temporal). + let num_orig = list.len(); + // Step 7: combined bi-predictive candidates (B slices only). + if params.slice_is_b { + append_combined_bi_candidates(&mut list, num_orig, params.max_num_merge_cand, ref_poc); + } + // Step 8: zero-MV padding to MaxNumMergeCand. + append_zero_merge_candidates( + &mut list, + params.slice_is_b, + params.zero_num_ref_idx, + params.max_num_merge_cand, + ); + // Step 9: select N = mergeCandList[ merge_idx ]. + let idx = merge_idx.min(list.len().saturating_sub(1)); + let mut chosen = list[idx]; + // Step 10: (nOrigPbW + nOrigPbH == 12) ⇒ drop L1, keep uni-L0. + if chosen.pred_flag_l0 && chosen.pred_flag_l1 && pb_w_plus_h == 12 { + chosen.pred_flag_l1 = false; + chosen.ref_idx_l1 = -1; + } + chosen +} + +/// Reference-picture identity for the §8.5.3.2.7 motion-vector scaling: +/// the picture order count plus whether it is a long-term reference. +/// +/// The §8.5.3.2.7 derivation reads two things about each candidate +/// reference picture: its POC (for `DiffPicOrderCnt`, eqs 8-179..8-197) +/// and whether it is marked "used for long-term reference" (the +/// `LongTermRefPic(...)` equality test and the short-term gate on +/// scaling). The picture driver resolves a `(list, ref_idx)` to this. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RefPicId { + /// `PicOrderCntVal` of the reference picture. + pub poc: i32, + /// `true` iff the picture is marked "used for long-term reference". + pub long_term: bool, +} + +/// §8.5.3.2.7 motion-vector scaling (eqs 8-179..8-183 / 8-193..8-197): +/// scale `mv` from the temporal distance `td = currPic − neighRefPic` to +/// `tb = currPic − curRefPic`. +/// +/// `td`/`tb` are the §8.5.3.2.7 `DiffPicOrderCnt` distances (clipped to +/// `[−128, 127]` per eqs 8-182/8-183). Returns the eq 8-181 scaled MV. +#[must_use] +fn scale_temporal_mv(mv: Mv, curr_poc: i32, neigh_ref_poc: i32, cur_ref_poc: i32) -> Mv { + // eqs 8-182 / 8-196 and 8-183 / 8-197. + let td = (curr_poc - neigh_ref_poc).clamp(-128, 127); + let tb = (curr_poc - cur_ref_poc).clamp(-128, 127); + if td == 0 { + // td == 0 means same picture; the caller only scales when the + // POCs differ, so this guard is defensive (avoids /0). + return mv; + } + // eq 8-179 / 8-193: tx = (16384 + (|td| >> 1)) / td. + let tx = (16384 + (td.abs() >> 1)) / td; + // eq 8-180 / 8-194. + let dist_scale = (((tb * tx) + 32) >> 6).clamp(-4096, 4095); + // eq 8-181 / 8-195: per component. + [ + scale_component(dist_scale, mv[0]), + scale_component(dist_scale, mv[1]), + ] +} + +#[inline] +#[must_use] +fn scale_component(dist_scale: i32, mv: i32) -> i32 { + let v = dist_scale * mv; + let sign = if v < 0 { -1 } else { 1 }; + (sign * ((v.abs() + 127) >> 8)).clamp(-32768, 32767) +} + +/// The motion of one MVP source neighbour, paired with which list its MV +/// was taken from, so the §8.5.3.2.7 scaling can resolve the source +/// reference picture. Produced by [`mvp_neighbour_mv`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +struct MvpSource { + mv: Mv, + /// The list (0 or 1) the MV / refIdx were drawn from at the neighbour. + src_list: usize, + /// `RefIdxLY[ xNb ][ yNb ]` for that source list. + src_ref_idx: i32, +} + +/// §8.5.3.2.7 — the "same POC" (no-scaling) neighbour-MV pick used by the +/// A pass-1 (eqs 8-171/8-172) and the B step-3 (eqs 8-184/8-185): take the +/// neighbour's L`X` MV when its L`X` reference picture has the same POC as +/// the current reference picture; otherwise its L`Y` (Y = 1−X) MV under +/// the same POC test. Returns `None` when neither matches. +#[must_use] +fn mvp_neighbour_mv_same_poc( + n: NeighbourPu, + x: usize, + cur_ref_poc: i32, + neigh_ref_poc: &dyn Fn(usize, i32) -> i32, +) -> Option { + let (px, ix, mx) = list_fields(n, x); + if px && neigh_ref_poc(x, ix) == cur_ref_poc { + return Some(mx); + } + let y = 1 - x; + let (py, iy, my) = list_fields(n, y); + if py && neigh_ref_poc(y, iy) == cur_ref_poc { + return Some(my); + } + None +} + +/// §8.5.3.2.7 — the long-term-matched neighbour-MV pick used by A pass-2 +/// (eqs 8-173..8-178) and B step-5 (eqs 8-187..8-192): take the +/// neighbour's L`X` MV when the current ref and the neighbour's L`X` ref +/// have equal long-term status; else its L`Y` MV under the same test. +/// Returns the source MV + which list it came from (for later scaling). +#[must_use] +fn mvp_neighbour_mv_long_term( + n: NeighbourPu, + x: usize, + cur_long_term: bool, + neigh_long_term: &dyn Fn(usize, i32) -> bool, +) -> Option { + let (px, ix, mx) = list_fields(n, x); + if px && cur_long_term == neigh_long_term(x, ix) { + return Some(MvpSource { + mv: mx, + src_list: x, + src_ref_idx: ix, + }); + } + let y = 1 - x; + let (py, iy, my) = list_fields(n, y); + if py && cur_long_term == neigh_long_term(y, iy) { + return Some(MvpSource { + mv: my, + src_list: y, + src_ref_idx: iy, + }); + } + None +} + +/// `(predFlagLL, refIdxLL, mvLL)` of a neighbour for list `l` (0 or 1). +#[inline] +#[must_use] +fn list_fields(n: NeighbourPu, l: usize) -> (bool, i32, Mv) { + if l == 0 { + (n.pred_flag_l0, n.ref_idx_l0, n.mv_l0) + } else { + (n.pred_flag_l1, n.ref_idx_l1, n.mv_l1) + } +} + +/// The §8.5.3.2.7 inputs for one list `X`: the current PU's reference +/// picture and the §8.5.3.2.7 ref-pic resolvers. +pub struct MvpContext<'a> { + /// `X` — the list being predicted (0 or 1). + pub x: usize, + /// `PicOrderCntVal` of the current picture. + pub curr_poc: i32, + /// The current PU's reference picture `RefPicListX[ refIdxLX ]`. + pub cur_ref: RefPicId, + /// Resolve a neighbour's `(list, ref_idx)` to its reference POC. + pub neigh_ref_poc: &'a dyn Fn(usize, i32) -> i32, + /// Resolve a neighbour's `(list, ref_idx)` to its long-term flag. + pub neigh_ref_long_term: &'a dyn Fn(usize, i32) -> bool, + /// Resolve a `(list, ref_idx)` to whether it is a short-term picture + /// (the §8.5.3.2.7 scaling gate requires both refs short-term). + pub neigh_ref_short_term: &'a dyn Fn(usize, i32) -> bool, +} + +impl std::fmt::Debug for MvpContext<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("MvpContext") + .field("x", &self.x) + .field("curr_poc", &self.curr_poc) + .field("cur_ref", &self.cur_ref) + .finish_non_exhaustive() + } +} + +/// §8.5.3.2.7 — derive `mvLXA` and `availableFlagLXA` from the left +/// neighbours A0 (`xPb−1, yPb+nPbH`) then A1 (`xPb−1, yPb+nPbH−1`). +/// +/// `a0`/`a1` are the §6.4.2-gated neighbour PUs (`None` when unavailable). +/// Returns `(availableFlagLXA, mvLXA, isScaledFlagLX)`. +#[must_use] +fn derive_mvp_a( + a0: Option, + a1: Option, + ctx: &MvpContext, +) -> (bool, Mv, bool) { + // step 5: isScaledFlagLX = (availableA0 || availableA1). + let is_scaled = a0.is_some() || a1.is_some(); + // step 6 (pass 1): same-POC, no scaling, first match over A0 then A1. + for n in [a0, a1].into_iter().flatten() { + if let Some(mv) = mvp_neighbour_mv_same_poc(n, ctx.x, ctx.cur_ref.poc, ctx.neigh_ref_poc) { + return (true, mv, is_scaled); + } + } + // step 7 (pass 2): long-term-matched, then scale when both short-term. + for n in [a0, a1].into_iter().flatten() { + if let Some(src) = + mvp_neighbour_mv_long_term(n, ctx.x, ctx.cur_ref.long_term, ctx.neigh_ref_long_term) + { + let mv = maybe_scale(src, ctx); + return (true, mv, is_scaled); + } + } + (false, [0, 0], is_scaled) +} + +/// §8.5.3.2.7 — derive `mvLXB` and `availableFlagLXB` from the above +/// neighbours B0 (`xPb+nPbW, yPb−1`), B1 (`xPb+nPbW−1, yPb−1`), B2 +/// (`xPb−1, yPb−1`), with the `isScaledFlag` interaction (steps 3–5). +/// +/// Returns `(availableFlagLXB, mvLXB, mvLXA_override)` where the override +/// is `Some(mvLXB)` when step 4 copies B into A (isScaledFlag == 0 path). +#[must_use] +fn derive_mvp_b( + b0: Option, + b1: Option, + b2: Option, + is_scaled: bool, + ctx: &MvpContext, +) -> (bool, Mv, Option) { + // step 3: same-POC, no scaling, first match over B0, B1, B2. + let mut avail_b = false; + let mut mv_b = [0, 0]; + for n in [b0, b1, b2].into_iter().flatten() { + if let Some(mv) = mvp_neighbour_mv_same_poc(n, ctx.x, ctx.cur_ref.poc, ctx.neigh_ref_poc) { + avail_b = true; + mv_b = mv; + break; + } + } + // step 4: when isScaledFlagLX == 0 and availableFlagLXB == 1, copy B + // into A (mvLXA = mvLXB, availableFlagLXA = 1). + let mut a_override = None; + if !is_scaled && avail_b { + a_override = Some(mv_b); + } + // step 5: when isScaledFlagLX == 0, reset B and re-derive with the + // long-term-match + scaling pass (this is the B that becomes the + // scaled candidate when A was unscaled). + if !is_scaled { + avail_b = false; + mv_b = [0, 0]; + for n in [b0, b1, b2].into_iter().flatten() { + if let Some(src) = + mvp_neighbour_mv_long_term(n, ctx.x, ctx.cur_ref.long_term, ctx.neigh_ref_long_term) + { + avail_b = true; + mv_b = maybe_scale(src, ctx); + break; + } + } + } + (avail_b, mv_b, a_override) +} + +/// Apply the §8.5.3.2.7 eq 8-181/8-195 scaling to a long-term-matched +/// source MV when the POCs differ and both pictures are short-term; +/// otherwise return the MV unchanged (eqs 8-173..8-178 / 8-187..8-192). +#[must_use] +fn maybe_scale(src: MvpSource, ctx: &MvpContext) -> Mv { + let neigh_poc = (ctx.neigh_ref_poc)(src.src_list, src.src_ref_idx); + let neigh_short = (ctx.neigh_ref_short_term)(src.src_list, src.src_ref_idx); + let both_short = neigh_short && !ctx.cur_ref.long_term; + if neigh_poc != ctx.cur_ref.poc && both_short { + scale_temporal_mv(src.mv, ctx.curr_poc, neigh_poc, ctx.cur_ref.poc) + } else { + src.mv + } +} + +/// §8.5.3.2.6 / §8.5.3.2.7 — derive the luma motion-vector predictor +/// `mvpLX` for one list `X`. +/// +/// `neigh` carries the five §6.4.2-gated spatial neighbour PUs (the A/B +/// derivation reads A0/A1 and B0/B1/B2); `ctx` carries `X`, the current +/// PU's reference picture, and the ref-pic resolvers. `col` is the +/// §8.5.3.2.8 temporal predictor `mvLXCol` (`None` when +/// `availableFlagLXCol == 0`). `mvp_lx_flag` selects `mvpListLX[ flag ]`. +/// +/// The §8.5.3.2.6 list (eq 8-170) is built as: A (if available); B (if +/// available and `mvLXA != mvLXB`); the temporal Col (if fewer than 2 and +/// available); zero-MV padding to two entries. +#[must_use] +pub fn derive_mvp_candidate( + neigh: &SpatialMergeNeighbours, + ctx: &MvpContext, + col: Option, + mvp_lx_flag: bool, +) -> Mv { + let (avail_a, mv_a, is_scaled) = derive_mvp_a(neigh.a0, neigh.a1, ctx); + let (avail_b, mv_b, a_override) = derive_mvp_b(neigh.b0, neigh.b1, neigh.b2, is_scaled, ctx); + // step 4 of B can promote A from B's same-POC match. + let (avail_a, mv_a) = if !avail_a { + match a_override { + Some(mv) => (true, mv), + None => (avail_a, mv_a), + } + } else { + (avail_a, mv_a) + }; + + // §8.5.3.2.6 step 2: Col is suppressed when A and B are both available + // with different MVs. + let col = if avail_a && avail_b && mv_a != mv_b { + None + } else { + col + }; + + // §8.5.3.2.6 step 3: assemble mvpListLX (eq 8-170). + let mut list: Vec = Vec::with_capacity(2); + if avail_a { + list.push(mv_a); + if avail_b && mv_a != mv_b { + list.push(mv_b); + } + } else if avail_b { + list.push(mv_b); + } + if list.len() < 2 { + if let Some(c) = col { + list.push(c); + } + } + while list.len() < 2 { + list.push([0, 0]); + } + + // step 4: mvpLX = mvpListLX[ mvp_lX_flag ]. + list[usize::from(mvp_lx_flag)] +} + +/// Per-4×4-block motion / mode information for one decoded picture, the +/// store the §8.7.2.4 boundary-strength derivation and the inter +/// reconstruction driver read out of. +/// +/// The grid is indexed in 4×4-luma-sample units (`PuMvField` granularity +/// of §8.5.3): block `(bx, by)` covers luma samples +/// `[bx*4, bx*4+3] × [by*4, by*4+3]`. Intra blocks carry `predMode == +/// intra` and undefined MVs; inter blocks carry the §8.5.3.2-resolved +/// `predFlagLX` / `refIdxLX` (as an opaque reference-picture identity) +/// / `mvLX`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct MotionField { + width_4: usize, + height_4: usize, + cells: Vec, +} + +/// One 4×4 block's motion / mode record in a [`MotionField`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct MotionCell { + /// `true` when the covering coding unit is intra (`MODE_INTRA`). + pub is_intra: bool, + /// `true` when the covering luma transform block holds one or more + /// non-zero transform-coefficient levels (the §8.7.2.4 `cbf` test). + pub has_nonzero_coeff: bool, + /// `PredFlagL0[x][y]`. + pub pred_flag_l0: bool, + /// `PredFlagL1[x][y]`. + pub pred_flag_l1: bool, + /// A reference-picture identity for list 0 (e.g. the POC) — the + /// §8.7.2.4 "different reference pictures" test compares these, not + /// the `RefIdxLX` list positions (NOTE 1). `i32::MIN` when unused. + pub ref_poc_l0: i32, + /// A reference-picture identity for list 1; `i32::MIN` when unused. + pub ref_poc_l1: i32, + /// `MvL0[x][y]` in quarter-luma-sample units. + pub mv_l0: Mv, + /// `MvL1[x][y]`. + pub mv_l1: Mv, +} + +impl MotionField { + /// Allocate a motion field covering a `width_luma × height_luma` + /// picture, rounded up to whole 4×4 blocks. Every cell starts as an + /// intra cell with no motion. + #[must_use] + pub fn new(width_luma: usize, height_luma: usize) -> Self { + let width_4 = width_luma.div_ceil(4); + let height_4 = height_luma.div_ceil(4); + // The unwritten background is an intra cell with no reference + // pictures (the §8.7.2.4 intra test reads `is_intra`). + let background = MotionCell { + is_intra: true, + ref_poc_l0: i32::MIN, + ref_poc_l1: i32::MIN, + ..MotionCell::default() + }; + Self { + width_4, + height_4, + cells: vec![background; width_4 * height_4], + } + } + + /// Width of the field in 4×4 blocks. + #[inline] + #[must_use] + pub fn width_4(&self) -> usize { + self.width_4 + } + + /// Height of the field in 4×4 blocks. + #[inline] + #[must_use] + pub fn height_4(&self) -> usize { + self.height_4 + } + + /// The motion cell covering luma sample `(x, y)`. + /// + /// # Panics + /// Panics if `(x, y)` lies outside the field. + #[must_use] + pub fn cell_at(&self, x: usize, y: usize) -> MotionCell { + let bx = x / 4; + let by = y / 4; + self.cells[by * self.width_4 + bx] + } + + /// Set every 4×4 cell covering the luma rectangle `[(x0, y0), + /// (x0 + w, y0 + h))` to `cell`. Coordinates and dimensions are in + /// luma samples; the rectangle is clipped to the field. + pub fn fill_rect(&mut self, x0: usize, y0: usize, w: usize, h: usize, cell: MotionCell) { + let bx0 = x0 / 4; + let by0 = y0 / 4; + let bx1 = ((x0 + w).min(self.width_4 * 4)).div_ceil(4); + let by1 = ((y0 + h).min(self.height_4 * 4)).div_ceil(4); + for by in by0..by1 { + for bx in bx0..bx1 { + self.cells[by * self.width_4 + bx] = cell; + } + } + } + + /// Mark every 4×4 cell covering the luma rectangle `[(x0, y0), + /// (x0 + w, y0 + h))` as carrying a non-zero transform coefficient + /// (the §8.7.2.4 `cbf` boundary-strength test reads this). ORs the flag + /// without disturbing the cell's motion. Coordinates are in luma + /// samples; the rectangle is clipped to the field. + pub fn mark_nonzero_coeff(&mut self, x0: usize, y0: usize, w: usize, h: usize) { + let bx0 = x0 / 4; + let by0 = y0 / 4; + let bx1 = ((x0 + w).min(self.width_4 * 4)).div_ceil(4); + let by1 = ((y0 + h).min(self.height_4 * 4)).div_ceil(4); + for by in by0..by1 { + for bx in bx0..bx1 { + self.cells[by * self.width_4 + bx].has_nonzero_coeff = true; + } + } + } +} + +/// §8.5.3.2.8 / §8.5.3.2.9 inputs for the temporal (collocated) luma +/// motion-vector predictor of one list `X`. +#[derive(Clone, Copy)] +pub struct TemporalMvContext<'a> { + /// `CtbLog2SizeY`. + pub ctb_log2_size_y: u32, + /// `pic_width_in_luma_samples`. + pub pic_width_luma: u32, + /// `pic_height_in_luma_samples`. + pub pic_height_luma: u32, + /// `PicOrderCnt( CurrPic )`. + pub curr_poc: i32, + /// `PicOrderCnt( ColPic )`. + pub col_poc: i32, + /// `PicOrderCnt( RefPicListX[ refIdxLX ] )` — the current PU's + /// reference for list `X` (`currPocDiff = currPoc − this`). + pub curr_ref_poc: i32, + /// `LongTermRefPic( CurrPic, currPb, refIdxLX, LX )` — whether the + /// current PU's `RefPicListX[ refIdxLX ]` is a long-term picture. + pub curr_ref_long_term: bool, + /// `NoBackwardPredFlag` (§8.3.5). + pub no_backward_pred: bool, + /// `collocated_from_l0_flag` — the §8.5.3.2.9 `N` used in the + /// bi-predicted-`!NoBackwardPred` branch (`N` is its value). + pub collocated_from_l0_flag: bool, + /// The list `X` of the `mvLXCol` being derived (0 or 1) — selects + /// `listCol = LX` in the bi-predicted `NoBackwardPredFlag == 1` + /// branch of §8.5.3.2.9. + pub list_x: usize, + /// Resolve a collocated-picture reference POC to whether that + /// reference is a long-term picture in the col picture's lists + /// (`LongTermRefPic( ColPic, colPb, refIdxCol, listCol )`). + pub col_ref_long_term: &'a dyn Fn(i32) -> bool, +} + +impl std::fmt::Debug for TemporalMvContext<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("TemporalMvContext") + .field("ctb_log2_size_y", &self.ctb_log2_size_y) + .field("curr_poc", &self.curr_poc) + .field("col_poc", &self.col_poc) + .field("curr_ref_poc", &self.curr_ref_poc) + .field("curr_ref_long_term", &self.curr_ref_long_term) + .field("no_backward_pred", &self.no_backward_pred) + .field("collocated_from_l0_flag", &self.collocated_from_l0_flag) + .finish_non_exhaustive() + } +} + +/// §8.5.3.2.9 — derive `mvLXCol` / `availableFlagLXCol` from one collocated +/// motion cell `col` of the collocated picture `ColPic`. +/// +/// Returns `None` when the cell is intra, when the long-term-status test +/// between the current and collocated references fails, i.e. +/// `availableFlagLXCol == 0`; otherwise `Some(mvLXCol)`. +#[must_use] +fn collocated_mv(col: MotionCell, ctx: &TemporalMvContext) -> Option { + // §8.5.3.2.9 — an intra colPb yields availableFlagLXCol == 0. + if col.is_intra { + return None; + } + // Select mvCol / refPocCol / (implicitly listCol) per §8.5.3.2.9. + let (mv_col, ref_poc_col) = if !col.pred_flag_l0 { + // predFlagL0Col == 0 ⇒ take L1. + (col.mv_l1, col.ref_poc_l1) + } else if !col.pred_flag_l1 { + // predFlagL0Col == 1 && predFlagL1Col == 0 ⇒ take L0. + (col.mv_l0, col.ref_poc_l0) + } else { + // Bi-predicted colPb. + if ctx.no_backward_pred { + // listCol = LX — the list whose mvLXCol is being derived. + if ctx.list_x == 0 { + (col.mv_l0, col.ref_poc_l0) + } else { + (col.mv_l1, col.ref_poc_l1) + } + } else if ctx.collocated_from_l0_flag { + // listCol = LN with N = collocated_from_l0_flag: N == 1 ⇒ L1. + (col.mv_l1, col.ref_poc_l1) + } else { + // N == 0 ⇒ L0. + (col.mv_l0, col.ref_poc_l0) + } + }; + + // §8.5.3.2.9 — long-term-status equality gate. + let col_long_term = (ctx.col_ref_long_term)(ref_poc_col); + if ctx.curr_ref_long_term != col_long_term { + return None; + } + + // colPocDiff / currPocDiff (eqs 8-202 / 8-203). + let col_poc_diff = ctx.col_poc - ref_poc_col; + let curr_poc_diff = ctx.curr_poc - ctx.curr_ref_poc; + + // eq 8-204 vs 8-205..8-209: copy when long-term or equal POC diffs, + // else scale via the td=colPocDiff / tb=currPocDiff distances. + if ctx.curr_ref_long_term || col_poc_diff == curr_poc_diff { + Some(mv_col) + } else { + Some(scale_temporal_mv_td_tb(mv_col, col_poc_diff, curr_poc_diff)) + } +} + +/// §8.5.3.2.9 eqs 8-205..8-209 — scale `mv` directly from the +/// `td = colPocDiff` / `tb = currPocDiff` distances (the temporal-MV +/// flavour of [`scale_temporal_mv`] that takes the differences rather +/// than the POCs). +#[must_use] +fn scale_temporal_mv_td_tb(mv: Mv, col_poc_diff: i32, curr_poc_diff: i32) -> Mv { + let td = col_poc_diff.clamp(-128, 127); + let tb = curr_poc_diff.clamp(-128, 127); + if td == 0 { + return mv; + } + let tx = (16384 + (td.abs() >> 1)) / td; + let dist_scale = (((tb * tx) + 32) >> 6).clamp(-4096, 4095); + [ + scale_component(dist_scale, mv[0]), + scale_component(dist_scale, mv[1]), + ] +} + +/// §8.5.3.2.8 — derive the temporal (collocated) luma motion-vector +/// predictor `mvLXCol` for a prediction block at luma `(x_pb, y_pb)` of +/// size `(n_pb_w, n_pb_h)`, reading the collocated picture's motion field +/// `col_field`. +/// +/// Implements the bottom-right-then-center §8.5.3.2.8 location search: +/// the bottom-right collocated location `(xPb+nPbW, yPb+nPbH)` is used +/// only when it lies in the same CTB row as `yPb` and inside the picture; +/// otherwise (or when that cell yields `availableFlagLXCol == 0`) the +/// center location `(xPb+nPbW/2, yPb+nPbH/2)` is used. Both locations are +/// snapped to a 16×16 grid (`(v>>4)<<4`). +/// +/// Returns `None` (`availableFlagLXCol == 0`) when neither location yields +/// an available collocated MV. +#[must_use] +pub fn derive_temporal_mv( + col_field: &MotionField, + x_pb: u32, + y_pb: u32, + n_pb_w: u32, + n_pb_h: u32, + ctx: &TemporalMvContext, +) -> Option { + // Step 1 — bottom-right collocated location (eqs 8-198 / 8-199). + let x_col_br = x_pb + n_pb_w; + let y_col_br = y_pb + n_pb_h; + let same_ctb_row = (y_pb >> ctx.ctb_log2_size_y) == (y_col_br >> ctx.ctb_log2_size_y); + if same_ctb_row && y_col_br < ctx.pic_height_luma && x_col_br < ctx.pic_width_luma { + let xc = (x_col_br >> 4) << 4; + let yc = (y_col_br >> 4) << 4; + let cell = col_field.cell_at(xc as usize, yc as usize); + if let Some(mv) = collocated_mv(cell, ctx) { + return Some(mv); + } + } + // Step 2 — central collocated location (eqs 8-200 / 8-201). + let x_col_ctr = x_pb + (n_pb_w >> 1); + let y_col_ctr = y_pb + (n_pb_h >> 1); + let xc = (x_col_ctr >> 4) << 4; + let yc = (y_col_ctr >> 4) << 4; + let cell = col_field.cell_at(xc as usize, yc as usize); + collocated_mv(cell, ctx) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A uni-L0 neighbour PU with the given refIdx + MV. + fn uni_l0(ref_idx: i32, mv: Mv) -> NeighbourPu { + NeighbourPu { + pred_flag_l0: true, + pred_flag_l1: false, + ref_idx_l0: ref_idx, + ref_idx_l1: -1, + mv_l0: mv, + mv_l1: [0, 0], + } + } + + fn no_split() -> PartitionContext { + PartitionContext::default() + } + + fn no_par_mrg() -> (bool, bool, bool, bool, bool) { + (false, false, false, false, false) + } + + #[test] + fn spatial_merge_all_unavailable_yields_empty() { + let neigh = SpatialMergeNeighbours::default(); + let c = derive_spatial_merge_candidates(&neigh, no_split(), no_par_mrg()); + let mut list = Vec::new(); + c.append_to(&mut list); + assert!(list.is_empty()); + } + + #[test] + fn spatial_merge_b1_pruned_against_identical_a1() { + // A1 and B1 carry identical motion ⇒ B1 is dropped (redundancy). + let pu = uni_l0(0, [4, 8]); + let neigh = SpatialMergeNeighbours { + a1: Some(pu), + b1: Some(pu), + ..Default::default() + }; + let c = derive_spatial_merge_candidates(&neigh, no_split(), no_par_mrg()); + assert!(c.a1.is_some()); + assert!(c.b1.is_none(), "B1 == A1 ⇒ pruned"); + } + + #[test] + fn spatial_merge_b1_kept_when_motion_differs() { + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [4, 8])), + b1: Some(uni_l0(0, [4, 9])), + ..Default::default() + }; + let c = derive_spatial_merge_candidates(&neigh, no_split(), no_par_mrg()); + assert!(c.a1.is_some() && c.b1.is_some()); + // Order into the list is A1 then B1 (eq 8-119). + let mut list = Vec::new(); + c.append_to(&mut list); + assert_eq!(list.len(), 2); + assert_eq!(list[0].mv_l0, [4, 8]); + assert_eq!(list[1].mv_l0, [4, 9]); + } + + /// §8.5.3.2.3 — the redundancy comparisons are gated on the *raw* + /// `availableN` of the earlier position, not its post-redundancy + /// `availableFlagN`: when A1 == B1 == B0 (all covering PUs carry the + /// same motion), B1 is pruned against A1 AND B0 is still pruned + /// against the (pruned) B1, leaving only A1. + #[test] + fn spatial_merge_b0_pruned_against_raw_b1_even_when_b1_pruned() { + let pu = uni_l0(0, [0, 0]); + let neigh = SpatialMergeNeighbours { + a1: Some(pu), + b1: Some(pu), + b0: Some(pu), + a0: Some(pu), + b2: Some(pu), + }; + let c = derive_spatial_merge_candidates(&neigh, no_split(), no_par_mrg()); + assert!(c.a1.is_some()); + assert!(c.b1.is_none(), "B1 == A1 ⇒ availableFlagB1 = 0"); + assert!(c.b0.is_none(), "B0 == raw B1 ⇒ availableFlagB0 = 0"); + assert!(c.a0.is_none(), "A0 == raw A1 ⇒ availableFlagA0 = 0"); + assert!(c.b2.is_none(), "B2 == raw A1/B1 ⇒ availableFlagB2 = 0"); + let mut list = Vec::new(); + c.append_to(&mut list); + assert_eq!(list.len(), 1, "only A1 survives"); + } + + /// The B1-vs-A1 raw gate also holds when B1 is excluded by the + /// horizontal-split partition rule: an excluded B1 (raw available = + /// FALSE) does NOT prune an identical B0. + #[test] + fn spatial_merge_b0_kept_when_b1_raw_unavailable() { + let pu = uni_l0(0, [4, 0]); + let neigh = SpatialMergeNeighbours { + b1: Some(pu), + b0: Some(pu), + ..Default::default() + }; + // partIdx 1 of a horizontal split forces availableB1 = FALSE. + let part = PartitionContext { + part_idx: 1, + part_mode_vertical_split: false, + part_mode_horizontal_split: true, + }; + let c = derive_spatial_merge_candidates(&neigh, part, no_par_mrg()); + assert!(c.b1.is_none(), "partition rule excludes B1"); + assert!( + c.b0.is_some(), + "raw-unavailable B1 does not prune an identical B0" + ); + } + + #[test] + fn spatial_merge_b2_dropped_when_four_available() { + // A0,A1,B0,B1 all available with distinct motion ⇒ list full ⇒ B2 + // excluded even though it is itself available + distinct. + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [1, 0])), + b1: Some(uni_l0(0, [2, 0])), + b0: Some(uni_l0(0, [3, 0])), + a0: Some(uni_l0(0, [4, 0])), + b2: Some(uni_l0(0, [5, 0])), + }; + let c = derive_spatial_merge_candidates(&neigh, no_split(), no_par_mrg()); + assert!(c.a1.is_some() && c.b1.is_some() && c.b0.is_some() && c.a0.is_some()); + assert!(c.b2.is_none(), "four already available ⇒ B2 excluded"); + } + + #[test] + fn spatial_merge_a1_excluded_for_vertical_split_part1() { + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [7, 7])), + ..Default::default() + }; + let part = PartitionContext { + part_idx: 1, + part_mode_vertical_split: true, + part_mode_horizontal_split: false, + }; + let c = derive_spatial_merge_candidates(&neigh, part, no_par_mrg()); + assert!(c.a1.is_none(), "PART_Nx2N partIdx 1 ⇒ A1 excluded"); + } + + #[test] + fn spatial_merge_same_par_mrg_forces_unavailable() { + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [1, 1])), + b1: Some(uni_l0(0, [2, 2])), + ..Default::default() + }; + // A1's neighbour is in the same parallel-merge region. + let c = + derive_spatial_merge_candidates(&neigh, no_split(), (true, false, false, false, false)); + assert!(c.a1.is_none()); + assert!(c.b1.is_some()); + } + + #[test] + fn combined_bi_pairs_l0_and_l1_per_table_8_7() { + // Two B candidates: cand0 uni-L0, cand1 uni-L1. combIdx 0 pairs + // l0CandIdx=0 (cand0's L0) with l1CandIdx=1 (cand1's L1). + let cand0 = MergeCandidate { + ref_idx_l0: 0, + ref_idx_l1: -1, + pred_flag_l0: true, + pred_flag_l1: false, + mv_l0: [4, 0], + mv_l1: [0, 0], + }; + let cand1 = MergeCandidate { + ref_idx_l0: -1, + ref_idx_l1: 0, + pred_flag_l0: false, + pred_flag_l1: true, + mv_l0: [0, 0], + mv_l1: [-4, 0], + }; + let mut list = vec![cand0, cand1]; + // POCs distinct so the eq 8-143 distinctness test passes. + append_combined_bi_candidates(&mut list, 2, 5, |list_x, _| if list_x == 0 { 0 } else { 8 }); + assert!(list.len() > 2, "at least one combined candidate added"); + let comb = list[2]; + assert!(comb.pred_flag_l0 && comb.pred_flag_l1, "combined is bi"); + assert_eq!(comb.mv_l0, [4, 0], "L0 from cand0"); + assert_eq!(comb.mv_l1, [-4, 0], "L1 from cand1"); + } + + #[test] + fn combined_bi_skips_degenerate_same_pic_same_mv() { + // Both candidates point at the same POC with the same MV ⇒ every + // pair is degenerate ⇒ no combined candidate is produced. + let bi = MergeCandidate { + ref_idx_l0: 0, + ref_idx_l1: 0, + pred_flag_l0: true, + pred_flag_l1: true, + mv_l0: [2, 2], + mv_l1: [2, 2], + }; + let mut list = vec![bi, bi]; + append_combined_bi_candidates(&mut list, 2, 5, |_, _| 0); + assert_eq!(list.len(), 2, "all pairs degenerate ⇒ nothing added"); + } + + #[test] + fn combined_bi_noop_below_two_orig() { + let mut list = vec![MergeCandidate::default()]; + append_combined_bi_candidates(&mut list, 1, 5, |_, _| 0); + assert_eq!(list.len(), 1); + } + + #[test] + fn build_merge_selects_index_and_pads_with_zero() { + // One spatial candidate; merge_idx 2 lands in the zero padding. + let spatial = SpatialMergeCandidates { + a1: Some(uni_l0(0, [4, 4]).to_candidate()), + ..Default::default() + }; + let params = MergeListParams { + slice_is_b: false, + max_num_merge_cand: 5, + zero_num_ref_idx: 1, + }; + let chosen = build_merge_candidate(&spatial, None, params, 2, 16, |_, _| 0); + // Index 2 is a zero-MV uni-L0 candidate. + assert_eq!(chosen.mv_l0, [0, 0]); + assert!(chosen.pred_flag_l0 && !chosen.pred_flag_l1); + } + + #[test] + fn build_merge_step10_drops_l1_for_8x4_or_4x8() { + // A bi candidate selected at a PU with nOrigPbW + nOrigPbH == 12 + // (8x4 / 4x8) ⇒ L1 is dropped (step 10). + let bi = MergeCandidate { + ref_idx_l0: 0, + ref_idx_l1: 0, + pred_flag_l0: true, + pred_flag_l1: true, + mv_l0: [1, 1], + mv_l1: [2, 2], + }; + let spatial = SpatialMergeCandidates { + a1: Some(bi), + ..Default::default() + }; + let params = MergeListParams { + slice_is_b: true, + max_num_merge_cand: 5, + zero_num_ref_idx: 1, + }; + let chosen = build_merge_candidate(&spatial, None, params, 0, 12, |_, _| 0); + assert!(chosen.pred_flag_l0); + assert!(!chosen.pred_flag_l1, "8x4/4x8 bi ⇒ uni-L0"); + assert_eq!(chosen.ref_idx_l1, -1); + } + + /// Build an [`MvpContext`] for list 0 where every neighbour reference + /// at `(list, ref_idx)` resolves to the same short-term POC `ref_poc` + /// and the current reference is short-term at `cur_poc`. + fn mvp_ctx_same<'a>( + curr_poc: i32, + cur_poc: i32, + ref_poc: &'a dyn Fn(usize, i32) -> i32, + long_term: &'a dyn Fn(usize, i32) -> bool, + short_term: &'a dyn Fn(usize, i32) -> bool, + ) -> MvpContext<'a> { + MvpContext { + x: 0, + curr_poc, + cur_ref: RefPicId { + poc: cur_poc, + long_term: false, + }, + neigh_ref_poc: ref_poc, + neigh_ref_long_term: long_term, + neigh_ref_short_term: short_term, + } + } + + #[test] + fn mvp_no_neighbours_pads_zero() { + let neigh = SpatialMergeNeighbours::default(); + let rp = |_: usize, _: i32| 0; + let lt = |_: usize, _: i32| false; + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(4, 0, &rp, <, &st); + // Both list entries are zero MVs. + assert_eq!(derive_mvp_candidate(&neigh, &ctx, None, false), [0, 0]); + assert_eq!(derive_mvp_candidate(&neigh, &ctx, None, true), [0, 0]); + } + + #[test] + fn mvp_a_same_poc_no_scaling() { + // A1 available, same-POC ⇒ mvpListLX[0] = A1's MV unchanged. + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [12, -8])), + ..Default::default() + }; + let rp = |_: usize, _: i32| 0; // neighbour ref POC == cur ref POC. + let lt = |_: usize, _: i32| false; + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(4, 0, &rp, <, &st); + assert_eq!(derive_mvp_candidate(&neigh, &ctx, None, false), [12, -8]); + } + + #[test] + fn mvp_b_promotes_to_a_when_no_left_neighbour() { + // No A0/A1 ⇒ isScaledFlag == 0. B1 same-POC ⇒ step 4 copies B + // into A, so mvpListLX[0] = B's MV. + let neigh = SpatialMergeNeighbours { + b1: Some(uni_l0(0, [5, 5])), + ..Default::default() + }; + let rp = |_: usize, _: i32| 0; + let lt = |_: usize, _: i32| false; + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(4, 0, &rp, <, &st); + assert_eq!(derive_mvp_candidate(&neigh, &ctx, None, false), [5, 5]); + } + + #[test] + fn mvp_col_inserted_when_a_b_agree() { + // A and B both available with the SAME MV ⇒ list has one entry + // from A, Col fills slot 1 (step 2 keeps Col because mvA == mvB). + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [3, 3])), + b1: Some(uni_l0(0, [3, 3])), + ..Default::default() + }; + let rp = |_: usize, _: i32| 0; + let lt = |_: usize, _: i32| false; + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(4, 0, &rp, <, &st); + // slot 0 = A's MV, slot 1 = Col. + assert_eq!( + derive_mvp_candidate(&neigh, &ctx, Some([9, 9]), false), + [3, 3] + ); + assert_eq!( + derive_mvp_candidate(&neigh, &ctx, Some([9, 9]), true), + [9, 9] + ); + } + + #[test] + fn mvp_col_suppressed_when_a_b_differ() { + // A and B available with DIFFERENT MVs ⇒ Col suppressed (step 2); + // list = [mvA, mvB]. + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [1, 0])), + b1: Some(uni_l0(0, [2, 0])), + ..Default::default() + }; + let rp = |_: usize, _: i32| 0; + let lt = |_: usize, _: i32| false; + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(4, 0, &rp, <, &st); + assert_eq!( + derive_mvp_candidate(&neigh, &ctx, Some([9, 9]), false), + [1, 0] + ); + assert_eq!( + derive_mvp_candidate(&neigh, &ctx, Some([9, 9]), true), + [2, 0] + ); + } + + #[test] + fn mvp_a_scales_when_poc_differs_short_term() { + // A0 unavailable for same-POC (neighbour ref POC != cur ref POC), + // but long-term status matches ⇒ pass-2 picks A1 + scales. + // curr_poc = 8, cur ref POC = 4 ⇒ tb = 4. Neighbour ref POC = 2 + // ⇒ td = 6. mv = [64, 0]. + // tx = (16384 + 3)/6 = 2731; distScale = clip((4*2731+32)>>6) = + // (10956>>6) = 171; comp = (171*64 + 127)>>8 = (10944+127)>>8 = + // 11071>>8 = 43. + let neigh = SpatialMergeNeighbours { + a1: Some(uni_l0(0, [64, 0])), + ..Default::default() + }; + // Same-POC pass fails: neighbour ref POC (2) != cur ref POC (4). + let rp = |_: usize, _: i32| 2; + let lt = |_: usize, _: i32| false; // long-term status matches (both short). + let st = |_: usize, _: i32| true; + let ctx = mvp_ctx_same(8, 4, &rp, <, &st); + assert_eq!(derive_mvp_candidate(&neigh, &ctx, None, false), [43, 0]); + } + + #[test] + fn scale_temporal_mv_known_vector() { + // Same arithmetic as the test above, exercised directly. + assert_eq!(scale_temporal_mv([64, 0], 8, 2, 4), [43, 0]); + } + + #[test] + fn mv_reconstruct_fractional_no_wrap() { + // mvp + mvd, no wrap needed. + assert_eq!(reconstruct_mv([10, -4], [3, 2], false), [13, -2]); + } + + #[test] + fn mv_reconstruct_wraps_to_negative_half() { + // A component that exceeds 2^15 − 1 folds into the negative half. + // mvp = 2^15 − 1, mvd = 1 ⇒ u = 2^15 ⇒ result = 2^15 − 2^16 = −2^15. + let r = reconstruct_mv([MV_HALF - 1, 0], [1, 0], false); + assert_eq!(r[0], -MV_HALF); + } + + #[test] + fn mv_reconstruct_wraps_negative_underflow() { + // mvp = −2^15, mvd = −1 ⇒ sum = −2^15 − 1 + 2^16 = 2^15 − 1 ⇒ + // stays positive (the wrap keeps the value in range). + let r = reconstruct_mv([-MV_HALF, 0], [-1, 0], false); + assert_eq!(r[0], MV_HALF - 1); + } + + #[test] + fn mv_reconstruct_integer_path_quantizes_predictor() { + // integer path: ((mvp >> 2) + mvd) << 2. mvp = 13 (>>2 = 3), + // mvd = 1 ⇒ (3 + 1) << 2 = 16. + let r = reconstruct_mv([13, 0], [1, 0], true); + assert_eq!(r[0], 16); + } + + #[test] + fn chroma_mv_420() { + // 4:2:0: SubWidthC = SubHeightC = 2 ⇒ mvC = mvL * 2 / 2 = mvL. + assert_eq!(derive_chroma_mv([7, -9], 2, 2), [7, -9]); + } + + #[test] + fn chroma_mv_422() { + // 4:2:2: SubWidthC = 2, SubHeightC = 1 ⇒ mvCx = mvLx, mvCy = mvLy*2. + assert_eq!(derive_chroma_mv([7, -9], 2, 1), [7, -18]); + } + + #[test] + fn chroma_mv_444() { + // 4:4:4: SubWidthC = SubHeightC = 1 ⇒ mvC = mvL * 2. + assert_eq!(derive_chroma_mv([7, -9], 1, 1), [14, -18]); + } + + #[test] + fn zero_merge_p_slice_pads_uni_l0() { + let mut list = vec![MergeCandidate { + ref_idx_l0: 0, + ref_idx_l1: -1, + pred_flag_l0: true, + pred_flag_l1: false, + mv_l0: [4, 4], + mv_l1: [0, 0], + }]; + append_zero_merge_candidates(&mut list, false, 2, 5); + assert_eq!(list.len(), 5); + // The four added candidates are uni-L0 zero MVs; refIdx ramps + // 0,1 then clamps to 0 (zeroIdx >= numRefIdx). + assert_eq!(list[1].ref_idx_l0, 0); + assert_eq!(list[2].ref_idx_l0, 1); + assert_eq!(list[3].ref_idx_l0, 0); + assert_eq!(list[4].ref_idx_l0, 0); + for c in &list[1..] { + assert_eq!(c.mv_l0, [0, 0]); + assert!(c.pred_flag_l0 && !c.pred_flag_l1); + } + } + + #[test] + fn zero_merge_b_slice_pads_bi() { + let mut list = Vec::new(); + append_zero_merge_candidates(&mut list, true, 1, 3); + assert_eq!(list.len(), 3); + for c in &list { + assert!(c.pred_flag_l0 && c.pred_flag_l1, "B zero cand is bi"); + assert_eq!(c.mv_l0, [0, 0]); + assert_eq!(c.mv_l1, [0, 0]); + } + // numRefIdx = 1 ⇒ only zeroIdx 0 maps to refIdx 0; rest clamp. + assert_eq!(list[0].ref_idx_l0, 0); + assert_eq!(list[1].ref_idx_l0, 0); + } + + #[test] + fn motion_field_fill_and_query() { + let mut mf = MotionField::new(64, 64); + assert_eq!(mf.width_4(), 16); + assert_eq!(mf.height_4(), 16); + let inter = MotionCell { + is_intra: false, + has_nonzero_coeff: true, + pred_flag_l0: true, + pred_flag_l1: false, + ref_poc_l0: 0, + ref_poc_l1: i32::MIN, + mv_l0: [8, -4], + mv_l1: [0, 0], + }; + mf.fill_rect(16, 16, 32, 32, inter); + // Inside the rect. + assert_eq!(mf.cell_at(20, 20), inter); + assert_eq!(mf.cell_at(47, 47), inter); + // Outside stays intra default. + assert!(mf.cell_at(0, 0).is_intra); + assert!(mf.cell_at(48, 48).is_intra); + } + + // ---- §8.5.3.2.8 / §8.5.3.2.9 temporal collocated MV ---- + + fn col_field_with(cell: MotionCell, w: usize, h: usize) -> MotionField { + let mut mf = MotionField::new(w, h); + mf.fill_rect(0, 0, w, h, cell); + mf + } + + fn uni_l0_cell(ref_poc: i32, mv: Mv) -> MotionCell { + MotionCell { + is_intra: false, + has_nonzero_coeff: false, + pred_flag_l0: true, + pred_flag_l1: false, + ref_poc_l0: ref_poc, + ref_poc_l1: i32::MIN, + mv_l0: mv, + mv_l1: [0, 0], + } + } + + fn temporal_ctx<'a>(short_term: &'a dyn Fn(i32) -> bool) -> TemporalMvContext<'a> { + TemporalMvContext { + ctb_log2_size_y: 4, + pic_width_luma: 64, + pic_height_luma: 64, + curr_poc: 4, + col_poc: 0, + curr_ref_poc: 0, + curr_ref_long_term: false, + no_backward_pred: true, + collocated_from_l0_flag: true, + list_x: 0, + col_ref_long_term: short_term, + } + } + + #[test] + fn temporal_intra_col_is_unavailable() { + // An intra collocated cell yields availableFlagLXCol == 0. + let mf = MotionField::new(64, 64); // all-intra background. + let lt = |_: i32| false; + let ctx = temporal_ctx(<); + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &ctx), None); + } + + #[test] + fn temporal_equal_poc_diff_copies_mv() { + // colPoc 0, col ref poc -4 ⇒ colPocDiff 4. currPoc 4, currRef poc 0 + // ⇒ currPocDiff 4. Equal ⇒ mvLXCol = mvCol unchanged. + let cell = uni_l0_cell(-4, [20, -8]); + let mf = col_field_with(cell, 64, 64); + let lt = |_: i32| false; + let ctx = temporal_ctx(<); + // PU at (0,0) 16×16: bottom-right (16,16) is in the next CTB row + // (yPb>>4 == 0, yColBr>>4 == 1) ⇒ falls through to center (8,8). + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &ctx), Some([20, -8])); + } + + #[test] + fn temporal_unequal_poc_diff_scales_mv() { + // colPocDiff 2 (col 0, col ref -2), currPocDiff 4 ⇒ scale. + // td=2, tb=4: tx=(16384+1)/2=8192; dist=(4*8192+32)>>6=512; + // scale_component(512, 64) = (512*64+127)>>8 = (32768+127)>>8 = 128. + let cell = uni_l0_cell(-2, [64, 0]); + let mf = col_field_with(cell, 64, 64); + let lt = |_: i32| false; + let ctx = temporal_ctx(<); + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &ctx), Some([128, 0])); + } + + #[test] + fn temporal_long_term_mismatch_is_unavailable() { + // Current ref short-term, col ref long-term ⇒ mismatch ⇒ None. + let cell = uni_l0_cell(-4, [20, 0]); + let mf = col_field_with(cell, 64, 64); + let lt = |_: i32| true; // col ref is long-term. + let ctx = temporal_ctx(<); + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &ctx), None); + } + + #[test] + fn temporal_long_term_match_copies_without_scaling() { + // Both long-term ⇒ copy mvCol regardless of POC diffs. + let cell = uni_l0_cell(-2, [33, -7]); + let mf = col_field_with(cell, 64, 64); + let lt = |_: i32| true; + let ctx = TemporalMvContext { + curr_ref_long_term: true, + ..temporal_ctx(<) + }; + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &ctx), Some([33, -7])); + } + + #[test] + fn temporal_bottom_right_used_when_in_same_ctb_row() { + // An 8×8 PU at (0,0): bottom-right (8,8) snaps to (0,0), same CTB + // row ⇒ the BR cell is read. Put a distinct MV only at (0,0). + let cell = uni_l0_cell(-4, [12, 4]); + let mf = col_field_with(cell, 64, 64); + let lt = |_: i32| false; + let ctx = temporal_ctx(<); + assert_eq!(derive_temporal_mv(&mf, 0, 0, 8, 8, &ctx), Some([12, 4])); + } + + /// A bi-predicted collocated cell with distinct L0 / L1 motion, both + /// references at POC distance 4 from the col picture so no scaling + /// perturbs the listCol selection under test. + fn bi_cell() -> MotionCell { + MotionCell { + is_intra: false, + has_nonzero_coeff: false, + pred_flag_l0: true, + pred_flag_l1: true, + ref_poc_l0: -4, + ref_poc_l1: 4, + mv_l0: [10, 2], + mv_l1: [-30, -6], + } + } + + #[test] + fn temporal_bi_col_no_backward_pred_selects_list_x() { + // §8.5.3.2.9 bi-predicted colPb, NoBackwardPredFlag == 1: + // listCol = LX — the list whose mvLXCol is being derived. + let mf = col_field_with(bi_cell(), 64, 64); + let lt = |_: i32| false; + let l0 = TemporalMvContext { + list_x: 0, + ..temporal_ctx(<) + }; + // colPocDiff (0 − −4 = 4) == currPocDiff (4 − 0 = 4) ⇒ copy. + assert_eq!(derive_temporal_mv(&mf, 0, 0, 16, 16, &l0), Some([10, 2])); + let l1 = TemporalMvContext { + list_x: 1, + curr_ref_poc: -4, // keep currPocDiff == colPocDiff (both 8). + curr_poc: 4, + ..temporal_ctx(<) + }; + // listCol = L1: colPocDiff = 0 − 4 = −4, currPocDiff = 4 − −4 = 8 + // ⇒ scaled (eqs 8-205..8-207): td = −4, tx = (16384+2)/−4 = −4096 + // (truncating division), tb = 8, distScaleFactor = + // (8·−4096 + 32) >> 6 = −32736 >> 6 = −512. + let got = derive_temporal_mv(&mf, 0, 0, 16, 16, &l1).unwrap(); + // comp(−512, −30): v = 15360 ⇒ (15360+127)>>8 = 60; + // comp(−512, −6): v = 3072 ⇒ (3072+127)>>8 = 12. + assert_eq!(got, [60, 12], "L1 motion selected and scaled"); + } + + #[test] + fn temporal_bi_col_backward_pred_selects_list_n() { + // §8.5.3.2.9 bi-predicted colPb, NoBackwardPredFlag == 0: + // listCol = LN with N being the VALUE of collocated_from_l0_flag + // (flag == 1 ⇒ L1, flag == 0 ⇒ L0). + let mf = col_field_with(bi_cell(), 64, 64); + let lt = |_: i32| false; + let base = temporal_ctx(<); + let from_l0 = TemporalMvContext { + no_backward_pred: false, + collocated_from_l0_flag: true, + curr_poc: 4, + curr_ref_poc: 8, // currPocDiff = −4 == colPocDiff (L1) ⇒ copy. + ..base + }; + assert_eq!( + derive_temporal_mv(&mf, 0, 0, 16, 16, &from_l0), + Some([-30, -6]), + "collocated_from_l0_flag == 1 ⇒ N = 1 ⇒ the col L1 motion" + ); + let from_l1 = TemporalMvContext { + no_backward_pred: false, + collocated_from_l0_flag: false, + curr_poc: 4, + curr_ref_poc: 0, // currPocDiff = 4 == colPocDiff (L0) ⇒ copy. + ..base + }; + assert_eq!( + derive_temporal_mv(&mf, 0, 0, 16, 16, &from_l1), + Some([10, 2]), + "collocated_from_l0_flag == 0 ⇒ N = 0 ⇒ the col L0 motion" + ); + } +} diff --git a/vendor/oxideav-h265/src/nal.rs b/vendor/oxideav-h265/src/nal.rs new file mode 100644 index 0000000..b776bed --- /dev/null +++ b/vendor/oxideav-h265/src/nal.rs @@ -0,0 +1,342 @@ +//! H.265 / HEVC NAL-unit byte-stream walker. +//! +//! This module implements the byte-stream framing and NAL-unit header +//! parse described in ITU-T Rec. H.265 (ISO/IEC 23008-2): +//! +//! * **Annex B** — byte-stream format. NAL units are separated by a +//! start-code prefix `0x00 0x00 0x01` (or `0x00 0x00 0x00 0x01` +//! when a leading zero byte is present). +//! * **§7.3.1.1** — NAL unit syntax. The first two bytes of the +//! RBSP-bearing NAL payload are the NAL unit header. +//! * **§7.4.1.1** — Emulation-prevention. Inside the payload, the +//! sequence `0x00 0x00 0x03` decodes to `0x00 0x00` (the `0x03` +//! byte is the emulation-prevention escape). +//! +//! Scope of this module: split a byte stream into NAL units, parse +//! their two-byte headers, and surface the unescaped RBSP body. The +//! SPS/PPS/VPS/slice payloads themselves are not parsed here. + +/// Errors that can arise while walking a NAL byte stream. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum NalError { + /// The byte stream did not contain any NAL start code. + NoStartCode, + /// `forbidden_zero_bit` (the high bit of the first NAL-header + /// byte) was set, which is reserved per §7.4.2.2 and indicates a + /// malformed stream. + ForbiddenZeroBitSet, + /// `nuh_temporal_id_plus1` was zero. §7.4.2.2 requires the + /// field to be strictly greater than zero. + TemporalIdPlus1Zero, + /// A NAL unit was shorter than the two-byte header. + TruncatedHeader, +} + +impl core::fmt::Display for NalError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::NoStartCode => f.write_str("no Annex B start code in input"), + Self::ForbiddenZeroBitSet => f.write_str("forbidden_zero_bit was set in NAL header"), + Self::TemporalIdPlus1Zero => f.write_str("nuh_temporal_id_plus1 was zero"), + Self::TruncatedHeader => f.write_str("NAL unit shorter than two-byte header"), + } + } +} + +impl std::error::Error for NalError {} + +/// Parsed NAL unit header per H.265 §7.3.1.2. +/// +/// Layout (16 bits, big-endian): +/// +/// ```text +/// bit 0 : forbidden_zero_bit (1 bit, must be 0) +/// bits 1..=6 : nal_unit_type (6 bits) +/// bits 7..=12 : nuh_layer_id (6 bits) +/// bits 13..=15 : nuh_temporal_id_plus1 (3 bits, must be > 0) +/// ``` +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NalHeader { + /// `nal_unit_type` field, 0..=63. The interpretation table is in + /// §7.4.2.2 (Table 7-1). + pub nal_unit_type: u8, + /// `nuh_layer_id` field, 0..=63 (5 bits used in the base spec; + /// the sixth bit is reserved for layered extensions). + pub nuh_layer_id: u8, + /// `TemporalId` derived value, equal to + /// `nuh_temporal_id_plus1 - 1`, range 0..=6. + pub temporal_id: u8, +} + +impl NalHeader { + /// Parse the two-byte NAL header from the first two bytes of an + /// (already-unescaped) NAL unit payload. + pub fn parse(bytes: &[u8]) -> Result { + if bytes.len() < 2 { + return Err(NalError::TruncatedHeader); + } + let b0 = bytes[0]; + let b1 = bytes[1]; + + if b0 & 0x80 != 0 { + return Err(NalError::ForbiddenZeroBitSet); + } + + let nal_unit_type = (b0 >> 1) & 0x3F; + let nuh_layer_id = ((b0 & 0x01) << 5) | ((b1 >> 3) & 0x1F); + let temporal_id_plus1 = b1 & 0x07; + if temporal_id_plus1 == 0 { + return Err(NalError::TemporalIdPlus1Zero); + } + Ok(Self { + nal_unit_type, + nuh_layer_id, + temporal_id: temporal_id_plus1 - 1, + }) + } + + /// Convenience predicate: per §7.4.2.2 (Table 7-1) NAL units with + /// `nal_unit_type` in `[32, 40]` are non-VCL parameter-set or + /// delimiter units (VPS/SPS/PPS/AUD/EOS/EOB/FD/prefix-SEI/ + /// suffix-SEI). NAL units below 32 are VCL slice payloads. + pub fn is_vcl(&self) -> bool { + self.nal_unit_type < 32 + } +} + +/// One NAL unit extracted from an Annex B byte stream. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NalUnit { + /// Parsed header for this unit. + pub header: NalHeader, + /// Unescaped RBSP payload, excluding the two header bytes. + /// Emulation-prevention `0x03` bytes have been stripped per + /// §7.4.1.1. + pub rbsp: Vec, + /// The coded (still-escaped) payload bytes, excluding the two + /// header bytes. The §7.4.7.1 `entry_point_offset_minus1` subset + /// boundaries count emulation-prevention bytes, so the WPP / tile + /// substream split needs this form alongside the RBSP. + pub escaped: Vec, +} + +/// Strip emulation-prevention bytes per §7.4.1.1. +/// +/// For every occurrence of `0x00 0x00 0x03` in the input, the `0x03` +/// byte is dropped from the output. This is the inverse of the +/// encoder-side emulation-prevention insertion that prevents an +/// in-payload byte sequence from being mistaken for a start code. +pub fn strip_emulation_prevention(escaped: &[u8]) -> Vec { + let mut out = Vec::with_capacity(escaped.len()); + let mut zero_run: u8 = 0; + for &b in escaped { + if zero_run >= 2 && b == 0x03 { + // §7.4.1.1: drop the 0x03 escape byte after `00 00`. + zero_run = 0; + continue; + } + out.push(b); + if b == 0x00 { + zero_run = zero_run.saturating_add(1); + } else { + zero_run = 0; + } + } + out +} + +/// Iterator that walks an Annex B byte stream and yields one NAL +/// unit per `next()` call. +#[derive(Debug, Clone)] +pub struct NalIter<'a> { + buf: &'a [u8], + cursor: usize, +} + +impl<'a> NalIter<'a> { + /// Construct a walker over `buf`. The walker scans forward for + /// the first Annex B start code; leading bytes prior to it are + /// discarded (this matches the behaviour required by Annex B, + /// which permits arbitrary leading-zero padding). + pub fn new(buf: &'a [u8]) -> Self { + Self { buf, cursor: 0 } + } + + /// Locate the next start-code prefix at or after `from` and + /// return `(start_code_offset, payload_offset)` where + /// `payload_offset` is the byte immediately past the start + /// code's terminating `0x01`. Returns `None` if no start code + /// remains in the buffer. + fn find_start_code(&self, from: usize) -> Option<(usize, usize)> { + let buf = self.buf; + let mut i = from; + while i + 2 < buf.len() { + if buf[i] == 0x00 && buf[i + 1] == 0x00 { + if buf[i + 2] == 0x01 { + return Some((i, i + 3)); + } + if buf[i + 2] == 0x00 && i + 3 < buf.len() && buf[i + 3] == 0x01 { + return Some((i, i + 4)); + } + } + i += 1; + } + None + } +} + +impl Iterator for NalIter<'_> { + type Item = Result; + + fn next(&mut self) -> Option { + let (_, payload_start) = self.find_start_code(self.cursor)?; + let payload_end = match self.find_start_code(payload_start) { + Some((next_sc, _)) => next_sc, + None => self.buf.len(), + }; + self.cursor = payload_end; + + // §B.1.2 permits `trailing_zero_8bits` between NAL units + // and `leading_zero_8bits` before the next start code. They + // appear in the buffer as zero bytes immediately preceding + // the next start code; for the purpose of this round (which + // does not yet parse the RBSP stop bit) we keep the payload + // exactly as the start codes delimit it. + let payload = &self.buf[payload_start..payload_end]; + + let unescaped = strip_emulation_prevention(payload); + let header = match NalHeader::parse(&unescaped) { + Ok(h) => h, + Err(e) => return Some(Err(e)), + }; + let rbsp = unescaped[2..].to_vec(); + // The escaped form, aligned with `rbsp` (header bytes dropped). + // The two header bytes are never part of an emulation-prevention + // pattern's tail (`nuh_temporal_id_plus1 != 0` forbids 0x00 0x00 + // at the header), so dropping them keeps the two forms in step. + let escaped = payload[2..].to_vec(); + Some(Ok(NalUnit { + header, + rbsp, + escaped, + })) + } +} + +/// Convenience: collect every NAL unit in `buf` into a `Vec`. Stops +/// at the first parse error. +pub fn collect_nal_units(buf: &[u8]) -> Result, NalError> { + let mut iter = NalIter::new(buf); + let mut out = Vec::new(); + // If the very first call finds no start code at all, surface a + // dedicated `NoStartCode` error rather than returning an empty + // vec — an empty Annex B stream is almost always a caller bug. + let first = iter.next(); + match first { + None => Err(NalError::NoStartCode), + Some(Ok(u)) => { + out.push(u); + for n in iter { + out.push(n?); + } + Ok(out) + } + Some(Err(e)) => Err(e), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Build a NAL header pair `(b0, b1)` for the given fields. + fn header_bytes(nal_unit_type: u8, nuh_layer_id: u8, temporal_id: u8) -> [u8; 2] { + let b0 = ((nal_unit_type & 0x3F) << 1) | ((nuh_layer_id >> 5) & 0x01); + let b1 = ((nuh_layer_id & 0x1F) << 3) | ((temporal_id + 1) & 0x07); + [b0, b1] + } + + #[test] + fn parses_single_nal_with_three_byte_start_code() { + // Annex B stream: [00 00 01] [hdr0 hdr1] [payload...] + // VPS (nal_unit_type=32), layer 0, temporal_id 0. + let h = header_bytes(32, 0, 0); + let stream: Vec = [0x00, 0x00, 0x01, h[0], h[1], 0xAA, 0xBB, 0xCC].to_vec(); + let units = collect_nal_units(&stream).expect("walker"); + assert_eq!(units.len(), 1); + assert_eq!(units[0].header.nal_unit_type, 32); + assert_eq!(units[0].header.nuh_layer_id, 0); + assert_eq!(units[0].header.temporal_id, 0); + assert!(!units[0].header.is_vcl()); + assert_eq!(units[0].rbsp, vec![0xAA, 0xBB, 0xCC]); + } + + #[test] + fn parses_four_byte_start_code_and_two_units() { + // SPS (33), then a slice IDR_W_RADL (19, VCL). + let h_sps = header_bytes(33, 0, 0); + let h_idr = header_bytes(19, 0, 0); + let mut stream = vec![0x00, 0x00, 0x00, 0x01, h_sps[0], h_sps[1], 0x10, 0x20]; + stream.extend_from_slice(&[0x00, 0x00, 0x01, h_idr[0], h_idr[1], 0x30, 0x40]); + let units = collect_nal_units(&stream).expect("walker"); + assert_eq!(units.len(), 2); + assert_eq!(units[0].header.nal_unit_type, 33); + assert_eq!(units[0].rbsp, vec![0x10, 0x20]); + assert_eq!(units[1].header.nal_unit_type, 19); + assert!(units[1].header.is_vcl()); + assert_eq!(units[1].rbsp, vec![0x30, 0x40]); + } + + #[test] + fn strips_emulation_prevention_byte() { + // Payload literally contains `00 00 00`; after escape that's + // `00 00 03 00` on the wire. The walker should expose the + // original `00 00 00` in `rbsp`. + let h = header_bytes(34, 0, 0); // PPS + let stream = vec![0x00, 0x00, 0x01, h[0], h[1], 0x00, 0x00, 0x03, 0x00, 0xFF]; + let units = collect_nal_units(&stream).expect("walker"); + assert_eq!(units.len(), 1); + assert_eq!(units[0].rbsp, vec![0x00, 0x00, 0x00, 0xFF]); + } + + #[test] + fn rejects_forbidden_zero_bit() { + // Manually craft a header byte with the forbidden bit set. + let stream = vec![0x00, 0x00, 0x01, 0x80, 0x01]; + let err = collect_nal_units(&stream).unwrap_err(); + assert_eq!(err, NalError::ForbiddenZeroBitSet); + } + + #[test] + fn rejects_zero_temporal_id_plus1() { + // nal_unit_type 32, layer 0, temporal_id_plus1 = 0 (b1 low + // three bits all zero) — must be rejected per §7.4.2.2. + let stream = vec![0x00, 0x00, 0x01, 0x40, 0x00]; + let err = collect_nal_units(&stream).unwrap_err(); + assert_eq!(err, NalError::TemporalIdPlus1Zero); + } + + #[test] + fn no_start_code_is_an_error() { + let stream = vec![0xAA, 0xBB, 0xCC]; + let err = collect_nal_units(&stream).unwrap_err(); + assert_eq!(err, NalError::NoStartCode); + } + + #[test] + fn header_field_packing_round_trip() { + // nal_unit_type=21 (CRA_NUT), nuh_layer_id=0, temporal_id=2. + let h = header_bytes(21, 0, 2); + let parsed = NalHeader::parse(&[h[0], h[1]]).unwrap(); + assert_eq!(parsed.nal_unit_type, 21); + assert_eq!(parsed.nuh_layer_id, 0); + assert_eq!(parsed.temporal_id, 2); + assert!(parsed.is_vcl()); + + // Also exercise a non-zero layer id (e.g. SHVC enhancement). + let h2 = header_bytes(1, 5, 1); + let parsed2 = NalHeader::parse(&[h2[0], h2[1]]).unwrap(); + assert_eq!(parsed2.nuh_layer_id, 5); + assert_eq!(parsed2.temporal_id, 1); + } +} diff --git a/vendor/oxideav-h265/src/palette.rs b/vendor/oxideav-h265/src/palette.rs new file mode 100644 index 0000000..d9aba13 --- /dev/null +++ b/vendor/oxideav-h265/src/palette.rs @@ -0,0 +1,981 @@ +//! §7.3.8.13 `palette_coding( )` parse, the §8.4.4.2.7 palette-mode +//! decoding process, and the palette predictor state machinery +//! (§9.3.2.3 initialization, eq. 8-79 update) of the HEVC Screen +//! Content Coding extensions. +//! +//! A palette coding unit replaces prediction + transform coding +//! entirely: the CU signals a small colour table (composed of entries +//! REUSED from a rolling predictor palette plus explicitly signalled +//! new entries, eq. 7-82), an index map covering the block in the +//! §6.5.6 traverse scan (run-length coded, with per-run "copy the +//! index from the row above" escapes), and optional escape samples +//! (quantized when the CU is not transquant-bypassed) for positions +//! whose index equals `MaxPaletteIndex`. +//! +//! The predictor palette is CABAC-adjacent parse state: it initializes +//! from the PPS / SPS palette predictor initializers at every point +//! §9.3.2.1 re-initializes context variables (slice start, tile start, +//! WPP fallback), synchronizes across WPP rows and dependent slice +//! segments alongside the context tables (§9.3.2.4 / §9.3.2.5), and +//! every palette CU rewrites it per eq. 8-79. It therefore lives +//! inside [`SliceContexts`] so the existing storage / synchronization +//! clones carry it. + +use crate::binarization::{ + decode_cu_chroma_qp_offset, decode_cu_qp_delta, decode_eg_k, palette_run_prefix_ctx_inc, + palette_run_prefix_tr_cmax, read_truncated_rice_prefix, CuChromaQpOffset, CuQpDelta, +}; +use crate::cabac::{CabacEngine, CabacError}; +use crate::ctx_init::SliceContexts; +use crate::scan::traverse; + +/// The rolling predictor palette (§9.3.2.3 / eq. 8-79): +/// `PredictorPaletteSize` and `PredictorPaletteEntries[comp][i]`. +/// +/// Component 0 is luma; components 1 / 2 exist when `ChromaArrayType +/// != 0` (the parse always keeps three vectors; chroma vectors stay +/// empty-aligned for monochrome). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct PalettePredictor { + /// `PredictorPaletteEntries[comp][0..PredictorPaletteSize]`. + pub entries: [Vec; 3], +} + +impl PalettePredictor { + /// `PredictorPaletteSize`. + #[must_use] + pub fn size(&self) -> usize { + self.entries[0].len() + } + + /// §9.3.2.3 — initialize from explicit initializer rows + /// (`initializers[comp][i]`; the PPS body if present, else the SPS + /// body, else empty). `num_comps` is `ChromaArrayType == 0 ? 1 : 3`. + #[must_use] + pub fn from_initializers(initializers: &[Vec], num_comps: usize) -> Self { + let mut p = Self::default(); + let size = initializers.first().map_or(0, Vec::len); + for c in 0..num_comps.min(3) { + let row = initializers.get(c).map_or(&[][..], Vec::as_slice); + p.entries[c] = (0..size) + .map(|i| row.get(i).copied().unwrap_or(0).min(u32::from(u16::MAX)) as u16) + .collect(); + } + p + } +} + +/// Parameters the §7.3.8.13 parse needs from the active parameter +/// sets and CU context. +#[derive(Debug, Clone, Copy)] +pub struct PaletteParams { + /// `palette_max_size` (§7.4.3.2.3). + pub palette_max_size: u32, + /// `PaletteMaxPredictorSize` (eq. 7-35). + pub palette_max_predictor_size: u32, + /// `ChromaArrayType`. + pub chroma_array_type: u8, + /// `BitDepthY`. + pub bit_depth_luma: u32, + /// `BitDepthC`. + pub bit_depth_chroma: u32, + /// `cu_transquant_bypass_flag` of the CU. + pub cu_transquant_bypass_flag: bool, + /// PPS `cu_qp_delta_enabled_flag`. + pub cu_qp_delta_enabled_flag: bool, + /// Per-slice `cu_chroma_qp_offset_enabled_flag`. + pub cu_chroma_qp_offset_enabled_flag: bool, + /// `chroma_qp_offset_list_len_minus1`. + pub chroma_qp_offset_list_len_minus1: u32, +} + +/// Parse errors of `palette_coding( )`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PaletteError { + /// The arithmetic engine failed / bitstream exhausted. + Cabac(CabacError), + /// A syntax element violated a §7.4.9.6 conformance bound. + Malformed(&'static str), +} + +impl core::fmt::Display for PaletteError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Cabac(e) => write!(f, "palette_coding: {e}"), + Self::Malformed(m) => write!(f, "palette_coding: {m}"), + } + } +} + +impl std::error::Error for PaletteError {} + +impl From for PaletteError { + fn from(e: CabacError) -> Self { + Self::Cabac(e) + } +} + +/// One parsed palette coding unit: everything the §8.4.4.2.7 +/// reconstruction needs. Index / escape arrays are CU-local, in luma +/// resolution and CODED (pre-transpose) coordinates — eq. 8-69/8-70 +/// apply the transpose at reconstruction. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PaletteCu { + /// `nCbS`. + pub n_cbs: usize, + /// `CurrentPaletteEntries[comp][0..CurrentPaletteSize]` (eq. 7-82). + pub palette: [Vec; 3], + /// `palette_escape_val_present_flag`. + pub escape_present: bool, + /// `palette_transpose_flag`. + pub transpose: bool, + /// `PaletteIndexMap` over the CU, row-major in coded coordinates + /// (`index_map[y * n_cbs + x]`), values `0..=MaxPaletteIndex`. + pub index_map: Vec, + /// `PaletteEscapeVal[comp]`, row-major in coded luma coordinates; + /// only positions whose index equals `MaxPaletteIndex` (and pass + /// the §7.3.8.13 chroma-phase gate) carry meaningful values. + pub escape_vals: [Vec; 3], + /// The `delta_qp( )` decoded inside `palette_coding( )` when + /// escapes are present. + pub cu_qp_delta: Option, + /// The `chroma_qp_offset( )` decoded inside `palette_coding( )`. + pub cu_chroma_qp_offset: Option, +} + +impl PaletteCu { + /// `MaxPaletteIndex` (§7.4.9.6). + #[must_use] + pub fn max_palette_index(&self) -> u32 { + self.palette[0].len() as u32 + u32::from(self.escape_present) - 1 + } +} + +/// §9.3.3.6 — Truncated Binary decode (all bins bypass). +fn decode_tb(engine: &mut CabacEngine<'_>, c_max: u32) -> Result { + if c_max == 0 { + return Ok(0); + } + let n = c_max + 1; + let k = 31 - n.leading_zeros(); // Floor(Log2(n)), n >= 2 + let u = (1u32 << (k + 1)) - n; + let mut val = 0u32; + for _ in 0..k { + val = (val << 1) | u32::from(engine.decode_bypass()?); + } + if val < u { + Ok(val) + } else { + let val = (val << 1) | u32::from(engine.decode_bypass()?); + Ok(val - u) + } +} + +/// §9.3.3.14 — `num_palette_indices_minus1` (bypass TR prefix with +/// `cRiceParam = 3 + ((MaxPaletteIndex + 1) >> 3)`, EGk(k+1) escape). +fn decode_num_palette_indices_minus1( + engine: &mut CabacEngine<'_>, + max_palette_index: u32, +) -> Result { + let k = 3 + ((max_palette_index + 1) >> 3); + let c_max = 4u32 << k; + // TR(cMax, cRiceParam = k): unary quotient (up to 4 ones), then a + // k-bit rice remainder when the quotient did not escape. + let mut q = 0u32; + while q < 4 { + if engine.decode_bypass()? == 0 { + break; + } + q += 1; + } + if q < 4 { + let mut rem = 0u32; + for _ in 0..k { + rem = (rem << 1) | u32::from(engine.decode_bypass()?); + } + Ok((q << k) + rem) + } else { + // Prefix all-ones (prefixVal == cMax): EGk suffix with order + // k + 1 (eq. 9-33). + Ok(c_max + decode_eg_k(engine, k + 1)?) + } +} + +/// §9.3.3.12 — `palette_escape_val`: FL(bitDepth) under transquant +/// bypass, else EG3. +fn decode_palette_escape_val( + engine: &mut CabacEngine<'_>, + bypass_cu: bool, + bit_depth: u32, +) -> Result { + if bypass_cu { + let mut v = 0u32; + for _ in 0..bit_depth { + v = (v << 1) | u32::from(engine.decode_bypass()?); + } + Ok(v) + } else { + decode_eg_k(engine, 3) + } +} + +/// Decode one §7.3.8.13 `palette_coding( x0, y0, nCbS )` body and +/// apply the eq. 8-79 predictor palette update to +/// `ctx.palette_predictor`. +/// +/// `is_cu_qp_delta_coded` / `is_cu_chroma_qp_offset_coded` mirror the +/// §7.3.8.14 / §7.3.8.15 quantization-group gates (the caller's +/// [`crate::transform_unit::QuantGroupState`]). +/// +/// # Errors +/// [`PaletteError`] on CABAC exhaustion or a §7.4.9.6 bound violation. +#[allow(clippy::too_many_lines)] +pub fn decode_palette_coding( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &PaletteParams, + qg: &mut crate::transform_unit::QuantGroupState, + n_cbs: usize, +) -> Result { + let num_comps = if params.chroma_array_type == 0 { 1 } else { 3 }; + let max_size = params.palette_max_size as usize; + let predictor_size = ctx.palette_predictor.size(); + + // ---- predictor entry reuse (palette_predictor_run, EG0) ---- + let mut reuse = vec![false; predictor_size]; + let mut num_predicted = 0usize; + let mut finished = false; + let mut idx = 0usize; + while idx < predictor_size && !finished && num_predicted < max_size { + let run = decode_eg_k(engine, 0)?; + if run == 1 { + finished = true; + } else { + if run > 1 { + idx += (run - 1) as usize; + } + if idx >= predictor_size { + return Err(PaletteError::Malformed( + "palette_predictor_run past PredictorPaletteSize", + )); + } + reuse[idx] = true; + num_predicted += 1; + } + idx += 1; + } + + // ---- num_signalled_palette_entries (EG0) + new entries ---- + let num_signalled = if num_predicted < max_size { + decode_eg_k(engine, 0)? as usize + } else { + 0 + }; + if num_predicted + num_signalled > max_size { + return Err(PaletteError::Malformed( + "CurrentPaletteSize past palette_max_size", + )); + } + let mut new_entries: [Vec; 3] = Default::default(); + for (c, out) in new_entries.iter_mut().enumerate().take(num_comps) { + let bd = if c == 0 { + params.bit_depth_luma + } else { + params.bit_depth_chroma + }; + for _ in 0..num_signalled { + let mut v = 0u32; + for _ in 0..bd { + v = (v << 1) | u32::from(engine.decode_bypass()?); + } + out.push(v as u16); + } + } + + // ---- CurrentPaletteEntries (eq. 7-82) ---- + let mut palette: [Vec; 3] = Default::default(); + for c in 0..num_comps { + for (i, &r) in reuse.iter().enumerate() { + if r { + palette[c].push(ctx.palette_predictor.entries[c][i]); + } + } + palette[c].extend_from_slice(&new_entries[c]); + } + let current_palette_size = palette[0].len(); + + // ---- palette_escape_val_present_flag ---- + let escape_present = if current_palette_size != 0 { + engine.decode_bypass()? != 0 + } else { + true // inferred 1 (§7.4.9.6) + }; + let max_palette_index = current_palette_size as i64 - 1 + i64::from(escape_present); + if max_palette_index < 0 { + return Err(PaletteError::Malformed( + "empty palette without escape samples", + )); + } + let max_palette_index = max_palette_index as u32; + if max_palette_index > u32::from(u8::MAX) { + return Err(PaletteError::Malformed("MaxPaletteIndex past u8 range")); + } + + // ---- explicit index list + final-run / transpose flags ---- + let mut palette_index_idc: Vec = Vec::new(); + let mut copy_above_final_run = false; + let mut transpose = false; + let mut num_palette_indices = 1usize; // num_palette_indices_minus1 + 1 (inferred 0) + if max_palette_index > 0 { + let npi_m1 = decode_num_palette_indices_minus1(engine, max_palette_index)?; + if npi_m1 as usize >= n_cbs * n_cbs { + return Err(PaletteError::Malformed( + "num_palette_indices_minus1 past the block area", + )); + } + num_palette_indices = npi_m1 as usize + 1; + let mut adjust = 0u32; + for _ in 0..num_palette_indices { + if max_palette_index - adjust > 0 { + // §9.3.3.13: cMax = MaxPaletteIndex on the first + // invocation, MaxPaletteIndex − 1 afterwards. + let c_max = max_palette_index - adjust; + palette_index_idc.push(decode_tb(engine, c_max)?); + } else { + palette_index_idc.push(0); + } + adjust = 1; + } + copy_above_final_run = engine.decode_decision(&mut ctx.palette_copy_above_flag[0])? != 0; + transpose = engine.decode_decision(&mut ctx.palette_transpose_flag[0])? != 0; + } + + // ---- delta_qp( ) / chroma_qp_offset( ) (escapes only) ---- + let mut cu_qp_delta = None; + let mut cu_chroma_qp_offset = None; + if escape_present { + if params.cu_qp_delta_enabled_flag && !qg.is_cu_qp_delta_coded { + qg.is_cu_qp_delta_coded = true; + let (bin0, rest) = ctx.cu_qp_delta_abs.split_at_mut(1); + let delta = decode_cu_qp_delta(engine, &mut bin0[0], &mut rest[0])?; + qg.cu_qp_delta_val = delta.value; + cu_qp_delta = Some(delta); + } + if !params.cu_transquant_bypass_flag + && params.cu_chroma_qp_offset_enabled_flag + && !qg.is_cu_chroma_qp_offset_coded + { + qg.is_cu_chroma_qp_offset_coded = true; + let offset = decode_cu_chroma_qp_offset( + engine, + &mut ctx.cu_chroma_qp_offset_flag[0], + &mut ctx.cu_chroma_qp_offset_idx[0], + params.chroma_qp_offset_list_len_minus1, + )?; + cu_chroma_qp_offset = Some(offset); + } + } + + // ---- index-map run loop (§7.3.8.13, transcribed) ---- + let scan = traverse(n_cbs); + let area = n_cbs * n_cbs; + let mut index_map = vec![0u8; area]; + let mut copy_above = vec![false; area]; // CopyAboveIndicesFlag, coded coords + let mut remaining = num_palette_indices; + let mut scan_pos = 0usize; + let mut curr_palette_index = 0u32; + // The RAW `palette_idx_idc` (`PaletteIndexIdc[ currNumIndices ]`, + // §7.4.9.6 inferred 0 when absent) BEFORE the eq. 7-84 + // adjustment: §9.3.4.2.8 derives the `palette_run_prefix` ctxInc + // from the syntax element value, not from `CurrPaletteIndex`. + let mut raw_palette_idx_idc = 0u32; + while scan_pos < area { + let pos = &scan[scan_pos]; + let (x_c, y_c) = (pos.x as usize, pos.y as usize); + let prev_copy_above = scan_pos > 0 && { + let p = &scan[scan_pos - 1]; + copy_above[p.y as usize * n_cbs + p.x as usize] + }; + let mut run_minus1 = area - scan_pos - 1; + let mut copy_flag = false; + if max_palette_index > 0 && scan_pos >= n_cbs && !prev_copy_above { + if remaining > 0 && scan_pos < area - 1 { + let ctx_bin = engine.decode_decision(&mut ctx.palette_copy_above_flag[0])? != 0; + copy_flag = ctx_bin; + } else { + copy_flag = !(scan_pos == area - 1 && remaining > 0); + } + } + if !copy_flag { + // CurrPaletteIndex = PaletteIndexIdc[currNumIndices], then + // the eq. 7-84 adjustment against adjustedRefPaletteIndex + // (eq. 7-83). + let curr_num_indices = num_palette_indices - remaining; + curr_palette_index = palette_index_idc + .get(curr_num_indices) + .copied() + .unwrap_or(0); + raw_palette_idx_idc = curr_palette_index; + let adjusted_ref = if scan_pos > 0 { + let p = &scan[scan_pos - 1]; + if !copy_above[p.y as usize * n_cbs + p.x as usize] { + u32::from(index_map[p.y as usize * n_cbs + p.x as usize]) + } else { + u32::from(index_map[(y_c - 1) * n_cbs + x_c]) + } + } else { + max_palette_index + 1 + }; + if curr_palette_index >= adjusted_ref { + curr_palette_index += 1; + } + if curr_palette_index > max_palette_index { + return Err(PaletteError::Malformed( + "palette index past MaxPaletteIndex", + )); + } + } + if max_palette_index > 0 { + if !copy_flag { + if remaining == 0 { + return Err(PaletteError::Malformed( + "palette runs exhaust the signalled index count", + )); + } + remaining -= 1; + } + if remaining > 0 || copy_flag != copy_above_final_run { + let max_run_minus1 = (area as i64) + - (scan_pos as i64) + - 1 + - (remaining as i64) + - i64::from(copy_above_final_run); + if max_run_minus1 < 0 { + return Err(PaletteError::Malformed("PaletteMaxRunMinus1 negative")); + } + run_minus1 = 0; + if max_run_minus1 > 0 { + // palette_run_prefix: TR with per-bin §9.3.4.2.8 + // ctxInc for bins 0..=4, bypass beyond. + let idc_for_ctx = if copy_flag { 0 } else { raw_palette_idx_idc }; + let c_max = palette_run_prefix_tr_cmax(max_run_minus1 as u32); + let (prefix, _escape) = + read_truncated_rice_prefix( + c_max, + |bin_idx| match palette_run_prefix_ctx_inc( + bin_idx, + copy_flag, + idc_for_ctx, + ) { + Some(inc) => engine + .decode_decision(&mut ctx.palette_run_prefix[inc as usize]), + None => engine.decode_bypass(), + }, + )?; + if prefix < 2 { + run_minus1 = prefix as usize; // eq. 7-85 + } else { + let prefix_offset = 1u32 << (prefix - 1); + let suffix = if max_run_minus1 as u32 != prefix_offset { + // palette_run_suffix: TB with the Table + // 9-43 cMax. + let c_max_tb = if (prefix_offset << 1) > max_run_minus1 as u32 { + max_run_minus1 as u32 - prefix_offset + } else { + prefix_offset - 1 + }; + decode_tb(engine, c_max_tb)? + } else { + 0 + }; + run_minus1 = (prefix_offset + suffix) as usize; // eq. 7-86 + } + if run_minus1 as i64 > max_run_minus1 { + return Err(PaletteError::Malformed( + "PaletteRunMinus1 past PaletteMaxRunMinus1", + )); + } + } + } + } + // Write the run. + let mut run_pos = 0usize; + while run_pos <= run_minus1 { + let p = &scan[scan_pos]; + let (x_r, y_r) = (p.x as usize, p.y as usize); + if !copy_flag { + copy_above[y_r * n_cbs + x_r] = false; + index_map[y_r * n_cbs + x_r] = curr_palette_index as u8; + } else { + if y_r == 0 { + return Err(PaletteError::Malformed("copy-above run in the top row")); + } + copy_above[y_r * n_cbs + x_r] = true; + index_map[y_r * n_cbs + x_r] = index_map[(y_r - 1) * n_cbs + x_r]; + } + run_pos += 1; + scan_pos += 1; + } + } + if max_palette_index > 0 && remaining != 0 { + return Err(PaletteError::Malformed( + "palette runs left signalled indices unconsumed", + )); + } + + // ---- escape values ---- + let mut escape_vals: [Vec; 3] = Default::default(); + for v in escape_vals.iter_mut().take(num_comps) { + *v = vec![0u16; area]; + } + if escape_present { + #[allow(clippy::needless_range_loop)] + for c in 0..num_comps { + let bd = if c == 0 { + params.bit_depth_luma + } else { + params.bit_depth_chroma + }; + for pos in &scan { + let (x_c, y_c) = (pos.x as usize, pos.y as usize); + if u32::from(index_map[y_c * n_cbs + x_c]) != max_palette_index { + continue; + } + // §7.3.8.13 per-component sample-presence gate. + let present = c == 0 + || (x_c % 2 == 0 && y_c % 2 == 0 && params.chroma_array_type == 1) + || (x_c % 2 == 0 && !transpose && params.chroma_array_type == 2) + || (y_c % 2 == 0 && transpose && params.chroma_array_type == 2) + || params.chroma_array_type == 3; + if present { + let v = + decode_palette_escape_val(engine, params.cu_transquant_bypass_flag, bd)?; + // Conformance bound: 0..(1 << (bitDepth + 1)) − 1; + // clamp into u16 defensively. + escape_vals[c][y_c * n_cbs + x_c] = + v.min((1u32 << (bd + 1).min(16)) - 1) as u16; + } + } + } + } + + let cu = PaletteCu { + n_cbs, + palette, + escape_present, + transpose, + index_map, + escape_vals, + cu_qp_delta, + cu_chroma_qp_offset, + }; + + // ---- predictor palette update (eq. 8-79) ---- + let max_pred = params.palette_max_predictor_size as usize; + let mut new_pred: [Vec; 3] = Default::default(); + for (c, np) in new_pred.iter_mut().enumerate().take(num_comps) { + np.clone_from(&cu.palette[c]); + } + let mut new_size = current_palette_size; + for (i, &r) in reuse.iter().enumerate() { + if new_size >= max_pred { + break; + } + if !r { + for (c, np) in new_pred.iter_mut().enumerate().take(num_comps) { + np.push(ctx.palette_predictor.entries[c][i]); + } + new_size += 1; + } + } + ctx.palette_predictor = PalettePredictor { entries: new_pred }; + + Ok(cu) +} + +/// §8.4.4.2.7 — reconstruct one colour component of a palette CU into +/// the caller's sample writer. +/// +/// * `c_idx` — colour component (0 luma, 1 Cb, 2 Cr). +/// * `(sub_w, sub_h)` — `(nSubWidth, nSubHeight)` for the component +/// (1/1 for luma; `SubWidthC`/`SubHeightC` for chroma). +/// * `qp` — the §8.6.1-derived `Qp′` for the component (the escape +/// path clamps at 0 per eq. 8-73..8-75). +/// * `bit_depth` — the component's bit depth. +/// * `set` — called as `set(x, y, value)` in COMPONENT coordinates +/// relative to the CU's component-plane origin. +#[allow(clippy::too_many_arguments)] +pub fn reconstruct_palette_component( + cu: &PaletteCu, + c_idx: usize, + sub_w: usize, + sub_h: usize, + qp: i32, + bit_depth: u32, + cu_transquant_bypass: bool, + mut set: F, +) { + let n = cu.n_cbs; + let (n_cb_sx, n_cb_sy) = (n / sub_w, n / sub_h); + let max_index = cu.max_palette_index(); + let level_scale = [40i64, 45, 51, 57, 64, 72]; + let qp = qp.max(0); + for y in 0..n_cb_sy { + for x in 0..n_cb_sx { + // eq. 8-69 / 8-70 — transpose maps the CODED coordinates + // onto the raster block. + let (x_l, y_l) = if cu.transpose { + (y * sub_h, x * sub_w) + } else { + (x * sub_w, y * sub_h) + }; + let idx = u32::from(cu.index_map[y_l * n + x_l]); + let is_escape = cu.escape_present && idx == max_index; + let v = if !is_escape { + // eq. 8-71. + i32::from(cu.palette[c_idx][idx as usize]) + } else if cu_transquant_bypass { + // eq. 8-72. + i32::from(cu.escape_vals[c_idx][y_l * n + x_l]) + } else { + // eq. 8-77 / 8-78 — escape dequantization. + let val = i64::from(cu.escape_vals[c_idx][y_l * n + x_l]); + let tmp = + ((val * level_scale[(qp % 6) as usize]) << (qp / 6)).wrapping_add(32) >> 6; + tmp.clamp(0, (1i64 << bit_depth) - 1) as i32 + }; + set(x, y, v); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cabac::init_type; + use crate::encoder::bitwriter::BitWriter; + use crate::encoder::cabac::CabacEncoder; + use crate::transform_unit::QuantGroupState; + + fn params(bypass: bool) -> PaletteParams { + PaletteParams { + palette_max_size: 63, + palette_max_predictor_size: 128, + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + cu_transquant_bypass_flag: bypass, + cu_qp_delta_enabled_flag: false, + cu_chroma_qp_offset_enabled_flag: false, + chroma_qp_offset_list_len_minus1: 0, + } + } + + /// Bypass-encode an EG0 value (the §9.3.3.3 dual of + /// `decode_eg_k(0)`). + fn encode_eg0(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32) { + let mut prefix_ones = 0u32; + while ((1u64 << (prefix_ones + 1)) - 1) <= u64::from(v) { + prefix_ones += 1; + } + for _ in 0..prefix_ones { + cabac.encode_bypass(w, 1); + } + cabac.encode_bypass(w, 0); + let base = (1u64 << prefix_ones) - 1; + let suffix = u64::from(v) - base; + for i in (0..prefix_ones).rev() { + cabac.encode_bypass(w, ((suffix >> i) & 1) as u8); + } + } + + /// TB-encode (§9.3.3.6 dual of `decode_tb`). + fn encode_tb(cabac: &mut CabacEncoder, w: &mut BitWriter, v: u32, c_max: u32) { + if c_max == 0 { + return; + } + let n = c_max + 1; + let k = 31 - n.leading_zeros(); + let u = (1u32 << (k + 1)) - n; + if v < u { + for i in (0..k).rev() { + cabac.encode_bypass(w, ((v >> i) & 1) as u8); + } + } else { + let val = v + u; + for i in (0..=k).rev() { + cabac.encode_bypass(w, ((val >> i) & 1) as u8); + } + } + } + + /// Round-trip a hand-built 8x8 palette CU: three signalled + /// entries, no escapes, an explicit-index run, a copy-above run + /// and the final run. + #[test] + fn palette_coding_roundtrips_hand_built_block() { + let n = 8usize; + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + let mut ectx = SliceContexts::init(init_type(2, false), 26); + + // Empty predictor ⇒ no palette_predictor_run loop bins. + // num_signalled_palette_entries = 3. + encode_eg0(&mut cabac, &mut w, 3); + // new_palette_entries: comp0 {10, 20, 30}, comp1 {60, 70, 80}, + // comp2 {110, 120, 130} — FL(8) each. + for base in [10u32, 60, 110] { + for i in 0..3u32 { + cabac.encode_bypass_bits(&mut w, base + 10 * i, 8); + } + } + // palette_escape_val_present_flag = 0. + cabac.encode_bypass(&mut w, 0); + // MaxPaletteIndex = 2. Plan: rows 0..3 index 0 (run to end of + // 32 samples? no — traverse scan): we emit indices [0, 1] and + // rely on: idx run of 31, copy-above run of 16, final run + // (explicit, index 1) to the end. + // num_palette_indices_minus1 = 1 (two explicit indices). + { + // cRiceParam k = 3 + ((2+1)>>3) = 3; value 1 < cMax: + // quotient 0 ⇒ one 0 bin, then 3 rice bits '001'. + cabac.encode_bypass(&mut w, 0); + cabac.encode_bypass_bits(&mut w, 1, 3); + } + // palette_idx_idc[0] = 0 (TB cMax = 2: n=3, k=1, u=1; 0 -> '0'). + encode_tb(&mut cabac, &mut w, 0, 2); + // palette_idx_idc[1] = 0 (TB cMax = 1: n=2,k=0,u=1 -> 0 bins + // for value 0? k=0: read 0 bits, val=0 < u=1 -> 0). No bins. + encode_tb(&mut cabac, &mut w, 0, 1); + // copy_above_indices_for_final_run_flag = 0 (final run explicit). + cabac.encode_decision(&mut w, &mut ectx.palette_copy_above_flag[0], 0); + // palette_transpose_flag = 0. + cabac.encode_decision(&mut w, &mut ectx.palette_transpose_flag[0], 0); + // (no escapes ⇒ no delta_qp) + // Scan loop plan over 64 samples: + // pos 0: explicit idx (idc 0 ⇒ index 0), remaining 2-1=1, + // run: PaletteMaxRunMinus1 = 64-0-1-1-0 = 62, + // prefix cMax = floor(log2(62))+1 = 6. + // PaletteRunMinus1 = 31: prefix ≥ 2: 31 = 16+15 ⇒ + // prefix 5 ('11111' then 0 if < cMax... prefix=5 < + // cMax=6 ⇒ five 1s + terminating 0), suffix TB: + // PrefixOffset=16, (32 > 62? no) ⇒ cMax_tb = 15, + // suffix = 15. + // pos 32: copy_above_palette_indices_flag = 1, run: + // remaining 1 > 0 ⇒ PaletteMaxRunMinus1 = + // 64-32-1-1-0 = 30, PaletteRunMinus1 = 15: prefix 4 + // + suffix TB (PrefixOffset 8, 16>30? no ⇒ cMax_tb + // = 7, suffix 7). + // pos 48: prev is copy-above ⇒ no copy flag read; explicit + // index (idc 0 adjusted vs left neighbour...) run to + // end (remaining becomes 0, copy_flag(0) == + // final_run_flag(0) ⇒ RunToEnd). + { + // pos 0 run: prefix 5 bins: ctxInc from + // palette_run_prefix_ctx_inc(bin, false, idx=0): + // bin0 -> eq 9-63(0) = 0; bins 1..4 -> 3,3,4,4; bin 5+ + // bypass... prefix value 5 means bins 0..4 = 1 and bin 5 + // = 0 terminator (5 < cMax 6). + for bin_idx in 0..5u32 { + let inc = palette_run_prefix_ctx_inc(bin_idx, false, 0).unwrap(); + cabac.encode_decision(&mut w, &mut ectx.palette_run_prefix[inc as usize], 1); + } + cabac.encode_bypass(&mut w, 0); // bin 5: bypass terminator + encode_tb(&mut cabac, &mut w, 15, 15); // suffix + } + { + // pos 32: copy_above_palette_indices_flag = 1. + cabac.encode_decision(&mut w, &mut ectx.palette_copy_above_flag[0], 1); + // run prefix 4 (bins 0..3 ones, bin 4 zero), copy row of + // Table 9-51: 5,6,6,7 then terminator ctx 7. + for bin_idx in 0..4u32 { + let inc = palette_run_prefix_ctx_inc(bin_idx, true, 0).unwrap(); + cabac.encode_decision(&mut w, &mut ectx.palette_run_prefix[inc as usize], 1); + } + let inc = palette_run_prefix_ctx_inc(4, true, 0).unwrap(); + cabac.encode_decision(&mut w, &mut ectx.palette_run_prefix[inc as usize], 0); + encode_tb(&mut cabac, &mut w, 7, 7); // suffix + } + // pos 48: explicit index, remaining -> 0, copy(false) == + // final(false) ⇒ RunToEnd, no bins. + cabac.encode_terminate(&mut w, 1); + let bytes = w.finish(); + + // ---- decode ---- + let mut dctx = SliceContexts::init(init_type(2, false), 26); + let mut engine = + CabacEngine::new(crate::bitreader::BitReader::new(&bytes)).expect("engine"); + let mut qg = QuantGroupState::default(); + let cu = decode_palette_coding(&mut engine, &mut dctx, ¶ms(true), &mut qg, n) + .expect("palette parse"); + assert_eq!(cu.palette[0], vec![10, 20, 30]); + assert_eq!(cu.palette[1], vec![60, 70, 80]); + assert_eq!(cu.palette[2], vec![110, 120, 130]); + assert!(!cu.escape_present); + assert!(!cu.transpose); + // Positions 0..=31 (traverse order = rows 0..3 serpentine): + // index 0. Positions 32..47 copy row above (rows 4..5 copy + // row 3 = index 0)... every sample ends up index 0 except the + // final run: idc[1] = 0 adjusts (eq. 7-84) against the + // neighbour index 0 ⇒ index 1 for positions 48..63 (rows + // 6..7). + for pos in 0..48usize { + let p = traverse(n)[pos]; + assert_eq!( + cu.index_map[p.y as usize * n + p.x as usize], + 0, + "pos {pos}" + ); + } + for pos in 48..64usize { + let p = traverse(n)[pos]; + assert_eq!( + cu.index_map[p.y as usize * n + p.x as usize], + 1, + "pos {pos}" + ); + } + // Predictor update: current palette becomes the predictor. + assert_eq!(dctx.palette_predictor.entries[0], vec![10, 20, 30]); + assert_eq!(dctx.palette_predictor.size(), 3); + + // ---- reconstruction (4:2:0) ---- + let mut luma = vec![0i32; 64]; + reconstruct_palette_component(&cu, 0, 1, 1, 26, 8, true, |x, y, v| { + luma[y * 8 + x] = v; + }); + for y in 0..8 { + for x in 0..8 { + let expect = if y >= 6 { 20 } else { 10 }; + assert_eq!(luma[y * 8 + x], expect, "luma ({x},{y})"); + } + } + let mut cb = [0i32; 16]; + reconstruct_palette_component(&cu, 1, 2, 2, 26, 8, true, |x, y, v| { + cb[y * 4 + x] = v; + }); + for y in 0..4 { + for x in 0..4 { + let expect = if y >= 3 { 70 } else { 60 }; + assert_eq!(cb[y * 4 + x], expect, "cb ({x},{y})"); + } + } + } + + /// Predictor reuse: runs select predictor entries, the update + /// appends unused entries after the current palette (eq. 8-79). + #[test] + fn predictor_reuse_and_update() { + let n = 4usize; + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + // Seed a 4-entry predictor. + let seed = PalettePredictor { + entries: [vec![1, 2, 3, 4], vec![11, 12, 13, 14], vec![21, 22, 23, 24]], + }; + + // Reuse entries 0 and 2: runs 0 ("reuse current"), then 2 + // (skip one, reuse), then 1 (finish). + encode_eg0(&mut cabac, &mut w, 0); + encode_eg0(&mut cabac, &mut w, 2); + encode_eg0(&mut cabac, &mut w, 1); + // num_signalled = 0. + encode_eg0(&mut cabac, &mut w, 0); + // escape_present = 0 (CurrentPaletteSize = 2). + cabac.encode_bypass(&mut w, 0); + // MaxPaletteIndex = 1 > 0: num_palette_indices_minus1 = 0 + // (k = 3, quotient 0 + 3 rice zero bits). + cabac.encode_bypass(&mut w, 0); + cabac.encode_bypass_bits(&mut w, 0, 3); + // palette_idx_idc[0] = 0: TB cMax = 1 -> n=2, k=0, u=1, value + // 0 < u -> zero bins... wait k = floor(log2(2)) = 1, u = 2^2-2 + // = 2: value 0 < 2 -> FL(k=1) one bin '0'. + encode_tb(&mut cabac, &mut w, 0, 1); + let mut ectx = SliceContexts::init(init_type(2, false), 26); + // final-run flag = 0, transpose = 0. + cabac.encode_decision(&mut w, &mut ectx.palette_copy_above_flag[0], 0); + cabac.encode_decision(&mut w, &mut ectx.palette_transpose_flag[0], 0); + // Scan: pos 0 explicit idx 0, remaining -> 0, copy(0) == + // final(0) => run to end. No further bins. + cabac.encode_terminate(&mut w, 1); + let bytes = w.finish(); + + let mut dctx = SliceContexts::init(init_type(2, false), 26); + dctx.palette_predictor = seed; + let mut engine = + CabacEngine::new(crate::bitreader::BitReader::new(&bytes)).expect("engine"); + let mut qg = QuantGroupState::default(); + let cu = decode_palette_coding(&mut engine, &mut dctx, ¶ms(true), &mut qg, n) + .expect("palette parse"); + assert_eq!(cu.palette[0], vec![1, 3]); + assert_eq!(cu.palette[1], vec![11, 13]); + assert!(cu.index_map.iter().all(|&i| i == 0)); + // eq. 8-79: current palette first, then unused predictor + // entries 1 and 3. + assert_eq!(dctx.palette_predictor.entries[0], vec![1, 3, 2, 4]); + assert_eq!(dctx.palette_predictor.entries[2], vec![21, 23, 22, 24]); + } + + /// §9.3.3.6 TB is the FL/offset split around `u`. + #[test] + fn tb_binarization_shapes() { + for c_max in 1u32..20 { + for v in 0..=c_max { + let mut w = BitWriter::new(); + let mut cabac = CabacEncoder::new(); + encode_tb(&mut cabac, &mut w, v, c_max); + cabac.encode_terminate(&mut w, 1); + let bytes = w.finish(); + let mut engine = + CabacEngine::new(crate::bitreader::BitReader::new(&bytes)).expect("engine"); + assert_eq!( + decode_tb(&mut engine, c_max).expect("tb"), + v, + "cMax {c_max} value {v}" + ); + } + } + } + + /// Escape reconstruction: eq. 8-77 dequantization and the eq. 8-72 + /// bypass passthrough. + #[test] + fn escape_dequantization_matches_eq_8_77() { + let cu = PaletteCu { + n_cbs: 4, + palette: [vec![50], vec![60], vec![70]], + escape_present: true, + transpose: false, + index_map: { + let mut m = vec![0u8; 16]; + m[0] = 1; // escape at (0,0) + m + }, + escape_vals: [ + { + let mut v = vec![0u16; 16]; + v[0] = 7; + v + }, + vec![0u16; 16], + vec![0u16; 16], + ], + cu_qp_delta: None, + cu_chroma_qp_offset: None, + }; + // qP = 10: levelScale[4] = 64, shift 1: ((7*64) << 1 + 32) >> 6 + // = (896 + 32) >> 6 = 14. + let mut out = [0i32; 16]; + reconstruct_palette_component(&cu, 0, 1, 1, 10, 8, false, |x, y, v| { + out[y * 4 + x] = v; + }); + assert_eq!(out[0], 14); + assert_eq!(out[1], 50); + // Bypass: the escape value is the sample. + let mut out2 = [0i32; 16]; + reconstruct_palette_component(&cu, 0, 1, 1, 10, 8, true, |x, y, v| { + out2[y * 4 + x] = v; + }); + assert_eq!(out2[0], 7); + } +} diff --git a/vendor/oxideav-h265/src/picture.rs b/vendor/oxideav-h265/src/picture.rs new file mode 100644 index 0000000..184a0ae --- /dev/null +++ b/vendor/oxideav-h265/src/picture.rs @@ -0,0 +1,327 @@ +//! Decoded-picture sample storage — the §8 reconstruction target. +//! +//! A [`Picture`] holds the three reconstructed sample planes (luma `SL` +//! and the two chroma planes `SCb` / `SCr`) sized from the active SPS +//! geometry and `ChromaArrayType`. Reconstruction (§8.4 intra / §8.5 +//! inter sample prediction, §8.6 residual add, §8.7 in-loop filters) +//! writes into these planes; the DPB and any output cropping read out of +//! them. +//! +//! Samples are stored one `i32` per pixel so the prediction + residual +//! arithmetic of §8.4.4 / §8.6.2 (which works in the full `i32` range +//! before the final `Clip1Y` / `Clip1C` clip) can write the clipped +//! result without an intermediate type change. The stored values are +//! always already clipped to `[0, (1 << bitDepth) − 1]`. + +/// One reconstructed picture: the luma plane and (unless monochrome) the +/// two chroma planes, each row-major. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Picture { + /// `pic_width_in_luma_samples`. + width_luma: usize, + /// `pic_height_in_luma_samples`. + height_luma: usize, + /// Chroma plane width (`width_luma >> SubWidthC`), 0 if monochrome. + width_chroma: usize, + /// Chroma plane height (`height_luma >> SubHeightC`), 0 if monochrome. + height_chroma: usize, + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, + /// 3 = 4:4:4). + chroma_array_type: u8, + /// `BitDepthY`. + bit_depth_luma: u8, + /// `BitDepthC`. + bit_depth_chroma: u8, + /// `SL[ x ][ y ]`, row-major (`luma[y * width_luma + x]`). + luma: Vec, + /// `SCb[ x ][ y ]`, row-major; empty when monochrome. + cb: Vec, + /// `SCr[ x ][ y ]`, row-major; empty when monochrome. + cr: Vec, +} + +/// The three colour components addressable in a [`Picture`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Plane { + /// The luma plane `SL`. + Luma, + /// The first chroma plane `SCb`. + Cb, + /// The second chroma plane `SCr`. + Cr, +} + +/// `(SubWidthC, SubHeightC)` from Table 6-1 for a `ChromaArrayType`. +/// `ChromaArrayType == 0` (monochrome) has no chroma planes; this +/// returns `(2, 2)` for it purely so callers that never touch chroma do +/// not special-case it (the chroma planes are zero-sized in that case). +#[must_use] +pub fn sub_wh_c(chroma_array_type: u8) -> (usize, usize) { + match chroma_array_type { + // 4:2:0. + 1 => (2, 2), + // 4:2:2. + 2 => (2, 1), + // 4:4:4. + 3 => (1, 1), + // monochrome (no chroma) — never indexed. + _ => (2, 2), + } +} + +impl Picture { + /// Allocate a black (all-zero) picture of the given geometry. The + /// chroma planes are sized by `chroma_array_type` per Table 6-1; a + /// monochrome picture (`chroma_array_type == 0`) carries no chroma + /// samples. + #[must_use] + pub fn new( + width_luma: usize, + height_luma: usize, + chroma_array_type: u8, + bit_depth_luma: u8, + bit_depth_chroma: u8, + ) -> Self { + let (width_chroma, height_chroma) = if chroma_array_type == 0 { + (0, 0) + } else { + let (sw, sh) = sub_wh_c(chroma_array_type); + (width_luma / sw, height_luma / sh) + }; + let luma = vec![0i32; width_luma * height_luma]; + let cb = vec![0i32; width_chroma * height_chroma]; + let cr = vec![0i32; width_chroma * height_chroma]; + Self { + width_luma, + height_luma, + width_chroma, + height_chroma, + chroma_array_type, + bit_depth_luma, + bit_depth_chroma, + luma, + cb, + cr, + } + } + + /// `pic_width_in_luma_samples`. + #[inline] + #[must_use] + pub fn width_luma(&self) -> usize { + self.width_luma + } + + /// `pic_height_in_luma_samples`. + #[inline] + #[must_use] + pub fn height_luma(&self) -> usize { + self.height_luma + } + + /// `ChromaArrayType`. + #[inline] + #[must_use] + pub fn chroma_array_type(&self) -> u8 { + self.chroma_array_type + } + + /// `BitDepthY`. + #[inline] + #[must_use] + pub fn bit_depth_luma(&self) -> u8 { + self.bit_depth_luma + } + + /// `BitDepthC`. + #[inline] + #[must_use] + pub fn bit_depth_chroma(&self) -> u8 { + self.bit_depth_chroma + } + + /// Plane dimensions `(width, height)` in samples for `plane`. + #[must_use] + pub fn plane_dims(&self, plane: Plane) -> (usize, usize) { + match plane { + Plane::Luma => (self.width_luma, self.height_luma), + Plane::Cb | Plane::Cr => (self.width_chroma, self.height_chroma), + } + } + + /// `BitDepth` of `plane`. + #[must_use] + pub fn bit_depth(&self, plane: Plane) -> u8 { + match plane { + Plane::Luma => self.bit_depth_luma, + Plane::Cb | Plane::Cr => self.bit_depth_chroma, + } + } + + #[inline] + fn plane_slice(&self, plane: Plane) -> (&[i32], usize) { + match plane { + Plane::Luma => (&self.luma, self.width_luma), + Plane::Cb => (&self.cb, self.width_chroma), + Plane::Cr => (&self.cr, self.width_chroma), + } + } + + #[inline] + fn plane_slice_mut(&mut self, plane: Plane) -> (&mut [i32], usize) { + match plane { + Plane::Luma => (&mut self.luma, self.width_luma), + Plane::Cb => (&mut self.cb, self.width_chroma), + Plane::Cr => (&mut self.cr, self.width_chroma), + } + } + + /// Read one sample at `(x, y)` of `plane`. + /// + /// # Panics + /// Panics if `(x, y)` lies outside the plane. + #[must_use] + pub fn sample(&self, plane: Plane, x: usize, y: usize) -> i32 { + let (buf, stride) = self.plane_slice(plane); + buf[y * stride + x] + } + + /// Write one sample at `(x, y)` of `plane`. + /// + /// # Panics + /// Panics if `(x, y)` lies outside the plane. + pub fn set_sample(&mut self, plane: Plane, x: usize, y: usize, v: i32) { + let (buf, stride) = self.plane_slice_mut(plane); + buf[y * stride + x] = v; + } + + /// Borrow the raw row-major plane buffer (read-only). + #[must_use] + pub fn plane(&self, plane: Plane) -> &[i32] { + self.plane_slice(plane).0 + } + + /// Borrow the raw row-major plane buffer + its row stride (mutable). + /// + /// Used by the §8.7.2 deblocking driver to wrap a component plane in a + /// [`crate::deblock::SamplePlane`] for in-place edge filtering. + pub fn plane_mut(&mut self, plane: Plane) -> (&mut [i32], usize) { + self.plane_slice_mut(plane) + } + + /// Pack the three planes into a single planar 8-bit buffer in + /// `Y` then `Cb` then `Cr` order, each plane row-major. Only valid + /// for `BitDepth == 8` planes (the common `yuv420p` / `yuv444p` + /// fixture layout); samples are already clipped to `[0, 255]` by the + /// reconstruction step so the cast is exact. + /// + /// Returns `None` if any plane has a bit depth other than 8. + #[must_use] + pub fn to_planar_u8(&self) -> Option> { + if self.bit_depth_luma != 8 { + return None; + } + if self.chroma_array_type != 0 && self.bit_depth_chroma != 8 { + return None; + } + let mut out = Vec::with_capacity(self.luma.len() + self.cb.len() + self.cr.len()); + out.extend(self.luma.iter().map(|&v| v as u8)); + out.extend(self.cb.iter().map(|&v| v as u8)); + out.extend(self.cr.iter().map(|&v| v as u8)); + Some(out) + } + + /// Pack the three planes into a single planar little-endian 16-bit + /// buffer in `Y` then `Cb` then `Cr` order, each plane row-major — + /// the `yuv420p10le` / `yuv422p10le` / `yuv444p10le` fixture layout + /// for bit depths above 8. Samples are already clipped to + /// `[0, (1 << BitDepth) − 1]` by the reconstruction step so the + /// `u16` cast is exact. + #[must_use] + pub fn to_planar_le16(&self) -> Vec { + let n = self.luma.len() + self.cb.len() + self.cr.len(); + let mut out = Vec::with_capacity(n * 2); + for plane in [&self.luma, &self.cb, &self.cr] { + for &v in plane.iter() { + out.extend_from_slice(&(v as u16).to_le_bytes()); + } + } + out + } +} + +/// `Clip3( 0, (1 << bitDepth) − 1, x )` — the §8 `Clip1Y` / `Clip1C` +/// sample clip. +#[inline] +#[must_use] +pub fn clip1(x: i32, bit_depth: u8) -> i32 { + let max = (1i32 << bit_depth) - 1; + x.clamp(0, max) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn allocates_420_planes_by_table_6_1() { + let p = Picture::new(16, 16, 1, 8, 8); + assert_eq!(p.plane_dims(Plane::Luma), (16, 16)); + assert_eq!(p.plane_dims(Plane::Cb), (8, 8)); + assert_eq!(p.plane_dims(Plane::Cr), (8, 8)); + } + + #[test] + fn allocates_422_planes_by_table_6_1() { + let p = Picture::new(16, 16, 2, 8, 8); + // SubWidthC = 2, SubHeightC = 1. + assert_eq!(p.plane_dims(Plane::Cb), (8, 16)); + } + + #[test] + fn allocates_444_planes_by_table_6_1() { + let p = Picture::new(16, 16, 3, 8, 8); + assert_eq!(p.plane_dims(Plane::Cb), (16, 16)); + } + + #[test] + fn monochrome_has_no_chroma() { + let p = Picture::new(16, 16, 0, 8, 8); + assert_eq!(p.plane_dims(Plane::Cb), (0, 0)); + assert!(p.plane(Plane::Cb).is_empty()); + } + + #[test] + fn sample_roundtrips() { + let mut p = Picture::new(8, 8, 1, 8, 8); + p.set_sample(Plane::Luma, 3, 4, 200); + assert_eq!(p.sample(Plane::Luma, 3, 4), 200); + assert_eq!(p.sample(Plane::Luma, 0, 0), 0); + } + + #[test] + fn clip1_clamps_to_bit_depth_range() { + assert_eq!(clip1(-5, 8), 0); + assert_eq!(clip1(300, 8), 255); + assert_eq!(clip1(81, 8), 81); + assert_eq!(clip1(2000, 10), 1023); + } + + #[test] + fn planar_u8_packs_y_cb_cr() { + let mut p = Picture::new(2, 2, 1, 8, 8); + for y in 0..2 { + for x in 0..2 { + p.set_sample(Plane::Luma, x, y, 0x51); + } + } + p.set_sample(Plane::Cb, 0, 0, 0x5a); + p.set_sample(Plane::Cr, 0, 0, 0xf0); + let packed = p.to_planar_u8().unwrap(); + // 4 luma + 1 cb + 1 cr. + assert_eq!(packed.len(), 6); + assert_eq!(&packed[0..4], &[0x51, 0x51, 0x51, 0x51]); + assert_eq!(packed[4], 0x5a); + assert_eq!(packed[5], 0xf0); + } +} diff --git a/vendor/oxideav-h265/src/poc.rs b/vendor/oxideav-h265/src/poc.rs new file mode 100644 index 0000000..b95675e --- /dev/null +++ b/vendor/oxideav-h265/src/poc.rs @@ -0,0 +1,403 @@ +//! §8.3.1 picture-order-count derivation and the Table 7-1 NAL-unit-type +//! classification it (and the §8.3.2 DPB marking) needs. +//! +//! Every coded picture carries a `PicOrderCntVal` (§8.3.1), the +//! decoder-wide identity used to address reference pictures in the §8.3.2 +//! reference-picture-set marking, the §8.3.4 reference-picture-list +//! construction, and the §8.5.3.2.8 / §8.5.3.2.9 temporal motion-vector +//! scaling. The value is `PicOrderCntMsb + slice_pic_order_cnt_lsb` +//! (equation 8-2), where the MSB is rolled forward from the previous +//! `TemporalId == 0` non-RASL/RADL/SLNR picture (`prevTid0Pic`) by the +//! equation-8-1 wrap rule — except an IRAP picture with +//! `NoRaslOutputFlag == 1` resets the MSB to 0. +//! +//! The [`PocState`] threads `prevTid0Pic`'s `(slice_pic_order_cnt_lsb, +//! PicOrderCntMsb)` across the picture sequence so a multi-picture decode +//! (an I-frame followed by a P-frame, a B-pyramid, …) derives each POC +//! exactly. [`NalKind`] classifies a `nal_unit_type` into the Table 7-1 +//! categories the POC + DPB processes branch on. + +/// Table 7-1 `nal_unit_type` classification — the categories the §8.3.x +/// decoding processes branch on (IRAP / IDR / leading-picture / SLNR). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct NalKind(u8); + +impl NalKind { + /// `TRAIL_N` (0). + pub const TRAIL_N: u8 = 0; + /// `TRAIL_R` (1). + pub const TRAIL_R: u8 = 1; + /// `TSA_N` (2). + pub const TSA_N: u8 = 2; + /// `TSA_R` (3). + pub const TSA_R: u8 = 3; + /// `STSA_N` (4). + pub const STSA_N: u8 = 4; + /// `STSA_R` (5). + pub const STSA_R: u8 = 5; + /// `RADL_N` (6). + pub const RADL_N: u8 = 6; + /// `RADL_R` (7). + pub const RADL_R: u8 = 7; + /// `RASL_N` (8). + pub const RASL_N: u8 = 8; + /// `RASL_R` (9). + pub const RASL_R: u8 = 9; + /// `BLA_W_LP` (16). + pub const BLA_W_LP: u8 = 16; + /// `BLA_W_RADL` (17). + pub const BLA_W_RADL: u8 = 17; + /// `BLA_N_LP` (18). + pub const BLA_N_LP: u8 = 18; + /// `IDR_W_RADL` (19). + pub const IDR_W_RADL: u8 = 19; + /// `IDR_N_LP` (20). + pub const IDR_N_LP: u8 = 20; + /// `CRA_NUT` (21). + pub const CRA_NUT: u8 = 21; + /// `RSV_IRAP_VCL23` (23) — inclusive upper bound of the IRAP range. + pub const RSV_IRAP_VCL23: u8 = 23; + + /// Wrap a raw `nal_unit_type` (0..=63). + #[inline] + #[must_use] + pub fn new(nal_unit_type: u8) -> Self { + Self(nal_unit_type) + } + + /// The raw `nal_unit_type` value. + #[inline] + #[must_use] + pub fn value(self) -> u8 { + self.0 + } + + /// A VCL (coded-slice-segment) NAL unit: `nal_unit_type` in + /// `TRAIL_N..=RASL_R` (0..=9) or `BLA_W_LP..=RSV_IRAP_VCL23` + /// (16..=23) — i.e. `nal_unit_type <= 31` covers the reserved VCL + /// ranges too, but §3.29 limits coded-slice-segment NAL units to + /// these two spans. + #[inline] + #[must_use] + pub fn is_vcl(self) -> bool { + (self.0 <= Self::RASL_R) || (Self::BLA_W_LP..=31).contains(&self.0) + } + + /// IRAP picture (§3 — `BLA_W_LP..=RSV_IRAP_VCL23`, 16..=23). + #[inline] + #[must_use] + pub fn is_irap(self) -> bool { + (Self::BLA_W_LP..=Self::RSV_IRAP_VCL23).contains(&self.0) + } + + /// IDR picture (`IDR_W_RADL` or `IDR_N_LP`). + #[inline] + #[must_use] + pub fn is_idr(self) -> bool { + self.0 == Self::IDR_W_RADL || self.0 == Self::IDR_N_LP + } + + /// BLA picture (`BLA_W_LP`, `BLA_W_RADL`, `BLA_N_LP`). + #[inline] + #[must_use] + pub fn is_bla(self) -> bool { + (Self::BLA_W_LP..=Self::BLA_N_LP).contains(&self.0) + } + + /// CRA picture (`CRA_NUT`). + #[inline] + #[must_use] + pub fn is_cra(self) -> bool { + self.0 == Self::CRA_NUT + } + + /// RASL picture (`RASL_N` or `RASL_R`). + #[inline] + #[must_use] + pub fn is_rasl(self) -> bool { + self.0 == Self::RASL_N || self.0 == Self::RASL_R + } + + /// RADL picture (`RADL_N` or `RADL_R`). + #[inline] + #[must_use] + pub fn is_radl(self) -> bool { + self.0 == Self::RADL_N || self.0 == Self::RADL_R + } + + /// Sub-layer non-reference picture (SLNR): a VCL NAL unit with an + /// even `nal_unit_type` in the `0..=14` range (`TRAIL_N`, `TSA_N`, + /// `STSA_N`, `RADL_N`, `RASL_N`, `RSV_VCL_N10/12/14`). These are the + /// `*_N` coded-slice types per the Table 7-1 "sub-layer non-reference" + /// rows. IRAP / IDR / CRA / BLA types are never SLNR. + #[inline] + #[must_use] + pub fn is_slnr(self) -> bool { + self.0 <= Self::RADL_R && self.0 % 2 == 0 + || self.0 == 10 + || self.0 == 12 + || self.0 == 14 + || self.0 == Self::RASL_N + } +} + +/// §8.3.1 `(slice_pic_order_cnt_lsb, PicOrderCntMsb)` carried forward +/// from `prevTid0Pic` — the previous `TemporalId == 0` picture that is not +/// a RASL, RADL or SLNR picture. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PocState { + /// `prevPicOrderCntLsb` — `slice_pic_order_cnt_lsb` of `prevTid0Pic`. + prev_poc_lsb: u32, + /// `prevPicOrderCntMsb` — `PicOrderCntMsb` of `prevTid0Pic`. + prev_poc_msb: i32, + /// Whether a `prevTid0Pic` has been seen (false at stream start). + seen: bool, +} + +/// The §8.3.1 outputs for one picture. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PicOrderCnt { + /// `PicOrderCntMsb` (equation 8-1). + pub msb: i32, + /// `slice_pic_order_cnt_lsb`. + pub lsb: u32, + /// `PicOrderCntVal = PicOrderCntMsb + slice_pic_order_cnt_lsb` + /// (equation 8-2). + pub val: i32, +} + +impl PocState { + /// A fresh state at the start of a coded video sequence (no + /// `prevTid0Pic` yet). + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// §8.3.1 — derive the current picture's `PicOrderCntVal`. + /// + /// `nal_kind` is the current picture's [`NalKind`]; `no_rasl_output` + /// is `NoRaslOutputFlag` (1 for an IDR / BLA, and for a CRA at the + /// start of the bitstream or after an end-of-sequence — the caller + /// resolves it); `poc_lsb` is `slice_pic_order_cnt_lsb` (0 for an IDR, + /// which signals no `slice_pic_order_cnt_lsb`); `max_poc_lsb` is + /// `MaxPicOrderCntLsb` from the active SPS. + /// + /// Returns the derived [`PicOrderCnt`]. The caller must then call + /// [`PocState::update_prev_tid0`] **after** picture decode if the + /// picture qualifies as a `prevTid0Pic` (`TemporalId == 0` and not + /// RASL / RADL / SLNR) so the next picture's MSB rolls forward. + #[must_use] + pub fn derive( + &self, + nal_kind: NalKind, + no_rasl_output: bool, + poc_lsb: u32, + max_poc_lsb: u32, + ) -> PicOrderCnt { + let msb = if nal_kind.is_irap() && no_rasl_output { + // §8.3.1 — IRAP with NoRaslOutputFlag == 1 resets the MSB. + 0 + } else if !self.seen { + // No prevTid0Pic yet (and not an MSB-reset IRAP): prev values + // are 0 per the IDR NOTE-1 boundary condition. + poc_msb(poc_lsb, 0, 0, max_poc_lsb) + } else { + poc_msb(poc_lsb, self.prev_poc_lsb, self.prev_poc_msb, max_poc_lsb) + }; + let val = msb + poc_lsb as i32; + PicOrderCnt { + msb, + lsb: poc_lsb, + val, + } + } + + /// Update the carried `prevTid0Pic` state after decoding a picture + /// whose `TemporalId == 0` and that is not a RASL, RADL or SLNR + /// picture. `poc` is the picture's derived [`PicOrderCnt`]. + pub fn update_prev_tid0(&mut self, poc: PicOrderCnt) { + self.prev_poc_lsb = poc.lsb; + self.prev_poc_msb = poc.msb; + self.seen = true; + } + + /// Convenience: derive the POC and, when the picture qualifies as a + /// `prevTid0Pic` (`temporal_id == 0` and not RASL / RADL / SLNR), + /// roll the state forward. Returns the derived [`PicOrderCnt`]. + pub fn decode_picture_poc( + &mut self, + nal_kind: NalKind, + temporal_id: u8, + no_rasl_output: bool, + poc_lsb: u32, + max_poc_lsb: u32, + ) -> PicOrderCnt { + let poc = self.derive(nal_kind, no_rasl_output, poc_lsb, max_poc_lsb); + if temporal_id == 0 && !(nal_kind.is_rasl() || nal_kind.is_radl() || nal_kind.is_slnr()) { + self.update_prev_tid0(poc); + } + poc + } +} + +/// §8.3.1 equation 8-1 — `PicOrderCntMsb` from the current LSB and the +/// previous picture's LSB / MSB. +#[inline] +fn poc_msb(poc_lsb: u32, prev_poc_lsb: u32, prev_poc_msb: i32, max_poc_lsb: u32) -> i32 { + let half = (max_poc_lsb / 2) as i32; + let lsb = poc_lsb as i32; + let prev_lsb = prev_poc_lsb as i32; + let max = max_poc_lsb as i32; + if lsb < prev_lsb && (prev_lsb - lsb) >= half { + prev_poc_msb + max + } else if lsb > prev_lsb && (lsb - prev_lsb) > half { + prev_poc_msb - max + } else { + prev_poc_msb + } +} + +/// §8.3.1 equation 8-4 — `DiffPicOrderCnt( picA, picB )`. +#[inline] +#[must_use] +pub fn diff_pic_order_cnt(poc_a: i32, poc_b: i32) -> i32 { + poc_a - poc_b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn idr_is_classified() { + assert!(NalKind::new(NalKind::IDR_W_RADL).is_idr()); + assert!(NalKind::new(NalKind::IDR_N_LP).is_idr()); + assert!(NalKind::new(NalKind::IDR_W_RADL).is_irap()); + assert!(!NalKind::new(NalKind::TRAIL_R).is_irap()); + assert!(NalKind::new(NalKind::CRA_NUT).is_cra()); + assert!(NalKind::new(NalKind::CRA_NUT).is_irap()); + assert!(NalKind::new(NalKind::BLA_W_LP).is_bla()); + } + + #[test] + fn vcl_classification_matches_table_7_1() { + assert!(NalKind::new(0).is_vcl()); + assert!(NalKind::new(9).is_vcl()); + assert!(NalKind::new(20).is_vcl()); + assert!(NalKind::new(23).is_vcl()); + assert!(NalKind::new(31).is_vcl()); + // VPS/SPS/PPS are non-VCL. + assert!(!NalKind::new(32).is_vcl()); + assert!(!NalKind::new(33).is_vcl()); + } + + #[test] + fn slnr_picks_the_n_types() { + for &n in &[ + NalKind::TRAIL_N, + NalKind::TSA_N, + NalKind::STSA_N, + NalKind::RADL_N, + NalKind::RASL_N, + 10, + 12, + 14, + ] { + assert!(NalKind::new(n).is_slnr(), "type {n} is SLNR"); + } + for &r in &[ + NalKind::TRAIL_R, + NalKind::TSA_R, + NalKind::STSA_R, + NalKind::RADL_R, + NalKind::RASL_R, + ] { + assert!(!NalKind::new(r).is_slnr(), "type {r} is not SLNR"); + } + } + + #[test] + fn idr_poc_is_zero() { + // §8.3.1 NOTE 1: an IDR has poc_lsb inferred 0, NoRaslOutputFlag 1 + // ⇒ PicOrderCntVal == 0. + let mut st = PocState::new(); + let poc = st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 256); + assert_eq!(poc.val, 0); + assert_eq!(poc.msb, 0); + } + + #[test] + fn trailing_pictures_roll_the_msb_forward() { + // IDR(poc 0), then four P-frames at lsb 1,2,3,4 ⇒ poc 1,2,3,4. + let mut st = PocState::new(); + let idr = st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 256); + assert_eq!(idr.val, 0); + for lsb in 1..=4 { + let p = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, lsb, 256); + assert_eq!(p.val, lsb as i32, "trailing poc lsb {lsb}"); + } + } + + #[test] + fn lsb_wrap_increments_the_msb() { + // MaxPicOrderCntLsb = 16 (small for the test). Walk the lsb up in + // small forward steps (≤ half) so the MSB stays 0: 4, 8, 12, 15. + // Then lsb 2 against prev 15: 2 < 15 and (15 − 2) = 13 >= 8 ⇒ + // equation-8-1 forward-wrap branch ⇒ msb += 16 ⇒ poc 18. + let mut st = PocState::new(); + st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 16); + for lsb in [4u32, 8, 12, 15] { + st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, lsb, 16); + } + let b = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, 2, 16); + assert_eq!(b.val, 18, "lsb wrap 15→2 rolls the msb to 16"); + } + + #[test] + fn lsb_backward_jump_decrements_the_msb() { + // From a high lsb, a forward jump greater than half decrements + // the MSB (B-frame reordering). Start msb at 16 (poc 16 at lsb 0), + // then a lsb 14: 14 > 0 and (14 − 0) > 8 ⇒ msb −= 16 ⇒ poc −2. + let mut st = PocState::new(); + st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 16); + // Advance to poc 16 (lsb wraps 0 four times via lsb 4,8,12,0). + for lsb in [4u32, 8, 12, 0] { + st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, lsb, 16); + } + // prevTid0 now (lsb 0, msb 16). A lsb-14 picture: backward branch. + let b = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, 14, 16); + assert_eq!(b.val, 14); + } + + #[test] + fn rasl_radl_slnr_do_not_advance_prev_tid0() { + let mut st = PocState::new(); + st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 256); + // A RADL at lsb 2 derives poc 2 but does NOT become prevTid0Pic. + let radl = st.decode_picture_poc(NalKind::new(NalKind::RADL_R), 0, false, 2, 256); + assert_eq!(radl.val, 2); + // The next trailing picture still references the IDR's prev state + // (lsb 0, msb 0), so lsb 1 ⇒ poc 1 (not relative to the RADL). + let p = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, 1, 256); + assert_eq!(p.val, 1); + } + + #[test] + fn temporal_id_nonzero_does_not_advance_prev_tid0() { + let mut st = PocState::new(); + st.decode_picture_poc(NalKind::new(NalKind::IDR_N_LP), 0, true, 0, 256); + // A TemporalId == 1 trailing picture derives its POC but does not + // update prevTid0Pic. + let t1 = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 1, false, 5, 256); + assert_eq!(t1.val, 5); + let p = st.decode_picture_poc(NalKind::new(NalKind::TRAIL_R), 0, false, 1, 256); + assert_eq!(p.val, 1, "prevTid0 unchanged by the sub-layer picture"); + } + + #[test] + fn diff_pic_order_cnt_subtracts() { + assert_eq!(diff_pic_order_cnt(8, 2), 6); + assert_eq!(diff_pic_order_cnt(2, 8), -6); + } +} diff --git a/vendor/oxideav-h265/src/pps.rs b/vendor/oxideav-h265/src/pps.rs new file mode 100644 index 0000000..8bf1c50 --- /dev/null +++ b/vendor/oxideav-h265/src/pps.rs @@ -0,0 +1,1880 @@ +//! Picture Parameter Set (PPS) parser per ITU-T Rec. H.265 §7.3.2.3.1. +//! +//! Round-5 scope: parse the general `pic_parameter_set_rbsp()` body +//! through `pps_extension_present_flag`, materialising every field of +//! the §7.3.2.3.1 syntax table including the tiles block +//! (`num_tile_columns_minus1` / `num_tile_rows_minus1` / +//! `uniform_spacing_flag` and, when `uniform_spacing_flag == 0`, the +//! `column_width_minus1[]` / `row_height_minus1[]` arrays) and the +//! deblocking-filter-control block. The §7.4.3.3.1 inference rules for +//! the conditionally-signalled fields are applied so the parsed struct +//! always carries the effective value. +//! +//! One body is parsed via the shared `scaling_list` module; one is +//! surfaced rather than decoded: +//! +//! * `pps_scaling_list_data_present_flag == 1` triggers a §7.3.4 +//! `scaling_list_data()` parse into [`ScalingListData`] (shared with +//! the SPS path). +//! * When `pps_extension_present_flag == 1` the eight bits of typed +//! extension flags (`pps_range_extension_flag`, +//! `pps_multilayer_extension_flag`, `pps_3d_extension_flag`, +//! `pps_scc_extension_flag`, `pps_extension_4bits`) are decoded into +//! [`PpsExtensionFlags`]. When all five sub-fields are zero only the +//! `rbsp_trailing_bits()` remain and they are consumed implicitly; +//! otherwise the extension bodies (`pps_range_extension()`, +//! `pps_multilayer_extension()`, `pps_3d_extension()`, +//! `pps_scc_extension()`, and the +//! `pps_extension_data_flag` while-loop gated by +//! `pps_extension_4bits`) are surfaced as a single [`OpaqueTail`] +//! starting at the bit position of the first body. The §7.4.3.3.1 +//! inference rules apply for the absent case (every flag inferred +//! to 0). +//! +//! ## Layout summary +//! +//! ```text +//! pps_pic_parameter_set_id ue(v) +//! pps_seq_parameter_set_id ue(v) +//! dependent_slice_segments_enabled_flag u(1) +//! output_flag_present_flag u(1) +//! num_extra_slice_header_bits u(3) +//! sign_data_hiding_enabled_flag u(1) +//! cabac_init_present_flag u(1) +//! num_ref_idx_l0_default_active_minus1 ue(v) +//! num_ref_idx_l1_default_active_minus1 ue(v) +//! init_qp_minus26 se(v) +//! constrained_intra_pred_flag u(1) +//! transform_skip_enabled_flag u(1) +//! cu_qp_delta_enabled_flag u(1) +//! if( cu_qp_delta_enabled_flag ) +//! diff_cu_qp_delta_depth ue(v) +//! pps_cb_qp_offset se(v) +//! pps_cr_qp_offset se(v) +//! pps_slice_chroma_qp_offsets_present_flag u(1) +//! weighted_pred_flag u(1) +//! weighted_bipred_flag u(1) +//! transquant_bypass_enabled_flag u(1) +//! tiles_enabled_flag u(1) +//! entropy_coding_sync_enabled_flag u(1) +//! if( tiles_enabled_flag ) { +//! num_tile_columns_minus1 ue(v) +//! num_tile_rows_minus1 ue(v) +//! uniform_spacing_flag u(1) +//! if( !uniform_spacing_flag ) { +//! for( i = 0; i < num_tile_columns_minus1; i++ ) +//! column_width_minus1[i] ue(v) +//! for( i = 0; i < num_tile_rows_minus1; i++ ) +//! row_height_minus1[i] ue(v) +//! } +//! loop_filter_across_tiles_enabled_flag u(1) +//! } +//! pps_loop_filter_across_slices_enabled_flag u(1) +//! deblocking_filter_control_present_flag u(1) +//! if( deblocking_filter_control_present_flag ) { +//! deblocking_filter_override_enabled_flag u(1) +//! pps_deblocking_filter_disabled_flag u(1) +//! if( !pps_deblocking_filter_disabled_flag ) { +//! pps_beta_offset_div2 se(v) +//! pps_tc_offset_div2 se(v) +//! } +//! } +//! pps_scaling_list_data_present_flag u(1) +//! if( pps_scaling_list_data_present_flag ) +//! scaling_list_data( ) /* §7.3.4 */ +//! lists_modification_present_flag u(1) +//! log2_parallel_merge_level_minus2 ue(v) +//! slice_segment_header_extension_present_flag u(1) +//! pps_extension_present_flag u(1) +//! if( pps_extension_present_flag ) { +//! pps_range_extension_flag u(1) +//! pps_multilayer_extension_flag u(1) +//! pps_3d_extension_flag u(1) +//! pps_scc_extension_flag u(1) +//! pps_extension_4bits u(4) +//! } +//! /* opaque tail begins here when any of the four extension +//! flags is 1, or when pps_extension_4bits != 0 */ +//! ``` +//! +//! Validity checks performed here, sourced from §7.4.3.3.1: +//! +//! * `pps_pic_parameter_set_id` range 0..=63. +//! * `pps_seq_parameter_set_id` range 0..=15. +//! * `num_ref_idx_l{0,1}_default_active_minus1` range 0..=14. +//! * `init_qp_minus26` range −( 26 + QpBdOffsetY ) to +25. The +//! lower bound depends on the bit depth from the active SPS +//! (`QpBdOffsetY = 6 * bit_depth_luma_minus8`); without an SPS the +//! parser uses the loosest legal bound, −( 26 + 6*8 ) = −74, and a +//! caller that has resolved the SPS can re-check against the exact +//! bound via [`PicParameterSet::init_qp_in_range`]. +//! * `pps_cb_qp_offset` / `pps_cr_qp_offset` range −12..=12. +//! * `pps_beta_offset_div2` / `pps_tc_offset_div2` range −6..=6. + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::scaling_list::{ScalingListData, ScalingListError}; +use crate::sps::OpaqueTail; + +/// Errors that can arise while parsing a PPS RBSP. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PpsError { + /// The RBSP ran out of bits before the PPS was fully parsed. + Truncated, + /// A syntax element's parsed value was outside the legal range + /// specified for it in §7.4.3.3.1. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value as an `i64` (covers both `ue(v)` and + /// `se(v)` elements). + got: i64, + }, + /// A `scaling_list_data()` parse (§7.3.4) from the PPS failed. + ScalingList(ScalingListError), + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), +} + +impl core::fmt::Display for PpsError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("PPS RBSP truncated"), + Self::ValueOutOfRange { field, got } => { + write!(f, "PPS syntax element {field} out of range: {got}") + } + Self::ScalingList(e) => write!(f, "scaling-list error during PPS parse: {e}"), + Self::Bitstream(e) => write!(f, "bitstream error during PPS parse: {e}"), + } + } +} + +impl std::error::Error for PpsError {} + +impl From for PpsError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +impl From for PpsError { + fn from(e: ScalingListError) -> Self { + // Flatten truncation / raw-reader faults to the PPS-level + // equivalents; carry structured scaling-list faults as-is. + match e { + ScalingListError::Truncated => Self::Truncated, + ScalingListError::Bitstream(b) => Self::Bitstream(b), + other => Self::ScalingList(other), + } + } +} + +/// Tiles partitioning block per §7.3.2.3.1 (`tiles_enabled_flag == 1`). +/// +/// When `tiles_enabled_flag` is 0 this block is absent and the +/// derived values are inferred per §7.4.3.3.1 (one column, one row, +/// uniform spacing, loop filtering across tiles enabled). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct TileInfo { + /// `num_tile_columns_minus1` (`ue(v)`). The number of tile columns + /// is `value + 1`. + pub num_tile_columns_minus1: u32, + /// `num_tile_rows_minus1` (`ue(v)`). The number of tile rows is + /// `value + 1`. + pub num_tile_rows_minus1: u32, + /// `uniform_spacing_flag`. When true the explicit + /// `column_width_minus1[]` / `row_height_minus1[]` arrays are + /// absent and the partitioning is uniform. + pub uniform_spacing_flag: bool, + /// `column_width_minus1[i]` for `i` in + /// `0..num_tile_columns_minus1`. Empty when `uniform_spacing_flag`. + pub column_width_minus1: Vec, + /// `row_height_minus1[i]` for `i` in `0..num_tile_rows_minus1`. + /// Empty when `uniform_spacing_flag`. + pub row_height_minus1: Vec, +} + +/// Deblocking-filter-control block per §7.3.2.3.1 +/// (`deblocking_filter_control_present_flag == 1`). +/// +/// The [`Default`] value matches the §7.4.3.3.1 inference for the +/// absent-control case: every flag false and both offsets 0. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DeblockingFilterControl { + /// `deblocking_filter_override_enabled_flag`. Inferred to false + /// when the control block is absent (§7.4.3.3.1). + pub override_enabled_flag: bool, + /// `pps_deblocking_filter_disabled_flag`. Inferred to false when + /// the control block is absent (§7.4.3.3.1). + pub disabled_flag: bool, + /// `pps_beta_offset_div2` (`se(v)`, range −6..=6). Inferred to 0 + /// when absent (the disabled / no-control case). + pub beta_offset_div2: i8, + /// `pps_tc_offset_div2` (`se(v)`, range −6..=6). Inferred to 0 + /// when absent. + pub tc_offset_div2: i8, +} + +/// PPS extension-flag block per §7.3.2.3.1 +/// (`pps_extension_present_flag == 1`), holding the four typed +/// extension-present flags and the reserved-for-future-use +/// `pps_extension_4bits` group as a single `u8` (low 4 bits carry the +/// value; high 4 bits are zero). +/// +/// Per §7.4.3.3.1, when `pps_extension_present_flag == 0` every flag +/// in this block is inferred to 0 and `pps_extension_4bits` is +/// inferred to 0; the parser surfaces that case as +/// [`PicParameterSet::extension_flags`] = `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PpsExtensionFlags { + /// `pps_range_extension_flag` (§7.3.2.3.1). When true, a + /// `pps_range_extension()` body (§7.3.2.3.2) follows in the bit + /// stream and is currently surfaced inside the PPS + /// [`PicParameterSet::opaque_tail`]. + pub pps_range_extension_flag: bool, + /// `pps_multilayer_extension_flag` (§7.3.2.3.1, Annex F). When + /// true, a `pps_multilayer_extension()` body follows and is + /// surfaced inside the opaque tail. + pub pps_multilayer_extension_flag: bool, + /// `pps_3d_extension_flag` (§7.3.2.3.1, Annex I). When true, a + /// `pps_3d_extension()` body follows and is surfaced inside the + /// opaque tail. + pub pps_3d_extension_flag: bool, + /// `pps_scc_extension_flag` (§7.3.2.3.1). When true, a + /// `pps_scc_extension()` body follows and is surfaced inside the + /// opaque tail. + pub pps_scc_extension_flag: bool, + /// `pps_extension_4bits` (`u(4)`). For bitstreams conforming to + /// the current version of the specification this value shall be + /// 0; non-zero values are reserved for future use. The §7.4.3.3.1 + /// decoder-side rule is to allow any value and ignore the + /// `pps_extension_data_flag` while-loop it gates, so the parser + /// surfaces the value verbatim. The trailing + /// `while( more_rbsp_data() ) pps_extension_data_flag` block (only + /// signalled when this field is non-zero) is surfaced inside the + /// opaque tail. + pub pps_extension_4bits: u8, +} + +impl PpsExtensionFlags { + /// True when at least one of the four extension flags is set or + /// `pps_extension_4bits` is non-zero — i.e. when at least one + /// downstream extension body follows in the bit stream and the + /// PPS therefore carries an opaque tail starting at the first + /// body's bit position. + pub fn has_body(&self) -> bool { + self.pps_range_extension_flag + || self.pps_multilayer_extension_flag + || self.pps_3d_extension_flag + || self.pps_scc_extension_flag + || self.pps_extension_4bits != 0 + } + + /// True when the `pps_scc_extension()` body can be decoded in + /// place — it is signalled and no still-opaque body + /// (`pps_multilayer_extension()` / `pps_3d_extension()`) precedes it + /// in the bit stream. When a multilayer / 3D body precedes it, the + /// SCC body stays inside the opaque tail. + fn scc_decodable_in_place(&self) -> bool { + self.pps_scc_extension_flag + && !self.pps_multilayer_extension_flag + && !self.pps_3d_extension_flag + } + + /// True when an extension body still follows the (range + optionally + /// SCC) bodies decoded in place — i.e. a multilayer / 3D body, the + /// `pps_extension_data_flag` while-loop, or an SCC body whose + /// multilayer / 3D predecessor kept it opaque. + fn has_opaque_body_after_decoded(&self) -> bool { + if self.pps_multilayer_extension_flag || self.pps_3d_extension_flag { + // The first un-decoded body is the multilayer / 3D one; + // everything from there (incl. any SCC body) is opaque. + return true; + } + // No multilayer / 3D body: SCC (if present) was decoded in + // place, so only the pps_extension_data_flag while-loop may + // remain. + self.pps_extension_4bits != 0 + } +} + +/// One `( cb_qp_offset_list[i], cr_qp_offset_list[i] )` pair from the +/// `pps_range_extension()` chroma-QP-offset list (§7.3.2.3.2). Both +/// offsets are `se(v)` values constrained to −12..=+12 (§7.4.3.3.2), +/// used in the §8.6.1 derivation of `Qp′Cb` / `Qp′Cr` when +/// `cu_chroma_qp_offset_flag` selects entry `i`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ChromaQpOffsetListEntry { + /// `cb_qp_offset_list[i]` (`se(v)`, −12..=+12). + pub cb_qp_offset: i8, + /// `cr_qp_offset_list[i]` (`se(v)`, −12..=+12). + pub cr_qp_offset: i8, +} + +/// Decoded `pps_range_extension()` body per §7.3.2.3.2, present when +/// [`PpsExtensionFlags::pps_range_extension_flag`] is set. Per +/// §7.4.3.3.2 the absent fields are inferred to 0 / empty when this +/// struct is `None`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PpsRangeExtension { + /// `log2_max_transform_skip_block_size_minus2` (`ue(v)`), present + /// only when `transform_skip_enabled_flag` is set; inferred to 0 + /// otherwise. `Log2MaxTransformSkipSize = value + 2` (eq. 7-38). + pub log2_max_transform_skip_block_size_minus2: u32, + /// `cross_component_prediction_enabled_flag` — when 1, + /// `log2_res_scale_abs_plus1` / `res_scale_sign_flag` may be + /// present in the transform-unit syntax. + pub cross_component_prediction_enabled_flag: bool, + /// `chroma_qp_offset_list_enabled_flag` — when 1, + /// `cu_chroma_qp_offset_flag` may be present in the transform-unit + /// syntax and [`Self::chroma_qp_offset_list`] is populated. + pub chroma_qp_offset_list_enabled_flag: bool, + /// `diff_cu_chroma_qp_offset_depth` (`ue(v)`), present only when + /// `chroma_qp_offset_list_enabled_flag`. `Log2MinCuChromaQpOffsetSize + /// = CtbLog2SizeY − value` (eq. 7-39). + pub diff_cu_chroma_qp_offset_depth: u32, + /// `chroma_qp_offset_list_len_minus1` (`ue(v)`, 0..=5), present + /// only when `chroma_qp_offset_list_enabled_flag`. The + /// [`Self::chroma_qp_offset_list`] then holds `value + 1` entries. + pub chroma_qp_offset_list_len_minus1: u32, + /// The `cb_qp_offset_list[] / cr_qp_offset_list[]` pairs + /// (§7.3.2.3.2). Empty when `chroma_qp_offset_list_enabled_flag` + /// is 0; otherwise holds `chroma_qp_offset_list_len_minus1 + 1` + /// entries. + pub chroma_qp_offset_list: Vec, + /// `log2_sao_offset_scale_luma` (`ue(v)`) — base-2 log of the SAO + /// luma-offset scaling parameter (range 0..=Max(0, BitDepthY−10)). + pub log2_sao_offset_scale_luma: u32, + /// `log2_sao_offset_scale_chroma` (`ue(v)`) — base-2 log of the + /// SAO chroma-offset scaling parameter (0..=Max(0, BitDepthC−10)). + pub log2_sao_offset_scale_chroma: u32, +} + +impl PpsRangeExtension { + /// Maximum permitted `chroma_qp_offset_list_len_minus1` (§7.4.3.3.2). + const MAX_CHROMA_QP_OFFSET_LIST_LEN_MINUS1: u32 = 5; + + /// Decode `pps_range_extension()` (§7.3.2.3.2). The leading + /// `log2_max_transform_skip_block_size_minus2` is present only when + /// `transform_skip_enabled_flag` (a general-body field) is set. + fn parse(br: &mut BitReader, transform_skip_enabled_flag: bool) -> Result { + let log2_max_transform_skip_block_size_minus2 = if transform_skip_enabled_flag { + br.ue()? + } else { + 0 + }; + let cross_component_prediction_enabled_flag = br.u1()? != 0; + let chroma_qp_offset_list_enabled_flag = br.u1()? != 0; + let mut diff_cu_chroma_qp_offset_depth = 0u32; + let mut chroma_qp_offset_list_len_minus1 = 0u32; + let mut chroma_qp_offset_list = Vec::new(); + if chroma_qp_offset_list_enabled_flag { + diff_cu_chroma_qp_offset_depth = br.ue()?; + chroma_qp_offset_list_len_minus1 = br.ue()?; + if chroma_qp_offset_list_len_minus1 > Self::MAX_CHROMA_QP_OFFSET_LIST_LEN_MINUS1 { + return Err(PpsError::ValueOutOfRange { + field: "chroma_qp_offset_list_len_minus1", + got: chroma_qp_offset_list_len_minus1 as i64, + }); + } + let len = chroma_qp_offset_list_len_minus1 as usize + 1; + chroma_qp_offset_list.reserve(len); + for _ in 0..len { + let cb = br.se()?; + let cr = br.se()?; + for (field, v) in [("cb_qp_offset_list", cb), ("cr_qp_offset_list", cr)] { + if !(-12..=12).contains(&v) { + return Err(PpsError::ValueOutOfRange { + field, + got: v as i64, + }); + } + } + chroma_qp_offset_list.push(ChromaQpOffsetListEntry { + cb_qp_offset: cb as i8, + cr_qp_offset: cr as i8, + }); + } + } + let log2_sao_offset_scale_luma = br.ue()?; + let log2_sao_offset_scale_chroma = br.ue()?; + Ok(Self { + log2_max_transform_skip_block_size_minus2, + cross_component_prediction_enabled_flag, + chroma_qp_offset_list_enabled_flag, + diff_cu_chroma_qp_offset_depth, + chroma_qp_offset_list_len_minus1, + chroma_qp_offset_list, + log2_sao_offset_scale_luma, + log2_sao_offset_scale_chroma, + }) + } +} + +/// Decoded `pps_scc_extension()` body per §7.3.2.3.3, present when +/// [`PpsExtensionFlags::pps_scc_extension_flag`] is set and no opaque +/// multilayer / 3D body precedes it. Per §7.4.3.3.3 the absent fields +/// are inferred to 0 / empty when this struct is `None`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PpsSccExtension { + /// `pps_curr_pic_ref_enabled_flag` — when 1, a picture referring to + /// the PPS may appear in one of its own slices' reference picture + /// lists (intra block copy at the picture level). + pub pps_curr_pic_ref_enabled_flag: bool, + /// `residual_adaptive_colour_transform_enabled_flag` — when 1, the + /// adaptive colour transform may be applied to residuals. + pub residual_adaptive_colour_transform_enabled_flag: bool, + /// `pps_slice_act_qp_offsets_present_flag` — present only when + /// `residual_adaptive_colour_transform_enabled_flag`; when 1, the + /// `slice_act_*_qp_offset` fields are present in slice headers. + pub pps_slice_act_qp_offsets_present_flag: bool, + /// `pps_act_y_qp_offset_plus5` (`se(v)`), present only when + /// `residual_adaptive_colour_transform_enabled_flag`. + /// `PpsActQpOffsetY = value − 5` (eq. 7-39). + pub pps_act_y_qp_offset_plus5: i32, + /// `pps_act_cb_qp_offset_plus5` (`se(v)`), present only when + /// `residual_adaptive_colour_transform_enabled_flag`. + /// `PpsActQpOffsetCb = value − 5` (eq. 7-40). + pub pps_act_cb_qp_offset_plus5: i32, + /// `pps_act_cr_qp_offset_plus3` (`se(v)`), present only when + /// `residual_adaptive_colour_transform_enabled_flag`. + /// `PpsActQpOffsetCr = value − 3` (eq. 7-41). + pub pps_act_cr_qp_offset_plus3: i32, + /// `pps_palette_predictor_initializers_present_flag` — when 1, the + /// picture palette predictor is initialised from + /// [`Self::pps_palette_predictor_initializer`]. + pub pps_palette_predictor_initializers_present_flag: bool, + /// `pps_num_palette_predictor_initializers` (`ue(v)`), present only + /// when the initializers-present flag is set; the initializer table + /// then holds this many entries per component. + pub pps_num_palette_predictor_initializers: u32, + /// `monochrome_palette_flag` — present only when there is at least + /// one initializer; selects `numComps` (1 when set, else 3). + pub monochrome_palette_flag: bool, + /// `luma_bit_depth_entry_minus8` (`ue(v)`); the initializer's luma + /// component is `u(v)` of `luma_bit_depth_entry_minus8 + 8` bits. + pub luma_bit_depth_entry_minus8: u32, + /// `chroma_bit_depth_entry_minus8` (`ue(v)`), present only when not + /// `monochrome_palette_flag`; chroma components are `u(v)` of + /// `chroma_bit_depth_entry_minus8 + 8` bits. + pub chroma_bit_depth_entry_minus8: u32, + /// `pps_palette_predictor_initializer[comp][i]` (§7.3.2.3.3), + /// indexed `[comp][i]`. `comp` runs over `numComps`. Empty when no + /// initializers are signalled. + pub pps_palette_predictor_initializer: Vec>, +} + +impl PpsSccExtension { + /// Decode `pps_scc_extension()` (§7.3.2.3.3). Unlike the SPS variant, + /// the palette predictor initializer `u(v)` widths come from this + /// body's own `luma_bit_depth_entry_minus8` / + /// `chroma_bit_depth_entry_minus8`, so no SPS context is needed. + fn parse(br: &mut BitReader) -> Result { + let pps_curr_pic_ref_enabled_flag = br.u1()? != 0; + let residual_adaptive_colour_transform_enabled_flag = br.u1()? != 0; + let mut pps_slice_act_qp_offsets_present_flag = false; + let mut pps_act_y_qp_offset_plus5 = 0i32; + let mut pps_act_cb_qp_offset_plus5 = 0i32; + let mut pps_act_cr_qp_offset_plus3 = 0i32; + if residual_adaptive_colour_transform_enabled_flag { + pps_slice_act_qp_offsets_present_flag = br.u1()? != 0; + pps_act_y_qp_offset_plus5 = br.se()?; + pps_act_cb_qp_offset_plus5 = br.se()?; + pps_act_cr_qp_offset_plus3 = br.se()?; + // §7.4.3.3.3: PpsActQpOffsetY/Cb/Cr (eq. 7-39/40/41 — the + // raw values minus 5/5/3) must each lie in −12..=12 in a + // conforming bitstream. + // Widened arithmetic: se(v) can carry the full i32 range on + // a malformed stream, so the eq.-7-39..7-41 "minus 5/5/3" + // must not overflow before the range check rejects it. + for (field, qp) in [ + ( + "pps_act_y_qp_offset_plus5", + i64::from(pps_act_y_qp_offset_plus5) - 5, + ), + ( + "pps_act_cb_qp_offset_plus5", + i64::from(pps_act_cb_qp_offset_plus5) - 5, + ), + ( + "pps_act_cr_qp_offset_plus3", + i64::from(pps_act_cr_qp_offset_plus3) - 3, + ), + ] { + if !(-12..=12).contains(&qp) { + return Err(PpsError::ValueOutOfRange { field, got: qp }); + } + } + } + let pps_palette_predictor_initializers_present_flag = br.u1()? != 0; + let mut pps_num_palette_predictor_initializers = 0u32; + let mut monochrome_palette_flag = false; + let mut luma_bit_depth_entry_minus8 = 0u32; + let mut chroma_bit_depth_entry_minus8 = 0u32; + let mut pps_palette_predictor_initializer = Vec::new(); + if pps_palette_predictor_initializers_present_flag { + pps_num_palette_predictor_initializers = br.ue()?; + // §7.4.3.3.3: bounded by PaletteMaxPredictorSize, itself + // capped by the profile limits (palette_max_size + + // delta_palette_max_predictor_size); reject anything past + // the largest representable predictor so a malformed count + // cannot drive the initializer allocation. + if pps_num_palette_predictor_initializers > 128 { + return Err(PpsError::ValueOutOfRange { + field: "pps_num_palette_predictor_initializers", + got: i64::from(pps_num_palette_predictor_initializers), + }); + } + if pps_num_palette_predictor_initializers > 0 { + monochrome_palette_flag = br.u1()? != 0; + luma_bit_depth_entry_minus8 = br.ue()?; + if !monochrome_palette_flag { + chroma_bit_depth_entry_minus8 = br.ue()?; + } + // §7.4.3.3.3: the entry bit depths are BitDepth values + // (8..=16), i.e. the minus8 fields lie in 0..=8 — checked + // before the `+ 8` width arithmetic below. + for (field, v) in [ + ("luma_bit_depth_entry_minus8", luma_bit_depth_entry_minus8), + ( + "chroma_bit_depth_entry_minus8", + chroma_bit_depth_entry_minus8, + ), + ] { + if v > 8 { + return Err(PpsError::ValueOutOfRange { + field, + got: i64::from(v), + }); + } + } + let num_comps = if monochrome_palette_flag { 1 } else { 3 }; + let num_entries = pps_num_palette_predictor_initializers as usize; + pps_palette_predictor_initializer.reserve(num_comps); + for comp in 0..num_comps { + let width = if comp == 0 { + (luma_bit_depth_entry_minus8 + 8) as u8 + } else { + (chroma_bit_depth_entry_minus8 + 8) as u8 + }; + let mut row = Vec::with_capacity(num_entries); + for _ in 0..num_entries { + row.push(br.u(width)?); + } + pps_palette_predictor_initializer.push(row); + } + } + } + Ok(Self { + pps_curr_pic_ref_enabled_flag, + residual_adaptive_colour_transform_enabled_flag, + pps_slice_act_qp_offsets_present_flag, + pps_act_y_qp_offset_plus5, + pps_act_cb_qp_offset_plus5, + pps_act_cr_qp_offset_plus3, + pps_palette_predictor_initializers_present_flag, + pps_num_palette_predictor_initializers, + monochrome_palette_flag, + luma_bit_depth_entry_minus8, + chroma_bit_depth_entry_minus8, + pps_palette_predictor_initializer, + }) + } + + /// `PpsActQpOffsetY` (eq. 7-39) — `pps_act_y_qp_offset_plus5 − 5`. + pub fn pps_act_qp_offset_y(&self) -> i32 { + self.pps_act_y_qp_offset_plus5 - 5 + } + + /// `PpsActQpOffsetCb` (eq. 7-40) — `pps_act_cb_qp_offset_plus5 − 5`. + pub fn pps_act_qp_offset_cb(&self) -> i32 { + self.pps_act_cb_qp_offset_plus5 - 5 + } + + /// `PpsActQpOffsetCr` (eq. 7-41) — `pps_act_cr_qp_offset_plus3 − 3`. + pub fn pps_act_qp_offset_cr(&self) -> i32 { + self.pps_act_cr_qp_offset_plus3 - 3 + } +} + +/// Parsed Picture Parameter Set per §7.3.2.3.1. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PicParameterSet { + /// `pps_pic_parameter_set_id` (`ue(v)`, range 0..=63). + pub pps_id: u8, + /// `pps_seq_parameter_set_id` (`ue(v)`, range 0..=15) — the SPS + /// this PPS activates. + pub sps_id: u8, + /// `dependent_slice_segments_enabled_flag`. + pub dependent_slice_segments_enabled_flag: bool, + /// `output_flag_present_flag`. + pub output_flag_present_flag: bool, + /// `num_extra_slice_header_bits` (`u(3)`). The conformance range + /// is 0..=2 but decoders must accept any value, so this is not + /// range-checked. + pub num_extra_slice_header_bits: u8, + /// `sign_data_hiding_enabled_flag`. + pub sign_data_hiding_enabled_flag: bool, + /// `cabac_init_present_flag`. + pub cabac_init_present_flag: bool, + /// `num_ref_idx_l0_default_active_minus1` (`ue(v)`, range 0..=14). + /// `num_ref_idx_l0_default_active = value + 1`. + pub num_ref_idx_l0_default_active_minus1: u8, + /// `num_ref_idx_l1_default_active_minus1` (`ue(v)`, range 0..=14). + pub num_ref_idx_l1_default_active_minus1: u8, + /// `init_qp_minus26` (`se(v)`). `init_qp = value + 26`. + pub init_qp_minus26: i32, + /// `constrained_intra_pred_flag`. + pub constrained_intra_pred_flag: bool, + /// `transform_skip_enabled_flag`. + pub transform_skip_enabled_flag: bool, + /// `cu_qp_delta_enabled_flag`. When set, [`Self::diff_cu_qp_delta_depth`] + /// is signalled; otherwise it is inferred to 0. + pub cu_qp_delta_enabled_flag: bool, + /// `diff_cu_qp_delta_depth` (`ue(v)`). Inferred to 0 when + /// `cu_qp_delta_enabled_flag` is false (§7.4.3.3.1). + pub diff_cu_qp_delta_depth: u32, + /// `pps_cb_qp_offset` (`se(v)`, range −12..=12). + pub pps_cb_qp_offset: i8, + /// `pps_cr_qp_offset` (`se(v)`, range −12..=12). + pub pps_cr_qp_offset: i8, + /// `pps_slice_chroma_qp_offsets_present_flag`. + pub pps_slice_chroma_qp_offsets_present_flag: bool, + /// `weighted_pred_flag`. + pub weighted_pred_flag: bool, + /// `weighted_bipred_flag`. + pub weighted_bipred_flag: bool, + /// `transquant_bypass_enabled_flag`. + pub transquant_bypass_enabled_flag: bool, + /// `tiles_enabled_flag`. When set, [`Self::tiles`] carries the + /// signalled values; otherwise it carries the §7.4.3.3.1 inferred + /// single-tile values. + pub tiles_enabled_flag: bool, + /// `entropy_coding_sync_enabled_flag`. + pub entropy_coding_sync_enabled_flag: bool, + /// Tiles block. Present (with inferred single-tile values) even + /// when `tiles_enabled_flag` is false, so callers always have an + /// effective tile geometry. + pub tiles: TileInfo, + /// `loop_filter_across_tiles_enabled_flag`. Inferred to true when + /// the tiles block is absent (§7.4.3.3.1). + pub loop_filter_across_tiles_enabled_flag: bool, + /// `pps_loop_filter_across_slices_enabled_flag`. + pub pps_loop_filter_across_slices_enabled_flag: bool, + /// `deblocking_filter_control_present_flag`. + pub deblocking_filter_control_present_flag: bool, + /// Deblocking-filter-control values, carrying §7.4.3.3.1 inferred + /// defaults when the control block is absent. + pub deblocking: DeblockingFilterControl, + /// `pps_scaling_list_data_present_flag` (§7.3.2.3.1). When set, the + /// PPS carries an explicit [`Self::scaling_list_data`]. + pub pps_scaling_list_data_present_flag: bool, + /// The parsed §7.3.4 `scaling_list_data()` structure when + /// `pps_scaling_list_data_present_flag == 1`; `None` otherwise. + pub scaling_list_data: Option, + /// `lists_modification_present_flag`. + pub lists_modification_present_flag: bool, + /// `log2_parallel_merge_level_minus2` (`ue(v)`). + /// `Log2ParMrgLevel = value + 2`. + pub log2_parallel_merge_level_minus2: u32, + /// `slice_segment_header_extension_present_flag`. + pub slice_segment_header_extension_present_flag: bool, + /// `pps_extension_present_flag`. When set, the + /// [`Self::extension_flags`] block is decoded into typed fields; + /// any extension body whose flag is set (and the + /// `pps_extension_data_flag` while-loop gated by + /// `pps_extension_4bits != 0`) is surfaced inside + /// [`Self::opaque_tail`]. + pub pps_extension_present_flag: bool, + /// Typed extension-flag block per §7.3.2.3.1 + /// (`pps_extension_present_flag == 1`). `None` when the gate is + /// absent; in that case every flag is inferred to 0 per the + /// §7.4.3.3.1 inference rules. + pub extension_flags: Option, + /// Decoded `pps_range_extension()` body (§7.3.2.3.2), present when + /// `extension_flags.pps_range_extension_flag` is set. `None` + /// otherwise; per §7.4.3.3.2 every field is then inferred to 0 / + /// empty. + pub pps_range_extension: Option, + /// Decoded `pps_scc_extension()` body (§7.3.2.3.3), present when + /// `extension_flags.pps_scc_extension_flag` is set **and** no opaque + /// multilayer / 3D body precedes it. `None` otherwise; per + /// §7.4.3.3.3 every field is then inferred to 0 / empty. + pub pps_scc_extension: Option, + /// Opaque suffix of the PPS RBSP. Populated when + /// `pps_extension_present_flag == 1` **and** + /// [`PpsExtensionFlags::has_body`] is true on the decoded flags + /// — the bit position recorded inside the tail is the start of + /// the first signalled extension body (`pps_range_extension()` + /// if `pps_range_extension_flag`, otherwise the next set flag's + /// body, otherwise the `pps_extension_data_flag` while-loop). The + /// individual extension-body syntax structures are not yet + /// decoded. `None` when the PPS ended cleanly after the flag + /// block (no extension body is signalled and only + /// `rbsp_trailing_bits()` remains; consumed implicitly) or when + /// `pps_extension_present_flag == 0`. + pub opaque_tail: Option, +} + +impl PicParameterSet { + /// Parse `pic_parameter_set_rbsp()` starting from the first bit of + /// the (already-unescaped) RBSP body — i.e. after the two-byte NAL + /// header has been removed (see [`crate::nal::NalUnit`]). + pub fn parse(rbsp: &[u8]) -> Result { + let mut br = BitReader::new(rbsp); + Self::parse_inner(&mut br, rbsp) + } + + fn parse_inner(br: &mut BitReader<'_>, rbsp: &[u8]) -> Result { + let pps_id_raw = br.ue()?; + if pps_id_raw > 63 { + return Err(PpsError::ValueOutOfRange { + field: "pps_pic_parameter_set_id", + got: pps_id_raw as i64, + }); + } + let sps_id_raw = br.ue()?; + if sps_id_raw > 15 { + return Err(PpsError::ValueOutOfRange { + field: "pps_seq_parameter_set_id", + got: sps_id_raw as i64, + }); + } + + let dependent_slice_segments_enabled_flag = br.u1()? != 0; + let output_flag_present_flag = br.u1()? != 0; + let num_extra_slice_header_bits = br.u(3)? as u8; + let sign_data_hiding_enabled_flag = br.u1()? != 0; + let cabac_init_present_flag = br.u1()? != 0; + + let num_ref_idx_l0_default_active_minus1_raw = br.ue()?; + if num_ref_idx_l0_default_active_minus1_raw > 14 { + return Err(PpsError::ValueOutOfRange { + field: "num_ref_idx_l0_default_active_minus1", + got: num_ref_idx_l0_default_active_minus1_raw as i64, + }); + } + let num_ref_idx_l1_default_active_minus1_raw = br.ue()?; + if num_ref_idx_l1_default_active_minus1_raw > 14 { + return Err(PpsError::ValueOutOfRange { + field: "num_ref_idx_l1_default_active_minus1", + got: num_ref_idx_l1_default_active_minus1_raw as i64, + }); + } + + let init_qp_minus26 = br.se()?; + // §7.4.3.3.1: −( 26 + QpBdOffsetY ) .. +25. The lower bound + // depends on the active SPS bit depth; QpBdOffsetY is at most + // 6 * 8 = 48 (the maximum legal bit_depth_luma_minus8), so the + // loosest legal lower bound is −74. We range-check against the + // loosest bound here (no SPS context) and provide + // `init_qp_in_range()` for callers that have resolved the SPS. + if !(-74..=25).contains(&init_qp_minus26) { + return Err(PpsError::ValueOutOfRange { + field: "init_qp_minus26", + got: init_qp_minus26 as i64, + }); + } + + let constrained_intra_pred_flag = br.u1()? != 0; + let transform_skip_enabled_flag = br.u1()? != 0; + + let cu_qp_delta_enabled_flag = br.u1()? != 0; + let diff_cu_qp_delta_depth = if cu_qp_delta_enabled_flag { + br.ue()? + } else { + // §7.4.3.3.1 inference. + 0 + }; + + let pps_cb_qp_offset = br.se()?; + if !(-12..=12).contains(&pps_cb_qp_offset) { + return Err(PpsError::ValueOutOfRange { + field: "pps_cb_qp_offset", + got: pps_cb_qp_offset as i64, + }); + } + let pps_cr_qp_offset = br.se()?; + if !(-12..=12).contains(&pps_cr_qp_offset) { + return Err(PpsError::ValueOutOfRange { + field: "pps_cr_qp_offset", + got: pps_cr_qp_offset as i64, + }); + } + + let pps_slice_chroma_qp_offsets_present_flag = br.u1()? != 0; + let weighted_pred_flag = br.u1()? != 0; + let weighted_bipred_flag = br.u1()? != 0; + let transquant_bypass_enabled_flag = br.u1()? != 0; + let tiles_enabled_flag = br.u1()? != 0; + let entropy_coding_sync_enabled_flag = br.u1()? != 0; + + let (tiles, loop_filter_across_tiles_enabled_flag) = if tiles_enabled_flag { + let num_tile_columns_minus1 = br.ue()?; + let num_tile_rows_minus1 = br.ue()?; + // §A.4.1 item f): "num_tile_columns_minus1 shall be less + // than MaxTileCols and num_tile_rows_minus1 shall be less + // than MaxTileRows". The largest Table A.8 entries are + // MaxTileCols = 40 / MaxTileRows = 44 (levels 7 .. 7.2); + // the tighter §7.4.3.3.1 PicWidthInCtbsY-relative bound + // needs the active SPS, which the PPS parse does not see. + // Rejecting here also bounds the explicit width / height + // array allocations below. + if num_tile_columns_minus1 >= 40 { + return Err(PpsError::ValueOutOfRange { + field: "num_tile_columns_minus1", + got: num_tile_columns_minus1 as i64, + }); + } + if num_tile_rows_minus1 >= 44 { + return Err(PpsError::ValueOutOfRange { + field: "num_tile_rows_minus1", + got: num_tile_rows_minus1 as i64, + }); + } + let uniform_spacing_flag = br.u1()? != 0; + let (column_width_minus1, row_height_minus1) = if !uniform_spacing_flag { + let mut cols = Vec::with_capacity(num_tile_columns_minus1 as usize); + for _ in 0..num_tile_columns_minus1 { + cols.push(br.ue()?); + } + let mut rows = Vec::with_capacity(num_tile_rows_minus1 as usize); + for _ in 0..num_tile_rows_minus1 { + rows.push(br.ue()?); + } + (cols, rows) + } else { + (Vec::new(), Vec::new()) + }; + let loop_filter_across_tiles_enabled_flag = br.u1()? != 0; + ( + TileInfo { + num_tile_columns_minus1, + num_tile_rows_minus1, + uniform_spacing_flag, + column_width_minus1, + row_height_minus1, + }, + loop_filter_across_tiles_enabled_flag, + ) + } else { + // §7.4.3.3.1 inference: one column, one row, uniform + // spacing, loop filtering across tiles enabled. + ( + TileInfo { + num_tile_columns_minus1: 0, + num_tile_rows_minus1: 0, + uniform_spacing_flag: true, + column_width_minus1: Vec::new(), + row_height_minus1: Vec::new(), + }, + true, + ) + }; + + let pps_loop_filter_across_slices_enabled_flag = br.u1()? != 0; + + let deblocking_filter_control_present_flag = br.u1()? != 0; + let deblocking = if deblocking_filter_control_present_flag { + let override_enabled_flag = br.u1()? != 0; + let disabled_flag = br.u1()? != 0; + let (beta_offset_div2, tc_offset_div2) = if !disabled_flag { + let beta = br.se()?; + if !(-6..=6).contains(&beta) { + return Err(PpsError::ValueOutOfRange { + field: "pps_beta_offset_div2", + got: beta as i64, + }); + } + let tc = br.se()?; + if !(-6..=6).contains(&tc) { + return Err(PpsError::ValueOutOfRange { + field: "pps_tc_offset_div2", + got: tc as i64, + }); + } + (beta as i8, tc as i8) + } else { + // §7.4.3.3.1: beta/tc offsets inferred to 0 when the + // deblocking filter is disabled at PPS level. + (0, 0) + }; + DeblockingFilterControl { + override_enabled_flag, + disabled_flag, + beta_offset_div2, + tc_offset_div2, + } + } else { + DeblockingFilterControl::default() + }; + + let pps_scaling_list_data_present_flag = br.u1()? != 0; + let scaling_list_data = if pps_scaling_list_data_present_flag { + // scaling_list_data() (§7.3.4), shared with the SPS path. + Some(ScalingListData::parse(br)?) + } else { + None + }; + + let lists_modification_present_flag = br.u1()? != 0; + let log2_parallel_merge_level_minus2 = br.ue()?; + let slice_segment_header_extension_present_flag = br.u1()? != 0; + + let pps_extension_present_flag = br.u1()? != 0; + let (extension_flags, pps_range_extension, pps_scc_extension, opaque_tail) = + if pps_extension_present_flag { + // §7.3.2.3.1: when the gate is open, decode the eight bits + // of typed extension flags first. + let pps_range_extension_flag = br.u1()? != 0; + let pps_multilayer_extension_flag = br.u1()? != 0; + let pps_3d_extension_flag = br.u1()? != 0; + let pps_scc_extension_flag = br.u1()? != 0; + let pps_extension_4bits = br.u(4)? as u8; + let flags = PpsExtensionFlags { + pps_range_extension_flag, + pps_multilayer_extension_flag, + pps_3d_extension_flag, + pps_scc_extension_flag, + pps_extension_4bits, + }; + // §7.3.2.3.1: the range extension (if signalled) is the + // first body to follow the eight typed flag bits, so decode + // it in full. Its leading + // log2_max_transform_skip_block_size_minus2 is present only + // when transform_skip_enabled_flag was set in the general + // body. + let range_ext = if flags.pps_range_extension_flag { + Some(PpsRangeExtension::parse(br, transform_skip_enabled_flag)?) + } else { + None + }; + // §7.3.2.3.1 body order is range, multilayer, 3d, scc. The + // SCC body can be decoded in place only when no + // (still-opaque) multilayer / 3D body precedes it; + // otherwise it stays inside the opaque tail. + let scc_ext = if flags.scc_decodable_in_place() { + Some(PpsSccExtension::parse(br)?) + } else { + None + }; + // If any still-opaque body (a multilayer / 3D body, an SCC + // body kept opaque by such a predecessor, or the + // pps_extension_data_flag while-loop) follows, capture the + // rest of the RBSP as an opaque tail starting at the first + // un-decoded body's bit position. Otherwise only + // rbsp_trailing_bits remains, consumed implicitly. + let tail = if flags.has_opaque_body_after_decoded() { + Some(OpaqueTail::capture_at(br.bit_pos(), rbsp)) + } else { + None + }; + (Some(flags), range_ext, scc_ext, tail) + } else { + // §7.4.3.3.1: every extension flag inferred to 0; only + // rbsp_trailing_bits remains, consumed implicitly. + (None, None, None, None) + }; + + Ok(Self { + pps_id: pps_id_raw as u8, + sps_id: sps_id_raw as u8, + dependent_slice_segments_enabled_flag, + output_flag_present_flag, + num_extra_slice_header_bits, + sign_data_hiding_enabled_flag, + cabac_init_present_flag, + num_ref_idx_l0_default_active_minus1: num_ref_idx_l0_default_active_minus1_raw as u8, + num_ref_idx_l1_default_active_minus1: num_ref_idx_l1_default_active_minus1_raw as u8, + init_qp_minus26, + constrained_intra_pred_flag, + transform_skip_enabled_flag, + cu_qp_delta_enabled_flag, + diff_cu_qp_delta_depth, + pps_cb_qp_offset: pps_cb_qp_offset as i8, + pps_cr_qp_offset: pps_cr_qp_offset as i8, + pps_slice_chroma_qp_offsets_present_flag, + weighted_pred_flag, + weighted_bipred_flag, + transquant_bypass_enabled_flag, + tiles_enabled_flag, + entropy_coding_sync_enabled_flag, + tiles, + loop_filter_across_tiles_enabled_flag, + pps_loop_filter_across_slices_enabled_flag, + deblocking_filter_control_present_flag, + deblocking, + pps_scaling_list_data_present_flag, + scaling_list_data, + lists_modification_present_flag, + log2_parallel_merge_level_minus2, + slice_segment_header_extension_present_flag, + pps_extension_present_flag, + extension_flags, + pps_range_extension, + pps_scc_extension, + opaque_tail, + }) + } + + /// `init_qp = init_qp_minus26 + 26` per §7.4.3.3.1 — the + /// per-picture base QP before any slice-header `slice_qp_delta`. + pub fn init_qp(&self) -> i32 { + self.init_qp_minus26 + 26 + } + + /// `num_ref_idx_l0_default_active = num_ref_idx_l0_default_active_minus1 + 1`. + pub fn num_ref_idx_l0_default_active(&self) -> u8 { + self.num_ref_idx_l0_default_active_minus1 + 1 + } + + /// `num_ref_idx_l1_default_active = num_ref_idx_l1_default_active_minus1 + 1`. + pub fn num_ref_idx_l1_default_active(&self) -> u8 { + self.num_ref_idx_l1_default_active_minus1 + 1 + } + + /// Number of tile columns: `num_tile_columns_minus1 + 1`. + pub fn num_tile_columns(&self) -> u32 { + self.tiles.num_tile_columns_minus1 + 1 + } + + /// Number of tile rows: `num_tile_rows_minus1 + 1`. + pub fn num_tile_rows(&self) -> u32 { + self.tiles.num_tile_rows_minus1 + 1 + } + + /// `Log2ParMrgLevel = log2_parallel_merge_level_minus2 + 2` + /// (equation 7-37). + pub fn log2_par_mrg_level(&self) -> u32 { + self.log2_parallel_merge_level_minus2 + 2 + } + + /// Re-check `init_qp_minus26` against the exact §7.4.3.3.1 lower + /// bound `−( 26 + QpBdOffsetY )` once the active SPS bit depth is + /// known. `bit_depth_luma_minus8` is the value carried on the SPS + /// this PPS activates (`QpBdOffsetY = 6 * bit_depth_luma_minus8`). + /// The parser already verified the upper bound (+25) and the + /// loosest lower bound (−74) during the parse. + pub fn init_qp_in_range(&self, bit_depth_luma_minus8: u8) -> bool { + let qp_bd_offset_y = 6 * bit_depth_luma_minus8 as i32; + let lower = -(26 + qp_bd_offset_y); + (lower..=25).contains(&self.init_qp_minus26) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::nal::collect_nal_units; + + /// PPS RBSP body extracted from + /// `docs/video/h265/fixtures/tiny-i-only-16x16-main/input.hevc`, + /// after the Annex B start code and the two-byte NAL header have + /// been removed. The wire PPS (NAL idx 2, type 34) was 6 bytes + /// including the two-byte header (`44 01`); the body is the + /// remaining 4 bytes. It carries no emulation-prevention bytes. + const TINY_PPS_RBSP: &[u8] = &[0xC1, 0x73, 0xC0, 0x89]; + + #[test] + fn parses_tiny_fixture_pps() { + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS parse"); + // Trace cross-check + // (docs/video/h265/fixtures/tiny-i-only-16x16-main/trace.txt, + // line 3 "PPS ..."): + // pps_id=0 sps_id=0 dependent_slice_segments=0 + // output_flag_present=0 num_extra_slice_header_bits=0 + // sign_data_hiding=1 cabac_init_present=0 + // num_ref_idx_l0_default=1 num_ref_idx_l1_default=1 init_qp=26 + // constrained_intra_pred=0 transform_skip_enabled=0 + // cu_qp_delta_enabled=1 diff_cu_qp_delta_depth=0 + // weighted_pred=0 weighted_bipred=0 transquant_bypass=0 + // tiles_enabled=0 num_tile_columns=1 num_tile_rows=1 + // entropy_coding_sync_enabled=0 loop_filter_across_tiles=1 + // deblock_filter_override_enabled=0 lists_modification_present=0 + assert_eq!(pps.pps_id, 0); + assert_eq!(pps.sps_id, 0); + assert!(!pps.dependent_slice_segments_enabled_flag); + assert!(!pps.output_flag_present_flag); + assert_eq!(pps.num_extra_slice_header_bits, 0); + assert!(pps.sign_data_hiding_enabled_flag); + assert!(!pps.cabac_init_present_flag); + assert_eq!(pps.num_ref_idx_l0_default_active_minus1, 0); + assert_eq!(pps.num_ref_idx_l1_default_active_minus1, 0); + assert_eq!(pps.num_ref_idx_l0_default_active(), 1); + assert_eq!(pps.num_ref_idx_l1_default_active(), 1); + assert_eq!(pps.init_qp_minus26, 0); + assert_eq!(pps.init_qp(), 26); + assert!(!pps.constrained_intra_pred_flag); + assert!(!pps.transform_skip_enabled_flag); + assert!(pps.cu_qp_delta_enabled_flag); + assert_eq!(pps.diff_cu_qp_delta_depth, 0); + assert_eq!(pps.pps_cb_qp_offset, 0); + assert_eq!(pps.pps_cr_qp_offset, 0); + assert!(!pps.pps_slice_chroma_qp_offsets_present_flag); + assert!(!pps.weighted_pred_flag); + assert!(!pps.weighted_bipred_flag); + assert!(!pps.transquant_bypass_enabled_flag); + assert!(!pps.tiles_enabled_flag); + assert!(!pps.entropy_coding_sync_enabled_flag); + // tiles_enabled=0 → single tile inferred per §7.4.3.3.1. + assert_eq!(pps.num_tile_columns(), 1); + assert_eq!(pps.num_tile_rows(), 1); + assert!(pps.tiles.uniform_spacing_flag); + assert!(pps.tiles.column_width_minus1.is_empty()); + assert!(pps.tiles.row_height_minus1.is_empty()); + assert!(pps.loop_filter_across_tiles_enabled_flag); // inferred true + assert!(pps.pps_loop_filter_across_slices_enabled_flag); + // deblocking control absent → defaults inferred. + assert!(!pps.deblocking_filter_control_present_flag); + assert!(!pps.deblocking.override_enabled_flag); + assert!(!pps.deblocking.disabled_flag); + assert_eq!(pps.deblocking.beta_offset_div2, 0); + assert_eq!(pps.deblocking.tc_offset_div2, 0); + assert!(!pps.pps_scaling_list_data_present_flag); + assert!(!pps.lists_modification_present_flag); + assert_eq!(pps.log2_parallel_merge_level_minus2, 0); + assert!(!pps.slice_segment_header_extension_present_flag); + // No PPS extension in this fixture → no opaque tail. + assert!(!pps.pps_extension_present_flag); + assert!(pps.opaque_tail.is_none()); + } + + /// End-to-end: pull the PPS NAL out of the raw Annex B stream + /// through the walker, then parse its (already-unescaped, header- + /// stripped) RBSP. The fixture's PPS NAL bytes (start code + + /// `44 01 C1 73 C0 89`) are captured inline so the test does not + /// depend on the `docs/` tree at run time. + #[test] + fn parses_tiny_fixture_pps_via_nal_walker() { + // 4-byte start code + PPS NAL (type 34: header 0x44 0x01). + let stream = [0x00, 0x00, 0x00, 0x01, 0x44, 0x01, 0xC1, 0x73, 0xC0, 0x89]; + let nals = collect_nal_units(&stream).expect("collect"); + assert_eq!(nals.len(), 1); + let pps_nal = &nals[0]; + assert_eq!(pps_nal.header.nal_unit_type, 34); + // `NalUnit::rbsp` already excludes the two header bytes and has + // emulation-prevention stripped. + let pps = PicParameterSet::parse(&pps_nal.rbsp).expect("PPS parse via walker"); + assert_eq!(pps.pps_id, 0); + assert_eq!(pps.sps_id, 0); + assert_eq!(pps.init_qp(), 26); + assert!(pps.cu_qp_delta_enabled_flag); + } + + /// Hand-assembled PPS exercising the tiles block with explicit + /// (non-uniform) column/row spacing and the deblocking-control + /// block with non-zero β / tC offsets. + #[test] + fn parses_tiles_and_deblocking_blocks() { + // Build the RBSP bit-by-bit as a string, then pack MSB-first. + let mut bits = String::new(); + // pps_pic_parameter_set_id = 0 → ue '1' + bits += "1"; + // pps_seq_parameter_set_id = 0 → ue '1' + bits += "1"; + // dependent_slice_segments_enabled_flag = 0 + bits += "0"; + // output_flag_present_flag = 0 + bits += "0"; + // num_extra_slice_header_bits = 0 → u(3) + bits += "000"; + // sign_data_hiding_enabled_flag = 0 + bits += "0"; + // cabac_init_present_flag = 0 + bits += "0"; + // num_ref_idx_l0_default_active_minus1 = 0 → ue '1' + bits += "1"; + // num_ref_idx_l1_default_active_minus1 = 0 → ue '1' + bits += "1"; + // init_qp_minus26 = 0 → se '1' + bits += "1"; + // constrained_intra_pred_flag = 0 + bits += "0"; + // transform_skip_enabled_flag = 0 + bits += "0"; + // cu_qp_delta_enabled_flag = 0 + bits += "0"; + // pps_cb_qp_offset = 0 → se '1' + bits += "1"; + // pps_cr_qp_offset = 0 → se '1' + bits += "1"; + // pps_slice_chroma_qp_offsets_present_flag = 0 + bits += "0"; + // weighted_pred_flag = 0 + bits += "0"; + // weighted_bipred_flag = 0 + bits += "0"; + // transquant_bypass_enabled_flag = 0 + bits += "0"; + // tiles_enabled_flag = 1 + bits += "1"; + // entropy_coding_sync_enabled_flag = 0 + bits += "0"; + // tiles block: + // num_tile_columns_minus1 = 1 → ue codeNum 1 = '010' + bits += "010"; + // num_tile_rows_minus1 = 1 → ue '010' + bits += "010"; + // uniform_spacing_flag = 0 + bits += "0"; + // column_width_minus1[0] = 2 → ue codeNum 2 = '011' + bits += "011"; + // row_height_minus1[0] = 3 → ue codeNum 3 = '00100' + bits += "00100"; + // loop_filter_across_tiles_enabled_flag = 0 + bits += "0"; + // pps_loop_filter_across_slices_enabled_flag = 1 + bits += "1"; + // deblocking_filter_control_present_flag = 1 + bits += "1"; + // deblocking_filter_override_enabled_flag = 1 + bits += "1"; + // pps_deblocking_filter_disabled_flag = 0 + bits += "0"; + // pps_beta_offset_div2 = -2 → se codeNum 4 = '00101' + bits += "00101"; + // pps_tc_offset_div2 = 3 → se codeNum 5 = '00110' + bits += "00110"; + // pps_scaling_list_data_present_flag = 0 + bits += "0"; + // lists_modification_present_flag = 0 + bits += "0"; + // log2_parallel_merge_level_minus2 = 0 → ue '1' + bits += "1"; + // slice_segment_header_extension_present_flag = 0 + bits += "0"; + // pps_extension_present_flag = 0 + bits += "0"; + // rbsp_trailing_bits(): stop bit '1' then zero-pad to a byte. + bits += "1"; + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + + let pps = PicParameterSet::parse(&rbsp).expect("tiles/deblock PPS parse"); + assert!(pps.tiles_enabled_flag); + assert_eq!(pps.tiles.num_tile_columns_minus1, 1); + assert_eq!(pps.tiles.num_tile_rows_minus1, 1); + assert_eq!(pps.num_tile_columns(), 2); + assert_eq!(pps.num_tile_rows(), 2); + assert!(!pps.tiles.uniform_spacing_flag); + assert_eq!(pps.tiles.column_width_minus1, vec![2]); + assert_eq!(pps.tiles.row_height_minus1, vec![3]); + assert!(!pps.loop_filter_across_tiles_enabled_flag); + assert!(pps.pps_loop_filter_across_slices_enabled_flag); + assert!(pps.deblocking_filter_control_present_flag); + assert!(pps.deblocking.override_enabled_flag); + assert!(!pps.deblocking.disabled_flag); + assert_eq!(pps.deblocking.beta_offset_div2, -2); + assert_eq!(pps.deblocking.tc_offset_div2, 3); + } + + /// `pps_extension_present_flag == 1` with every typed extension + /// flag (and `pps_extension_4bits`) equal to 0 decodes the + /// flag block but consumes only `rbsp_trailing_bits()` afterwards + /// — no opaque tail is surfaced because no extension body + /// follows. + #[test] + fn decodes_extension_flag_block_without_bodies() { + let mut bits = minimal_pps_prefix_bits(); + // pps_extension_present_flag = 1 + bits += "1"; + bits += "0000"; // pps_range/multilayer/3d/scc flags = 0 + bits += "0000"; // pps_extension_4bits = 0 + bits += "1"; // rbsp stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("ext PPS parse"); + assert!(pps.pps_extension_present_flag); + let flags = pps.extension_flags.expect("extension flag block"); + assert!(!flags.pps_range_extension_flag); + assert!(!flags.pps_multilayer_extension_flag); + assert!(!flags.pps_3d_extension_flag); + assert!(!flags.pps_scc_extension_flag); + assert_eq!(flags.pps_extension_4bits, 0); + assert!(!flags.has_body()); + // No extension body follows → no opaque tail. + assert!(pps.opaque_tail.is_none()); + } + + /// `pps_extension_present_flag == 1` with + /// `pps_range_extension_flag == 1` decodes the flag block then the + /// `pps_range_extension()` body (§7.3.2.3.2). The prefix has + /// `transform_skip_enabled_flag == 0`, so the body opens directly + /// with `cross_component_prediction_enabled_flag`. With no body + /// after the range extension, no opaque tail is captured. + #[test] + fn decodes_pps_range_extension_body() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "1"; // pps_range_extension_flag = 1 + bits += "000"; // pps_multilayer/3d/scc = 0 + bits += "0000"; // pps_extension_4bits = 0 + // pps_range_extension() body (transform_skip off): + bits += "1"; // cross_component_prediction_enabled_flag = 1 + bits += "0"; // chroma_qp_offset_list_enabled_flag = 0 + bits += "010"; // log2_sao_offset_scale_luma = 1 (ue) + bits += "1"; // log2_sao_offset_scale_chroma = 0 (ue) + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("range-ext PPS parse"); + assert!(pps.pps_extension_present_flag); + let flags = pps.extension_flags.expect("extension flag block"); + assert!(flags.pps_range_extension_flag); + assert!(flags.has_body()); + // No body after the range extension → no opaque tail. + assert!(pps.opaque_tail.is_none()); + let re = pps.pps_range_extension.expect("range extension body"); + assert_eq!(re.log2_max_transform_skip_block_size_minus2, 0); + assert!(re.cross_component_prediction_enabled_flag); + assert!(!re.chroma_qp_offset_list_enabled_flag); + assert!(re.chroma_qp_offset_list.is_empty()); + assert_eq!(re.log2_sao_offset_scale_luma, 1); + assert_eq!(re.log2_sao_offset_scale_chroma, 0); + } + + /// `pps_range_extension()` with `chroma_qp_offset_list_enabled_flag + /// == 1` decodes the `diff_cu_chroma_qp_offset_depth`, + /// `chroma_qp_offset_list_len_minus1`, and the `cb/cr_qp_offset_list` + /// se(v) pairs (§7.3.2.3.2). + #[test] + fn decodes_pps_range_extension_chroma_qp_offset_list() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "1"; // pps_range_extension_flag = 1 + bits += "0000000"; // multilayer/3d/scc + 4bits = 0 + // pps_range_extension() body (transform_skip off): + bits += "0"; // cross_component_prediction_enabled_flag = 0 + bits += "1"; // chroma_qp_offset_list_enabled_flag = 1 + bits += "1"; // diff_cu_chroma_qp_offset_depth = 0 (ue) + bits += "010"; // chroma_qp_offset_list_len_minus1 = 1 (ue) → 2 entries + // entry 0: cb=+1 (se '010'), cr=-1 (se '011') + bits += "010"; + bits += "011"; + // entry 1: cb=+2 (se '00100'), cr=0 (se '1') + bits += "00100"; + bits += "1"; + bits += "1"; // log2_sao_offset_scale_luma = 0 (ue) + bits += "1"; // log2_sao_offset_scale_chroma = 0 (ue) + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("range-ext PPS parse"); + let re = pps.pps_range_extension.expect("range extension body"); + assert!(re.chroma_qp_offset_list_enabled_flag); + assert_eq!(re.diff_cu_chroma_qp_offset_depth, 0); + assert_eq!(re.chroma_qp_offset_list_len_minus1, 1); + assert_eq!(re.chroma_qp_offset_list.len(), 2); + assert_eq!(re.chroma_qp_offset_list[0].cb_qp_offset, 1); + assert_eq!(re.chroma_qp_offset_list[0].cr_qp_offset, -1); + assert_eq!(re.chroma_qp_offset_list[1].cb_qp_offset, 2); + assert_eq!(re.chroma_qp_offset_list[1].cr_qp_offset, 0); + } + + /// `pps_scc_extension()` (§7.3.2.3.3) with no preceding + /// range/multilayer/3D body: the body is decoded in place with no + /// opaque tail. Adaptive colour transform off, palette initializers + /// absent — only the leading flag and the two trailing flags. + #[test] + fn decodes_pps_scc_extension_minimal() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0"; // pps_range_extension_flag = 0 + bits += "0"; // pps_multilayer_extension_flag = 0 + bits += "0"; // pps_3d_extension_flag = 0 + bits += "1"; // pps_scc_extension_flag = 1 + bits += "0000"; // pps_extension_4bits = 0 + // pps_scc_extension(): + bits += "1"; // pps_curr_pic_ref_enabled_flag = 1 + bits += "0"; // residual_adaptive_colour_transform_enabled_flag = 0 + bits += "0"; // pps_palette_predictor_initializers_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("scc PPS parse"); + let flags = pps.extension_flags.expect("extension flag block"); + assert!(flags.pps_scc_extension_flag); + assert!(pps.opaque_tail.is_none()); + let scc = pps.pps_scc_extension.expect("scc extension body"); + assert!(scc.pps_curr_pic_ref_enabled_flag); + assert!(!scc.residual_adaptive_colour_transform_enabled_flag); + assert!(!scc.pps_palette_predictor_initializers_present_flag); + assert!(scc.pps_palette_predictor_initializer.is_empty()); + } + + /// `pps_scc_extension()` with + /// `residual_adaptive_colour_transform_enabled_flag == 1` decodes the + /// `pps_slice_act_qp_offsets_present_flag` and the three + /// `pps_act_*_qp_offset_*` se(v) fields (§7.3.2.3.3). + #[test] + fn decodes_pps_scc_extension_act_offsets() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0001"; // range/multilayer/3d = 0, scc = 1 + bits += "0000"; // pps_extension_4bits = 0 + // pps_scc_extension(): + bits += "0"; // pps_curr_pic_ref_enabled_flag = 0 + bits += "1"; // residual_adaptive_colour_transform_enabled_flag = 1 + bits += "1"; // pps_slice_act_qp_offsets_present_flag = 1 + bits += "010"; // pps_act_y_qp_offset_plus5 = +1 (se '010') + bits += "011"; // pps_act_cb_qp_offset_plus5 = -1 (se '011') + bits += "00100"; // pps_act_cr_qp_offset_plus3 = +2 (se '00100') + bits += "0"; // pps_palette_predictor_initializers_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("scc PPS parse"); + assert!(pps.opaque_tail.is_none()); + let scc = pps.pps_scc_extension.expect("scc extension body"); + assert!(!scc.pps_curr_pic_ref_enabled_flag); + assert!(scc.residual_adaptive_colour_transform_enabled_flag); + assert!(scc.pps_slice_act_qp_offsets_present_flag); + assert_eq!(scc.pps_act_y_qp_offset_plus5, 1); + assert_eq!(scc.pps_act_cb_qp_offset_plus5, -1); + assert_eq!(scc.pps_act_cr_qp_offset_plus3, 2); + // PpsActQpOffset{Y,Cb,Cr} = plus5−5 / plus5−5 / plus3−3. + assert_eq!(scc.pps_act_qp_offset_y(), -4); + assert_eq!(scc.pps_act_qp_offset_cb(), -6); + assert_eq!(scc.pps_act_qp_offset_cr(), -1); + } + + /// §7.4.3.3.3: a `PpsActQpOffsetY` (here from a large + /// `pps_act_y_qp_offset_plus5`) outside −12..=12 violates bitstream + /// conformance and is rejected. + #[test] + fn rejects_out_of_range_pps_act_qp_offset() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0001"; // range/multilayer/3d = 0, scc = 1 + bits += "0000"; // pps_extension_4bits = 0 + // pps_scc_extension(): + bits += "0"; // pps_curr_pic_ref_enabled_flag = 0 + bits += "1"; // residual_adaptive_colour_transform_enabled_flag = 1 + bits += "0"; // pps_slice_act_qp_offsets_present_flag = 0 + // pps_act_y_qp_offset_plus5 = +30 (se → codeNum 59, + // ue '00000111100') → PpsActQpOffsetY = 25 > 12, + // illegal + bits += "00000111100"; + bits += "1"; // pps_act_cb_qp_offset_plus5 = 0 (se) + bits += "1"; // pps_act_cr_qp_offset_plus3 = 0 (se) + bits += "0"; // pps_palette_predictor_initializers_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let err = PicParameterSet::parse(&rbsp).expect_err("act qp out of range"); + assert!(matches!( + err, + PpsError::ValueOutOfRange { + field: "pps_act_y_qp_offset_plus5", + got: 25 + } + )); + } + + /// `pps_scc_extension()` with palette predictor initializers + /// present: the per-component `pps_palette_predictor_initializer` + /// table is sized `u(v)` from this body's own + /// `luma_bit_depth_entry_minus8` / `chroma_bit_depth_entry_minus8`. + /// `monochrome_palette_flag == 0` → `numComps == 3`. + #[test] + fn decodes_pps_scc_extension_palette_initializers() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0001"; // range/multilayer/3d = 0, scc = 1 + bits += "0000"; // pps_extension_4bits = 0 + // pps_scc_extension(): + bits += "0"; // pps_curr_pic_ref_enabled_flag = 0 + bits += "0"; // residual_adaptive_colour_transform_enabled_flag = 0 + bits += "1"; // pps_palette_predictor_initializers_present_flag = 1 + bits += "011"; // pps_num_palette_predictor_initializers = 2 (ue) + bits += "0"; // monochrome_palette_flag = 0 → numComps = 3 + bits += "1"; // luma_bit_depth_entry_minus8 = 0 (ue) → 8-bit luma + bits += "1"; // chroma_bit_depth_entry_minus8 = 0 (ue) → 8-bit chroma + // comp 0 (8-bit): 0x0A, 0x0B + bits += "00001010"; + bits += "00001011"; + // comp 1 (8-bit): 0x0C, 0x0D + bits += "00001100"; + bits += "00001101"; + // comp 2 (8-bit): 0x0E, 0x0F + bits += "00001110"; + bits += "00001111"; + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("scc PPS parse"); + assert!(pps.opaque_tail.is_none()); + let scc = pps.pps_scc_extension.expect("scc extension body"); + assert!(scc.pps_palette_predictor_initializers_present_flag); + assert_eq!(scc.pps_num_palette_predictor_initializers, 2); + assert!(!scc.monochrome_palette_flag); + assert_eq!(scc.luma_bit_depth_entry_minus8, 0); + assert_eq!(scc.chroma_bit_depth_entry_minus8, 0); + assert_eq!( + scc.pps_palette_predictor_initializer, + vec![vec![0x0A, 0x0B], vec![0x0C, 0x0D], vec![0x0E, 0x0F]], + ); + } + + /// `pps_range_extension_flag == 1` followed by + /// `pps_scc_extension_flag == 1` (no multilayer/3D between): both + /// bodies are decoded in place per the §7.3.2.3.1 body order, with + /// no opaque tail. + #[test] + fn decodes_pps_range_then_scc_body() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "1"; // pps_range_extension_flag = 1 + bits += "00"; // pps_multilayer/3d = 0 + bits += "1"; // pps_scc_extension_flag = 1 + bits += "0000"; // pps_extension_4bits = 0 + // pps_range_extension() body (transform_skip off): + bits += "0"; // cross_component_prediction_enabled_flag = 0 + bits += "0"; // chroma_qp_offset_list_enabled_flag = 0 + bits += "1"; // log2_sao_offset_scale_luma = 0 (ue) + bits += "1"; // log2_sao_offset_scale_chroma = 0 (ue) + // pps_scc_extension(): + bits += "1"; // pps_curr_pic_ref_enabled_flag = 1 + bits += "0"; // residual_adaptive_colour_transform_enabled_flag = 0 + bits += "0"; // pps_palette_predictor_initializers_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("range+scc PPS parse"); + assert!(pps.opaque_tail.is_none()); + let re = pps.pps_range_extension.expect("range extension body"); + assert_eq!(re, PpsRangeExtension::default()); + let scc = pps.pps_scc_extension.expect("scc extension body"); + assert!(scc.pps_curr_pic_ref_enabled_flag); + } + + /// When a `pps_multilayer_extension()` body precedes the SCC body, + /// the SCC body cannot be decoded in place; the whole span stays in + /// the opaque tail. + #[test] + fn pps_scc_stays_opaque_behind_multilayer_body() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0"; // pps_range_extension_flag = 0 + bits += "1"; // pps_multilayer_extension_flag = 1 + bits += "0"; // pps_3d_extension_flag = 0 + bits += "1"; // pps_scc_extension_flag = 1 + bits += "0000"; // pps_extension_4bits = 0 + bits += "11001100"; // opaque multilayer + scc span sentinel + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("multilayer PPS parse"); + let flags = pps.extension_flags.expect("extension flag block"); + assert!(flags.pps_multilayer_extension_flag); + assert!(flags.pps_scc_extension_flag); + assert!(pps.pps_scc_extension.is_none()); + assert!(pps.opaque_tail.is_some()); + } + + /// `chroma_qp_offset_list_len_minus1` above its §7.4.3.3.2 cap of 5 + /// is rejected. + #[test] + fn rejects_oversized_chroma_qp_offset_list_len() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "1"; // pps_range_extension_flag = 1 + bits += "0000000"; // multilayer/3d/scc + 4bits = 0 + bits += "0"; // cross_component_prediction_enabled_flag = 0 + bits += "1"; // chroma_qp_offset_list_enabled_flag = 1 + bits += "1"; // diff_cu_chroma_qp_offset_depth = 0 (ue) + bits += "00111"; // chroma_qp_offset_list_len_minus1 = 6 (ue) → > 5 + bits += "1"; // padding to keep a well-formed buffer + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let err = PicParameterSet::parse(&rbsp).expect_err("len out of range"); + assert!(matches!( + err, + PpsError::ValueOutOfRange { + field: "chroma_qp_offset_list_len_minus1", + got: 6 + } + )); + } + + /// `pps_extension_present_flag == 1` with the four typed + /// extension flags all 0 but `pps_extension_4bits != 0` still + /// surfaces an opaque tail — the §7.3.2.3.1 + /// `while( more_rbsp_data() ) pps_extension_data_flag` block is + /// gated by `pps_extension_4bits` (the §7.4.3.3.1 decoder rule is + /// to ignore the data flags but they must be skipped past + /// rbsp_trailing_bits, so the bytes are surfaced as opaque). + #[test] + fn captures_extension_data_flag_tail_when_4bits_nonzero() { + let mut bits = minimal_pps_prefix_bits(); + bits += "1"; // pps_extension_present_flag = 1 + bits += "0000"; // pps_range/multilayer/3d/scc = 0 + bits += "0001"; // pps_extension_4bits = 1 (reserved, non-zero) + bits += "0"; // a single pps_extension_data_flag value + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("ext-4bits PPS parse"); + let flags = pps.extension_flags.expect("extension flag block"); + assert_eq!(flags.pps_extension_4bits, 1); + assert!(flags.has_body()); + assert!(pps.opaque_tail.is_some()); + } + + /// When `pps_extension_present_flag == 0` the typed + /// extension-flag block is absent and every flag is inferred to + /// 0 per §7.4.3.3.1. + #[test] + fn extension_flags_absent_when_gate_zero() { + let mut bits = minimal_pps_prefix_bits(); + bits += "0"; // pps_extension_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("no-ext PPS parse"); + assert!(!pps.pps_extension_present_flag); + assert!(pps.extension_flags.is_none()); + assert!(pps.opaque_tail.is_none()); + } + + /// `pps_scaling_list_data_present_flag == 1` parses an explicit + /// `scaling_list_data()` (§7.3.4). Here every one of the 24 slots + /// signals pred_mode=0, delta=0 (use the §7.4.5 default list), so + /// the parsed lists equal the default tables and the PPS continues + /// through the rest of the body. + #[test] + fn parses_scaling_list_present() { + let mut bits = minimal_pps_prefix_bits_until_scaling_list(); + bits += "1"; // pps_scaling_list_data_present_flag = 1 + // scaling_list_data(): 24 slots, each '0' (pred_mode + // = 0) + '1' (scaling_list_pred_matrix_id_delta ue + // = 0). sizeId 0/1/2 each 6 slots; sizeId 3 only 2. + for size_id in 0..4 { + let step = if size_id == 3 { 3 } else { 1 }; + let mut m = 0; + while m < 6 { + bits += "0"; + bits += "1"; + m += step; + } + } + // Remainder of the PPS body. + bits += "0"; // lists_modification_present_flag + bits += "1"; // log2_parallel_merge_level_minus2 ue = 0 + bits += "0"; // slice_segment_header_extension_present_flag + bits += "0"; // pps_extension_present_flag + bits += "1"; // rbsp stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("scaling-list PPS parse"); + assert!(pps.pps_scaling_list_data_present_flag); + let data = pps.scaling_list_data.expect("scaling_list_data present"); + assert_eq!(data.lists[0][0].coef, vec![16u16; 16]); + assert_eq!(data.lists[1][0].coef[63], 115); // 8x8 intra default tail + } + + /// `pps_pic_parameter_set_id` out of range (> 63) is rejected. + #[test] + fn rejects_pps_id_out_of_range() { + // ue codeNum 64 = leadingZeroBits 6, suffix = 64+1-(2^6-1)=1 → + // '0000001000001'. codeNum = 2^6 - 1 + 1 = 64 (> 63). + let mut bits = String::from("0000001000001"); + bits += "1"; // pad to ensure non-empty buffer for any further read + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + assert_eq!( + PicParameterSet::parse(&rbsp), + Err(PpsError::ValueOutOfRange { + field: "pps_pic_parameter_set_id", + got: 64, + }) + ); + } + + /// A truncated PPS RBSP surfaces `Truncated`. + #[test] + fn rejects_truncated() { + // Just the first two ue() ids then end-of-buffer mid-flag-block. + let rbsp = [0xC0]; // pps_id=0 ('1'), sps_id=0 ('1'), then '000000' + let err = PicParameterSet::parse(&rbsp).unwrap_err(); + assert_eq!(err, PpsError::Truncated); + } + + #[test] + fn init_qp_range_check_uses_sps_bit_depth() { + // init_qp_minus26 = -70 is within the loosest -74 bound the + // parser accepts but only legal for high bit depths (where + // QpBdOffsetY is large enough). Build a complete PPS carrying + // -70 and exercise the SPS-aware range helper on the result. + let mut bits = String::new(); + bits += "1"; // pps_id = 0 + bits += "1"; // sps_id = 0 + bits += "0"; // dependent_slice_segments_enabled_flag + bits += "0"; // output_flag_present_flag + bits += "000"; // num_extra_slice_header_bits + bits += "0"; // sign_data_hiding_enabled_flag + bits += "0"; // cabac_init_present_flag + bits += "1"; // num_ref_idx_l0_default_active_minus1 = 0 + bits += "1"; // num_ref_idx_l1_default_active_minus1 = 0 + // init_qp_minus26 = -70 → se value -70: codeNum = 2*70 = 140. + // ue(140): leadingZeroBits = 7, suffix = 140+1-128 = 13. + bits += "0000000"; // 7 leading zeros + bits += "1"; // terminator + bits += "0001101"; // 7-bit suffix = 13 → codeNum = 127 + 13 = 140 + bits += "0"; // constrained_intra_pred_flag + bits += "0"; // transform_skip_enabled_flag + bits += "0"; // cu_qp_delta_enabled_flag = 0 + bits += "1"; // pps_cb_qp_offset = 0 (se '1') + bits += "1"; // pps_cr_qp_offset = 0 (se '1') + bits += "0"; // pps_slice_chroma_qp_offsets_present_flag + bits += "0"; // weighted_pred_flag + bits += "0"; // weighted_bipred_flag + bits += "0"; // transquant_bypass_enabled_flag + bits += "0"; // tiles_enabled_flag = 0 + bits += "0"; // entropy_coding_sync_enabled_flag + bits += "1"; // pps_loop_filter_across_slices_enabled_flag + bits += "0"; // deblocking_filter_control_present_flag = 0 + bits += "0"; // pps_scaling_list_data_present_flag = 0 + bits += "0"; // lists_modification_present_flag + bits += "1"; // log2_parallel_merge_level_minus2 = 0 (ue '1') + bits += "0"; // slice_segment_header_extension_present_flag + bits += "0"; // pps_extension_present_flag = 0 + bits += "1"; // rbsp_trailing_bits stop bit + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let pps = PicParameterSet::parse(&rbsp).expect("low-init-qp PPS parse"); + assert_eq!(pps.init_qp_minus26, -70); + assert_eq!(pps.init_qp(), -44); + // 8-bit (minus8=0): QpBdOffsetY=0, lower bound -26 → out of range. + assert!(!pps.init_qp_in_range(0)); + // 12-bit (minus8=4): QpBdOffsetY=24, lower bound -50 → out. + assert!(!pps.init_qp_in_range(4)); + // 16-bit (minus8=8): QpBdOffsetY=48, lower bound -74 → in range. + assert!(pps.init_qp_in_range(8)); + } + + /// Fuzz regression (r282 hardening): §A.4.1 item f) bounds the + /// tile grid (`num_tile_columns_minus1 < MaxTileCols`, at most 40 + /// per Table A.8). An unbounded `ue(v)` count previously drove the + /// explicit column-width array pre-allocation directly off the + /// wire value. + #[test] + fn rejects_oversized_tile_column_count() { + let mut bits = minimal_pps_prefix_bits_until_scaling_list(); + // The helper's last four bits are `tiles_enabled_flag = 0`, + // `entropy_coding_sync = 0`, `loop_filter_across_slices = 1`, + // `deblocking_filter_control_present = 0` — rewrite the tail + // with tiles enabled and an out-of-range column count (the + // parse rejects before reading anything further). + bits.truncate(bits.len() - 4); + bits += "1"; // tiles_enabled_flag = 1 + bits += "0"; // entropy_coding_sync_enabled_flag = 0 + bits += "00000101001"; // num_tile_columns_minus1 ue = 40 + bits += "1"; // num_tile_rows_minus1 = 0 + while bits.len() % 8 != 0 { + bits += "0"; + } + let rbsp = pack_bits(&bits); + let err = PicParameterSet::parse(&rbsp).unwrap_err(); + assert_eq!( + err, + PpsError::ValueOutOfRange { + field: "num_tile_columns_minus1", + got: 40 + } + ); + } + + // --- test helpers -------------------------------------------------- + + /// Pack an MSB-first bit string (must be a whole number of bytes) + /// into a byte vector. + fn pack_bits(bits: &str) -> Vec { + assert_eq!(bits.len() % 8, 0, "bit string must be byte-aligned"); + bits.as_bytes() + .chunks(8) + .map(|chunk| chunk.iter().fold(0u8, |acc, &b| (acc << 1) | (b - b'0'))) + .collect() + } + + /// Minimal PPS prefix bits up to (but not including) + /// `pps_extension_present_flag`, with every field set to the + /// simplest legal value (no tiles, no deblocking control, no + /// scaling list). The caller appends the extension flag + tail. + fn minimal_pps_prefix_bits() -> String { + let mut bits = minimal_pps_prefix_bits_until_scaling_list(); + // pps_scaling_list_data_present_flag = 0 + bits += "0"; + // lists_modification_present_flag = 0 + bits += "0"; + // log2_parallel_merge_level_minus2 = 0 → ue '1' + bits += "1"; + // slice_segment_header_extension_present_flag = 0 + bits += "0"; + bits + } + + /// Minimal PPS prefix bits up to (but not including) + /// `pps_scaling_list_data_present_flag`. + fn minimal_pps_prefix_bits_until_scaling_list() -> String { + let mut bits = String::new(); + bits += "1"; // pps_id = 0 + bits += "1"; // sps_id = 0 + bits += "0"; // dependent_slice_segments_enabled_flag + bits += "0"; // output_flag_present_flag + bits += "000"; // num_extra_slice_header_bits + bits += "0"; // sign_data_hiding_enabled_flag + bits += "0"; // cabac_init_present_flag + bits += "1"; // num_ref_idx_l0_default_active_minus1 = 0 + bits += "1"; // num_ref_idx_l1_default_active_minus1 = 0 + bits += "1"; // init_qp_minus26 = 0 (se '1') + bits += "0"; // constrained_intra_pred_flag + bits += "0"; // transform_skip_enabled_flag + bits += "0"; // cu_qp_delta_enabled_flag = 0 (depth not signalled) + bits += "1"; // pps_cb_qp_offset = 0 (se '1') + bits += "1"; // pps_cr_qp_offset = 0 (se '1') + bits += "0"; // pps_slice_chroma_qp_offsets_present_flag + bits += "0"; // weighted_pred_flag + bits += "0"; // weighted_bipred_flag + bits += "0"; // transquant_bypass_enabled_flag + bits += "0"; // tiles_enabled_flag = 0 + bits += "0"; // entropy_coding_sync_enabled_flag + bits += "1"; // pps_loop_filter_across_slices_enabled_flag + bits += "0"; // deblocking_filter_control_present_flag = 0 + bits + } +} diff --git a/vendor/oxideav-h265/src/pu_mv.rs b/vendor/oxideav-h265/src/pu_mv.rs new file mode 100644 index 0000000..8c06e05 --- /dev/null +++ b/vendor/oxideav-h265/src/pu_mv.rs @@ -0,0 +1,1228 @@ +//! §8.5.3.1 / §8.5.3.2.1 — the per-PU motion-vector / reference-index +//! resolution driver. +//! +//! This module is the seam between the §7.3.8.6 `prediction_unit()` +//! syntax (parsed by [`crate::slice_data`] into a +//! [`crate::slice_data::PredictionUnit`]) and the resolved per-PU motion +//! data the §8.5.3.3 inter-sample-prediction path +//! ([`crate::recon::reconstruct_inter_pu`]) consumes. It runs the +//! §8.5.3.2.1 "Derivation process for motion vector components and +//! reference indices": it gathers the §8.5.3.2.3 spatial neighbours out +//! of the per-block [`MotionField`], dispatches the merge-mode +//! (§8.5.3.2.2) versus MVP (§8.5.3.2.6) candidate derivation that already +//! lives in [`crate::motion`], reconstructs each list's +//! `mvLX = mvpLX + mvdLX` (eqs 8-94..8-101), applies the §8.5.3.2.1 +//! `nPbSw == 8 && nPbSh == 8` bi→uni reduction (eqs 8-102/8-103), and +//! returns the fully-resolved [`PuMotion`] — which the caller then writes +//! back into the motion field (eqs 8-80..8-85) before reconstruction. +//! +//! The arithmetic sub-processes (spatial / temporal candidate lists, MVP +//! candidate, the MV wrap) stay in [`crate::motion`]; this module owns the +//! neighbour-location plumbing and the §8.5.3.2.1 ordered-step control +//! flow that ties them to the parsed PU syntax. + +use crate::binarization::InterPredIdc; +use crate::motion::{ + build_merge_candidate, derive_mvp_candidate, derive_spatial_merge_candidates, + derive_temporal_mv, reconstruct_mv, MergeCandidate, MergeListParams, MotionCell, MotionField, + Mv, MvpContext, NeighbourPu, PartitionContext, RefPicId, SpatialMergeNeighbours, + TemporalMvContext, +}; +use crate::slice_data::PredictionUnit; + +/// The §8.5.3.2.1 `PartMode` split class the `nPbSw` / `nPbSh` (eqs +/// 8-86/8-87) and the §8.5.3.2.3 partition-exclusion rules read. +/// +/// The values mirror the §7.4.9.5 `PartMode` enumeration but carry only +/// the geometry the MV-resolution driver needs (the §7.3.8.5 part-mode +/// binarization itself lives in [`crate::binarization`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PartMode { + /// `PART_2Nx2N` — one PU covering the whole CU. + Part2Nx2N, + /// `PART_2NxN` — top / bottom horizontal split. + Part2NxN, + /// `PART_Nx2N` — left / right vertical split. + PartNx2N, + /// `PART_NxN` — four quadrants. + PartNxN, + /// `PART_2NxnU` — asymmetric top (¼) / bottom (¾) horizontal split. + Part2NxnU, + /// `PART_2NxnD` — asymmetric top (¾) / bottom (¼) horizontal split. + Part2NxnD, + /// `PART_nLx2N` — asymmetric left (¼) / right (¾) vertical split. + PartNLx2N, + /// `PART_nRx2N` — asymmetric left (¾) / right (¼) vertical split. + PartNRx2N, +} + +impl PartMode { + /// `true` for the vertical-split modes (`PART_Nx2N`, `PART_nLx2N`, + /// `PART_nRx2N`) — the §8.5.3.2.3 modes that exclude `A1` for the + /// second partition. + #[must_use] + fn is_vertical_split(self) -> bool { + matches!(self, Self::PartNx2N | Self::PartNLx2N | Self::PartNRx2N) + } + + /// `true` for the horizontal-split modes (`PART_2NxN`, `PART_2NxnU`, + /// `PART_2NxnD`) — the §8.5.3.2.3 modes that exclude `B1` for the + /// second partition. + #[must_use] + fn is_horizontal_split(self) -> bool { + matches!(self, Self::Part2NxN | Self::Part2NxnU | Self::Part2NxnD) + } +} + +impl From for PartMode { + fn from(m: crate::binarization::PartMode) -> Self { + use crate::binarization::PartMode as B; + match m { + B::Part2Nx2N => Self::Part2Nx2N, + B::Part2NxN => Self::Part2NxN, + B::PartNx2N => Self::PartNx2N, + B::PartNxN => Self::PartNxN, + B::Part2NxnU => Self::Part2NxnU, + B::Part2NxnD => Self::Part2NxnD, + B::PartNLx2N => Self::PartNLx2N, + B::PartNRx2N => Self::PartNRx2N, + } + } +} + +/// §7.3.8.6 — the prediction-block partitioning of one inter coding unit: +/// the per-`partIdx` `(xPb, yPb, nPbW, nPbH)` rectangles for the CU's +/// `PartMode`, relative to the picture. +/// +/// `(x0, y0)` is the CU's luma top-left; `n_cb_s` is `nCbS`. The returned +/// vector has one entry per prediction unit in §7.3.8.6 invocation order +/// (so its index is `partIdx`). Mirrors the §7.3.8.6 +/// `prediction_unit( … )` argument expressions exactly (including the AMP +/// `nCbS/4` / `nCbS*3/4` splits). +#[must_use] +pub fn pu_partitions(x0: usize, y0: usize, n_cb_s: usize, part_mode: PartMode) -> Vec { + let n = n_cb_s; + let h = n / 2; + let q = n / 4; + let t = n * 3 / 4; + let rect = |x: usize, y: usize, w: usize, ht: usize| PuRect { + x_pb: x, + y_pb: y, + n_pb_w: w, + n_pb_h: ht, + }; + match part_mode { + PartMode::Part2Nx2N => vec![rect(x0, y0, n, n)], + PartMode::Part2NxN => vec![rect(x0, y0, n, h), rect(x0, y0 + h, n, h)], + PartMode::PartNx2N => vec![rect(x0, y0, h, n), rect(x0 + h, y0, h, n)], + PartMode::Part2NxnU => vec![rect(x0, y0, n, q), rect(x0, y0 + q, n, t)], + PartMode::Part2NxnD => vec![rect(x0, y0, n, t), rect(x0, y0 + t, n, q)], + PartMode::PartNLx2N => vec![rect(x0, y0, q, n), rect(x0 + q, y0, t, n)], + PartMode::PartNRx2N => vec![rect(x0, y0, t, n), rect(x0 + t, y0, q, n)], + PartMode::PartNxN => vec![ + rect(x0, y0, h, h), + rect(x0 + h, y0, h, h), + rect(x0, y0 + h, h, h), + rect(x0 + h, y0 + h, h, h), + ], + } +} + +/// One §7.3.8.6 prediction-block rectangle (luma coordinates / sizes). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PuRect { + /// `xPb` — luma top-left x. + pub x_pb: usize, + /// `yPb` — luma top-left y. + pub y_pb: usize, + /// `nPbW` — prediction-block width. + pub n_pb_w: usize, + /// `nPbH` — prediction-block height. + pub n_pb_h: usize, +} + +/// The fully-resolved §8.5.3.2.1 output for one prediction unit: the +/// per-list utilization flag, reference index and luma motion vector. +/// +/// This is the `(predFlagLX, refIdxLX, mvLX)` triple that drives both the +/// §8.5.3.3 inter sample prediction and the eqs 8-80..8-85 motion-field +/// store. A reference index of `−1` (with `pred_flag == false`) marks an +/// unused list. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PuMotion { + /// `predFlagL0`. + pub pred_flag_l0: bool, + /// `predFlagL1`. + pub pred_flag_l1: bool, + /// `refIdxL0` (`−1` when L0 unused). + pub ref_idx_l0: i32, + /// `refIdxL1` (`−1` when L1 unused). + pub ref_idx_l1: i32, + /// `mvL0` in quarter-luma-sample units. + pub mv_l0: Mv, + /// `mvL1` in quarter-luma-sample units. + pub mv_l1: Mv, +} + +impl PuMotion { + /// Convert the resolved motion into the §8.5.3 [`MotionCell`] the + /// per-block [`MotionField`] stores. `ref_poc_l0` / `ref_poc_l1` + /// resolve each used list's reference index to a reference-picture + /// POC (the §8.7.2.4 / §8.5.3.2.9 identity, not the list position). + #[must_use] + pub fn to_cell(self, ref_poc_l0: i32, ref_poc_l1: i32) -> MotionCell { + MotionCell { + is_intra: false, + has_nonzero_coeff: false, + pred_flag_l0: self.pred_flag_l0, + pred_flag_l1: self.pred_flag_l1, + ref_poc_l0: if self.pred_flag_l0 { + ref_poc_l0 + } else { + i32::MIN + }, + ref_poc_l1: if self.pred_flag_l1 { + ref_poc_l1 + } else { + i32::MIN + }, + mv_l0: if self.pred_flag_l0 { + self.mv_l0 + } else { + [0, 0] + }, + mv_l1: if self.pred_flag_l1 { + self.mv_l1 + } else { + [0, 0] + }, + } + } +} + +/// The reference-picture resolvers the §8.5.3.2 derivations need, plus the +/// current-picture / slice context that does not vary per PU. +/// +/// All POC / long-term / short-term lookups go through closures so this +/// driver stays independent of the [`crate::dpb`] reference-list layout: +/// the picture-level driver binds them to `RefPicListX[ refIdx ]`. +pub struct PuMvContext<'a> { + /// `PicOrderCntVal` of the current picture. + pub curr_poc: i32, + /// `true` for a B slice (enables L1 + the §8.5.3.2.4 combined step). + pub slice_is_b: bool, + /// `CtbLog2SizeY`. + pub ctb_log2_size_y: u32, + /// `pic_width_in_luma_samples` (the §8.5.3.2.8 bottom-right bound). + pub pic_width_luma: u32, + /// `pic_height_in_luma_samples`. + pub pic_height_luma: u32, + /// `MaxNumMergeCand` (§7.4.7.1). + pub max_num_merge_cand: usize, + /// `num_ref_idx_l0_active` (the active L0 size, not the minus1 form). + pub num_ref_idx_l0_active: i32, + /// `num_ref_idx_l1_active`. + pub num_ref_idx_l1_active: i32, + /// `Log2ParMrgLevel` (§7.4.3.3.1) — the parallel-merge-region size. + pub log2_par_mrg_level: u32, + /// `slice_temporal_mvp_enabled_flag` (the §8.5.3.2.8 gate). + pub temporal_mvp_enabled: bool, + /// `collocated_from_l0_flag` (the §8.5.3.2.9 collocated list selector). + pub collocated_from_l0_flag: bool, + /// `PicOrderCnt( ColPic )` — the collocated picture's POC (§8.5.3.2.9). + pub col_poc: i32, + /// `NoBackwardPredFlag` (§8.3.5) — the §8.5.3.2.9 list-selection gate. + pub no_backward_pred: bool, + /// Resolve `(list, ref_idx)` of the current PU's reference list to a + /// reference-picture POC. + pub ref_poc: &'a dyn Fn(usize, i32) -> i32, + /// Resolve `(list, ref_idx)` to whether the picture is long-term. + pub ref_long_term: &'a dyn Fn(usize, i32) -> bool, + /// Resolve `(list, ref_idx)` to whether the picture is short-term. + pub ref_short_term: &'a dyn Fn(usize, i32) -> bool, + /// The collocated picture's per-block motion field (§8.5.3.2.9), when + /// `slice_temporal_mvp_enabled_flag` and a `ColPic` was selected. + pub col_field: Option<&'a MotionField>, + /// Resolve the collocated picture's stored `refIdxCol` reference POC to + /// whether that reference is long-term (the §8.5.3.2.9 scaling gate). + pub col_ref_long_term: &'a dyn Fn(i32) -> bool, + /// `use_integer_mv_flag` (§7.4.7.1) — selects the eqs 8-98..8-101 / + /// 8-124..8-125 integer-resolution motion-vector path for every + /// reference. + pub use_integer_mv: bool, + /// `TwoVersionsOfCurrDecPicFlag` (§7.4.3.3.3, eq. 7-40) — gates the + /// §8.5.3.2.1 eqs 8-102/8-103 8×8 bi→uni reduction. + pub two_versions_curr_pic: bool, + /// Resolve `(list, ref_idx)` to whether `RefPicListX[ ref_idx ]` is + /// the CURRENT picture (§8.3.4 currPic — intra block copy). Its + /// motion vectors take the integer-resolution path regardless of + /// `use_integer_mv`. + pub is_curr_pic: &'a dyn Fn(usize, i32) -> bool, +} + +impl std::fmt::Debug for PuMvContext<'_> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PuMvContext") + .field("curr_poc", &self.curr_poc) + .field("slice_is_b", &self.slice_is_b) + .field("ctb_log2_size_y", &self.ctb_log2_size_y) + .field("max_num_merge_cand", &self.max_num_merge_cand) + .field("log2_par_mrg_level", &self.log2_par_mrg_level) + .field("temporal_mvp_enabled", &self.temporal_mvp_enabled) + .field("col_poc", &self.col_poc) + .field("no_backward_pred", &self.no_backward_pred) + .finish_non_exhaustive() + } +} + +/// The per-PU geometry the §8.5.3.2.1 driver needs: the CU + PU locations +/// and sizes plus the `PartMode` / `partIdx` split context. +#[derive(Debug, Clone, Copy)] +pub struct PuGeometry { + /// `(xCb, yCb)` — luma top-left of the coding block. + pub x_cb: usize, + /// `yCb`. + pub y_cb: usize, + /// `nCbS` — luma coding-block size. + pub n_cb_s: usize, + /// `(xPb, yPb)` — luma top-left of the prediction block. + pub x_pb: usize, + /// `yPb`. + pub y_pb: usize, + /// `nPbW` — prediction-block width. + pub n_pb_w: usize, + /// `nPbH` — prediction-block height. + pub n_pb_h: usize, + /// `PartMode` of the coding unit. + pub part_mode: PartMode, + /// `partIdx` of this PU within the CU. + pub part_idx: u32, +} + +/// A spatial neighbour location and whether the §6.4.2 prediction-block +/// availability test passed there. The driver reads the [`MotionField`] +/// cell at `(x, y)` when `available`. +#[derive(Debug, Clone, Copy)] +struct NeighbourLoc { + x: i32, + y: i32, + available: bool, +} + +/// Read the [`NeighbourPu`] motion for a spatial neighbour, mapping the +/// motion field's stored reference POCs back to the current PU's reference +/// indices (the §8.5.3.2.3 candidate copies the neighbour's `refIdxLX`, +/// which the field does not store directly). +/// +/// Returns `None` when the neighbour is §6.4.2-unavailable, off-picture, or +/// covered by an intra block (intra neighbours contribute no candidate). +fn neighbour_pu(field: &MotionField, loc: NeighbourLoc, ctx: &PuMvContext) -> Option { + if !loc.available || loc.x < 0 || loc.y < 0 { + return None; + } + let (x, y) = (loc.x as usize, loc.y as usize); + if x >= field.width_4() * 4 || y >= field.height_4() * 4 { + return None; + } + let cell = field.cell_at(x, y); + if cell.is_intra { + return None; + } + // Map the stored reference POC back to a refIdx in the current PU's + // reference list, scanning the active entries (the merge candidate + // carries the neighbour's refIdx, which must index *this* slice's + // RefPicListX since both slices share the same DPB). + let ref_idx_l0 = if cell.pred_flag_l0 { + poc_to_ref_idx(0, cell.ref_poc_l0, ctx.num_ref_idx_l0_active, ctx.ref_poc) + } else { + -1 + }; + let ref_idx_l1 = if cell.pred_flag_l1 { + poc_to_ref_idx(1, cell.ref_poc_l1, ctx.num_ref_idx_l1_active, ctx.ref_poc) + } else { + -1 + }; + Some(NeighbourPu { + pred_flag_l0: cell.pred_flag_l0 && ref_idx_l0 >= 0, + pred_flag_l1: cell.pred_flag_l1 && ref_idx_l1 >= 0, + ref_idx_l0, + ref_idx_l1, + mv_l0: cell.mv_l0, + mv_l1: cell.mv_l1, + }) +} + +/// Resolve a reference POC to a reference index in list `x` by scanning +/// the active entries; `−1` when no active entry matches. +fn poc_to_ref_idx(x: usize, poc: i32, active: i32, ref_poc: &dyn Fn(usize, i32) -> i32) -> i32 { + for r in 0..active { + if ref_poc(x, r) == poc { + return r; + } + } + -1 +} + +/// The five §8.5.3.2.3 neighbour locations (A1, B1, B0, A0, B2) for a PU +/// at `(xPb, yPb)` of size `(nPbW, nPbH)`, with the §6.4.2 availability +/// closure applied. +fn spatial_neighbours( + field: &MotionField, + geom: &PuGeometry, + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, +) -> SpatialMergeNeighbours { + let (x_pb, y_pb) = (geom.x_pb as i32, geom.y_pb as i32); + let (w, h) = (geom.n_pb_w as i32, geom.n_pb_h as i32); + let locs = [ + // A1 = (xPb − 1, yPb + nPbH − 1) + NeighbourLoc { + x: x_pb - 1, + y: y_pb + h - 1, + available: available(x_pb - 1, y_pb + h - 1), + }, + // B1 = (xPb + nPbW − 1, yPb − 1) + NeighbourLoc { + x: x_pb + w - 1, + y: y_pb - 1, + available: available(x_pb + w - 1, y_pb - 1), + }, + // B0 = (xPb + nPbW, yPb − 1) + NeighbourLoc { + x: x_pb + w, + y: y_pb - 1, + available: available(x_pb + w, y_pb - 1), + }, + // A0 = (xPb − 1, yPb + nPbH) + NeighbourLoc { + x: x_pb - 1, + y: y_pb + h, + available: available(x_pb - 1, y_pb + h), + }, + // B2 = (xPb − 1, yPb − 1) + NeighbourLoc { + x: x_pb - 1, + y: y_pb - 1, + available: available(x_pb - 1, y_pb - 1), + }, + ]; + SpatialMergeNeighbours { + a1: neighbour_pu(field, locs[0], ctx), + b1: neighbour_pu(field, locs[1], ctx), + b0: neighbour_pu(field, locs[2], ctx), + a0: neighbour_pu(field, locs[3], ctx), + b2: neighbour_pu(field, locs[4], ctx), + } +} + +/// The §8.5.3.2.3 parallel-merge-region (`Log2ParMrgLevel`) test for each +/// of the five neighbour positions — `true` when the neighbour shares the +/// current PB's parallel-merge region (`xPb >> L == xNb >> L && yPb >> L == +/// yNb >> L`), which forces it unavailable. +fn par_mrg_tests(geom: &PuGeometry, log2_par: u32) -> (bool, bool, bool, bool, bool) { + let (x_pb, y_pb) = (geom.x_pb as i32, geom.y_pb as i32); + let (w, h) = (geom.n_pb_w as i32, geom.n_pb_h as i32); + let same = |nx: i32, ny: i32| -> bool { + (x_pb >> log2_par) == (nx >> log2_par) && (y_pb >> log2_par) == (ny >> log2_par) + }; + ( + same(x_pb - 1, y_pb + h - 1), // A1 + same(x_pb + w - 1, y_pb - 1), // B1 + same(x_pb + w, y_pb - 1), // B0 + same(x_pb - 1, y_pb + h), // A0 + same(x_pb - 1, y_pb - 1), // B2 + ) +} + +/// §8.5.3.2.8 — derive the temporal merge candidate `Col` for one list as a +/// [`MergeCandidate`], or `None` when `availableFlagLXCol == 0`. +fn temporal_merge_candidate( + geom: &PuGeometry, + ctx: &PuMvContext, + is_b: bool, +) -> Option { + let col_field = ctx.col_field?; + if !ctx.temporal_mvp_enabled { + return None; + } + // refIdxLXCol = 0 (§8.5.3.2.2 step 2); the merge candidate's reference + // pictures are RefPicListX[ 0 ]. + let l0_col = temporal_mv_for_list(col_field, geom, ctx, 0); + let l1_col = if is_b { + temporal_mv_for_list(col_field, geom, ctx, 1) + } else { + None + }; + if l0_col.is_none() && l1_col.is_none() { + return None; + } + Some(MergeCandidate { + ref_idx_l0: if l0_col.is_some() { 0 } else { -1 }, + ref_idx_l1: if l1_col.is_some() { 0 } else { -1 }, + pred_flag_l0: l0_col.is_some(), + pred_flag_l1: l1_col.is_some(), + mv_l0: l0_col.unwrap_or([0, 0]), + mv_l1: l1_col.unwrap_or([0, 0]), + }) +} + +/// §8.5.3.2.8 — the temporal MV `mvLXCol` for one list with `refIdxCol == 0`. +fn temporal_mv_for_list( + col_field: &MotionField, + geom: &PuGeometry, + ctx: &PuMvContext, + x: usize, +) -> Option { + let curr_ref_poc = (ctx.ref_poc)(x, 0); + let curr_ref_short = (ctx.ref_short_term)(x, 0); + let tctx = TemporalMvContext { + ctb_log2_size_y: ctx.ctb_log2_size_y, + pic_width_luma: ctx.pic_width_luma, + pic_height_luma: ctx.pic_height_luma, + curr_poc: ctx.curr_poc, + col_poc: ctx.col_poc, + curr_ref_poc, + curr_ref_long_term: !curr_ref_short, + no_backward_pred: ctx.no_backward_pred, + collocated_from_l0_flag: ctx.collocated_from_l0_flag, + list_x: x, + col_ref_long_term: ctx.col_ref_long_term, + }; + derive_temporal_mv( + col_field, + geom.x_pb as u32, + geom.y_pb as u32, + geom.n_pb_w as u32, + geom.n_pb_h as u32, + &tctx, + ) +} + +/// §8.5.3.2.1 — resolve one prediction unit's motion vectors, reference +/// indices and prediction-list utilization flags. +/// +/// `field` is the *current* picture's motion field as built so far (the +/// spatial neighbours are read out of it); `geom` is the PU geometry; +/// `pu` is the parsed §7.3.8.6 syntax; `ctx` carries the reference-picture +/// resolvers and slice context; `available` is the §6.4.2 prediction-block +/// availability test (`(xNb, yNb) -> bool`). +/// +/// Returns the fully-resolved [`PuMotion`]; the caller writes it back into +/// the motion field (eqs 8-80..8-85) with [`PuMotion::to_cell`]. +#[must_use] +pub fn resolve_pu_motion( + field: &MotionField, + geom: &PuGeometry, + pu: &PredictionUnit, + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, +) -> PuMotion { + // §8.5.3.2.1: merge_flag selects the §8.5.3.2.2 merge branch. A skip CU + // (merge_flag inferred 1) carries only merge_idx and no AMVP motion; + // an explicit AMVP PU always signals at least one mvp_lX_flag. + if pu.merge_flag || !has_explicit_mv(pu) { + resolve_merge(field, geom, pu, ctx, available) + } else { + resolve_amvp(field, geom, pu, ctx, available) + } +} + +/// `true` when the PU carries explicit AMVP motion (an `mvp_lX_flag`), +/// i.e. it is not a merge / skip PU. +fn has_explicit_mv(pu: &PredictionUnit) -> bool { + pu.mvp_l0_flag.is_some() || pu.mvp_l1_flag.is_some() +} + +/// One inter coding unit's geometry for [`resolve_cu_motion`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct InterCuDesc { + /// `(x0, y0)` — luma top-left of the coding block. + pub x0: usize, + /// `y0`. + pub y0: usize, + /// `nCbS` — luma coding-block size. + pub n_cb_s: usize, + /// `PartMode` of the coding unit. + pub part_mode: PartMode, +} + +/// §7.3.8.6 + §8.5.3.2.1 — resolve every prediction unit of one inter +/// coding unit and write the per-PU motion into `field` (eqs 8-80..8-85). +/// +/// `cu` describes the CU; `pus` are the parsed prediction units in +/// §7.3.8.6 order (one per `partIdx`). Each PU is resolved against the +/// motion field *as updated by the earlier PUs of the same CU* (so the +/// second partition's A1/B1 neighbours see the first partition's motion, +/// modulo the §8.5.3.2.3 same-CU partition exclusion). +/// +/// Returns the resolved [`PuMotion`] for each PU (same order as `pus`), so +/// the caller can drive [`crate::recon::reconstruct_inter_pu`] per PU. +#[must_use] +pub fn resolve_cu_motion( + field: &mut MotionField, + cu: InterCuDesc, + pus: &[PredictionUnit], + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, +) -> Vec { + let InterCuDesc { + x0, + y0, + n_cb_s, + part_mode, + } = cu; + let rects = pu_partitions(x0, y0, n_cb_s, part_mode); + let mut out = Vec::with_capacity(pus.len()); + for (part_idx, (rect, pu)) in rects.iter().zip(pus.iter()).enumerate() { + let geom = PuGeometry { + x_cb: x0, + y_cb: y0, + n_cb_s, + x_pb: rect.x_pb, + y_pb: rect.y_pb, + n_pb_w: rect.n_pb_w, + n_pb_h: rect.n_pb_h, + part_mode, + part_idx: part_idx as u32, + }; + let motion = resolve_pu_motion(field, &geom, pu, ctx, available); + // eqs 8-80..8-85: store this PU's motion into the field for the + // later PUs / later CUs / deblocking / temporal-MV of future pics. + let ref_poc_l0 = if motion.pred_flag_l0 { + (ctx.ref_poc)(0, motion.ref_idx_l0) + } else { + i32::MIN + }; + let ref_poc_l1 = if motion.pred_flag_l1 { + (ctx.ref_poc)(1, motion.ref_idx_l1) + } else { + i32::MIN + }; + field.fill_rect( + rect.x_pb, + rect.y_pb, + rect.n_pb_w, + rect.n_pb_h, + motion.to_cell(ref_poc_l0, ref_poc_l1), + ); + out.push(motion); + } + out +} + +/// §8.5.3.2.2 — the merge-mode branch of §8.5.3.2.1. +fn resolve_merge( + field: &MotionField, + geom: &PuGeometry, + pu: &PredictionUnit, + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, +) -> PuMotion { + // §8.5.3.2.2 eqs 8-110..8-113: when Log2ParMrgLevel > 2 and nCbS == 8, + // all PUs of the CU share the 2Nx2N merge list (PU expands to the CU). + let merge_geom = if ctx.log2_par_mrg_level > 2 && geom.n_cb_s == 8 { + PuGeometry { + x_pb: geom.x_cb, + y_pb: geom.y_cb, + n_pb_w: geom.n_cb_s, + n_pb_h: geom.n_cb_s, + part_idx: 0, + part_mode: PartMode::Part2Nx2N, + ..*geom + } + } else { + *geom + }; + + let part = PartitionContext { + part_idx: merge_geom.part_idx, + part_mode_vertical_split: merge_geom.part_mode.is_vertical_split(), + part_mode_horizontal_split: merge_geom.part_mode.is_horizontal_split(), + }; + let neigh = spatial_neighbours(field, &merge_geom, ctx, available); + let par = par_mrg_tests(&merge_geom, ctx.log2_par_mrg_level); + let spatial = derive_spatial_merge_candidates(&neigh, part, par); + let col = temporal_merge_candidate(&merge_geom, ctx, ctx.slice_is_b); + + let zero_num_ref_idx = if ctx.slice_is_b { + ctx.num_ref_idx_l0_active.min(ctx.num_ref_idx_l1_active) + } else { + ctx.num_ref_idx_l0_active + }; + let params = MergeListParams { + slice_is_b: ctx.slice_is_b, + max_num_merge_cand: ctx.max_num_merge_cand, + zero_num_ref_idx, + }; + let merge_idx = pu.merge_idx.unwrap_or(0) as usize; + // The §8.5.3.2.4 combined-candidate distinctness test (eq 8-143) reads + // RefPicListX[ refIdx ] POC; the original PB size drives the eq 8-122 + // step-10 reduction. + let pb_w_plus_h = (geom.n_pb_w + geom.n_pb_h) as u32; + let ref_poc = ctx.ref_poc; + let chosen = build_merge_candidate(&spatial, col, params, merge_idx, pb_w_plus_h, ref_poc); + + // §8.5.3.2.1 step 9 (eqs 8-124/8-125): the merged motion vector is + // rounded to integer resolution when use_integer_mv_flag is 1 or + // the reference picture is the current picture. + let round = |mv: Mv| [(mv[0] >> 2) << 2, (mv[1] >> 2) << 2]; + let mv_l0 = + if chosen.pred_flag_l0 && (ctx.use_integer_mv || (ctx.is_curr_pic)(0, chosen.ref_idx_l0)) { + round(chosen.mv_l0) + } else { + chosen.mv_l0 + }; + let mv_l1 = + if chosen.pred_flag_l1 && (ctx.use_integer_mv || (ctx.is_curr_pic)(1, chosen.ref_idx_l1)) { + round(chosen.mv_l1) + } else { + chosen.mv_l1 + }; + + let mut out = PuMotion { + pred_flag_l0: chosen.pred_flag_l0, + pred_flag_l1: chosen.pred_flag_l1, + ref_idx_l0: chosen.ref_idx_l0, + ref_idx_l1: chosen.ref_idx_l1, + mv_l0, + mv_l1, + }; + apply_bi_to_uni_reduction(&mut out, geom, ctx); + out +} + +/// §8.5.3.2.1 steps 1–5 — the AMVP (non-merge) branch. +fn resolve_amvp( + field: &MotionField, + geom: &PuGeometry, + pu: &PredictionUnit, + ctx: &PuMvContext, + available: &dyn Fn(i32, i32) -> bool, +) -> PuMotion { + let idc = pu.inter_pred_idc.unwrap_or(InterPredIdc::PredL0); + let uses_l0 = matches!(idc, InterPredIdc::PredL0 | InterPredIdc::PredBi); + let uses_l1 = matches!(idc, InterPredIdc::PredL1 | InterPredIdc::PredBi); + + // The §8.5.3.2.7 A/B MVP derivation reads the raw §6.4.2-gated + // neighbours; the §8.5.3.2.3 merge redundancy / partition-exclusion + // and the parallel-merge-region test apply only to merge mode. + let neigh = spatial_neighbours(field, geom, ctx, available); + + let mut out = PuMotion { + ref_idx_l0: -1, + ref_idx_l1: -1, + ..PuMotion::default() + }; + + for (x, uses, ref_idx_field, mvd_field, mvp_flag_field) in [ + (0usize, uses_l0, pu.ref_idx_l0, pu.mvd_l0, pu.mvp_l0_flag), + (1usize, uses_l1, pu.ref_idx_l1, pu.mvd_l1, pu.mvp_l1_flag), + ] { + if !uses { + continue; + } + let ref_idx = ref_idx_field.unwrap_or(0) as i32; + let cur_ref_poc = (ctx.ref_poc)(x, ref_idx); + let cur_ref_long = (ctx.ref_long_term)(x, ref_idx); + let mvp_ctx = MvpContext { + x, + curr_poc: ctx.curr_poc, + cur_ref: RefPicId { + poc: cur_ref_poc, + long_term: cur_ref_long, + }, + neigh_ref_poc: ctx.ref_poc, + neigh_ref_long_term: ctx.ref_long_term, + neigh_ref_short_term: ctx.ref_short_term, + }; + let col = temporal_mvp(geom, ctx, x, ref_idx); + let mvp_flag = mvp_flag_field.unwrap_or(0) != 0; + let mvp = derive_mvp_candidate(&neigh, &mvp_ctx, col, mvp_flag); + let mvd = mvd_field + .map(|c| [c[0].value, c[1].value]) + .unwrap_or([0, 0]); + // The integer-MV path (eqs 8-98..8-101) applies when the + // reference picture is the current picture (intra block copy) + // or use_integer_mv_flag is 1. + let integer_mv = ctx.use_integer_mv || (ctx.is_curr_pic)(x, ref_idx); + let mv = reconstruct_mv(mvp, mvd, integer_mv); + match x { + 0 => { + out.pred_flag_l0 = true; + out.ref_idx_l0 = ref_idx; + out.mv_l0 = mv; + } + _ => { + out.pred_flag_l1 = true; + out.ref_idx_l1 = ref_idx; + out.mv_l1 = mv; + } + } + } + + apply_bi_to_uni_reduction(&mut out, geom, ctx); + out +} + +/// §8.5.3.2.8 — the temporal MVP `mvLXCol` for the AMVP branch (one list, +/// the PU's signalled `refIdxLX`). +fn temporal_mvp(geom: &PuGeometry, ctx: &PuMvContext, x: usize, ref_idx: i32) -> Option { + if !ctx.temporal_mvp_enabled { + return None; + } + let col_field = ctx.col_field?; + let curr_ref_poc = (ctx.ref_poc)(x, ref_idx); + let curr_ref_short = (ctx.ref_short_term)(x, ref_idx); + let tctx = TemporalMvContext { + ctb_log2_size_y: ctx.ctb_log2_size_y, + pic_width_luma: ctx.pic_width_luma, + pic_height_luma: ctx.pic_height_luma, + curr_poc: ctx.curr_poc, + col_poc: ctx.col_poc, + curr_ref_poc, + curr_ref_long_term: !curr_ref_short, + no_backward_pred: ctx.no_backward_pred, + collocated_from_l0_flag: ctx.collocated_from_l0_flag, + list_x: x, + col_ref_long_term: ctx.col_ref_long_term, + }; + derive_temporal_mv( + col_field, + geom.x_pb as u32, + geom.y_pb as u32, + geom.n_pb_w as u32, + geom.n_pb_h as u32, + &tctx, + ) +} + +/// §8.5.3.2.1 eqs 8-102/8-103 — the `nPbSw == 8 && nPbSh == 8` bi→uni-L0 +/// reduction (the SCC `TwoVersionsOfCurrDecPicFlag` clause): +/// +/// * `noIntegerMvFlag = !( ( mvL0 & 0x3 == 0 ) || ( mvL1 & 0x3 == 0 ) )` +/// (eq 8-102 — either vector being fully integer clears it); +/// * `identicalMvs = ( mvL0 == mvL1 ) && DiffPicOrderCnt( +/// RefPicList0[ refIdxL0 ], RefPicList1[ refIdxL1 ] ) == 0` +/// (eq 8-103); +/// * with both prediction flags set, an 8×8 prediction block, +/// `TwoVersionsOfCurrDecPicFlag == 1`, `noIntegerMvFlag == 1` and +/// `identicalMvs == 0`, list 1 is dropped. +fn apply_bi_to_uni_reduction(out: &mut PuMotion, geom: &PuGeometry, ctx: &PuMvContext) { + if !ctx.two_versions_curr_pic { + return; + } + // nPbSw / nPbSh (eqs 8-86/8-87). + let n_pb_sw = geom.n_cb_s + / if matches!(geom.part_mode, PartMode::Part2Nx2N | PartMode::Part2NxN) { + 1 + } else { + 2 + }; + let n_pb_sh = geom.n_cb_s + / if matches!(geom.part_mode, PartMode::Part2Nx2N | PartMode::PartNx2N) { + 1 + } else { + 2 + }; + let integer_mv = |mv: Mv| (mv[0] & 0x3) == 0 && (mv[1] & 0x3) == 0; + let no_integer_mv = !(integer_mv(out.mv_l0) || integer_mv(out.mv_l1)); + let identical_mvs = out.mv_l0 == out.mv_l1 + && (ctx.ref_poc)(0, out.ref_idx_l0) == (ctx.ref_poc)(1, out.ref_idx_l1); + if out.pred_flag_l0 + && out.pred_flag_l1 + && n_pb_sw == 8 + && n_pb_sh == 8 + && no_integer_mv + && !identical_mvs + { + out.pred_flag_l1 = false; + out.ref_idx_l1 = -1; + out.mv_l1 = [0, 0]; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::binarization::MvdComponent; + + fn intra_field(w: usize, h: usize) -> MotionField { + MotionField::new(w, h) + } + + fn inter_cell_l0(ref_poc: i32, mv: Mv) -> MotionCell { + MotionCell { + is_intra: false, + pred_flag_l0: true, + pred_flag_l1: false, + ref_poc_l0: ref_poc, + ref_poc_l1: i32::MIN, + mv_l0: mv, + ..MotionCell::default() + } + } + + fn base_ctx<'a>( + ref_poc: &'a dyn Fn(usize, i32) -> i32, + long: &'a dyn Fn(usize, i32) -> bool, + short: &'a dyn Fn(usize, i32) -> bool, + col_long: &'a dyn Fn(i32) -> bool, + ) -> PuMvContext<'a> { + PuMvContext { + curr_poc: 4, + slice_is_b: false, + ctb_log2_size_y: 6, + pic_width_luma: 64, + pic_height_luma: 64, + max_num_merge_cand: 5, + num_ref_idx_l0_active: 1, + num_ref_idx_l1_active: 1, + log2_par_mrg_level: 2, + temporal_mvp_enabled: false, + collocated_from_l0_flag: true, + col_poc: 0, + no_backward_pred: true, + ref_poc, + ref_long_term: long, + ref_short_term: short, + col_field: None, + col_ref_long_term: col_long, + use_integer_mv: false, + two_versions_curr_pic: false, + is_curr_pic: &|_, _| false, + } + } + + /// A merge / skip PU with no explicit AMVP motion. + fn merge_pu(merge_idx: u8) -> PredictionUnit { + PredictionUnit { + merge_flag: true, + merge_idx: Some(merge_idx), + inter_pred_idc: None, + ref_idx_l0: None, + mvd_l0: None, + mvp_l0_flag: None, + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + } + } + + fn geom_2nx2n(x: usize, y: usize, n: usize) -> PuGeometry { + PuGeometry { + x_cb: x, + y_cb: y, + n_cb_s: n, + x_pb: x, + y_pb: y, + n_pb_w: n, + n_pb_h: n, + part_mode: PartMode::Part2Nx2N, + part_idx: 0, + } + } + + #[test] + fn merge_picks_left_neighbour_motion() { + // Left neighbour A1 carries an L0 MV referencing POC 0; the merge + // candidate at merge_idx 0 copies it verbatim. + let mut field = intra_field(32, 32); + field.fill_rect(0, 0, 16, 32, inter_cell_l0(0, [12, -4])); + let ref_poc = |_l: usize, r: i32| if r == 0 { 0 } else { -999 }; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = base_ctx(&ref_poc, &long, &short, &col_long); + let geom = geom_2nx2n(16, 0, 16); + let pu = merge_pu(0); + // A1 at (15, 15) is available; everything else unavailable. + let avail = |x: i32, y: i32| x < 16 && y < 32 && x >= 0 && y >= 0; + let out = resolve_pu_motion(&field, &geom, &pu, &ctx, &avail); + assert!(out.pred_flag_l0); + assert!(!out.pred_flag_l1); + assert_eq!(out.ref_idx_l0, 0); + assert_eq!(out.mv_l0, [12, -4]); + } + + #[test] + fn merge_all_intra_neighbours_pads_zero() { + // No inter neighbours ⇒ the list is filled with zero candidates; + // merge_idx 0 selects a zero-MV uni-L0 candidate (P slice). + let field = intra_field(32, 32); + let ref_poc = |_l: usize, r: i32| if r == 0 { 0 } else { -999 }; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = base_ctx(&ref_poc, &long, &short, &col_long); + let geom = geom_2nx2n(0, 0, 16); + let pu = merge_pu(0); + let avail = |_x: i32, _y: i32| false; + let out = resolve_pu_motion(&field, &geom, &pu, &ctx, &avail); + assert!(out.pred_flag_l0); + assert!(!out.pred_flag_l1); + assert_eq!(out.mv_l0, [0, 0]); + assert_eq!(out.ref_idx_l0, 0); + } + + #[test] + fn amvp_adds_mvd_to_predictor() { + // AMVP L0: a left neighbour A1 provides the MVP; the signalled mvd + // is added (eqs 8-94..8-97). With one neighbour and no scaling the + // predictor is the neighbour MV. + let mut field = intra_field(32, 32); + field.fill_rect(0, 0, 16, 32, inter_cell_l0(0, [8, 0])); + let ref_poc = |_l: usize, r: i32| if r == 0 { 0 } else { -999 }; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = base_ctx(&ref_poc, &long, &short, &col_long); + let geom = geom_2nx2n(16, 0, 16); + let mvd = |v: i32| MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + }; + let pu = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(InterPredIdc::PredL0), + ref_idx_l0: Some(0), + mvd_l0: Some([mvd(3), mvd(2)]), + mvp_l0_flag: Some(0), + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + let avail = |x: i32, y: i32| x < 16 && y < 32 && x >= 0 && y >= 0; + let out = resolve_pu_motion(&field, &geom, &pu, &ctx, &avail); + assert!(out.pred_flag_l0); + // predictor [8,0] + mvd [3,2] = [11, 2]. + assert_eq!(out.mv_l0, [11, 2]); + assert_eq!(out.ref_idx_l0, 0); + } + + /// Eqs 8-124/8-125: a merge candidate whose reference is the + /// current picture rounds its motion vector to integer resolution. + #[test] + fn merge_rounds_mv_for_curr_pic_reference() { + let mut field = intra_field(32, 32); + // Fractional neighbour MV [13, -6] referencing POC 4 (= curr). + field.fill_rect(0, 0, 16, 32, inter_cell_l0(4, [13, -6])); + let ref_poc = |_l: usize, r: i32| if r == 0 { 4 } else { -999 }; + let long = |_l: usize, r: i32| r == 0; + let short = |_l: usize, _r: i32| false; + let col_long = |_p: i32| false; + let mut ctx = base_ctx(&ref_poc, &long, &short, &col_long); + let is_curr = |l: usize, r: i32| l == 0 && r == 0; + ctx.is_curr_pic = &is_curr; + let geom = geom_2nx2n(16, 0, 16); + let avail = |x: i32, y: i32| x < 16 && y < 32 && x >= 0 && y >= 0; + let out = resolve_pu_motion(&field, &geom, &merge_pu(0), &ctx, &avail); + assert!(out.pred_flag_l0); + // ( 13 >> 2 ) << 2 = 12; ( −6 >> 2 ) << 2 = −8 (arithmetic). + assert_eq!(out.mv_l0, [12, -8]); + } + + /// Eqs 8-98..8-101: the AMVP integer path applies the mvd at + /// integer scale on the truncated predictor when the reference is + /// the current picture. + #[test] + fn amvp_integer_path_for_curr_pic_reference() { + let mut field = intra_field(32, 32); + // Neighbour predictor [9, 5] (fractional) referencing curr POC 4. + field.fill_rect(0, 0, 16, 32, inter_cell_l0(4, [9, 5])); + let ref_poc = |_l: usize, r: i32| if r == 0 { 4 } else { -999 }; + let long = |_l: usize, r: i32| r == 0; + let short = |_l: usize, _r: i32| false; + let col_long = |_p: i32| false; + let mut ctx = base_ctx(&ref_poc, &long, &short, &col_long); + let is_curr = |l: usize, r: i32| l == 0 && r == 0; + ctx.is_curr_pic = &is_curr; + let geom = geom_2nx2n(16, 0, 16); + let mvd = |v: i32| MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + }; + let pu = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(InterPredIdc::PredL0), + ref_idx_l0: Some(0), + mvd_l0: Some([mvd(-3), mvd(1)]), + mvp_l0_flag: Some(0), + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + let avail = |x: i32, y: i32| x < 16 && y < 32 && x >= 0 && y >= 0; + let out = resolve_pu_motion(&field, &geom, &pu, &ctx, &avail); + assert!(out.pred_flag_l0); + // ( ( 9 >> 2 ) + (−3) ) << 2 = −4; ( ( 5 >> 2 ) + 1 ) << 2 = 8. + assert_eq!(out.mv_l0, [-4, 8]); + } + + #[test] + fn to_cell_round_trips_used_lists() { + let m = PuMotion { + pred_flag_l0: true, + pred_flag_l1: false, + ref_idx_l0: 0, + ref_idx_l1: -1, + mv_l0: [4, -8], + mv_l1: [0, 0], + }; + let cell = m.to_cell(2, 0); + assert!(!cell.is_intra); + assert!(cell.pred_flag_l0); + assert!(!cell.pred_flag_l1); + assert_eq!(cell.ref_poc_l0, 2); + assert_eq!(cell.ref_poc_l1, i32::MIN); + assert_eq!(cell.mv_l0, [4, -8]); + } + + #[test] + fn pu_partitions_match_spec_geometry() { + // §7.3.8.6: a 16x16 CU at (32, 16). + let p = pu_partitions(32, 16, 16, PartMode::Part2Nx2N); + assert_eq!( + p, + vec![PuRect { + x_pb: 32, + y_pb: 16, + n_pb_w: 16, + n_pb_h: 16 + }] + ); + + let p = pu_partitions(0, 0, 16, PartMode::Part2NxN); + assert_eq!( + p, + vec![ + PuRect { + x_pb: 0, + y_pb: 0, + n_pb_w: 16, + n_pb_h: 8 + }, + PuRect { + x_pb: 0, + y_pb: 8, + n_pb_w: 16, + n_pb_h: 8 + }, + ] + ); + + let p = pu_partitions(0, 0, 16, PartMode::PartNx2N); + assert_eq!( + p, + vec![ + PuRect { + x_pb: 0, + y_pb: 0, + n_pb_w: 8, + n_pb_h: 16 + }, + PuRect { + x_pb: 8, + y_pb: 0, + n_pb_w: 8, + n_pb_h: 16 + }, + ] + ); + + // AMP PART_2NxnU: top quarter (4) + bottom three-quarters (12). + let p = pu_partitions(0, 0, 16, PartMode::Part2NxnU); + assert_eq!( + p, + vec![ + PuRect { + x_pb: 0, + y_pb: 0, + n_pb_w: 16, + n_pb_h: 4 + }, + PuRect { + x_pb: 0, + y_pb: 4, + n_pb_w: 16, + n_pb_h: 12 + }, + ] + ); + + // PART_NxN: four quadrants. + let p = pu_partitions(0, 0, 16, PartMode::PartNxN); + assert_eq!(p.len(), 4); + assert_eq!( + p[3], + PuRect { + x_pb: 8, + y_pb: 8, + n_pb_w: 8, + n_pb_h: 8 + } + ); + } + + #[test] + fn cu_driver_writes_motion_field_and_resolves_second_partition() { + // A PART_Nx2N CU: PU0 (left) merges with a zero-pad list (no + // neighbours); PU1 (right) merges and its A1 neighbour is PU0, + // so it inherits PU0's motion. + let mut field = intra_field(32, 32); + let ref_poc = |_l: usize, r: i32| if r == 0 { 5 } else { -999 }; + let long = |_l: usize, _r: i32| false; + let short = |_l: usize, _r: i32| true; + let col_long = |_p: i32| false; + let ctx = base_ctx(&ref_poc, &long, &short, &col_long); + // PU0 is AMVP with an explicit MV (so it gets a deterministic, non- + // zero motion); PU1 is a merge PU that picks up PU0 from A1. + let mvd = |v: i32| MvdComponent { + greater0_flag: u8::from(v != 0), + greater1_flag: None, + minus2: None, + sign_flag: None, + value: v, + }; + let pu0 = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: Some(InterPredIdc::PredL0), + ref_idx_l0: Some(0), + mvd_l0: Some([mvd(20), mvd(0)]), + mvp_l0_flag: Some(0), + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + let pu1 = merge_pu(0); + // PU0 has no neighbours (zero MVP) ⇒ mv = [20, 0]. + // PU1's A1 = (7, 15) lies in PU0 ⇒ inherits [20, 0]; but the + // §8.5.3.2.3 vertical-split exclusion drops A1 for partIdx 1, so + // PU1 falls back to B1/.../zero. Here only A1 is in-picture-left, + // so PU1 ends up zero-MV. + let avail = |x: i32, y: i32| (0..32).contains(&x) && (0..32).contains(&y); + let cu = InterCuDesc { + x0: 0, + y0: 0, + n_cb_s: 16, + part_mode: PartMode::PartNx2N, + }; + let out = resolve_cu_motion(&mut field, cu, &[pu0, pu1], &ctx, &avail); + assert_eq!(out.len(), 2); + assert_eq!(out[0].mv_l0, [20, 0]); + // PU0's motion is written into the field. + assert_eq!(field.cell_at(0, 0).mv_l0, [20, 0]); + assert!(!field.cell_at(0, 0).is_intra); + // PU1: A1 excluded by the vertical-split rule ⇒ zero-MV merge. + assert_eq!(out[1].mv_l0, [0, 0]); + assert!(out[1].pred_flag_l0); + } +} diff --git a/vendor/oxideav-h265/src/recon.rs b/vendor/oxideav-h265/src/recon.rs new file mode 100644 index 0000000..ea9f521 --- /dev/null +++ b/vendor/oxideav-h265/src/recon.rs @@ -0,0 +1,3899 @@ +//! §8.4 intra sample reconstruction driver. +//! +//! This module is the rung between the §7.3.8 slice-data syntax walk +//! (the [`crate::slice_data`] CTU/CU/transform-tree structures) and the +//! per-block §8.4.4 intra prediction + §8.6 dequantization / inverse +//! transform primitives already implemented in [`crate::intra_pred`] and +//! [`crate::transform`]. It walks a decoded [`crate::slice_data::CodingTreeUnit`] +//! and writes reconstructed samples into a [`crate::picture::Picture`]: +//! +//! 1. §8.4.2 — derive `IntraPredModeY` for each luma prediction block +//! from the signalled `prev_intra_luma_pred_flag` / `mpm_idx` / +//! `rem_intra_luma_pred_mode` and the neighbour modes; §8.4.3 — +//! derive `IntraPredModeC`. +//! 2. §8.4.4.1 — for every transform block, gather the §8.4.4.2.1 +//! reference samples from the already-reconstructed picture (the +//! §6.4.1 availability of left / above neighbours), run §8.4.4.2 +//! prediction. +//! 3. §8.6.2 — dequantize + inverse-transform the coded residual block +//! (when its coded-block-flag is set), add it to the prediction, and +//! §8.4.4.1 clip to `[0, (1 << bitDepth) − 1]`, storing the result. +//! +//! The transform-tree recursion mirrors the §8.4.4.1 luma decode order +//! (the residual quadtree drives the transform-block grid) so each block +//! sees its left / above neighbours already reconstructed before it +//! predicts. + +use crate::availability::PictureTiling; +use crate::binarization::{ + derive_intra_pred_mode_c, derive_intra_pred_mode_y, intra_luma_cand_mode_list, + luma_intra_mode_source_from_flag, CuPredMode, LumaIntraModeSource, PartMode, +}; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::intra_pred::{ + intra_predict_with_substitution, Component as IpComponent, IntraPredError, IntraPredParams, + MarkedReferenceSamples, INTRA_DC, +}; +use crate::picture::{clip1, sub_wh_c, Picture, Plane}; +use crate::scaling_list::ScalingFactors; +use crate::slice_data::{CodingQuadtree, CodingTreeUnit, CodingUnit, IntraLumaMode}; +use crate::transform::{ + rdpcm_accumulate, residual_block, BlockParams, Component as TfComponent, PredMode, + TransformError, +}; +use crate::transform_tree::TransformTree; +use crate::transform_unit::TransformUnit; + +/// Errors raised while reconstructing samples from a decoded CTU. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum ReconError { + /// A §8.4.4.2 intra-prediction primitive failed. + IntraPred(IntraPredError), + /// A §8.6.2 dequantization / inverse-transform primitive failed. + Transform(TransformError), + /// A §8.5.3.3 inter-prediction primitive failed. + InterPred(crate::inter_pred::InterPredError), + /// The decoded CTU carried an inter prediction unit, which the intra + /// reconstruction path does not handle. + InterNotSupported, + /// The §6.4.1 picture-tiling geometry needed for neighbour + /// availability could not be built. + Tiling(crate::availability::AvailabilityError), +} + +impl core::fmt::Display for ReconError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::IntraPred(e) => write!(f, "intra prediction failed: {e}"), + Self::Transform(e) => write!(f, "inverse transform failed: {e}"), + Self::InterPred(e) => write!(f, "inter prediction failed: {e}"), + Self::InterNotSupported => { + f.write_str("inter prediction is not reconstructed by the intra path") + } + Self::Tiling(e) => write!(f, "picture tiling geometry invalid: {e}"), + } + } +} + +impl std::error::Error for ReconError {} + +impl From for ReconError { + fn from(e: IntraPredError) -> Self { + Self::IntraPred(e) + } +} + +impl From for ReconError { + fn from(e: TransformError) -> Self { + Self::Transform(e) + } +} + +/// SPS / PPS / slice-derived state constant across one picture's intra +/// reconstruction. Every field is a §8 input the per-block prediction / +/// dequantization reads. +#[derive(Debug, Clone)] +pub struct ReconParams { + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, + /// 3 = 4:4:4). + pub chroma_array_type: u8, + /// `BitDepthY`. + pub bit_depth_luma: u8, + /// `BitDepthC`. + pub bit_depth_chroma: u8, + /// `intra_smoothing_disabled_flag` (§8.4.4.2.3 step-1 gate). + pub intra_smoothing_disabled: bool, + /// `strong_intra_smoothing_enabled_flag` (§8.4.4.2.3 `biIntFlag`). + pub strong_intra_smoothing_enabled: bool, + /// `SliceQpY` (§7.4.7.1) — the slice quantization parameter, the + /// §8.6.1 luma-QP starting point (the tiny single-CU fixtures carry + /// `CuQpDeltaVal == 0`, so `QpY == SliceQpY`). + pub slice_qp_y: i32, + /// `pps_cb_qp_offset + slice_cb_qp_offset` (§8.6.1 `qPiCb` offset). + pub cb_qp_offset: i32, + /// `pps_cr_qp_offset + slice_cr_qp_offset` (§8.6.1 `qPiCr` offset). + pub cr_qp_offset: i32, + /// `PpsActQpOffsetY + slice_act_y_qp_offset` — the §8.6.2 eq. 8-291 + /// luma qP offset applied when `tu_residual_act_flag == 1`. + pub act_y_qp_offset: i32, + /// `PpsActQpOffsetCb + slice_act_cb_qp_offset` — the §8.6.1 + /// eq. 8-287 `qPiCb` offset base for `tu_residual_act_flag == 1` + /// transform units (replacing the pps + slice Cb offsets). + pub act_cb_qp_offset: i32, + /// `PpsActQpOffsetCr + slice_act_cr_qp_offset` (eq. 8-288). + pub act_cr_qp_offset: i32, + /// `transform_skip_rotation_enabled_flag`. + pub transform_skip_rotation_enabled: bool, + /// `implicit_rdpcm_enabled_flag` (§7.4.3.2.2) — gates the §8.4.4.1 + /// intra `residualDpcm` condition (transform skip or transquant + /// bypass, predModeIntra 10 / 26) that invokes the §8.6.5 + /// directional residual modification, and (with transquant bypass) + /// the §8.4.4.2.6 `disableIntraBoundaryFilter` derivation. + pub implicit_rdpcm_enabled: bool, + /// `intra_boundary_filtering_disabled_flag` (§7.4.3.2.3) — the + /// first §8.4.4.2.6 `disableIntraBoundaryFilter` condition. + pub intra_boundary_filtering_disabled: bool, + /// `extended_precision_processing_flag`. + pub extended_precision: bool, + /// The active §7.4.5 `ScalingFactor` matrices when + /// `scaling_list_enabled_flag == 1` (the PPS `scaling_list_data()` + /// if present, else the SPS body, else the default lists); `None` + /// when the flag is 0 (the §8.6.3 flat-16 path). + pub scaling: Option, + /// `(cb_qp_offset_list[i], cr_qp_offset_list[i])` (§7.4.3.3.2) — + /// the PPS range extension chroma QP offset lists dereferenced by + /// `cu_chroma_qp_offset_idx`. Empty when + /// `chroma_qp_offset_list_enabled_flag == 0`. + pub chroma_qp_offset_list: Vec<(i32, i32)>, + /// The live `( CuQpOffsetCb, CuQpOffsetCr )` state (§7.4.9.10): + /// reset to `(0, 0)` at each slice start (§7.4.7.1), overwritten + /// whenever a reconstructed transform unit / palette CU carries a + /// parsed `cu_chroma_qp_offset_flag`, and consumed by the §8.6.1 + /// eqs. 8-285..8-288 chroma QP derivation. Interior-mutable so the + /// decode-order state threads through the shared `&ReconParams` + /// without touching every recursion signature (picture + /// reconstruction is single-threaded). + pub cu_qp_offset_c: core::cell::Cell<(i32, i32)>, +} + +/// §7.4.9.10 — resolve a parsed `cu_chroma_qp_offset` element to the +/// `( CuQpOffsetCb, CuQpOffsetCr )` pair it selects (eqs. 7-87 / 7-88; +/// `(0, 0)` when the flag is 0) and store it in the live state. +fn apply_cu_chroma_qp_offset(params: &ReconParams, off: &crate::binarization::CuChromaQpOffset) { + let pair = match off.offset_indices() { + Some(idx) => params + .chroma_qp_offset_list + .get(idx as usize) + .copied() + .unwrap_or((0, 0)), + None => (0, 0), + }; + params.cu_qp_offset_c.set(pair); +} + +/// §8.6.3 `m[ x ][ y ]` source selection: the `ScalingFactor[ sizeId ] +/// [ matrixId ]` matrix for a transform block, or `None` for the flat +/// 16 (scaling lists disabled, or the `transform_skip_flag == 1 && +/// nTbS > 4` exception). +/// +/// `sizeId` is Table 7-3 (`log2(nTbS) − 2`); `matrixId` is Table 7-4 +/// (`(CuPredMode == MODE_INTRA ? 0 : 3) + cIdx`). +fn scaling_matrix( + params: &ReconParams, + n_tbs: usize, + pred_mode: PredMode, + cidx: TfComponent, + transform_skip: bool, +) -> Option<&crate::scaling_list::ScalingFactorMatrix> { + let sf = params.scaling.as_ref()?; + if transform_skip && n_tbs > 4 { + return None; + } + let size_id = match n_tbs { + 4 => 0usize, + 8 => 1, + 16 => 2, + _ => 3, + }; + let matrix_id = match pred_mode { + PredMode::Intra => 0usize, + _ => 3, + } + match cidx { + TfComponent::Luma => 0usize, + TfComponent::Cb => 1, + TfComponent::Cr => 2, + }; + Some(&sf.factors[size_id][matrix_id]) +} + +/// `QpBdOffsetY = 6 * bit_depth_luma_minus8` (§7.4.3.2.1, eq. 7-4). +#[inline] +fn qp_bd_offset(bit_depth: u8) -> i32 { + 6 * (i32::from(bit_depth) - 8) +} + +/// §8.6.1 — derive `Qp′Y` for a luma transform block. +/// +/// `Qp′Y = QpY + QpBdOffsetY`, with `QpY` the slice QP plus any +/// `CuQpDeltaVal` (clipped per the §8.6.1 wrap). The neighbour-prediction +/// of `qPY_PRED` collapses to a single value when every coding unit in +/// the picture shares the slice QP (no `cu_qp_delta`); the recursion +/// threads `cu_qp_delta_val` so the general single-CU-per-QG case is +/// exact. +#[inline] +fn luma_qp(params: &ReconParams, qp_y: i32) -> u32 { + // §8.6.1 eq. 8-284: Qp′Y = QpY + QpBdOffsetY, with `qp_y` the + // already-derived (eq. 8-283) luma quantization parameter. + let qp_bd = qp_bd_offset(params.bit_depth_luma); + (qp_y + qp_bd) as u32 +} + +/// §8.6.2 eq. 8-291 — the luma qP of a `tu_residual_act_flag == 1` +/// transform block: `Clip3( 0, 51 + QpBdOffsetY, Qp′Y + +/// PpsActQpOffsetY + slice_act_y_qp_offset )`. +#[inline] +fn luma_qp_act(params: &ReconParams, qp_y: i32) -> u32 { + let qp_bd = qp_bd_offset(params.bit_depth_luma); + (qp_y + qp_bd + params.act_y_qp_offset).clamp(0, 51 + qp_bd) as u32 +} + +/// §8.6.1 eq. 8-283 with `qPY_PRED == SliceQpY` — the single-QG +/// fallback used when no picture-level QP state is initialized (the +/// standalone per-CTU helpers). +#[inline] +fn fallback_qp_y(params: &ReconParams, cu_qp_delta_val: i32) -> i32 { + let qp_bd = qp_bd_offset(params.bit_depth_luma); + let modulus = 52 + qp_bd; + (params.slice_qp_y + cu_qp_delta_val + 52 + 2 * qp_bd).rem_euclid(modulus) - qp_bd +} + +/// Table 8-10 — `ChromaArrayType == 1` chroma-QP mapping `QpC = f(qPi)`. +#[inline] +fn qpc_420(qpi: i32) -> i32 { + match qpi { + x if x < 30 => x, + 30 => 29, + 31 => 30, + 32 => 31, + 33 => 32, + 34 => 33, + 35 => 33, + 36 => 34, + 37 => 34, + 38 => 35, + 39 => 35, + 40 => 36, + 41 => 36, + 42 => 37, + 43 => 37, + x => x - 6, + } +} + +/// §8.6.1 — derive `Qp′Cb` / `Qp′Cr` for a chroma transform block. +/// +/// `qPiCx = Clip3( −QpBdOffsetC, 57, QpY + cQpOffset )`; for +/// `ChromaArrayType == 1` `qPCx = qPC_table( qPiCx )` (Table 8-10), for +/// the other chroma types `qPCx = Min( qPiCx, 51 )`; then +/// `Qp′Cx = qPCx + QpBdOffsetC` (eq. 8-260). +#[inline] +fn chroma_qp(params: &ReconParams, qp_y: i32, cidx: TfComponent) -> u32 { + chroma_qp_act(params, qp_y, cidx, false) +} + +/// §8.6.1 with the eq. 8-285..8-288 offset selection: for a +/// `tu_residual_act_flag == 1` transform unit the `qPiCx` offset base +/// is `PpsActQpOffsetCx + slice_act_cx_qp_offset` instead of the +/// pps + slice component offsets. +#[inline] +fn chroma_qp_act(params: &ReconParams, qp_y: i32, cidx: TfComponent, act: bool) -> u32 { + let qp_bd_c = qp_bd_offset(params.bit_depth_chroma); + // `qp_y` is the already-derived (eq. 8-283) QpY — the §8.6.1 + // chroma input. + let qpy = qp_y; + let (cu_off_cb, cu_off_cr) = params.cu_qp_offset_c.get(); + let offset = match (cidx, act) { + (TfComponent::Cb, false) => params.cb_qp_offset + cu_off_cb, + (TfComponent::Cr, false) => params.cr_qp_offset + cu_off_cr, + (TfComponent::Cb, true) => params.act_cb_qp_offset + cu_off_cb, + (TfComponent::Cr, true) => params.act_cr_qp_offset + cu_off_cr, + (TfComponent::Luma, _) => 0, + }; + let qpi = (qpy + offset).clamp(-qp_bd_c, 57); + let qpc = if params.chroma_array_type == 1 { + qpc_420(qpi) + } else { + qpi.min(51) + }; + (qpc + qp_bd_c) as u32 +} + +/// Gather the §8.4.4.2.1 reference-sample array for a transform block at +/// plane position `(xb, yb)` of side `n_tbs` from the already- +/// reconstructed picture, marking each neighbour available per the §6.4.1 +/// z-scan availability process (via [`ReconCtx::ref_sample_available`]): +/// a neighbour is available iff it is inside the picture, already decoded +/// in z-scan order, and in the same slice / tile. The unavailable samples +/// are substituted by [`intra_predict_with_substitution`]. +fn gather_reference_samples( + pic: &Picture, + ctx: &ReconCtx, + plane: Plane, + xb: usize, + yb: usize, + n_tbs: usize, +) -> MarkedReferenceSamples { + let (pw, ph) = pic.plane_dims(plane); + let (sub_w, sub_h) = match plane { + Plane::Luma => (1, 1), + Plane::Cb | Plane::Cr => sub_wh_c(pic.chroma_array_type()), + }; + let avail = |x: i64, y: i64| -> bool { + x >= 0 + && y >= 0 + && (x as usize) < pw + && (y as usize) < ph + && ctx.ref_sample_available(xb, yb, x, y, sub_w, sub_h) + }; + let read = |x: i64, y: i64| -> (i32, bool) { + if avail(x, y) { + (pic.sample(plane, x as usize, y as usize), true) + } else { + (0, false) + } + }; + // Corner p[−1][−1]. + let corner = read(xb as i64 - 1, yb as i64 - 1); + // Left column p[−1][0 .. 2*nTbS−1]. + let mut left = Vec::with_capacity(2 * n_tbs); + for y in 0..(2 * n_tbs) { + left.push(read(xb as i64 - 1, yb as i64 + y as i64)); + } + // Top row p[0 .. 2*nTbS−1][−1]. + let mut top = Vec::with_capacity(2 * n_tbs); + for x in 0..(2 * n_tbs) { + top.push(read(xb as i64 + x as i64, yb as i64 - 1)); + } + MarkedReferenceSamples::new(n_tbs, corner, left, top) + .expect("reference array dimensions match n_tbs") +} + +/// §8.6.6 — residual modification for transform blocks using +/// cross-component prediction (`ChromaArrayType == 3` only): +/// +/// `r[ x ][ y ] += ( ResScaleVal * ( ( rY[ x ][ y ] << BitDepthC ) >> +/// BitDepthY ) ) >> 3` (eq. 8-324), with `rY` the co-located luma +/// residual of the same transform unit. The intermediate runs in `i64` +/// so the `<< BitDepthC` cannot overflow at extended-precision coeff +/// ranges; the shifts are arithmetic per the §5.8 operator definitions. +fn apply_cross_comp_pred( + r: &mut [i32], + r_y: &[i32], + res_scale_val: i32, + bit_depth_luma: u8, + bit_depth_chroma: u8, +) { + debug_assert_eq!(r.len(), r_y.len()); + let bd_y = i64::from(bit_depth_luma); + let bd_c = i64::from(bit_depth_chroma); + let scale = i64::from(res_scale_val); + for (rv, &ry) in r.iter_mut().zip(r_y.iter()) { + let scaled = (scale * ((i64::from(ry) << bd_c) >> bd_y)) >> 3; + *rv = (i64::from(*rv) + scaled) as i32; + } +} + +/// The §8.6.6 inputs for one chroma transform block: the co-located +/// luma residual array `rY` (post-§8.6.5, same `nTbS` — 4:4:4 only) +/// and the §7.4.9.12-derived `ResScaleVal`. +#[derive(Clone, Copy)] +struct CcpInput<'a> { + luma_residual: &'a [i32], + res_scale_val: i32, +} + +impl<'a> CcpInput<'a> { + /// Build the §8.6.6 input for one chroma component, when the + /// bitstream carried a `cross_comp_pred( )` with a non-zero + /// `ResScaleVal` and the transform unit has a luma residual to + /// predict from (an all-zero `rY` contributes nothing). + fn resolve( + chroma_array_type: u8, + ccp: Option<&crate::binarization::CrossCompPred>, + luma_residual: Option<&'a [i32]>, + ) -> Option { + if chroma_array_type != 3 { + return None; + } + let res_scale_val = ccp?.res_scale_val; + if res_scale_val == 0 { + return None; + } + Some(Self { + luma_residual: luma_residual?, + res_scale_val, + }) + } +} + +/// Predict one intra transform block, add its residual, clip, and store +/// into `pic`. `(xb, yb)` is the plane-coordinate top-left; `pred_mode` +/// is the §8.4.x prediction mode for the plane's component. +/// +/// Returns the final residual array (post-§8.6.5/§8.6.6 modification) +/// so a 4:4:4 caller can feed the luma residual into the chroma +/// blocks' §8.6.6 cross-component prediction; `None` when the block +/// carried no residual at all. +#[allow(clippy::too_many_arguments)] +fn reconstruct_intra_block( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + plane: Plane, + cidx: TfComponent, + ip_component: IpComponent, + xb: usize, + yb: usize, + n_tbs: usize, + pred_mode_intra: u8, + residual: Option<&[i32]>, + qp: u32, + transquant_bypass: bool, + transform_skip: bool, + ccp: Option>, +) -> Result>, ReconError> { + // §8.6.2 residual array (zero when the block has no coded coeffs). + let res: Option> = match residual { + Some(levels) => Some(intra_residual_array( + params, + cidx, + n_tbs, + pred_mode_intra, + levels, + qp, + transquant_bypass, + transform_skip, + )?), + None => None, + }; + + // §8.4.4.1 step 8: cross-component prediction modifies the chroma + // residual from the co-located luma residual (after the step-7 + // §8.6.5 modification, before the §8.6.7 add). A block with no + // coded chroma residual still receives the scaled luma residual. + let res = match ccp { + Some(c) => { + let mut r = res.unwrap_or_else(|| vec![0i32; n_tbs * n_tbs]); + apply_cross_comp_pred( + &mut r, + c.luma_residual, + c.res_scale_val, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + Some(r) + } + None => res, + }; + + predict_add_store( + pic, + params, + ctx, + plane, + ip_component, + xb, + yb, + n_tbs, + pred_mode_intra, + transquant_bypass, + res.as_deref(), + )?; + Ok(res) +} + +/// §8.6.2 + §8.6.5 — dequantize / inverse-transform one intra block's +/// coded levels and apply the §8.4.4.1 implicit-RDPCM residual +/// modification when its condition holds. +#[allow(clippy::too_many_arguments)] +fn intra_residual_array( + params: &ReconParams, + cidx: TfComponent, + n_tbs: usize, + pred_mode_intra: u8, + levels: &[i32], + qp: u32, + transquant_bypass: bool, + transform_skip: bool, +) -> Result, ReconError> { + let bit_depth = match cidx { + TfComponent::Luma => params.bit_depth_luma, + TfComponent::Cb | TfComponent::Cr => params.bit_depth_chroma, + }; + let bp = BlockParams { + n_tbs, + q_p: qp, + component: cidx, + pred_mode: PredMode::Intra, + bit_depth, + extended_precision: params.extended_precision, + transquant_bypass, + transform_skip, + transform_skip_rotation_enabled: params.transform_skip_rotation_enabled, + }; + let m = scaling_matrix(params, n_tbs, PredMode::Intra, cidx, transform_skip); + let mut r = residual_block(levels, m, bp)?; + // §8.4.4.1: residualDpcm — implicit RDPCM applies the §8.6.5 + // directional residual modification to intra blocks in + // transform-skip / transquant-bypass form whose prediction mode is + // exactly horizontal (10) or vertical (26), with + // mDir = predModeIntra / 26. + if params.implicit_rdpcm_enabled + && (transform_skip || transquant_bypass) + && (pred_mode_intra == 10 || pred_mode_intra == 26) + { + rdpcm_accumulate(&mut r, n_tbs, pred_mode_intra == 26); + } + Ok(r) +} + +/// §8.4.4.2.1 prediction + §8.6.7 picture construction for one intra +/// transform block: gather references, predict, add `res` (when +/// present), clip, store. +#[allow(clippy::too_many_arguments)] +fn predict_add_store( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + plane: Plane, + ip_component: IpComponent, + xb: usize, + yb: usize, + n_tbs: usize, + pred_mode_intra: u8, + transquant_bypass: bool, + res: Option<&[i32]>, +) -> Result<(), ReconError> { + let bit_depth = pic.bit_depth(plane); + let marked = gather_reference_samples(pic, ctx, plane, xb, yb, n_tbs); + // §8.4.4.2.6: disableIntraBoundaryFilter is 1 when + // intra_boundary_filtering_disabled_flag is 1, or when + // implicit_rdpcm_enabled_flag and cu_transquant_bypass_flag are + // both 1. That derivation gates only the ANGULAR mode-10 / mode-26 + // edge filters; the §8.4.4.2.5 INTRA_DC smoothing (eq. 8-48..8-51) + // is gated on intra_boundary_filtering_disabled_flag alone, so the + // implicit-RDPCM term is withheld for the DC mode. + let disable_boundary_filter = params.intra_boundary_filtering_disabled + || (pred_mode_intra != INTRA_DC && params.implicit_rdpcm_enabled && transquant_bypass); + let ip_params = IntraPredParams { + pred_mode_intra, + cidx: ip_component, + bit_depth, + bit_depth_luma: params.bit_depth_luma, + intra_smoothing_disabled: params.intra_smoothing_disabled, + strong_intra_smoothing_enabled: params.strong_intra_smoothing_enabled, + chroma_array_type_3: params.chroma_array_type == 3, + disable_boundary_filter, + }; + let pred = intra_predict_with_substitution(&marked, &ip_params)?; + + // §8.4.4.1 / §8.6.7: recSamples = Clip1( predSamples + resSamples ). + for y in 0..n_tbs { + for x in 0..n_tbs { + let p = pred[y * n_tbs + x]; + let r = res.map_or(0, |r| r[y * n_tbs + x]); + let v = clip1(p + r, bit_depth); + pic.set_sample(plane, xb + x, yb + y, v); + } + } + Ok(()) +} + +// --------------------------------------------------------------------------- +// §8.5 inter sample reconstruction +// --------------------------------------------------------------------------- + +use crate::inter_pred::{InterPredGeometry, InterPrediction, ListPrediction, RefPlane}; + +/// One reference list's fully-resolved per-PU motion: the +/// §8.5.3.2-derived luma motion vector, the §8.5.3.2.10 chroma motion +/// vector, and the §8.5.3.3.2-selected reference picture. +#[derive(Debug, Clone, Copy)] +pub struct ResolvedList<'a> { + /// `predFlagLX` — whether this list contributes. + pub pred_flag: bool, + /// `mvLX` in quarter-luma-sample units. + pub mv_l: [i32; 2], + /// `mvCLX` in eighth-chroma-sample units (§8.5.3.2.10). + pub mv_c: [i32; 2], + /// `RefPicListX[refIdxLX]` — the reference picture's samples. + pub ref_pic: &'a Picture, +} + +/// Build the §8.5.3.3.2 [`ListPrediction`] for one reference list, +/// borrowing the reference picture's luma + (when chroma is present) +/// Cb / Cr planes for the lifetime `'a`. +fn build_list_prediction<'a>( + list: &ResolvedList<'a>, + chroma_array_type: u8, +) -> Result, ReconError> { + let (lw, lh) = list.ref_pic.plane_dims(Plane::Luma); + let lp = + RefPlane::new(list.ref_pic.plane(Plane::Luma), lw, lh).map_err(ReconError::InterPred)?; + let (cb, cr) = if chroma_array_type != 0 { + let (cw, ch) = list.ref_pic.plane_dims(Plane::Cb); + ( + Some( + RefPlane::new(list.ref_pic.plane(Plane::Cb), cw, ch) + .map_err(ReconError::InterPred)?, + ), + Some( + RefPlane::new(list.ref_pic.plane(Plane::Cr), cw, ch) + .map_err(ReconError::InterPred)?, + ), + ) + } else { + (None, None) + }; + Ok(ListPrediction { + pred_flag: list.pred_flag, + luma: lp, + cb, + cr, + mv_l: list.mv_l, + mv_c: list.mv_c, + }) +} + +/// §8.5.3.3 — reconstruct one inter prediction unit's motion-compensated +/// prediction into `pic`, then (when a residual block is supplied) add +/// the §8.6.2 residual and §8.6.5 / §8.4.4.1 clip. +/// +/// `(x_pb, y_pb)` is the PU's luma top-left; `(n_pb_w, n_pb_h)` its luma +/// size. The L0 / L1 lists carry the resolved motion + reference picture. +/// `residual_luma` / `residual_cb` / `residual_cr` are the optional +/// §8.6.2-output residual arrays (already dequantized + inverse +/// transformed) for the PU's covering transform blocks; pass `None` for a +/// skip / zero-residual PU (the prediction is written directly). +/// +/// # Errors +/// Propagates [`ReconError::InterNotSupported`] reuse is avoided here; the +/// §8.5.3.3 interpolation failures surface as [`ReconError`] via the +/// `InterPred` variant carrying the [`crate::inter_pred::InterPredError`]. +#[allow(clippy::too_many_arguments)] +pub fn reconstruct_inter_pu( + pic: &mut Picture, + params: &ReconParams, + x_pb: usize, + y_pb: usize, + n_pb_w: usize, + n_pb_h: usize, + l0: ResolvedList<'_>, + l1: ResolvedList<'_>, + residual_luma: Option<&[i32]>, + residual_cb: Option<&[i32]>, + residual_cr: Option<&[i32]>, +) -> Result<(), ReconError> { + reconstruct_inter_pu_weighted( + pic, + params, + x_pb, + y_pb, + n_pb_w, + n_pb_h, + l0, + l1, + residual_luma, + residual_cb, + residual_cr, + None, + ) +} + +/// §8.5.3.3 — as [`reconstruct_inter_pu`], with the §8.5.3.3.4.1 +/// weighted-sample-prediction dispatch: `weights == None` uses the +/// §8.5.3.3.4.2 default combine, `weights == Some(..)` the §8.5.3.3.4.3 +/// explicit per-reference combine. +/// +/// # Errors +/// Same contract as [`reconstruct_inter_pu`]. +#[allow(clippy::too_many_arguments)] +pub fn reconstruct_inter_pu_weighted( + pic: &mut Picture, + params: &ReconParams, + x_pb: usize, + y_pb: usize, + n_pb_w: usize, + n_pb_h: usize, + l0: ResolvedList<'_>, + l1: ResolvedList<'_>, + residual_luma: Option<&[i32]>, + residual_cb: Option<&[i32]>, + residual_cr: Option<&[i32]>, + weights: Option<&crate::inter_pred::PuWeights>, +) -> Result<(), ReconError> { + let cat = params.chroma_array_type; + // Build the §8.5.3.3.2 reference planes for each used list. + let lp0 = build_list_prediction(&l0, cat)?; + let lp1 = build_list_prediction(&l1, cat)?; + let geom = InterPredGeometry { + x_pb: x_pb as i32, + y_pb: y_pb as i32, + n_pb_w, + n_pb_h, + chroma_array_type: cat, + bit_depth_luma: params.bit_depth_luma, + bit_depth_chroma: params.bit_depth_chroma, + }; + let InterPrediction { luma, cb, cr } = + crate::inter_pred::predict_inter_pu_weighted(&lp0, &lp1, &geom, weights) + .map_err(ReconError::InterPred)?; + + // §8.6.5 / §8.4.4.1: recSamples = Clip1( predSamples + resSamples ). + write_inter_plane( + pic, + Plane::Luma, + x_pb, + y_pb, + n_pb_w, + n_pb_h, + &luma, + residual_luma, + ); + if cat != 0 { + let (sw, sh) = sub_wh_c(cat); + let xc = x_pb / sw; + let yc = y_pb / sh; + let pcw = n_pb_w / sw; + let pch = n_pb_h / sh; + write_inter_plane(pic, Plane::Cb, xc, yc, pcw, pch, &cb, residual_cb); + write_inter_plane(pic, Plane::Cr, xc, yc, pcw, pch, &cr, residual_cr); + } + Ok(()) +} + +/// Write one motion-compensated prediction plane plus its optional +/// residual into `pic` with the §8.4.4.1 clip. +#[allow(clippy::too_many_arguments)] +fn write_inter_plane( + pic: &mut Picture, + plane: Plane, + x0: usize, + y0: usize, + w: usize, + h: usize, + pred: &[i32], + residual: Option<&[i32]>, +) { + let bit_depth = pic.bit_depth(plane); + for y in 0..h { + for x in 0..w { + let p = pred[y * w + x]; + let r = residual.map_or(0, |r| r[y * w + x]); + pic.set_sample(plane, x0 + x, y0 + y, clip1(p + r, bit_depth)); + } + } +} + +/// Map an `IpComponent` for the plane / cIdx pair. +#[inline] +fn ip_component_of(cidx: TfComponent) -> IpComponent { + match cidx { + TfComponent::Luma => IpComponent::Luma, + TfComponent::Cb => IpComponent::Cb, + TfComponent::Cr => IpComponent::Cr, + } +} + +/// A per-coding-unit residual buffer for one component, sized to the luma +/// coding block (luma) or its chroma sub-sampling (Cb / Cr). The §8.5 +/// inter reconstruction adds this onto the motion-compensated prediction. +/// +/// The transform tree (§7.3.8.8) subdivides the coding block independently +/// of the §7.3.8.6 prediction-unit partitioning, so the inter +/// reconstruction first assembles the whole-CU residual (every leaf +/// transform block's §8.6.2 dequant + inverse transform written into its +/// position) and then slices out each prediction unit's covering region. +#[derive(Debug, Clone)] +pub struct CuResidualPlane { + /// Top-left x of the plane within its component (luma coordinates for + /// luma, chroma-subsampled coordinates for Cb / Cr). + pub x0: usize, + /// Top-left y of the plane. + pub y0: usize, + /// Plane width in samples. + pub width: usize, + /// Plane height in samples. + pub height: usize, + /// Row-major residual samples (`width * height`), zero where no + /// transform block coded coefficients. + pub samples: Vec, +} + +impl CuResidualPlane { + /// A zero residual plane covering `(x0, y0)` of size `width × height`. + fn zeros(x0: usize, y0: usize, width: usize, height: usize) -> Self { + Self { + x0, + y0, + width, + height, + samples: vec![0; width * height], + } + } + + /// Write a `n × n` residual sub-block at component position + /// `(bx, by)` (the block's top-left in the same coordinate system as + /// `x0`/`y0`), clipping to the plane bounds. + fn write_block(&mut self, bx: usize, by: usize, n: usize, block: &[i32]) { + for y in 0..n { + let py = by + y; + if py < self.y0 || py >= self.y0 + self.height { + continue; + } + for x in 0..n { + let px = bx + x; + if px < self.x0 || px >= self.x0 + self.width { + continue; + } + let idx = (py - self.y0) * self.width + (px - self.x0); + self.samples[idx] = block[y * n + x]; + } + } + } + + /// Extract the `w × h` residual covering the prediction region at + /// component position `(rx, ry)` (row-major), zero-filling positions + /// outside this plane. + #[must_use] + pub fn slice_region(&self, rx: usize, ry: usize, w: usize, h: usize) -> Vec { + let mut out = vec![0; w * h]; + for y in 0..h { + let py = ry + y; + if py < self.y0 || py >= self.y0 + self.height { + continue; + } + for x in 0..w { + let px = rx + x; + if px < self.x0 || px >= self.x0 + self.width { + continue; + } + out[y * w + x] = self.samples[(py - self.y0) * self.width + (px - self.x0)]; + } + } + out + } +} + +/// The three per-component residual planes of one inter coding unit. +#[derive(Debug, Clone)] +pub struct CuResidual { + /// The luma residual plane (luma coordinates). + pub luma: CuResidualPlane, + /// The Cb residual plane (chroma-subsampled coordinates), absent for + /// monochrome. + pub cb: Option, + /// The Cr residual plane. + pub cr: Option, +} + +impl CuResidual { + /// `true` when this CU codes no residual at all (skip / `rqt_root_cbf + /// == 0`); the prediction is written directly. + #[must_use] + pub fn is_zero(&self) -> bool { + let plane_zero = |p: &Option| match p { + Some(plane) => plane.samples.iter().all(|&s| s == 0), + None => true, + }; + self.luma.samples.iter().all(|&s| s == 0) && plane_zero(&self.cb) && plane_zero(&self.cr) + } +} + +/// §8.5 / §8.6.2 — assemble one inter coding unit's residual planes by +/// walking its §7.3.8.8 transform tree, dequantizing + inverse-transforming +/// each leaf transform block (`MODE_INTER` path) into its CU-relative +/// position. +/// +/// `(x_cb, y_cb)` is the CU's luma top-left; `n_cb_s` its luma side. +/// `qp_y` is the §8.6.1-derived `QpY` of the CU (`SliceQpY` for the +/// single-QG case). Returns `CuResidual` with the luma plane and — for a +/// non-monochrome `ChromaArrayType` — the Cb / Cr planes. +/// +/// # Errors +/// Propagates [`ReconError::Transform`] from the §8.6.2 inverse transform. +pub fn extract_cu_residual( + params: &ReconParams, + tree: Option<&TransformTree>, + x_cb: usize, + y_cb: usize, + n_cb_s: usize, + qp_y: i32, + transquant_bypass: bool, +) -> Result { + let cat = params.chroma_array_type; + let mut luma = CuResidualPlane::zeros(x_cb, y_cb, n_cb_s, n_cb_s); + let (mut cb, mut cr) = if cat != 0 { + let (sw, sh) = sub_wh_c(cat); + let (cw, ch) = (n_cb_s / sw, n_cb_s / sh); + let (cx, cy) = (x_cb / sw, y_cb / sh); + ( + Some(CuResidualPlane::zeros(cx, cy, cw, ch)), + Some(CuResidualPlane::zeros(cx, cy, cw, ch)), + ) + } else { + (None, None) + }; + + if let Some(tree) = tree { + // The CU log2 size is the depth-0 transform-tree size. + let log2_cb = n_cb_s.trailing_zeros(); + extract_residual_tree( + params, + tree, + x_cb, + y_cb, + log2_cb, + qp_y, + transquant_bypass, + &mut luma, + cb.as_mut(), + cr.as_mut(), + )?; + } + + Ok(CuResidual { luma, cb, cr }) +} + +/// Recursive helper for [`extract_cu_residual`]: walk a transform-tree node +/// and write each leaf's residual into the component planes. +// +// `as_deref_mut` here is the standard `Option<&mut T>` reborrow needed to +// reuse the optional chroma planes across the four-child loop; clippy's +// `needless_option_as_deref` misfires on the reborrow pattern. +#[allow(clippy::too_many_arguments, clippy::needless_option_as_deref)] +fn extract_residual_tree( + params: &ReconParams, + tree: &TransformTree, + x0: usize, + y0: usize, + log2_trafo_size: u32, + qp_y: i32, + transquant_bypass: bool, + luma: &mut CuResidualPlane, + mut cb: Option<&mut CuResidualPlane>, + mut cr: Option<&mut CuResidualPlane>, +) -> Result<(), ReconError> { + match tree { + TransformTree::Split { children, .. } => { + let half = 1usize << (log2_trafo_size - 1); + let offsets = [(0, 0), (half, 0), (0, half), (half, half)]; + for (child, (dx, dy)) in children.iter().zip(offsets) { + extract_residual_tree( + params, + child, + x0 + dx, + y0 + dy, + log2_trafo_size - 1, + qp_y, + transquant_bypass, + luma, + cb.as_deref_mut(), + cr.as_deref_mut(), + )?; + } + Ok(()) + } + TransformTree::Leaf { unit, .. } => { + let n_tbs = 1usize << log2_trafo_size; + // §7.4.9.10 — thread the CuQpOffsetCb / CuQpOffsetCr state + // in decode order on the inter residual path too. + if let Some(off) = &unit.cu_chroma_qp_offset { + apply_cu_chroma_qp_offset(params, off); + } + // §8.5.4.1 step 4 — a tu_residual_act_flag == 1 unit + // (4:4:4) derives all three co-located residual arrays + // (ACT-adjusted qP), applies cross-component prediction, + // then the §8.6.8.2 inverse colour transform, before the + // arrays land in the CU planes. + if unit.tu_residual_act_flag == 1 && params.chroma_array_type == 3 { + let mut r_y = match &unit.residual_luma { + Some(rb) => inter_residual_block( + params, + rb, + TfComponent::Luma, + luma_qp_act(params, qp_y), + transquant_bypass, + )?, + None => vec![0i32; n_tbs * n_tbs], + }; + let chroma_res = |blocks: &[crate::residual::ResidualBlock], + coded: bool, + cidx: TfComponent| + -> Result, ReconError> { + match blocks.first() { + Some(rb) if coded => inter_residual_block( + params, + rb, + cidx, + chroma_qp_act(params, qp_y, cidx, true), + transquant_bypass, + ), + _ => Ok(vec![0i32; n_tbs * n_tbs]), + } + }; + let mut r_cb = + chroma_res(&unit.residual_cb, unit.cbf_cb_halves[0], TfComponent::Cb)?; + let mut r_cr = + chroma_res(&unit.residual_cr, unit.cbf_cr_halves[0], TfComponent::Cr)?; + for (r, ccp) in [ + (&mut r_cb, unit.cross_comp_pred_cb.as_ref()), + (&mut r_cr, unit.cross_comp_pred_cr.as_ref()), + ] { + if let Some(c) = CcpInput::resolve(params.chroma_array_type, ccp, Some(&r_y)) { + apply_cross_comp_pred( + r, + c.luma_residual, + c.res_scale_val, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + } + } + crate::transform::act_inverse( + &mut r_y, + &mut r_cb, + &mut r_cr, + params.bit_depth_luma, + params.bit_depth_chroma, + params.extended_precision, + transquant_bypass, + ); + luma.write_block(x0, y0, n_tbs, &r_y); + if let Some(plane) = cb { + plane.write_block(x0, y0, n_tbs, &r_cb); + } + if let Some(plane) = cr { + plane.write_block(x0, y0, n_tbs, &r_cr); + } + return Ok(()); + } + // Luma residual (§8.6.2 with the MODE_INTER path). The + // array is kept for the §8.5.4.3 step-5 cross-component + // prediction of this unit's chroma blocks (4:4:4). + let luma_res: Option> = match &unit.residual_luma { + Some(rb) => { + let qp = luma_qp(params, qp_y); + let res = + inter_residual_block(params, rb, TfComponent::Luma, qp, transquant_bypass)?; + luma.write_block(x0, y0, n_tbs, &res); + Some(res) + } + None => None, + }; + // Chroma residuals, positioned at the chroma-subsampled + // coordinates of this luma node. §7.3.8.10 deferred chroma: + // a 4×4 luma leaf (ChromaArrayType != 3) carries no chroma + // of its own — the blkIdx == 3 child holds the PARENT + // node's chroma blocks, positioned at ( xBase, yBase ), the + // 8×8 parent's top-left (x0 / y0 with the low 3 bits + // cleared). + if params.chroma_array_type != 0 { + let (x_base, y_base) = if log2_trafo_size == 2 && params.chroma_array_type != 3 { + (x0 & !7, y0 & !7) + } else { + (x0, y0) + }; + let (sw, sh) = sub_wh_c(params.chroma_array_type); + let (xc, yc) = (x_base / sw, y_base / sh); + let luma_res = luma_res.as_deref(); + let ccp_cb = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cb.as_ref(), + luma_res, + ); + let ccp_cr = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cr.as_ref(), + luma_res, + ); + if let Some(plane) = cb { + let qp = chroma_qp(params, qp_y, TfComponent::Cb); + write_chroma_residual_blocks( + params, + &unit.residual_cb, + unit.cbf_cb_halves, + TfComponent::Cb, + qp, + transquant_bypass, + xc, + yc, + sh, + n_tbs, + ccp_cb, + plane, + )?; + } + if let Some(plane) = cr { + let qp = chroma_qp(params, qp_y, TfComponent::Cr); + write_chroma_residual_blocks( + params, + &unit.residual_cr, + unit.cbf_cr_halves, + TfComponent::Cr, + qp, + transquant_bypass, + xc, + yc, + sh, + n_tbs, + ccp_cr, + plane, + )?; + } + } + Ok(()) + } + } +} + +/// Write a transform unit's chroma residual blocks into `plane`. The +/// `ChromaArrayType == 2` lower-half companion (when present as a second +/// block) is positioned `1 << log2TrafoSizeC` samples below the first. +/// +/// `n_tbs_c` is the §7.3.8.10 chroma transform-block side of this unit +/// (equal to the luma side for 4:4:4) — needed when a `ccp` residual +/// modification must materialize a block whose cbf is clear. `ccp` +/// carries the §8.5.4.3 step-5 cross-component prediction input. +#[allow(clippy::too_many_arguments)] +fn write_chroma_residual_blocks( + params: &ReconParams, + blocks: &[crate::residual::ResidualBlock], + coded_halves: [bool; 2], + cidx: TfComponent, + qp: u32, + transquant_bypass: bool, + xc: usize, + yc: usize, + sub_h: usize, + n_tbs_c: usize, + ccp: Option>, + plane: &mut CuResidualPlane, +) -> Result<(), ReconError> { + // §7.3.8.10 codes the halves upper-then-lower, each gated on its + // own cbf (`sub_h == 1` ⇔ ChromaArrayType == 2 stacked pair) — pair + // the residual list entries to the coded halves. + let mut next_block = 0usize; + let halves = if sub_h == 1 { 2 } else { 1 }; + for (v, &coded) in coded_halves.iter().enumerate().take(halves) { + let (mut res, n) = if coded { + let Some(rb) = blocks.get(next_block) else { + break; + }; + next_block += 1; + let n = rb.size(); + ( + inter_residual_block(params, rb, cidx, qp, transquant_bypass)?, + n, + ) + } else if ccp.is_some() { + // §8.5.4.3 step 5 applies to every chroma transform block + // of the unit; a cbf-clear block starts from zeros. + (vec![0i32; n_tbs_c * n_tbs_c], n_tbs_c) + } else { + continue; + }; + if let Some(c) = ccp { + apply_cross_comp_pred( + &mut res, + c.luma_residual, + c.res_scale_val, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + } + let by = if v == 1 { yc + n } else { yc }; + plane.write_block(xc, by, n, &res); + } + Ok(()) +} + +/// §8.6.2 — dequantize + inverse-transform one residual block in the +/// `MODE_INTER` path (the §8.6.4 `trType` selection always picks DCT-II for +/// inter, vs. the §8.6.4.1 DST-VII gate that only fires for 4×4 luma intra). +fn inter_residual_block( + params: &ReconParams, + rb: &crate::residual::ResidualBlock, + cidx: TfComponent, + qp: u32, + transquant_bypass: bool, +) -> Result, ReconError> { + let n_tbs = rb.size(); + let bit_depth = match cidx { + TfComponent::Luma => params.bit_depth_luma, + TfComponent::Cb | TfComponent::Cr => params.bit_depth_chroma, + }; + let bp = BlockParams { + n_tbs, + q_p: qp, + component: cidx, + pred_mode: PredMode::Inter, + bit_depth, + extended_precision: params.extended_precision, + transquant_bypass, + transform_skip: rb.transform_skip, + transform_skip_rotation_enabled: params.transform_skip_rotation_enabled, + }; + let m = scaling_matrix(params, n_tbs, PredMode::Inter, cidx, rb.transform_skip); + let mut r = residual_block(&rb.levels, m, bp)?; + // §8.5.4.2 step 3 / §8.5.4.3 step 4: when explicit_rdpcm_flag is 1, + // the §8.6.5 directional residual modification is invoked with + // mDir = explicit_rdpcm_dir_flag (0 horizontal, 1 vertical). + if rb.explicit_rdpcm_flag { + rdpcm_accumulate(&mut r, n_tbs, rb.explicit_rdpcm_dir_flag); + } + Ok(r) +} + +/// Per-picture intra-reconstruction neighbour state — the §8.4.2 +/// `IntraPredModeY` field plus the §6.4.1 picture tiling that resolves +/// neighbour availability. +/// +/// One [`ReconCtx`] is shared across every CTU of a slice so the §8.4.2 +/// most-probable-mode derivation sees the actual left / above neighbour +/// modes (rather than the flat-single-CU `INTRA_DC` assumption). Build it +/// with [`ReconCtx::new`]; reconstruct each CTU in tile-scan order with +/// [`reconstruct_intra_ctu_ctx`]. +#[derive(Debug)] +pub struct ReconCtx { + field: IntraModeField, + tiling: PictureTiling, + /// `SliceAddrRs[ ctbAddrRs ]` — the raster address of the first CTB + /// of the independent slice segment that owns each CTB. All-zero for a + /// single-slice picture; the multi-slice driver populates it so the + /// §6.4.1 z-scan availability denies neighbours across slice + /// boundaries. + slice_addr_rs: Vec, + /// §8.6.1 per-picture luma-QP derivation state (`None` for the + /// standalone per-CTU helpers, which fall back to the + /// `qPY_PRED == SliceQpY` single-QG shortcut). + qp: Option, + /// `constrained_intra_pred_flag` (§8.4.4.2.1) — when set, reference + /// samples from non-`MODE_INTRA` coding units are "not available + /// for intra prediction". + constrained_intra: bool, +} + +/// §8.6.1 quantization-parameter derivation state: the per-4×4 `QpY` +/// map (feeding the `qPY_A` / `qPY_B` neighbour reads and the §8.7.2 +/// deblocking QP), the decode-order `qPY_PREV` thread, and the current +/// quantization group. +#[derive(Debug)] +struct QpState { + /// Per-4×4-cell `QpY`. + map: Vec, + w_cells: usize, + h_cells: usize, + /// `Log2MinCuQpDeltaSize`. + qg_log2: u32, + /// `CtbLog2SizeY` (the §8.6.1 same-CTB gate on `qPY_A` / `qPY_B`). + ctb_log2: u32, + /// `SliceQpY`. + slice_qp_y: i32, + /// `QpBdOffsetY`. + qp_bd_offset_y: i32, + /// `QpY` of the most recent coding unit (becomes `qPY_PREV` when the + /// next quantization group starts). `None` before the first QG of + /// the slice. + last_cu_qp: Option, + /// The current quantization group's grid cell + its `qPY_PRED`. + cur_qg: Option<(usize, usize)>, + cur_pred: i32, + /// `CuQpDeltaVal` accumulated for the current QG (0 until a CU in + /// the group carries the decoded delta). + cur_delta: i32, + /// The most recent CU origin `derive_cu_qp` resolved (idempotence + /// guard: the intra path may query the same CU twice). + last_cu: Option<(usize, usize)>, + last_qp: i32, +} + +impl QpState { + fn cell(&self, x: usize, y: usize) -> usize { + (y >> 2).min(self.h_cells - 1) * self.w_cells + (x >> 2).min(self.w_cells - 1) + } + + fn qp_at(&self, x: usize, y: usize) -> i32 { + i32::from(self.map[self.cell(x, y)]) + } +} + +impl ReconCtx { + /// Build the neighbour context for a `pic_width` × `pic_height` luma + /// picture with the given `CtbLog2SizeY` / `MinTbLog2SizeY` and tile + /// layout. + /// + /// # Errors + /// Propagates [`crate::availability::AvailabilityError`] (wrapped in + /// [`ReconError::Tiling`]) when the geometry is degenerate. + pub fn new( + pic_width_luma: usize, + pic_height_luma: usize, + ctb_log2_size_y: u32, + min_tb_log2_size_y: u32, + tiles: &crate::availability::TilingParams, + ) -> Result { + let ctb_size = 1usize << ctb_log2_size_y; + let pic_w_ctbs = pic_width_luma.div_ceil(ctb_size) as u32; + let pic_h_ctbs = pic_height_luma.div_ceil(ctb_size) as u32; + let tiling = PictureTiling::new( + pic_w_ctbs, + pic_h_ctbs, + pic_width_luma as u32, + pic_height_luma as u32, + ctb_log2_size_y, + min_tb_log2_size_y, + tiles, + ) + .map_err(ReconError::Tiling)?; + Ok(Self { + field: IntraModeField::new(pic_width_luma, pic_height_luma, ctb_log2_size_y), + tiling, + slice_addr_rs: vec![0u32; (pic_w_ctbs * pic_h_ctbs) as usize], + qp: None, + constrained_intra: false, + }) + } + + /// Enable the §8.4.4.2.1 `constrained_intra_pred_flag` gate: + /// reference samples whose covering coding unit is not + /// `MODE_INTRA` are treated as "not available for intra + /// prediction" (they substitute per §8.4.4.2.2). + pub fn set_constrained_intra(&mut self, on: bool) { + self.constrained_intra = on; + } + + /// Initialize the §8.6.1 per-picture QP-derivation state. + /// + /// `slice_qp_y` is `SliceQpY`; `qg_log2` is `Log2MinCuQpDeltaSize` + /// (§7.4.3.3.1: `CtbLog2SizeY − diff_cu_qp_delta_depth`); + /// `qp_bd_offset_y` is `QpBdOffsetY`. Must be called before the CU + /// walk when the picture carries `cu_qp_delta` values; without it + /// the per-CU derivation falls back to the `qPY_PRED == SliceQpY` + /// single-QG shortcut. + pub fn init_qp_state(&mut self, slice_qp_y: i32, qg_log2: u32, qp_bd_offset_y: i32) { + // The 4×4 cell grid matches the intra-mode field's min-block grid. + let w_cells = self.field.w_blocks(); + let h_cells = self.field.h_blocks(); + self.qp = Some(QpState { + map: vec![slice_qp_y as i8; w_cells * h_cells], + w_cells, + h_cells, + qg_log2, + ctb_log2: self.field.ctb_log2(), + slice_qp_y, + qp_bd_offset_y, + last_cu_qp: None, + cur_qg: None, + cur_pred: slice_qp_y, + cur_delta: 0, + last_cu: None, + last_qp: slice_qp_y, + }); + } + + /// §8.6.1 — derive `QpY` for the coding unit at `(x_cb, y_cb)` of + /// side `1 << log2_cb_size`, whose transform tree carries + /// `cu_delta` (`Some` when a `cu_qp_delta` was decoded in it). + /// + /// Must be invoked once per coding unit **in decode order**; the + /// derivation threads `qPY_PREV` across quantization groups and + /// stamps the per-4×4 QP map. Re-invoking for the same CU origin + /// returns the cached value. Returns the fallback single-QG value + /// when [`Self::init_qp_state`] was not called. + pub fn derive_cu_qp( + &mut self, + params: &ReconParams, + x_cb: usize, + y_cb: usize, + log2_cb_size: u32, + cu_delta: Option, + ) -> i32 { + let Some(_) = self.qp else { + return fallback_qp_y(params, cu_delta.unwrap_or(0)); + }; + // Idempotence: the picture drivers may resolve the same CU twice + // (once for the deblock descriptor, once inside the intra path). + if let Some(qp) = self + .qp + .as_ref() + .and_then(|q| (q.last_cu == Some((x_cb, y_cb))).then_some(q.last_qp)) + { + return qp; + } + // The quantization-group origin (§8.6.1): xQg = xCb − (xCb & + // ((1 << Log2MinCuQpDeltaSize) − 1)). + let (qg_log2, cur_qg, ctb_log2) = { + let q = self.qp.as_ref().unwrap(); + (q.qg_log2, q.cur_qg, q.ctb_log2) + }; + let x_qg = x_cb & !((1usize << qg_log2) - 1); + let y_qg = y_cb & !((1usize << qg_log2) - 1); + let qg = (x_qg >> qg_log2, y_qg >> qg_log2); + if cur_qg != Some(qg) { + // New quantization group: derive qPY_PRED (steps 1–4). + let q = self.qp.as_ref().unwrap(); + // Step 1 — qPY_PREV (first QG in slice ⇒ SliceQpY; the tile + // / WPP CTB-row resets are follow-ups of those subsystems). + let qp_prev = q.last_cu_qp.unwrap_or(q.slice_qp_y); + // Step 2 — qPY_A from (xQg − 1, yQg), same-CTB gated. + let same_ctb_a = x_qg > 0 + && (x_qg - 1) >> ctb_log2 == x_cb >> ctb_log2 + && y_qg >> ctb_log2 == y_cb >> ctb_log2; + let avail_a = + x_qg > 0 && same_ctb_a && self.available(x_cb, y_cb, x_qg as i64 - 1, y_qg as i64); + let q = self.qp.as_ref().unwrap(); + let qp_a = if avail_a { + q.qp_at(x_qg - 1, y_qg) + } else { + qp_prev + }; + // Step 3 — qPY_B from (xQg, yQg − 1), same-CTB gated. + let same_ctb_b = y_qg > 0 + && (y_qg - 1) >> ctb_log2 == y_cb >> ctb_log2 + && x_qg >> ctb_log2 == x_cb >> ctb_log2; + let avail_b = + y_qg > 0 && same_ctb_b && self.available(x_cb, y_cb, x_qg as i64, y_qg as i64 - 1); + let q = self.qp.as_mut().unwrap(); + let qp_b = if avail_b { + q.qp_at(x_qg, y_qg - 1) + } else { + qp_prev + }; + // Step 4 — qPY_PRED (eq. 8-282). + q.cur_pred = (qp_a + qp_b + 1) >> 1; + q.cur_qg = Some(qg); + q.cur_delta = 0; + } + let q = self.qp.as_mut().unwrap(); + // §7.4.9.14: CuQpDeltaVal applies from the CU that decodes it to + // the end of the quantization group. + if let Some(delta) = cu_delta { + q.cur_delta = delta; + } + // Eq. 8-283. + let modulus = 52 + q.qp_bd_offset_y; + let qp_y = (q.cur_pred + q.cur_delta + 52 + 2 * q.qp_bd_offset_y).rem_euclid(modulus) + - q.qp_bd_offset_y; + // Stamp the CU area for later qPY_A / qPY_B reads + deblocking. + let n = 1usize << log2_cb_size; + for y in (y_cb..(y_cb + n).min(q.h_cells * 4)).step_by(4) { + for x in (x_cb..(x_cb + n).min(q.w_cells * 4)).step_by(4) { + let idx = q.cell(x, y); + q.map[idx] = qp_y as i8; + } + } + q.last_cu_qp = Some(qp_y); + q.last_cu = Some((x_cb, y_cb)); + q.last_qp = qp_y; + qp_y + } + + /// The `SliceAddrRs` of the CTB containing the luma position. + #[must_use] + pub fn slice_addr_rs_of_luma(&self, x_luma: usize, y_luma: usize) -> u32 { + let ctb_log2 = self.field.ctb_log2(); + let w = self.tiling.pic_width_in_ctbs_y() as usize; + let rs = (y_luma >> ctb_log2) * w + (x_luma >> ctb_log2); + self.slice_addr_of(rs as u32) + } + + /// The §6.5.1 `TileId` of the CTB containing the luma position. + #[must_use] + pub fn tile_id_of_luma(&self, x_luma: usize, y_luma: usize) -> u32 { + let ctb_log2 = self.field.ctb_log2(); + let w = self.tiling.pic_width_in_ctbs_y() as usize; + let rs = (y_luma >> ctb_log2) * w + (x_luma >> ctb_log2); + self.tiling + .tile_id(self.tiling.ctb_addr_rs_to_ts(rs as u32)) + } + + /// The per-4×4-cell §8.6.1 `QpY` map (for the §8.7.2 per-position + /// `QpQ` / `QpP` reads). `None` when no QP state is initialized. + #[must_use] + pub fn qp_cells(&self) -> Option<(&[i8], usize)> { + self.qp.as_ref().map(|q| (q.map.as_slice(), q.w_cells)) + } + + /// §8.6.1 step-1 — reset `qPY_PREV` to `SliceQpY` (invoked at the + /// first quantization group of a CTB row when + /// `entropy_coding_sync_enabled_flag` is set, and at tile starts). + pub fn reset_qp_prev(&mut self) { + if let Some(q) = self.qp.as_mut() { + q.last_cu_qp = None; + } + } + + /// The §8.6.1-derived `QpY` recorded at a luma location (for the + /// deblocking p-side QP). Returns `None` when no QP state is + /// initialized. + #[must_use] + pub fn qp_y_at(&self, x_luma: usize, y_luma: usize) -> Option { + self.qp.as_ref().map(|q| q.qp_at(x_luma, y_luma)) + } + + /// Debug: the recon-side §8.4.2 derived mode recorded at a luma + /// location. + #[doc(hidden)] + #[must_use] + pub fn debug_mode_at(&self, x_luma: usize, y_luma: usize) -> Option { + self.field.recorded_mode(x_luma, y_luma) + } + + /// Set the per-CTB `SliceAddrRs` map (one entry per CTB raster + /// address, `PicSizeInCtbsY` long). Each entry is the raster address + /// of the first CTB of the independent slice segment owning that CTB. + /// Used by the multi-slice driver so the §6.4.1 z-scan availability + /// denies cross-slice neighbours. + /// + /// # Panics + /// Panics if `map.len()` is not `PicSizeInCtbsY`. + pub fn set_slice_addr_rs(&mut self, map: Vec) { + assert_eq!( + map.len(), + self.slice_addr_rs.len(), + "SliceAddrRs map must be PicSizeInCtbsY long" + ); + self.slice_addr_rs = map; + } + + /// `SliceAddrRs[ ctbAddrRs ]` for the CTB raster address. + #[inline] + fn slice_addr_of(&self, ctb_rs: u32) -> u32 { + self.slice_addr_rs + .get(ctb_rs as usize) + .copied() + .unwrap_or(0) + } + + /// §6.4.1 z-scan availability of the neighbour luma location + /// `( x_nb, y_nb )` for the current prediction block at + /// `( x_curr, y_curr )`, consulting the per-CTB `SliceAddrRs` map so + /// neighbours in a different slice segment are unavailable. + fn available(&self, x_curr: usize, y_curr: usize, x_nb: i64, y_nb: i64) -> bool { + self.tiling.z_scan_availability( + x_curr as u32, + y_curr as u32, + x_nb as i32, + y_nb as i32, + |ctb_rs| self.slice_addr_of(ctb_rs), + ) + } + + /// §8.4.4.2.1 reference-sample availability for one neighbour sample of + /// a transform block. `(x_tb, y_tb)` is the current transform block's + /// **plane** top-left and `(x_ref, y_ref)` the neighbour's **plane** + /// coordinates; `(sub_w, sub_h)` is the plane's `(SubWidthC, SubHeightC)` + /// (`(1, 1)` for luma). The §6.4.1 z-scan availability is evaluated on + /// the corresponding luma locations. + fn ref_sample_available( + &self, + x_tb: usize, + y_tb: usize, + x_ref: i64, + y_ref: i64, + sub_w: usize, + sub_h: usize, + ) -> bool { + if x_ref < 0 || y_ref < 0 { + return false; + } + // Map plane coordinates to luma for the §6.4.1 test. + let x_curr_luma = x_tb * sub_w; + let y_curr_luma = y_tb * sub_h; + let x_nb_luma = (x_ref as usize * sub_w) as i64; + let y_nb_luma = (y_ref as usize * sub_h) as i64; + if !self.available(x_curr_luma, y_curr_luma, x_nb_luma, y_nb_luma) { + return false; + } + // §8.4.4.2.1: CuPredMode[ xNbY ][ yNbY ] != MODE_INTRA with + // constrained_intra_pred_flag == 1 ⇒ not available. + !self.constrained_intra + || self + .field + .is_intra_at(x_nb_luma as usize, y_nb_luma as usize) + } + + /// Borrow the §6.4.1 / §6.5 picture tiling (the inter driver's §6.4.2 + /// prediction-block availability reads it). + #[must_use] + pub fn tiling(&self) -> &PictureTiling { + &self.tiling + } + + /// `SliceAddrRs[ ctbAddrRs ]` for the CTB containing the luma location + /// (the inter driver's §6.4.2 availability uses the same map). + #[must_use] + pub fn slice_addr_rs_of(&self, ctb_rs: u32) -> u32 { + self.slice_addr_of(ctb_rs) + } + + /// Test-only: the §8.4.2 `IntraPredModeY` recorded at a luma location. + #[cfg(test)] + #[must_use] + pub(crate) fn recorded_mode(&self, x_luma: usize, y_luma: usize) -> Option { + self.field.recorded_mode(x_luma, y_luma) + } +} + +/// Reconstruct one decoded coding tree unit's intra samples into `pic`, +/// driving the §8.4.2 most-probable-mode derivation off the shared +/// [`ReconCtx`] neighbour field. CTUs must be reconstructed in tile-scan +/// order so each one's left / above neighbours are already recorded. +/// +/// # Errors +/// [`ReconError::InterNotSupported`] if any leaf coding unit is inter; +/// [`ReconError::IntraPred`] / [`ReconError::Transform`] on a primitive +/// failure. +pub fn reconstruct_intra_ctu_ctx( + pic: &mut Picture, + params: &ReconParams, + ctx: &mut ReconCtx, + ctu: &CodingTreeUnit, +) -> Result<(), ReconError> { + reconstruct_quadtree(pic, params, ctx, &ctu.quadtree) +} + +/// Reconstruct one **intra** leaf coding unit into `pic`, recording its +/// §8.4.2 `IntraPredModeY` into the shared [`ReconCtx`] neighbour field. +/// +/// This is the per-CU entry the §8.5 picture-level inter driver calls for +/// an intra coding unit embedded in a P / B slice (mixed-mode pictures); +/// the inter coding units of the same picture go through +/// [`crate::inter_recon::resolve_and_reconstruct_inter_cu`]. +/// +/// # Errors +/// [`ReconError::IntraPred`] / [`ReconError::Transform`] on a primitive +/// failure; [`ReconError::InterNotSupported`] if `cu` is not intra. +pub fn reconstruct_intra_cu_ctx( + pic: &mut Picture, + params: &ReconParams, + ctx: &mut ReconCtx, + cu: &CodingUnit, +) -> Result<(), ReconError> { + reconstruct_cu(pic, params, ctx, cu) +} + +/// Reconstruct one decoded coding tree unit's intra samples into `pic`. +/// `(ctb_x, ctb_y)` is the CTB's luma top-left position. +/// +/// This single-CTU convenience builds a fresh single-CTU [`ReconCtx`] +/// internally — its neighbours are the CTU's own already-reconstructed +/// blocks, so a multi-CTU picture must instead share one [`ReconCtx`] +/// across CTUs via [`reconstruct_intra_ctu_ctx`]. +/// +/// # Errors +/// [`ReconError::InterNotSupported`] if any leaf coding unit is inter; +/// [`ReconError::IntraPred`] / [`ReconError::Transform`] on a primitive +/// failure. +pub fn reconstruct_intra_ctu( + pic: &mut Picture, + params: &ReconParams, + ctu: &CodingTreeUnit, +) -> Result<(), ReconError> { + // A single CTB covers the whole synthetic picture for this path; the + // CTB log2 size is the smallest power of two covering the picture. + let max_dim = pic.width_luma().max(pic.height_luma()).max(1); + let ctb_log2 = (usize::BITS - (max_dim - 1).leading_zeros()).max(4); + let min_tb_log2 = 2; + let mut ctx = ReconCtx::new( + pic.width_luma(), + pic.height_luma(), + ctb_log2, + min_tb_log2, + &crate::availability::TilingParams::single_tile(), + )?; + reconstruct_intra_ctu_ctx(pic, params, &mut ctx, ctu) +} + +/// One slice segment's §7.4.7.1 `SliceAddrRs`-derivation inputs: the +/// `slice_segment_address` (raster CTB address of its first CTB) and the +/// `dependent_slice_segment_flag`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SliceSegmentBoundary { + /// `slice_segment_address` (raster CTB address). + pub slice_segment_address: u32, + /// `dependent_slice_segment_flag`. + pub dependent: bool, +} + +/// §7.4.7.1 — build the per-CTB `SliceAddrRs[ ctbAddrRs ]` map for a +/// picture from its ordered slice segments. +/// +/// `segments` are the picture's coded slice segments **in decode +/// (tile-scan-start) order**; each carries its `slice_segment_address` +/// (raster) and `dependent_slice_segment_flag`. An independent segment +/// (`dependent == false`) sets `SliceAddrRs = slice_segment_address`; a +/// dependent segment inherits the active independent segment's +/// `SliceAddrRs`. CTBs are partitioned in tile-scan order, so the run of +/// CTBs owned by a segment starts at `CtbAddrRsToTs[slice_segment_address]` +/// and extends until the next segment's tile-scan start. +/// +/// Returns a `PicSizeInCtbsY`-long vector indexed by CTB **raster** +/// address. CTBs before the first segment (which shouldn't happen for a +/// well-formed picture, since the first segment starts at address 0) carry +/// `SliceAddrRs = 0`. +#[must_use] +pub fn build_slice_addr_map(tiling: &PictureTiling, segments: &[SliceSegmentBoundary]) -> Vec { + let pic_size = (tiling.pic_width_in_ctbs_y() * tiling.pic_height_in_ctbs_y()) as usize; + let mut map = vec![0u32; pic_size]; + + // Resolve each segment's SliceAddrRs and its tile-scan start address. + // (slice_addr_rs, ctb_addr_ts_start) + let mut resolved: Vec<(u32, u32)> = Vec::with_capacity(segments.len()); + let mut active_slice_addr_rs = 0u32; + for seg in segments { + let slice_addr_rs = if seg.dependent { + active_slice_addr_rs + } else { + seg.slice_segment_address + }; + active_slice_addr_rs = slice_addr_rs; + let ts_start = tiling.ctb_addr_rs_to_ts(seg.slice_segment_address); + resolved.push((slice_addr_rs, ts_start)); + } + // Sort by tile-scan start so the run boundaries are monotonic. + resolved.sort_by_key(|&(_, ts)| ts); + + // Walk every CTB in tile-scan order, assigning the SliceAddrRs of the + // latest segment whose tile-scan start is <= the CTB's tile-scan addr. + for ts in 0..pic_size as u32 { + // The owning segment is the last one with ts_start <= ts. + let owner = resolved + .iter() + .rev() + .find(|&&(_, ts_start)| ts_start <= ts) + .map_or(0, |&(addr, _)| addr); + let rs = tiling.ctb_addr_ts_to_rs(ts); + map[rs as usize] = owner; + } + map +} + +/// Picture-level intra decode parameters — the SPS/PPS/slice constants the +/// multi-CTU driver [`reconstruct_intra_picture`] needs beyond the +/// per-block [`ReconParams`]. +#[derive(Debug, Clone)] +pub struct IntraPictureParams { + /// `CtbLog2SizeY`. + pub ctb_log2_size_y: u32, + /// `MinTbLog2SizeY` (= `log2_min_luma_transform_block_size_minus2 + 2`). + pub min_tb_log2_size_y: u32, + /// The active PPS tile layout (§6.5.1). + pub tiles: crate::availability::TilingParams, + /// `slice_sao_luma_flag` (§8.7.3.1 luma gate). + pub slice_sao_luma_flag: bool, + /// `slice_sao_chroma_flag` (§8.7.3.1 chroma gate). + pub slice_sao_chroma_flag: bool, + /// `log2_sao_offset_scale_luma` (§7.4.3.3.2; 0 for 8-bit Main). + pub log2_sao_offset_scale_luma: u8, + /// `log2_sao_offset_scale_chroma`. + pub log2_sao_offset_scale_chroma: u8, +} + +/// One decoded CTU positioned in the picture for the multi-CTU driver. +#[derive(Debug)] +pub struct PlacedCtu<'a> { + /// The CTB's luma top-left `( x_ctb, y_ctb )`. + pub x_ctb: u32, + /// The CTB's luma top-left `( x_ctb, y_ctb )`. + pub y_ctb: u32, + /// `SliceAddrRs` — the raster address of the first CTB of the + /// independent slice segment that owns this CTB. `0` for a + /// single-slice picture; the multi-slice driver + /// ([`reconstruct_intra_multislice_picture`]) sets it to the slice's + /// `slice_segment_address` so cross-slice neighbours are denied. + pub slice_addr_rs: u32, + /// The decoded coding tree unit. + pub ctu: &'a CodingTreeUnit, +} + +/// Reconstruct a full intra picture from its decoded CTUs and apply the +/// §8.7.3 sample-adaptive-offset in-loop filter. +/// +/// `ctus` are the picture's decoded coding tree units **in tile-scan +/// (decode) order** — each one's left / above neighbours must already be +/// reconstructed when it is processed, which the tile-scan order +/// guarantees. The driver shares one [`ReconCtx`] across all CTUs so the +/// §8.4.2 most-probable-mode derivation sees the true neighbour modes, then +/// resolves each CTB's [`crate::sao::ResolvedSao`] (honouring +/// `sao_merge_left_flag` / `sao_merge_up_flag`) and runs +/// [`crate::sao::apply_sao_picture`]. +/// +/// The returned picture is the §8.7.3 SAO output (the in-loop deblocking +/// filter, §8.7.2, is applied by the caller via +/// [`crate::deblock::deblock_picture`] before SAO when deblocking is +/// enabled; this driver covers the recon + SAO stages). +/// +/// # Errors +/// Propagates [`ReconError`] from the per-CTU reconstruction (including +/// [`ReconError::Tiling`] for degenerate geometry). +pub fn reconstruct_intra_picture( + pic_width_luma: usize, + pic_height_luma: usize, + params: &ReconParams, + pic_params: &IntraPictureParams, + ctus: &[PlacedCtu<'_>], +) -> Result { + let mut pic = Picture::new( + pic_width_luma, + pic_height_luma, + params.chroma_array_type, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + let mut ctx = ReconCtx::new( + pic_width_luma, + pic_height_luma, + pic_params.ctb_log2_size_y, + pic_params.min_tb_log2_size_y, + &pic_params.tiles, + )?; + + let ctb_size = 1usize << pic_params.ctb_log2_size_y; + let pic_w_ctbs = pic_width_luma.div_ceil(ctb_size); + let pic_h_ctbs = pic_height_luma.div_ceil(ctb_size); + + // Build the per-CTB SliceAddrRs map from the placed CTUs (default 0 + // for any CTB not covered) and feed it to the neighbour context so the + // §6.4.1 z-scan availability denies cross-slice neighbours. + let mut slice_addr_map = vec![0u32; pic_w_ctbs * pic_h_ctbs]; + for placed in ctus { + let rx = (placed.x_ctb as usize) >> pic_params.ctb_log2_size_y; + let ry = (placed.y_ctb as usize) >> pic_params.ctb_log2_size_y; + slice_addr_map[ry * pic_w_ctbs + rx] = placed.slice_addr_rs; + } + ctx.set_slice_addr_rs(slice_addr_map.clone()); + + // §8.7.3.1 resolved-SAO grid (raster order), default all-off so a CTU + // not present in `ctus` leaves its CTB unmodified. + let mut sao_grid = vec![crate::sao::ResolvedSao::off(); pic_w_ctbs * pic_h_ctbs]; + + for placed in ctus { + reconstruct_intra_ctu_ctx(&mut pic, params, &mut ctx, placed.ctu)?; + + // §7.4.9.3 SAO merge: resolve against the already-resolved left / + // above CTB in the grid, but only when that neighbour is in the + // SAME slice segment (the merge candidate availability follows the + // §6.4.1 slice-boundary rule). A neighbour in a different slice is + // not a merge candidate. + let rx = (placed.x_ctb as usize) >> pic_params.ctb_log2_size_y; + let ry = (placed.y_ctb as usize) >> pic_params.ctb_log2_size_y; + let here = slice_addr_map[ry * pic_w_ctbs + rx]; + if let Some(sao_params) = &placed.ctu.sao { + let left = (rx > 0 && slice_addr_map[ry * pic_w_ctbs + (rx - 1)] == here) + .then(|| sao_grid[ry * pic_w_ctbs + (rx - 1)]); + let above = (ry > 0 && slice_addr_map[(ry - 1) * pic_w_ctbs + rx] == here) + .then(|| sao_grid[(ry - 1) * pic_w_ctbs + rx]); + sao_grid[ry * pic_w_ctbs + rx] = crate::sao::ResolvedSao::resolve( + sao_params, + left.as_ref(), + above.as_ref(), + pic_params.log2_sao_offset_scale_luma, + pic_params.log2_sao_offset_scale_chroma, + ); + } + } + + // §8.7.3.1 — apply SAO across the whole picture (no-op when both slice + // SAO flags are clear or every CTB resolved to type 0). + let filtered = crate::sao::apply_sao_picture( + &pic, + &sao_grid, + pic_params.ctb_log2_size_y, + params.chroma_array_type, + pic_params.slice_sao_luma_flag, + pic_params.slice_sao_chroma_flag, + ); + Ok(filtered) +} + +fn reconstruct_quadtree( + pic: &mut Picture, + params: &ReconParams, + ctx: &mut ReconCtx, + qt: &CodingQuadtree, +) -> Result<(), ReconError> { + match qt { + CodingQuadtree::Split(children) => { + for child in children { + reconstruct_quadtree(pic, params, ctx, child)?; + } + Ok(()) + } + CodingQuadtree::Leaf(cu) => reconstruct_cu(pic, params, ctx, cu), + } +} + +/// §8.4.2 — derive `IntraPredModeY` for one luma prediction block at +/// `( x_pb, y_pb )` of side `n_pb`, consulting the [`ReconCtx`] neighbour +/// field for the candidate modes, then record it back into the field. +fn derive_and_record_luma_mode( + ctx: &mut ReconCtx, + x_pb: usize, + y_pb: usize, + n_pb: usize, + luma_mode: &IntraLumaMode, + pcm_flag: bool, +) -> u8 { + // Step 1 / 2 — candidate modes from the left (A) and above (B) + // neighbours, gated on §6.4.1 z-scan availability. + let avail_a = ctx.available(x_pb, y_pb, x_pb as i64 - 1, y_pb as i64); + let avail_b = ctx.available(x_pb, y_pb, x_pb as i64, y_pb as i64 - 1); + let cand_a = ctx + .field + .cand_intra_pred_mode(x_pb, y_pb, Neighbour::Left, avail_a); + let cand_b = ctx + .field + .cand_intra_pred_mode(x_pb, y_pb, Neighbour::Above, avail_b); + + // Step 3 / 4 — candModeList + the prev_intra_luma_pred_flag selection. + let cand_list = intra_luma_cand_mode_list(cand_a, cand_b); + let source = luma_intra_mode_source_from_flag(u8::from(luma_mode.prev_intra_luma_pred_flag)); + let field_val = match source { + LumaIntraModeSource::Mpm => luma_mode.mpm_idx.unwrap_or(0), + LumaIntraModeSource::Remaining => luma_mode.rem_intra_luma_pred_mode.unwrap_or(0), + }; + let mode = derive_intra_pred_mode_y(cand_list, source, field_val); + ctx.field.record_intra_pb(x_pb, y_pb, n_pb, mode, pcm_flag); + mode +} + +/// Reconstruct one leaf coding unit. Only intra CUs are handled; each luma +/// prediction block's `IntraPredModeY` is derived per §8.4.2 from the +/// [`ReconCtx`] neighbour field (most-probable-mode), and chroma +/// `IntraPredModeC` per §8.4.3 from the first PB's luma mode. +/// §8.4.1 — write a PCM coding unit's (already scaled) samples into +/// the picture: `SL[xCb+i][yCb+j] = pcm_sample_luma[nCbS*j + i] << +/// (BitDepthY − PcmBitDepthY)` (equation 8-12; the shift was applied +/// at parse time) and the chroma analogues. +/// §8.4.4.2.7 — write a palette CU's reconstructed components into +/// the picture. `qp_y` is the §8.6.1-derived QpY of the CU; per- +/// component `Qp′` values (eq. 8-73..8-75) feed the escape +/// dequantization. +fn write_palette_cu( + pic: &mut Picture, + params: &ReconParams, + pal: &crate::palette::PaletteCu, + x_cb: usize, + y_cb: usize, + qp_y: i32, + transquant_bypass: bool, +) { + // §7.4.9.10 — a chroma_qp_offset( ) parsed inside + // palette_coding( ) updates the slice-wide state exactly like a + // transform unit's. + if let Some(off) = &pal.cu_chroma_qp_offset { + apply_cu_chroma_qp_offset(params, off); + } + let qp_luma = luma_qp(params, qp_y) as i32; + crate::palette::reconstruct_palette_component( + pal, + 0, + 1, + 1, + qp_luma, + u32::from(params.bit_depth_luma), + transquant_bypass, + |x, y, v| pic.set_sample(Plane::Luma, x_cb + x, y_cb + y, v), + ); + if params.chroma_array_type != 0 { + let (sub_w, sub_h) = sub_wh_c(params.chroma_array_type); + let (cx, cy) = (x_cb / sub_w, y_cb / sub_h); + for (c_idx, plane, comp) in [ + (1usize, Plane::Cb, TfComponent::Cb), + (2, Plane::Cr, TfComponent::Cr), + ] { + let qp_c = chroma_qp(params, qp_y, comp) as i32; + crate::palette::reconstruct_palette_component( + pal, + c_idx, + sub_w, + sub_h, + qp_c, + u32::from(params.bit_depth_chroma), + transquant_bypass, + |x, y, v| pic.set_sample(plane, cx + x, cy + y, v), + ); + } + } +} + +fn write_pcm_cu( + pic: &mut Picture, + chroma_array_type: u8, + x_cb: usize, + y_cb: usize, + n_cb: usize, + pcm: &crate::slice_data::PcmSamples, +) { + for j in 0..n_cb { + for i in 0..n_cb { + pic.set_sample( + Plane::Luma, + x_cb + i, + y_cb + j, + i32::from(pcm.luma[n_cb * j + i]), + ); + } + } + if chroma_array_type != 0 { + let (sub_w, sub_h) = sub_wh_c(chroma_array_type); + let (cw, ch) = (n_cb / sub_w, n_cb / sub_h); + let (cx, cy) = (x_cb / sub_w, y_cb / sub_h); + for (plane, samples) in [(Plane::Cb, &pcm.cb), (Plane::Cr, &pcm.cr)] { + for j in 0..ch { + for i in 0..cw { + pic.set_sample(plane, cx + i, cy + j, i32::from(samples[cw * j + i])); + } + } + } + } +} + +fn reconstruct_cu( + pic: &mut Picture, + params: &ReconParams, + ctx: &mut ReconCtx, + cu: &CodingUnit, +) -> Result<(), ReconError> { + if matches!(cu.cu_pred_mode, CuPredMode::Inter | CuPredMode::Skip) { + // Record the inter CU so a later intra block's §8.4.2 neighbour + // derivation maps it to INTRA_DC, then signal the inter path is + // unhandled by this driver. + ctx.field.record_non_intra_cu( + cu.x0 as usize, + cu.y0 as usize, + 1usize << cu.log2_cb_size, + cu.cu_pred_mode, + ); + return Err(ReconError::InterNotSupported); + } + + let n_cb = 1usize << cu.log2_cb_size; + let x_cb = cu.x0 as usize; + let y_cb = cu.y0 as usize; + + if cu.pcm_flag { + // §8.4.1 — PCM reconstruction: the parsed (already + // bit-depth-scaled, equation 8-12) samples ARE the + // reconstructed picture; stamp the mode field so neighbours + // see a written block (→ DC). + ctx.field.record_intra_pb(x_cb, y_cb, n_cb, INTRA_DC, true); + if let Some(pcm) = cu.pcm.as_ref() { + write_pcm_cu(pic, params.chroma_array_type, x_cb, y_cb, n_cb, pcm); + } + return Ok(()); + } + + if let Some(pal) = cu.palette.as_deref() { + // §8.4.4.2.7 — palette-mode reconstruction. A palette CU has + // no IntraPredModeY; neighbours derive INTRA_DC (the PCM + // convention). + ctx.field.record_intra_pb(x_cb, y_cb, n_cb, INTRA_DC, true); + // §8.6.1 QP derivation feeds the escape dequantization; the + // delta_qp( ) arrives inside palette_coding( ). + let cu_delta = pal.cu_qp_delta.as_ref().map(|d| d.value); + let qp_y = ctx.derive_cu_qp(params, x_cb, y_cb, cu.log2_cb_size, cu_delta); + write_palette_cu( + pic, + params, + pal, + x_cb, + y_cb, + qp_y, + cu.cu_transquant_bypass_flag, + ); + return Ok(()); + } + + // §7.4.9.5: PART_NxN intra splits the CU into four nCbS/2 luma PBs in + // raster order; PART_2Nx2N is one PB covering the CU. + let is_nxn = cu.part_mode == PartMode::PartNxN; + let n_pb = if is_nxn { n_cb / 2 } else { n_cb }; + let pb_origins: &[(usize, usize)] = if is_nxn { + &[(0, 0), (1, 0), (0, 1), (1, 1)] + } else { + &[(0, 0)] + }; + + // §8.4.2 — derive (and record) each luma PB's IntraPredModeY. The + // §8.4.3 chroma mode uses the CU-corner PB (blkIdx 0) for the + // ChromaArrayType != 3 single-chroma-block case. + let mut pb_modes = [INTRA_DC; 4]; + for (i, &(qx, qy)) in pb_origins.iter().enumerate() { + let x_pb = x_cb + qx * n_pb; + let y_pb = y_cb + qy * n_pb; + let luma_mode = cu + .intra_luma + .get(i) + .copied() + .unwrap_or(crate::slice_data::IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }); + pb_modes[i] = derive_and_record_luma_mode(ctx, x_pb, y_pb, n_pb, &luma_mode, false); + } + + // §8.4.3 — IntraPredModeC. For ChromaArrayType != 3 the CU has one + // chroma PB whose mode derives from the corner (blkIdx 0) luma PB; + // for ChromaArrayType == 3 with PART_NxN, §7.3.8.5 signals four + // intra_chroma_pred_mode elements and each chroma PB derives from + // its OWN co-located luma PB's IntraPredModeY. + let per_pb_chroma = + params.chroma_array_type == 3 && is_nxn && cu.intra_chroma_pred_mode.len() == 4; + let mut modes_c = [INTRA_DC; 4]; + // ChromaArrayType == 0 (monochrome): §7.3.8.5 signals no + // intra_chroma_pred_mode and no chroma PB exists — keep the DC + // placeholders (nothing downstream consumes them without a + // chroma plane). + if params.chroma_array_type != 0 { + for (i, mode_c) in modes_c.iter_mut().enumerate() { + let (raw, luma_for_c) = if per_pb_chroma { + (cu.intra_chroma_pred_mode[i], pb_modes[i]) + } else { + (cu.intra_chroma_pred_mode[0], pb_modes[0]) + }; + *mode_c = derive_intra_pred_mode_c(raw, luma_for_c, params.chroma_array_type == 2); + } + } + let intra_pred_mode_c = modes_c[0]; + + // §8.6.1 — derive the CU's QpY (threading qPY_PREV across + // quantization groups when the picture-level QP state is + // initialized; single-QG fallback otherwise). + let cu_delta = cu.transform_tree.as_ref().and_then(first_tree_cu_qp_delta); + let qp_y = ctx.derive_cu_qp(params, x_cb, y_cb, cu.log2_cb_size, cu_delta); + + // Walk the transform tree, reconstructing each leaf transform block. + // For PART_NxN the top-level tree is a Split whose four children map to + // the four luma PBs (each carrying that PB's luma mode); chroma uses + // the CU-level IntraPredModeC throughout. + if let Some(tree) = &cu.transform_tree { + if is_nxn { + if let TransformTree::Split { children, .. } = tree { + let half = n_cb / 2; + // §7.3.8.10: when the four children are 4×4 luma leaves + // (and ChromaArrayType != 3), the CU's chroma transform + // blocks are decoded once, deferred to blkIdx == 3 — the + // children carry no chroma of their own. + let child_log2 = cu.log2_cb_size - 1; + let defer_chroma = child_log2 == 2 + && params.chroma_array_type != 0 + && params.chroma_array_type != 3; + let offsets = [(0, 0), (half, 0), (0, half), (half, half)]; + for (i, (child, (dx, dy))) in children.iter().zip(offsets).enumerate() { + reconstruct_transform_tree( + pic, + params, + ctx, + child, + x_cb + dx, + y_cb + dy, + child_log2, + pb_modes[i], + modes_c[i], + qp_y, + cu.cu_transquant_bypass_flag, + defer_chroma, + )?; + } + if defer_chroma { + reconstruct_deferred_chroma( + pic, + params, + ctx, + children, + x_cb, + y_cb, + cu.log2_cb_size, + intra_pred_mode_c, + qp_y, + cu.cu_transquant_bypass_flag, + )?; + } + return Ok(()); + } + } + reconstruct_transform_tree( + pic, + params, + ctx, + tree, + x_cb, + y_cb, + cu.log2_cb_size, + pb_modes[0], + intra_pred_mode_c, + qp_y, + cu.cu_transquant_bypass_flag, + false, + )?; + } + Ok(()) +} + +/// The §7.4.9.14 `cu_qp_delta` decoded inside a CU's transform tree +/// (the first leaf carrying one, in z-scan order), if any. +pub(crate) fn first_tree_cu_qp_delta(tree: &TransformTree) -> Option { + match tree { + TransformTree::Leaf { unit, .. } => unit.cu_qp_delta.as_ref().map(|d| d.value), + TransformTree::Split { children, .. } => children.iter().find_map(first_tree_cu_qp_delta), + } +} + +/// §7.3.8.10 deferred-chroma reconstruction: the chroma transform blocks +/// of an 8×8 luma node whose children are 4×4 leaves are carried by the +/// `blkIdx == 3` child's transform unit and cover the whole node. +#[allow(clippy::too_many_arguments)] +fn reconstruct_deferred_chroma( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + children: &[TransformTree; 4], + x0: usize, + y0: usize, + log2_trafo_size: u32, + intra_pred_mode_c: u8, + qp_y: i32, + transquant_bypass: bool, +) -> Result<(), ReconError> { + let TransformTree::Leaf { unit, .. } = &children[3] else { + // A malformed tree (blkIdx 3 split below 4×4) cannot occur; the + // §7.3.8.8 recursion bottoms out at MinTbLog2SizeY >= 2. + return Ok(()); + }; + let (sw, sh) = sub_wh_c(params.chroma_array_type); + let xc = x0 / sw; + let yc = y0 / sh; + // Chroma TB side: half the 8×8 node for 4:2:0 / 4:2:2 → 4. + let n_tbs_c = (1usize << log2_trafo_size) / 2; + reconstruct_chroma_blocks( + pic, + params, + ctx, + Plane::Cb, + TfComponent::Cb, + &unit.residual_cb, + unit.cbf_cb_halves, + xc, + yc, + n_tbs_c, + intra_pred_mode_c, + qp_y, + transquant_bypass, + None, + )?; + reconstruct_chroma_blocks( + pic, + params, + ctx, + Plane::Cr, + TfComponent::Cr, + &unit.residual_cr, + unit.cbf_cr_halves, + xc, + yc, + n_tbs_c, + intra_pred_mode_c, + qp_y, + transquant_bypass, + None, + )?; + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn reconstruct_transform_tree( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + tree: &TransformTree, + x0: usize, + y0: usize, + log2_trafo_size: u32, + intra_pred_mode_y: u8, + intra_pred_mode_c: u8, + qp_y: i32, + transquant_bypass: bool, + skip_chroma: bool, +) -> Result<(), ReconError> { + match tree { + TransformTree::Split { children, .. } => { + let child_log2 = log2_trafo_size - 1; + // §7.3.8.10: 4×4 luma children (ChromaArrayType != 3) defer + // their chroma to blkIdx == 3, covering this whole node. + let defer_chroma = !skip_chroma + && child_log2 == 2 + && params.chroma_array_type != 0 + && params.chroma_array_type != 3; + let half = 1usize << child_log2; + // raster order [tl, tr, bl, br]. + let offsets = [(0, 0), (half, 0), (0, half), (half, half)]; + for (child, (dx, dy)) in children.iter().zip(offsets) { + reconstruct_transform_tree( + pic, + params, + ctx, + child, + x0 + dx, + y0 + dy, + child_log2, + intra_pred_mode_y, + intra_pred_mode_c, + qp_y, + transquant_bypass, + skip_chroma || defer_chroma, + )?; + } + if defer_chroma { + reconstruct_deferred_chroma( + pic, + params, + ctx, + children, + x0, + y0, + log2_trafo_size, + intra_pred_mode_c, + qp_y, + transquant_bypass, + )?; + } + Ok(()) + } + TransformTree::Leaf { unit, .. } => reconstruct_transform_unit( + pic, + params, + ctx, + unit, + x0, + y0, + log2_trafo_size, + intra_pred_mode_y, + intra_pred_mode_c, + qp_y, + transquant_bypass, + skip_chroma, + ), + } +} + +#[allow(clippy::too_many_arguments)] +fn reconstruct_transform_unit( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + unit: &TransformUnit, + x0: usize, + y0: usize, + log2_trafo_size: u32, + intra_pred_mode_y: u8, + intra_pred_mode_c: u8, + qp_y: i32, + transquant_bypass: bool, + skip_chroma: bool, +) -> Result<(), ReconError> { + let n_tbs = 1usize << log2_trafo_size; + let _ = unit.cu_qp_delta.as_ref(); + // §7.4.9.10 — a parsed chroma_qp_offset( ) element updates the + // slice-wide CuQpOffsetCb / CuQpOffsetCr state in decode order. + if let Some(off) = &unit.cu_chroma_qp_offset { + apply_cu_chroma_qp_offset(params, off); + } + + // §8.6.8 adaptive colour transform (4:4:4 only): the three + // co-located residual arrays of this unit are jointly modified + // before the per-component prediction + add. + if unit.tu_residual_act_flag == 1 && params.chroma_array_type == 3 && !skip_chroma { + return reconstruct_act_transform_unit( + pic, + params, + ctx, + unit, + x0, + y0, + n_tbs, + intra_pred_mode_y, + intra_pred_mode_c, + qp_y, + transquant_bypass, + ); + } + + // Luma block: `qp_y` is the CU's §8.6.1-derived QpY. + let luma_qp = luma_qp(params, qp_y); + let luma_levels = unit.residual_luma.as_ref().map(|rb| rb.levels.as_slice()); + let luma_ts = unit + .residual_luma + .as_ref() + .is_some_and(|rb| rb.transform_skip); + // (§7.3.8.11: explicit_rdpcm_flag is only signalled for MODE_INTER + // blocks — an intra unit's residual never carries it.) + let luma_residual = reconstruct_intra_block( + pic, + params, + ctx, + Plane::Luma, + TfComponent::Luma, + IpComponent::Luma, + x0, + y0, + n_tbs, + intra_pred_mode_y, + luma_levels, + luma_qp, + transquant_bypass, + luma_ts, + None, + )?; + + // Chroma blocks. For 4:2:0 / 4:2:2 the chroma transform block sits at + // (x0 >> SubWidthC, y0 >> SubHeightC) and is half the luma side for + // 4:2:0; the §7.3.8.10 driver collects the chroma residual at the + // parent node, so a chroma block is reconstructed once per luma node + // that carries chroma residual (the residual_cb / residual_cr lists). + if params.chroma_array_type != 0 && !skip_chroma { + let (sw, sh) = sub_wh_c(params.chroma_array_type); + let xc = x0 / sw; + let yc = y0 / sh; + // §7.3.8.10 log2TrafoSizeC = Max( 2, log2TrafoSize − + // ( ChromaArrayType == 3 ? 0 : 1 ) ); the log2TrafoSize == 2 + // deferred case is handled by the parent (skip_chroma). + let n_tbs_c = if params.chroma_array_type == 3 { + 1usize << log2_trafo_size + } else { + (1usize << log2_trafo_size) / 2 + }; + // §8.4.4.1 step 8 (4:4:4 only): the chroma residuals of this + // transform unit are cross-component-predicted from its luma + // residual, scaled by the §7.4.9.12 ResScaleVal per component. + let luma_res = luma_residual.as_deref(); + let ccp_cb = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cb.as_ref(), + luma_res, + ); + let ccp_cr = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cr.as_ref(), + luma_res, + ); + reconstruct_chroma_blocks( + pic, + params, + ctx, + Plane::Cb, + TfComponent::Cb, + &unit.residual_cb, + unit.cbf_cb_halves, + xc, + yc, + n_tbs_c, + intra_pred_mode_c, + qp_y, + transquant_bypass, + ccp_cb, + )?; + reconstruct_chroma_blocks( + pic, + params, + ctx, + Plane::Cr, + TfComponent::Cr, + &unit.residual_cr, + unit.cbf_cr_halves, + xc, + yc, + n_tbs_c, + intra_pred_mode_c, + qp_y, + transquant_bypass, + ccp_cr, + )?; + } + Ok(()) +} + +/// §8.4.4.1 with `residual_adaptive_colour_transform_enabled_flag` and +/// `tu_residual_act_flag == 1` (4:4:4): the transform unit's three +/// co-located residual arrays are derived (ACT-adjusted qP per +/// eq. 8-291 / 8-287 / 8-288), cross-component prediction applies +/// first (§8.4.4.1 step 8), then the §8.6.8.2 inverse colour +/// transform, then each component is predicted and stored. +#[allow(clippy::too_many_arguments)] +fn reconstruct_act_transform_unit( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + unit: &TransformUnit, + x0: usize, + y0: usize, + n_tbs: usize, + intra_pred_mode_y: u8, + intra_pred_mode_c: u8, + qp_y: i32, + transquant_bypass: bool, +) -> Result<(), ReconError> { + let qp_l = luma_qp_act(params, qp_y); + let qp_cb = chroma_qp_act(params, qp_y, TfComponent::Cb, true); + let qp_cr = chroma_qp_act(params, qp_y, TfComponent::Cr, true); + + // The §8.6.8.2 transform mixes the components, so a cbf-clear + // component still needs a materialized (zero) residual array. + let mut r_y = match &unit.residual_luma { + Some(rb) => intra_residual_array( + params, + TfComponent::Luma, + n_tbs, + intra_pred_mode_y, + &rb.levels, + qp_l, + transquant_bypass, + rb.transform_skip, + )?, + None => vec![0i32; n_tbs * n_tbs], + }; + let chroma_res = |blocks: &[crate::residual::ResidualBlock], + coded: bool, + cidx: TfComponent, + qp: u32| + -> Result, ReconError> { + match blocks.first() { + Some(rb) if coded => intra_residual_array( + params, + cidx, + n_tbs, + intra_pred_mode_c, + &rb.levels, + qp, + transquant_bypass, + rb.transform_skip, + ), + _ => Ok(vec![0i32; n_tbs * n_tbs]), + } + }; + let mut r_cb = chroma_res( + &unit.residual_cb, + unit.cbf_cb_halves[0], + TfComponent::Cb, + qp_cb, + )?; + let mut r_cr = chroma_res( + &unit.residual_cr, + unit.cbf_cr_halves[0], + TfComponent::Cr, + qp_cr, + )?; + + // §8.4.4.1 step 8 — cross-component prediction precedes the + // colour transform (the §8.4.1 step-2 ordering). + if let Some(c) = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cb.as_ref(), + Some(&r_y), + ) { + apply_cross_comp_pred( + &mut r_cb, + c.luma_residual, + c.res_scale_val, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + } + if let Some(c) = CcpInput::resolve( + params.chroma_array_type, + unit.cross_comp_pred_cr.as_ref(), + Some(&r_y), + ) { + apply_cross_comp_pred( + &mut r_cr, + c.luma_residual, + c.res_scale_val, + params.bit_depth_luma, + params.bit_depth_chroma, + ); + } + + // §8.6.8.2 — the inverse adaptive colour transformation. + crate::transform::act_inverse( + &mut r_y, + &mut r_cb, + &mut r_cr, + params.bit_depth_luma, + params.bit_depth_chroma, + params.extended_precision, + transquant_bypass, + ); + + // Per-component §8.4.4.2.1 prediction + §8.6.7 construction + // (4:4:4 — the chroma blocks are co-located and equal-sized). + predict_add_store( + pic, + params, + ctx, + Plane::Luma, + IpComponent::Luma, + x0, + y0, + n_tbs, + intra_pred_mode_y, + transquant_bypass, + Some(&r_y), + )?; + predict_add_store( + pic, + params, + ctx, + Plane::Cb, + ip_component_of(TfComponent::Cb), + x0, + y0, + n_tbs, + intra_pred_mode_c, + transquant_bypass, + Some(&r_cb), + )?; + predict_add_store( + pic, + params, + ctx, + Plane::Cr, + ip_component_of(TfComponent::Cr), + x0, + y0, + n_tbs, + intra_pred_mode_c, + transquant_bypass, + Some(&r_cr), + )?; + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn reconstruct_chroma_blocks( + pic: &mut Picture, + params: &ReconParams, + ctx: &ReconCtx, + plane: Plane, + cidx: TfComponent, + residual_blocks: &[crate::residual::ResidualBlock], + coded_halves: [bool; 2], + xc: usize, + yc: usize, + n_tbs_c: usize, + intra_pred_mode_c: u8, + qp_y: i32, + transquant_bypass: bool, + ccp: Option>, +) -> Result<(), ReconError> { + let qp = chroma_qp(params, qp_y, cidx); + // `ChromaArrayType == 2` stacks two square chroma TBs vertically per + // luma node (upper then lower); every other type has one. A block + // with no coded residual (cbf clear) is still intra-PREDICTED — only + // the residual add is skipped. + let vertical_blocks = if params.chroma_array_type == 2 { 2 } else { 1 }; + let mut next_block = 0usize; + for (v, &half_coded) in coded_halves.iter().enumerate().take(vertical_blocks) { + // §7.3.8.10 codes the halves upper-then-lower, each gated on + // its own cbf — pair the residual list entries to the coded + // halves. + let block = if half_coded { + let b = residual_blocks.get(next_block); + next_block += 1; + b + } else { + None + }; + let levels = block.map(|rb| rb.levels.as_slice()); + let ts = block.is_some_and(|rb| rb.transform_skip); + reconstruct_intra_block( + pic, + params, + ctx, + plane, + cidx, + ip_component_of(cidx), + xc, + yc + v * n_tbs_c, + n_tbs_c, + intra_pred_mode_c, + levels, + qp, + transquant_bypass, + ts, + ccp, + )?; + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::availability::TilingParams; + use crate::binarization::{CuPredMode, PartMode}; + use crate::residual::ResidualBlock; + use crate::slice_data::{CodingQuadtree, CodingTreeUnit, CodingUnit, IntraLumaMode}; + use crate::transform_tree::TransformTree; + use crate::transform_unit::TransformUnit; + + /// §8 reconstruction params for a Main-profile 4:2:0 8-bit slice at + /// SliceQpY = 25 (the tiny-i fixture geometry). + fn tiny_params() -> ReconParams { + ReconParams { + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + intra_smoothing_disabled: false, + strong_intra_smoothing_enabled: true, + slice_qp_y: 25, + cb_qp_offset: 0, + cr_qp_offset: 0, + act_y_qp_offset: 0, + act_cb_qp_offset: 0, + act_cr_qp_offset: 0, + transform_skip_rotation_enabled: false, + implicit_rdpcm_enabled: false, + intra_boundary_filtering_disabled: false, + extended_precision: false, + scaling: None, + chroma_qp_offset_list: Vec::new(), + cu_qp_offset_c: core::cell::Cell::new((0, 0)), + } + } + + /// A single-DC residual block of side `1 << log2`. + fn dc_block(log2: u32, dc: i32) -> ResidualBlock { + let size = 1usize << log2; + let mut levels = vec![0i32; size * size]; + levels[0] = dc; + ResidualBlock { + log2_trafo_size: log2, + last_sig_coeff_x: 0, + last_sig_coeff_y: 0, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + } + } + + /// Build a flat 16x16 intra CU (PART_2Nx2N, PLANAR luma via mpm_idx 0) + /// carrying the given luma / Cb / Cr DC residuals. + fn flat_intra_ctu(luma_dc: i32, cb_dc: Option, cr_dc: Option) -> CodingTreeUnit { + let mut unit = TransformUnit { + residual_luma: Some(dc_block(4, luma_dc)), + ..Default::default() + }; + if let Some(d) = cb_dc { + unit.residual_cb = vec![dc_block(3, d)]; + unit.cbf_cb_halves = [true, false]; + } + if let Some(d) = cr_dc { + unit.residual_cr = vec![dc_block(3, d)]; + unit.cbf_cr_halves = [true, false]; + } + let tree = TransformTree::Leaf { + cbf_luma: true, + unit, + }; + let cu = CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + // prev_intra_luma_pred_flag + mpm_idx 0 ⇒ candModeList[0] = + // PLANAR for the all-DC neighbour fallback. + intra_luma: vec![IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }], + // intra_chroma_pred_mode 4 ⇒ derived (= luma mode). + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(tree), + }; + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(cu)), + } + } + + /// Build a 16x16 transquant-bypass intra CTU whose single luma TB + /// carries `levels` (row-major raw bypass residual) and whose luma + /// mode comes from `luma_mode` (an MPM/rem selector against the + /// no-neighbour candModeList {PLANAR, DC, 26}). + fn bypass_intra_ctu(levels: Vec, luma_mode: IntraLumaMode) -> CodingTreeUnit { + let unit = TransformUnit { + residual_luma: Some(ResidualBlock { + log2_trafo_size: 4, + last_sig_coeff_x: 15, + last_sig_coeff_y: 15, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }), + ..Default::default() + }; + let cu = CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: true, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![luma_mode], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: true, + unit, + }), + }; + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(cu)), + } + } + + /// §8.4.4.1 implicit RDPCM, vertical: a transquant-bypass TB in + /// mode 26 (candModeList[2] with no neighbours) whose residual has + /// row 0 = 5 accumulates down every column (eq. 8-323), so the + /// whole block reconstructs to 128 + 5. + #[test] + fn implicit_rdpcm_vertical_accumulates_bypass_residual() { + let mut params = tiny_params(); + params.implicit_rdpcm_enabled = true; + let mut levels = vec![0i32; 256]; + levels[..16].fill(5); // row 0 only + let ctu = bypass_intra_ctu( + levels, + IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(2), // candModeList[2] = 26 (vertical) + rem_intra_luma_pred_mode: None, + }, + ); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 133, "luma at ({x},{y})"); + } + } + } + + /// §8.4.4.1 implicit RDPCM, horizontal: mode 10 + /// (rem_intra_luma_pred_mode 8 against candModeList {0, 1, 26}) + /// with column 0 = 5 accumulates across every row (eq. 8-322). + #[test] + fn implicit_rdpcm_horizontal_accumulates_bypass_residual() { + let mut params = tiny_params(); + params.implicit_rdpcm_enabled = true; + let mut levels = vec![0i32; 256]; + for y in 0..16 { + levels[y * 16] = 5; // column 0 only + } + let ctu = bypass_intra_ctu( + levels, + IntraLumaMode { + prev_intra_luma_pred_flag: false, + mpm_idx: None, + // 8 → +1 for cand 0, +1 for cand 1 ⇒ IntraPredModeY 10. + rem_intra_luma_pred_mode: Some(8), + }, + ); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 133, "luma at ({x},{y})"); + } + } + } + + /// The implicit-RDPCM condition is exact: a bypass block whose mode + /// is NOT 10 / 26 (here DC via mpm_idx 1) keeps its raw residual — + /// row 0 is 128 + 5, every other row stays at the DC prediction. + #[test] + fn implicit_rdpcm_skips_non_directional_modes() { + let mut params = tiny_params(); + params.implicit_rdpcm_enabled = true; + let mut levels = vec![0i32; 256]; + levels[..16].fill(5); + let ctu = bypass_intra_ctu( + levels, + IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(1), // candModeList[1] = DC + rem_intra_luma_pred_mode: None, + }, + ); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, 0), 133, "row 0 at x={x}"); + assert_eq!(pic.sample(Plane::Luma, x, 5), 128, "row 5 at x={x}"); + } + } + + /// §8.5.4.2 step 3: an inter residual block with + /// `explicit_rdpcm_flag == 1` runs the §8.6.5 modification with + /// mDir = `explicit_rdpcm_dir_flag` before placement. + #[test] + fn explicit_rdpcm_inter_residual_accumulates() { + let params = tiny_params(); + let mut levels = vec![0i32; 16]; + levels[..4].fill(3); // row 0 + let rb = ResidualBlock { + log2_trafo_size: 2, + last_sig_coeff_x: 3, + last_sig_coeff_y: 3, + levels, + transform_skip: false, + explicit_rdpcm_flag: true, + explicit_rdpcm_dir_flag: true, // vertical + }; + let r = inter_residual_block(¶ms, &rb, TfComponent::Luma, 25, true).unwrap(); + assert!(r.iter().all(|&v| v == 3), "vertical accumulation: {r:?}"); + + let mut levels_h = vec![0i32; 16]; + for y in 0..4 { + levels_h[y * 4] = 2; // column 0 + } + let rb_h = ResidualBlock { + explicit_rdpcm_dir_flag: false, // horizontal + levels: levels_h, + ..rb + }; + let r = inter_residual_block(¶ms, &rb_h, TfComponent::Luma, 25, true).unwrap(); + assert!(r.iter().all(|&v| v == 2), "horizontal accumulation: {r:?}"); + } + + #[test] + fn flat_intra_luma_reconstructs_to_constant_field() { + // pred = midlevel 128 (no neighbours); luma DC −67 dequant+IDCT + // gives a uniform −47 residual, so recSamples = 128 − 47 = 81. + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, None, None); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 81, "luma at ({x},{y})"); + } + } + } + + #[test] + fn flat_intra_chroma_cb_reconstructs_exactly() { + // Cb DC −27 at QpC(25)=25 gives a uniform −38 residual ⇒ + // 128 − 38 = 90 (the fixture's expected.yuv Cb plane value). + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, Some(-27), None); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..8 { + for x in 0..8 { + assert_eq!(pic.sample(Plane::Cb, x, y), 90, "cb at ({x},{y})"); + } + } + } + + #[test] + fn chroma_residual_produces_uniform_field() { + // A pure-DC chroma residual reconstructs to a constant plane (the + // inverse-transform DC basis is flat); validates the chroma + // predict + dequant + add + clip pipeline end to end. + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, Some(-27), Some(64)); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + let cr0 = pic.sample(Plane::Cr, 0, 0); + for y in 0..8 { + for x in 0..8 { + assert_eq!(pic.sample(Plane::Cr, x, y), cr0, "cr uniform at ({x},{y})"); + } + } + assert!(cr0 > 128, "positive DC raises the Cr plane"); + } + + #[test] + fn clip_saturates_out_of_range_reconstruction() { + // A large negative luma DC drives pred+res below 0; the §8.4.4.1 + // Clip1Y must clamp to 0 (not wrap). + let params = tiny_params(); + let ctu = flat_intra_ctu(-400, None, None); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + assert_eq!(pic.sample(Plane::Luma, 0, 0), 0); + } + + /// Build an 8×8 intra CU at `(x0, y0)` carrying the given luma-mode + /// signalling and a uniform DC luma residual (no chroma). + fn intra_cu_8x8( + x0: u32, + y0: u32, + luma: IntraLumaMode, + luma_dc: i32, + chroma_pred_mode: u8, + ) -> CodingUnit { + let unit = TransformUnit { + residual_luma: Some(dc_block(3, luma_dc)), + ..Default::default() + }; + CodingUnit { + x0, + y0, + log2_cb_size: 3, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![luma], + intra_chroma_pred_mode: vec![chroma_pred_mode], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: true, + unit, + }), + } + } + + /// The §8.4.2 neighbour MPM derivation makes a CU's IntraPredModeY + /// depend on its already-reconstructed left / above neighbours. A right + /// CU signalling `mpm_idx == 0` against a left neighbour coded with a + /// non-DC angular mode picks up `candModeList[0]` = the neighbour's + /// mode (proved by inspecting the recorded IntraModeField), whereas the + /// flat-single-CU path would have derived INTRA_DC. + #[test] + fn neighbour_mpm_propagates_left_cu_mode_to_right_cu() { + let params = tiny_params(); + // Left CU (0,0): remaining-mode angular 18. Both neighbours are + // out-of-picture ⇒ candA == candB == INTRA_DC; the step-4 ordered + // procedure maps rem_intra_luma_pred_mode 18 (with neither DC nor + // PLANAR below it) up to IntraPredModeY 20. + let left = IntraLumaMode { + prev_intra_luma_pred_flag: false, + mpm_idx: None, + rem_intra_luma_pred_mode: Some(18), + }; + // Right CU (8,0): mpm_idx 0 ⇒ IntraPredModeY = candModeList[0]. Its + // left neighbour (7,*) is the left CU (mode 20, available in z-scan + // order); its above neighbour is out-of-picture (DC). candA(20) != + // candB(DC) and neither is PLANAR ⇒ candModeList[0] == candA == 20. + let right = IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }; + let tl = intra_cu_8x8(0, 0, left, 0, 4); + let tr = intra_cu_8x8(8, 0, right, 0, 4); + let bl = intra_cu_8x8(0, 8, left, 0, 4); + let br = intra_cu_8x8(8, 8, right, 0, 4); + let ctu = CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Split(vec![ + CodingQuadtree::Leaf(Box::new(tl)), + CodingQuadtree::Leaf(Box::new(tr)), + CodingQuadtree::Leaf(Box::new(bl)), + CodingQuadtree::Leaf(Box::new(br)), + ]), + }; + let mut pic = Picture::new(16, 16, 1, 8, 8); + let mut ctx = ReconCtx::new(16, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + reconstruct_intra_ctu_ctx(&mut pic, ¶ms, &mut ctx, &ctu).unwrap(); + + // The left CU's remaining-mode 18 resolves to IntraPredModeY 20. + assert_eq!(ctx.recorded_mode(0, 0), Some(20), "left CU mode"); + // The right CU's mpm_idx 0 picked up the left neighbour's mode 20 + // through candModeList[0] — the §8.4.2 propagation under test. + assert_eq!( + ctx.recorded_mode(8, 0), + Some(20), + "right CU inherited the left neighbour's mode via MPM" + ); + } + + /// Counter-case: with NO recorded left neighbour (a single isolated + /// CU), the same `mpm_idx == 0` signalling derives candModeList[0] from + /// the all-DC fallback ⇒ INTRA_PLANAR (0), not the angular 20 above. + #[test] + fn isolated_cu_mpm_zero_is_planar_not_neighbour_mode() { + let params = tiny_params(); + let right = IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }; + let cu = intra_cu_8x8(8, 0, right, 0, 4); + let ctu = CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(cu)), + }; + let mut pic = Picture::new(16, 16, 1, 8, 8); + let mut ctx = ReconCtx::new(16, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + reconstruct_intra_ctu_ctx(&mut pic, ¶ms, &mut ctx, &ctu).unwrap(); + // candA == candB == DC ⇒ candModeList = [PLANAR, DC, 26]; index 0 + // is INTRA_PLANAR. + assert_eq!(ctx.recorded_mode(8, 0), Some(0)); + } + + #[test] + fn inter_cu_is_rejected_by_intra_path() { + let params = tiny_params(); + let mut ctu = flat_intra_ctu(-67, None, None); + if let CodingQuadtree::Leaf(cu) = &mut ctu.quadtree { + cu.cu_pred_mode = CuPredMode::Inter; + } + let mut pic = Picture::new(16, 16, 1, 8, 8); + assert_eq!( + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu), + Err(ReconError::InterNotSupported) + ); + } + + /// End-to-end §8.5 inter reconstruction: a uni-L0 P-block with a + /// full-pel motion vector copies a shifted reference window, then a + /// uniform residual is added and clipped. + #[test] + fn inter_uni_l0_full_pel_reconstructs() { + let params = tiny_params(); + // Reference picture: luma ramp sample(x,y) == x (mod 256), flat + // chroma 128. + let mut refpic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + refpic.set_sample(Plane::Luma, x, y, x as i32); + } + } + for y in 0..8 { + for x in 0..8 { + refpic.set_sample(Plane::Cb, x, y, 128); + refpic.set_sample(Plane::Cr, x, y, 128); + } + } + let l0 = ResolvedList { + pred_flag: true, + mv_l: [8, 0], // +2 full luma samples right. + mv_c: [8, 0], // 4:2:0 ⇒ mvC = mvL. + ref_pic: &refpic, + }; + // Unused L1 points at the same picture but pred_flag is false. + let l1 = ResolvedList { + pred_flag: false, + mv_l: [0, 0], + mv_c: [0, 0], + ref_pic: &refpic, + }; + let mut pic = Picture::new(16, 16, 1, 8, 8); + // A flat +5 luma residual over the 8x8 PU at (0,0). + let res = vec![5i32; 8 * 8]; + reconstruct_inter_pu( + &mut pic, + ¶ms, + 0, + 0, + 8, + 8, + l0, + l1, + Some(&res), + None, + None, + ) + .unwrap(); + // predSamples[xL] reads ref column xPb + 2 + xL = 2 + xL; + 5 res. + for yl in 0..8 { + for xl in 0..8 { + assert_eq!( + pic.sample(Plane::Luma, xl, yl), + (2 + xl as i32) + 5, + "luma ({xl},{yl})" + ); + } + } + // Chroma: flat 128 prediction, no residual ⇒ 128. + for yc in 0..4 { + for xc in 0..4 { + assert_eq!(pic.sample(Plane::Cb, xc, yc), 128); + assert_eq!(pic.sample(Plane::Cr, xc, yc), 128); + } + } + } + + /// Bi-prediction averages two reference windows; a clip guards the + /// out-of-range sum. + #[test] + fn inter_bi_averages_and_clips() { + let params = tiny_params(); + let mut a = Picture::new(16, 16, 1, 8, 8); + let mut b = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + a.set_sample(Plane::Luma, x, y, 40); + b.set_sample(Plane::Luma, x, y, 200); + } + } + let l0 = ResolvedList { + pred_flag: true, + mv_l: [0, 0], + mv_c: [0, 0], + ref_pic: &a, + }; + let l1 = ResolvedList { + pred_flag: true, + mv_l: [0, 0], + mv_c: [0, 0], + ref_pic: &b, + }; + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_inter_pu(&mut pic, ¶ms, 0, 0, 8, 8, l0, l1, None, None, None).unwrap(); + // (40 + 200) >> 1 == 120. + for yl in 0..8 { + for xl in 0..8 { + assert_eq!(pic.sample(Plane::Luma, xl, yl), 120); + } + } + } + + #[test] + fn packed_output_matches_planar_layout() { + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, Some(-27), None); + let mut pic = Picture::new(16, 16, 1, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + let packed = pic.to_planar_u8().unwrap(); + // 256 luma + 64 cb + 64 cr. + assert_eq!(packed.len(), 384); + assert!(packed[..256].iter().all(|&v| v == 81)); + assert!(packed[256..320].iter().all(|&v| v == 90)); + } + + /// Picture-level driver with SAO off: a single flat CTU reconstructs to + /// the same constant field as the per-CTU path, and the SAO pass (type + /// 0 / both flags clear) is a no-op. + #[test] + fn picture_driver_single_ctu_matches_per_ctu_no_sao() { + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, Some(-27), Some(64)); + let pic_params = IntraPictureParams { + ctb_log2_size_y: 4, + min_tb_log2_size_y: 2, + tiles: TilingParams::single_tile(), + slice_sao_luma_flag: false, + slice_sao_chroma_flag: false, + log2_sao_offset_scale_luma: 0, + log2_sao_offset_scale_chroma: 0, + }; + let placed = [PlacedCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + ctu: &ctu, + }]; + let out = reconstruct_intra_picture(16, 16, ¶ms, &pic_params, &placed).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(out.sample(Plane::Luma, x, y), 81); + } + } + for y in 0..8 { + for x in 0..8 { + assert_eq!(out.sample(Plane::Cb, x, y), 90); + } + } + } + + /// Picture-level driver applies the §8.7.3 SAO band offset: a flat luma + /// field at 81 with a band-offset CTB shifts every covered sample by the + /// band's offset. + #[test] + fn picture_driver_applies_sao_band_offset() { + use crate::slice_data::{SaoComponent, SaoCtbParams}; + let params = tiny_params(); + let ctu = flat_intra_ctu(-67, Some(-27), Some(64)); + // SAO band offset on luma: band_position chosen so the 81-valued + // luma band gets a +7 offset. band_shift = bitDepth-5 = 3, so + // sample 81 >> 3 == 10 falls in band 10; bandTable maps four + // consecutive bands from sao_band_position. Pick band_position 10 so + // band 10 → bandTable index 1 → offset_val[1]. + let mut luma_sao = SaoComponent { + sao_type_idx: 1, // band offset + ..Default::default() + }; + luma_sao.band_position = 10; + luma_sao.offset_abs = [7, 0, 0, 0]; + luma_sao.offset_sign = [0, 0, 0, 0]; + let ctu_sao = CodingTreeUnit { + sao: Some(SaoCtbParams { + merge_left: false, + merge_up: false, + components: [luma_sao, SaoComponent::default(), SaoComponent::default()], + }), + quadtree: ctu.quadtree.clone(), + }; + let pic_params = IntraPictureParams { + ctb_log2_size_y: 4, + min_tb_log2_size_y: 2, + tiles: TilingParams::single_tile(), + slice_sao_luma_flag: true, + slice_sao_chroma_flag: false, + log2_sao_offset_scale_luma: 0, + log2_sao_offset_scale_chroma: 0, + }; + let placed = [PlacedCtu { + x_ctb: 0, + y_ctb: 0, + slice_addr_rs: 0, + ctu: &ctu_sao, + }]; + let out = reconstruct_intra_picture(16, 16, ¶ms, &pic_params, &placed).unwrap(); + // Luma 81 (band 10, bandTable idx 1) + offset 7 = 88. + assert_eq!(out.sample(Plane::Luma, 4, 4), 88, "SAO band offset applied"); + } + + /// Multi-slice neighbour isolation: two 16×16 CTUs side by side in a + /// 32×16 picture. The right CTU's `mpm_idx == 0` inherits the left + /// CTU's angular mode 20 through the §8.4.2 MPM when both share a slice + /// (map `[0, 0]`), but falls back to INTRA_PLANAR when the right CTU is + /// in a different slice (map `[0, 1]`) — the §6.4.1 z-scan availability + /// denies a neighbour across the slice boundary. + #[test] + fn slice_boundary_blocks_neighbour_mpm() { + let params = tiny_params(); + let left = IntraLumaMode { + prev_intra_luma_pred_flag: false, + mpm_idx: None, + rem_intra_luma_pred_mode: Some(18), + }; + let right = IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }; + let make_ctus = || { + ( + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(intra_cu_16x16(0, 0, left))), + }, + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(intra_cu_16x16(16, 0, right))), + }, + ) + }; + + // Same-slice baseline (map [0, 0]): the right CTU inherits mode 20. + let (l0, r0) = make_ctus(); + let mut pic = Picture::new(32, 16, 1, 8, 8); + let mut ctx = ReconCtx::new(32, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + ctx.set_slice_addr_rs(vec![0, 0]); + reconstruct_intra_ctu_ctx(&mut pic, ¶ms, &mut ctx, &l0).unwrap(); + reconstruct_intra_ctu_ctx(&mut pic, ¶ms, &mut ctx, &r0).unwrap(); + assert_eq!(ctx.recorded_mode(16, 0), Some(20), "same-slice inherits 20"); + + // Cross-slice (map [0, 1]): the right CTU's left neighbour (15,*) + // is in slice 0 ⇒ denied ⇒ MPM falls back to PLANAR. + let (l1, r1) = make_ctus(); + let mut pic2 = Picture::new(32, 16, 1, 8, 8); + let mut ctx2 = ReconCtx::new(32, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + ctx2.set_slice_addr_rs(vec![0, 1]); + reconstruct_intra_ctu_ctx(&mut pic2, ¶ms, &mut ctx2, &l1).unwrap(); + reconstruct_intra_ctu_ctx(&mut pic2, ¶ms, &mut ctx2, &r1).unwrap(); + assert_eq!(ctx2.recorded_mode(0, 0), Some(20), "left CTU mode 20"); + assert_eq!( + ctx2.recorded_mode(16, 0), + Some(0), + "cross-slice right CTU falls back to PLANAR (no cross-slice MPM)" + ); + } + + /// §7.4.7.1 SliceAddrRs map for the `multi-slice-per-frame` fixture + /// geometry: a 64×64 picture, 16×16 CTBs ⇒ a 4×4 CTB raster grid, four + /// row-wise independent slices at addresses 0, 4, 8, 12 (no tiles). + /// Each CTB's SliceAddrRs is the address of its slice's first CTB. + #[test] + fn slice_addr_map_partitions_four_row_slices() { + let tiling = PictureTiling::new(4, 4, 64, 64, 4, 2, &TilingParams::single_tile()).unwrap(); + let segs = [ + SliceSegmentBoundary { + slice_segment_address: 0, + dependent: false, + }, + SliceSegmentBoundary { + slice_segment_address: 4, + dependent: false, + }, + SliceSegmentBoundary { + slice_segment_address: 8, + dependent: false, + }, + SliceSegmentBoundary { + slice_segment_address: 12, + dependent: false, + }, + ]; + let map = build_slice_addr_map(&tiling, &segs); + // Row 0 (CTBs 0..3) ⇒ SliceAddrRs 0; row 1 (4..7) ⇒ 4; etc. + assert_eq!( + map, + vec![0, 0, 0, 0, 4, 4, 4, 4, 8, 8, 8, 8, 12, 12, 12, 12] + ); + } + + /// A dependent slice segment inherits the SliceAddrRs of the preceding + /// independent segment. + #[test] + fn slice_addr_map_dependent_inherits() { + // 4×1 CTB row. Independent slice at 0, dependent continuation at 2. + let tiling = PictureTiling::new(4, 1, 64, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + let segs = [ + SliceSegmentBoundary { + slice_segment_address: 0, + dependent: false, + }, + SliceSegmentBoundary { + slice_segment_address: 2, + dependent: true, + }, + ]; + let map = build_slice_addr_map(&tiling, &segs); + // The dependent segment inherits SliceAddrRs 0 ⇒ the whole row is + // one slice (SliceAddrRs 0). + assert_eq!(map, vec![0, 0, 0, 0]); + } + + /// Two independent slices split a single CTB row. + #[test] + fn slice_addr_map_two_independent_in_a_row() { + let tiling = PictureTiling::new(4, 1, 64, 16, 4, 2, &TilingParams::single_tile()).unwrap(); + let segs = [ + SliceSegmentBoundary { + slice_segment_address: 0, + dependent: false, + }, + SliceSegmentBoundary { + slice_segment_address: 2, + dependent: false, + }, + ]; + let map = build_slice_addr_map(&tiling, &segs); + assert_eq!(map, vec![0, 0, 2, 2]); + } + + /// A 16×16 PART_2Nx2N intra CU at `(x0, y0)` with a uniform DC luma + /// residual and the given luma-mode signalling (test helper). + fn intra_cu_16x16(x0: u32, y0: u32, luma: IntraLumaMode) -> CodingUnit { + let unit = TransformUnit { + residual_luma: Some(dc_block(4, 0)), + ..Default::default() + }; + CodingUnit { + x0, + y0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: false, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![luma], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: true, + unit, + }), + } + } + + // ----------------------------------------------------------------- + // §8.6.6 cross-component prediction (4:4:4) + // ----------------------------------------------------------------- + + /// 4:4:4 8-bit params for the transquant-bypass CCP fixtures. + fn params_444() -> ReconParams { + ReconParams { + chroma_array_type: 3, + ..tiny_params() + } + } + + /// A §7.4.9.12 `cross_comp_pred()` result with the given + /// `ResScaleVal` (a signed power of two in −8..=8). + fn ccp(res_scale_val: i32) -> crate::binarization::CrossCompPred { + let mag = res_scale_val.unsigned_abs(); + assert!(mag.is_power_of_two() && mag <= 8); + crate::binarization::CrossCompPred { + log2_res_scale_abs_plus1: mag.trailing_zeros() + 1, + res_scale_sign_flag: Some(u8::from(res_scale_val < 0)), + res_scale_val, + } + } + + /// A 16×16 transquant-bypass 4:4:4 intra CTU: PLANAR luma (mpm 0, + /// no neighbours), derived chroma (mode 4), raw bypass residuals. + fn ccp_intra_ctu( + luma_levels: Vec, + cb_levels: Option>, + ccp_cb: Option, + ccp_cr: Option, + ) -> CodingTreeUnit { + let raw = |levels: Vec| ResidualBlock { + log2_trafo_size: 4, + last_sig_coeff_x: 15, + last_sig_coeff_y: 15, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }; + let mut unit = TransformUnit { + residual_luma: Some(raw(luma_levels)), + cross_comp_pred_cb: ccp_cb, + cross_comp_pred_cr: ccp_cr, + ..Default::default() + }; + if let Some(l) = cb_levels { + unit.residual_cb = vec![raw(l)]; + unit.cbf_cb_halves = [true, false]; + } + let cu = CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: true, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { + cbf_luma: true, + unit, + }), + }; + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(cu)), + } + } + + /// Eq. 8-324 with a cbf-clear chroma block: the scaled luma + /// residual alone modifies the chroma reconstruction. + /// rY = 8, ResScaleVal = +1 ⇒ Cb += (8 >> 3) = 1; ResScaleVal = −1 + /// ⇒ Cr += (−8 >> 3) = −1 (arithmetic shift). + #[test] + fn ccp_intra_uncoded_chroma_receives_scaled_luma_residual() { + let params = params_444(); + let ctu = ccp_intra_ctu(vec![8; 256], None, Some(ccp(1)), Some(ccp(-1))); + let mut pic = Picture::new(16, 16, 3, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 136, "luma at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cb, x, y), 129, "cb at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cr, x, y), 127, "cr at ({x},{y})"); + } + } + } + + /// Eq. 8-324 on top of a coded chroma residual: r += scaled rY + /// AFTER the block's own §8.6.2 output. rY = 8, coded Cb = 4, + /// ResScaleVal = +2 ⇒ Cb residual 4 + ((2·8) >> 3) = 6. + #[test] + fn ccp_intra_coded_chroma_adds_scaled_luma_residual() { + let params = params_444(); + let ctu = ccp_intra_ctu(vec![8; 256], Some(vec![4; 256]), Some(ccp(2)), None); + let mut pic = Picture::new(16, 16, 3, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Cb, x, y), 134, "cb at ({x},{y})"); + // Cr carried no cross_comp_pred and no residual. + assert_eq!(pic.sample(Plane::Cr, x, y), 128, "cr at ({x},{y})"); + } + } + } + + /// Eq. 8-324 bit-depth alignment: `( rY << BitDepthC ) >> BitDepthY` + /// rescales the luma residual into the chroma depth before the + /// ResScaleVal multiply. + #[test] + fn ccp_bit_depth_alignment_rescales_luma_residual() { + // BitDepthY = 10, BitDepthC = 8: rY = 16 → (16 << 8) >> 10 = 4; + // scale 4 ⇒ += (4·4) >> 3 = 2. + let mut r = vec![10i32; 4]; + apply_cross_comp_pred(&mut r, &[16, 16, -16, -16], 4, 10, 8); + assert_eq!(r, vec![12, 12, 8, 8]); + // Chroma deeper than luma: rY = 3 → (3 << 12) >> 8 = 48; + // scale −8 ⇒ += (−384) >> 3 = −48. + let mut r = vec![0i32; 2]; + apply_cross_comp_pred(&mut r, &[3, -3], -8, 8, 12); + assert_eq!(r, vec![-48, 48]); + } + + /// §8.5.4.3 step 5 in the inter residual-extraction path: a + /// cbf-clear Cb block still receives the scaled luma residual, and + /// a coded Cr block is modified after its own inverse transform. + #[test] + fn ccp_inter_extract_modifies_chroma_planes() { + let params = params_444(); + let raw = |levels: Vec| ResidualBlock { + log2_trafo_size: 3, + last_sig_coeff_x: 7, + last_sig_coeff_y: 7, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }; + let mut unit = TransformUnit { + residual_luma: Some(raw(vec![16; 64])), + cross_comp_pred_cb: Some(ccp(2)), + cross_comp_pred_cr: Some(ccp(-4)), + ..Default::default() + }; + unit.residual_cr = vec![raw(vec![5; 64])]; + unit.cbf_cr_halves = [true, false]; + let tree = TransformTree::Leaf { + cbf_luma: true, + unit, + }; + let res = extract_cu_residual(¶ms, Some(&tree), 0, 0, 8, 25, true).unwrap(); + assert!(res.luma.samples.iter().all(|&v| v == 16), "luma"); + // Cb (uncoded): (2·16) >> 3 = 4. + assert!( + res.cb.as_ref().unwrap().samples.iter().all(|&v| v == 4), + "cb: {:?}", + &res.cb.as_ref().unwrap().samples[..8] + ); + // Cr (coded 5): 5 + ((−4·16) >> 3) = −3. + assert!( + res.cr.as_ref().unwrap().samples.iter().all(|&v| v == -3), + "cr: {:?}", + &res.cr.as_ref().unwrap().samples[..8] + ); + } + + /// A zero ResScaleVal (`log2_res_scale_abs_plus1 == 0`) is the + /// signalled no-op: no chroma modification, cbf-clear blocks stay + /// zero. + #[test] + fn ccp_zero_scale_is_noop() { + let params = params_444(); + let none = crate::binarization::CrossCompPred { + log2_res_scale_abs_plus1: 0, + res_scale_sign_flag: None, + res_scale_val: 0, + }; + let ctu = ccp_intra_ctu(vec![8; 256], None, Some(none), Some(none)); + let mut pic = Picture::new(16, 16, 3, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Cb, x, y), 128, "cb at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cr, x, y), 128, "cr at ({x},{y})"); + } + } + } + + // ----------------------------------------------------------------- + // §8.6.8 adaptive colour transform (4:4:4) + // ----------------------------------------------------------------- + + /// A 16×16 transquant-bypass 4:4:4 intra CTU whose single TU has + /// `tu_residual_act_flag == 1` and carries the given raw bypass + /// residuals per component (all-cbf-set unless a level vec is + /// `None`). + fn act_intra_ctu( + luma_levels: Option>, + cb_levels: Option>, + cr_levels: Option>, + ) -> CodingTreeUnit { + let raw = |levels: Vec| ResidualBlock { + log2_trafo_size: 4, + last_sig_coeff_x: 15, + last_sig_coeff_y: 15, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }; + let mut unit = TransformUnit { + tu_residual_act_flag: 1, + ..Default::default() + }; + let cbf_luma = luma_levels.is_some(); + if let Some(l) = luma_levels { + unit.residual_luma = Some(raw(l)); + } + if let Some(l) = cb_levels { + unit.residual_cb = vec![raw(l)]; + unit.cbf_cb_halves = [true, false]; + } + if let Some(l) = cr_levels { + unit.residual_cr = vec![raw(l)]; + unit.cbf_cr_halves = [true, false]; + } + let cu = CodingUnit { + x0: 0, + y0: 0, + log2_cb_size: 4, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag: true, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: vec![], + intra_luma: vec![IntraLumaMode { + prev_intra_luma_pred_flag: true, + mpm_idx: Some(0), + rem_intra_luma_pred_mode: None, + }], + intra_chroma_pred_mode: vec![4], + rqt_root_cbf: true, + transform_tree: Some(TransformTree::Leaf { cbf_luma, unit }), + }; + CodingTreeUnit { + sao: None, + quadtree: CodingQuadtree::Leaf(Box::new(cu)), + } + } + + /// §8.6.8.2 lossless inverse in the intra path: coded + /// (Y, Cg, Co) = (4, 3, 14) lifts back to component residuals + /// (6, −4, 10) — tmp = 4 − 1 = 3, rY = 6, rCb = 3 − 7 = −4, + /// rCr = 14 − 4 = 10 — on top of the flat 128 prediction. + #[test] + fn act_intra_bypass_lifts_residual_triple() { + let params = params_444(); + let ctu = act_intra_ctu(Some(vec![4; 256]), Some(vec![3; 256]), Some(vec![14; 256])); + let mut pic = Picture::new(16, 16, 3, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 134, "luma at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cb, x, y), 124, "cb at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cr, x, y), 138, "cr at ({x},{y})"); + } + } + } + + /// A cbf-clear component still participates in the §8.6.8.2 + /// mixing: chroma-only (Cg = 2) produces tmp = −1 ⇒ + /// (rY, rCb, rCr) = (1, −1, −1). + #[test] + fn act_intra_mixes_into_uncoded_components() { + let params = params_444(); + let ctu = act_intra_ctu(None, Some(vec![2; 256]), None); + let mut pic = Picture::new(16, 16, 3, 8, 8); + reconstruct_intra_ctu(&mut pic, ¶ms, &ctu).unwrap(); + for y in 0..16 { + for x in 0..16 { + assert_eq!(pic.sample(Plane::Luma, x, y), 129, "luma at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cb, x, y), 127, "cb at ({x},{y})"); + assert_eq!(pic.sample(Plane::Cr, x, y), 127, "cr at ({x},{y})"); + } + } + } + + /// §8.5.4.1 step 4 in the inter residual-extraction path: the same + /// (4, 3, 14) → (6, −4, 10) lifting lands in the CU residual + /// planes. + #[test] + fn act_inter_extract_lifts_residual_triple() { + let params = params_444(); + let raw = |levels: Vec| ResidualBlock { + log2_trafo_size: 3, + last_sig_coeff_x: 7, + last_sig_coeff_y: 7, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }; + let unit = TransformUnit { + tu_residual_act_flag: 1, + residual_luma: Some(raw(vec![4; 64])), + residual_cb: vec![raw(vec![3; 64])], + residual_cr: vec![raw(vec![14; 64])], + cbf_cb_halves: [true, false], + cbf_cr_halves: [true, false], + ..Default::default() + }; + let tree = TransformTree::Leaf { + cbf_luma: true, + unit, + }; + let res = extract_cu_residual(¶ms, Some(&tree), 0, 0, 8, 25, true).unwrap(); + assert!(res.luma.samples.iter().all(|&v| v == 6), "luma"); + assert!( + res.cb.as_ref().unwrap().samples.iter().all(|&v| v == -4), + "cb" + ); + assert!( + res.cr.as_ref().unwrap().samples.iter().all(|&v| v == 10), + "cr" + ); + } + + /// §8.4.4.1 step-8 ordering: cross-component prediction applies + /// BEFORE the §8.6.8.2 colour transform. Luma coded 8 with + /// ResScaleVal +8 on Cb: rCb becomes 8 before the lifting ⇒ + /// tmp = 8 − 4 = 4, rY = 12, rCb = 4, rCr = 4 (Cr CCP absent, + /// rCr = 0 + rCb after eq. 8-339... rCr = 0 → rCb' = 4 ⇒ rCr = 4). + #[test] + fn act_applies_after_ccp() { + let params = params_444(); + let raw = |levels: Vec| ResidualBlock { + log2_trafo_size: 3, + last_sig_coeff_x: 7, + last_sig_coeff_y: 7, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }; + let unit = TransformUnit { + tu_residual_act_flag: 1, + residual_luma: Some(raw(vec![8; 64])), + cross_comp_pred_cb: Some(ccp(8)), + ..Default::default() + }; + let tree = TransformTree::Leaf { + cbf_luma: true, + unit, + }; + let res = extract_cu_residual(¶ms, Some(&tree), 0, 0, 8, 25, true).unwrap(); + assert!(res.luma.samples.iter().all(|&v| v == 12), "luma"); + assert!( + res.cb.as_ref().unwrap().samples.iter().all(|&v| v == 4), + "cb" + ); + assert!( + res.cr.as_ref().unwrap().samples.iter().all(|&v| v == 4), + "cr" + ); + } +} diff --git a/vendor/oxideav-h265/src/residual.rs b/vendor/oxideav-h265/src/residual.rs new file mode 100644 index 0000000..0740d31 --- /dev/null +++ b/vendor/oxideav-h265/src/residual.rs @@ -0,0 +1,1588 @@ +//! §7.3.8.11 `residual_coding( x0, y0, log2TrafoSize, cIdx )` syntax +//! driver. +//! +//! This module composes the per-element residual primitives the +//! [`crate::binarization`] module accumulated across rounds 26..35 — +//! `last_sig_coeff_{x,y}_{prefix,suffix}` (§9.3.4.2.3), +//! `coded_sub_block_flag` (§9.3.4.2.4), `sig_coeff_flag` (§9.3.4.2.5, +//! including the Table 9-50 16-entry `ctxIdxMap` whose `i = 15` cell +//! is pinned to `8` by the staged docs erratum for the PDF layout +//! truncation), `coeff_abs_level_greater1_flag` / +//! `coeff_abs_level_greater2_flag` (§9.3.4.2.6 / §9.3.4.2.7 via +//! [`Greater1State`]), `coeff_abs_level_remaining` (§9.3.3.11) and +//! `coeff_sign_flag` — into the full §7.3.8.11 coefficient-decode +//! loop that reconstructs the `TransCoeffLevel[ ][ ]` array of one +//! transform block. +//! +//! ## Driver scope +//! +//! [`decode_residual_coding_with`] implements the §7.3.8.11 syntax +//! from `last_sig_coeff_x_prefix` through the final +//! `TransCoeffLevel` composition: +//! +//! * the §7.3.8.11 do-while locate of `(lastSubBlock, lastScanPos)` +//! from the decoded (and, for `scanIdx == 2`, eq.-7-78-swapped) +//! `LastSignificantCoeff{X,Y}`, +//! * the reverse sub-block scan with `coded_sub_block_flag` decode +//! (presence gate `i < lastSubBlock && i > 0`) and the §7.4.9.11 +//! not-present inference (sub-blocks `0` and `lastSubBlock` ⇒ 1), +//! * the per-sub-block `sig_coeff_flag` loop with both §7.4.9.11 +//! inference rules (the last significant coefficient itself ⇒ 1; +//! the DC cell of a coded sub-block whose other 15 flags decoded +//! to 0 under `inferSbDcSigCoeffFlag` ⇒ 1) and the full +//! §9.3.4.2.5 `sigCtx` branch dispatch (eq. 9-40 transform-skip +//! contexts / Table 9-50 for `log2TrafoSize == 2` / eq. 9-42 DC / +//! eq. 9-43..9-53 general), +//! * the `coeff_abs_level_greater1_flag` pass with the per-sub-block +//! `numGreater1Flag < 8` cap and the §9.3.4.2.6 cross-sub-block +//! `ctxSet` state ([`Greater1State`] is entered lazily at the +//! first greater-1 bin of each sub-block, matching the spec's +//! "first time for the current sub-block scan index i" trigger so +//! sub-blocks that decode no greater-1 bins do not advance the +//! state), +//! * the at-most-one `coeff_abs_level_greater2_flag` at +//! `lastGreater1ScanPos` (§9.3.4.2.7, eq. 9-61 / 9-62), +//! * the §7.3.8.11 `signHidden` derivation +//! (`lastSigScanPos − firstSigScanPos > 3`, force-zeroed by the +//! transquant-bypass / RDPCM conditions the caller folds into +//! [`ResidualCodingParams::sign_hidden_suppressed`]) with the +//! `coeff_sign_flag` presence gate and the odd-parity +//! `sumAbsLevel` negation at `firstSigScanPos`, +//! * the level loop: `baseLevel = 1 + greater1 + greater2`, the +//! `coeff_abs_level_remaining` presence test +//! `baseLevel == ( ( numSigCoeff < 8 ) ? ( ( n == lastGreater1ScanPos ) ? 3 : 2 ) : 1 )`, +//! and the §9.3.3.11 per-sub-block Rice adaptation +//! (`cLastAbsLevel` / `cLastRiceParam` reset at the first +//! `coeff_abs_level_remaining` invocation of each sub-block, then +//! carried via eq. 9-24 — the +//! `persistent_rice_adaptation_enabled_flag == 0` path; the +//! persistent `StatCoeff[ sbType ]` path of eqs. 9-20..9-23 / +//! 9-25 remains with the §9.3.3.11 follow-up noted on +//! [`crate::binarization::decode_coeff_abs_level_remaining`]). +//! +//! Out of driver scope (caller-supplied / follow-up): +//! +//! * The leading `transform_skip_flag` / `explicit_rdpcm_flag` / +//! `explicit_rdpcm_dir_flag` elements of §7.3.8.11: their +//! presence gates hang off PPS / CU state the slice parser owns. +//! Their decoded (or §7.4.9.11-inferred-0) values reach this +//! driver only through the two derived booleans in +//! [`ResidualCodingParams`] +//! ([`sign_hidden_suppressed`](ResidualCodingParams::sign_hidden_suppressed) +//! and +//! [`transform_skip_sig_ctx`](ResidualCodingParams::transform_skip_sig_ctx)). +//! * The §9.3.4.3.6 aligned-bypass mode +//! (`cabac_bypass_alignment_enabled_flag`, a range-extension +//! tool) and the `escapeDataPresent` bookkeeping that exists only +//! to feed it — the baseline bypass decoder is used throughout. +//! * The §7.4.9.11 `scanIdx` derivation is exposed separately as +//! [`residual_coding_scan_idx`] so the caller (which owns +//! `CuPredMode` / `IntraPredModeY` / `IntraPredModeC`) selects +//! the scan before invoking the driver. +//! +//! ## Bin-source abstraction +//! +//! The driver is generic over [`ResidualBinSource`], mirroring the +//! `decode_coeff_abs_level_remaining_with` pattern: tests drive the +//! syntax loop with scripted bin sequences and assert both the +//! reconstructed levels and the exact `(element, ctxInc)` request +//! sequence, independently of the arithmetic engine's bin/bit +//! relationship. [`EngineResidualBinSource`] is the production +//! binding: it routes context-coded bins through +//! [`CabacEngine::decode_decision`] against the per-element banks in +//! [`ResidualContexts`] and bypass bins through +//! [`CabacEngine::decode_bypass`]. +//! +//! Context-bank sizes follow the spec's initValue tables (each table +//! spans the three `initType` columns, so the per-`initType` bank is +//! a third of the table's ctxIdx count): Table 9-26 / 9-27 +//! (`last_sig_coeff_{x,y}_prefix`, 54 ⇒ 18), Table 9-28 +//! (`coded_sub_block_flag`, 12 ⇒ 4), Table 9-29 (`sig_coeff_flag`, +//! 132 ⇒ 44), Table 9-30 (`coeff_abs_level_greater1_flag`, 72 ⇒ 24) +//! and Table 9-31 (`coeff_abs_level_greater2_flag`, 18 ⇒ 6). The +//! initValue tables themselves live in [`crate::ctx_init`]; +//! [`ResidualContexts::init`] performs the §9.3.2.2 per-`initType` +//! bank initialization from them, and +//! [`ResidualContexts::init_uniform`] remains as a single-initValue +//! bring-up constructor for scripted tests. + +use crate::binarization::{ + coded_sub_block_flag_ctx_inc_with_edge, coeff_abs_level_greater2_flag_ctx_inc, + coeff_abs_level_remaining_c_rice_param_eq_9_24, coeff_abs_level_remaining_c_rice_param_eq_9_25, + decode_coeff_abs_level_remaining_ext_with, decode_coeff_abs_level_remaining_with, + last_sig_coeff_position, last_sig_coeff_prefix_cmax, last_sig_coeff_prefix_ctx_inc, + last_sig_coeff_prefix_ctx_offset_shift, last_sig_coeff_suffix_n_bits, + read_truncated_rice_prefix, sig_coeff_flag_ctx_inc_from_sig_ctx, sig_coeff_flag_sig_ctx_dc, + sig_coeff_flag_sig_ctx_general, sig_coeff_flag_sig_ctx_log2_2, + sig_coeff_flag_sig_ctx_transform_skip, signed_level_from_sign_flag, Greater1State, +}; +use crate::cabac::{CabacEngine, CabacError, ContextModel}; +use crate::scan::{scan_order, ScanIdx, ScanOrderError}; + +// --------------------------------------------------------------------- +// Context banks +// --------------------------------------------------------------------- + +/// Per-`initType` context count for `last_sig_coeff_x_prefix` / +/// `last_sig_coeff_y_prefix` — Table 9-26 / Table 9-27 list ctxIdx +/// 0..53 across the three `initType` columns, 18 per `initType` +/// (§9.3.4.2.3 reaches ctxInc 0..=17: luma `ctxOffset + (binIdx >> +/// ctxShift)` peaks at 14 for `log2TrafoSize == 5`, chroma at +/// `15 + (binIdx >> 0)` ≤ 17 for `log2TrafoSize == 2`). +pub const LAST_SIG_COEFF_PREFIX_CTX_COUNT: usize = 18; + +/// Per-`initType` context count for `coded_sub_block_flag` — +/// Table 9-28 lists ctxIdx 0..11 across the three `initType` +/// columns, 4 per `initType` (§9.3.4.2.4: luma `{0, 1}`, chroma +/// `{2, 3}`). +pub const CODED_SUB_BLOCK_FLAG_CTX_COUNT: usize = 4; + +/// Per-`initType` context count for `sig_coeff_flag` — Table 9-29 +/// lists ctxIdx 0..131 across the three `initType` columns, 44 per +/// `initType` (§9.3.4.2.5: luma ctxInc 0..=26 plus the eq.-9-40 +/// transform-skip slot 42; chroma `27 + sigCtx` ≤ 41 plus the +/// transform-skip slot 43). +pub const SIG_COEFF_FLAG_CTX_COUNT: usize = 44; + +/// Per-`initType` context count for `coeff_abs_level_greater1_flag` +/// — Table 9-30 lists ctxIdx 0..71 across the three `initType` +/// columns, 24 per `initType` (eq. 9-59 luma `ctxSet * 4 + Min(3, +/// greater1Ctx)` ≤ 15, eq. 9-60 chroma `+ 16` ≤ 23). +pub const COEFF_ABS_LEVEL_GREATER1_FLAG_CTX_COUNT: usize = 24; + +/// Per-`initType` context count for `coeff_abs_level_greater2_flag` +/// — Table 9-31 lists ctxIdx 0..17 across the three `initType` +/// columns, 6 per `initType` (eq. 9-61 luma `ctxSet` ≤ 3, eq. 9-62 +/// chroma `ctxSet + 4` ≤ 5). +pub const COEFF_ABS_LEVEL_GREATER2_FLAG_CTX_COUNT: usize = 6; + +/// The context-coded syntax-element banks one §7.3.8.11 +/// `residual_coding( )` invocation draws on. Identifies which +/// [`ResidualContexts`] bank a [`ResidualBinSource::decision`] +/// request addresses; the paired `ctxInc` is bank-relative per the +/// §9.3.4.2 derivations. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum ResidualElement { + /// `last_sig_coeff_x_prefix` (§9.3.4.2.3). + LastSigCoeffXPrefix, + /// `last_sig_coeff_y_prefix` (§9.3.4.2.3). + LastSigCoeffYPrefix, + /// `coded_sub_block_flag` (§9.3.4.2.4). + CodedSubBlockFlag, + /// `sig_coeff_flag` (§9.3.4.2.5). + SigCoeffFlag, + /// `coeff_abs_level_greater1_flag` (§9.3.4.2.6). + CoeffAbsLevelGreater1Flag, + /// `coeff_abs_level_greater2_flag` (§9.3.4.2.7). + CoeffAbsLevelGreater2Flag, +} + +/// The per-`initType` CABAC context banks for the residual-coding +/// syntax elements, sized per Tables 9-26..9-31 (see the bank-size +/// constants). [`init`](Self::init) performs the §9.3.2.2 +/// initialization from the Table 9-26..9-31 initValues with the +/// Table 9-4 `initType` → ctxIdx mapping (tables in +/// [`crate::ctx_init`]); [`init_uniform`](Self::init_uniform) +/// constructs a bank set from a single initValue for bring-up and +/// tests. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResidualContexts { + /// `last_sig_coeff_x_prefix` bank (Table 9-26). + pub last_sig_coeff_x_prefix: [ContextModel; LAST_SIG_COEFF_PREFIX_CTX_COUNT], + /// `last_sig_coeff_y_prefix` bank (Table 9-27). + pub last_sig_coeff_y_prefix: [ContextModel; LAST_SIG_COEFF_PREFIX_CTX_COUNT], + /// `coded_sub_block_flag` bank (Table 9-28). + pub coded_sub_block_flag: [ContextModel; CODED_SUB_BLOCK_FLAG_CTX_COUNT], + /// `sig_coeff_flag` bank (Table 9-29). + pub sig_coeff_flag: [ContextModel; SIG_COEFF_FLAG_CTX_COUNT], + /// `coeff_abs_level_greater1_flag` bank (Table 9-30). + pub coeff_abs_level_greater1_flag: [ContextModel; COEFF_ABS_LEVEL_GREATER1_FLAG_CTX_COUNT], + /// `coeff_abs_level_greater2_flag` bank (Table 9-31). + pub coeff_abs_level_greater2_flag: [ContextModel; COEFF_ABS_LEVEL_GREATER2_FLAG_CTX_COUNT], + /// §9.3.2.2 Rice-parameter initialization states `StatCoeff[ k ]`, + /// `k` = eq. 9-20/9-21 `sbType` (0/1 chroma transform / bypass, + /// 2/3 luma transform / bypass). Zeroed at context + /// initialization, updated once per sub-block by the §9.3.3.11 + /// eq. 9-23 rule, and carried inside the context bank so the + /// §9.3.2.4 / §9.3.2.5 WPP and dependent-segment storage + /// (`TableStatCoeffWpp` / `TableStatCoeffDs`) travels with the + /// context-variable snapshot. Only consulted when + /// `persistent_rice_adaptation_enabled_flag == 1`. + pub stat_coeff: [u8; 4], +} + +impl ResidualContexts { + /// §9.3.2.2 initialization of every bank from the Table 9-26..9-31 + /// `initValue` entries for the given `initType` (the Table 9-4 + /// ctxIdx spans; see [`crate::ctx_init`]) at `SliceQpY == + /// slice_qp_y` (equation 7-54). + /// + /// # Panics + /// + /// Panics when `init_type > 2`. + #[must_use] + pub fn init(init_type: u8, slice_qp_y: i32) -> Self { + use crate::ctx_init::{ + sig_coeff_flag_init_values, uniform_init_values, TABLE_9_26_LAST_SIG_COEFF_X_PREFIX, + TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX, TABLE_9_28_CODED_SUB_BLOCK_FLAG, + TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG, TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG, + }; + let init = |v: u8| ContextModel::init(v, slice_qp_y); + Self { + last_sig_coeff_x_prefix: uniform_init_values::( + &TABLE_9_26_LAST_SIG_COEFF_X_PREFIX, + init_type, + ) + .map(init), + last_sig_coeff_y_prefix: uniform_init_values::( + &TABLE_9_27_LAST_SIG_COEFF_Y_PREFIX, + init_type, + ) + .map(init), + coded_sub_block_flag: uniform_init_values::( + &TABLE_9_28_CODED_SUB_BLOCK_FLAG, + init_type, + ) + .map(init), + sig_coeff_flag: sig_coeff_flag_init_values(init_type).map(init), + coeff_abs_level_greater1_flag: uniform_init_values::< + COEFF_ABS_LEVEL_GREATER1_FLAG_CTX_COUNT, + >( + &TABLE_9_30_COEFF_ABS_LEVEL_GREATER1_FLAG, init_type + ) + .map(init), + coeff_abs_level_greater2_flag: uniform_init_values::< + COEFF_ABS_LEVEL_GREATER2_FLAG_CTX_COUNT, + >( + &TABLE_9_31_COEFF_ABS_LEVEL_GREATER2_FLAG, init_type + ) + .map(init), + stat_coeff: [0; 4], + } + } + + /// Initialize every context in every bank from one `initValue` + /// via the §9.3.2.2 process ([`ContextModel::init`]). + /// + /// Bring-up scaffolding predating [`init`](Self::init): uniform + /// initialization still exercises every engine/state path (only + /// the per-context starting probabilities differ), and the + /// scripted-bin tests keep using it. + #[must_use] + pub fn init_uniform(init_value: u8, slice_qp_y: i32) -> Self { + let c = ContextModel::init(init_value, slice_qp_y); + Self { + last_sig_coeff_x_prefix: [c; LAST_SIG_COEFF_PREFIX_CTX_COUNT], + last_sig_coeff_y_prefix: [c; LAST_SIG_COEFF_PREFIX_CTX_COUNT], + coded_sub_block_flag: [c; CODED_SUB_BLOCK_FLAG_CTX_COUNT], + sig_coeff_flag: [c; SIG_COEFF_FLAG_CTX_COUNT], + coeff_abs_level_greater1_flag: [c; COEFF_ABS_LEVEL_GREATER1_FLAG_CTX_COUNT], + coeff_abs_level_greater2_flag: [c; COEFF_ABS_LEVEL_GREATER2_FLAG_CTX_COUNT], + stat_coeff: [0; 4], + } + } +} + +// --------------------------------------------------------------------- +// Bin-source abstraction +// --------------------------------------------------------------------- + +/// A source of decoded bins for the §7.3.8.11 driver. The production +/// implementation is [`EngineResidualBinSource`]; tests supply +/// scripted sources that also record the `(element, ctxInc)` request +/// sequence. +pub trait ResidualBinSource { + /// Decode one context-coded bin for `element` using the + /// bank-relative `ctx_inc` derived per §9.3.4.2. + fn decision(&mut self, element: ResidualElement, ctx_inc: u32) -> Result; + + /// Decode one bypass-coded bin (§9.3.4.3.4). + fn bypass(&mut self) -> Result; + + /// Decode `n` bypass-coded bins MSB-first into one value. + fn bypass_bits(&mut self, n: u8) -> Result { + let mut value: u32 = 0; + for _ in 0..n { + value = (value << 1) | u32::from(self.bypass()?); + } + Ok(value) + } + + /// §9.3.4.3.6 — alignment prior to aligned bypass decoding + /// (`ivlCurrRange = 256`). Invoked by the driver before the + /// `coeff_sign_flag` / `coeff_abs_level_remaining` bypass run of + /// a sub-block when `cabac_bypass_alignment_enabled_flag == 1` + /// and `escapeDataPresent == 1`. Scripted sources may treat it as + /// a recording no-op — the aligned engine still serves one bin + /// per call. + fn align_bypass(&mut self) {} + + /// Mutable access to the §9.3.2.2 `StatCoeff[ k ]` Rice + /// initialization states, consulted and updated (eqs. 9-22 / + /// 9-23) only when `persistent_rice_adaptation_enabled_flag == + /// 1`. The production source exposes + /// [`ResidualContexts::stat_coeff`] so the state persists across + /// TUs and travels with the WPP / dependent-segment context + /// storage. + fn stat_coeff(&mut self) -> &mut [u8; 4]; +} + +/// The production [`ResidualBinSource`]: context-coded bins go +/// through [`CabacEngine::decode_decision`] against the matching +/// [`ResidualContexts`] bank slot; bypass bins through +/// [`CabacEngine::decode_bypass`]. +#[derive(Debug)] +pub struct EngineResidualBinSource<'e, 'a, 'c> { + /// The arithmetic decoding engine, positioned in the slice-data + /// bin stream. + pub engine: &'e mut CabacEngine<'a>, + /// The residual context banks for the active `initType`. + pub contexts: &'c mut ResidualContexts, +} + +impl ResidualBinSource for EngineResidualBinSource<'_, '_, '_> { + fn decision(&mut self, element: ResidualElement, ctx_inc: u32) -> Result { + let bank: &mut [ContextModel] = match element { + ResidualElement::LastSigCoeffXPrefix => &mut self.contexts.last_sig_coeff_x_prefix, + ResidualElement::LastSigCoeffYPrefix => &mut self.contexts.last_sig_coeff_y_prefix, + ResidualElement::CodedSubBlockFlag => &mut self.contexts.coded_sub_block_flag, + ResidualElement::SigCoeffFlag => &mut self.contexts.sig_coeff_flag, + ResidualElement::CoeffAbsLevelGreater1Flag => { + &mut self.contexts.coeff_abs_level_greater1_flag + } + ResidualElement::CoeffAbsLevelGreater2Flag => { + &mut self.contexts.coeff_abs_level_greater2_flag + } + }; + // The §9.3.4.2 derivations bound every ctxInc by the bank + // sizes documented on the *_CTX_COUNT constants, so the + // index is in-bounds for driver-produced requests. + self.engine.decode_decision(&mut bank[ctx_inc as usize]) + } + + fn bypass(&mut self) -> Result { + self.engine.decode_bypass() + } + + fn bypass_bits(&mut self, n: u8) -> Result { + self.engine.decode_bypass_bits(n) + } + + fn align_bypass(&mut self) { + self.engine.align_bypass(); + } + + fn stat_coeff(&mut self) -> &mut [u8; 4] { + &mut self.contexts.stat_coeff + } +} + +// --------------------------------------------------------------------- +// Parameters / output / errors +// --------------------------------------------------------------------- + +/// Caller-derived inputs to one §7.3.8.11 `residual_coding( )` +/// invocation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResidualCodingParams { + /// `log2TrafoSize` of the transform block, 2..=5. + pub log2_trafo_size: u32, + /// `cIdx > 0` — selects every chroma context/derivation branch. + pub is_chroma: bool, + /// The §7.4.9.11 scan order ([`residual_coding_scan_idx`]). + /// Only [`ScanIdx::Diagonal`] / [`ScanIdx::Horizontal`] / + /// [`ScanIdx::Vertical`] are reachable from §7.4.9.11. + pub scan_idx: ScanIdx, + /// PPS `sign_data_hiding_enabled_flag` (§7.3.2.3.1). + pub sign_data_hiding_enabled_flag: bool, + /// The §7.3.8.11 `signHidden = 0` force condition: + /// `cu_transquant_bypass_flag`, or the implicit-RDPCM intra + /// condition (`implicit_rdpcm_enabled_flag && + /// transform_skip_flag && predModeIntra ∈ {10, 26}`), or + /// `explicit_rdpcm_flag`. When `true`, `signHidden` is 0 + /// regardless of the scan-position spread. + pub sign_hidden_suppressed: bool, + /// The §9.3.4.2.5 first-branch gate (eq. 9-40): + /// `transform_skip_context_enabled_flag && + /// ( transform_skip_flag || cu_transquant_bypass_flag )`. When + /// `true`, every `sig_coeff_flag` bin uses the dedicated + /// transform-skip context (42 luma / 16-chroma `sigCtx`). + pub transform_skip_sig_ctx: bool, + /// SPS range extension `persistent_rice_adaptation_enabled_flag` + /// — switches the `coeff_abs_level_remaining` Rice derivation to + /// the §9.3.3.11 eqs. 9-20..9-23 / 9-25 persistent path + /// (`StatCoeff[ sbType ]`-seeded, uncapped). + pub persistent_rice_adaptation_enabled_flag: bool, + /// SPS range extension `cabac_bypass_alignment_enabled_flag` — + /// the §9.3.4.3.6 alignment runs before the sub-block's + /// `coeff_sign_flag` / `coeff_abs_level_remaining` bypass bins + /// when `escapeDataPresent == 1`. + pub cabac_bypass_alignment_enabled_flag: bool, + /// SPS range extension `extended_precision_processing_flag` — + /// the `coeff_abs_level_remaining` escape suffix uses the + /// §9.3.3.4 limited EGk binarization with the eq. 9-14 + /// `log2TransformRange`. + pub extended_precision_processing_flag: bool, + /// `BitDepth` of the block's colour component (eq. 9-14 input; + /// only consulted when `extended_precision_processing_flag`). + pub bit_depth: u8, + /// The eq. 9-20/9-21 `sbType` discriminator: + /// `transform_skip_flag || cu_transquant_bypass_flag` (only + /// consulted when `persistent_rice_adaptation_enabled_flag`). + pub rice_stat_transform_skip: bool, +} + +/// The reconstructed coefficient array of one transform block — +/// §7.3.8.11 `TransCoeffLevel[ x0 ][ y0 ][ cIdx ][ ][ ]` with the +/// `( x0, y0, cIdx )` indices fixed by the invocation. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ResidualBlock { + /// `log2TrafoSize` — the block spans `1 << log2_trafo_size` + /// coefficients per side. + pub log2_trafo_size: u32, + /// §7.4.9.11 `LastSignificantCoeffX` (post the eq.-7-78 swap for + /// `scanIdx == 2`). + pub last_sig_coeff_x: u32, + /// §7.4.9.11 `LastSignificantCoeffY` (post the eq.-7-78 swap). + pub last_sig_coeff_y: u32, + /// Row-major `TransCoeffLevel[ yC ][ xC ]`, length + /// `(1 << log2_trafo_size)²`. Positions past the last + /// significant coefficient and in uncoded sub-blocks are 0. + pub levels: Vec, + /// `transform_skip_flag[ x0 ][ y0 ][ cIdx ]` (§7.3.8.11) — decoded + /// by the transform-unit driver before this block's coefficients; + /// `false` when the §7.3.8.11 presence gate did not fire. + pub transform_skip: bool, + /// `explicit_rdpcm_flag[ x0 ][ y0 ][ cIdx ]` (§7.3.8.11, range + /// extensions) — parsed for bit-exactness; the §8.6.8 RDPCM + /// reconstruction is a follow-up (reconstruction rejects it). + pub explicit_rdpcm_flag: bool, + /// `explicit_rdpcm_dir_flag[ x0 ][ y0 ][ cIdx ]` (§7.3.8.11). + pub explicit_rdpcm_dir_flag: bool, +} + +impl ResidualBlock { + /// Block side length in coefficients (`1 << log2_trafo_size`). + #[must_use] + pub fn size(&self) -> usize { + 1usize << self.log2_trafo_size + } + + /// `TransCoeffLevel[ xC ][ yC ]` accessor (spec index order; the + /// backing storage is row-major by `yC`). + /// + /// # Panics + /// Panics if `xc` or `yc` is outside `0..size()`. + #[must_use] + pub fn level(&self, xc: usize, yc: usize) -> i32 { + let size = self.size(); + assert!(xc < size && yc < size, "coefficient index out of block"); + self.levels[yc * size + xc] + } +} + +/// Errors from the §7.3.8.11 driver. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ResidualCodingError { + /// The underlying bin source failed (arithmetic-engine error / + /// bitstream exhausted). + Cabac(CabacError), + /// The §6.5 scan-order table rejected the request. + ScanOrder(ScanOrderError), + /// `log2TrafoSize` outside 2..=5 (§7.4.9.8 transform-block size + /// bounds). + UnsupportedLog2TrafoSize(u32), + /// A scan order §7.4.9.11 never selects for `residual_coding( )` + /// (only diagonal / horizontal / vertical are reachable). + UnsupportedScanIdx(ScanIdx), + /// A §7.3.8.13 `palette_coding( )` element violated a parse bound. + Palette(crate::palette::PaletteError), +} + +impl From for ResidualCodingError { + fn from(e: crate::palette::PaletteError) -> Self { + Self::Palette(e) + } +} + +impl core::fmt::Display for ResidualCodingError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Cabac(e) => write!(f, "residual_coding: {e}"), + Self::ScanOrder(e) => write!(f, "residual_coding: {e}"), + Self::UnsupportedLog2TrafoSize(v) => { + write!(f, "residual_coding: log2TrafoSize {v} outside 2..=5") + } + Self::Palette(e) => write!(f, "{e}"), + Self::UnsupportedScanIdx(s) => { + write!( + f, + "residual_coding: scanIdx {s:?} not reachable from §7.4.9.11" + ) + } + } + } +} + +impl std::error::Error for ResidualCodingError {} + +impl From for ResidualCodingError { + fn from(e: CabacError) -> Self { + Self::Cabac(e) + } +} + +impl From for ResidualCodingError { + fn from(e: ScanOrderError) -> Self { + Self::ScanOrder(e) + } +} + +// --------------------------------------------------------------------- +// §7.4.9.11 scanIdx derivation +// --------------------------------------------------------------------- + +/// §7.4.9.11 — derive the `residual_coding( )` scan order. +/// +/// * `cu_pred_mode_is_intra` — `CuPredMode[ x0 ][ y0 ] == +/// MODE_INTRA`. +/// * `log2_trafo_size`, `c_idx`, `chroma_array_type` — the §7.4.9.11 +/// intra-scan eligibility conditions (`log2TrafoSize == 2`, or +/// `log2TrafoSize == 3` with `cIdx == 0`, or `log2TrafoSize == 3` +/// with `ChromaArrayType == 3`). +/// * `pred_mode_intra` — `IntraPredModeY[ x0 ][ y0 ]` when +/// `cIdx == 0`, else `IntraPredModeC` (the §7.4.9.11 selection). +/// +/// Modes 6..=14 select the vertical scan, 22..=30 the horizontal +/// scan; everything else (including all non-intra and all larger +/// transform blocks) the up-right diagonal scan. +#[must_use] +pub fn residual_coding_scan_idx( + cu_pred_mode_is_intra: bool, + log2_trafo_size: u32, + c_idx: u8, + chroma_array_type: u8, + pred_mode_intra: u32, +) -> ScanIdx { + let intra_scan_eligible = + log2_trafo_size == 2 || (log2_trafo_size == 3 && (c_idx == 0 || chroma_array_type == 3)); + if cu_pred_mode_is_intra && intra_scan_eligible { + if (6..=14).contains(&pred_mode_intra) { + ScanIdx::Vertical + } else if (22..=30).contains(&pred_mode_intra) { + ScanIdx::Horizontal + } else { + ScanIdx::Diagonal + } + } else { + ScanIdx::Diagonal + } +} + +// --------------------------------------------------------------------- +// Driver +// --------------------------------------------------------------------- + +/// Decode one `last_sig_coeff_*_{prefix,suffix}` pair through the bin +/// source and return the §7.4.9.11 derived position (eqs. 7-74..7-77). +fn read_last_sig_prefix( + bins: &mut B, + log2_trafo_size: u32, + is_chroma: bool, + element: ResidualElement, +) -> Result { + let c_max = last_sig_coeff_prefix_cmax(log2_trafo_size); + let (ctx_offset, ctx_shift) = + last_sig_coeff_prefix_ctx_offset_shift(log2_trafo_size, is_chroma); + let (prefix, _is_escape) = read_truncated_rice_prefix(c_max, |bin_idx| { + let ctx_inc = last_sig_coeff_prefix_ctx_inc(bin_idx, ctx_offset, ctx_shift); + bins.decision(element, ctx_inc) + })?; + Ok(prefix) +} + +/// §7.3.8.11 — the conditional bypass suffix for one +/// `last_sig_coeff_{x,y}_prefix` value (present when `prefix > 3`), +/// folded into the §7.4.9.11 position. +fn read_last_sig_suffix( + bins: &mut B, + prefix: u32, +) -> Result { + let n_bits = last_sig_coeff_suffix_n_bits(prefix); + let suffix = if n_bits > 0 { + Some(bins.bypass_bits(n_bits as u8)?) + } else { + None + }; + Ok(last_sig_coeff_position(prefix, suffix)) +} + +/// §7.3.8.11 — decode one `residual_coding( )` body (from +/// `last_sig_coeff_x_prefix` onward; see the module docs for the +/// exact scope) against a generic [`ResidualBinSource`]. +/// +/// Returns the reconstructed [`ResidualBlock`]. See +/// [`decode_residual_coding`] for the engine-backed entry point. +pub fn decode_residual_coding_with( + params: &ResidualCodingParams, + bins: &mut B, +) -> Result { + let log2 = params.log2_trafo_size; + if !(2..=5).contains(&log2) { + return Err(ResidualCodingError::UnsupportedLog2TrafoSize(log2)); + } + let scan_idx_num = u32::from(params.scan_idx.index()); + if scan_idx_num > 2 { + return Err(ResidualCodingError::UnsupportedScanIdx(params.scan_idx)); + } + let is_chroma = params.is_chroma; + + // last_sig_coeff_{x,y}_{prefix,suffix} → LastSignificantCoeff{X,Y} + // (eqs. 7-74..7-77), then the eq.-7-78 swap for the vertical scan. + // §7.3.8.11 bin order: BOTH context-coded prefixes come first, then + // the two conditional bypass suffixes (x, then y). + let prefix_x = + read_last_sig_prefix(bins, log2, is_chroma, ResidualElement::LastSigCoeffXPrefix)?; + let prefix_y = + read_last_sig_prefix(bins, log2, is_chroma, ResidualElement::LastSigCoeffYPrefix)?; + let wire_x = read_last_sig_suffix(bins, prefix_x)?; + let wire_y = read_last_sig_suffix(bins, prefix_y)?; + let (last_x, last_y) = if params.scan_idx == ScanIdx::Vertical { + (wire_y, wire_x) + } else { + (wire_x, wire_y) + }; + + // §6.5 scan tables: the 4x4 in-sub-block scan and the sub-block + // scan over the (1 << (log2 - 2))² grid. + let pos_scan = scan_order(2, params.scan_idx)?; + let sub_scan = scan_order((log2 - 2) as u8, params.scan_idx)?; + let num_sb_1d = 1usize << (log2 - 2); + let size = 1usize << log2; + + // §7.3.8.11 do-while: locate (lastSubBlock, lastScanPos) from the + // last-significant position. The decoded position is always + // inside the TB (the §9.3.4.2.3 cMax bounds the prefix), so the + // walk terminates. + let mut last_scan_pos: i32 = 16; + let mut last_sub_block: i32 = (num_sb_1d * num_sb_1d) as i32 - 1; + loop { + if last_scan_pos == 0 { + last_scan_pos = 16; + last_sub_block -= 1; + } + last_scan_pos -= 1; + debug_assert!(last_sub_block >= 0, "last-sig position outside the TB"); + let sb = sub_scan[last_sub_block as usize]; + let xc = (u32::from(sb.x) << 2) + u32::from(pos_scan[last_scan_pos as usize].x); + let yc = (u32::from(sb.y) << 2) + u32::from(pos_scan[last_scan_pos as usize].y); + if xc == last_x && yc == last_y { + break; + } + } + + let mut levels = vec![0i32; size * size]; + // coded_sub_block_flag[ xS ][ yS ] grid, row-major by yS. + let mut csbf = vec![0u8; num_sb_1d * num_sb_1d]; + let csbf_at = |grid: &[u8], xs: usize, ys: usize| -> u8 { + if xs < num_sb_1d && ys < num_sb_1d { + grid[ys * num_sb_1d + xs] + } else { + 0 + } + }; + + // §9.3.4.2.6 cross-sub-block greater-1 state. `last_g1_bin` is + // the most recently decoded coeff_abs_level_greater1_flag value, + // consumed by the next sub-block's lazy entry. + let mut g1_state = Greater1State::new(); + let mut last_g1_bin: u8 = 0; + + for i in (0..=last_sub_block).rev() { + let sb = sub_scan[i as usize]; + let (xs, ys) = (u32::from(sb.x), u32::from(sb.y)); + let is_last_sb = i == last_sub_block; + + // coded_sub_block_flag: decoded for 0 < i < lastSubBlock, + // inferred 1 for sub-blocks 0 and lastSubBlock (§7.4.9.11 — + // both inference conditions reduce to these two scan + // indices: (0,0) is sub-block scan index 0 and the + // last-significant sub-block is lastSubBlock). + let mut infer_sb_dc_sig = false; + let sb_coded: u8 = if i < last_sub_block && i > 0 { + let right = csbf_at(&csbf, xs as usize + 1, ys as usize); + let below = csbf_at(&csbf, xs as usize, ys as usize + 1); + let ctx_inc = + coded_sub_block_flag_ctx_inc_with_edge(is_chroma, xs, ys, log2, right, below); + let bin = bins.decision(ResidualElement::CodedSubBlockFlag, ctx_inc)?; + infer_sb_dc_sig = true; + bin + } else { + 1 + }; + csbf[ys as usize * num_sb_1d + xs as usize] = sb_coded; + + // sig_coeff_flag pass. `sig[n]` is indexed by the in-sub-block + // scan position n. + let mut sig = [0u8; 16]; + if is_last_sb { + // The last significant coefficient is significant by + // definition (§7.4.9.11 first inference bullet). + sig[last_scan_pos as usize] = 1; + } + let start_n: i32 = if is_last_sb { last_scan_pos - 1 } else { 15 }; + for n in (0..=start_n).rev() { + let xc = (xs << 2) + u32::from(pos_scan[n as usize].x); + let yc = (ys << 2) + u32::from(pos_scan[n as usize].y); + if sb_coded == 1 && (n > 0 || !infer_sb_dc_sig) { + // §9.3.4.2.5 sigCtx branch dispatch. + let sig_ctx = if params.transform_skip_sig_ctx { + sig_coeff_flag_sig_ctx_transform_skip(is_chroma) + } else if log2 == 2 { + sig_coeff_flag_sig_ctx_log2_2(xc & 3, yc & 3) + } else if xc + yc == 0 { + sig_coeff_flag_sig_ctx_dc(is_chroma, log2, scan_idx_num) + } else { + let right = csbf_at(&csbf, xs as usize + 1, ys as usize); + let below = csbf_at(&csbf, xs as usize, ys as usize + 1); + sig_coeff_flag_sig_ctx_general( + is_chroma, + log2, + xc, + yc, + xs, + ys, + right, + below, + scan_idx_num, + ) + }; + let ctx_inc = sig_coeff_flag_ctx_inc_from_sig_ctx(sig_ctx, is_chroma); + let bin = bins.decision(ResidualElement::SigCoeffFlag, ctx_inc)?; + sig[n as usize] = bin; + if bin == 1 { + infer_sb_dc_sig = false; + } + } else if n == 0 && sb_coded == 1 && infer_sb_dc_sig { + // §7.4.9.11 second inference bullet: the DC cell of a + // decoded-coded sub-block whose 15 other flags were + // all 0 is inferred significant. + sig[0] = 1; + } + } + + // coeff_abs_level_greater1_flag pass (§7.3.8.11), with the + // per-sub-block numGreater1Flag < 8 cap and the lazy + // §9.3.4.2.6 sub-block entry. + let mut first_sig_scan_pos: i32 = 16; + let mut last_sig_scan_pos: i32 = -1; + let mut num_greater1: u32 = 0; + let mut last_greater1_scan_pos: i32 = -1; + let mut g1 = [0u8; 16]; + let mut entered_subblock = false; + // §7.3.8.11 escapeDataPresent: set when any coefficient of + // this sub-block will (or may) carry a + // coeff_abs_level_remaining — a second-or-later greater1 + // flag, a significant position past the 8-flag cap, or a + // greater2 flag equal to 1. Gates the §9.3.4.3.6 aligned + // bypass decoding. + let mut escape_data_present = false; + for n in (0..16).rev() { + if sig[n] == 1 { + if num_greater1 < 8 { + if !entered_subblock { + g1_state.on_subblock_entry(i as u32, is_chroma, last_g1_bin); + entered_subblock = true; + } + let ctx_inc = g1_state.current_ctx_inc(is_chroma); + let bin = bins.decision(ResidualElement::CoeffAbsLevelGreater1Flag, ctx_inc)?; + g1_state.on_coeff_abs_level_greater1_flag(bin); + last_g1_bin = bin; + g1[n] = bin; + num_greater1 += 1; + if bin == 1 && last_greater1_scan_pos == -1 { + last_greater1_scan_pos = n as i32; + } else if bin == 1 { + escape_data_present = true; + } + } else { + escape_data_present = true; + } + if last_sig_scan_pos == -1 { + last_sig_scan_pos = n as i32; + } + first_sig_scan_pos = n as i32; + } + } + + // §7.3.8.11 signHidden. + let sign_hidden = if params.sign_hidden_suppressed { + false + } else { + last_sig_scan_pos - first_sig_scan_pos > 3 + }; + + // coeff_abs_level_greater2_flag — at most once per sub-block. + let mut g2 = [0u8; 16]; + if last_greater1_scan_pos != -1 { + let ctx_inc = coeff_abs_level_greater2_flag_ctx_inc(g1_state.ctx_set(), is_chroma); + let bin = bins.decision(ResidualElement::CoeffAbsLevelGreater2Flag, ctx_inc)?; + g2[last_greater1_scan_pos as usize] = bin; + if bin == 1 { + escape_data_present = true; + } + } + + // §9.3.4.3.6 — with cabac_bypass_alignment_enabled_flag, the + // bypass decoding of this sub-block's coeff_sign_flag and + // coeff_abs_level_remaining bins runs aligned + // (ivlCurrRange = 256) when escapeDataPresent == 1. All the + // remaining bins of the sub-block are bypass-coded, so one + // alignment here covers both passes. + if params.cabac_bypass_alignment_enabled_flag && escape_data_present { + bins.align_bypass(); + } + + // coeff_sign_flag pass (bypass): present for every significant + // position except the hidden first one. + let mut sign = [0u8; 16]; + for n in (0..16).rev() { + if sig[n] == 1 + && (!params.sign_data_hiding_enabled_flag + || !sign_hidden + || n as i32 != first_sig_scan_pos) + { + sign[n] = bins.bypass()?; + } + } + + // Level pass: coeff_abs_level_remaining + TransCoeffLevel + // composition, with the §9.3.3.11 per-sub-block Rice + // adaptation — eq. 9-24 when + // persistent_rice_adaptation_enabled_flag == 0, the + // StatCoeff-seeded eqs. 9-20..9-23 / 9-25 path when it is 1. + let mut num_sig_coeff: u32 = 0; + let mut sum_abs_level: u64 = 0; + let mut c_last_abs_level: u32 = 0; + let mut c_last_rice_param: u32 = 0; + // eq. 9-20 / 9-21 sbType (persistent path only). + let sb_type = 2 * usize::from(!is_chroma) + usize::from(params.rice_stat_transform_skip); + let mut first_remaining_in_sb = true; + for n in (0..16).rev() { + if sig[n] != 1 { + continue; + } + let base_level = 1 + u32::from(g1[n]) + u32::from(g2[n]); + let threshold = if num_sig_coeff < 8 { + if n as i32 == last_greater1_scan_pos { + 3 + } else { + 2 + } + } else { + 1 + }; + let mut remaining: u32 = 0; + if base_level == threshold { + let c_rice_param = if params.persistent_rice_adaptation_enabled_flag { + if first_remaining_in_sb { + // eq. 9-22: cLastRiceParam starts at + // initRiceValue = StatCoeff[ sbType ] / 4 + // (cLastAbsLevel stays 0). + c_last_rice_param = u32::from(bins.stat_coeff()[sb_type] / 4); + } + coeff_abs_level_remaining_c_rice_param_eq_9_25( + c_last_abs_level, + c_last_rice_param, + ) + } else { + coeff_abs_level_remaining_c_rice_param_eq_9_24( + c_last_abs_level, + c_last_rice_param, + ) + }; + remaining = if params.extended_precision_processing_flag { + // eq. 9-14: log2TransformRange = + // Max( 15, BitDepth + 6 ) for the component. + let log2_transform_range = + u32::from(params.bit_depth).saturating_add(6).max(15); + decode_coeff_abs_level_remaining_ext_with( + c_rice_param, + log2_transform_range, + || bins.bypass(), + )? + } else { + decode_coeff_abs_level_remaining_with(c_rice_param, || bins.bypass())? + }; + // eq. 9-23: the sub-block's FIRST + // coeff_abs_level_remaining updates + // StatCoeff[ sbType ] once (the shift distance is + // capped defensively; conforming states never near + // it). + if params.persistent_rice_adaptation_enabled_flag && first_remaining_in_sb { + let stat = &mut bins.stat_coeff()[sb_type]; + let shift = u32::from(*stat / 4).min(24); + if remaining >= (3u32 << shift) { + *stat = stat.saturating_add(1); + } else if u64::from(remaining) * 2 < (1u64 << shift) && *stat > 0 { + *stat -= 1; + } + } + first_remaining_in_sb = false; + // §9.3.3.11: cAbsLevel = baseLevel + + // coeff_abs_level_remaining[ n ]; carried with the + // cRiceParam to the next invocation in this sub-block. + // A non-conformant bin stream can drive `remaining` + // to the binarization's u32 saturation point, so the + // composition saturates instead of overflowing. + c_last_abs_level = base_level.saturating_add(remaining); + c_last_rice_param = c_rice_param; + } + // §7.4.9.11 bitstream conformance bounds the resulting + // TransCoeffLevel to [CoeffMin, CoeffMax]; the widest + // profile bound (eqs. 7-27 .. 7-30 with + // extended_precision_processing_flag and BitDepth 16) is + // ±(1 << 22). Clamping the magnitude keeps the decode + // total — and the i32 level array sound — on + // non-conformant escapes; conforming values are unchanged. + let abs_level = base_level.saturating_add(remaining).min(1 << 22); + let xc = (xs << 2) + u32::from(pos_scan[n].x); + let yc = (ys << 2) + u32::from(pos_scan[n].y); + let idx = yc as usize * size + xc as usize; + levels[idx] = signed_level_from_sign_flag(abs_level, sign[n]); + if params.sign_data_hiding_enabled_flag && sign_hidden { + sum_abs_level += u64::from(abs_level); + if n as i32 == first_sig_scan_pos && sum_abs_level % 2 == 1 { + levels[idx] = -levels[idx]; + } + } + num_sig_coeff += 1; + } + } + + Ok(ResidualBlock { + log2_trafo_size: log2, + last_sig_coeff_x: last_x, + last_sig_coeff_y: last_y, + levels, + transform_skip: false, + explicit_rdpcm_flag: false, + explicit_rdpcm_dir_flag: false, + }) +} + +/// §7.3.8.11 — engine-backed entry point: binds `engine` + `contexts` +/// into an [`EngineResidualBinSource`] and runs +/// [`decode_residual_coding_with`]. +pub fn decode_residual_coding( + engine: &mut CabacEngine<'_>, + contexts: &mut ResidualContexts, + params: &ResidualCodingParams, +) -> Result { + let mut bins = EngineResidualBinSource { engine, contexts }; + decode_residual_coding_with(params, &mut bins) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + use std::collections::VecDeque; + + /// Scripted [`ResidualBinSource`]: serves context-coded bins from + /// `decisions` and bypass bins from `bypasses`, recording every + /// `(element, ctxInc)` decision request so tests can assert the + /// exact §9.3.4.2 context sequence. + struct Scripted { + decisions: VecDeque, + bypasses: VecDeque, + log: Vec<(ResidualElement, u32)>, + bypass_reads: usize, + stat_coeff: [u8; 4], + } + + impl Scripted { + fn new(decisions: &[u8], bypasses: &[u8]) -> Self { + Self { + decisions: decisions.iter().copied().collect(), + bypasses: bypasses.iter().copied().collect(), + log: Vec::new(), + bypass_reads: 0, + stat_coeff: [0; 4], + } + } + } + + impl ResidualBinSource for Scripted { + fn decision(&mut self, element: ResidualElement, ctx_inc: u32) -> Result { + self.log.push((element, ctx_inc)); + Ok(self + .decisions + .pop_front() + .expect("decision script exhausted")) + } + + fn bypass(&mut self) -> Result { + self.bypass_reads += 1; + Ok(self.bypasses.pop_front().expect("bypass script exhausted")) + } + + fn stat_coeff(&mut self) -> &mut [u8; 4] { + &mut self.stat_coeff + } + } + + fn luma_params(log2: u32, scan_idx: ScanIdx) -> ResidualCodingParams { + ResidualCodingParams { + log2_trafo_size: log2, + is_chroma: false, + scan_idx, + sign_data_hiding_enabled_flag: false, + sign_hidden_suppressed: false, + transform_skip_sig_ctx: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth: 8, + rice_stat_transform_skip: false, + } + } + + /// DC-only 4x4 luma block: the last-significant position (0, 0) + /// makes every `sig_coeff_flag` inferred (the last coefficient + /// itself), so the only decisions are the two one-bin TR prefixes + /// and one `coeff_abs_level_greater1_flag`; the sign is the only + /// bypass bin. §7.3.8.11 + §9.3.4.2.3 (ctxOffset 0 / ctxShift 0 + /// for 4x4 luma) + eq. 9-59 (first sub-block: ctxSet 0, + /// greater1Ctx 1 ⇒ ctxInc 1). + #[test] + fn dc_only_4x4_luma() { + let params = luma_params(2, ScanIdx::Diagonal); + let mut bins = Scripted::new(&[0, 0, 0], &[1]); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!(block.last_sig_coeff_x, 0); + assert_eq!(block.last_sig_coeff_y, 0); + assert_eq!(block.level(0, 0), -1, "sign bin 1 ⇒ negative, abs 1"); + assert_eq!( + block.levels.iter().filter(|&&v| v != 0).count(), + 1, + "only the DC coefficient is non-zero" + ); + assert_eq!( + bins.log, + vec![ + (ResidualElement::LastSigCoeffXPrefix, 0), + (ResidualElement::LastSigCoeffYPrefix, 0), + (ResidualElement::CoeffAbsLevelGreater1Flag, 1), + ] + ); + assert_eq!(bins.bypass_reads, 1); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// Chroma DC-only 4x4: every bank routes through the chroma + /// offsets — last-sig prefix ctxOffset 15 (§9.3.4.2.3), greater-1 + /// `+ 16` (eq. 9-60). + #[test] + fn dc_only_4x4_chroma_ctx_routing() { + let params = ResidualCodingParams { + is_chroma: true, + ..luma_params(2, ScanIdx::Diagonal) + }; + let mut bins = Scripted::new(&[0, 0, 0], &[0]); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!(block.level(0, 0), 1); + assert_eq!( + bins.log, + vec![ + (ResidualElement::LastSigCoeffXPrefix, 15), + (ResidualElement::LastSigCoeffYPrefix, 15), + (ResidualElement::CoeffAbsLevelGreater1Flag, 17), + ] + ); + } + + /// Full 4x4 luma block with the last-significant coefficient at + /// (3, 3) (scan position 15): 15 decoded `sig_coeff_flag` bins + /// (all 0), a greater-1 = 1, a greater-2 = 1, and a + /// `coeff_abs_level_remaining` of 2 (TR bins `110`, cRiceParam 0) + /// at `baseLevel == 3`, composing `TransCoeffLevel = +5`. The + /// `sig_coeff_flag` ctxInc sequence is cross-checked against the + /// Table 9-50 lookup (including the erratum-pinned `i = 15 ⇒ 8` + /// cell, exercised at the (3, 3) start had it been decoded — here + /// the decoded cells sweep scan positions 14..0). + #[test] + fn last_at_3_3_with_remaining_4x4_luma() { + let params = luma_params(2, ScanIdx::Diagonal); + let mut decisions = vec![1, 1, 1, 1, 1, 1]; // two TR prefixes, value 3 = cMax + decisions.extend([0; 15]); // sig n = 14..0 + decisions.push(1); // greater1 at n = 15 + decisions.push(1); // greater2 at n = 15 + let mut bins = Scripted::new(&decisions, &[0, 1, 1, 0]); // sign +, remaining = 2 + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!((block.last_sig_coeff_x, block.last_sig_coeff_y), (3, 3)); + assert_eq!(block.level(3, 3), 5, "baseLevel 3 + remaining 2"); + assert_eq!(block.levels.iter().filter(|&&v| v != 0).count(), 1); + + // §9.3.4.2.3: 4x4 luma prefix ctxInc = binIdx (offset 0, + // shift 0). + assert_eq!( + bins.log[0..3], + [ + (ResidualElement::LastSigCoeffXPrefix, 0), + (ResidualElement::LastSigCoeffXPrefix, 1), + (ResidualElement::LastSigCoeffXPrefix, 2) + ] + ); + // The 15 sig bins route through the Table 9-50 map (eq. 9-41). + let pos_scan = scan_order(2, ScanIdx::Diagonal).unwrap(); + for (k, n) in (0..=14).rev().enumerate() { + let (element, ctx_inc) = bins.log[6 + k]; + assert_eq!(element, ResidualElement::SigCoeffFlag); + let expected = + sig_coeff_flag_sig_ctx_log2_2(u32::from(pos_scan[n].x), u32::from(pos_scan[n].y)); + assert_eq!(ctx_inc, expected, "sig ctxInc at scan pos {n}"); + } + assert_eq!( + bins.log[21], + (ResidualElement::CoeffAbsLevelGreater1Flag, 1) + ); + assert_eq!( + bins.log[22], + (ResidualElement::CoeffAbsLevelGreater2Flag, 0) + ); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// 8x8 luma block, last-significant at (4, 4) (sub-block (1, 1)): + /// exercises the `coded_sub_block_flag` decode + §9.3.4.2.4 + /// neighbour ctxInc, the §7.4.9.11 `inferSbDcSigCoeffFlag` DC + /// inference (sub-block (0, 1) decodes 15 zero sig bins, so its + /// DC cell is inferred 1), and the §9.3.4.2.6 eq.-9-58 ctxSet + /// bump across sub-blocks (prior sub-block's greater-1 bin was 1 + /// ⇒ terminal greater1Ctx 0 ⇒ ctxSet 2 + 1 = 3, ctxInc 13). + #[test] + fn two_subblock_8x8_luma_csbf_and_dc_inference() { + let params = luma_params(3, ScanIdx::Diagonal); + let mut decisions = Vec::new(); + decisions.extend([1, 1, 1, 1, 0]); // last_sig_x prefix = 4 + decisions.extend([1, 1, 1, 1, 0]); // last_sig_y prefix = 4 + decisions.push(1); // i=3: greater1 (DC of sub-block (1,1)) = 1 + decisions.push(0); // i=3: greater2 = 0 + decisions.push(0); // i=2: coded_sub_block_flag (1,0) = 0 + decisions.push(1); // i=1: coded_sub_block_flag (0,1) = 1 + decisions.extend([0; 15]); // i=1: sig n=15..1 all 0 ⇒ DC inferred + decisions.push(0); // i=1: greater1 (inferred DC) = 0 + decisions.extend([0; 16]); // i=0: sig n=15..0 all 0 + // bypass: last_x suffix 0, last_y suffix 0, sign(i=3) +, sign(i=1) − + let mut bins = Scripted::new(&decisions, &[0, 0, 0, 1]); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!((block.last_sig_coeff_x, block.last_sig_coeff_y), (4, 4)); + assert_eq!(block.level(4, 4), 2, "baseLevel 1 + greater1, no remaining"); + assert_eq!( + block.level(0, 4), + -1, + "inferred-DC coefficient of sub-block (0,1)" + ); + assert_eq!(block.levels.iter().filter(|&&v| v != 0).count(), 2); + + // §9.3.4.2.4 ctxInc: sub-block (1,0) sees below-neighbour + // (1,1) coded ⇒ 1; sub-block (0,1) sees right-neighbour (1,1) + // coded ⇒ 1. + let csbf_log: Vec = bins + .log + .iter() + .filter(|(e, _)| *e == ResidualElement::CodedSubBlockFlag) + .map(|&(_, c)| c) + .collect(); + assert_eq!(csbf_log, vec![1, 1]); + // eq. 9-57 ctxSet 2 (i > 0, luma, first invocation ⇒ ctxInc + // 9), then eq. 9-58 bump (prior greater-1 was 1) ⇒ ctxInc 13. + let g1_log: Vec = bins + .log + .iter() + .filter(|(e, _)| *e == ResidualElement::CoeffAbsLevelGreater1Flag) + .map(|&(_, c)| c) + .collect(); + assert_eq!(g1_log, vec![9, 13]); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// Sign data hiding: significant coefficients at scan positions 5 + /// and 0 (`lastSigScanPos − firstSigScanPos = 5 > 3` ⇒ + /// `signHidden`), so the first-in-scan-order sign bin is omitted + /// and the §7.3.8.11 odd-`sumAbsLevel` parity rule negates the + /// coefficient at `firstSigScanPos`. + #[test] + fn sign_data_hiding_parity_flip() { + let params = ResidualCodingParams { + sign_data_hiding_enabled_flag: true, + ..luma_params(2, ScanIdx::Diagonal) + }; + let mut decisions = Vec::new(); + decisions.extend([1, 1, 0]); // last_sig_x prefix = 2 + decisions.push(0); // last_sig_y prefix = 0 ⇒ last at (2,0), scan pos 5 + decisions.extend([0, 0, 0, 0, 1]); // sig n=4..0: only n=0 + decisions.extend([1, 0]); // greater1: n=5 ⇒ 1, n=0 ⇒ 0 + decisions.push(0); // greater2 at n=5 + let mut bins = Scripted::new(&decisions, &[0]); // single sign (n=5) + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!((block.last_sig_coeff_x, block.last_sig_coeff_y), (2, 0)); + assert_eq!(block.level(2, 0), 2); + // sumAbsLevel = 2 + 1 = 3 (odd) ⇒ the hidden-sign coefficient + // at firstSigScanPos flips negative. + assert_eq!(block.level(0, 0), -1); + assert_eq!( + bins.bypass_reads, 1, + "the firstSigScanPos sign bin is hidden" + ); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// Same coefficient layout with sign data hiding disabled: both + /// sign bins are read and no parity flip occurs. + #[test] + fn no_sign_hiding_when_disabled() { + let params = luma_params(2, ScanIdx::Diagonal); + let mut decisions = Vec::new(); + decisions.extend([1, 1, 0, 0]); // last at (2,0) + decisions.extend([0, 0, 0, 0, 1]); // sig n=4..0 + decisions.extend([1, 0]); // greater1 + decisions.push(0); // greater2 + let mut bins = Scripted::new(&decisions, &[0, 0]); // both signs read + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!(block.level(2, 0), 2); + assert_eq!(block.level(0, 0), 1, "no parity flip without sign hiding"); + assert_eq!(bins.bypass_reads, 2); + } + + /// Greater-1 cap: 10 significant coefficients in one sub-block — + /// only the first 8 in reverse scan order consume + /// `coeff_abs_level_greater1_flag` bins, and the 9th / 10th hit + /// the `numSigCoeff >= 8` threshold (`baseLevel == 1`) so each + /// reads a `coeff_abs_level_remaining` (value 0 ⇒ abs level 1). + #[test] + fn greater1_cap_and_numsig_threshold() { + let params = luma_params(2, ScanIdx::Diagonal); + let mut decisions = Vec::new(); + decisions.extend([1, 1, 1, 1, 1, 1]); // last at (3,3) + // sig n=14..0: nine 1s (n=14..6) then six 0s (n=5..0). + decisions.extend([1; 9]); + decisions.extend([0; 6]); + decisions.extend([0; 8]); // greater1: capped at 8 bins, all 0 + // bypass: 10 signs, then two remaining values of 0 (single + // TR-prefix terminator bin each at cRiceParam 0). + let mut bins = Scripted::new(&decisions, &[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + let g1_bins = bins + .log + .iter() + .filter(|(e, _)| *e == ResidualElement::CoeffAbsLevelGreater1Flag) + .count(); + assert_eq!(g1_bins, 8, "numGreater1Flag < 8 cap"); + assert_eq!(block.levels.iter().filter(|&&v| v == 1).count(), 10); + assert_eq!(bins.bypass_reads, 12, "10 signs + 2 single-bin remainings"); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// §9.3.3.11 Rice adaptation across one sub-block: the first + /// `coeff_abs_level_remaining` (cRiceParam 0) decodes 10 via the + /// TR-escape + EG1 path (`cAbsLevel = 13`), so eq. 9-24 bumps the + /// second invocation to cRiceParam 1 (TR prefix `0` + one suffix + /// bit `1` ⇒ value 1). + #[test] + fn rice_adaptation_within_subblock() { + let params = luma_params(2, ScanIdx::Diagonal); + let mut decisions = Vec::new(); + decisions.extend([1, 1, 1, 1, 1, 1]); // last at (3,3) + decisions.push(1); // sig n=14 = 1 + decisions.extend([0; 14]); // sig n=13..0 = 0 + decisions.extend([1, 1]); // greater1 at n=15, n=14 + decisions.push(1); // greater2 at n=15 (lastGreater1ScanPos) + // remaining #1 = 10 at cRiceParam 0: TR escape prefix `1111`, + // then EGk(k=1) of suffixVal = 6 = prefix `110` (§9.3.3.3 ones- + // then-zero) + 3-bit suffix `000`. + // remaining #2 = 1 at cRiceParam 1: TR prefix `0` (terminator) + // + 1-bit suffix `1`. + let bypasses = [ + 0, 0, // signs at n=15, n=14 + 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, // remaining #1 = 10 (escape + EG1) + 0, 1, // remaining #2 = 1 at cRiceParam 1 + ]; + let mut bins = Scripted::new(&decisions, &bypasses); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + let pos_scan = scan_order(2, ScanIdx::Diagonal).unwrap(); + assert_eq!(block.level(3, 3), 13, "baseLevel 3 + remaining 10"); + let p14 = pos_scan[14]; + assert_eq!( + block.level(usize::from(p14.x), usize::from(p14.y)), + 3, + "baseLevel 2 + remaining 1 under the adapted cRiceParam" + ); + assert!(bins.decisions.is_empty() && bins.bypasses.is_empty()); + } + + /// eq. 7-78: under the vertical scan (`scanIdx == 2`) the decoded + /// last-significant coordinates are swapped. + #[test] + fn vertical_scan_swaps_last_sig_coordinates() { + let params = luma_params(2, ScanIdx::Vertical); + let mut decisions = Vec::new(); + decisions.extend([1, 1, 0]); // wire X prefix = 2 + decisions.push(0); // wire Y prefix = 0 + // After the swap the last position is (0, 2) = vertical scan + // pos 2; sig bins for n=1..0, then one greater1. + decisions.extend([0, 0, 0]); + let mut bins = Scripted::new(&decisions, &[0]); + let block = decode_residual_coding_with(¶ms, &mut bins).unwrap(); + assert_eq!((block.last_sig_coeff_x, block.last_sig_coeff_y), (0, 2)); + assert_eq!(block.level(0, 2), 1); + } + + /// §9.3.4.2.5 eq. 9-40: with the transform-skip context gate set, + /// every decoded `sig_coeff_flag` uses the dedicated sigCtx (42 + /// luma ⇒ ctxInc 42). + #[test] + fn transform_skip_sig_ctx_routing() { + let params = ResidualCodingParams { + transform_skip_sig_ctx: true, + ..luma_params(2, ScanIdx::Diagonal) + }; + let mut decisions = Vec::new(); + decisions.extend([1, 0, 1, 0]); // last at (1, 1) = diag scan pos 4 + decisions.extend([0, 0, 0, 0]); // sig n=3..0 + decisions.push(0); // greater1 at n=4 + let mut bins = Scripted::new(&decisions, &[0]); + decode_residual_coding_with(¶ms, &mut bins).unwrap(); + let sig_ctxs: Vec = bins + .log + .iter() + .filter(|(e, _)| *e == ResidualElement::SigCoeffFlag) + .map(|&(_, c)| c) + .collect(); + assert_eq!(sig_ctxs, vec![42; 4]); + } + + /// §7.4.9.11 scanIdx derivation. + #[test] + fn scan_idx_derivation() { + // Intra 4x4 luma: mode bands select the scan. + for mode in 6..=14 { + assert_eq!( + residual_coding_scan_idx(true, 2, 0, 1, mode), + ScanIdx::Vertical + ); + } + for mode in 22..=30 { + assert_eq!( + residual_coding_scan_idx(true, 2, 0, 1, mode), + ScanIdx::Horizontal + ); + } + assert_eq!( + residual_coding_scan_idx(true, 2, 0, 1, 0), + ScanIdx::Diagonal + ); + assert_eq!( + residual_coding_scan_idx(true, 2, 0, 1, 34), + ScanIdx::Diagonal + ); + // 8x8: luma eligible, 4:2:0 chroma not, 4:4:4 chroma eligible. + assert_eq!( + residual_coding_scan_idx(true, 3, 0, 1, 10), + ScanIdx::Vertical + ); + assert_eq!( + residual_coding_scan_idx(true, 3, 1, 1, 10), + ScanIdx::Diagonal + ); + assert_eq!( + residual_coding_scan_idx(true, 3, 1, 3, 10), + ScanIdx::Vertical + ); + // 16x16+ and inter: always diagonal. + assert_eq!( + residual_coding_scan_idx(true, 4, 0, 1, 10), + ScanIdx::Diagonal + ); + assert_eq!( + residual_coding_scan_idx(false, 2, 0, 1, 10), + ScanIdx::Diagonal + ); + } + + /// Driver input validation. + #[test] + fn rejects_out_of_range_inputs() { + let mut bins = Scripted::new(&[], &[]); + let bad_size = ResidualCodingParams { + log2_trafo_size: 6, + ..luma_params(2, ScanIdx::Diagonal) + }; + assert_eq!( + decode_residual_coding_with(&bad_size, &mut bins), + Err(ResidualCodingError::UnsupportedLog2TrafoSize(6)) + ); + let bad_scan = luma_params(2, ScanIdx::Traverse); + assert_eq!( + decode_residual_coding_with(&bad_scan, &mut bins), + Err(ResidualCodingError::UnsupportedScanIdx(ScanIdx::Traverse)) + ); + } + + /// Engine-backed smoke run: the [`EngineResidualBinSource`] + /// binding decodes a block from a real §9.3.4.3 arithmetic-engine + /// bin stream without error, and the last-significant coefficient + /// is non-zero by the §7.4.9.11 inference. + #[test] + fn engine_backed_smoke() { + let buf = [0x5A; 96]; + let mut engine = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut contexts = ResidualContexts::init_uniform(154, 26); + let params = luma_params(3, ScanIdx::Diagonal); + let block = decode_residual_coding(&mut engine, &mut contexts, ¶ms).unwrap(); + assert_eq!(block.size(), 8); + assert!(block.last_sig_coeff_x < 8 && block.last_sig_coeff_y < 8); + assert_ne!( + block.level( + block.last_sig_coeff_x as usize, + block.last_sig_coeff_y as usize + ), + 0, + "the last significant coefficient is significant by inference" + ); + } + + /// The engine binding mutates the addressed bank slot (context + /// adaptation reaches the right [`ResidualContexts`] field). + #[test] + fn engine_binding_adapts_contexts() { + let buf = [0xA5; 96]; + let mut engine = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut contexts = ResidualContexts::init_uniform(154, 26); + let before = contexts.clone(); + let params = luma_params(2, ScanIdx::Diagonal); + decode_residual_coding(&mut engine, &mut contexts, ¶ms).unwrap(); + assert_ne!( + contexts.last_sig_coeff_x_prefix, before.last_sig_coeff_x_prefix, + "last_sig_coeff_x_prefix bank must adapt" + ); + } + + // --- §9.3.2.2 Table 9-26..9-31 per-initType bank init --- + + fn cm(p_state_idx: u8, val_mps: u8) -> ContextModel { + ContextModel { + p_state_idx, + val_mps, + } + } + + /// Representative derived `(pStateIdx, valMps)` pins across QPs: + /// the §9.3.2.2 equations applied to cited Table 9-26..9-31 + /// entries, hand-evaluated. + #[test] + fn residual_contexts_init_pins() { + // Table 9-26 ctxIdx 0 (initType 0, initValue 110). + assert_eq!( + ResidualContexts::init(0, 0).last_sig_coeff_x_prefix[0], + cm(32, 1) + ); + assert_eq!( + ResidualContexts::init(0, 26).last_sig_coeff_x_prefix[0], + cm(7, 1) + ); + assert_eq!( + ResidualContexts::init(0, 51).last_sig_coeff_x_prefix[0], + cm(15, 0) + ); + // Table 9-26 ctxIdx 18 (initType 1, initValue 125) and ctxIdx + // 53 (initType 2, initValue 93). + assert_eq!( + ResidualContexts::init(1, 26).last_sig_coeff_x_prefix[0], + cm(7, 1) + ); + assert_eq!( + ResidualContexts::init(2, 26).last_sig_coeff_x_prefix[17], + cm(8, 0) + ); + // Table 9-27 prints the same values as Table 9-26, so the two + // banks start identical (they adapt independently afterwards). + let ctx = ResidualContexts::init(1, 30); + assert_eq!(ctx.last_sig_coeff_x_prefix, ctx.last_sig_coeff_y_prefix); + // Table 9-28 ctxIdx 0 (initType 0, initValue 91) and ctxIdx 4 + // (initType 1, initValue 121). + assert_eq!( + ResidualContexts::init(0, 26).coded_sub_block_flag[0], + cm(24, 0) + ); + assert_eq!( + ResidualContexts::init(1, 26).coded_sub_block_flag[0], + cm(24, 0) + ); + // Table 9-29: ctxIdx 0 (initType 0, initValue 111), ctxIdx 42 + // (initType 1, initValue 155), ctxIdx 84 (initType 2, + // initValue 170), and the transform-skip tail ctxIdx 126 / 127 + // (initType 0, initValues 141 / 111) landing in bank slots + // 42 / 43. + assert_eq!(ResidualContexts::init(0, 26).sig_coeff_flag[0], cm(15, 1)); + for qp in [0, 26, 51] { + // initValue 155 ⇒ m == 0: QP-independent state. + assert_eq!(ResidualContexts::init(1, qp).sig_coeff_flag[0], cm(8, 1)); + } + assert_eq!(ResidualContexts::init(2, 51).sig_coeff_flag[0], cm(15, 1)); + assert_eq!(ResidualContexts::init(0, 26).sig_coeff_flag[42], cm(15, 1)); + assert_eq!(ResidualContexts::init(0, 51).sig_coeff_flag[43], cm(7, 0)); + // Table 9-30 ctxIdx 0 (initType 0, initValue 140) and ctxIdx + // 48 (initType 2, initValue 154). + assert_eq!( + ResidualContexts::init(0, 26).coeff_abs_level_greater1_flag[0], + cm(7, 1) + ); + assert_eq!( + ResidualContexts::init(2, 26).coeff_abs_level_greater1_flag[0], + cm(0, 1) + ); + // Table 9-31 ctxIdx 0 (initType 0, initValue 138) and ctxIdx 6 + // (initType 1, initValue 107). + assert_eq!( + ResidualContexts::init(0, 26).coeff_abs_level_greater2_flag[0], + cm(8, 0) + ); + assert_eq!( + ResidualContexts::init(1, 26).coeff_abs_level_greater2_flag[0], + cm(16, 0) + ); + } + + /// Whole-bank smoke test: every initType / QP combination yields + /// in-range states everywhere, and the three initTypes give three + /// distinct bank sets. + #[test] + fn residual_contexts_init_smoke() { + for init_type in 0u8..=2 { + for qp in [0, 17, 26, 37, 51] { + let ctx = ResidualContexts::init(init_type, qp); + let banks: [&[ContextModel]; 6] = [ + &ctx.last_sig_coeff_x_prefix, + &ctx.last_sig_coeff_y_prefix, + &ctx.coded_sub_block_flag, + &ctx.sig_coeff_flag, + &ctx.coeff_abs_level_greater1_flag, + &ctx.coeff_abs_level_greater2_flag, + ]; + for bank in banks { + for c in bank { + // Equations 9-4..9-6 bound preCtxState to + // 1..=126 ⇒ pStateIdx 0..=62. + assert!(c.p_state_idx <= 62); + assert!(c.val_mps <= 1); + } + } + } + } + assert_ne!(ResidualContexts::init(0, 26), ResidualContexts::init(1, 26)); + assert_ne!(ResidualContexts::init(1, 26), ResidualContexts::init(2, 26)); + assert_ne!(ResidualContexts::init(0, 26), ResidualContexts::init(2, 26)); + } +} diff --git a/vendor/oxideav-h265/src/sao.rs b/vendor/oxideav-h265/src/sao.rs new file mode 100644 index 0000000..201f817 --- /dev/null +++ b/vendor/oxideav-h265/src/sao.rs @@ -0,0 +1,762 @@ +//! §8.7.3 sample adaptive offset (SAO) apply. +//! +//! SAO is the second in-loop filter (it runs on a CTB basis after the +//! §8.7.2 deblocking filter completes for the whole picture). It takes the +//! reconstructed picture sample arrays and produces the modified +//! `saoPicture` arrays. Two offset types are defined: +//! +//! * **Band offset** (`SaoTypeIdx == 1`): the sample value range is split +//! into 32 equal bands; four consecutive bands (starting at +//! `sao_band_position`) each get a signed offset added. +//! * **Edge offset** (`SaoTypeIdx == 2`): each sample is classified by the +//! sign pattern of its two neighbours along one of four 1-D directions +//! (Table 8-13 `hPos` / `vPos`), giving an `edgeIdx` in 0..=4 that +//! selects one of the five offsets. +//! +//! This module implements: +//! +//! * §7.4.9.3 — the `SaoOffsetVal[cIdx][rx][ry][i]` derivation (equation +//! 7-72), including the `sao_offset_sign` inference for edge offset +//! (categories 0/1 positive, 2/3 negative) and the merge-flag +//! inheritance of all five SAO arrays from the left / above CTB. +//! * §8.7.3.1 — the picture-level CTB-grid driver +//! ([`apply_sao_picture`]) that visits every CTB and dispatches the +//! per-component modification, honouring `slice_sao_luma_flag` / +//! `slice_sao_chroma_flag`. +//! * §8.7.3.2 — the per-CTB modification process +//! ([`apply_sao_ctb`]), both the edge (equations 8-409..8-413) and band +//! (equations 8-414..8-415) paths, with the picture-boundary edge +//! guard (an out-of-picture neighbour forces `edgeIdx = 0`, i.e. no +//! offset). +//! +//! The cross-slice / cross-tile edge guards of §8.7.3.2 (the +//! `MinTbAddrZs` slice test and the `loop_filter_across_tiles_enabled_flag` +//! tile test) collapse to the picture-boundary test for a single-slice, +//! single-tile picture; multi-slice / multi-tile boundary masking is a +//! follow-up that threads the per-sample slice / tile id. + +use crate::picture::{sub_wh_c, Picture, Plane}; +use crate::slice_data::{SaoComponent, SaoCtbParams}; + +/// `Sign( x )` (§5, equation 5-18). +#[inline] +fn sign(x: i32) -> i32 { + match x.cmp(&0) { + core::cmp::Ordering::Greater => 1, + core::cmp::Ordering::Equal => 0, + core::cmp::Ordering::Less => -1, + } +} + +/// Table 8-13 — `(hPos[0], vPos[0], hPos[1], vPos[1])` for a SAO edge +/// offset class (0 = 0-deg, 1 = 90-deg, 2 = 135-deg, 3 = 45-deg). +/// `pub(crate)` so the encoder's SAO estimation classifies with the +/// same table. +#[inline] +pub(crate) fn eo_pos(eo_class: u8) -> (i32, i32, i32, i32) { + match eo_class { + // horizontal: left + right. + 0 => (-1, 0, 1, 0), + // vertical: above + below. + 1 => (0, -1, 0, 1), + // 135-degree: above-left + below-right. + 2 => (-1, -1, 1, 1), + // 45-degree: above-right + below-left. + _ => (1, -1, -1, 1), + } +} + +/// One CTB's resolved SAO parameters for a single colour component, after +/// merge inheritance and the §7.4.9.3 `SaoOffsetVal` derivation. +/// +/// `offset_val[0..5]` is `SaoOffsetVal[cIdx][rx][ry][0..4]` (equation +/// 7-72): `offset_val[0]` is always 0; the four signed offsets follow. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResolvedSaoComponent { + /// `SaoTypeIdx[cIdx][rx][ry]` — 0 (off), 1 (band), 2 (edge). + pub sao_type_idx: u8, + /// `SaoOffsetVal[cIdx][rx][ry][0..4]` (equation 7-72). + pub offset_val: [i32; 5], + /// `sao_band_position[cIdx][rx][ry]` (band offset only). + pub band_position: u8, + /// `SaoEoClass[cIdx][rx][ry]` (edge offset only). + pub eo_class: u8, +} + +impl ResolvedSaoComponent { + /// A "not applied" component (`SaoTypeIdx == 0`). + #[must_use] + pub fn off() -> Self { + Self { + sao_type_idx: 0, + offset_val: [0; 5], + band_position: 0, + eo_class: 0, + } + } + + /// Resolve a decoded [`SaoComponent`] (§7.3.8.3 syntax) into the + /// applied form, applying the §7.4.9.3 `SaoOffsetVal` derivation + /// (equation 7-72). `log2_offset_scale` is the §7.4.9.3 + /// `log2OffsetScale` (0 unless the range-extension + /// `log2_sao_offset_scale_*` PPS fields are set). + /// + /// For edge offset the `sao_offset_sign` of the four categories is + /// inferred per §7.4.9.3 (categories 0/1 positive, 2/3 negative) + /// rather than read; for band offset the decoded signs are used. + #[must_use] + pub fn from_decoded(c: &SaoComponent, log2_offset_scale: u8) -> Self { + let mut offset_val = [0i32; 5]; + for i in 0..4 { + // §7.4.9.3: for edge offset the sign is inferred (i<2 ⇒ +, + // i>=2 ⇒ −); for band offset the decoded sign applies. + let sign_bit = if c.sao_type_idx == 2 { + u8::from(i >= 2) + } else { + c.offset_sign[i] + }; + // equation 7-72: (1 − 2*sign) * abs << log2OffsetScale. + let signed = (1 - 2 * i32::from(sign_bit)) * (c.offset_abs[i] as i32); + offset_val[i + 1] = signed << log2_offset_scale; + } + Self { + sao_type_idx: c.sao_type_idx, + offset_val, + band_position: c.band_position, + eo_class: c.eo_class, + } + } +} + +/// One CTB's resolved SAO parameters for all three components. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ResolvedSao { + /// Per-component resolved parameters `[Y, Cb, Cr]`. + pub components: [ResolvedSaoComponent; 3], +} + +impl ResolvedSao { + /// All-off SAO (no CTB is modified). + #[must_use] + pub fn off() -> Self { + Self { + components: [ResolvedSaoComponent::off(); 3], + } + } + + /// Resolve one CTB's decoded [`SaoCtbParams`] into the applied form, + /// inheriting the left / above neighbour's resolved parameters when + /// `sao_merge_left_flag` / `sao_merge_up_flag` is set (§7.4.9.3). The + /// merge sources are the already-resolved CTBs; pass `None` when the + /// neighbour is unavailable. + #[must_use] + pub fn resolve( + params: &SaoCtbParams, + left: Option<&ResolvedSao>, + above: Option<&ResolvedSao>, + log2_offset_scale_luma: u8, + log2_offset_scale_chroma: u8, + ) -> Self { + if params.merge_left { + if let Some(l) = left { + return *l; + } + } + if params.merge_up { + if let Some(a) = above { + return *a; + } + } + let mut components = [ResolvedSaoComponent::off(); 3]; + for (cidx, comp) in components.iter_mut().enumerate() { + let scale = if cidx == 0 { + log2_offset_scale_luma + } else { + log2_offset_scale_chroma + }; + *comp = ResolvedSaoComponent::from_decoded(¶ms.components[cidx], scale); + } + Self { components } + } +} + +/// §8.7.3.2 — apply the SAO CTB modification process for one colour +/// component of one CTB, reading from `rec` and writing into `sao_out`. +/// +/// `(x_ctb, y_ctb)` is the component-plane top-left of the CTB; `n_w` / +/// `n_h` are the CTB width / height in component samples. Out-of-picture +/// edge-offset neighbours force `edgeIdx = 0` (no modification) per the +/// §8.7.3.2 picture-boundary guard. +/// +/// `rec` and `sao_out` may be the same picture when SAO is applied in +/// place; the edge classification reads `rec` (the pre-SAO array) so an +/// in-place application is exact only when the neighbour samples have not +/// yet been overwritten. For correctness across the whole CTB grid the +/// driver [`apply_sao_picture`] snapshots the pre-SAO planes. +#[allow(clippy::too_many_arguments)] +pub fn apply_sao_ctb( + rec: &Picture, + sao_out: &mut Picture, + plane: Plane, + comp: &ResolvedSaoComponent, + x_ctb: usize, + y_ctb: usize, + n_w: usize, + n_h: usize, +) { + apply_sao_ctb_with_boundaries(rec, sao_out, plane, comp, x_ctb, y_ctb, n_w, n_h, None); +} + +/// §8.7.3.1 in-loop-filter boundary constraints: the per-CTB slice / +/// tile identity grids and the across-boundary enable flags the +/// §8.7.3.2 edge-offset neighbour test consults (a neighbouring sample +/// in a different slice / tile with filtering-across disabled forces +/// `edgeIdx = 0`). +#[derive(Debug, Clone)] +pub struct SaoBoundaries { + /// Per-CTB `SliceAddrRs` (raster order). + pub slice_addr_of_ctb: Vec, + /// Per-CTB §6.5.1 `TileId` (raster order). + pub tile_id_of_ctb: Vec, + /// `PicWidthInCtbsY`. + pub pic_w_ctbs: usize, + /// `CtbLog2SizeY`. + pub ctb_log2_size_y: u32, + /// `slice_loop_filter_across_slices_enabled_flag` — the uniform + /// fallback used when [`Self::filter_across_of_ctb`] is `None`. + pub across_slices: bool, + /// `loop_filter_across_tiles_enabled_flag`. + pub across_tiles: bool, + /// Per-CTB (raster order) `slice_loop_filter_across_slices_enabled_ + /// flag` of the slice owning each CTB. When present, the §8.7.3.2 + /// cross-slice rule is evaluated per slice pair: the neighbour read + /// is denied when the LATER slice (decode order) of the two has its + /// flag equal to 0. + pub filter_across_of_ctb: Option>, + /// Per-CTB (raster order) tile-scan address `CtbAddrRsToTs` — the + /// decode-order key for the §8.7.3.2 `MinTbAddrZs` comparison. + /// `None` falls back to raster order (exact for single-tile + /// pictures). + pub ctb_ts_of_rs: Option>, +} + +impl SaoBoundaries { + /// Whether the §8.7.3.2 edge-offset classification may read the + /// neighbour at luma position `(x_nb, y_nb)` from the sample at + /// luma position `(x, y)`. + fn neighbour_allowed(&self, x: usize, y: usize, x_nb: usize, y_nb: usize) -> bool { + let idx = |xx: usize, yy: usize| { + (yy >> self.ctb_log2_size_y) * self.pic_w_ctbs + (xx >> self.ctb_log2_size_y) + }; + let a = idx(x, y); + let b = idx(x_nb, y_nb); + if a == b { + return true; + } + if self.slice_addr_of_ctb.get(a) != self.slice_addr_of_ctb.get(b) { + match &self.filter_across_of_ctb { + None => { + if !self.across_slices { + return false; + } + } + Some(flags) => { + // §8.7.3.2 — the read is denied when the later (in + // decode order) of the two slices has + // slice_loop_filter_across_slices_enabled_flag == 0. + let ts = |i: usize| self.ctb_ts_of_rs.as_ref().map_or(i as u32, |m| m[i]); + let later = if ts(b) < ts(a) { a } else { b }; + if !flags.get(later).copied().unwrap_or(true) { + return false; + } + } + } + } + if !self.across_tiles && self.tile_id_of_ctb.get(a) != self.tile_id_of_ctb.get(b) { + return false; + } + true + } +} + +/// [`apply_sao_ctb`] with the optional §8.7.3.2 slice / tile boundary +/// constraints (edge-offset neighbours across a disallowed boundary +/// force `edgeIdx = 0`, i.e. the sample is left unmodified). +#[allow(clippy::too_many_arguments)] +pub fn apply_sao_ctb_with_boundaries( + rec: &Picture, + sao_out: &mut Picture, + plane: Plane, + comp: &ResolvedSaoComponent, + x_ctb: usize, + y_ctb: usize, + n_w: usize, + n_h: usize, + boundaries: Option<&SaoBoundaries>, +) { + apply_sao_ctb_full( + rec, sao_out, plane, comp, x_ctb, y_ctb, n_w, n_h, boundaries, None, + ); +} + +/// [`apply_sao_ctb_with_boundaries`] with the per-CU loop-filter +/// suppression map: samples of PCM (`pcm_loop_filter_disabled_flag`) / +/// transquant-bypass coding units keep their reconstructed values +/// (§8.7.3.1 treats both `SaoTypeIdx` components as 0 for them). +#[allow(clippy::too_many_arguments)] +pub fn apply_sao_ctb_full( + rec: &Picture, + sao_out: &mut Picture, + plane: Plane, + comp: &ResolvedSaoComponent, + x_ctb: usize, + y_ctb: usize, + n_w: usize, + n_h: usize, + boundaries: Option<&SaoBoundaries>, + no_filter: Option<&crate::deblock::NoFilterMap<'_>>, +) { + if comp.sao_type_idx == 0 { + return; + } + let (nf_sw, nf_sh) = match plane { + Plane::Luma => (1, 1), + _ => crate::picture::sub_wh_c(rec.chroma_array_type()), + }; + let suppressed = + |x: usize, y: usize| -> bool { no_filter.is_some_and(|m| m.at_luma(x * nf_sw, y * nf_sh)) }; + let bit_depth = rec.bit_depth(plane); + let max = (1i32 << bit_depth) - 1; + let (pw, ph) = rec.plane_dims(plane); + let w = n_w.min(pw.saturating_sub(x_ctb)); + let h = n_h.min(ph.saturating_sub(y_ctb)); + + if comp.sao_type_idx == 2 { + // §8.7.3.2 edge offset (equations 8-409..8-413). + let (h0, v0, h1, v1) = eo_pos(comp.eo_class); + for j in 0..h { + for i in 0..w { + let xsi = (x_ctb + i) as i32; + let ysj = (y_ctb + j) as i32; + let n0x = xsi + h0; + let n0y = ysj + v0; + let n1x = xsi + h1; + let n1y = ysj + v1; + // §8.7.3.2: a neighbour outside the picture forces + // edgeIdx = 0 (no offset). + let in_pic = + |x: i32, y: i32| x >= 0 && y >= 0 && (x as usize) < pw && (y as usize) < ph; + if !in_pic(n0x, n0y) || !in_pic(n1x, n1y) { + continue; + } + // §8.7.3.2: a neighbour in a different slice / tile with + // loop filtering across that boundary disabled also + // forces edgeIdx = 0. Positions map to luma space for + // the CTB-grid lookup. + if let Some(b) = boundaries { + let (sw, sh) = match plane { + Plane::Luma => (1, 1), + _ => crate::picture::sub_wh_c(rec.chroma_array_type()), + }; + let (lx, ly) = (xsi as usize * sw, ysj as usize * sh); + if !b.neighbour_allowed(lx, ly, n0x as usize * sw, n0y as usize * sh) + || !b.neighbour_allowed(lx, ly, n1x as usize * sw, n1y as usize * sh) + { + continue; + } + } + let cur = rec.sample(plane, xsi as usize, ysj as usize); + let s0 = rec.sample(plane, n0x as usize, n0y as usize); + let s1 = rec.sample(plane, n1x as usize, n1y as usize); + // equation 8-411. + let mut edge_idx = 2 + sign(cur - s0) + sign(cur - s1); + // equation 8-412. + if edge_idx == 0 || edge_idx == 1 || edge_idx == 2 { + edge_idx = if edge_idx == 2 { 0 } else { edge_idx + 1 }; + } + // equation 8-413. + if suppressed(xsi as usize, ysj as usize) { + continue; // §8.7.3.1 PCM / bypass suppression + } + let off = comp.offset_val[edge_idx as usize]; + let v = (cur + off).clamp(0, max); + sao_out.set_sample(plane, xsi as usize, ysj as usize, v); + } + } + } else { + // §8.7.3.2 band offset (equations 8-414..8-415). + let band_shift = i32::from(bit_depth) - 5; + let sao_left_class = i32::from(comp.band_position); + // equation 8-414: bandTable maps four consecutive bands to 1..=4. + let mut band_table = [0usize; 32]; + for k in 0..4i32 { + band_table[((k + sao_left_class) & 31) as usize] = (k + 1) as usize; + } + for j in 0..h { + for i in 0..w { + let xsi = x_ctb + i; + let ysj = y_ctb + j; + if suppressed(xsi, ysj) { + continue; // §8.7.3.1 PCM / bypass suppression + } + let cur = rec.sample(plane, xsi, ysj); + let band_idx = band_table[(cur >> band_shift) as usize]; + // equation 8-415. + let off = comp.offset_val[band_idx]; + let v = (cur + off).clamp(0, max); + sao_out.set_sample(plane, xsi, ysj, v); + } + } + } +} + +/// §8.7.3.1 — apply SAO to a whole picture from the per-CTB resolved +/// parameter grid. +/// +/// `ctb_sao` is the row-major `PicHeightInCtbsY * PicWidthInCtbsY` grid of +/// resolved per-CTB SAO parameters (raster order). `ctb_log2_size_y` is +/// the luma CTB log2 side; `chroma_array_type` sizes the chroma CTB step. +/// `slice_sao_luma_flag` / `slice_sao_chroma_flag` gate the luma / chroma +/// passes. SAO is computed against a snapshot of the input planes so the +/// edge classification always reads the pre-SAO samples (§8.7.3.1: the +/// `recPicture` array is the pre-SAO reconstruction). +/// +/// Returns the modified picture; the input `pic` is consumed as the +/// `recPicture` source. +#[must_use] +pub fn apply_sao_picture( + pic: &Picture, + ctb_sao: &[ResolvedSao], + ctb_log2_size_y: u32, + chroma_array_type: u8, + slice_sao_luma_flag: bool, + slice_sao_chroma_flag: bool, +) -> Picture { + apply_sao_picture_with_boundaries( + pic, + ctb_sao, + ctb_log2_size_y, + chroma_array_type, + slice_sao_luma_flag, + slice_sao_chroma_flag, + None, + ) +} + +/// [`apply_sao_picture`] with the §8.7.3.2 slice / tile boundary +/// constraints. +#[must_use] +#[allow(clippy::too_many_arguments)] +pub fn apply_sao_picture_with_boundaries( + pic: &Picture, + ctb_sao: &[ResolvedSao], + ctb_log2_size_y: u32, + chroma_array_type: u8, + slice_sao_luma_flag: bool, + slice_sao_chroma_flag: bool, + boundaries: Option<&SaoBoundaries>, +) -> Picture { + apply_sao_picture_full( + pic, + ctb_sao, + ctb_log2_size_y, + chroma_array_type, + slice_sao_luma_flag, + slice_sao_chroma_flag, + boundaries, + None, + ) +} + +/// [`apply_sao_picture_with_boundaries`] with the per-CU loop-filter +/// suppression map (§8.7.3.1 PCM / transquant-bypass sample skip). +#[allow(clippy::too_many_arguments)] +#[must_use] +pub fn apply_sao_picture_full( + pic: &Picture, + ctb_sao: &[ResolvedSao], + ctb_log2_size_y: u32, + chroma_array_type: u8, + slice_sao_luma_flag: bool, + slice_sao_chroma_flag: bool, + boundaries: Option<&SaoBoundaries>, + no_filter: Option<&crate::deblock::NoFilterMap<'_>>, +) -> Picture { + let ctb_size_y = 1usize << ctb_log2_size_y; + let pic_width_in_ctbs = pic.width_luma().div_ceil(ctb_size_y); + let pic_height_in_ctbs = pic.height_luma().div_ceil(ctb_size_y); + // §8.7.3.1: saoPicture starts equal to recPicture; the edge / band + // classification reads recPicture (the snapshot below), the write + // targets saoPicture. + let rec = pic.clone(); + let mut out = pic.clone(); + + let (sw, sh) = if chroma_array_type == 0 { + (1, 1) + } else { + sub_wh_c(chroma_array_type) + }; + let n_ctb_chroma_w = ctb_size_y / sw; + let n_ctb_chroma_h = ctb_size_y / sh; + + for ry in 0..pic_height_in_ctbs { + for rx in 0..pic_width_in_ctbs { + let resolved = &ctb_sao[ry * pic_width_in_ctbs + rx]; + if slice_sao_luma_flag { + apply_sao_ctb_full( + &rec, + &mut out, + Plane::Luma, + &resolved.components[0], + rx * ctb_size_y, + ry * ctb_size_y, + ctb_size_y, + ctb_size_y, + boundaries, + no_filter, + ); + } + if chroma_array_type != 0 && slice_sao_chroma_flag { + apply_sao_ctb_full( + &rec, + &mut out, + Plane::Cb, + &resolved.components[1], + rx * n_ctb_chroma_w, + ry * n_ctb_chroma_h, + n_ctb_chroma_w, + n_ctb_chroma_h, + boundaries, + no_filter, + ); + apply_sao_ctb_full( + &rec, + &mut out, + Plane::Cr, + &resolved.components[2], + rx * n_ctb_chroma_w, + ry * n_ctb_chroma_h, + n_ctb_chroma_w, + n_ctb_chroma_h, + boundaries, + no_filter, + ); + } + } + } + out +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::slice_data::{SaoComponent, SaoCtbParams}; + + fn band_component(band_position: u8, abs: [u32; 4], sign: [u8; 4]) -> SaoComponent { + SaoComponent { + sao_type_idx: 1, + offset_abs: abs, + offset_sign: sign, + band_position, + eo_class: 0, + } + } + + fn edge_component(eo_class: u8, abs: [u32; 4]) -> SaoComponent { + SaoComponent { + sao_type_idx: 2, + offset_abs: abs, + offset_sign: [0; 4], + band_position: 0, + eo_class, + } + } + + #[test] + fn offset_val_band_uses_decoded_signs_eq_7_72() { + // abs = [1,2,3,4], signs = [0,1,0,1] ⇒ +1,−2,+3,−4. + let c = band_component(0, [1, 2, 3, 4], [0, 1, 0, 1]); + let r = ResolvedSaoComponent::from_decoded(&c, 0); + assert_eq!(r.offset_val, [0, 1, -2, 3, -4]); + } + + #[test] + fn offset_val_edge_infers_signs() { + // edge: i<2 positive, i>=2 negative regardless of decoded sign. + let c = edge_component(0, [1, 2, 3, 4]); + let r = ResolvedSaoComponent::from_decoded(&c, 0); + assert_eq!(r.offset_val, [0, 1, 2, -3, -4]); + } + + #[test] + fn offset_val_scales_by_log2_offset_scale() { + let c = band_component(0, [1, 1, 1, 1], [0, 0, 0, 0]); + let r = ResolvedSaoComponent::from_decoded(&c, 2); + // each offset << 2. + assert_eq!(r.offset_val, [0, 4, 4, 4, 4]); + } + + #[test] + fn merge_left_inherits_resolved_params() { + let left = ResolvedSao { + components: [ + ResolvedSaoComponent { + sao_type_idx: 1, + offset_val: [0, 5, 5, 5, 5], + band_position: 7, + eo_class: 0, + }, + ResolvedSaoComponent::off(), + ResolvedSaoComponent::off(), + ], + }; + let params = SaoCtbParams { + merge_left: true, + merge_up: false, + components: [SaoComponent::default(); 3], + }; + let r = ResolvedSao::resolve(¶ms, Some(&left), None, 0, 0); + assert_eq!(r, left); + } + + #[test] + fn band_offset_adds_to_samples_in_band() { + // 8-bit, bandShift = 3, sao_band_position = 0 ⇒ bands 0..=3 (sample + // values 0..31) get offsets +1,+2,+3,+4. A sample of value 10 is in + // band 1 (10 >> 3 == 1) ⇒ +2. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 10); + } + } + let comp = + ResolvedSaoComponent::from_decoded(&band_component(0, [1, 2, 3, 4], [0, 0, 0, 0]), 0); + let mut out = pic.clone(); + apply_sao_ctb(&pic, &mut out, Plane::Luma, &comp, 0, 0, 16, 16); + assert_eq!(out.sample(Plane::Luma, 0, 0), 12); + } + + #[test] + fn band_offset_leaves_other_bands_untouched() { + // sample 200 (>> 3 == 25) is outside bands 0..=3 ⇒ unchanged. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 200); + } + } + let comp = + ResolvedSaoComponent::from_decoded(&band_component(0, [1, 2, 3, 4], [0, 0, 0, 0]), 0); + let mut out = pic.clone(); + apply_sao_ctb(&pic, &mut out, Plane::Luma, &comp, 0, 0, 16, 16); + assert_eq!(out.sample(Plane::Luma, 5, 5), 200); + } + + #[test] + fn edge_offset_local_minimum_gets_category_1() { + // horizontal EO. A sample lower than both horizontal neighbours is a + // local minimum: edgeIdx = 2 + Sign(cur-left) + Sign(cur-right) + // = 2 + (−1) + (−1) = 0 → remapped to category 1, offset_val[1]. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 100); + } + } + // Make (5,5) a local minimum along the horizontal axis. + pic.set_sample(Plane::Luma, 5, 5, 50); + let comp = ResolvedSaoComponent::from_decoded(&edge_component(0, [3, 0, 0, 0]), 0); + let mut out = pic.clone(); + apply_sao_ctb(&pic, &mut out, Plane::Luma, &comp, 0, 0, 16, 16); + // offset_val[1] = +3 (category 1, inferred positive). + assert_eq!(out.sample(Plane::Luma, 5, 5), 53); + // a flat-region sample (cur == both neighbours) ⇒ edgeIdx 2 → 0, + // offset_val[0] = 0 ⇒ unchanged. + assert_eq!(out.sample(Plane::Luma, 0, 5), 100); + } + + #[test] + fn edge_offset_picture_boundary_neighbour_skips() { + // The left column has no left neighbour for horizontal EO ⇒ the + // §8.7.3.2 boundary guard leaves it unmodified even if it would + // otherwise classify. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 100); + } + } + pic.set_sample(Plane::Luma, 0, 5, 50); + let comp = ResolvedSaoComponent::from_decoded(&edge_component(0, [3, 0, 0, 0]), 0); + let mut out = pic.clone(); + apply_sao_ctb(&pic, &mut out, Plane::Luma, &comp, 0, 0, 16, 16); + // (0,5) has no left neighbour ⇒ unchanged. + assert_eq!(out.sample(Plane::Luma, 0, 5), 50); + } + + #[test] + fn picture_driver_off_grid_is_identity() { + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 123); + } + } + let grid = vec![ResolvedSao::off(); 1]; + let out = apply_sao_picture(&pic, &grid, 4, 1, true, true); + assert_eq!(out, pic); + } + + #[test] + fn picture_driver_band_offset_one_ctb() { + // 16×16 picture, one 16×16 CTB, band offset on luma only. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, 10); + pic.set_sample(Plane::Cb, x / 2, y / 2, 10); + } + } + let resolved = ResolvedSao { + components: [ + ResolvedSaoComponent::from_decoded( + &band_component(0, [1, 2, 3, 4], [0, 0, 0, 0]), + 0, + ), + ResolvedSaoComponent::off(), + ResolvedSaoComponent::off(), + ], + }; + let out = apply_sao_picture(&pic, &[resolved], 4, 1, true, true); + // luma band 1 ⇒ +2; chroma off ⇒ unchanged. + assert_eq!(out.sample(Plane::Luma, 0, 0), 12); + assert_eq!(out.sample(Plane::Cb, 0, 0), 10); + } + + #[test] + fn edge_offset_classification_reads_presao_snapshot() { + // A diagonal gradient: SAO must classify each sample against the + // PRE-SAO neighbours, not the partially-modified output. Build a + // horizontal ramp so each interior sample is monotonic (edgeIdx 0 + // → category 0 → no offset), proving no double-application. + let mut pic = Picture::new(16, 16, 1, 8, 8); + for y in 0..16 { + for x in 0..16 { + pic.set_sample(Plane::Luma, x, y, (x as i32) * 4 + 20); + } + } + let comp = ResolvedSaoComponent::from_decoded(&edge_component(0, [9, 9, 9, 9]), 0); + let resolved = ResolvedSao { + components: [ + comp, + ResolvedSaoComponent::off(), + ResolvedSaoComponent::off(), + ], + }; + let out = apply_sao_picture(&pic, &[resolved], 4, 1, true, false); + // Interior column 5: cur=40, left=36, right=44. Sign(40-36)=+1, + // Sign(40-44)=−1 ⇒ edgeIdx 2 → 0, offset_val[0]=0 ⇒ unchanged. + assert_eq!(out.sample(Plane::Luma, 5, 5), 40); + } +} diff --git a/vendor/oxideav-h265/src/scaling_list.rs b/vendor/oxideav-h265/src/scaling_list.rs new file mode 100644 index 0000000..ef4cafb --- /dev/null +++ b/vendor/oxideav-h265/src/scaling_list.rs @@ -0,0 +1,1011 @@ +//! §7.3.4 `scaling_list_data()` parse + §7.4.5 `ScalingList` derivation. +//! +//! H.265 carries an optional set of quantization scaling lists in the +//! SPS (`sps_scaling_list_data_present_flag == 1`) and PPS +//! (`pps_scaling_list_data_present_flag == 1`). The +//! `scaling_list_data()` syntax structure (ITU-T Rec. H.265 §7.3.4) +//! signals, for each of the 24 (sizeId, matrixId) slots, either: +//! +//! * a **prediction** from an earlier list of the same `sizeId` +//! (`scaling_list_pred_mode_flag == 0`), where +//! `scaling_list_pred_matrix_id_delta` selects the reference list +//! (delta 0 means "use the default list", per §7.4.5); or +//! * an **explicit** delta-coded list +//! (`scaling_list_pred_mode_flag == 1`), built from a running +//! `nextCoef` accumulator modulo 256, optionally preceded by a DC +//! coefficient (`scaling_list_dc_coef_minus8`) for sizeId > 1. +//! +//! This module parses that structure and derives the flat +//! `ScalingList[sizeId][matrixId][i]` coefficient arrays plus the +//! per-slot DC coefficients, applying the §7.4.5 default-list and +//! prediction-inference rules (equations 7-42 and 7-43). +//! +//! [`ScalingListData::scaling_factors`] then expands the flat lists +//! into the two-dimensional `ScalingFactor[sizeId][matrixId][x][y]` +//! quantization matrices (§7.4.5 equations 7-44..7-51), placing each +//! flat coefficient at the `(x, y)` cell given by the §6.5.3 up-right +//! diagonal scan order ([`crate::scan`]) and applying the +//! `2x`/`4x` block-upsampling for the 16x16 / 32x32 sizes plus the +//! DC-coefficient `[0][0]` override. + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::scan::up_right_diagonal; + +/// Number of `sizeId` values (4x4, 8x8, 16x16, 32x32) — §7.4.5 +/// Table 7-3. +pub const NUM_SIZE_IDS: usize = 4; + +/// Number of `matrixId` values per `sizeId` — §7.4.5 Table 7-4 +/// (intra Y/Cb/Cr + inter Y/Cb/Cr). +pub const NUM_MATRIX_IDS: usize = 6; + +/// Maximum number of coefficients in a flat scaling list. `sizeId` 0 +/// carries 16; `sizeId` 1..3 carry 64 +/// (`Min(64, 1 << (4 + (sizeId << 1)))`). +pub const MAX_COEF_NUM: usize = 64; + +/// Number of explicit coefficients for a given `sizeId`: +/// `Min(64, 1 << (4 + (sizeId << 1)))` (§7.3.4) — 16 for `sizeId` 0, +/// 64 otherwise. +fn coef_num(size_id: usize) -> usize { + (1usize << (4 + (size_id << 1))).min(MAX_COEF_NUM) +} + +/// Errors that can arise while parsing `scaling_list_data()`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ScalingListError { + /// The RBSP ran out of bits before the structure was fully parsed. + Truncated, + /// `scaling_list_pred_matrix_id_delta` exceeded the §7.4.5 bound + /// (`matrixId` for `sizeId <= 2`, `matrixId / 3` for `sizeId == 3`), + /// which would index a non-existent or future reference list. + PredMatrixIdDeltaOutOfRange { + /// The `sizeId` of the offending slot. + size_id: u8, + /// The `matrixId` of the offending slot. + matrix_id: u8, + /// The (illegal) `scaling_list_pred_matrix_id_delta` value. + got: u32, + }, + /// `scaling_list_dc_coef_minus8` was outside the §7.4.5 range of + /// −7 to 247, inclusive. + DcCoefOutOfRange { + /// The `sizeId` of the offending slot (always > 1). + size_id: u8, + /// The `matrixId` of the offending slot. + matrix_id: u8, + /// The (illegal) `scaling_list_dc_coef_minus8` value. + got: i32, + }, + /// `scaling_list_delta_coef` was outside the §7.4.5 range of −128 + /// to 127, inclusive. + DeltaCoefOutOfRange { + /// The `sizeId` of the offending slot. + size_id: u8, + /// The `matrixId` of the offending slot. + matrix_id: u8, + /// The coefficient index `i`. + index: u8, + /// The (illegal) `scaling_list_delta_coef` value. + got: i32, + }, + /// A derived coefficient `ScalingList[sizeId][matrixId][i]` was not + /// greater than 0, violating the §7.4.5 conformance requirement. + NonPositiveCoef { + /// The `sizeId` of the offending slot. + size_id: u8, + /// The `matrixId` of the offending slot. + matrix_id: u8, + /// The coefficient index `i`. + index: u8, + }, + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), +} + +impl core::fmt::Display for ScalingListError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("scaling_list_data() truncated"), + Self::PredMatrixIdDeltaOutOfRange { + size_id, + matrix_id, + got, + } => write!( + f, + "scaling_list_pred_matrix_id_delta[{size_id}][{matrix_id}] out of range: {got}" + ), + Self::DcCoefOutOfRange { + size_id, + matrix_id, + got, + } => write!( + f, + "scaling_list_dc_coef_minus8[{}][{matrix_id}] out of range: {got}", + size_id - 2 + ), + Self::DeltaCoefOutOfRange { + size_id, + matrix_id, + index, + got, + } => write!( + f, + "scaling_list_delta_coef[{size_id}][{matrix_id}][{index}] out of range: {got}" + ), + Self::NonPositiveCoef { + size_id, + matrix_id, + index, + } => write!( + f, + "ScalingList[{size_id}][{matrix_id}][{index}] is not greater than 0" + ), + Self::Bitstream(e) => write!(f, "bitstream error during scaling_list_data(): {e}"), + } + } +} + +impl std::error::Error for ScalingListError {} + +impl From for ScalingListError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +/// Default 4x4 list — §7.4.5 Table 7-5: every coefficient is 16 for +/// all six `matrixId`s. +const DEFAULT_4X4: [u16; 16] = [16; 16]; + +/// Default 8x8 intra list (`matrixId` 0..2) — §7.4.5 Table 7-6, rows +/// for `ScalingList[1..3][0..2]`. Also serves as the default for the +/// 16x16 and 32x32 intra lists (sizeId 1, 2, 3). +const DEFAULT_8X8_INTRA: [u16; 64] = [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 16, 17, 16, 17, 18, // i = 0..15 + 17, 18, 18, 17, 18, 21, 19, 20, 21, 20, 19, 21, 24, 22, 22, 24, // i = 16..31 + 24, 22, 22, 24, 25, 25, 27, 30, 27, 25, 25, 29, 31, 35, 35, 31, // i = 32..47 + 29, 36, 41, 44, 41, 36, 47, 54, 54, 47, 65, 70, 65, 88, 88, 115, // i = 48..63 +]; + +/// Default 8x8 inter list (`matrixId` 3..5) — §7.4.5 Table 7-6, rows +/// for `ScalingList[1..3][3..5]`. Also serves as the default for the +/// 16x16 and 32x32 inter lists. +const DEFAULT_8X8_INTER: [u16; 64] = [ + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, // i = 0..15 + 18, 18, 18, 18, 18, 20, 20, 20, 20, 20, 20, 20, 24, 24, 24, 24, // i = 16..31 + 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 28, 28, 28, 28, 28, // i = 32..47 + 28, 33, 33, 33, 33, 33, 41, 41, 41, 41, 54, 54, 54, 71, 71, 91, // i = 48..63 +]; + +/// The §7.4.5 default `ScalingList[sizeId][matrixId][i]` values, for +/// `i = 0..coefNum(sizeId) - 1`. `sizeId == 0` is the flat 4x4 list; +/// every other `sizeId` reuses the 8x8 intra/inter defaults +/// (`matrixId < 3` → intra, `matrixId >= 3` → inter). +pub fn default_scaling_list(size_id: usize, matrix_id: usize) -> &'static [u16] { + if size_id == 0 { + &DEFAULT_4X4 + } else if matrix_id < 3 { + &DEFAULT_8X8_INTRA + } else { + &DEFAULT_8X8_INTER + } +} + +/// One parsed-and-derived scaling list: the flat coefficient array +/// `ScalingList[sizeId][matrixId][i]` plus its DC coefficient (the +/// §7.4.5 `scaling_list_dc_coef_minus8 + 8`, only meaningful for +/// `sizeId > 1`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScalingListMatrix { + /// The flat coefficients, length `coefNum(sizeId)` (16 for + /// `sizeId` 0, else 64). + pub coef: Vec, + /// `scaling_list_dc_coef_minus8 + 8` — the DC coefficient for + /// `sizeId > 1`, supplying `ScalingFactor[sizeId][matrixId][0][0]`. + /// Inferred to 8 (and unused) for `sizeId <= 1`. + pub dc_coef: u16, +} + +/// The full parsed-and-derived `scaling_list_data()` structure: all 24 +/// `(sizeId, matrixId)` slots. Slots not signalled for `sizeId == 3` +/// (matrixId 1, 2, 4, 5 are skipped by the `matrixId += 3` step) +/// retain their default value. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScalingListData { + /// `[sizeId][matrixId]` — the derived per-slot scaling lists. + pub lists: [[ScalingListMatrix; NUM_MATRIX_IDS]; NUM_SIZE_IDS], +} + +impl ScalingListData { + /// The all-default `scaling_list_data()`: every slot carries its + /// §7.4.5 Table 7-5 / Table 7-6 default list with a DC scaling + /// factor of 16 (`scaling_list_dc_coef_minus8` inferred to 8). + /// + /// This is the active scaling-list data when + /// `scaling_list_enabled_flag == 1` but neither the SPS nor the PPS + /// carries an explicit `scaling_list_data()` body. + #[must_use] + pub fn all_default() -> Self { + let lists: [[ScalingListMatrix; NUM_MATRIX_IDS]; NUM_SIZE_IDS] = + core::array::from_fn(|size_id| { + core::array::from_fn(|matrix_id| ScalingListMatrix { + coef: default_scaling_list(size_id, matrix_id).to_vec(), + // §7.4.5: the inferred scaling_list_dc_coef_minus8 + // is 8 ⇒ ScalingFactor[sizeId][matrixId][0][0] = 16 + // (matching the default lists' first coefficient). + dc_coef: 16, + }) + }); + Self { lists } + } + + /// Parse `scaling_list_data()` (§7.3.4) and derive the per-slot + /// `ScalingList` coefficient arrays (§7.4.5), applying the + /// default-list and prediction-inference rules. + pub fn parse(br: &mut BitReader<'_>) -> Result { + // Seed every slot with its default; signalled slots overwrite. + // sizeId == 3 only visits matrixId 0 and 3 (the `+= 3` step), + // so the other four slots stay at their (unused) default. + let mut lists = Self::all_default().lists; + + for (size_id, size_lists) in lists.iter_mut().enumerate() { + // matrixId += (sizeId == 3) ? 3 : 1 (§7.3.4) + let step = if size_id == 3 { 3 } else { 1 }; + let mut matrix_id = 0usize; + while matrix_id < NUM_MATRIX_IDS { + let pred_mode_flag = br.u1()? != 0; + if !pred_mode_flag { + // Prediction from a reference list of the same sizeId. + let delta = br.ue()?; + let max_delta = if size_id <= 2 { + matrix_id as u32 + } else { + matrix_id as u32 / 3 + }; + if delta > max_delta { + return Err(ScalingListError::PredMatrixIdDeltaOutOfRange { + size_id: size_id as u8, + matrix_id: matrix_id as u8, + got: delta, + }); + } + if delta == 0 { + // §7.4.5: inferred from the default scaling list. + let def = default_scaling_list(size_id, matrix_id); + size_lists[matrix_id] = ScalingListMatrix { + coef: def.to_vec(), + // §7.4.5: scaling_list_dc_coef_minus8 is + // inferred to be 8 for the default list, + // i.e. a DC scaling factor of 16. + dc_coef: 16, + }; + } else { + // refMatrixId = matrixId − delta * step (7-42), + // and copy the reference list (7-43) including + // its DC coefficient (§7.4.5 last paragraph). + let ref_matrix_id = matrix_id - (delta as usize) * step; + size_lists[matrix_id] = size_lists[ref_matrix_id].clone(); + } + } else { + // Explicitly signalled list. + let n = coef_num(size_id); + let mut next_coef: i32 = 8; + let mut dc_coef: u16 = 8; + if size_id > 1 { + let dc = br.se()?; + if !(-7..=247).contains(&dc) { + return Err(ScalingListError::DcCoefOutOfRange { + size_id: size_id as u8, + matrix_id: matrix_id as u8, + got: dc, + }); + } + next_coef = dc + 8; + dc_coef = (dc + 8) as u16; + } + let mut coef = Vec::with_capacity(n); + for i in 0..n { + let delta_coef = br.se()?; + // §7.4.5: "The value of scaling_list_delta_coef + // shall be in the range of −128 to 127, + // inclusive." (Also keeps the eq. nextCoef sum + // below inside i32.) + if !(-128..=127).contains(&delta_coef) { + return Err(ScalingListError::DeltaCoefOutOfRange { + size_id: size_id as u8, + matrix_id: matrix_id as u8, + index: i as u8, + got: delta_coef, + }); + } + // nextCoef = (nextCoef + delta_coef + 256) % 256 + next_coef = (next_coef + delta_coef + 256).rem_euclid(256); + if next_coef <= 0 { + return Err(ScalingListError::NonPositiveCoef { + size_id: size_id as u8, + matrix_id: matrix_id as u8, + index: i as u8, + }); + } + coef.push(next_coef as u16); + } + size_lists[matrix_id] = ScalingListMatrix { coef, dc_coef }; + } + matrix_id += step; + } + } + + Ok(Self { lists }) + } + + /// Derive the §7.4.5 `ScalingFactor[sizeId][matrixId][x][y]` + /// quantization matrices (equations 7-44..7-51) from the parsed + /// flat lists. + /// + /// `chroma_array_type` is the §7.4.3.2.1 `ChromaArrayType` + /// (`separate_colour_plane_flag ? 0 : chroma_format_idc`). It only + /// affects the 32x32 chroma matrices: equations 7-50 / 7-51 derive + /// `ScalingFactor[3][matrixId]` for `matrixId ∈ {1, 2, 4, 5}` from + /// the corresponding 16x16 lists (`ScalingList[2][matrixId]`) **only + /// when `ChromaArrayType == 3`** (4:4:4). For other chroma formats + /// those 32x32 chroma matrices are not used, and they are left as + /// all-zero so a consumer that reads one signals its own bug. + pub fn scaling_factors(&self, chroma_array_type: u8) -> ScalingFactors { + // ScanOrder[2][0] — up-right diagonal scan of a 4x4 block + // (16 positions); ScanOrder[3][0] — of an 8x8 block (64). + let scan_4 = up_right_diagonal(4); + let scan_8 = up_right_diagonal(8); + + let mut out = ScalingFactors { + factors: core::array::from_fn(|size_id| { + let dim = 1usize << (2 + size_id); // 4, 8, 16, 32 + core::array::from_fn(|_matrix_id| ScalingFactorMatrix { + dim: dim as u8, + coef: vec![0u16; dim * dim], + }) + }), + }; + + for matrix_id in 0..NUM_MATRIX_IDS { + // 4x4 (sizeId 0) — equation 7-44: place ScalingList[0][m][i] + // at (ScanOrder[2][0][i][0], ScanOrder[2][0][i][1]). + place( + &mut out.factors[0][matrix_id], + &self.lists[0][matrix_id].coef, + &scan_4, + 1, + ); + + // 8x8 (sizeId 1) — equation 7-45: 8x8 scan, no upsampling. + place( + &mut out.factors[1][matrix_id], + &self.lists[1][matrix_id].coef, + &scan_8, + 1, + ); + + // 16x16 (sizeId 2) — equation 7-46: 8x8 scan, each entry + // replicated into a 2x2 block. Then 7-47 overrides [0][0] + // with the DC coefficient. + place( + &mut out.factors[2][matrix_id], + &self.lists[2][matrix_id].coef, + &scan_8, + 2, + ); + set_dc( + &mut out.factors[2][matrix_id], + self.lists[2][matrix_id].dc_coef, + ); + } + + // 32x32 (sizeId 3) — only matrixId 0 (intra Y) and 3 (inter Y) + // are signalled (the `matrixId += 3` step). Equation 7-48 uses + // the 8x8 scan with each entry replicated into a 4x4 block, + // 7-49 overrides [0][0] with the DC coefficient. + for &matrix_id in &[0usize, 3usize] { + place( + &mut out.factors[3][matrix_id], + &self.lists[3][matrix_id].coef, + &scan_8, + 4, + ); + set_dc( + &mut out.factors[3][matrix_id], + self.lists[3][matrix_id].dc_coef, + ); + } + + // 32x32 chroma (matrixId 1, 2, 4, 5) — equations 7-50 / 7-51, + // applicable only for ChromaArrayType == 3 (4:4:4). The flat + // list comes from the 16x16 (sizeId 2) list of the same + // matrixId, and the DC coefficient also from sizeId 2. + if chroma_array_type == 3 { + for &matrix_id in &[1usize, 2usize, 4usize, 5usize] { + place( + &mut out.factors[3][matrix_id], + &self.lists[2][matrix_id].coef, + &scan_8, + 4, + ); + set_dc( + &mut out.factors[3][matrix_id], + self.lists[2][matrix_id].dc_coef, + ); + } + } + + out + } +} + +/// Scatter a flat scaling list into a `ScalingFactor` matrix along the +/// up-right diagonal `scan`, replicating each coefficient into a +/// `rep`x`rep` block (`rep == 1` for 4x4 / 8x8, 2 for 16x16, 4 for +/// 32x32 — the `x * rep + k` / `y * rep + j` indexing of equations +/// 7-46 / 7-48 / 7-50). +fn place( + matrix: &mut ScalingFactorMatrix, + coef: &[u16], + scan: &[crate::scan::ScanPos], + rep: usize, +) { + let dim = matrix.dim as usize; + for (i, value) in coef.iter().copied().enumerate() { + let pos = scan[i]; + let bx = pos.x as usize * rep; + let by = pos.y as usize * rep; + for j in 0..rep { + for k in 0..rep { + let x = bx + k; + let y = by + j; + matrix.coef[y * dim + x] = value; + } + } + } +} + +/// Override `ScalingFactor[sizeId][matrixId][0][0]` with the DC +/// coefficient (equations 7-47 / 7-49 / 7-51). +fn set_dc(matrix: &mut ScalingFactorMatrix, dc_coef: u16) { + matrix.coef[0] = dc_coef; +} + +/// One derived §7.4.5 `ScalingFactor[sizeId][matrixId][x][y]` +/// quantization matrix, stored row-major (`coef[y * dim + x]`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScalingFactorMatrix { + /// Side length of the (square) matrix: 4, 8, 16, or 32 — `1 << (2 + + /// sizeId)`. + pub dim: u8, + /// The `dim * dim` scaling factors, row-major: the value at column + /// `x`, row `y` is `coef[y * dim + x]`. + pub coef: Vec, +} + +impl ScalingFactorMatrix { + /// `ScalingFactor[..][..][x][y]` — the scaling factor at column `x` + /// (horizontal), row `y` (vertical). Panics if `x` or `y` is `>= + /// dim`. + #[inline] + pub fn at(&self, x: usize, y: usize) -> u16 { + let dim = self.dim as usize; + assert!(x < dim && y < dim, "ScalingFactor index out of range"); + self.coef[y * dim + x] + } +} + +/// The full set of §7.4.5 `ScalingFactor[sizeId][matrixId][x][y]` +/// quantization matrices, derived from a [`ScalingListData`] via +/// [`ScalingListData::scaling_factors`]. +/// +/// The 32x32 chroma matrices (`factors[3][1]`, `[3][2]`, `[3][4]`, +/// `[3][5]`) are all-zero unless `ChromaArrayType == 3`; see +/// [`ScalingListData::scaling_factors`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ScalingFactors { + /// `[sizeId][matrixId]` — the derived quantization matrices. + pub factors: [[ScalingFactorMatrix; NUM_MATRIX_IDS]; NUM_SIZE_IDS], +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Pack a sequence of `(value, bit_width)` MSB-first into bytes. + fn pack(fields: &[(u64, u32)]) -> Vec { + let mut out = Vec::new(); + let mut cur = 0u8; + let mut nbits = 0u32; + for &(val, w) in fields { + for i in (0..w).rev() { + let bit = ((val >> i) & 1) as u8; + cur = (cur << 1) | bit; + nbits += 1; + if nbits == 8 { + out.push(cur); + cur = 0; + nbits = 0; + } + } + } + if nbits > 0 { + cur <<= 8 - nbits; + out.push(cur); + } + out + } + + /// ue(v) codeword for a small codeNum, as `(value, width)` fields. + /// codeNum 0 → '1'; codeNum N → prefix of `m` zeros, a 1, then + /// `m`-bit suffix where `m = floor(log2(N+1))`. + fn ue(code_num: u32) -> Vec<(u64, u32)> { + let x = code_num + 1; + let m = 31 - x.leading_zeros(); // floor(log2(x)) + // m leading zeros + the implicit leading 1 of `x` (so `x` in + // (m+1) bits) gives the standard Exp-Golomb codeword. + vec![(0, m), (x as u64, m + 1)] + } + + /// se(v) codeword: map value → codeNum per Table 9-3, then ue(). + fn se(value: i32) -> Vec<(u64, u32)> { + let code_num = if value > 0 { + (2 * value - 1) as u32 + } else { + (-2 * value) as u32 + }; + ue(code_num) + } + + /// A `scaling_list_data()` where every one of the 24 slots is + /// pred_mode_flag=0, delta=0 (i.e. "use the default list"). + /// 24 slots visited: sizeId 0/1/2 each 6, sizeId 3 only 2. + fn all_default_bits() -> Vec<(u64, u32)> { + let mut f = Vec::new(); + for size_id in 0..4 { + let step = if size_id == 3 { 3 } else { 1 }; + let mut m = 0; + while m < 6 { + f.push((0, 1)); // scaling_list_pred_mode_flag = 0 + f.extend(ue(0)); // scaling_list_pred_matrix_id_delta = 0 + m += step; + } + } + f + } + + #[test] + fn all_default_lists_match_tables() { + let bits = all_default_bits(); + let buf = pack(&bits); + let mut br = BitReader::new(&buf); + let data = ScalingListData::parse(&mut br).unwrap(); + + // 4x4 — Table 7-5: all 16. + for m in 0..6 { + assert_eq!(data.lists[0][m].coef, vec![16u16; 16]); + } + // 8x8 intra (matrixId 0..2) — Table 7-6. + for m in 0..3 { + assert_eq!(data.lists[1][m].coef, DEFAULT_8X8_INTRA.to_vec()); + } + // 8x8 inter (matrixId 3..5). + for m in 3..6 { + assert_eq!(data.lists[1][m].coef, DEFAULT_8X8_INTER.to_vec()); + } + // 16x16 reuses the 8x8 defaults; the default DC is 16 (§7.4.5: + // scaling_list_dc_coef_minus8 inferred to 8 ⇒ 8 + 8). + assert_eq!(data.lists[2][0].coef, DEFAULT_8X8_INTRA.to_vec()); + assert_eq!(data.lists[2][0].dc_coef, 16); + assert_eq!(data.lists[2][3].coef, DEFAULT_8X8_INTER.to_vec()); + // 32x32 visits only matrixId 0 (intra) and 3 (inter). + assert_eq!(data.lists[3][0].coef, DEFAULT_8X8_INTRA.to_vec()); + assert_eq!(data.lists[3][3].coef, DEFAULT_8X8_INTER.to_vec()); + assert_eq!(data.lists[3][0].dc_coef, 16); + } + + /// Coefficient-numbering: sizeId 0 carries 16, sizeId 1..3 carry 64. + #[test] + fn coef_num_per_size_id() { + assert_eq!(coef_num(0), 16); + assert_eq!(coef_num(1), 64); + assert_eq!(coef_num(2), 64); + assert_eq!(coef_num(3), 64); + } + + /// An explicitly-signalled 4x4 list (sizeId 0, matrixId 0): all 16 + /// slots carry delta 0, so every coefficient equals the + /// `nextCoef` seed (8). Verifies the running modulo accumulator and + /// that no DC coefficient is read for sizeId <= 1. + #[test] + fn explicit_flat_4x4_list() { + let mut f = Vec::new(); + // sizeId 0, matrixId 0: pred_mode = 1, 16 delta_coef = 0. + f.push((1, 1)); + for _ in 0..16 { + f.extend(se(0)); + } + // Remaining 23 slots: default (pred_mode = 0, delta = 0). + for size_id in 0..4 { + let step = if size_id == 3 { 3 } else { 1 }; + let mut m = 0; + while m < 6 { + if !(size_id == 0 && m == 0) { + f.push((0, 1)); + f.extend(ue(0)); + } + m += step; + } + } + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let data = ScalingListData::parse(&mut br).unwrap(); + // nextCoef seeds at 8; every delta is 0 ⇒ all coefs = 8. + assert_eq!(data.lists[0][0].coef, vec![8u16; 16]); + } + + /// Explicit 16x16 list (sizeId 2) reads a DC coefficient first. + /// dc = +4 ⇒ scaling_list_dc_coef_minus8 = 4 ⇒ dc_coef = 12, + /// nextCoef seeds at 12; deltas all 0 ⇒ every coef = 12. + #[test] + fn explicit_16x16_reads_dc_coef() { + let mut f = Vec::new(); + // Default sizeId 0 and 1 (12 slots). + for _ in 0..2 { + for _ in 0..6 { + f.push((0, 1)); + f.extend(ue(0)); + } + } + // sizeId 2, matrixId 0: explicit with DC = +4. + f.push((1, 1)); + f.extend(se(4)); // scaling_list_dc_coef_minus8 = 4 + for _ in 0..64 { + f.extend(se(0)); + } + // sizeId 2, matrixId 1..5: default. + for _ in 1..6 { + f.push((0, 1)); + f.extend(ue(0)); + } + // sizeId 3, matrixId 0 and 3: default. + for _ in 0..2 { + f.push((0, 1)); + f.extend(ue(0)); + } + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let data = ScalingListData::parse(&mut br).unwrap(); + assert_eq!(data.lists[2][0].dc_coef, 12); + assert_eq!(data.lists[2][0].coef, vec![12u16; 64]); + } + + /// Prediction with delta != 0 copies the referenced list (eq 7-43), + /// including its DC coefficient. Set sizeId 2, matrixId 0 explicit + /// with DC=+4, then matrixId 1 predicts from it (delta = 1 ⇒ + /// refMatrixId = 0). + #[test] + fn pred_matrix_id_delta_copies_reference() { + let mut f = Vec::new(); + for _ in 0..2 { + for _ in 0..6 { + f.push((0, 1)); + f.extend(ue(0)); + } + } + // sizeId 2, matrixId 0: explicit, DC = +4, all deltas 0. + f.push((1, 1)); + f.extend(se(4)); + for _ in 0..64 { + f.extend(se(0)); + } + // sizeId 2, matrixId 1: predicts from matrixId 0 (delta = 1). + f.push((0, 1)); + f.extend(ue(1)); + // sizeId 2, matrixId 2..5: default. + for _ in 2..6 { + f.push((0, 1)); + f.extend(ue(0)); + } + // sizeId 3, matrixId 0 and 3: default. + for _ in 0..2 { + f.push((0, 1)); + f.extend(ue(0)); + } + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let data = ScalingListData::parse(&mut br).unwrap(); + // matrixId 1 == copy of matrixId 0 (coefs and DC). + assert_eq!(data.lists[2][1].coef, data.lists[2][0].coef); + assert_eq!(data.lists[2][1].dc_coef, 12); + } + + /// `scaling_list_pred_matrix_id_delta` out of range is rejected: + /// for sizeId 0, matrixId 0 the max allowed delta is 0, so delta=1 + /// must error. + #[test] + fn rejects_pred_matrix_id_delta_out_of_range() { + let mut f = Vec::new(); + f.push((0, 1)); // pred_mode = 0 + f.extend(ue(1)); // delta = 1 > matrixId(0) + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let err = ScalingListData::parse(&mut br).unwrap_err(); + assert_eq!( + err, + ScalingListError::PredMatrixIdDeltaOutOfRange { + size_id: 0, + matrix_id: 0, + got: 1, + } + ); + } + + /// A delta-coef sequence that drives `nextCoef` to 0 (modulo 256) + /// must be rejected (§7.4.5: ScalingList coefficient > 0). + #[test] + fn rejects_non_positive_coef() { + let mut f = Vec::new(); + // sizeId 0, matrixId 0: explicit. nextCoef seeds at 8; a + // delta_coef of −8 wraps it to 0. + f.push((1, 1)); + f.extend(se(-8)); + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let err = ScalingListData::parse(&mut br).unwrap_err(); + assert_eq!( + err, + ScalingListError::NonPositiveCoef { + size_id: 0, + matrix_id: 0, + index: 0, + } + ); + } + + /// Fuzz regression (r282 `parse_annexb`): §7.4.5 bounds + /// `scaling_list_delta_coef` to −128..=127, inclusive. An + /// unbounded `se(v)` value previously overflowed the i32 + /// `nextCoef + scaling_list_delta_coef + 256` sum. + #[test] + fn rejects_delta_coef_out_of_range() { + let mut f = Vec::new(); + // sizeId 0, matrixId 0: explicit list; first delta_coef + // = −129 (codeNum 258), one past the §7.4.5 lower bound. + f.push((1, 1)); + f.extend(se(-129)); + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let err = ScalingListData::parse(&mut br).unwrap_err(); + assert_eq!( + err, + ScalingListError::DeltaCoefOutOfRange { + size_id: 0, + matrix_id: 0, + index: 0, + got: -129, + } + ); + } + + /// `scaling_list_dc_coef_minus8` outside −7..=247 is rejected. + /// se(v) for −8 (codeNum 16) gives dc = −8 < −7. + #[test] + fn rejects_dc_coef_out_of_range() { + let mut f = Vec::new(); + for _ in 0..2 { + for _ in 0..6 { + f.push((0, 1)); + f.extend(ue(0)); + } + } + // sizeId 2, matrixId 0: explicit with DC = −8 (out of range). + f.push((1, 1)); + f.extend(se(-8)); + let buf = pack(&f); + let mut br = BitReader::new(&buf); + let err = ScalingListData::parse(&mut br).unwrap_err(); + assert_eq!( + err, + ScalingListError::DcCoefOutOfRange { + size_id: 2, + matrix_id: 0, + got: -8, + } + ); + } + + /// Truncation midway through the structure surfaces `Truncated`. + #[test] + fn truncation_is_reported() { + // Just one bit — not enough for the first slot. + let buf = [0u8; 0]; + let mut br = BitReader::new(&buf); + assert_eq!( + ScalingListData::parse(&mut br).unwrap_err(), + ScalingListError::Truncated + ); + } + + /// Parse the all-default `scaling_list_data()` and derive its + /// `ScalingFactor` matrices. + fn all_default_factors(chroma_array_type: u8) -> ScalingFactors { + let buf = pack(&all_default_bits()); + let mut br = BitReader::new(&buf); + ScalingListData::parse(&mut br) + .unwrap() + .scaling_factors(chroma_array_type) + } + + /// 4x4 (sizeId 0) `ScalingFactor` matrices are 4x4, and — since the + /// default 4x4 list is flat 16 — every cell is 16 (equation 7-44). + /// Also exercises the [`ScalingFactorMatrix::at`] accessor. + #[test] + fn factor_4x4_default_all_16() { + let f = all_default_factors(1); + for m in 0..NUM_MATRIX_IDS { + let mat = &f.factors[0][m]; + assert_eq!(mat.dim, 4); + assert_eq!(mat.coef.len(), 16); + assert!(mat.coef.iter().all(|&c| c == 16)); + assert_eq!(mat.at(2, 3), 16); + } + } + + /// 8x8 (sizeId 1) default intra `ScalingFactor` is the 8x8 intra + /// table scattered along the up-right diagonal scan (equation 7-45). + /// Spot-check the diagonal placement: `ScalingList[1][0][i]` lands + /// at `(ScanOrder[3][0][i][0], ScanOrder[3][0][i][1])`. + #[test] + fn factor_8x8_intra_follows_diagonal_scan() { + let f = all_default_factors(1); + let mat = &f.factors[1][0]; + assert_eq!(mat.dim, 8); + let scan = crate::scan::up_right_diagonal(8); + for (i, &expected) in DEFAULT_8X8_INTRA.iter().enumerate() { + let p = scan[i]; + assert_eq!( + mat.at(p.x as usize, p.y as usize), + expected, + "8x8 intra coef i={i} misplaced" + ); + } + // i = 0 maps to (0, 0): the first table entry is 16. + assert_eq!(mat.at(0, 0), DEFAULT_8X8_INTRA[0]); + } + + /// 16x16 (sizeId 2) uses the 8x8 scan with each entry replicated + /// into a 2x2 block (equation 7-46), then the DC coefficient + /// overrides `[0][0]` (equation 7-47). Build an explicit list with + /// DC = +4 ⇒ `dc_coef = 12`, which also seeds `next_coef`; with all + /// deltas 0 every flat list coef is 12, so the whole matrix is 12 — + /// confirming both the 2x2 replication blankets the grid and the DC + /// override lands on `[0][0]`. A second slot (DC = 0, delta seeds an + /// i=0 coef of 8) separates the DC override from the list body. + #[test] + fn factor_16x16_replicates_2x2_and_dc_override() { + // Default sizeId 0 and 1. + let mut bits = Vec::new(); + for _ in 0..2 { + for _ in 0..6 { + bits.push((0, 1)); + bits.extend(ue(0)); + } + } + // sizeId 2, matrixId 0: explicit, DC = +4 (dc_coef 12), deltas 0 + // ⇒ every flat coef = 12 (next_coef seeds from the DC value). + bits.push((1, 1)); + bits.extend(se(4)); + for _ in 0..64 { + bits.extend(se(0)); + } + // sizeId 2, matrixId 1: explicit, DC = -8+? -> use dc=0 so + // dc_coef = 8, then a first delta of 0 ⇒ list coef 8 throughout; + // the DC override is then a no-op (8 == 8) — but matrixId 2 sets + // DC -1 to separate the override from the list body. + bits.push((1, 1)); + bits.extend(se(0)); // dc_coef 8 + for _ in 0..64 { + bits.extend(se(0)); + } + // sizeId 2, matrixId 2: explicit, DC = -1 (dc_coef 7) but list + // body driven to 8 (next_coef seeds at 7, first delta +1 ⇒ 8). + bits.push((1, 1)); + bits.extend(se(-1)); // dc_coef 7 + bits.extend(se(1)); // i=0: next_coef 7+1 = 8 + for _ in 1..64 { + bits.extend(se(0)); // remaining deltas 0 ⇒ all 8 + } + // sizeId 2, matrixId 3..5 default; sizeId 3 matrixId 0/3 default. + for _ in 3..6 { + bits.push((0, 1)); + bits.extend(ue(0)); + } + for _ in 0..2 { + bits.push((0, 1)); + bits.extend(ue(0)); + } + let buf = pack(&bits); + let mut br = BitReader::new(&buf); + let data = ScalingListData::parse(&mut br).unwrap(); + let f = data.scaling_factors(1); + + // matrixId 0: DC seeds list, all 12. + let mat0 = &f.factors[2][0]; + assert_eq!(mat0.dim, 16); + assert_eq!(mat0.coef.len(), 256); + assert!(mat0.coef.iter().all(|&c| c == 12)); + + // matrixId 2: list body 8, DC override 7 at [0][0] only — proves + // the override is isolated to the single corner cell while the + // 2x2 replication blankets the rest with the list value. + let mat2 = &f.factors[2][2]; + assert_eq!(mat2.at(0, 0), 7); + assert_eq!(mat2.at(1, 0), 8); + assert_eq!(mat2.at(0, 1), 8); + assert_eq!(mat2.at(1, 1), 8); + for y in 0..16 { + for x in 0..16 { + if x == 0 && y == 0 { + continue; + } + assert_eq!(mat2.at(x, y), 8, "cell ({x},{y})"); + } + } + } + + /// 32x32 (sizeId 3) only derives matrixId 0 (intra Y) and 3 + /// (inter Y) for non-4:4:4 chroma; each 8x8-scan entry replicates + /// into a 4x4 block (equation 7-48) and the DC overrides [0][0] + /// (7-49). The chroma matrices (1,2,4,5) stay all-zero. + #[test] + fn factor_32x32_replicates_4x4_chroma_zero_when_not_444() { + let f = all_default_factors(1); // ChromaArrayType 1 (4:2:0) + let intra = &f.factors[3][0]; + assert_eq!(intra.dim, 32); + assert_eq!(intra.coef.len(), 1024); + // The default DC is 16 (scaling_list_dc_coef_minus8 inferred + // to 8), matching the i=0 list coefficient. + assert_eq!(intra.at(0, 0), 16); + assert_eq!(intra.at(1, 0), 16); + assert_eq!(intra.at(3, 3), 16); + // Inter Y (matrixId 3) is also derived. + assert_eq!(f.factors[3][3].at(1, 0), 16); + // Chroma matrices are untouched (all-zero) for ChromaArrayType + // != 3. + for &m in &[1usize, 2, 4, 5] { + assert!(f.factors[3][m].coef.iter().all(|&c| c == 0)); + } + } + + /// With `ChromaArrayType == 3` (4:4:4) the 32x32 chroma matrices + /// (matrixId 1, 2, 4, 5) are derived from the 16x16 (sizeId 2) + /// lists of the same matrixId (equations 7-50 / 7-51), so they are + /// no longer all-zero. + #[test] + fn factor_32x32_chroma_derived_when_444() { + let f = all_default_factors(3); + for &m in &[1usize, 2, 4, 5] { + let mat = &f.factors[3][m]; + assert_eq!(mat.dim, 32); + // Derived from the default 16x16 list (intra for m<3, inter + // otherwise) ⇒ not all-zero; the default DC 16 at [0][0]. + assert!(mat.coef.iter().any(|&c| c != 0)); + assert_eq!(mat.at(0, 0), 16); + } + // The chroma 32x32 matrix matches the 16x16 luma-scan placement + // of the same matrixId's 8x8 default table, replicated 4x4. + let mat = &f.factors[3][1]; + let scan = crate::scan::up_right_diagonal(8); + // i=1 (intra default table entry) lands at scan[1] scaled by 4. + let p = scan[1]; + assert_eq!( + mat.at(p.x as usize * 4, p.y as usize * 4), + DEFAULT_8X8_INTRA[1] + ); + } +} diff --git a/vendor/oxideav-h265/src/scan.rs b/vendor/oxideav-h265/src/scan.rs new file mode 100644 index 0000000..b38617f --- /dev/null +++ b/vendor/oxideav-h265/src/scan.rs @@ -0,0 +1,552 @@ +//! §6.5 scan-order array initialization processes and the §7.4.2 +//! `ScanOrder[ log2BlockSize ][ scanIdx ]` table. +//! +//! ITU-T Rec. H.265 §6.5.3..§6.5.6 define four scan orders that map a +//! scan position `sPos` (0..`blkSize * blkSize − 1`) to a +//! `(horizontal, vertical)` coordinate pair: +//! +//! * §6.5.3 [`up_right_diagonal`] — walks the block along up-right +//! diagonals (equation 6-11). `scanIdx == 0`. +//! * §6.5.4 [`horizontal`] — raster order, row by row (equation 6-12). +//! `scanIdx == 1`. +//! * §6.5.5 [`vertical`] — column by column (equation 6-13). +//! `scanIdx == 2`. +//! * §6.5.6 [`traverse`] — boustrophedon (serpentine) raster: even rows +//! left-to-right, odd rows right-to-left (equation 6-14). +//! `scanIdx == 3`. +//! +//! §7.4.2 assembles these into +//! `ScanOrder[ log2BlockSize ][ scanIdx ][ sPos ][ sComp ]`, with +//! `scanIdx` 0 = diagonal, 1 = horizontal, 2 = vertical, 3 = traverse. +//! The diagonal / horizontal / vertical scans are populated for +//! `log2BlockSize` 0..3 (block sizes 1, 2, 4, 8) and the traverse scan +//! for `log2BlockSize` 2..5 (block sizes 4, 8, 16, 32). [`scan_order`] +//! is the validity-checked accessor over that table. +//! +//! The §7.4.5 `ScalingFactor` derivation (equations 7-44..7-51) reads +//! `ScanOrder[ 2 ][ 0 ]` (a 4x4 block) and `ScanOrder[ 3 ][ 0 ]` (an +//! 8x8 block); the residual-coding path (§7.3.8.11 / §9.3.4.2.4) reads +//! the full table via the `scanIdx` selected per the §9.3.4.2.4 rules. + +/// One scan-position entry: the `(x, y)` coordinate the position maps +/// to. `x` is the horizontal component (`sComp == 0`) and `y` is the +/// vertical component (`sComp == 1`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ScanPos { + /// Horizontal component — `diagScan[ sPos ][ 0 ]`. + pub x: u8, + /// Vertical component — `diagScan[ sPos ][ 1 ]`. + pub y: u8, +} + +/// Build the §6.5.3 up-right diagonal scan order for a `blkSize`x`blkSize` +/// block, returning the `diagScan` array as a `Vec` of length +/// `blkSize * blkSize`, indexed by scan position `sPos`. +/// +/// This is a direct transcription of equation 6-11: starting at the +/// top-left, each inner `while( y >= 0 )` loop walks one up-right +/// diagonal (decrementing `y`, incrementing `x`), emitting only the +/// in-bounds `(x, y)` cells; the outer loop seeds the next diagonal at +/// `y = x, x = 0` and stops once every cell has been visited. +pub fn up_right_diagonal(blk_size: usize) -> Vec { + let n = blk_size * blk_size; + let mut diag = Vec::with_capacity(n); + + // The 6-11 pseudocode uses a signed `y` that the inner loop drives + // below 0 as its termination test, so the coordinates are tracked + // as `i32` and only the in-bounds cells are recorded. + let blk = blk_size as i32; + let mut x: i32 = 0; + let mut y: i32 = 0; + let mut stop = false; + while !stop { + while y >= 0 { + if x < blk && y < blk { + diag.push(ScanPos { + x: x as u8, + y: y as u8, + }); + } + y -= 1; + x += 1; + } + y = x; + x = 0; + if diag.len() >= n { + stop = true; + } + } + + diag +} + +/// Build the §6.5.4 horizontal scan order for a `blkSize`x`blkSize` +/// block, returning the `horScan` array (equation 6-12) as a +/// `Vec` of length `blkSize * blkSize`, indexed by scan +/// position `sPos`. +/// +/// Direct transcription of equation 6-12: a plain raster walk — +/// the outer loop runs over rows `y`, the inner over columns `x`. +/// This is the `scanIdx == 1` entry of the §7.4.2 `ScanOrder` table. +pub fn horizontal(blk_size: usize) -> Vec { + let mut scan = Vec::with_capacity(blk_size * blk_size); + for y in 0..blk_size { + for x in 0..blk_size { + scan.push(ScanPos { + x: x as u8, + y: y as u8, + }); + } + } + scan +} + +/// Build the §6.5.5 vertical scan order for a `blkSize`x`blkSize` +/// block, returning the `verScan` array (equation 6-13) as a +/// `Vec` of length `blkSize * blkSize`, indexed by scan +/// position `sPos`. +/// +/// Direct transcription of equation 6-13: the transpose of the +/// horizontal scan — the outer loop runs over columns `x`, the inner +/// over rows `y`. This is the `scanIdx == 2` entry of the §7.4.2 +/// `ScanOrder` table. +pub fn vertical(blk_size: usize) -> Vec { + let mut scan = Vec::with_capacity(blk_size * blk_size); + for x in 0..blk_size { + for y in 0..blk_size { + scan.push(ScanPos { + x: x as u8, + y: y as u8, + }); + } + } + scan +} + +/// Build the §6.5.6 traverse scan order for a `blkSize`x`blkSize` +/// block, returning the `travScan` array (equation 6-14) as a +/// `Vec` of length `blkSize * blkSize`, indexed by scan +/// position `sPos`. +/// +/// Direct transcription of equation 6-14: a boustrophedon (serpentine) +/// raster — even-indexed rows are walked left-to-right +/// (`x = 0 .. blkSize − 1`) and odd-indexed rows right-to-left +/// (`x = blkSize − 1 .. 0`). This is the `scanIdx == 3` entry of the +/// §7.4.2 `ScanOrder` table. +pub fn traverse(blk_size: usize) -> Vec { + let mut scan = Vec::with_capacity(blk_size * blk_size); + for y in 0..blk_size { + if y % 2 == 0 { + for x in 0..blk_size { + scan.push(ScanPos { + x: x as u8, + y: y as u8, + }); + } + } else { + for x in (0..blk_size).rev() { + scan.push(ScanPos { + x: x as u8, + y: y as u8, + }); + } + } + } + scan +} + +/// §7.4.2 `scanIdx` selector: `0` up-right diagonal, `1` horizontal, +/// `2` vertical, `3` traverse. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ScanIdx { + /// `scanIdx == 0` — §6.5.3 up-right diagonal scan. + Diagonal, + /// `scanIdx == 1` — §6.5.4 horizontal scan. + Horizontal, + /// `scanIdx == 2` — §6.5.5 vertical scan. + Vertical, + /// `scanIdx == 3` — §6.5.6 traverse scan. + Traverse, +} + +impl ScanIdx { + /// The numeric `scanIdx` value used by §7.4.2 / §9.3.4.2.4. + #[must_use] + pub fn index(self) -> u8 { + match self { + Self::Diagonal => 0, + Self::Horizontal => 1, + Self::Vertical => 2, + Self::Traverse => 3, + } + } +} + +/// Errors from the §7.4.2 [`scan_order`] accessor. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ScanOrderError { + /// `log2BlockSize` is outside the range §7.4.2 populates for the + /// requested `scanIdx`: 0..=3 for diagonal / horizontal / vertical, + /// 2..=5 for traverse. + Log2BlockSizeOutOfRange { + /// The requested scan order. + scan_idx: ScanIdx, + /// The out-of-range `log2BlockSize`. + log2_block_size: u8, + }, +} + +impl core::fmt::Display for ScanOrderError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Log2BlockSizeOutOfRange { + scan_idx, + log2_block_size, + } => write!( + f, + "ScanOrder: log2BlockSize {log2_block_size} out of range for {scan_idx:?} scan" + ), + } + } +} + +impl std::error::Error for ScanOrderError {} + +/// §7.4.2 `ScanOrder[ log2BlockSize ][ scanIdx ]` accessor. +/// +/// Returns the scan-position array for a `(1 << log2BlockSize)`-square +/// block under the requested [`ScanIdx`], built by invoking the +/// corresponding §6.5.3..§6.5.6 initialization process with +/// `1 << log2BlockSize`. +/// +/// Per §7.4.2 the table is only populated for `log2BlockSize` in 0..=3 +/// for the up-right diagonal / horizontal / vertical scans and 2..=5 +/// for the traverse scan; an out-of-range `log2_block_size` yields +/// [`ScanOrderError::Log2BlockSizeOutOfRange`]. +pub fn scan_order(log2_block_size: u8, scan_idx: ScanIdx) -> Result, ScanOrderError> { + let in_range = match scan_idx { + ScanIdx::Diagonal | ScanIdx::Horizontal | ScanIdx::Vertical => log2_block_size <= 3, + ScanIdx::Traverse => (2..=5).contains(&log2_block_size), + }; + if !in_range { + return Err(ScanOrderError::Log2BlockSizeOutOfRange { + scan_idx, + log2_block_size, + }); + } + let blk_size = 1usize << log2_block_size; + Ok(match scan_idx { + ScanIdx::Diagonal => up_right_diagonal(blk_size), + ScanIdx::Horizontal => horizontal(blk_size), + ScanIdx::Vertical => vertical(blk_size), + ScanIdx::Traverse => traverse(blk_size), + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The 4x4 up-right diagonal scan (§6.5.3, `blkSize == 4`) visits + /// the 16 cells in the canonical diagonal order. Hand-derived from + /// equation 6-11. + #[test] + fn diag_scan_4x4() { + let scan = up_right_diagonal(4); + let coords: Vec<(u8, u8)> = scan.iter().map(|p| (p.x, p.y)).collect(); + assert_eq!( + coords, + vec![ + (0, 0), + (0, 1), + (1, 0), + (0, 2), + (1, 1), + (2, 0), + (0, 3), + (1, 2), + (2, 1), + (3, 0), + (1, 3), + (2, 2), + (3, 1), + (2, 3), + (3, 2), + (3, 3), + ] + ); + } + + /// The 2x2 scan is the smallest non-trivial case and exercises the + /// outer-loop re-seed (`y = x, x = 0`) twice. + #[test] + fn diag_scan_2x2() { + let scan = up_right_diagonal(2); + let coords: Vec<(u8, u8)> = scan.iter().map(|p| (p.x, p.y)).collect(); + assert_eq!(coords, vec![(0, 0), (0, 1), (1, 0), (1, 1)]); + } + + /// The scan is a permutation of every `(x, y)` cell in the block: + /// each coordinate appears exactly once, and the length is + /// `blkSize * blkSize`. Checked for the 4x4 and 8x8 blocks the + /// §7.4.5 derivation reads. + #[test] + fn diag_scan_is_a_permutation() { + for &blk in &[4usize, 8] { + let scan = up_right_diagonal(blk); + assert_eq!(scan.len(), blk * blk); + let mut seen = vec![false; blk * blk]; + for p in &scan { + let (x, y) = (p.x as usize, p.y as usize); + assert!(x < blk && y < blk); + let flat = y * blk + x; + assert!(!seen[flat], "cell ({x},{y}) visited twice"); + seen[flat] = true; + } + assert!(seen.iter().all(|&v| v), "not every cell visited"); + } + } + + /// Equation 6-11 walks each diagonal from its bottom-left toward its + /// top-right: the sum `x + y` (the diagonal index) is + /// non-decreasing across the scan, and within a diagonal `y` + /// strictly decreases. Verified on the 8x8 block. + #[test] + fn diag_scan_8x8_diagonal_ordering() { + let scan = up_right_diagonal(8); + let mut prev_diag = 0usize; + let mut prev_y = i32::MAX; + for p in &scan { + let diag = p.x as usize + p.y as usize; + assert!(diag >= prev_diag, "diagonal index decreased"); + if diag != prev_diag { + prev_diag = diag; + prev_y = i32::MAX; + } + assert!( + (p.y as i32) < prev_y, + "y not strictly decreasing in diagonal" + ); + prev_y = p.y as i32; + } + } + + fn coords(scan: &[ScanPos]) -> Vec<(u8, u8)> { + scan.iter().map(|p| (p.x, p.y)).collect() + } + + /// The 4x4 horizontal scan (§6.5.4, equation 6-12) is a plain + /// raster: row 0 left-to-right, then row 1, etc. Hand-derived. + #[test] + fn hor_scan_4x4() { + assert_eq!( + coords(&horizontal(4)), + vec![ + (0, 0), + (1, 0), + (2, 0), + (3, 0), + (0, 1), + (1, 1), + (2, 1), + (3, 1), + (0, 2), + (1, 2), + (2, 2), + (3, 2), + (0, 3), + (1, 3), + (2, 3), + (3, 3), + ] + ); + } + + /// The 2x2 vertical scan (§6.5.5, equation 6-13) walks column 0 + /// top-to-bottom, then column 1. Hand-derived. + #[test] + fn ver_scan_2x2() { + assert_eq!(coords(&vertical(2)), vec![(0, 0), (0, 1), (1, 0), (1, 1)]); + } + + /// The 4x4 vertical scan (§6.5.5, equation 6-13) is the transpose + /// of the horizontal scan: column by column. Hand-derived. + #[test] + fn ver_scan_4x4() { + assert_eq!( + coords(&vertical(4)), + vec![ + (0, 0), + (0, 1), + (0, 2), + (0, 3), + (1, 0), + (1, 1), + (1, 2), + (1, 3), + (2, 0), + (2, 1), + (2, 2), + (2, 3), + (3, 0), + (3, 1), + (3, 2), + (3, 3), + ] + ); + } + + /// The 4x4 traverse scan (§6.5.6, equation 6-14) is a serpentine + /// raster: even rows (0, 2) left-to-right, odd rows (1, 3) + /// right-to-left. Hand-derived. + #[test] + fn trav_scan_4x4() { + assert_eq!( + coords(&traverse(4)), + vec![ + (0, 0), + (1, 0), + (2, 0), + (3, 0), + (3, 1), + (2, 1), + (1, 1), + (0, 1), + (0, 2), + (1, 2), + (2, 2), + (3, 2), + (3, 3), + (2, 3), + (1, 3), + (0, 3), + ] + ); + } + + /// The 2x2 traverse scan exercises a single direction flip: row 0 + /// left-to-right, row 1 right-to-left. Hand-derived. + #[test] + fn trav_scan_2x2() { + assert_eq!(coords(&traverse(2)), vec![(0, 0), (1, 0), (1, 1), (0, 1)]); + } + + /// Each new scan is a permutation of every `(x, y)` cell — every + /// coordinate appears exactly once and the length is + /// `blkSize * blkSize`. Checked across the block sizes §7.4.2 + /// populates (1, 2, 4, 8 for diag/hor/vert; 4, 8, 16, 32 for + /// traverse). + #[test] + fn scans_are_permutations() { + let check = |scan: &[ScanPos], blk: usize| { + assert_eq!(scan.len(), blk * blk); + let mut seen = vec![false; blk * blk]; + for p in scan { + let (x, y) = (p.x as usize, p.y as usize); + assert!(x < blk && y < blk); + let flat = y * blk + x; + assert!(!seen[flat], "cell ({x},{y}) visited twice"); + seen[flat] = true; + } + assert!(seen.iter().all(|&v| v), "not every cell visited"); + }; + for &blk in &[1usize, 2, 4, 8] { + check(&horizontal(blk), blk); + check(&vertical(blk), blk); + } + for &blk in &[4usize, 8, 16, 32] { + check(&traverse(blk), blk); + } + } + + /// The horizontal and vertical scans are transposes: position + /// `i` of the vertical scan is the `(y, x)`-swapped position of the + /// horizontal scan. Holds for every `(x, y)` per equations + /// 6-12 / 6-13. + #[test] + fn hor_and_ver_are_transposes() { + for &blk in &[1usize, 2, 4, 8] { + let hor = horizontal(blk); + let ver = vertical(blk); + for (h, v) in hor.iter().zip(ver.iter()) { + assert_eq!((h.x, h.y), (v.y, v.x)); + } + } + } + + /// Even rows of the traverse scan match the horizontal scan's rows + /// exactly; odd rows are the horizontal rows reversed (equation + /// 6-14). Verified on the 8x8 block. + #[test] + fn trav_scan_reverses_odd_rows() { + let blk = 8usize; + let trav = traverse(blk); + for (i, p) in trav.iter().enumerate() { + let row = i / blk; + let col_in_row = i % blk; + let expected_x = if row % 2 == 0 { + col_in_row + } else { + blk - 1 - col_in_row + }; + assert_eq!((p.x as usize, p.y as usize), (expected_x, row)); + } + } + + /// §7.4.2 `scan_order` dispatches to the right §6.5.x process and + /// agrees with the direct builders across every populated + /// `(log2BlockSize, scanIdx)` slot. + #[test] + fn scan_order_dispatch_matches_builders() { + for log2 in 0u8..=3 { + let blk = 1usize << log2; + assert_eq!( + scan_order(log2, ScanIdx::Diagonal).unwrap(), + up_right_diagonal(blk) + ); + assert_eq!( + scan_order(log2, ScanIdx::Horizontal).unwrap(), + horizontal(blk) + ); + assert_eq!(scan_order(log2, ScanIdx::Vertical).unwrap(), vertical(blk)); + } + for log2 in 2u8..=5 { + let blk = 1usize << log2; + assert_eq!(scan_order(log2, ScanIdx::Traverse).unwrap(), traverse(blk)); + } + } + + /// §7.4.2 only populates diag/hor/vert for `log2BlockSize` 0..=3 and + /// traverse for 2..=5; outside those ranges `scan_order` reports the + /// gap rather than fabricating a scan. + #[test] + fn scan_order_rejects_out_of_range() { + for &idx in &[ScanIdx::Diagonal, ScanIdx::Horizontal, ScanIdx::Vertical] { + assert!(matches!( + scan_order(4, idx), + Err(ScanOrderError::Log2BlockSizeOutOfRange { .. }) + )); + assert!(scan_order(3, idx).is_ok()); + } + assert!(matches!( + scan_order(1, ScanIdx::Traverse), + Err(ScanOrderError::Log2BlockSizeOutOfRange { .. }) + )); + assert!(scan_order(2, ScanIdx::Traverse).is_ok()); + assert!(scan_order(5, ScanIdx::Traverse).is_ok()); + assert!(matches!( + scan_order(6, ScanIdx::Traverse), + Err(ScanOrderError::Log2BlockSizeOutOfRange { .. }) + )); + } + + /// The §7.4.2 `scanIdx` numbering: 0 diagonal, 1 horizontal, + /// 2 vertical, 3 traverse. + #[test] + fn scan_idx_numbering() { + assert_eq!(ScanIdx::Diagonal.index(), 0); + assert_eq!(ScanIdx::Horizontal.index(), 1); + assert_eq!(ScanIdx::Vertical.index(), 2); + assert_eq!(ScanIdx::Traverse.index(), 3); + } +} diff --git a/vendor/oxideav-h265/src/sei.rs b/vendor/oxideav-h265/src/sei.rs new file mode 100644 index 0000000..60d7d97 --- /dev/null +++ b/vendor/oxideav-h265/src/sei.rs @@ -0,0 +1,607 @@ +//! H.265 / HEVC Supplemental Enhancement Information (SEI) parse. +//! +//! This module implements the SEI framing of ITU-T Rec. H.265 +//! (ISO/IEC 23008-2): +//! +//! * **§7.3.2.4** — `sei_rbsp()`: a `do … while( more_rbsp_data() )` +//! loop of `sei_message()` structures followed by +//! `rbsp_trailing_bits()`. +//! * **§7.3.5** — `sei_message()`: the extensible `payloadType` / +//! `payloadSize` framing where each `0xFF` byte adds 255 and the +//! first non-`0xFF` byte is the final additive term. +//! * **§D.2** — `sei_payload( payloadType, payloadSize )`: the +//! payload-type dispatch. The `nal_unit_type` (PREFIX_SEI_NUT vs +//! SUFFIX_SEI_NUT) selects which payload types are legal at a given +//! position; each message body is delimited to exactly `payloadSize` +//! bytes. +//! +//! Because §7.3.5 makes every message length-prefixed in whole bytes, +//! the framing layer is robust against a payload body it does not +//! decode: an unknown or not-yet-implemented `payloadType` is surfaced +//! as [`SeiPayload::Reserved`] carrying the verbatim `payloadSize` +//! bytes. The framing therefore always advances by `payloadSize` bytes +//! per message regardless of which payload bodies are typed. +//! +//! The byte-aligned payload trailer (§D.3.1 `more_data_in_payload()`: +//! the `payload_bit_equal_to_one` + zero-padding to a byte boundary +//! that may follow a sub-byte payload body) is the responsibility of +//! the individual payload parser when it reads a non-byte-aligned body; +//! the framing layer only needs the byte count. + +use crate::bitreader::{BitReader, BitReaderError}; + +/// The SEI NAL-unit type, which selects the §D.2 payload dispatch +/// branch. Per §7.4.2.2 (Table 7-1), `nal_unit_type == 39` is +/// `PREFIX_SEI_NUT` and `nal_unit_type == 40` is `SUFFIX_SEI_NUT`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SeiNalType { + /// `PREFIX_SEI_NUT` (`nal_unit_type == 39`). Prefix SEI precede the + /// associated coded picture in decoding order. + Prefix, + /// `SUFFIX_SEI_NUT` (`nal_unit_type == 40`). Suffix SEI follow the + /// associated coded picture in decoding order; the §D.2 dispatch + /// admits a smaller set of payload types here. + Suffix, +} + +/// `nal_unit_type` value for `PREFIX_SEI_NUT` (§7.4.2.2, Table 7-1). +pub const PREFIX_SEI_NUT: u8 = 39; +/// `nal_unit_type` value for `SUFFIX_SEI_NUT` (§7.4.2.2, Table 7-1). +pub const SUFFIX_SEI_NUT: u8 = 40; + +impl SeiNalType { + /// Map a raw `nal_unit_type` to its SEI category, or `None` if the + /// value is neither of the two SEI NAL-unit types. + pub fn from_nal_unit_type(nal_unit_type: u8) -> Option { + match nal_unit_type { + PREFIX_SEI_NUT => Some(Self::Prefix), + SUFFIX_SEI_NUT => Some(Self::Suffix), + _ => None, + } + } +} + +/// Errors that can arise while parsing an SEI RBSP. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SeiError { + /// The declared `payloadSize` extended past the end of the RBSP + /// (the message claimed more bytes than remain in the buffer). + PayloadSizeOverrun { + /// The decoded §7.3.5 `payloadSize`. + payload_size: usize, + /// The number of bytes remaining in the RBSP at the start of + /// the payload. + available: usize, + }, + /// The RBSP ended in the middle of the §7.3.5 `payloadType` / + /// `payloadSize` extensible byte run (no terminating non-`0xFF` + /// byte before end-of-buffer). + TruncatedHeader, + /// A typed payload body was shorter than its fixed §D.2 layout + /// requires (the `payloadSize` was smaller than the syntax demands). + TruncatedPayload { + /// The §D.2 `payloadType` whose body was short. + payload_type: u32, + }, + /// A bit-level read inside a typed payload body failed. + Bit(BitReaderError), +} + +impl From for SeiError { + fn from(e: BitReaderError) -> Self { + Self::Bit(e) + } +} + +impl core::fmt::Display for SeiError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::PayloadSizeOverrun { + payload_size, + available, + } => write!( + f, + "SEI payloadSize {payload_size} exceeds {available} remaining RBSP bytes" + ), + Self::TruncatedHeader => f.write_str("SEI message header truncated"), + Self::TruncatedPayload { payload_type } => { + write!(f, "SEI payload type {payload_type} body truncated") + } + Self::Bit(e) => write!(f, "SEI bit read error: {e}"), + } + } +} + +impl std::error::Error for SeiError {} + +/// The §D.2 `recovery_point` SEI message (`payloadType == 6`): a +/// recovery-point indication for random access (§D.3.8). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct RecoveryPoint { + /// `recovery_poc_cnt` (`se(v)`): the picture-order-count offset of + /// the recovery point relative to the current picture. + pub recovery_poc_cnt: i32, + /// `exact_match_flag` (`u(1)`). + pub exact_match_flag: bool, + /// `broken_link_flag` (`u(1)`). + pub broken_link_flag: bool, +} + +/// The §D.2 `active_parameter_sets` SEI message (`payloadType == 129`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ActiveParameterSets { + /// `active_video_parameter_set_id` (`u(4)`). + pub active_video_parameter_set_id: u8, + /// `self_contained_cvs_flag` (`u(1)`). + pub self_contained_cvs_flag: bool, + /// `no_parameter_set_update_flag` (`u(1)`). + pub no_parameter_set_update_flag: bool, + /// `active_seq_parameter_set_id[ i ]` for + /// `i = 0 .. num_sps_ids_minus1` (`ue(v)` each). + pub active_seq_parameter_set_ids: Vec, +} + +/// The §D.2 `content_light_level_info` SEI message +/// (`payloadType == 144`): HDR content light-level metadata. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ContentLightLevelInfo { + /// `max_content_light_level` (`u(16)`), in candelas per square + /// metre (0 ⇒ unknown). + pub max_content_light_level: u16, + /// `max_pic_average_light_level` (`u(16)`), in candelas per square + /// metre (0 ⇒ unknown). + pub max_pic_average_light_level: u16, +} + +/// The §D.2 `mastering_display_colour_volume` SEI message +/// (`payloadType == 137`): HDR mastering-display metadata (SMPTE +/// ST 2086 carriage). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct MasteringDisplayColourVolume { + /// `display_primaries_x[ c ]` for the three colour primaries in the + /// G, B, R order in which they appear on the wire (`u(16)` each). + pub display_primaries_x: [u16; 3], + /// `display_primaries_y[ c ]` (`u(16)` each). + pub display_primaries_y: [u16; 3], + /// `white_point_x` (`u(16)`). + pub white_point_x: u16, + /// `white_point_y` (`u(16)`). + pub white_point_y: u16, + /// `max_display_mastering_luminance` (`u(32)`). + pub max_display_mastering_luminance: u32, + /// `min_display_mastering_luminance` (`u(32)`). + pub min_display_mastering_luminance: u32, +} + +/// The §D.2 `alternative_transfer_characteristics` SEI message +/// (`payloadType == 147`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct AlternativeTransferCharacteristics { + /// `preferred_transfer_characteristics` (`u(8)`): a code point in + /// the same value space as the VUI `transfer_characteristics`. + pub preferred_transfer_characteristics: u8, +} + +/// The §D.2 `decoded_picture_hash` SEI message (`payloadType == 132`, +/// suffix-only): a per-component hash of the decoded picture used for +/// decoder conformance checking. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct DecodedPictureHash { + /// `hash_type` (`u(8)`): 0 ⇒ MD5, 1 ⇒ CRC, 2 ⇒ checksum. + pub hash_type: u8, + /// The per-component hash payload, one entry per colour component + /// in the order they appear on the wire. The interpretation + /// depends on `hash_type`. + pub component_hashes: Vec, +} + +/// One component's decoded-picture hash value (§D.2 `decoded_picture_hash`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum PictureHash { + /// `hash_type == 0`: the 16-byte `picture_md5[ cIdx ][ i ]` digest. + Md5([u8; 16]), + /// `hash_type == 1`: the `picture_crc[ cIdx ]` (`u(16)`). + Crc(u16), + /// `hash_type == 2`: the `picture_checksum[ cIdx ]` (`u(32)`). + Checksum(u32), +} + +/// The §D.2 `user_data_unregistered` SEI message (`payloadType == 5`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UserDataUnregistered { + /// `uuid_iso_iec_11578` (`u(128)`): the 16-byte UUID, stored in + /// wire order (most-significant byte first). + pub uuid_iso_iec_11578: [u8; 16], + /// The remaining `user_data_payload_byte` bytes + /// (`payloadSize - 16`). + pub user_data_payload: Vec, +} + +/// The §D.2 `user_data_registered_itu_t_t35` SEI message +/// (`payloadType == 4`). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct UserDataRegisteredItuTT35 { + /// `itu_t_t35_country_code` (`b(8)`). + pub country_code: u8, + /// `itu_t_t35_country_code_extension_byte` (`b(8)`), present only + /// when `country_code == 0xFF` per §D.2.6. + pub country_code_extension: Option, + /// The remaining `itu_t_t35_payload_byte` bytes. + pub payload: Vec, +} + +/// A decoded SEI payload body, or the verbatim bytes of a payload type +/// this module does not yet type. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum SeiPayload { + /// `payloadType == 4`. + UserDataRegisteredItuTT35(UserDataRegisteredItuTT35), + /// `payloadType == 5`. + UserDataUnregistered(UserDataUnregistered), + /// `payloadType == 6`. + RecoveryPoint(RecoveryPoint), + /// `payloadType == 129`. + ActiveParameterSets(ActiveParameterSets), + /// `payloadType == 132` (suffix SEI). + DecodedPictureHash(DecodedPictureHash), + /// `payloadType == 137`. + MasteringDisplayColourVolume(MasteringDisplayColourVolume), + /// `payloadType == 144`. + ContentLightLevelInfo(ContentLightLevelInfo), + /// `payloadType == 147`. + AlternativeTransferCharacteristics(AlternativeTransferCharacteristics), + /// Any payload type this module does not decode (or a §D.2 + /// `reserved_sei_message`): the verbatim `payloadSize` bytes. + Reserved { + /// The §D.2 `payloadType`. + payload_type: u32, + /// The verbatim payload bytes (`payloadSize` of them). + data: Vec, + }, +} + +/// One parsed `sei_message()` (§7.3.5). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SeiMessage { + /// The §7.3.5 `payloadType`. + pub payload_type: u32, + /// The §7.3.5 `payloadSize`, in bytes. + pub payload_size: usize, + /// The decoded (or verbatim) payload body. + pub payload: SeiPayload, +} + +/// Decode the extensible §7.3.5 `payloadType` / `payloadSize` byte run: +/// every `0xFF` byte contributes 255 and the first non-`0xFF` byte is +/// the final additive term. `cursor` is advanced past the consumed +/// bytes. Returns the accumulated value, or [`SeiError::TruncatedHeader`] +/// when the run is not terminated before end-of-buffer. +fn read_extensible_byte_run(rbsp: &[u8], cursor: &mut usize) -> Result { + let mut value: u32 = 0; + loop { + let byte = *rbsp.get(*cursor).ok_or(SeiError::TruncatedHeader)?; + *cursor += 1; + if byte == 0xFF { + value = value.saturating_add(255); + } else { + value = value.saturating_add(byte as u32); + return Ok(value); + } + } +} + +impl SeiMessage { + /// Parse one `sei_message()` (§7.3.5) starting at `cursor` within + /// `rbsp`, dispatching the payload per §D.2 against `nal_type`. + /// `cursor` is advanced to the byte immediately after this + /// message's payload (i.e. past `payloadSize` bytes). + pub fn parse(rbsp: &[u8], cursor: &mut usize, nal_type: SeiNalType) -> Result { + let payload_type = read_extensible_byte_run(rbsp, cursor)?; + let payload_size = read_extensible_byte_run(rbsp, cursor)? as usize; + + let available = rbsp.len().saturating_sub(*cursor); + if payload_size > available { + return Err(SeiError::PayloadSizeOverrun { + payload_size, + available, + }); + } + let body = &rbsp[*cursor..*cursor + payload_size]; + *cursor += payload_size; + + let payload = decode_payload(payload_type, body, nal_type)?; + Ok(Self { + payload_type, + payload_size, + payload, + }) + } +} + +/// Dispatch a single SEI payload body (already delimited to +/// `payloadSize` bytes) per §D.2. Payload types this module does not +/// type are surfaced as [`SeiPayload::Reserved`]. +fn decode_payload( + payload_type: u32, + body: &[u8], + nal_type: SeiNalType, +) -> Result { + // The §D.2 dispatch is split by nal_unit_type. The suffix branch + // admits only a subset of payload types; payload 132 + // (decoded_picture_hash) is suffix-only and 129 / 137 / 144 / 147 / + // 6 are prefix-only. Types legal in both branches (4 / 5) decode + // identically. A payload type that is not legal in the active + // branch is treated as reserved (carried verbatim). + match (nal_type, payload_type) { + (_, 4) => Ok(SeiPayload::UserDataRegisteredItuTT35( + decode_user_data_registered(body), + )), + (_, 5) => Ok(SeiPayload::UserDataUnregistered( + decode_user_data_unregistered(body)?, + )), + (SeiNalType::Prefix, 6) => Ok(SeiPayload::RecoveryPoint(decode_recovery_point(body)?)), + (SeiNalType::Prefix, 129) => Ok(SeiPayload::ActiveParameterSets( + decode_active_parameter_sets(body)?, + )), + (SeiNalType::Suffix, 132) => Ok(SeiPayload::DecodedPictureHash( + decode_decoded_picture_hash(body)?, + )), + (SeiNalType::Prefix, 137) => Ok(SeiPayload::MasteringDisplayColourVolume( + decode_mastering_display_colour_volume(body)?, + )), + (SeiNalType::Prefix, 144) => Ok(SeiPayload::ContentLightLevelInfo( + decode_content_light_level_info(body)?, + )), + (SeiNalType::Prefix, 147) => Ok(SeiPayload::AlternativeTransferCharacteristics( + decode_alternative_transfer_characteristics(body)?, + )), + _ => Ok(SeiPayload::Reserved { + payload_type, + data: body.to_vec(), + }), + } +} + +fn decode_recovery_point(body: &[u8]) -> Result { + let mut r = BitReader::new(body); + let recovery_poc_cnt = r + .se() + .map_err(|_| SeiError::TruncatedPayload { payload_type: 6 })?; + let exact_match_flag = r + .u1() + .map_err(|_| SeiError::TruncatedPayload { payload_type: 6 })? + != 0; + let broken_link_flag = r + .u1() + .map_err(|_| SeiError::TruncatedPayload { payload_type: 6 })? + != 0; + Ok(RecoveryPoint { + recovery_poc_cnt, + exact_match_flag, + broken_link_flag, + }) +} + +fn decode_active_parameter_sets(body: &[u8]) -> Result { + let mut r = BitReader::new(body); + let err = || SeiError::TruncatedPayload { payload_type: 129 }; + let active_video_parameter_set_id = r.u(4).map_err(|_| err())? as u8; + let self_contained_cvs_flag = r.u1().map_err(|_| err())? != 0; + let no_parameter_set_update_flag = r.u1().map_err(|_| err())? != 0; + let num_sps_ids_minus1 = r.ue().map_err(|_| err())?; + let count = (num_sps_ids_minus1 as usize) + .checked_add(1) + .ok_or_else(err)?; + let mut active_seq_parameter_set_ids = Vec::with_capacity(count); + for _ in 0..count { + active_seq_parameter_set_ids.push(r.ue().map_err(|_| err())?); + } + // The trailing `layer_sps_idx[ i ]` loop runs only for the + // multilayer (Annex F) extension (`MaxLayersMinus1 > 0`); for the + // single-layer base stream it is empty. Those entries, when + // present, fall into the byte-aligned payload trailer and are not + // surfaced here. + Ok(ActiveParameterSets { + active_video_parameter_set_id, + self_contained_cvs_flag, + no_parameter_set_update_flag, + active_seq_parameter_set_ids, + }) +} + +fn decode_content_light_level_info(body: &[u8]) -> Result { + if body.len() < 4 { + return Err(SeiError::TruncatedPayload { payload_type: 144 }); + } + Ok(ContentLightLevelInfo { + max_content_light_level: u16::from_be_bytes([body[0], body[1]]), + max_pic_average_light_level: u16::from_be_bytes([body[2], body[3]]), + }) +} + +fn decode_mastering_display_colour_volume( + body: &[u8], +) -> Result { + // 3 * (u16 + u16) + u16 + u16 + u32 + u32 = 24 bytes. + if body.len() < 24 { + return Err(SeiError::TruncatedPayload { payload_type: 137 }); + } + let mut display_primaries_x = [0u16; 3]; + let mut display_primaries_y = [0u16; 3]; + let mut off = 0usize; + for c in 0..3 { + display_primaries_x[c] = u16::from_be_bytes([body[off], body[off + 1]]); + display_primaries_y[c] = u16::from_be_bytes([body[off + 2], body[off + 3]]); + off += 4; + } + let white_point_x = u16::from_be_bytes([body[off], body[off + 1]]); + let white_point_y = u16::from_be_bytes([body[off + 2], body[off + 3]]); + off += 4; + let max_display_mastering_luminance = + u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + off += 4; + let min_display_mastering_luminance = + u32::from_be_bytes([body[off], body[off + 1], body[off + 2], body[off + 3]]); + Ok(MasteringDisplayColourVolume { + display_primaries_x, + display_primaries_y, + white_point_x, + white_point_y, + max_display_mastering_luminance, + min_display_mastering_luminance, + }) +} + +fn decode_alternative_transfer_characteristics( + body: &[u8], +) -> Result { + let preferred_transfer_characteristics = *body + .first() + .ok_or(SeiError::TruncatedPayload { payload_type: 147 })?; + Ok(AlternativeTransferCharacteristics { + preferred_transfer_characteristics, + }) +} + +fn decode_decoded_picture_hash(body: &[u8]) -> Result { + let err = || SeiError::TruncatedPayload { payload_type: 132 }; + let hash_type = *body.first().ok_or_else(err)?; + let mut off = 1usize; + let mut component_hashes = Vec::new(); + // The §D.2 loop bound is `chroma_format_idc == 0 ? 1 : 3`. Without + // the activated SPS in hand, the body length disambiguates: each + // component contributes a fixed number of bytes for the given + // hash_type, so the count is `remaining / per_component`. + let per_component = match hash_type { + 0 => 16, + 1 => 2, + 2 => 4, + // Unknown hash_type: surface the raw tail as a single + // checksum-sized read is not defined; treat the whole body as + // reserved by returning the parsed hash_type with no + // components (the framing already retained payload_size). + _ => { + return Ok(DecodedPictureHash { + hash_type, + component_hashes, + }) + } + }; + while off + per_component <= body.len() { + let chunk = &body[off..off + per_component]; + off += per_component; + let entry = match hash_type { + 0 => { + let mut md5 = [0u8; 16]; + md5.copy_from_slice(chunk); + PictureHash::Md5(md5) + } + 1 => PictureHash::Crc(u16::from_be_bytes([chunk[0], chunk[1]])), + 2 => { + PictureHash::Checksum(u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])) + } + _ => unreachable!(), + }; + component_hashes.push(entry); + } + Ok(DecodedPictureHash { + hash_type, + component_hashes, + }) +} + +fn decode_user_data_unregistered(body: &[u8]) -> Result { + if body.len() < 16 { + return Err(SeiError::TruncatedPayload { payload_type: 5 }); + } + let mut uuid_iso_iec_11578 = [0u8; 16]; + uuid_iso_iec_11578.copy_from_slice(&body[..16]); + Ok(UserDataUnregistered { + uuid_iso_iec_11578, + user_data_payload: body[16..].to_vec(), + }) +} + +fn decode_user_data_registered(body: &[u8]) -> UserDataRegisteredItuTT35 { + // §D.2.6: country_code is b(8); when 0xFF a second extension byte + // follows. The remainder is itu_t_t35_payload_byte. An empty body + // degenerates to a zero country code with no payload. + let Some(&country_code) = body.first() else { + return UserDataRegisteredItuTT35 { + country_code: 0, + country_code_extension: None, + payload: Vec::new(), + }; + }; + if country_code != 0xFF { + UserDataRegisteredItuTT35 { + country_code, + country_code_extension: None, + payload: body[1..].to_vec(), + } + } else { + let country_code_extension = body.get(1).copied(); + let payload_start = if country_code_extension.is_some() { + 2 + } else { + 1 + }; + UserDataRegisteredItuTT35 { + country_code, + country_code_extension, + payload: body.get(payload_start..).unwrap_or(&[]).to_vec(), + } + } +} + +/// Parse a full `sei_rbsp()` (§7.3.2.4): a sequence of `sei_message()` +/// structures up to the `rbsp_trailing_bits()`. The `rbsp` is the +/// (already emulation-prevention-stripped) NAL payload **excluding the +/// two-byte NAL header**, and `nal_type` is the SEI category derived +/// from the NAL header's `nal_unit_type`. +/// +/// Per §7.3.5 every message is byte-length-prefixed, so the trailer is +/// recognised positionally: parsing stops once the only bytes that +/// remain are the `rbsp_trailing_bits()` (a single `0x80` byte, or a +/// `0x80` followed by zero padding). A buffer of all-zero / empty tail +/// is also treated as the end of messages. +pub fn parse_sei_rbsp(rbsp: &[u8], nal_type: SeiNalType) -> Result, SeiError> { + let mut messages = Vec::new(); + let mut cursor = 0usize; + loop { + if !more_sei_messages(rbsp, cursor) { + break; + } + let msg = SeiMessage::parse(rbsp, &mut cursor, nal_type)?; + messages.push(msg); + } + Ok(messages) +} + +/// `more_rbsp_data()` for the SEI message loop (§7.3.2.4): another +/// `sei_message()` follows iff at least one bit set to 1 remains +/// before the `rbsp_trailing_bits()` `0x80` stop bit. Operating on +/// whole bytes (every message is byte-aligned), this reduces to "the +/// remaining bytes are not exactly the trailing-bits structure." +fn more_sei_messages(rbsp: &[u8], cursor: usize) -> bool { + let rest = &rbsp[cursor.min(rbsp.len())..]; + if rest.is_empty() { + return false; + } + // rbsp_trailing_bits() is `rbsp_stop_one_bit` (0x80 when + // byte-aligned) followed by zero `rbsp_alignment_zero_bit`s. If the + // first remaining byte is 0x80 and every following byte is 0x00, + // the rest is purely the trailing-bits structure: no more messages. + if rest[0] == 0x80 && rest[1..].iter().all(|&b| b == 0) { + return false; + } + // An all-zero tail (no stop bit reached, e.g. a degenerate buffer) + // carries no further sei_message() and is treated as the end. + if rest.iter().all(|&b| b == 0) { + return false; + } + true +} + +#[cfg(test)] +mod tests; diff --git a/vendor/oxideav-h265/src/sei/tests.rs b/vendor/oxideav-h265/src/sei/tests.rs new file mode 100644 index 0000000..9cf8ded --- /dev/null +++ b/vendor/oxideav-h265/src/sei/tests.rs @@ -0,0 +1,478 @@ +//! Tests for the §7.3.5 / §D.2 SEI parse. + +use super::*; + +/// Build a single-message SEI RBSP body: the §7.3.5 payloadType / +/// payloadSize framing (short form, both < 255) + `body` + an +/// `rbsp_trailing_bits()` `0x80` stop byte. +fn sei_rbsp_one(payload_type: u8, body: &[u8]) -> Vec { + let mut v = vec![payload_type, body.len() as u8]; + v.extend_from_slice(body); + v.push(0x80); + v +} + +#[test] +fn nal_type_mapping() { + assert_eq!(SeiNalType::from_nal_unit_type(39), Some(SeiNalType::Prefix)); + assert_eq!(SeiNalType::from_nal_unit_type(40), Some(SeiNalType::Suffix)); + assert_eq!(SeiNalType::from_nal_unit_type(0), None); + assert_eq!(SeiNalType::from_nal_unit_type(34), None); + assert_eq!(PREFIX_SEI_NUT, 39); + assert_eq!(SUFFIX_SEI_NUT, 40); +} + +#[test] +fn extensible_byte_run_short_form() { + let buf = [0x07]; + let mut cur = 0; + assert_eq!(read_extensible_byte_run(&buf, &mut cur).unwrap(), 7); + assert_eq!(cur, 1); +} + +#[test] +fn extensible_byte_run_ff_accumulation() { + // 0xFF + 0xFF + 0x03 == 255 + 255 + 3 == 513. + let buf = [0xFF, 0xFF, 0x03]; + let mut cur = 0; + assert_eq!(read_extensible_byte_run(&buf, &mut cur).unwrap(), 513); + assert_eq!(cur, 3); +} + +#[test] +fn extensible_byte_run_ff_then_zero() { + // 0xFF + 0x00 == 255. + let buf = [0xFF, 0x00]; + let mut cur = 0; + assert_eq!(read_extensible_byte_run(&buf, &mut cur).unwrap(), 255); + assert_eq!(cur, 2); +} + +#[test] +fn extensible_byte_run_truncated() { + // A run of only 0xFF with no terminator is truncated. + let buf = [0xFF, 0xFF]; + let mut cur = 0; + assert_eq!( + read_extensible_byte_run(&buf, &mut cur), + Err(SeiError::TruncatedHeader) + ); +} + +#[test] +fn recovery_point_decode() { + // recovery_poc_cnt = 0 (se -> ue codeNum 0 -> bit '1'), then + // exact_match_flag = 1, broken_link_flag = 0. Bits: 1 1 0 -> 0b110 + // padded = 0xC0. payloadSize = 1 byte. + let body = [0b1100_0000]; + let rbsp = sei_rbsp_one(6, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + assert_eq!(msgs.len(), 1); + assert_eq!(msgs[0].payload_type, 6); + assert_eq!(msgs[0].payload_size, 1); + match &msgs[0].payload { + SeiPayload::RecoveryPoint(rp) => { + assert_eq!(rp.recovery_poc_cnt, 0); + assert!(rp.exact_match_flag); + assert!(!rp.broken_link_flag); + } + other => panic!("expected RecoveryPoint, got {other:?}"), + } +} + +#[test] +fn recovery_point_negative_poc() { + // recovery_poc_cnt = -1: se(v) codeNum 2 -> ue '011' (3 bits), + // then exact=0, broken=1 -> '01'. Bitstring: 011 0 1 -> 0b01101000 + // = 0x68. payloadSize = 1. + let body = [0b0110_1000]; + let rbsp = sei_rbsp_one(6, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::RecoveryPoint(rp) => { + assert_eq!(rp.recovery_poc_cnt, -1); + assert!(!rp.exact_match_flag); + assert!(rp.broken_link_flag); + } + other => panic!("expected RecoveryPoint, got {other:?}"), + } +} + +#[test] +fn content_light_level_decode() { + // max_content_light_level = 0x03E8 (1000), max_pic_average = 0x00C8 (200). + let body = [0x03, 0xE8, 0x00, 0xC8]; + let rbsp = sei_rbsp_one(144, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::ContentLightLevelInfo(cll) => { + assert_eq!(cll.max_content_light_level, 1000); + assert_eq!(cll.max_pic_average_light_level, 200); + } + other => panic!("expected ContentLightLevelInfo, got {other:?}"), + } +} + +#[test] +fn content_light_level_truncated() { + let body = [0x03, 0xE8, 0x00]; // only 3 bytes + let rbsp = sei_rbsp_one(144, &body); + assert_eq!( + parse_sei_rbsp(&rbsp, SeiNalType::Prefix), + Err(SeiError::TruncatedPayload { payload_type: 144 }) + ); +} + +#[test] +fn mastering_display_decode() { + let mut body = Vec::new(); + // primaries (x,y) for c=0,1,2. + for c in 0u16..3 { + body.extend_from_slice(&(1000 + c).to_be_bytes()); // x + body.extend_from_slice(&(2000 + c).to_be_bytes()); // y + } + body.extend_from_slice(&15000u16.to_be_bytes()); // white_x + body.extend_from_slice(&16000u16.to_be_bytes()); // white_y + body.extend_from_slice(&10_000_000u32.to_be_bytes()); // max lum + body.extend_from_slice(&50u32.to_be_bytes()); // min lum + assert_eq!(body.len(), 24); + let rbsp = sei_rbsp_one(137, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::MasteringDisplayColourVolume(m) => { + assert_eq!(m.display_primaries_x, [1000, 1001, 1002]); + assert_eq!(m.display_primaries_y, [2000, 2001, 2002]); + assert_eq!(m.white_point_x, 15000); + assert_eq!(m.white_point_y, 16000); + assert_eq!(m.max_display_mastering_luminance, 10_000_000); + assert_eq!(m.min_display_mastering_luminance, 50); + } + other => panic!("expected MasteringDisplayColourVolume, got {other:?}"), + } +} + +#[test] +fn mastering_display_truncated() { + let body = vec![0u8; 23]; + let rbsp = sei_rbsp_one(137, &body); + assert_eq!( + parse_sei_rbsp(&rbsp, SeiNalType::Prefix), + Err(SeiError::TruncatedPayload { payload_type: 137 }) + ); +} + +#[test] +fn alternative_transfer_characteristics_decode() { + // preferred_transfer_characteristics = 18 (HLG). + let body = [18u8]; + let rbsp = sei_rbsp_one(147, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::AlternativeTransferCharacteristics(a) => { + assert_eq!(a.preferred_transfer_characteristics, 18); + } + other => panic!("expected AlternativeTransferCharacteristics, got {other:?}"), + } +} + +#[test] +fn active_parameter_sets_decode() { + // active_video_parameter_set_id=0 (u4), self_contained=1 (u1), + // no_update=1 (u1), num_sps_ids_minus1=0 (ue '1'), + // active_seq_parameter_set_id[0]=0 (ue '1'). + // Bits: 0000 1 1 1 1 -> 0b0000_1111 = 0x0F. + let body = [0x0F]; + let rbsp = sei_rbsp_one(129, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::ActiveParameterSets(a) => { + assert_eq!(a.active_video_parameter_set_id, 0); + assert!(a.self_contained_cvs_flag); + assert!(a.no_parameter_set_update_flag); + assert_eq!(a.active_seq_parameter_set_ids, vec![0]); + } + other => panic!("expected ActiveParameterSets, got {other:?}"), + } +} + +#[test] +fn user_data_unregistered_decode() { + let mut body = Vec::new(); + let uuid: [u8; 16] = [ + 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, + 0x00, + ]; + body.extend_from_slice(&uuid); + body.extend_from_slice(b"hello"); + let rbsp = sei_rbsp_one(5, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::UserDataUnregistered(u) => { + assert_eq!(u.uuid_iso_iec_11578, uuid); + assert_eq!(u.user_data_payload, b"hello"); + } + other => panic!("expected UserDataUnregistered, got {other:?}"), + } +} + +#[test] +fn user_data_unregistered_too_short() { + let body = vec![0u8; 15]; + let rbsp = sei_rbsp_one(5, &body); + assert_eq!( + parse_sei_rbsp(&rbsp, SeiNalType::Prefix), + Err(SeiError::TruncatedPayload { payload_type: 5 }) + ); +} + +#[test] +fn user_data_unregistered_works_in_suffix() { + // payload 5 is legal in both prefix and suffix branches. + let mut body = vec![0u8; 16]; + body.push(0x42); + let rbsp = sei_rbsp_one(5, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Suffix).unwrap(); + match &msgs[0].payload { + SeiPayload::UserDataUnregistered(u) => { + assert_eq!(u.user_data_payload, vec![0x42]); + } + other => panic!("expected UserDataUnregistered, got {other:?}"), + } +} + +#[test] +fn user_data_registered_country_code() { + // Single-byte country code != 0xFF, then payload. + let body = [0x26, 0xAA, 0xBB]; // 0x26 = US country code historically + let rbsp = sei_rbsp_one(4, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::UserDataRegisteredItuTT35(u) => { + assert_eq!(u.country_code, 0x26); + assert_eq!(u.country_code_extension, None); + assert_eq!(u.payload, vec![0xAA, 0xBB]); + } + other => panic!("expected UserDataRegisteredItuTT35, got {other:?}"), + } +} + +#[test] +fn user_data_registered_country_code_extension() { + let body = [0xFF, 0x01, 0xCC]; // 0xFF -> extension byte 0x01, payload 0xCC + let rbsp = sei_rbsp_one(4, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::UserDataRegisteredItuTT35(u) => { + assert_eq!(u.country_code, 0xFF); + assert_eq!(u.country_code_extension, Some(0x01)); + assert_eq!(u.payload, vec![0xCC]); + } + other => panic!("expected UserDataRegisteredItuTT35, got {other:?}"), + } +} + +#[test] +fn decoded_picture_hash_md5_suffix() { + // hash_type = 0 (MD5), 3 components of 16 bytes each. + let mut body = vec![0u8]; + for c in 0..3u8 { + for i in 0..16u8 { + body.push(c.wrapping_mul(16).wrapping_add(i)); + } + } + let rbsp = sei_rbsp_one(132, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Suffix).unwrap(); + match &msgs[0].payload { + SeiPayload::DecodedPictureHash(h) => { + assert_eq!(h.hash_type, 0); + assert_eq!(h.component_hashes.len(), 3); + match h.component_hashes[1] { + PictureHash::Md5(md5) => assert_eq!(md5[0], 16), + ref other => panic!("expected Md5, got {other:?}"), + } + } + other => panic!("expected DecodedPictureHash, got {other:?}"), + } +} + +#[test] +fn decoded_picture_hash_crc() { + // hash_type = 1 (CRC), 1 component (mono) of u16. + let body = [1u8, 0xAB, 0xCD]; + let rbsp = sei_rbsp_one(132, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Suffix).unwrap(); + match &msgs[0].payload { + SeiPayload::DecodedPictureHash(h) => { + assert_eq!(h.hash_type, 1); + assert_eq!(h.component_hashes, vec![PictureHash::Crc(0xABCD)]); + } + other => panic!("expected DecodedPictureHash, got {other:?}"), + } +} + +#[test] +fn decoded_picture_hash_checksum() { + // hash_type = 2 (checksum), 3 components of u32 each. + let mut body = vec![2u8]; + for c in 0..3u32 { + body.extend_from_slice(&(0x0100_0000u32 * (c + 1)).to_be_bytes()); + } + let rbsp = sei_rbsp_one(132, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Suffix).unwrap(); + match &msgs[0].payload { + SeiPayload::DecodedPictureHash(h) => { + assert_eq!(h.hash_type, 2); + assert_eq!( + h.component_hashes, + vec![ + PictureHash::Checksum(0x0100_0000), + PictureHash::Checksum(0x0200_0000), + PictureHash::Checksum(0x0300_0000), + ] + ); + } + other => panic!("expected DecodedPictureHash, got {other:?}"), + } +} + +#[test] +fn prefix_only_payload_in_suffix_is_reserved() { + // recovery_point (6) is prefix-only; in a suffix NAL it must be + // carried verbatim, not decoded. + let body = [0b1100_0000]; + let rbsp = sei_rbsp_one(6, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Suffix).unwrap(); + match &msgs[0].payload { + SeiPayload::Reserved { payload_type, data } => { + assert_eq!(*payload_type, 6); + assert_eq!(data, &body); + } + other => panic!("expected Reserved, got {other:?}"), + } +} + +#[test] +fn suffix_only_payload_in_prefix_is_reserved() { + // decoded_picture_hash (132) is suffix-only. + let body = [1u8, 0xAB, 0xCD]; + let rbsp = sei_rbsp_one(132, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + match &msgs[0].payload { + SeiPayload::Reserved { payload_type, .. } => assert_eq!(*payload_type, 132), + other => panic!("expected Reserved, got {other:?}"), + } +} + +#[test] +fn unknown_payload_type_is_reserved() { + let body = [0xDE, 0xAD, 0xBE, 0xEF]; + let rbsp = sei_rbsp_one(99, &body); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + assert_eq!(msgs[0].payload_type, 99); + match &msgs[0].payload { + SeiPayload::Reserved { payload_type, data } => { + assert_eq!(*payload_type, 99); + assert_eq!(data, &body); + } + other => panic!("expected Reserved, got {other:?}"), + } +} + +#[test] +fn multiple_messages_in_one_rbsp() { + // Two messages: CLL then alternative_transfer_characteristics, then + // the 0x80 trailer. + let mut rbsp = Vec::new(); + rbsp.push(144); + rbsp.push(4); + rbsp.extend_from_slice(&[0x03, 0xE8, 0x00, 0xC8]); + rbsp.push(147); + rbsp.push(1); + rbsp.push(16); // BT.2020-10 transfer + rbsp.push(0x80); + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + assert_eq!(msgs.len(), 2); + assert_eq!(msgs[0].payload_type, 144); + assert_eq!(msgs[1].payload_type, 147); + match &msgs[1].payload { + SeiPayload::AlternativeTransferCharacteristics(a) => { + assert_eq!(a.preferred_transfer_characteristics, 16); + } + other => panic!("expected ATC, got {other:?}"), + } +} + +#[test] +fn payload_size_overrun() { + // payloadSize claims 10 bytes but only 1 follows before the buffer + // ends. + let rbsp = [147u8, 10, 0x00]; + assert_eq!( + parse_sei_rbsp(&rbsp, SeiNalType::Prefix), + Err(SeiError::PayloadSizeOverrun { + payload_size: 10, + available: 1, + }) + ); +} + +#[test] +fn truncated_header_in_rbsp() { + // A lone 0xFF run with no terminator: more_sei_messages sees a + // non-trailer byte, parse attempts the header and finds it + // truncated. + let rbsp = [0xFFu8, 0xFF]; + assert_eq!( + parse_sei_rbsp(&rbsp, SeiNalType::Prefix), + Err(SeiError::TruncatedHeader) + ); +} + +#[test] +fn empty_rbsp_yields_no_messages() { + assert_eq!( + parse_sei_rbsp(&[], SeiNalType::Prefix).unwrap(), + Vec::::new() + ); +} + +#[test] +fn trailer_only_rbsp_yields_no_messages() { + // Just the rbsp_trailing_bits() 0x80 (plus zero padding). + assert_eq!( + parse_sei_rbsp(&[0x80], SeiNalType::Prefix).unwrap(), + Vec::::new() + ); + assert_eq!( + parse_sei_rbsp(&[0x80, 0x00, 0x00], SeiNalType::Prefix).unwrap(), + Vec::::new() + ); +} + +#[test] +fn long_payload_type_and_size_round_trip() { + // payloadType = 256 (0xFF 0x01), payloadSize = 1 (0x01), single + // byte body, then trailer. Decodes as Reserved. + let mut rbsp = vec![0xFF, 0x01, 0x01, 0x77, 0x80]; + let msgs = parse_sei_rbsp(&rbsp, SeiNalType::Prefix).unwrap(); + assert_eq!(msgs.len(), 1); + assert_eq!(msgs[0].payload_type, 256); + assert_eq!(msgs[0].payload_size, 1); + match &msgs[0].payload { + SeiPayload::Reserved { data, .. } => assert_eq!(data, &vec![0x77]), + other => panic!("expected Reserved, got {other:?}"), + } + // mutate to confirm the framing consumed exactly the declared size + rbsp.clear(); +} + +#[test] +fn error_display_strings() { + let e = SeiError::PayloadSizeOverrun { + payload_size: 5, + available: 2, + }; + assert!(format!("{e}").contains("exceeds")); + assert!(format!("{}", SeiError::TruncatedHeader).contains("truncated")); + assert!(format!("{}", SeiError::TruncatedPayload { payload_type: 6 }).contains('6')); +} diff --git a/vendor/oxideav-h265/src/sequence.rs b/vendor/oxideav-h265/src/sequence.rs new file mode 100644 index 0000000..10633df --- /dev/null +++ b/vendor/oxideav-h265/src/sequence.rs @@ -0,0 +1,1620 @@ +//! Whole-bitstream decode driver — Annex B byte stream to output +//! pictures. +//! +//! This is the §8.1 general decoding process expressed over the crate's +//! subsystems: the [`crate::nal`] Annex B demux feeds parameter-set +//! activation ([`crate::sps`] / [`crate::pps`]), each coded picture's +//! slice segments are parsed ([`crate::slice`]) and their +//! `slice_segment_data()` CABAC-decoded through the §7.3.8 syntax walk +//! ([`crate::slice_data`]), and the decoded coding tree units are handed +//! to the picture-level reconstruction + in-loop-filter driver +//! ([`crate::inter_recon::reconstruct_inter_picture`]) with the §8.3 +//! POC / RPS / reference-list cycle threaded by +//! [`crate::decode::PictureSequenceState`]. Decoded pictures are +//! returned in output order (§8.3.1 `PicOrderCntVal` order within each +//! coded video sequence). + +use std::collections::BTreeMap; + +use crate::availability::{PictureTiling, TilingParams}; +use crate::bitreader::BitReader; +use crate::cabac::{init_type, CabacEngine}; +use crate::ctx_init::SliceContexts; +use crate::decode::{PictureHeaderInfo, PictureSequenceState, SliceRefParams}; +use crate::dpb::{LongTermEntry, RefPicLists}; +use crate::inter_pred::WpListWeights; +use crate::inter_recon::{ + reconstruct_inter_picture, InterSliceContext, PlacedInterCtu, RefListAccess, SliceWpTables, +}; +use crate::nal::{NalError, NalIter, NalUnit}; +use crate::picture::Picture; +use crate::poc::NalKind; +use crate::pps::{PicParameterSet, PpsError}; +use crate::recon::{ReconError, ReconParams}; +use crate::residual::ResidualCodingError; +use crate::slice::{SliceError, SliceLongTermRefPicSource, SliceSegmentHeader, SliceType}; +use crate::slice_data::{ + decode_coding_tree_unit_in_picture, end_of_slice_segment_flag, CodingTreeUnit, + PictureParseState, SliceDataParams, +}; +use crate::sps::{ + MaterializedShortTermRefPicSet, SeqParameterSet, ShortTermRefPicSetMaterializeError, SpsError, +}; + +/// NAL unit type: video parameter set (Table 7-1). +const NAL_VPS: u8 = 32; +/// NAL unit type: sequence parameter set. +const NAL_SPS: u8 = 33; +/// NAL unit type: picture parameter set. +const NAL_PPS: u8 = 34; + +/// Errors from the whole-bitstream decode driver. +#[derive(Debug)] +pub enum SequenceError { + /// Annex B demux / NAL header error. + Nal(NalError), + /// SPS parse error. + Sps(SpsError), + /// PPS parse error. + Pps(PpsError), + /// Slice-segment-header parse error. + Slice(SliceError), + /// §7.3.8 slice-data CABAC walk error. + SliceData(ResidualCodingError), + /// Picture reconstruction error. + Recon(ReconError), + /// §7.4.8 short-term-RPS materialization error. + Rps(ShortTermRefPicSetMaterializeError), + /// A referenced parameter set was never activated. + MissingParameterSet { + /// `"sps"` or `"pps"`. + kind: &'static str, + /// The referenced parameter-set id. + id: u8, + }, + /// A structural bitstream-conformance failure. + Malformed(&'static str), + /// A conformant configuration this driver does not decode yet. + Unsupported(&'static str), +} + +impl core::fmt::Display for SequenceError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Nal(e) => write!(f, "NAL demux error: {e}"), + Self::Sps(e) => write!(f, "SPS parse error: {e}"), + Self::Pps(e) => write!(f, "PPS parse error: {e}"), + Self::Slice(e) => write!(f, "slice header parse error: {e}"), + Self::SliceData(e) => write!(f, "slice data decode error: {e}"), + Self::Recon(e) => write!(f, "picture reconstruction error: {e}"), + Self::Rps(e) => write!(f, "short-term RPS materialization error: {e:?}"), + Self::MissingParameterSet { kind, id } => { + write!(f, "referenced {kind} id {id} was never activated") + } + Self::Malformed(what) => write!(f, "malformed bitstream: {what}"), + Self::Unsupported(what) => write!(f, "unsupported configuration: {what}"), + } + } +} + +impl std::error::Error for SequenceError {} + +impl From for SequenceError { + fn from(e: NalError) -> Self { + Self::Nal(e) + } +} +impl From for SequenceError { + fn from(e: SpsError) -> Self { + Self::Sps(e) + } +} +impl From for SequenceError { + fn from(e: PpsError) -> Self { + Self::Pps(e) + } +} +impl From for SequenceError { + fn from(e: SliceError) -> Self { + Self::Slice(e) + } +} +impl From for SequenceError { + fn from(e: ResidualCodingError) -> Self { + Self::SliceData(e) + } +} +impl From for SequenceError { + fn from(e: ReconError) -> Self { + Self::Recon(e) + } +} +impl From for SequenceError { + fn from(e: ShortTermRefPicSetMaterializeError) -> Self { + Self::Rps(e) + } +} + +/// One decoded picture with its output-ordering keys. +#[derive(Debug, Clone)] +pub struct DecodedFrame { + /// Index of the coded video sequence this picture belongs to + /// (incremented at each IRAP with `NoRaslOutputFlag == 1`). + pub cvs_index: u32, + /// `PicOrderCntVal` (§8.3.1). + pub poc: i32, + /// `pic_output_flag` — `false` pictures are decoded (they may be + /// referenced) but not output. + pub output: bool, + /// The reconstructed, in-loop-filtered picture. + pub picture: Picture, +} + +/// One slice segment of the picture being assembled. +#[derive(Debug)] +struct SegmentData { + nal_type: u8, + temporal_id: u8, + layer_id: u8, + rbsp: Vec, + /// Coded (escaped) payload — the §7.4.7.1 entry-point offsets are + /// expressed in this byte space. + escaped: Vec, + header: SliceSegmentHeader, +} + +/// The whole-bitstream decoder: parameter-set activation + per-picture +/// slice-data decode + the §8.3 reference cycle. +#[derive(Debug, Default)] +pub struct SequenceDecoder { + sps: BTreeMap, + pps: BTreeMap, + state: PictureSequenceState, + frames: Vec, + pending: Vec, + cvs_index: u32, + seen_picture: bool, + /// Debug: tolerate an end_of_slice_segment_flag mismatch (decode + /// as much as possible instead of erroring). + tolerant: bool, +} + +impl SequenceDecoder { + /// A fresh decoder with no activated parameter sets. + #[must_use] + pub fn new() -> Self { + Self::default() + } + + /// Debug: keep decoding past an `end_of_slice_segment_flag` + /// mismatch. Not part of the stable API. + #[doc(hidden)] + pub fn set_tolerant(&mut self, tolerant: bool) { + self.tolerant = tolerant; + } + + /// Feed a whole Annex B byte stream, decoding every access unit. + /// + /// # Errors + /// Any demux / parse / decode error; the decoder state is + /// unspecified after an error. + pub fn push_annexb(&mut self, data: &[u8]) -> Result<(), SequenceError> { + for unit in NalIter::new(data) { + self.push_nal_unit(unit?)?; + } + Ok(()) + } + + /// Feed one demuxed NAL unit. + /// + /// # Errors + /// Any parse / decode error. + pub fn push_nal_unit(&mut self, unit: NalUnit) -> Result<(), SequenceError> { + let NalUnit { + header, + rbsp, + escaped, + } = unit; + if header.is_vcl() { + // §7.4.2.4.4: a VCL NAL with first_slice_segment_in_pic_flag + // set starts a new access unit. + let first_in_pic = rbsp.first().is_some_and(|b| b & 0x80 != 0); + if first_in_pic { + self.finish_picture()?; + } + let pps_id = peek_slice_pps_id(&rbsp, header.nal_unit_type)?; + let pps = self + .pps + .get(&pps_id) + .ok_or(SequenceError::MissingParameterSet { + kind: "pps", + id: pps_id, + })?; + let sps = self + .sps + .get(&pps.sps_id) + .ok_or(SequenceError::MissingParameterSet { + kind: "sps", + id: pps.sps_id, + })?; + let parsed = SliceSegmentHeader::parse(&rbsp, header.nal_unit_type, sps, pps)?; + self.pending.push(SegmentData { + nal_type: header.nal_unit_type, + temporal_id: header.temporal_id, + layer_id: header.nuh_layer_id, + rbsp, + escaped, + header: parsed, + }); + return Ok(()); + } + match header.nal_unit_type { + NAL_VPS => { + // The VPS carries no fields the single-layer decode + // needs; activation is a no-op. + } + NAL_SPS => { + let sps = SeqParameterSet::parse(&rbsp)?; + self.sps.insert(sps.sps_id, sps); + } + NAL_PPS => { + let pps = PicParameterSet::parse(&rbsp)?; + self.pps.insert(pps.pps_id, pps); + } + // AUD / EOS / EOB / FD / SEI: nothing to activate. + _ => {} + } + Ok(()) + } + + /// Decode any picture still being assembled (a flush point — call + /// when the input stream ends but the decoder object lives on). + /// + /// # Errors + /// Any decode error from the pending picture. + pub fn flush(&mut self) -> Result<(), SequenceError> { + self.finish_picture() + } + + /// Drain the pictures decoded so far, in decode order. The caller + /// owns output reordering (the streaming [`crate::decoder`] holds a + /// `sps_max_num_reorder_pics`-deep queue; [`Self::finish`] sorts a + /// whole sequence at once). + pub fn take_decoded(&mut self) -> Vec { + std::mem::take(&mut self.frames) + } + + /// `sps_max_num_reorder_pics` of the highest sub-layer of the most + /// recently activated SPS (`None` before any SPS). + #[must_use] + pub fn max_num_reorder_pics(&self) -> Option { + self.sps.values().next_back().map(|sps| { + let idx = + usize::from(sps.max_sub_layers_minus1).min(sps.sub_layer_ordering_info.len() - 1); + sps.sub_layer_ordering_info[idx].max_num_reorder_pics + }) + } + + /// Decode any picture still being assembled and return every + /// decoded frame in output order. + /// + /// # Errors + /// Any decode error from the final pending picture. + pub fn finish(mut self) -> Result, SequenceError> { + self.finish_picture()?; + // §C.5.2.2 output order: `PicOrderCntVal` order within each + // coded video sequence, sequences in decode order. + let mut frames = self.frames; + frames.sort_by_key(|f| (f.cvs_index, f.poc)); + Ok(frames) + } + + /// Decode the pending picture's slice segments into a picture. + fn finish_picture(&mut self) -> Result<(), SequenceError> { + if self.pending.is_empty() { + return Ok(()); + } + let segs = std::mem::take(&mut self.pending); + self.decode_picture(&segs) + } + + fn decode_picture(&mut self, segs: &[SegmentData]) -> Result<(), SequenceError> { + let indep = &segs[0]; + if indep.header.dependent_slice_segment_flag { + return Err(SequenceError::Malformed( + "first slice segment of a picture is dependent", + )); + } + let pps = self + .pps + .get(&indep.header.slice_pic_parameter_set_id) + .ok_or(SequenceError::MissingParameterSet { + kind: "pps", + id: indep.header.slice_pic_parameter_set_id, + })?; + let sps = self + .sps + .get(&pps.sps_id) + .ok_or(SequenceError::MissingParameterSet { + kind: "sps", + id: pps.sps_id, + })?; + + let geom = Geometry::derive(sps, pps)?; + + // §7.4.2.4.4 CVS bookkeeping: an IRAP with NoRaslOutputFlag + // starts a new coded video sequence (for output ordering). + let nal_kind = NalKind::new(indep.nal_type); + let no_rasl_output = + nal_kind.is_idr() || nal_kind.is_bla() || (nal_kind.is_irap() && !self.seen_picture); + if nal_kind.is_irap() && no_rasl_output && self.seen_picture { + self.cvs_index += 1; + } + self.seen_picture = true; + + // ---- §7.3.8 slice-data CABAC decode of every slice segment ---- + let pic_size_in_ctbs = (geom.pic_w_ctbs * geom.pic_h_ctbs) as usize; + let mut decoded: Vec<(u32, u32, CodingTreeUnit)> = Vec::new(); + let mut slice_addr_of: Vec> = vec![None; pic_size_in_ctbs]; + let first_slice_type = segs[0] + .header + .slice_type + .ok_or(SequenceError::Malformed("independent slice without type"))?; + let mut parse_state = PictureParseState::new(&build_slice_data_params( + &segs[0].header, + sps, + pps, + &geom, + first_slice_type, + )); + + // §7.4.7.1 — a dependent slice segment inherits the slice-level + // header values (and SliceAddrRs) from the preceding independent + // slice segment; §9.3.2.2 restores its CABAC context variables + // from the state stored at the end of the previous segment + // (TableStateIdxDs, §9.3.2.4). + let mut cur_indep: &SegmentData = indep; + let mut ds_stored: Option = None; + for seg in segs { + if seg.header.dependent_slice_segment_flag { + if ds_stored.is_none() { + return Err(SequenceError::Malformed( + "dependent slice segment without a preceding segment's context state", + )); + } + } else { + cur_indep = seg; + } + decode_slice_segment_data( + seg, + &cur_indep.header, + sps, + pps, + &geom, + &mut parse_state, + &mut decoded, + &mut slice_addr_of, + &mut ds_stored, + self.tolerant, + )?; + } + + // ---- §8.3 reference cycle + §8.4/§8.5/§8.7 reconstruction ---- + let slice_type = indep + .header + .slice_type + .ok_or(SequenceError::Malformed("independent slice without type"))?; + let header_info = self.build_header_info(indep, sps, nal_kind, no_rasl_output)?; + let slice_ref = build_slice_ref_params(&indep.header, pps, slice_type, &header_info); + + let ref_state = self.state.begin_picture(&header_info, &slice_ref); + let lists = ref_state.ref_pic_lists.clone().unwrap_or(RefPicLists { + list0: Vec::new(), + list1: None, + }); + let entries = self.state.dpb().entries(); + let col_field = ref_state.col_pic.map(|idx| &entries[idx].motion); + let col_poc = ref_state + .col_pic + .map(|idx| entries[idx].poc) + .unwrap_or_default(); + let refs = RefListAccess { + lists: &lists, + entries, + }; + + let recon_params = build_recon_params(&indep.header, sps, pps, &geom)?; + let slice_ctx = build_inter_slice_context( + &indep.header, + sps, + pps, + &geom, + &recon_params, + ref_state.poc.val, + col_poc, + ref_state.no_backward_pred, + slice_type, + ); + + // Per-slice slice_loop_filter_across_slices_enabled_flag + // (§7.4.7.1: inferred from the PPS flag when absent). + let mut across_of_slice: BTreeMap = BTreeMap::new(); + for seg in segs { + if !seg.header.dependent_slice_segment_flag { + across_of_slice.insert( + seg.header.slice_segment_address, + seg.header + .slice_loop_filter_across_slices_enabled_flag + .unwrap_or(pps.pps_loop_filter_across_slices_enabled_flag), + ); + } + } + let placed: Vec> = decoded + .iter() + .map(|(x, y, ctu)| { + let rs = (y >> geom.ctb_log2) * geom.pic_w_ctbs + (x >> geom.ctb_log2); + let slice_addr_rs = slice_addr_of[rs as usize].unwrap_or(0); + PlacedInterCtu { + x_ctb: *x, + y_ctb: *y, + slice_addr_rs, + filter_across_slices: across_of_slice + .get(&slice_addr_rs) + .copied() + .unwrap_or(pps.pps_loop_filter_across_slices_enabled_flag), + ctu, + } + }) + .collect(); + + let (picture, motion) = reconstruct_inter_picture( + geom.width as usize, + geom.height as usize, + &recon_params, + &slice_ctx, + &geom.tiles, + &placed, + &refs, + col_field, + )?; + + let output = indep.header.pic_output_flag; + let poc = ref_state.poc; + self.frames.push(DecodedFrame { + cvs_index: self.cvs_index, + poc: poc.val, + output, + picture: picture.clone(), + }); + self.state + .store_picture(poc, indep.layer_id, picture, motion); + Ok(()) + } + + /// Assemble the §8.3 [`PictureHeaderInfo`] from the independent + /// slice segment header. + fn build_header_info( + &self, + seg: &SegmentData, + sps: &SeqParameterSet, + nal_kind: NalKind, + no_rasl_output: bool, + ) -> Result { + let max_poc_lsb = 1u32 << (sps.log2_max_pic_order_cnt_lsb_minus4 + 4); + let short_term_rps = materialize_slice_rps(&seg.header, sps)?; + let mut long_term = Vec::new(); + for lt in &seg.header.long_term_ref_pics { + let poc_lsb_lt = match lt.source { + SliceLongTermRefPicSource::Sps { lt_idx_sps } => { + sps.long_term_ref_pics + .get(lt_idx_sps as usize) + .ok_or(SequenceError::Malformed( + "lt_idx_sps out of range of the SPS long-term table", + ))? + .poc_lsb + } + SliceLongTermRefPicSource::InSlice { poc_lsb_lt, .. } => poc_lsb_lt, + }; + let used = lt.used_by_curr_pic_lt(sps).ok_or(SequenceError::Malformed( + "lt_idx_sps out of range of the SPS long-term table", + ))?; + long_term.push(LongTermEntry { + poc_lsb_lt, + used_by_curr_pic_lt: used, + delta_poc_msb_present: lt.delta_poc_msb_present_flag, + delta_poc_msb_cycle_lt: lt.delta_poc_msb_cycle_lt, + }); + } + Ok(PictureHeaderInfo { + nal_kind, + temporal_id: seg.temporal_id, + layer_id: seg.layer_id, + no_rasl_output, + poc_lsb: seg.header.slice_pic_order_cnt_lsb.unwrap_or(0), + max_poc_lsb, + short_term_rps, + long_term, + }) + } +} + +/// Decode a whole Annex B byte stream to its output-order frames. +/// +/// # Errors +/// Any demux / parse / decode error. +pub fn decode_annexb_sequence(data: &[u8]) -> Result, SequenceError> { + let mut dec = SequenceDecoder::new(); + dec.push_annexb(data)?; + dec.finish() +} + +/// Debug helper: CABAC-decode the FIRST picture's slice-segment data and +/// return whatever CTUs were decoded, even when the walk diverges (the +/// `end_of_slice_segment_flag` never fires). Not part of the stable API. +#[doc(hidden)] +pub fn decode_annexb_sequence_debug( + data: &[u8], +) -> Result, SequenceError> { + // Which picture (1-based) to CABAC-decode; earlier pictures are + // fully decoded through the normal driver so the DPB and parse + // state are real. + let target: usize = std::env::var("H265_DEBUG_PIC") + .ok() + .and_then(|v| v.parse().ok()) + .unwrap_or(1); + let mut dec = SequenceDecoder::new(); + let mut segs: Vec = Vec::new(); + let mut pic_no = 0usize; + for unit in NalIter::new(data) { + let unit = unit?; + if unit.header.is_vcl() { + let first = unit.rbsp.first().is_some_and(|b| b & 0x80 != 0); + if first { + pic_no += 1; + if pic_no > target && !segs.is_empty() { + break; + } + } + if pic_no < target { + dec.push_nal_unit(unit)?; + continue; + } + let pps_id = peek_slice_pps_id(&unit.rbsp, unit.header.nal_unit_type)?; + let pps = dec.pps.get(&pps_id).unwrap(); + let sps = dec.sps.get(&pps.sps_id).unwrap(); + let parsed = + SliceSegmentHeader::parse(&unit.rbsp, unit.header.nal_unit_type, sps, pps)?; + segs.push(SegmentData { + nal_type: unit.header.nal_unit_type, + temporal_id: unit.header.temporal_id, + layer_id: unit.header.nuh_layer_id, + rbsp: unit.rbsp, + escaped: unit.escaped, + header: parsed, + }); + } else { + dec.push_nal_unit(unit)?; + } + } + let seg = &segs[0]; + let pps = dec.pps.get(&seg.header.slice_pic_parameter_set_id).unwrap(); + let sps = dec.sps.get(&pps.sps_id).unwrap(); + let geom = Geometry::derive(sps, pps)?; + let pic_size = (geom.pic_w_ctbs * geom.pic_h_ctbs) as usize; + let mut decoded = Vec::new(); + let mut slice_addr_of = vec![None; pic_size]; + let st = seg.header.slice_type.unwrap(); + let mut parse_state = + PictureParseState::new(&build_slice_data_params(&seg.header, sps, pps, &geom, st)); + let mut ds_stored = None; + let res = decode_slice_segment_data( + seg, + &seg.header, + sps, + pps, + &geom, + &mut parse_state, + &mut decoded, + &mut slice_addr_of, + &mut ds_stored, + false, + ); + if let Err(e) = res { + eprintln!("(walk error: {e})"); + } + Ok(decoded) +} + +/// Debug helper: reconstruct the FIRST picture even when the CABAC walk +/// diverges, returning the in-loop-filtered picture. Not stable API. +#[doc(hidden)] +pub fn decode_annexb_first_picture_tolerant(data: &[u8]) -> Result { + let mut dec = SequenceDecoder::new(); + let mut segs: Vec = Vec::new(); + for unit in NalIter::new(data) { + let unit = unit?; + if unit.header.is_vcl() { + let first = unit.rbsp.first().is_some_and(|b| b & 0x80 != 0); + if first && !segs.is_empty() { + break; + } + let pps_id = peek_slice_pps_id(&unit.rbsp, unit.header.nal_unit_type)?; + let pps = dec.pps.get(&pps_id).unwrap(); + let sps = dec.sps.get(&pps.sps_id).unwrap(); + let parsed = + SliceSegmentHeader::parse(&unit.rbsp, unit.header.nal_unit_type, sps, pps)?; + segs.push(SegmentData { + nal_type: unit.header.nal_unit_type, + temporal_id: unit.header.temporal_id, + layer_id: unit.header.nuh_layer_id, + rbsp: unit.rbsp, + escaped: unit.escaped, + header: parsed, + }); + } else { + dec.push_nal_unit(unit)?; + } + } + let seg = &segs[0]; + let pps = dec + .pps + .get(&seg.header.slice_pic_parameter_set_id) + .unwrap() + .clone(); + let sps = dec.sps.get(&pps.sps_id).unwrap().clone(); + let geom = Geometry::derive(&sps, &pps)?; + let pic_size = (geom.pic_w_ctbs * geom.pic_h_ctbs) as usize; + let mut decoded = Vec::new(); + let mut slice_addr_of = vec![None; pic_size]; + let st0 = seg.header.slice_type.unwrap(); + let mut parse_state = PictureParseState::new(&build_slice_data_params( + &seg.header, + &sps, + &pps, + &geom, + st0, + )); + let mut ds_stored = None; + if let Err(e) = decode_slice_segment_data( + seg, + &seg.header, + &sps, + &pps, + &geom, + &mut parse_state, + &mut decoded, + &mut slice_addr_of, + &mut ds_stored, + true, + ) { + eprintln!("(walk error: {e})"); + } + let slice_type = seg.header.slice_type.unwrap(); + let recon_params = build_recon_params(&seg.header, &sps, &pps, &geom)?; + let slice_ctx = build_inter_slice_context( + &seg.header, + &sps, + &pps, + &geom, + &recon_params, + 0, + 0, + true, + slice_type, + ); + let placed: Vec> = decoded + .iter() + .map(|(x, y, ctu)| PlacedInterCtu { + x_ctb: *x, + y_ctb: *y, + slice_addr_rs: 0, + filter_across_slices: true, + ctu, + }) + .collect(); + let lists = RefPicLists { + list0: Vec::new(), + list1: None, + }; + let refs = RefListAccess { + lists: &lists, + entries: &[], + }; + let (picture, _) = reconstruct_inter_picture( + geom.width as usize, + geom.height as usize, + &recon_params, + &slice_ctx, + &geom.tiles, + &placed, + &refs, + None, + )?; + Ok(picture) +} + +/// The per-SPS geometry constants (§7.4.3.2.1 derived variables). +struct Geometry { + width: u32, + height: u32, + ctb_log2: u32, + min_cb_log2: u32, + min_tb_log2: u32, + max_tb_log2: u32, + chroma_array_type: u8, + pic_w_ctbs: u32, + pic_h_ctbs: u32, + tiles: TilingParams, +} + +impl Geometry { + fn derive(sps: &SeqParameterSet, pps: &PicParameterSet) -> Result { + let min_cb_log2 = u32::from(sps.log2_min_luma_coding_block_size_minus3) + 3; + let ctb_log2 = min_cb_log2 + u32::from(sps.log2_diff_max_min_luma_coding_block_size); + let min_tb_log2 = u32::from(sps.log2_min_luma_transform_block_size_minus2) + 2; + let max_tb_log2 = min_tb_log2 + u32::from(sps.log2_diff_max_min_luma_transform_block_size); + let width = sps.pic_width_in_luma_samples; + let height = sps.pic_height_in_luma_samples; + if width == 0 || height == 0 { + return Err(SequenceError::Malformed("zero picture dimensions")); + } + let ctb = 1u32 << ctb_log2; + let chroma_array_type = if sps.separate_colour_plane_flag { + 0 + } else { + sps.chroma_format_idc + }; + let tiles = if pps.tiles_enabled_flag { + TilingParams { + num_tile_columns_minus1: pps.tiles.num_tile_columns_minus1, + num_tile_rows_minus1: pps.tiles.num_tile_rows_minus1, + uniform_spacing_flag: pps.tiles.uniform_spacing_flag, + column_width_minus1: pps.tiles.column_width_minus1.clone(), + row_height_minus1: pps.tiles.row_height_minus1.clone(), + } + } else { + TilingParams::single_tile() + }; + Ok(Self { + width, + height, + ctb_log2, + min_cb_log2, + min_tb_log2, + max_tb_log2, + chroma_array_type, + pic_w_ctbs: width.div_ceil(ctb), + pic_h_ctbs: height.div_ceil(ctb), + tiles, + }) + } + + fn tiling(&self) -> Result { + PictureTiling::new( + self.pic_w_ctbs, + self.pic_h_ctbs, + self.width, + self.height, + self.ctb_log2, + self.min_tb_log2, + &self.tiles, + ) + .map_err(|_| SequenceError::Malformed("invalid tile geometry")) + } +} + +/// Pre-read `slice_pic_parameter_set_id` from a slice-segment RBSP (the +/// two leading fields before it are fixed-width). +fn peek_slice_pps_id(rbsp: &[u8], nal_unit_type: u8) -> Result { + let mut br = BitReader::new(rbsp); + let _first = br.u1().map_err(|_| { + SequenceError::Malformed("slice header truncated before first_slice_segment_in_pic_flag") + })?; + if (NalKind::BLA_W_LP..=NalKind::RSV_IRAP_VCL23).contains(&nal_unit_type) { + let _ = br.u1().map_err(|_| { + SequenceError::Malformed("slice header truncated at no_output_of_prior_pics_flag") + })?; + } + let pps_id = br.ue().map_err(|_| { + SequenceError::Malformed("slice header truncated at slice_pic_parameter_set_id") + })?; + if pps_id > 63 { + return Err(SequenceError::Malformed( + "slice_pic_parameter_set_id out of range", + )); + } + Ok(pps_id as u8) +} + +/// §7.4.8 — materialize the slice's short-term RPS (SPS-indexed or +/// slice-inline, explicit or inter-RPS-predicted). +fn materialize_slice_rps( + header: &SliceSegmentHeader, + sps: &SeqParameterSet, +) -> Result { + // IDR: no RPS block — empty set. + let Some(sps_flag) = header.short_term_ref_pic_set_sps_flag else { + return Ok(MaterializedShortTermRefPicSet { + delta_poc_s0: Vec::new(), + used_by_curr_pic_s0: Vec::new(), + delta_poc_s1: Vec::new(), + used_by_curr_pic_s1: Vec::new(), + }); + }; + // Materialize the SPS chain (set i may inter-predict from an + // earlier set). + let mut chain: Vec = + Vec::with_capacity(sps.short_term_ref_pic_sets.len()); + for (idx, set) in sps.short_term_ref_pic_sets.iter().enumerate() { + let source = if set.inter_ref_pic_set_prediction_flag { + let ref_idx = idx + .checked_sub(set.delta_idx_minus1 as usize + 1) + .ok_or(SequenceError::Malformed("RefRpsIdx underflow"))?; + Some(&chain[ref_idx]) + } else { + None + }; + chain.push(set.materialize(source)?); + } + if sps_flag { + let idx = header.short_term_ref_pic_set_idx.unwrap_or(0) as usize; + chain + .into_iter() + .nth(idx) + .ok_or(SequenceError::Malformed("short_term_ref_pic_set_idx OOR")) + } else { + let set = header + .inline_short_term_ref_pic_set + .as_ref() + .ok_or(SequenceError::Malformed("missing inline st_ref_pic_set"))?; + let source = if set.inter_ref_pic_set_prediction_flag { + // stRpsIdx == num_short_term_ref_pic_sets for the inline set. + let ref_idx = chain + .len() + .checked_sub(set.delta_idx_minus1 as usize + 1) + .ok_or(SequenceError::Malformed("RefRpsIdx underflow"))?; + Some(&chain[ref_idx]) + } else { + None + }; + Ok(set.materialize(source)?) + } +} + +/// `NumPicTotalCurr` (§7.4.7.2) from the already-resolved picture +/// header info (single-layer; `pps_curr_pic_ref_enabled_flag` +/// contributes the closing `NumPicTotalCurr++`). +fn num_pic_total_curr(info: &PictureHeaderInfo, curr_pic_ref_enabled: bool) -> u32 { + let st = info + .short_term_rps + .used_by_curr_pic_s0 + .iter() + .chain(info.short_term_rps.used_by_curr_pic_s1.iter()) + .filter(|&&u| u) + .count(); + let lt = info + .long_term + .iter() + .filter(|e| e.used_by_curr_pic_lt) + .count(); + (st + lt) as u32 + u32::from(curr_pic_ref_enabled) +} + +fn build_slice_ref_params( + header: &SliceSegmentHeader, + pps: &PicParameterSet, + slice_type: SliceType, + info: &PictureHeaderInfo, +) -> SliceRefParams { + let is_b = slice_type == SliceType::B; + let is_inter = slice_type != SliceType::I; + let curr_pic_ref_enabled = pps + .pps_scc_extension + .as_ref() + .is_some_and(|s| s.pps_curr_pic_ref_enabled_flag); + SliceRefParams { + is_inter, + is_b, + num_ref_idx_l0_active_minus1: u32::from( + header + .num_ref_idx_l0_active_minus1 + .unwrap_or(pps.num_ref_idx_l0_default_active_minus1), + ), + num_ref_idx_l1_active_minus1: u32::from( + header + .num_ref_idx_l1_active_minus1 + .unwrap_or(pps.num_ref_idx_l1_default_active_minus1), + ), + num_pic_total_curr: num_pic_total_curr(info, curr_pic_ref_enabled), + temporal_mvp_enabled: header.slice_temporal_mvp_enabled_flag, + collocated_from_l0_flag: header.collocated_from_l0_flag.unwrap_or(true), + collocated_ref_idx: header.collocated_ref_idx.unwrap_or(0), + curr_pic_ref_enabled, + } +} + +fn build_recon_params( + header: &SliceSegmentHeader, + sps: &SeqParameterSet, + pps: &PicParameterSet, + geom: &Geometry, +) -> Result { + let slice_qp_y = header + .slice_qp_y(pps) + .ok_or(SequenceError::Malformed("slice header without slice_qp"))?; + let range = sps.sps_range_extension.as_ref(); + // §7.4.5: when scaling_list_enabled_flag == 1 the active + // scaling-list data is the PPS body if present, else the SPS body + // if present, else the default lists. + let scaling = if sps.scaling_list_enabled_flag { + let factors = match (&pps.scaling_list_data, &sps.scaling_list_data) { + (Some(d), _) => d.scaling_factors(geom.chroma_array_type), + (None, Some(d)) => d.scaling_factors(geom.chroma_array_type), + (None, None) => crate::scaling_list::ScalingListData::all_default() + .scaling_factors(geom.chroma_array_type), + }; + Some(factors) + } else { + None + }; + Ok(ReconParams { + chroma_array_type: geom.chroma_array_type, + bit_depth_luma: sps.bit_depth_luma_minus8 + 8, + bit_depth_chroma: sps.bit_depth_chroma_minus8 + 8, + intra_smoothing_disabled: range.is_some_and(|r| r.intra_smoothing_disabled_flag), + strong_intra_smoothing_enabled: sps.strong_intra_smoothing_enabled_flag, + slice_qp_y, + cb_qp_offset: i32::from(pps.pps_cb_qp_offset) + i32::from(header.slice_cb_qp_offset), + cr_qp_offset: i32::from(pps.pps_cr_qp_offset) + i32::from(header.slice_cr_qp_offset), + // §7.4.3.3.3: PpsActQpOffset{Y,Cb,Cr} = pps_act_{y,cb}_qp_offset_plus5 − 5 + // / pps_act_cr_qp_offset_plus3 − 3; the slice offsets add on top + // (§7.4.7.1), each 0 when absent. + act_y_qp_offset: pps + .pps_scc_extension + .as_ref() + .map_or(-5, |s| s.pps_act_y_qp_offset_plus5 - 5) + + header.slice_act_y_qp_offset, + act_cb_qp_offset: pps + .pps_scc_extension + .as_ref() + .map_or(-5, |s| s.pps_act_cb_qp_offset_plus5 - 5) + + header.slice_act_cb_qp_offset, + act_cr_qp_offset: pps + .pps_scc_extension + .as_ref() + .map_or(-3, |s| s.pps_act_cr_qp_offset_plus3 - 3) + + header.slice_act_cr_qp_offset, + transform_skip_rotation_enabled: range + .is_some_and(|r| r.transform_skip_rotation_enabled_flag), + implicit_rdpcm_enabled: range.is_some_and(|r| r.implicit_rdpcm_enabled_flag), + intra_boundary_filtering_disabled: sps + .sps_scc_extension + .as_ref() + .is_some_and(|s| s.intra_boundary_filtering_disabled_flag), + extended_precision: range.is_some_and(|r| r.extended_precision_processing_flag), + scaling, + chroma_qp_offset_list: pps + .pps_range_extension + .as_ref() + .map(|r| { + r.chroma_qp_offset_list + .iter() + .map(|e| (i32::from(e.cb_qp_offset), i32::from(e.cr_qp_offset))) + .collect() + }) + .unwrap_or_default(), + cu_qp_offset_c: core::cell::Cell::new((0, 0)), + }) +} + +#[allow(clippy::too_many_arguments)] +fn build_inter_slice_context( + header: &SliceSegmentHeader, + sps: &SeqParameterSet, + pps: &PicParameterSet, + geom: &Geometry, + recon: &ReconParams, + curr_poc: i32, + col_poc: i32, + no_backward_pred: bool, + slice_type: SliceType, +) -> InterSliceContext { + let pps_range = pps.pps_range_extension.as_ref(); + let deblock = header.deblocking.as_ref(); + // §8.5.3.3.4.1 — weightedPredFlag: weighted_pred_flag for P slices, + // weighted_bipred_flag for B slices. + let weighted_pred_flag = match slice_type { + SliceType::P => pps.weighted_pred_flag, + SliceType::B => pps.weighted_bipred_flag, + SliceType::I => false, + }; + let wp = if weighted_pred_flag { + header + .pred_weight_table + .as_ref() + .map(|pwt| build_slice_wp_tables(pwt, sps)) + } else { + None + }; + InterSliceContext { + curr_poc, + constrained_intra_pred: pps.constrained_intra_pred_flag, + slice_is_b: slice_type == SliceType::B, + ctb_log2_size_y: geom.ctb_log2, + pic_width_luma: geom.width, + pic_height_luma: geom.height, + max_num_merge_cand: usize::from(header.max_num_merge_cand().unwrap_or(5)), + num_ref_idx_l0_active: i32::from( + header + .num_ref_idx_l0_active_minus1 + .unwrap_or(pps.num_ref_idx_l0_default_active_minus1), + ) + 1, + num_ref_idx_l1_active: i32::from( + header + .num_ref_idx_l1_active_minus1 + .unwrap_or(pps.num_ref_idx_l1_default_active_minus1), + ) + 1, + log2_par_mrg_level: pps.log2_parallel_merge_level_minus2 + 2, + temporal_mvp_enabled: header.slice_temporal_mvp_enabled_flag, + collocated_from_l0_flag: header.collocated_from_l0_flag.unwrap_or(true), + col_poc, + no_backward_pred, + min_tb_log2_size_y: geom.min_tb_log2, + log2_min_cu_qp_delta_size: geom.ctb_log2 - pps.diff_cu_qp_delta_depth, + wpp_qp_row_reset: pps.entropy_coding_sync_enabled_flag, + filter_across_slices: header + .slice_loop_filter_across_slices_enabled_flag + .unwrap_or(pps.pps_loop_filter_across_slices_enabled_flag), + filter_across_tiles: pps.loop_filter_across_tiles_enabled_flag, + deblock_enabled: deblock.map_or(true, |d| !d.disabled_flag), + beta_offset_div2: deblock.map_or(0, |d| i32::from(d.beta_offset_div2)), + tc_offset_div2: deblock.map_or(0, |d| i32::from(d.tc_offset_div2)), + slice_qp_y: recon.slice_qp_y, + cb_qp_offset: recon.cb_qp_offset, + cr_qp_offset: recon.cr_qp_offset, + pps_cb_qp_offset: i32::from(pps.pps_cb_qp_offset), + pps_cr_qp_offset: i32::from(pps.pps_cr_qp_offset), + slice_sao_luma_flag: header.slice_sao_luma_flag, + slice_sao_chroma_flag: header.slice_sao_chroma_flag, + log2_sao_offset_scale_luma: pps_range.map_or(0, |r| r.log2_sao_offset_scale_luma as u8), + log2_sao_offset_scale_chroma: pps_range.map_or(0, |r| r.log2_sao_offset_scale_chroma as u8), + wp, + pcm_loop_filter_disabled: sps + .pcm + .as_ref() + .is_some_and(|p| p.loop_filter_disabled_flag), + use_integer_mv: header.use_integer_mv_flag, + // §7.4.3.3.3 eq. 7-40: TwoVersionsOfCurrDecPicFlag = + // pps_curr_pic_ref_enabled_flag && ( sao enabled || + // !pps_deblocking_filter_disabled_flag || + // deblocking_filter_override_enabled_flag ). + two_versions_curr_pic: pps + .pps_scc_extension + .as_ref() + .is_some_and(|s| s.pps_curr_pic_ref_enabled_flag) + && (sps.sample_adaptive_offset_enabled_flag + || !pps.deblocking.disabled_flag + || pps.deblocking.override_enabled_flag), + } +} + +/// §7.4.7.3 — resolve a parsed `pred_weight_table()` into the +/// per-reference values the §8.5.3.3.4.3 combine reads: `LumaWeightLX[i]` +/// / `ChromaWeightLX[i][j]` (weight-flag inference included), the +/// `WpOffsetBdShiftY`- / `WpOffsetBdShiftC`-scaled offsets (equations +/// 7-31 / 7-32 + 8-268 / 8-269 / 8-273 / 8-274), and the equation-7-58 +/// `ChromaOffsetLX` derivation. +fn build_slice_wp_tables( + pwt: &crate::slice::PredWeightTable, + sps: &SeqParameterSet, +) -> SliceWpTables { + let hp = sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.high_precision_offsets_enabled_flag); + let bd_y = i32::from(sps.bit_depth_luma_minus8) + 8; + let bd_c = i32::from(sps.bit_depth_chroma_minus8) + 8; + // Equations 7-31 / 7-32 / 7-34. + let bd_shift_y = if hp { 0 } else { bd_y - 8 }; + let bd_shift_c = if hp { 0 } else { bd_c - 8 }; + let half_range_c = 1i32 << (if hp { bd_c - 1 } else { 7 }); + let chroma_denom = pwt.chroma_log2_weight_denom(); + + let resolve = |l0: bool, n: usize| -> Vec { + (0..n) + .map(|i| { + let (lw, lo, cw0, cw1, co0, co1) = if l0 { + ( + pwt.luma_weight_l0(i), + pwt.entries_l0.get(i).map(|e| e.luma_offset), + pwt.chroma_weight_l0(i, 0), + pwt.chroma_weight_l0(i, 1), + pwt.chroma_offset_l0(i, 0, half_range_c), + pwt.chroma_offset_l0(i, 1, half_range_c), + ) + } else { + ( + pwt.luma_weight_l1(i), + pwt.entries_l1.get(i).map(|e| e.luma_offset), + pwt.chroma_weight_l1(i, 0), + pwt.chroma_weight_l1(i, 1), + pwt.chroma_offset_l1(i, 0, half_range_c), + pwt.chroma_offset_l1(i, 1, half_range_c), + ) + }; + WpListWeights { + w_luma: lw.unwrap_or(1 << pwt.luma_log2_weight_denom), + o_luma: lo.unwrap_or(0) << bd_shift_y, + w_cb: cw0.unwrap_or(1 << chroma_denom), + o_cb: co0.unwrap_or(0) << bd_shift_c, + w_cr: cw1.unwrap_or(1 << chroma_denom), + o_cr: co1.unwrap_or(0) << bd_shift_c, + } + }) + .collect() + }; + + SliceWpTables { + luma_log2_weight_denom: pwt.luma_log2_weight_denom, + chroma_log2_weight_denom: chroma_denom, + l0: resolve(true, pwt.entries_l0.len()), + l1: resolve(false, pwt.entries_l1.len()), + } +} + +/// §7.4.3 — derive the [`SliceDataParams`] for one slice segment. +fn build_slice_data_params( + header: &SliceSegmentHeader, + sps: &SeqParameterSet, + pps: &PicParameterSet, + geom: &Geometry, + slice_type: SliceType, +) -> SliceDataParams { + let pps_range = pps.pps_range_extension.as_ref(); + let (log2_min_ipcm, log2_max_ipcm) = sps.pcm.as_ref().map_or((3, 5), |p| { + let min = u32::from(p.log2_min_pcm_luma_coding_block_size_minus3) + 3; + ( + min, + min + u32::from(p.log2_diff_max_min_pcm_luma_coding_block_size), + ) + }); + let cu_chroma_qp_offset_enabled = header.cu_chroma_qp_offset_enabled_flag; + let log2_min_cu_chroma_qp_offset_size = + geom.ctb_log2 - pps_range.map_or(0, |r| r.diff_cu_chroma_qp_offset_depth); + let scc = sps.sps_scc_extension.as_ref(); + let palette_max_size = scc.map_or(0, |e| e.palette_max_size); + SliceDataParams { + ctb_log2_size_y: geom.ctb_log2, + min_cb_log2_size_y: geom.min_cb_log2, + max_tb_log2_size_y: geom.max_tb_log2, + min_tb_log2_size_y: geom.min_tb_log2, + pic_width_in_luma_samples: geom.width, + pic_height_in_luma_samples: geom.height, + chroma_array_type: geom.chroma_array_type, + bit_depth_luma: u32::from(sps.bit_depth_luma_minus8) + 8, + bit_depth_chroma: u32::from(sps.bit_depth_chroma_minus8) + 8, + slice_type_is_i: slice_type == SliceType::I, + slice_type_is_b: slice_type == SliceType::B, + slice_sao_luma_flag: header.slice_sao_luma_flag, + slice_sao_chroma_flag: header.slice_sao_chroma_flag, + transquant_bypass_enabled_flag: pps.transquant_bypass_enabled_flag, + cu_qp_delta_enabled_flag: pps.cu_qp_delta_enabled_flag, + log2_min_cu_qp_delta_size: geom.ctb_log2 - pps.diff_cu_qp_delta_depth, + cu_chroma_qp_offset_enabled_flag: cu_chroma_qp_offset_enabled, + log2_min_cu_chroma_qp_offset_size, + chroma_qp_offset_list_len_minus1: pps_range + .map_or(0, |r| r.chroma_qp_offset_list_len_minus1), + amp_enabled_flag: sps.amp_enabled_flag, + pcm_enabled_flag: sps.pcm_enabled_flag, + log2_min_ipcm_cb_size_y: log2_min_ipcm, + log2_max_ipcm_cb_size_y: log2_max_ipcm, + pcm_bit_depth_luma: sps + .pcm + .as_ref() + .map_or(8, |p| u32::from(p.bit_depth_luma_minus1) + 1), + pcm_bit_depth_chroma: sps + .pcm + .as_ref() + .map_or(8, |p| u32::from(p.bit_depth_chroma_minus1) + 1), + max_transform_hierarchy_depth_intra: u32::from(sps.max_transform_hierarchy_depth_intra), + max_transform_hierarchy_depth_inter: u32::from(sps.max_transform_hierarchy_depth_inter), + max_num_merge_cand: u32::from(header.max_num_merge_cand().unwrap_or(5)), + num_ref_idx_l0_active_minus1: u32::from( + header + .num_ref_idx_l0_active_minus1 + .unwrap_or(pps.num_ref_idx_l0_default_active_minus1), + ), + num_ref_idx_l1_active_minus1: u32::from( + header + .num_ref_idx_l1_active_minus1 + .unwrap_or(pps.num_ref_idx_l1_default_active_minus1), + ), + mvd_l1_zero_flag: header.mvd_l1_zero_flag.unwrap_or(false), + sign_data_hiding_enabled_flag: pps.sign_data_hiding_enabled_flag, + cross_component_prediction_enabled_flag: pps_range + .is_some_and(|r| r.cross_component_prediction_enabled_flag), + residual_adaptive_colour_transform_enabled_flag: pps + .pps_scc_extension + .as_ref() + .is_some_and(|s| s.residual_adaptive_colour_transform_enabled_flag), + transform_skip_enabled_flag: pps.transform_skip_enabled_flag, + log2_max_transform_skip_size: pps_range + .map_or(2, |r| r.log2_max_transform_skip_block_size_minus2 + 2), + implicit_rdpcm_enabled_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.implicit_rdpcm_enabled_flag), + explicit_rdpcm_enabled_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.explicit_rdpcm_enabled_flag), + transform_skip_context_enabled_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.transform_skip_context_enabled_flag), + persistent_rice_adaptation_enabled_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.persistent_rice_adaptation_enabled_flag), + cabac_bypass_alignment_enabled_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.cabac_bypass_alignment_enabled_flag), + extended_precision_processing_flag: sps + .sps_range_extension + .as_ref() + .is_some_and(|r| r.extended_precision_processing_flag), + palette_mode_enabled_flag: scc.is_some_and(|e| e.palette_mode_enabled_flag), + palette_max_size, + palette_max_predictor_size: palette_max_size + + scc.map_or(0, |e| e.delta_palette_max_predictor_size), + } +} + +/// §7.3.8.1 — CABAC-decode one slice segment's `slice_segment_data()`, +/// appending its CTUs (in tile-scan order) to `decoded` and recording +/// each CTB's `SliceAddrRs` in `slice_addr_of`. +/// +/// `effective_header` supplies the slice-level values — for an +/// independent segment it is `seg.header` itself; for a dependent +/// segment it is the preceding independent segment's header (§7.4.7.1 +/// inheritance). `ds_stored` is the picture's §9.3.2.4 +/// `TableStateIdxDs` context store: read (synchronized, §9.3.2.5 / +/// §9.3.2.2) at a dependent segment's start, written at every +/// segment's `end_of_slice_segment_flag == 1` while +/// `dependent_slice_segments_enabled_flag` is set. +#[allow(clippy::too_many_arguments)] +fn decode_slice_segment_data( + seg: &SegmentData, + effective_header: &SliceSegmentHeader, + sps: &SeqParameterSet, + pps: &PicParameterSet, + geom: &Geometry, + state: &mut PictureParseState, + decoded: &mut Vec<(u32, u32, CodingTreeUnit)>, + slice_addr_of: &mut [Option], + ds_stored: &mut Option, + tolerant: bool, +) -> Result<(), SequenceError> { + let header = effective_header; + let slice_type = header + .slice_type + .ok_or(SequenceError::Malformed("independent slice without type"))?; + let params = build_slice_data_params(header, sps, pps, geom, slice_type); + let slice_qp_y = header + .slice_qp_y(pps) + .ok_or(SequenceError::Malformed("slice header without slice_qp"))?; + + let data_offset = seg + .header + .byte_offset_to_slice_data + .ok_or(SequenceError::Malformed("slice header without data offset"))?; + if data_offset >= seg.rbsp.len() { + return Err(SequenceError::Malformed("slice data offset out of range")); + } + + // §7.4.7.1 — split `slice_segment_data( )` into its subsets. The + // entry-point offsets count CODED bytes (emulation-prevention bytes + // included), so map each escaped boundary onto the stripped RBSP. + // (Entry points are per-segment syntax: read them from the + // segment's own header even when it is dependent.) + let substreams = split_substreams( + &seg.escaped, + seg.rbsp.len(), + data_offset, + seg.header.entry_point_offsets.as_ref(), + )?; + + // Table 9-4 initType: I => 0; P => cabac_init ? 2 : 1; + // B => cabac_init ? 1 : 2 (crate::cabac::init_type on the raw + // slice_type value). + let raw_slice_type = match slice_type { + SliceType::B => 0, + SliceType::P => 1, + SliceType::I => 2, + }; + let it = init_type(raw_slice_type, header.cabac_init_flag.unwrap_or(false)); + + let tiling = geom.tiling()?; + let tiles_on = pps.tiles_enabled_flag; + let wpp = pps.entropy_coding_sync_enabled_flag; + // §7.4.7.1: SliceAddrRs is the INDEPENDENT segment's address; a + // dependent segment starts decoding at its own segment address but + // its CTBs belong to the inherited slice. + let slice_addr_rs = header.slice_segment_address; + let mut ctb_addr_ts = tiling.ctb_addr_rs_to_ts(seg.header.slice_segment_address); + let pic_size_in_ctbs = (geom.pic_w_ctbs * geom.pic_h_ctbs) as usize; + + let sub_range = |idx: usize| -> Result<&[u8], SequenceError> { + let &(a, b) = substreams + .get(idx) + .ok_or(SequenceError::Malformed("more CTB rows than substreams"))?; + seg.rbsp + .get(a..b) + .ok_or(SequenceError::Malformed("substream range out of RBSP")) + }; + let mut sub_idx = 0usize; + let mut engine = CabacEngine::new(BitReader::new(sub_range(0)?)) + .map_err(|_| SequenceError::Malformed("slice data too short for CABAC init"))?; + // §9.3.2.2 — a dependent slice segment synchronizes its context + // variables from TableStateIdxDs (§9.3.2.5) instead of + // re-initializing. + // §9.3.2.3 — the palette predictor re-initialization value (the + // PPS initializers if present, else the SPS initializers, else + // empty), applied wherever §9.3.2.1 re-initializes the context + // variables. A dependent segment SYNCHRONIZES the predictor from + // the stored state instead (it travels inside SliceContexts). + let num_comps = if geom.chroma_array_type == 0 { 1 } else { 3 }; + let base_palette_predictor = pps + .pps_scc_extension + .as_ref() + .filter(|e| e.pps_palette_predictor_initializers_present_flag) + .map(|e| { + crate::palette::PalettePredictor::from_initializers( + &e.pps_palette_predictor_initializer, + num_comps, + ) + }) + .or_else(|| { + sps.sps_scc_extension + .as_ref() + .filter(|e| e.sps_palette_predictor_initializers_present_flag) + .map(|e| { + crate::palette::PalettePredictor::from_initializers( + &e.sps_palette_predictor_initializer, + num_comps, + ) + }) + }) + .unwrap_or_default(); + let fresh_contexts = || { + let mut c = SliceContexts::init(it, slice_qp_y); + c.palette_predictor = base_palette_predictor.clone(); + c + }; + let mut ctx = if seg.header.dependent_slice_segment_flag { + ds_stored.clone().ok_or(SequenceError::Malformed( + "dependent segment without Ds state", + ))? + } else { + fresh_contexts() + }; + // §9.3.2.4 / §9.3.2.5 — the WPP context storage (stored after the + // second CTB of a row; synchronized at the next row's start when + // the above-right CTB is available). + let mut wpp_stored: Option = None; + let mut first_ctu = true; + // Set after the row-final CTU's end_of_subset_one_bit: the next CTU + // starts a new substream. + let mut advance_substream = false; + + loop { + if (ctb_addr_ts as usize) >= pic_size_in_ctbs { + return Err(SequenceError::Malformed( + "slice segment runs past the last CTB of the picture", + )); + } + let ctb_addr_rs = tiling.ctb_addr_ts_to_rs(ctb_addr_ts); + let rx = ctb_addr_rs % geom.pic_w_ctbs; + let ry = ctb_addr_rs / geom.pic_w_ctbs; + let x_ctb = rx << geom.ctb_log2; + let y_ctb = ry << geom.ctb_log2; + slice_addr_of[ctb_addr_rs as usize] = Some(slice_addr_rs); + + // §9.3.1 / §9.3.2.1 — subset-boundary context handling inside + // one slice segment. Item 2: the first CTU of a tile + // re-initializes the context variables (§9.3.2.2). Item 3 + // (WPP): the first luma CTB of a CTU row of a tile either + // synchronizes from the stored above-right state (§9.3.2.5) or + // re-initializes (§9.3.2.2). Either way the next entry-point + // substream starts here. The first CTU of the segment keeps + // the §9.3.1-item-1 slice initialization done above. + if !first_ctu { + let tile_start = + tiles_on && tiling.tile_id(ctb_addr_ts) != tiling.tile_id(ctb_addr_ts - 1); + // §9.3.2.1: CtbAddrInRs % PicWidthInCtbsY == 0, or the + // raster-left neighbour lies in a different tile. + let wpp_row_start = wpp + && !tile_start + && (rx == 0 + || tiling.tile_id(tiling.ctb_addr_rs_to_ts(ctb_addr_rs - 1)) + != tiling.tile_id(ctb_addr_ts)); + if tile_start || wpp_row_start { + if !advance_substream { + return Err(SequenceError::Malformed( + "subset start without end_of_subset_one_bit", + )); + } + sub_idx += 1; + engine = CabacEngine::new(BitReader::new(sub_range(sub_idx)?)) + .map_err(|_| SequenceError::Malformed("substream too short for CABAC init"))?; + if tile_start { + // §9.3.2.2 / §9.3.2.3 — fresh contexts (and + // re-initialized palette predictor) at the tile + // start. + ctx = fresh_contexts(); + } else { + // Spatial neighbour T = the CTB at ( x0 + CtbSizeY, + // y0 − CtbSizeY ) (eq. 9-3), §6.4.1-gated. + let t_avail = ry > 0 && rx + 1 < geom.pic_w_ctbs && { + let t_rs = (ry - 1) * geom.pic_w_ctbs + rx + 1; + slice_addr_of[t_rs as usize] == Some(slice_addr_rs) + && tiling.tile_id(tiling.ctb_addr_rs_to_ts(t_rs)) + == tiling.tile_id(ctb_addr_ts) + }; + ctx = match (&wpp_stored, t_avail) { + (Some(stored), true) => stored.clone(), + _ => fresh_contexts(), + }; + } + } + } + advance_substream = false; + first_ctu = false; + + // §7.3.8.3 SAO merge-candidate availability: the left / above + // CTB must exist, lie in the same slice segment sequence + // (same SliceAddrRs) and the same tile. + let tile_here = tiling.tile_id(ctb_addr_ts); + let merge_left = rx > 0 && { + let left_rs = ctb_addr_rs - 1; + slice_addr_of[left_rs as usize] == Some(slice_addr_rs) + && tiling.tile_id(tiling.ctb_addr_rs_to_ts(left_rs)) == tile_here + }; + let merge_up = ry > 0 && { + let up_rs = ctb_addr_rs - geom.pic_w_ctbs; + slice_addr_of[up_rs as usize] == Some(slice_addr_rs) + && tiling.tile_id(tiling.ctb_addr_rs_to_ts(up_rs)) == tile_here + }; + + let ctu = decode_coding_tree_unit_in_picture( + &mut engine, + &mut ctx, + ¶ms, + state, + x_ctb, + y_ctb, + slice_addr_rs, + tile_here, + merge_left, + merge_up, + )?; + decoded.push((x_ctb, y_ctb, ctu)); + + // §9.3.1 / §9.3.2.4 — store the context state after the SECOND + // CTB of a CTU row of a tile: CtbAddrInRs % PicWidthInCtbsY + // == 1, or CtbAddrInRs > 1 and the CTB two to the raster-left + // lies in a different tile. + if wpp + && (rx == 1 + || (ctb_addr_rs > 1 + && tiles_on + && tiling.tile_id(ctb_addr_ts) + != tiling.tile_id(tiling.ctb_addr_rs_to_ts(ctb_addr_rs - 2)))) + { + wpp_stored = Some(ctx.clone()); + } + + let eos = end_of_slice_segment_flag(&mut engine) + .map_err(|_| SequenceError::Malformed("CABAC underrun at end_of_slice_segment"))?; + ctb_addr_ts += 1; + if eos { + // §9.3.1 / §9.3.2.4 — store the context variables into + // TableStateIdxDs for a following dependent slice segment. + if pps.dependent_slice_segments_enabled_flag { + *ds_stored = Some(ctx.clone()); + } + break; + } + if (ctb_addr_ts as usize) >= pic_size_in_ctbs { + if tolerant { + eprintln!("(tolerant: end_of_slice_segment_flag not set on the last CTB)"); + break; + } + return Err(SequenceError::Malformed( + "end_of_slice_segment_flag not set on the last CTB", + )); + } + // §7.3.8.1 — end_of_subset_one_bit + byte_alignment( ) when + // the NEXT CTB (CtbAddrInTs already incremented) starts a new + // tile, or (WPP) a new CTU row of a tile; the next CTU reads + // from the following substream. + let next_rs = tiling.ctb_addr_ts_to_rs(ctb_addr_ts); + let tile_boundary = + tiles_on && tiling.tile_id(ctb_addr_ts) != tiling.tile_id(ctb_addr_ts - 1); + let wpp_boundary = wpp + && (next_rs % geom.pic_w_ctbs == 0 + || tiling.tile_id(ctb_addr_ts) + != tiling.tile_id(tiling.ctb_addr_rs_to_ts(next_rs - 1))); + if tile_boundary || wpp_boundary { + let one = end_of_slice_segment_flag(&mut engine) + .map_err(|_| SequenceError::Malformed("CABAC underrun at end_of_subset_one_bit"))?; + if !one && !tolerant { + return Err(SequenceError::Malformed("end_of_subset_one_bit not set")); + } + advance_substream = true; + } + } + Ok(()) +} + +/// §7.4.7.1 — the stripped-RBSP byte ranges of the +/// `num_entry_point_offsets + 1` subsets of `slice_segment_data( )`. +/// +/// The wire offsets count coded (escaped) bytes from the first byte of +/// the slice segment data, so walk the escaped payload with the +/// §7.4.1.1 emulation state machine and translate each boundary into +/// the stripped-RBSP index space. +fn split_substreams( + escaped: &[u8], + rbsp_len: usize, + stripped_data_offset: usize, + entry_points: Option<&crate::slice::EntryPointOffsets>, +) -> Result, SequenceError> { + let n_offsets = entry_points.map_or(0, |e| e.entry_point_offset_minus1.len()); + if n_offsets == 0 { + return Ok(vec![(stripped_data_offset, rbsp_len)]); + } + // stripped index -> escaped index of the slice-data start. + let mut stripped_of_escaped = vec![0usize; escaped.len() + 1]; + let mut zeros = 0u32; + let mut stripped = 0usize; + for (i, &b) in escaped.iter().enumerate() { + stripped_of_escaped[i] = stripped; + if zeros >= 2 && b == 0x03 { + // Emulation-prevention byte: consumed, not emitted. + zeros = 0; + continue; + } + if b == 0 { + zeros += 1; + } else { + zeros = 0; + } + stripped += 1; + } + stripped_of_escaped[escaped.len()] = stripped; + // Escaped index of the slice-data start. + let escaped_start = stripped_of_escaped + .iter() + .position(|&sidx| sidx == stripped_data_offset) + .ok_or(SequenceError::Malformed("slice data offset unmappable"))?; + + let entry_points = entry_points.expect("checked above"); + let mut ranges = Vec::with_capacity(n_offsets + 1); + let mut first_escaped = escaped_start; + let mut first_stripped = stripped_data_offset; + for &off_m1 in &entry_points.entry_point_offset_minus1 { + let len = off_m1 as usize + 1; + let last_escaped = first_escaped + .checked_add(len) + .filter(|&e| e <= escaped.len()) + .ok_or(SequenceError::Malformed("entry point past slice data"))?; + let last_stripped = stripped_of_escaped[last_escaped]; + ranges.push((first_stripped, last_stripped)); + first_escaped = last_escaped; + first_stripped = last_stripped; + } + ranges.push((first_stripped, rbsp_len)); + Ok(ranges) +} diff --git a/vendor/oxideav-h265/src/slice.rs b/vendor/oxideav-h265/src/slice.rs new file mode 100644 index 0000000..c01e2c9 --- /dev/null +++ b/vendor/oxideav-h265/src/slice.rs @@ -0,0 +1,5567 @@ +//! Slice segment header parser per ITU-T Rec. H.265 §7.3.6.1. +//! +//! Round-6 scope: parse the `slice_segment_header()` syntax structure +//! (§7.3.6.1) for an independent slice segment, materialising every +//! field that does **not** require decoded-picture-buffer state to +//! interpret. The parse takes the activated SPS and PPS as context +//! because several field widths and presence gates are derived from +//! them (the `slice_segment_address` width is +//! `Ceil( Log2( PicSizeInCtbsY ) )`, the `slice_pic_order_cnt_lsb` +//! width is `log2_max_pic_order_cnt_lsb_minus4 + 4`, the SAO / MVP +//! gates come from the SPS, and the tiles / entropy-sync entry-point +//! block comes from the PPS). +//! +//! ## What this round materialises +//! +//! * `first_slice_segment_in_pic_flag`, `no_output_of_prior_pics_flag` +//! (IRAP only), `slice_pic_parameter_set_id`. +//! * For non-first slice segments: `dependent_slice_segment_flag` +//! (only when `dependent_slice_segments_enabled_flag`) and +//! `slice_segment_address` (`u(v)`, width +//! `Ceil( Log2( PicSizeInCtbsY ) )`). +//! * For independent slice segments (`!dependent_slice_segment_flag`): +//! the `slice_reserved_flag[]` block, `slice_type`, +//! `pic_output_flag` (only when `output_flag_present_flag`), +//! `colour_plane_id` (only when `separate_colour_plane_flag`), +//! `slice_temporal_mvp_enabled_flag` (only when +//! `sps_temporal_mvp_enabled_flag`), the SAO luma / chroma gates, +//! `slice_qp_delta` (`se(v)`), the chroma QP offsets, the +//! deblocking-filter override block, and +//! `slice_loop_filter_across_slices_enabled_flag`. +//! * The entry-point-offset block (`num_entry_point_offsets`, +//! `offset_len_minus1`, `entry_point_offset_minus1[]`) when +//! `tiles_enabled_flag || entropy_coding_sync_enabled_flag`. +//! * The slice-segment-header extension block when +//! `slice_segment_header_extension_present_flag`. +//! * `byte_alignment()` consumed to the next byte boundary, so the +//! reported [`SliceSegmentHeader::byte_offset_to_slice_data`] points +//! at the first byte of `slice_segment_data()`. +//! +//! ## What this round defers (surfaced, not decoded) +//! +//! Three points need state this round does not carry: +//! +//! * The **non-IDR picture-order-count + reference-picture-set block** +//! (`slice_pic_order_cnt_lsb`, `short_term_ref_pic_set_sps_flag`, +//! the inline `st_ref_pic_set()`, the long-term block) needs the +//! SPS short-term-RPS parser to be re-entered for the in-line +//! `stRpsIdx == num_short_term_ref_pic_sets` case, which is not yet +//! exposed publicly. When the current NAL unit is **not** an IDR +//! (`nal_unit_type != IDR_W_RADL && != IDR_N_LP`), the parser stops +//! right after `colour_plane_id` and surfaces the remainder as +//! [`SliceSegmentHeader::opaque_tail`]. +//! * The **P / B reference-list / weighted-prediction sub-structures** +//! (`ref_pic_lists_modification()` §7.3.6.2 and `pred_weight_table()` +//! §7.3.6.3) need DPB-derived `NumPicTotalCurr` / `RefPicList` +//! values. When `slice_type` is P or B the parser materialises the +//! common P/B fields up to (but not including) the point where those +//! sub-structures would begin, then surfaces the remainder as the +//! opaque tail. The §7.3.6.2 syntax structure itself is implemented +//! as a standalone parser ([`RefPicListsModification::parse`]) so a +//! future round that wires up the §7.4.7.2 `NumPicTotalCurr` +//! derivation can decode the reference-picture-list-modification +//! block in place; the implicit `RefPicListTempX` derivation of +//! §8.3.4 stays the consumer's responsibility. When +//! `pps.lists_modification_present_flag == 0` the modification block +//! is statically absent (the §7.3.6.1 `if(... && NumPicTotalCurr > 1)` +//! short-circuit applies independent of any DPB state); the parser +//! in that case continues into the §7.3.6.1 +//! `mvd_l1_zero_flag` / `cabac_init_flag` / +//! `collocated_from_l0_flag` / `collocated_ref_idx` block in-place +//! and surfaces those four fields, then defers at the weighted-pred +//! gate. +//! +//! Independent **I-slice IDR** segments — the dominant case for the +//! intra-only fixtures this rebuild targets — are parsed end to end +//! through `byte_alignment()`. + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::pps::PicParameterSet; +use crate::sps::{OpaqueTail, SeqParameterSet, ShortTermRefPicSet, SpsError}; + +/// `nal_unit_type` value `BLA_W_LP` (Table 7-1). The IRAP range used by +/// the `no_output_of_prior_pics_flag` gate is `BLA_W_LP..=RSV_IRAP_VCL23`. +pub const BLA_W_LP: u8 = 16; +/// `nal_unit_type` value `IDR_W_RADL` (Table 7-1). +pub const IDR_W_RADL: u8 = 19; +/// `nal_unit_type` value `IDR_N_LP` (Table 7-1). +pub const IDR_N_LP: u8 = 20; +/// `nal_unit_type` value `RSV_IRAP_VCL23` (Table 7-1) — the inclusive +/// upper bound of the IRAP NAL-unit-type range. +pub const RSV_IRAP_VCL23: u8 = 23; + +/// `slice_type` enumeration per Table 7-7. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SliceType { + /// B slice (`slice_type == 0`). + B, + /// P slice (`slice_type == 1`). + P, + /// I slice (`slice_type == 2`). + I, +} + +impl SliceType { + /// Map the raw `ue(v)` `slice_type` value to the enum, rejecting + /// any value outside `0..=2`. + fn from_raw(v: u32) -> Result { + match v { + 0 => Ok(Self::B), + 1 => Ok(Self::P), + 2 => Ok(Self::I), + other => Err(SliceError::ValueOutOfRange { + field: "slice_type", + got: other as i64, + }), + } + } + + /// True for P and B slices (the slice types that signal reference + /// lists, weighted prediction, etc.). + pub fn is_inter(self) -> bool { + matches!(self, Self::P | Self::B) + } +} + +/// Errors that can arise while parsing a slice segment header. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SliceError { + /// The RBSP ran out of bits before the header was fully parsed. + Truncated, + /// A syntax element's parsed value was outside the legal range + /// specified for it in §7.4.7.1. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value as an `i64` (covers both `ue(v)` and + /// `se(v)` elements). + got: i64, + }, + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), + /// The in-line `st_ref_pic_set(num_short_term_ref_pic_sets)` parse + /// (invoked from §7.3.6.1 when `short_term_ref_pic_set_sps_flag == 0`) + /// failed. + InlineShortTermRpsParse(SpsError), +} + +impl core::fmt::Display for SliceError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("slice segment header RBSP truncated"), + Self::ValueOutOfRange { field, got } => { + write!(f, "slice header syntax element {field} out of range: {got}") + } + Self::Bitstream(e) => write!(f, "bitstream error during slice header parse: {e}"), + Self::InlineShortTermRpsParse(e) => { + write!(f, "in-line slice-header st_ref_pic_set parse failed: {e}") + } + } + } +} + +impl std::error::Error for SliceError {} + +impl From for SliceError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +impl From for SliceError { + fn from(e: SpsError) -> Self { + match e { + SpsError::Truncated => Self::Truncated, + SpsError::Bitstream(b) => Self::Bitstream(b), + other => Self::InlineShortTermRpsParse(other), + } + } +} + +/// Deblocking-filter override block carried in the slice header +/// (§7.3.6.1, gated by `deblocking_filter_override_flag`). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SliceDeblocking { + /// `slice_deblocking_filter_disabled_flag`. Inferred to + /// `pps_deblocking_filter_disabled_flag` when the override block is + /// absent (§7.4.7.1). + pub disabled_flag: bool, + /// `slice_beta_offset_div2` (`se(v)`, range −6..=6). Inferred to + /// `pps_beta_offset_div2` when absent. + pub beta_offset_div2: i8, + /// `slice_tc_offset_div2` (`se(v)`, range −6..=6). Inferred to + /// `pps_tc_offset_div2` when absent. + pub tc_offset_div2: i8, +} + +/// One long-term reference picture entry signalled in the slice +/// header (§7.3.6.1). For the first `num_long_term_sps` entries the +/// `lt_idx_sps` indexes the SPS's long-term-ref-pic table; for the +/// remaining `num_long_term_pics` entries the slice header carries +/// the POC LSB and `used_by_curr_pic_lt_flag` directly. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct SliceLongTermRefPic { + /// Source of the entry: SPS table or in-slice signalling. + pub source: SliceLongTermRefPicSource, + /// `delta_poc_msb_present_flag[i]`. + pub delta_poc_msb_present_flag: bool, + /// `delta_poc_msb_cycle_lt[i]`. Inferred to 0 when + /// [`Self::delta_poc_msb_present_flag`] is false (§7.4.7.1). + pub delta_poc_msb_cycle_lt: u32, +} + +/// Source of one [`SliceLongTermRefPic`] entry. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SliceLongTermRefPicSource { + /// First `num_long_term_sps` entries: `lt_idx_sps[i]` indexes the + /// SPS's long-term-ref-pic-poc table. The `u(v)` width is + /// `Ceil(Log2(num_long_term_ref_pics_sps))` bits; the value 0 is + /// inferred when `num_long_term_ref_pics_sps == 1`. + Sps { + /// `lt_idx_sps[i]` value (or 0 when inferred). + lt_idx_sps: u32, + }, + /// Remaining `num_long_term_pics` entries: the POC LSB and + /// `used_by_curr_pic_lt_flag` are signalled directly in the slice + /// header. + InSlice { + /// `poc_lsb_lt[i]` (`u(v)`, width + /// `log2_max_pic_order_cnt_lsb_minus4 + 4`). + poc_lsb_lt: u32, + /// `used_by_curr_pic_lt_flag[i]`. + used_by_curr_pic_lt_flag: bool, + }, +} + +impl SliceLongTermRefPic { + /// Resolve `UsedByCurrPicLt[i]` for this entry per §7.4.7.1: + /// + /// > `UsedByCurrPicLt[ i ]` is set equal to + /// > `used_by_curr_pic_lt_sps_flag[ lt_idx_sps[ i ] ]` when the + /// > entry's source is the SPS table, and to + /// > `used_by_curr_pic_lt_flag[ i ]` when the entry is signalled + /// > directly in the slice header. + /// + /// Returns `None` when [`SliceLongTermRefPicSource::Sps`] points at + /// an index that is out of range of `sps.long_term_ref_pics` + /// (a bitstream-conformance failure — the SPS-resident table must + /// cover every `lt_idx_sps[i]` value). + pub fn used_by_curr_pic_lt(&self, sps: &SeqParameterSet) -> Option { + match self.source { + SliceLongTermRefPicSource::Sps { lt_idx_sps } => sps + .long_term_ref_pics + .get(lt_idx_sps as usize) + .map(|entry| entry.used_by_curr_pic), + SliceLongTermRefPicSource::InSlice { + used_by_curr_pic_lt_flag, + .. + } => Some(used_by_curr_pic_lt_flag), + } + } +} + +/// Entry-point-offset block (§7.3.6.1, gated by +/// `tiles_enabled_flag || entropy_coding_sync_enabled_flag`). +/// +/// `num_entry_point_offsets` is the number of subsets of +/// `slice_segment_data()` minus one; each +/// `entry_point_offset_minus1[i] + 1` is the byte length of subset +/// `i` (§7.4.7.1). The trailing subset (`num_entry_point_offsets`) +/// runs to the end of `slice_segment_data()` and is therefore not +/// encoded. +/// +/// Per §7.4.7.1, the on-wire `num_entry_point_offsets` is bounded by +/// the active partitioning: +/// +/// * `tiles_enabled_flag == 1` and `entropy_coding_sync_enabled_flag +/// == 0` → `0..=(NumTileColumns * NumTileRows − 1)`. +/// * `tiles_enabled_flag == 0` and `entropy_coding_sync_enabled_flag +/// == 1` → `0..=(PicHeightInCtbsY − 1)`. +/// * Both flags set (the "tiles + WPP" combination) is constrained by +/// §7.4.3.3.1 to never appear in a conforming stream; this parser +/// accepts the wider of the two bounds in that pathological case +/// rather than gate the parse on a flag combination the PPS parser +/// already rejects. +/// +/// Each `entry_point_offset_minus1[i]` is `offset_len_minus1 + 1` bits +/// wide. `offset_len_minus1` itself is bounded to `0..=31` by +/// §7.4.7.1, so the per-entry width is in `1..=32`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EntryPointOffsets { + /// `num_entry_point_offsets` (`ue(v)`). The number of subsets of + /// slice-segment data is this value plus one. + pub num_entry_point_offsets: u32, + /// `offset_len_minus1` (`ue(v)`, range 0..=31). Each + /// `entry_point_offset_minus1[i]` is `offset_len_minus1 + 1` bits. + /// Only meaningful when `num_entry_point_offsets > 0`; left at 0 + /// when no offsets are signalled. + pub offset_len_minus1: u8, + /// `entry_point_offset_minus1[i]` (`u(offset_len_minus1 + 1)`) for + /// `i = 0 .. num_entry_point_offsets`. Empty when + /// `num_entry_point_offsets == 0`. + pub entry_point_offset_minus1: Vec, +} + +impl EntryPointOffsets { + /// Byte length of subset `i` per §7.4.7.1, i.e. + /// `entry_point_offset_minus1[i] + 1`. Returns `None` when `i` is + /// out of range. + pub fn subset_length(&self, i: usize) -> Option { + self.entry_point_offset_minus1 + .get(i) + .map(|v| u64::from(*v) + 1) + } +} + +/// Parsed `ref_pic_lists_modification()` syntax structure +/// (ITU-T Rec. H.265 §7.3.6.2 / §7.4.7.2). +/// +/// The structure is signalled in the slice header when +/// `lists_modification_present_flag == 1 && NumPicTotalCurr > 1` +/// (§7.3.6.1 gate). It carries a per-list "explicit list" override of +/// the implicit `RefPicList0` / `RefPicList1` derivation of §8.3.4: the +/// `list_entry_lX[i]` value is the index of the reference picture in +/// `RefPicListTempX` to place at position `i` of `RefPicListX`. The +/// `RefPicListTempX` derivation itself is part of §8.3.4 (DPB-driven) +/// and is **not** performed by this parser — this struct surfaces only +/// the on-wire syntax elements and applies the §7.4.7.2 inference and +/// range checks. +/// +/// Width of each `list_entry_lX[i]` is `Ceil( Log2( NumPicTotalCurr ) )` +/// bits and the value must be in `0 ..= NumPicTotalCurr - 1` +/// (§7.4.7.2). When `ref_pic_list_modification_flag_lX == 0` the +/// corresponding entry list is empty; the implicit derivation of +/// §8.3.4 applies (each `list_entry_lX[i]` is inferred to 0 per the +/// §7.4.7.2 paragraph "When the syntax element list_entry_lX[i] is +/// not present in the slice header, it is inferred to be equal to 0", +/// but the inference is exercised by §8.3.4, not surfaced here). +/// +/// The list-1 fields are present only when `slice_type == B` +/// (§7.3.6.2 syntax). For a P slice the `list_entry_l1` vector is +/// always empty. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct RefPicListsModification { + /// `ref_pic_list_modification_flag_l0` (`u(1)`). + pub ref_pic_list_modification_flag_l0: bool, + /// `list_entry_l0[i]` for `i = 0 ..= num_ref_idx_l0_active_minus1`. + /// Empty when `ref_pic_list_modification_flag_l0 == 0`. + pub list_entry_l0: Vec, + /// `ref_pic_list_modification_flag_l1` (`u(1)`). `None` when the + /// slice is not a B slice (the field is not signalled). + pub ref_pic_list_modification_flag_l1: Option, + /// `list_entry_l1[i]` for `i = 0 ..= num_ref_idx_l1_active_minus1`. + /// Empty for P slices and when `ref_pic_list_modification_flag_l1 + /// == 0`. + pub list_entry_l1: Vec, +} + +impl RefPicListsModification { + /// Parse `ref_pic_lists_modification()` (§7.3.6.2) from the current + /// bit position of `br`. + /// + /// * `slice_type` — the active slice type. Per §7.3.6.2 the L1 + /// block (`ref_pic_list_modification_flag_l1` / + /// `list_entry_l1[]`) is only signalled for B slices. For an + /// I slice the structure is never present at all (the §7.3.6.1 + /// gate `lists_modification_present_flag && NumPicTotalCurr > 1` + /// sits inside the inter-slice `slice_type != I` branch), so + /// the parser rejects `SliceType::I` up front. + /// * `num_ref_idx_l0_active_minus1` — the *active* value (after + /// the `num_ref_idx_active_override_flag` override, falling back + /// to `num_ref_idx_l0_default_active_minus1` from the PPS). Per + /// §7.4.7.1 the value is in `0 ..= 14`. + /// * `num_ref_idx_l1_active_minus1` — same, for L1; ignored for P + /// slices. + /// * `num_pic_total_curr` — `NumPicTotalCurr` (§7.4.7.2 / + /// equation 7-57). The caller derives it from the active RPS; + /// the §7.3.6.1 gate guarantees `num_pic_total_curr > 1` at the + /// point of call. This parser rejects `num_pic_total_curr <= 1` + /// (the §7.3.6.1 gate would have prevented the call); a call + /// with `num_pic_total_curr == 0` would also imply a bitstream + /// conformance failure per §7.4.7.1 ("when the current picture + /// contains a P or B slice, the value of NumPicTotalCurr shall + /// not be equal to 0"). Each `list_entry_lX[i]` is read as + /// `u(v)` of width `Ceil( Log2( num_pic_total_curr ) )` bits + /// and range-checked against `num_pic_total_curr - 1`. + pub fn parse( + br: &mut BitReader<'_>, + slice_type: SliceType, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + num_pic_total_curr: u32, + ) -> Result { + if slice_type == SliceType::I { + return Err(SliceError::ValueOutOfRange { + field: "ref_pic_lists_modification/slice_type", + got: 2, + }); + } + if num_pic_total_curr <= 1 { + return Err(SliceError::ValueOutOfRange { + field: "ref_pic_lists_modification/NumPicTotalCurr", + got: num_pic_total_curr as i64, + }); + } + // §7.4.7.1 ranges `num_ref_idx_lX_active_minus1` at 0..=14; + // defensively cap the per-list loop length so a corrupted call + // can't drive an unbounded allocation. (The cap matches the + // spec maximum; a value above 14 would be rejected by the + // §7.4.7.1 slice-header parse before reaching here.) + if num_ref_idx_l0_active_minus1 > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: num_ref_idx_l0_active_minus1 as i64, + }); + } + if slice_type == SliceType::B && num_ref_idx_l1_active_minus1 > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l1_active_minus1", + got: num_ref_idx_l1_active_minus1 as i64, + }); + } + + let entry_bits = ceil_log2(num_pic_total_curr); + let max_entry = num_pic_total_curr - 1; + + let ref_pic_list_modification_flag_l0 = br.u1()? != 0; + let mut list_entry_l0: Vec = Vec::new(); + if ref_pic_list_modification_flag_l0 { + let n = num_ref_idx_l0_active_minus1 as u32 + 1; + list_entry_l0.reserve(n as usize); + for _ in 0..n { + let v = br.u(entry_bits)?; + if v > max_entry { + return Err(SliceError::ValueOutOfRange { + field: "list_entry_l0", + got: v as i64, + }); + } + list_entry_l0.push(v); + } + } + + let (ref_pic_list_modification_flag_l1, list_entry_l1) = if slice_type == SliceType::B { + let flag = br.u1()? != 0; + let mut entries: Vec = Vec::new(); + if flag { + let n = num_ref_idx_l1_active_minus1 as u32 + 1; + entries.reserve(n as usize); + for _ in 0..n { + let v = br.u(entry_bits)?; + if v > max_entry { + return Err(SliceError::ValueOutOfRange { + field: "list_entry_l1", + got: v as i64, + }); + } + entries.push(v); + } + } + (Some(flag), entries) + } else { + (None, Vec::new()) + }; + + Ok(Self { + ref_pic_list_modification_flag_l0, + list_entry_l0, + ref_pic_list_modification_flag_l1, + list_entry_l1, + }) + } +} + +/// Inputs to the §7.4.7.2 `NumPicTotalCurr` derivation (equation 7-57). +/// +/// `NumPicTotalCurr` counts the reference pictures in the current +/// slice's RPS state that are flagged as *used by the current +/// picture* — i.e. eligible for entry into `RefPicListTemp0` / +/// `RefPicListTemp1`. The §7.3.6.1 gate +/// `lists_modification_present_flag && NumPicTotalCurr > 1` consumes +/// the derivation to decide whether the inter-slice header carries a +/// `ref_pic_lists_modification()` block, and the per-entry width of +/// that block's `list_entry_lX[i]` (`Ceil( Log2( NumPicTotalCurr ) )`, +/// §7.4.7.2) consumes the value directly. +/// +/// The four `UsedByCurrPic*` slices supplied by the caller are the +/// resolved per-position state of the active RPS: +/// +/// * `used_by_curr_pic_s0` — `UsedByCurrPicS0[ CurrRpsIdx ][ i ]` for +/// `i = 0 .. NumNegativePics[ CurrRpsIdx ]`. +/// * `used_by_curr_pic_s1` — `UsedByCurrPicS1[ CurrRpsIdx ][ i ]` for +/// `i = 0 .. NumPositivePics[ CurrRpsIdx ]`. +/// * `used_by_curr_pic_lt` — `UsedByCurrPicLt[ i ]` for +/// `i = 0 .. num_long_term_sps + num_long_term_pics`. The §7.4.7.1 +/// selector ("SPS-resident → `used_by_curr_pic_lt_sps_flag[ +/// lt_idx_sps[ i ] ]`; in-slice → `used_by_curr_pic_lt_flag[ i ]`") +/// is applied by the caller; [`SliceLongTermRefPic::used_by_curr_pic_lt`] +/// does the per-entry resolution against the active SPS. +/// +/// For the explicit (non-inter-RPS-predicted) short-term RPS form, the +/// `S0` / `S1` slices come directly from +/// [`ShortTermRefPicSet::used_by_curr_pic_s0_flag`] / +/// [`ShortTermRefPicSet::used_by_curr_pic_s1_flag`] and the +/// [`Self::from_explicit_short_term_rps`] builder is provided. For the +/// inter-RPS-prediction form the §7.4.8 derivation (equations +/// 7-58..7-66) must be run first; the result of that derivation is +/// then handed to [`Self::from_used_flags`]. +/// +/// The remaining inputs: +/// +/// * `pps_curr_pic_ref_enabled_flag` — §7.4.7.2 closing-clause flag, +/// from the SCC extension of the active PPS. Inferred to `false` +/// when the SCC PPS is not signalled (§7.4.3.3.1.4). +/// * `nal_unit_type` — used only by the F.7.4.7.2 multilayer-extension +/// variant of equation 7-57 (`F-56`): when the multilayer extension +/// applies and the current picture is IDR (`IDR_W_RADL` / +/// `IDR_N_LP`), the short-term and long-term loops are skipped +/// entirely. For base §7.4.7.2 the value is unused because every +/// IDR slice already has zero short-term and long-term entries. +/// * `num_active_ref_layer_pics` — F.7.4.7.2 `NumActiveRefLayerPics` +/// (the count of active inter-layer reference pictures for the +/// current slice, §F.7.4.7.1). Set to `0` for base §7.4.7.2. +/// +/// The `nal_unit_type` IDR gate and `num_active_ref_layer_pics` +/// contribution are only applied when [`Self::multilayer_extension`] +/// is `true` (forward-compat for the multilayer scaffold; left +/// `false` by every base-profile call site). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct NumPicTotalCurrInputs<'a> { + /// Per-position `UsedByCurrPicS0[ CurrRpsIdx ][ i ]` flags. + pub used_by_curr_pic_s0: &'a [bool], + /// Per-position `UsedByCurrPicS1[ CurrRpsIdx ][ i ]` flags. + pub used_by_curr_pic_s1: &'a [bool], + /// Per-position `UsedByCurrPicLt[ i ]` flags, length + /// `num_long_term_sps + num_long_term_pics`. + pub used_by_curr_pic_lt: &'a [bool], + /// `pps_curr_pic_ref_enabled_flag` (§7.4.3.3.1.4 SCC PPS). Inferred + /// to `false` when not signalled. + pub pps_curr_pic_ref_enabled_flag: bool, + /// `nal_unit_type` of the slice's NAL unit (Table 7-1). Consumed + /// only when [`Self::multilayer_extension`] is `true`. + pub nal_unit_type: u8, + /// F.7.4.7.2 `NumActiveRefLayerPics` (the §F.7.4.7.1 inter-layer + /// active count). Consumed only when [`Self::multilayer_extension`] + /// is `true`. + pub num_active_ref_layer_pics: u32, + /// Forward-compat toggle: when `true`, equation `F-56` of + /// F.7.4.7.2 is applied instead of equation 7-57 of §7.4.7.2 + /// (the short-term / long-term loops are skipped for IDR + /// `nal_unit_type`, and `NumActiveRefLayerPics` is added at the + /// end). Every base-profile call site leaves this `false`. + pub multilayer_extension: bool, +} + +impl<'a> NumPicTotalCurrInputs<'a> { + /// Build the inputs from already-resolved per-position + /// `UsedByCurrPic*` slices. The caller is responsible for having + /// run the §7.4.8 inter-RPS-prediction derivation if the active + /// short-term RPS uses the predicted form. + pub fn from_used_flags( + used_by_curr_pic_s0: &'a [bool], + used_by_curr_pic_s1: &'a [bool], + used_by_curr_pic_lt: &'a [bool], + ) -> Self { + Self { + used_by_curr_pic_s0, + used_by_curr_pic_s1, + used_by_curr_pic_lt, + pps_curr_pic_ref_enabled_flag: false, + nal_unit_type: 0, + num_active_ref_layer_pics: 0, + multilayer_extension: false, + } + } + + /// Build the inputs from an *explicit-form* short-term RPS, where + /// the `UsedByCurrPicS0` / `UsedByCurrPicS1` arrays are the + /// SPS-signalled `used_by_curr_pic_sX_flag` arrays themselves + /// (§7.4.8 equations 7-65 / 7-66). Returns `None` when the RPS + /// uses inter-prediction (`inter_ref_pic_set_prediction_flag == + /// 1`) — the §7.4.8 derivation must be run first and the result + /// passed to [`Self::from_used_flags`]. + pub fn from_explicit_short_term_rps( + curr_rps: &'a ShortTermRefPicSet, + used_by_curr_pic_lt: &'a [bool], + ) -> Option { + if curr_rps.inter_ref_pic_set_prediction_flag { + return None; + } + Some(Self::from_used_flags( + &curr_rps.used_by_curr_pic_s0_flag, + &curr_rps.used_by_curr_pic_s1_flag, + used_by_curr_pic_lt, + )) + } + + /// Set [`Self::pps_curr_pic_ref_enabled_flag`] (builder). + pub fn with_pps_curr_pic_ref_enabled(mut self, flag: bool) -> Self { + self.pps_curr_pic_ref_enabled_flag = flag; + self + } + + /// Set the multilayer-extension trio (builder). + pub fn with_multilayer_extension( + mut self, + nal_unit_type: u8, + num_active_ref_layer_pics: u32, + ) -> Self { + self.multilayer_extension = true; + self.nal_unit_type = nal_unit_type; + self.num_active_ref_layer_pics = num_active_ref_layer_pics; + self + } + + /// Compute `NumPicTotalCurr` per equation 7-57 (base §7.4.7.2) or + /// equation `F-56` (F.7.4.7.2 multilayer extension), depending on + /// [`Self::multilayer_extension`]. + /// + /// The base equation 7-57: + /// + /// ```text + /// NumPicTotalCurr = 0 + /// for i in 0..NumNegativePics[CurrRpsIdx]: + /// if UsedByCurrPicS0[CurrRpsIdx][i]: NumPicTotalCurr++ + /// for i in 0..NumPositivePics[CurrRpsIdx]: + /// if UsedByCurrPicS1[CurrRpsIdx][i]: NumPicTotalCurr++ + /// for i in 0..(num_long_term_sps + num_long_term_pics): + /// if UsedByCurrPicLt[i]: NumPicTotalCurr++ + /// if pps_curr_pic_ref_enabled_flag: NumPicTotalCurr++ + /// ``` + /// + /// The multilayer variant `F-56` skips the short-term and + /// long-term loops entirely for IDR `nal_unit_type` values + /// (`IDR_W_RADL` / `IDR_N_LP`), then adds `NumActiveRefLayerPics` + /// after the `pps_curr_pic_ref_enabled_flag` step. + pub fn compute(&self) -> u32 { + let is_idr = self.nal_unit_type == IDR_W_RADL || self.nal_unit_type == IDR_N_LP; + let skip_temporal_loops = self.multilayer_extension && is_idr; + + let mut n: u32 = 0; + if !skip_temporal_loops { + n += self.used_by_curr_pic_s0.iter().filter(|&&v| v).count() as u32; + n += self.used_by_curr_pic_s1.iter().filter(|&&v| v).count() as u32; + n += self.used_by_curr_pic_lt.iter().filter(|&&v| v).count() as u32; + } + if self.pps_curr_pic_ref_enabled_flag { + n += 1; + } + if self.multilayer_extension { + n += self.num_active_ref_layer_pics; + } + n + } +} + +/// Per-list weighted-prediction entry for one reference picture in +/// [`PredWeightTable`] (one entry per `i = 0 ..= num_ref_idx_lX_active_minus1`). +/// +/// Fields are the raw §7.3.6.3 syntax elements, kept in unresolved form +/// so the caller can both audit the on-wire bits and compute the +/// §7.4.7.3 derived variables `LumaWeightLX[i]`, +/// `ChromaWeightLX[i][j]`, `ChromaOffsetLX[i][j]` through the +/// helper methods on [`PredWeightTable`] (which also apply the +/// §7.4.7.3 inference rules for the absent fields). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct PredWeightEntry { + /// `luma_weight_lX_flag[i]` (`u(1)`). Inferred to `false` when the + /// §7.3.6.3 outer gate (`pic_layer_id != nuh_layer_id || + /// PicOrderCnt(RefPicListX[i]) != PicOrderCnt(CurrPic)`) is `false` + /// for this `i` — for a base-profile single-layer slice the gate is + /// always `true`, so this flag is always signalled. + pub luma_weight_flag: bool, + /// `chroma_weight_lX_flag[i]` (`u(1)`). Absent (inferred `false`) + /// when `ChromaArrayType == 0` or when the outer gate is `false` + /// for this `i`. + pub chroma_weight_flag: bool, + /// `delta_luma_weight_lX[i]` (`se(v)`, range −128..=127). Inferred + /// to `0` when [`Self::luma_weight_flag`] is `false`. + pub delta_luma_weight: i32, + /// `luma_offset_lX[i]` (`se(v)`, range + /// `−WpOffsetHalfRangeY ..= WpOffsetHalfRangeY − 1`). Inferred to + /// `0` when [`Self::luma_weight_flag`] is `false`. + pub luma_offset: i32, + /// `delta_chroma_weight_lX[i][j]` (`se(v)`, range −128..=127) for + /// `j = 0 (Cb), 1 (Cr)`. Both inferred to `0` when + /// [`Self::chroma_weight_flag`] is `false`. + pub delta_chroma_weight: [i32; 2], + /// `delta_chroma_offset_lX[i][j]` (`se(v)`, range + /// `−4 * WpOffsetHalfRangeC ..= 4 * WpOffsetHalfRangeC − 1`) for + /// `j = 0 (Cb), 1 (Cr)`. Both inferred to `0` when + /// [`Self::chroma_weight_flag`] is `false`. + pub delta_chroma_offset: [i32; 2], +} + +/// Parsed `pred_weight_table()` syntax structure (ITU-T Rec. H.265 +/// §7.3.6.3 / §7.4.7.3). +/// +/// The structure is signalled in the slice header when +/// `(weighted_pred_flag && slice_type == P) || +/// (weighted_bipred_flag && slice_type == B)` (§7.3.6.1 gate). It +/// carries per-reference weighting factors and additive offsets that +/// §8.5.3.3.4.3 applies to the inter-prediction samples produced from +/// each `RefPicListX[i]`. +/// +/// ### Outer §7.3.6.3 gate +/// +/// Each `luma_weight_lX_flag[i]` and `chroma_weight_lX_flag[i]` syntax +/// element is wrapped in a conditional: +/// +/// ```text +/// if( pic_layer_id( RefPicListX[ i ] ) != nuh_layer_id || +/// PicOrderCnt( RefPicListX[ i ] ) != PicOrderCnt( CurrPic ) ) +/// luma_weight_lX_flag[ i ] u(1) +/// ``` +/// +/// — the flag is only signalled when the reference is a *different +/// picture* (i.e. either an inter-layer reference or a temporal +/// reference). For a base-profile single-layer slice every active +/// reference is temporal, so the gate is universally `true` and every +/// flag is signalled. For inter-layer / SCC self-reference cases the +/// gate is `false` for some `i`, and the parser must skip the +/// corresponding flag bit and infer it to `0` (§7.4.7.3 "When +/// luma_weight_lX_flag[ i ] is not present, it is inferred to be equal +/// to 0"). +/// +/// The caller resolves the DPB-driven gate and passes the per-i +/// boolean decisions through [`PredWeightTableInputs::signal_luma_l0`] +/// / [`PredWeightTableInputs::signal_chroma_l0`] / +/// [`PredWeightTableInputs::signal_luma_l1`] / +/// [`PredWeightTableInputs::signal_chroma_l1`]; the default +/// [`PredWeightTableInputs::base_profile`] constructor leaves them all +/// `true` (the base-profile case). +/// +/// ### Derived variables +/// +/// Per §7.4.7.3 the on-wire deltas combine with the per-list +/// `..._log2_weight_denom` to produce the actual weighting factors and +/// offsets the §8.5.3.3.4.3 inter-prediction process consumes: +/// +/// * `ChromaLog2WeightDenom = luma_log2_weight_denom + +/// delta_chroma_log2_weight_denom` (range 0..=7). +/// * `LumaWeightLX[i] = (1 << luma_log2_weight_denom) + +/// delta_luma_weight_lX[i]` when the luma flag is set, else inferred +/// to `1 << luma_log2_weight_denom`. +/// * `ChromaWeightLX[i][j] = (1 << ChromaLog2WeightDenom) + +/// delta_chroma_weight_lX[i][j]` when the chroma flag is set, else +/// inferred to `1 << ChromaLog2WeightDenom`. +/// * `ChromaOffsetLX[i][j]` per equation 7-58 (a clipped expression +/// parameterised by `WpOffsetHalfRangeC` and `ChromaLog2WeightDenom`). +/// +/// The accessor methods on this struct apply those derivations. +/// +/// ### Conformance check +/// +/// §7.4.7.3 closes with the `sumWeightLXFlags` cap: for a P slice +/// `sumWeightL0Flags ≤ 24`; for a B slice +/// `sumWeightL0Flags + sumWeightL1Flags ≤ 24` where each +/// `sumWeightLXFlags = Σ ( luma_weight_lX_flag[i] + +/// 2 * chroma_weight_lX_flag[i] )`. The parser computes this sum and +/// enforces the cap. +/// +/// ### Range checks +/// +/// * `luma_log2_weight_denom` ∈ 0..=7. +/// * `luma_log2_weight_denom + delta_chroma_log2_weight_denom` ∈ 0..=7 +/// (the variable `ChromaLog2WeightDenom`). +/// * `delta_luma_weight_lX[i]` ∈ −128..=127 when the luma flag is set. +/// * `luma_offset_lX[i]` ∈ `−WpOffsetHalfRangeY ..= WpOffsetHalfRangeY − 1` +/// when the luma flag is set. +/// * `delta_chroma_weight_lX[i][j]` ∈ −128..=127 when the chroma flag +/// is set. +/// * `delta_chroma_offset_lX[i][j]` ∈ +/// `−4 * WpOffsetHalfRangeC ..= 4 * WpOffsetHalfRangeC − 1` when the +/// chroma flag is set. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PredWeightTable { + /// `luma_log2_weight_denom` (`ue(v)`, range 0..=7). + pub luma_log2_weight_denom: u8, + /// `delta_chroma_log2_weight_denom` (`se(v)`). Absent (and + /// inferred to 0 per §7.4.7.3) when `ChromaArrayType == 0`. + pub delta_chroma_log2_weight_denom: i32, + /// L0 per-reference entries, length + /// `num_ref_idx_l0_active_minus1 + 1`. + pub entries_l0: Vec, + /// L1 per-reference entries, length + /// `num_ref_idx_l1_active_minus1 + 1` for B slices. Empty for P + /// slices (the §7.3.6.3 `if( slice_type == B )` gate suppresses + /// every L1 syntax element). + pub entries_l1: Vec, +} + +/// Inputs to [`PredWeightTable::parse`]. +/// +/// Carries every value the parser needs to derive field widths, +/// presence gates, range bounds and the per-i §7.3.6.3 outer-gate +/// decisions. The [`Self::base_profile`] constructor covers the common +/// case (single-layer base profile, `high_precision_offsets_enabled_flag +/// == 0`, every per-i gate `true`); the other setters carry the +/// extension-specific knobs. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct PredWeightTableInputs<'a> { + /// Active `slice_type` (the L1 syntax block is suppressed for P). + pub slice_type: SliceType, + /// Active `num_ref_idx_l0_active_minus1` after the + /// `num_ref_idx_active_override_flag` override (range 0..=14 per + /// §7.4.7.1). + pub num_ref_idx_l0_active_minus1: u8, + /// Active `num_ref_idx_l1_active_minus1`. Ignored for P slices. + pub num_ref_idx_l1_active_minus1: u8, + /// `ChromaArrayType` per §7.4.2.2. When `0` (monochrome or + /// separate-colour-plane) the entire chroma sub-block is absent. + pub chroma_array_type: u8, + /// `high_precision_offsets_enabled_flag` from the SPS range + /// extension (§7.4.3.2.2 / equations 7-33 / 7-34). Inferred to + /// `false` when the SPS range extension is not signalled. + pub high_precision_offsets_enabled_flag: bool, + /// `BitDepthY` from the SPS (§7.4.3.2.1), used by + /// `WpOffsetHalfRangeY` when [`Self::high_precision_offsets_enabled_flag`] + /// is `true`. Ignored otherwise (`WpOffsetHalfRangeY = 128`). + pub bit_depth_y: u8, + /// `BitDepthC` from the SPS (§7.4.3.2.1), used by + /// `WpOffsetHalfRangeC` when [`Self::high_precision_offsets_enabled_flag`] + /// is `true`. Ignored otherwise (`WpOffsetHalfRangeC = 128`). + pub bit_depth_c: u8, + /// Per-i outer-gate decision for `luma_weight_l0_flag[i]`. When + /// `None`, every position is treated as gated `true` + /// (base-profile case). When `Some(slice)`, length must equal + /// `num_ref_idx_l0_active_minus1 + 1` and `slice[i] == false` + /// suppresses the corresponding flag bit (inferred to `0`). + pub signal_luma_l0: Option<&'a [bool]>, + /// Same as [`Self::signal_luma_l0`] for `chroma_weight_l0_flag[i]`. + pub signal_chroma_l0: Option<&'a [bool]>, + /// Same as [`Self::signal_luma_l0`] for `luma_weight_l1_flag[i]` + /// (B slices only). + pub signal_luma_l1: Option<&'a [bool]>, + /// Same as [`Self::signal_luma_l0`] for `chroma_weight_l1_flag[i]` + /// (B slices only). + pub signal_chroma_l1: Option<&'a [bool]>, +} + +impl<'a> PredWeightTableInputs<'a> { + /// Base-profile single-layer constructor: every per-i §7.3.6.3 + /// outer-gate decision is `true`, `high_precision_offsets_enabled_flag + /// == false`. The caller supplies only the slice-type, the active + /// ref-list cardinalities, and the activated SPS's + /// `ChromaArrayType` + bit depths. + pub fn base_profile( + slice_type: SliceType, + num_ref_idx_l0_active_minus1: u8, + num_ref_idx_l1_active_minus1: u8, + chroma_array_type: u8, + bit_depth_y: u8, + bit_depth_c: u8, + ) -> Self { + Self { + slice_type, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + chroma_array_type, + high_precision_offsets_enabled_flag: false, + bit_depth_y, + bit_depth_c, + signal_luma_l0: None, + signal_chroma_l0: None, + signal_luma_l1: None, + signal_chroma_l1: None, + } + } + + /// `WpOffsetHalfRangeY` per equation 7-33. + fn wp_offset_half_range_y(&self) -> i32 { + let shift = if self.high_precision_offsets_enabled_flag { + (self.bit_depth_y as i32) - 1 + } else { + 7 + }; + 1i32 << shift + } + + /// `WpOffsetHalfRangeC` per equation 7-34. + fn wp_offset_half_range_c(&self) -> i32 { + let shift = if self.high_precision_offsets_enabled_flag { + (self.bit_depth_c as i32) - 1 + } else { + 7 + }; + 1i32 << shift + } +} + +impl PredWeightTable { + /// Parse `pred_weight_table()` (§7.3.6.3) from the current bit + /// position of `br`. See [`PredWeightTableInputs`] for the per-call + /// inputs and the base-profile constructor. + /// + /// The parser: + /// + /// 1. Reads `luma_log2_weight_denom` (`ue(v)`, range 0..=7). + /// 2. When `chroma_array_type != 0`, reads + /// `delta_chroma_log2_weight_denom` (`se(v)`) and validates the + /// derived `ChromaLog2WeightDenom` ∈ 0..=7. + /// 3. Reads the L0 luma-flag pass, applying the per-i outer-gate + /// decision from [`PredWeightTableInputs::signal_luma_l0`]. + /// 4. When `chroma_array_type != 0`, reads the L0 chroma-flag + /// pass with the matching gate slice. + /// 5. Reads the L0 per-reference delta block: for each `i` where + /// the flag is set, reads `delta_luma_weight_l0[i]` + + /// `luma_offset_l0[i]`; when the chroma flag is set, reads + /// `delta_chroma_weight_l0[i][j]` + `delta_chroma_offset_l0[i][j]` + /// for `j ∈ {0, 1}`. + /// 6. For B slices, mirrors steps 3–5 for L1. + /// 7. Validates the §7.4.7.3 `sumWeightLXFlags ≤ 24` cap. + /// + /// Each delta is range-checked per §7.4.7.3; range failures + /// surface as [`SliceError::ValueOutOfRange`]. + pub fn parse( + br: &mut BitReader<'_>, + inputs: &PredWeightTableInputs<'_>, + ) -> Result { + if inputs.slice_type == SliceType::I { + return Err(SliceError::ValueOutOfRange { + field: "pred_weight_table/slice_type", + got: 2, + }); + } + if inputs.num_ref_idx_l0_active_minus1 > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: inputs.num_ref_idx_l0_active_minus1 as i64, + }); + } + if inputs.slice_type == SliceType::B && inputs.num_ref_idx_l1_active_minus1 > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l1_active_minus1", + got: inputs.num_ref_idx_l1_active_minus1 as i64, + }); + } + + let n_l0 = inputs.num_ref_idx_l0_active_minus1 as usize + 1; + let n_l1 = if inputs.slice_type == SliceType::B { + inputs.num_ref_idx_l1_active_minus1 as usize + 1 + } else { + 0 + }; + validate_signal_slice("signal_luma_l0", inputs.signal_luma_l0, n_l0)?; + validate_signal_slice("signal_chroma_l0", inputs.signal_chroma_l0, n_l0)?; + validate_signal_slice("signal_luma_l1", inputs.signal_luma_l1, n_l1)?; + validate_signal_slice("signal_chroma_l1", inputs.signal_chroma_l1, n_l1)?; + + let chroma_present = inputs.chroma_array_type != 0; + + let luma_log2_weight_denom_u = br.ue()?; + if luma_log2_weight_denom_u > 7 { + return Err(SliceError::ValueOutOfRange { + field: "luma_log2_weight_denom", + got: luma_log2_weight_denom_u as i64, + }); + } + let luma_log2_weight_denom = luma_log2_weight_denom_u as u8; + + let delta_chroma_log2_weight_denom: i32 = if chroma_present { + let v = br.se()?; + let chroma_denom = luma_log2_weight_denom as i32 + v; + if !(0..=7).contains(&chroma_denom) { + return Err(SliceError::ValueOutOfRange { + field: "ChromaLog2WeightDenom", + got: chroma_denom as i64, + }); + } + v + } else { + 0 + }; + + // L0: parse the two flag passes (luma, then chroma when + // chroma is present), then the per-reference delta block. + let entries_l0 = parse_pred_weight_list( + br, + n_l0, + chroma_present, + inputs.signal_luma_l0, + inputs.signal_chroma_l0, + inputs.wp_offset_half_range_y(), + inputs.wp_offset_half_range_c(), + "l0", + )?; + + // L1: B slices only. + let entries_l1 = if inputs.slice_type == SliceType::B { + parse_pred_weight_list( + br, + n_l1, + chroma_present, + inputs.signal_luma_l1, + inputs.signal_chroma_l1, + inputs.wp_offset_half_range_y(), + inputs.wp_offset_half_range_c(), + "l1", + )? + } else { + Vec::new() + }; + + // §7.4.7.3 sumWeightLXFlags cap: ≤ 24 per list contribution. + let sum_l0 = sum_weight_flags(&entries_l0); + if inputs.slice_type == SliceType::P && sum_l0 > 24 { + return Err(SliceError::ValueOutOfRange { + field: "sumWeightL0Flags", + got: sum_l0 as i64, + }); + } + if inputs.slice_type == SliceType::B { + let sum_l1 = sum_weight_flags(&entries_l1); + if sum_l0 + sum_l1 > 24 { + return Err(SliceError::ValueOutOfRange { + field: "sumWeightL0Flags+sumWeightL1Flags", + got: (sum_l0 + sum_l1) as i64, + }); + } + } + + Ok(Self { + luma_log2_weight_denom, + delta_chroma_log2_weight_denom, + entries_l0, + entries_l1, + }) + } + + /// `ChromaLog2WeightDenom = luma_log2_weight_denom + + /// delta_chroma_log2_weight_denom` per §7.4.7.3. Returns `0` when + /// the chroma sub-block was absent (`ChromaArrayType == 0`); the + /// derivation is moot in that case. + pub fn chroma_log2_weight_denom(&self) -> u8 { + // The parser's range check on `ChromaLog2WeightDenom ∈ 0..=7` + // guarantees the sum fits in a `u8`. + (self.luma_log2_weight_denom as i32 + self.delta_chroma_log2_weight_denom) as u8 + } + + /// `LumaWeightL0[i]` per §7.4.7.3: `(1 << luma_log2_weight_denom) + /// + delta_luma_weight_l0[i]` when the flag is set, else + /// inferred to `1 << luma_log2_weight_denom`. + pub fn luma_weight_l0(&self, i: usize) -> Option { + self.entries_l0 + .get(i) + .map(|e| self.luma_weight_value(e.luma_weight_flag, e.delta_luma_weight)) + } + + /// `LumaWeightL1[i]` per §7.4.7.3. + pub fn luma_weight_l1(&self, i: usize) -> Option { + self.entries_l1 + .get(i) + .map(|e| self.luma_weight_value(e.luma_weight_flag, e.delta_luma_weight)) + } + + /// `ChromaWeightL0[i][j]` per §7.4.7.3. + pub fn chroma_weight_l0(&self, i: usize, j: usize) -> Option { + let e = self.entries_l0.get(i)?; + let v = *e.delta_chroma_weight.get(j)?; + Some(self.chroma_weight_value(e.chroma_weight_flag, v)) + } + + /// `ChromaWeightL1[i][j]` per §7.4.7.3. + pub fn chroma_weight_l1(&self, i: usize, j: usize) -> Option { + let e = self.entries_l1.get(i)?; + let v = *e.delta_chroma_weight.get(j)?; + Some(self.chroma_weight_value(e.chroma_weight_flag, v)) + } + + /// `ChromaOffsetL0[i][j]` per §7.4.7.3 equation 7-58. + pub fn chroma_offset_l0(&self, i: usize, j: usize, wp_offset_half_range_c: i32) -> Option { + let e = self.entries_l0.get(i)?; + if !e.chroma_weight_flag { + return Some(0); + } + let delta_off = *e.delta_chroma_offset.get(j)?; + let chroma_w = self.chroma_weight_value(true, *e.delta_chroma_weight.get(j)?); + Some(chroma_offset_eq_7_58( + wp_offset_half_range_c, + delta_off, + chroma_w, + self.chroma_log2_weight_denom(), + )) + } + + /// `ChromaOffsetL1[i][j]` per §7.4.7.3 equation 7-58. + pub fn chroma_offset_l1(&self, i: usize, j: usize, wp_offset_half_range_c: i32) -> Option { + let e = self.entries_l1.get(i)?; + if !e.chroma_weight_flag { + return Some(0); + } + let delta_off = *e.delta_chroma_offset.get(j)?; + let chroma_w = self.chroma_weight_value(true, *e.delta_chroma_weight.get(j)?); + Some(chroma_offset_eq_7_58( + wp_offset_half_range_c, + delta_off, + chroma_w, + self.chroma_log2_weight_denom(), + )) + } + + fn luma_weight_value(&self, flag: bool, delta: i32) -> i32 { + let base = 1i32 << self.luma_log2_weight_denom; + if flag { + base + delta + } else { + base + } + } + + fn chroma_weight_value(&self, flag: bool, delta: i32) -> i32 { + let base = 1i32 << self.chroma_log2_weight_denom(); + if flag { + base + delta + } else { + base + } + } +} + +/// Verify the caller-supplied per-i gate slice has the expected length. +fn validate_signal_slice( + field: &'static str, + slice: Option<&[bool]>, + expected: usize, +) -> Result<(), SliceError> { + match slice { + None => Ok(()), + Some(s) if s.len() == expected => Ok(()), + Some(s) => Err(SliceError::ValueOutOfRange { + field, + got: s.len() as i64, + }), + } +} + +/// Parse one per-list (L0 or L1) sub-block of §7.3.6.3. +#[allow(clippy::too_many_arguments)] +fn parse_pred_weight_list( + br: &mut BitReader<'_>, + n: usize, + chroma_present: bool, + signal_luma: Option<&[bool]>, + signal_chroma: Option<&[bool]>, + wp_off_half_y: i32, + wp_off_half_c: i32, + list_tag: &'static str, +) -> Result, SliceError> { + let mut entries: Vec = (0..n).map(|_| PredWeightEntry::default()).collect(); + + // Luma flag pass. + for (i, e) in entries.iter_mut().enumerate() { + let signalled = signal_luma.map(|s| s[i]).unwrap_or(true); + e.luma_weight_flag = if signalled { br.u1()? != 0 } else { false }; + } + + // Chroma flag pass — present only when ChromaArrayType != 0. + if chroma_present { + for (i, e) in entries.iter_mut().enumerate() { + let signalled = signal_chroma.map(|s| s[i]).unwrap_or(true); + e.chroma_weight_flag = if signalled { br.u1()? != 0 } else { false }; + } + } + + // Per-reference delta block. + for (i, e) in entries.iter_mut().enumerate() { + if e.luma_weight_flag { + let d = br.se()?; + if !(-128..=127).contains(&d) { + return Err(SliceError::ValueOutOfRange { + field: if list_tag == "l0" { + "delta_luma_weight_l0" + } else { + "delta_luma_weight_l1" + }, + got: d as i64, + }); + } + e.delta_luma_weight = d; + + let off = br.se()?; + if off < -wp_off_half_y || off > wp_off_half_y - 1 { + return Err(SliceError::ValueOutOfRange { + field: if list_tag == "l0" { + "luma_offset_l0" + } else { + "luma_offset_l1" + }, + got: off as i64, + }); + } + e.luma_offset = off; + } + if e.chroma_weight_flag { + for j in 0..2 { + let d = br.se()?; + if !(-128..=127).contains(&d) { + return Err(SliceError::ValueOutOfRange { + field: if list_tag == "l0" { + "delta_chroma_weight_l0" + } else { + "delta_chroma_weight_l1" + }, + got: d as i64, + }); + } + e.delta_chroma_weight[j] = d; + + let off = br.se()?; + if off < -4 * wp_off_half_c || off > 4 * wp_off_half_c - 1 { + return Err(SliceError::ValueOutOfRange { + field: if list_tag == "l0" { + "delta_chroma_offset_l0" + } else { + "delta_chroma_offset_l1" + }, + got: off as i64, + }); + } + e.delta_chroma_offset[j] = off; + } + } + let _ = i; // silence the unused-`i` when iter_mut().enumerate() is mixed with explicit loop + } + + Ok(entries) +} + +/// §7.4.7.3 closing summand: +/// `sumWeightLXFlags = Σ luma_weight_lX_flag[i] + 2 * chroma_weight_lX_flag[i]`. +fn sum_weight_flags(entries: &[PredWeightEntry]) -> u32 { + entries + .iter() + .map(|e| u32::from(e.luma_weight_flag) + 2 * u32::from(e.chroma_weight_flag)) + .sum() +} + +/// §7.4.7.3 equation 7-58 for `ChromaOffsetLX[i][j]`. Extracted as a +/// free function so [`PredWeightTable::chroma_offset_l0`] / +/// [`PredWeightTable::chroma_offset_l1`] share the implementation. +fn chroma_offset_eq_7_58( + wp_off_half_c: i32, + delta_chroma_offset: i32, + chroma_weight: i32, + chroma_log2_weight_denom: u8, +) -> i32 { + let raw = wp_off_half_c + delta_chroma_offset + - ((wp_off_half_c * chroma_weight) >> chroma_log2_weight_denom); + raw.clamp(-wp_off_half_c, wp_off_half_c - 1) +} + +/// Parsed slice segment header per §7.3.6.1. +/// +/// Fields that this round defers (the non-IDR POC/RPS block, the P/B +/// reference-list / weighted-prediction sub-structures) are absent from +/// the materialised struct; when one of those points is reached the +/// remainder of the header is surfaced via [`Self::opaque_tail`] and +/// the corresponding `Option` fields stay `None`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SliceSegmentHeader { + /// `first_slice_segment_in_pic_flag`. + pub first_slice_segment_in_pic_flag: bool, + /// `no_output_of_prior_pics_flag`. `None` when not present (the NAL + /// unit is not an IRAP picture). + pub no_output_of_prior_pics_flag: Option, + /// `slice_pic_parameter_set_id` (`ue(v)`, range 0..=63). + pub slice_pic_parameter_set_id: u8, + /// `dependent_slice_segment_flag`. Inferred to false when the slice + /// is the first segment of the picture or when + /// `dependent_slice_segments_enabled_flag` is 0 (§7.4.7.1). + pub dependent_slice_segment_flag: bool, + /// `slice_segment_address` (`u(v)`). Inferred to 0 when not present + /// (the first slice segment of the picture). + pub slice_segment_address: u32, + /// `slice_reserved_flag[]` — `num_extra_slice_header_bits` raw + /// flags. Decoders ignore the value; carried for completeness. + /// Empty for dependent slice segments and when the count is 0. + pub slice_reserved_flags: Vec, + /// `slice_type` per Table 7-7. `None` for dependent slice segments + /// (the value is inherited from the associated independent slice + /// segment, which this struct does not resolve). + pub slice_type: Option, + /// `pic_output_flag`. Inferred to true when not present (§7.4.7.1). + pub pic_output_flag: bool, + /// `colour_plane_id` (`u(2)`). `None` when not present + /// (`separate_colour_plane_flag == 0`). + pub colour_plane_id: Option, + /// `slice_pic_order_cnt_lsb` (`u(v)`, width + /// `log2_max_pic_order_cnt_lsb_minus4 + 4` bits). `None` when the + /// current NAL unit is an IDR — IDR pictures have no slice POC LSB + /// (the POC is reset to 0 per §8.3.1) — or when the parser stopped + /// at the deferred P/B body before reaching this point. + pub slice_pic_order_cnt_lsb: Option, + /// `short_term_ref_pic_set_sps_flag`. `None` for IDR slices and + /// for headers that stopped before this point. + pub short_term_ref_pic_set_sps_flag: Option, + /// In-line `st_ref_pic_set(num_short_term_ref_pic_sets)` parsed from + /// the slice header itself (only when + /// `short_term_ref_pic_set_sps_flag == 0`). + pub inline_short_term_ref_pic_set: Option, + /// `short_term_ref_pic_set_idx` (`u(v)`, width + /// `Ceil(Log2(num_short_term_ref_pic_sets))`). `None` when the SPS + /// in-line form is used, when `num_short_term_ref_pic_sets <= 1` + /// (the value is inferred to 0), or for IDR slices. + pub short_term_ref_pic_set_idx: Option, + /// `num_long_term_sps` (`ue(v)`). `None` when the long-term-ref-pic + /// block is absent (no `long_term_ref_pics_present_flag` on the SPS + /// or IDR slice); 0 (with the SPS gate satisfied but + /// `num_long_term_ref_pics_sps == 0`). + pub num_long_term_sps: Option, + /// `num_long_term_pics` (`ue(v)`). `None` when the long-term-ref-pic + /// block is absent. + pub num_long_term_pics: Option, + /// Per-entry long-term ref pic block (§7.3.6.1), length + /// `num_long_term_sps + num_long_term_pics`. Empty when the block + /// is absent. + pub long_term_ref_pics: Vec, + /// `slice_temporal_mvp_enabled_flag`. Inferred to false when not + /// present (`sps_temporal_mvp_enabled_flag == 0`) (§7.4.7.1). + pub slice_temporal_mvp_enabled_flag: bool, + /// `slice_sao_luma_flag`. Inferred to false when not present + /// (`sample_adaptive_offset_enabled_flag == 0`). + pub slice_sao_luma_flag: bool, + /// `slice_sao_chroma_flag`. Inferred to false when not present. + pub slice_sao_chroma_flag: bool, + /// `num_ref_idx_active_override_flag` (§7.3.6.1). `None` for I + /// slices (the field is absent — `slice_type == 2`) and for + /// dependent slice segments. Read as `u(1)` immediately after the + /// SAO block for P / B slices. + pub num_ref_idx_active_override_flag: Option, + /// `num_ref_idx_l0_active_minus1` (§7.3.6.1, range 0..=14). For P + /// / B slices, signalled when `num_ref_idx_active_override_flag == + /// 1` and otherwise inferred to `pps.num_ref_idx_l0_default_active_ + /// minus1` per §7.4.7.1. `None` when the slice is I or the parser + /// stopped before reaching this point. + pub num_ref_idx_l0_active_minus1: Option, + /// `num_ref_idx_l1_active_minus1` (§7.3.6.1, range 0..=14). For B + /// slices, signalled when `num_ref_idx_active_override_flag == 1` + /// and otherwise inferred to `pps.num_ref_idx_l1_default_active_ + /// minus1` per §7.4.7.1. `None` when the slice is not B or the + /// parser stopped before reaching this point. + pub num_ref_idx_l1_active_minus1: Option, + /// `mvd_l1_zero_flag` (§7.3.6.1). `u(1)`, present only for B slices. + /// `None` for I / P slices, dependent slice segments, and headers + /// whose parse stopped before the inter-slice mvd block (either at + /// the `ref_pic_lists_modification()` gate when + /// `pps.lists_modification_present_flag == 1`, or at any earlier + /// deferral point). + pub mvd_l1_zero_flag: Option, + /// `cabac_init_flag` (§7.3.6.1). `u(1)`, present only when + /// `pps.cabac_init_present_flag == 1`; inferred to `false` + /// otherwise per §7.4.7.1. `None` for I slices, dependent slice + /// segments, and headers whose parse stopped before the inter-slice + /// cabac-init point. + pub cabac_init_flag: Option, + /// `collocated_from_l0_flag` (§7.3.6.1). `u(1)`, present only when + /// `slice_temporal_mvp_enabled_flag == 1 && slice_type == B`. + /// Inferred to `true` when absent (per §7.4.7.1, "When + /// `collocated_from_l0_flag` is not present, it is inferred to be + /// equal to 1"). `None` when the slice is I, when the parse + /// stopped before this point, or when + /// `slice_temporal_mvp_enabled_flag == 0` (the field has no + /// meaning). + pub collocated_from_l0_flag: Option, + /// `collocated_ref_idx` (§7.3.6.1). `ue(v)`, present only when + /// `slice_temporal_mvp_enabled_flag == 1` and the relevant active + /// list has more than one entry (specifically: + /// `(collocated_from_l0_flag && num_ref_idx_l0_active_minus1 > 0) + /// || (!collocated_from_l0_flag && num_ref_idx_l1_active_minus1 > + /// 0)`). Inferred to `0` when absent per §7.4.7.1. `None` when the + /// slice is I, when the parse stopped before this point, or when + /// `slice_temporal_mvp_enabled_flag == 0`. + pub collocated_ref_idx: Option, + /// `five_minus_max_num_merge_cand` (§7.3.6.1). `ue(v)`, present only + /// for P/B slices, immediately after the optional + /// `pred_weight_table()`. §7.4.7.1: the derived + /// `MaxNumMergeCand = 5 - five_minus_max_num_merge_cand` shall be in + /// the range 1..=5 — i.e. the wire value is in 0..=4. `None` for I + /// slices, dependent slice segments, and headers whose parse stopped + /// before this point (currently: the parse defers at the + /// `pred_weight_table()` gate when either + /// `pps.weighted_pred_flag && slice_type == P` or + /// `pps.weighted_bipred_flag && slice_type == B` is true). + pub five_minus_max_num_merge_cand: Option, + /// `use_integer_mv_flag` (§7.3.6.1) — present for P/B slices when + /// the SPS SCC `motion_vector_resolution_control_idc == 2`; + /// otherwise inferred equal to + /// `motion_vector_resolution_control_idc` (§7.4.7.1). When 1, + /// motion vectors of this slice referring to pictures other than + /// the current picture use integer resolution (eqs 8-98..8-101 / + /// 8-124..8-125). + pub use_integer_mv_flag: bool, + /// Decoded `pred_weight_table()` (§7.3.6.3) when the §7.3.6.1 outer + /// gate is statically present + /// (`(pps.weighted_pred_flag && slice_type == P) || + /// (pps.weighted_bipred_flag && slice_type == B)`). `None` when the + /// outer gate is statically absent (the table is not signalled), for + /// I slices, for dependent slice segments, and for headers whose + /// parse stopped before this point. + /// + /// The in-place call uses the base-profile single-layer assumption + /// for every per-i §7.3.6.3 outer-gate decision (universally `true`) + /// — see [`PredWeightTableInputs::base_profile`]. Single-layer base + /// profile is the only configuration this crate currently surfaces; + /// the multilayer Annex F / SCC self-reference cases need the SPS + /// range / multilayer / SCC extensions and the DPB to be wired up, + /// at which point the in-place call site here will be widened to + /// thread per-i gate decisions through. + pub pred_weight_table: Option, + /// `slice_qp_delta` (`se(v)`). `None` when the parser stopped before + /// reaching it (a deferred non-IDR or P/B body). + pub slice_qp_delta: Option, + /// `slice_cb_qp_offset` (`se(v)`, range −12..=12). Inferred to 0 + /// when not present (`pps_slice_chroma_qp_offsets_present_flag == 0`). + pub slice_cb_qp_offset: i8, + /// `slice_cr_qp_offset` (`se(v)`, range −12..=12). Inferred to 0 + /// when not present. + pub slice_cr_qp_offset: i8, + /// `slice_act_y_qp_offset` (`se(v)`, §7.3.6.1). Present only when + /// `pps_slice_act_qp_offsets_present_flag` (the SCC PPS body); + /// inferred to 0 otherwise. §7.4.7.1 bounds + /// `PpsActQpOffsetY + slice_act_y_qp_offset` to −12..=12. + pub slice_act_y_qp_offset: i32, + /// `slice_act_cb_qp_offset` (`se(v)`, §7.3.6.1). Present only when + /// `pps_slice_act_qp_offsets_present_flag`; inferred to 0 otherwise. + pub slice_act_cb_qp_offset: i32, + /// `slice_act_cr_qp_offset` (`se(v)`, §7.3.6.1). Present only when + /// `pps_slice_act_qp_offsets_present_flag`; inferred to 0 otherwise. + pub slice_act_cr_qp_offset: i32, + /// `cu_chroma_qp_offset_enabled_flag` (`u(1)`, §7.3.6.1). Present + /// only when the range-extension `chroma_qp_offset_list_enabled_flag` + /// is set; inferred to 0 otherwise. + pub cu_chroma_qp_offset_enabled_flag: bool, + /// Deblocking-filter values, carrying the §7.4.7.1 inferred + /// defaults when the slice override block is absent. `None` when + /// the parser stopped before this point. + pub deblocking: Option, + /// `slice_loop_filter_across_slices_enabled_flag`. Inferred to + /// `pps_loop_filter_across_slices_enabled_flag` when not present. + /// `None` when the parser stopped before this point. + pub slice_loop_filter_across_slices_enabled_flag: Option, + /// Entry-point-offset block. `None` when neither tiles nor + /// entropy-coding-sync are enabled (the block is absent), or when + /// the parser stopped before this point. + pub entry_point_offsets: Option, + /// `slice_segment_header_extension_length` (`ue(v)`). `None` when + /// `slice_segment_header_extension_present_flag == 0` or the parser + /// stopped before this point. + pub slice_segment_header_extension_length: Option, + /// Byte offset, from the start of the RBSP, of the first byte of + /// `slice_segment_data()` — i.e. the position immediately after + /// `byte_alignment()`. `None` when the header was not parsed all + /// the way to `byte_alignment()` (a deferred body). + pub byte_offset_to_slice_data: Option, + /// Decoded `ref_pic_lists_modification()` (§7.3.6.2) when the + /// §7.3.6.1 outer gate + /// (`pps.lists_modification_present_flag == 1 && NumPicTotalCurr > 1`) + /// is statically present. `None` when the gate is statically + /// absent (`pps.lists_modification_present_flag == 0`, + /// `NumPicTotalCurr <= 1`, an I slice, a dependent slice segment, + /// or a header whose parse stopped before this point — including + /// the inter-RPS-predicted SPS-form short-term RPS case, where + /// the per-position `UsedByCurrPicS0` / `UsedByCurrPicS1` flags + /// needed for the §7.4.7.2 `NumPicTotalCurr` derivation can only + /// be resolved by running the §7.4.8 inter-RPS-prediction step; + /// the parser defers in that case and surfaces an + /// [`Self::opaque_tail`] starting at the `ref_pic_lists_modification()` + /// bit position). + pub ref_pic_lists_modification: Option, + /// Opaque suffix of the slice-header RBSP. Populated when the + /// parser reaches a deferred body (the non-IDR POC/RPS block or a + /// P/B reference-list / weighted-prediction sub-structure); carries + /// the still-unparsed RBSP bytes and the start-bit offset. `None` + /// when the header was parsed to completion. + pub opaque_tail: Option, +} + +impl SliceSegmentHeader { + /// Parse `slice_segment_header()` from the first bit of the + /// (already-unescaped) slice-segment-layer RBSP body — i.e. after + /// the two-byte NAL header has been removed (see + /// [`crate::nal::NalUnit`]). + /// + /// * `nal_unit_type` is the value from the NAL header; it gates + /// both `no_output_of_prior_pics_flag` (IRAP range) and the + /// non-IDR POC/RPS block. + /// * `sps` is the activated SPS, `pps` the activated PPS. The + /// caller resolves `slice_pic_parameter_set_id` to the right PPS + /// and that PPS's `pps_seq_parameter_set_id` to the right SPS; + /// this parser uses the supplied pair for the field widths and + /// presence gates. + pub fn parse( + rbsp: &[u8], + nal_unit_type: u8, + sps: &SeqParameterSet, + pps: &PicParameterSet, + ) -> Result { + let mut br = BitReader::new(rbsp); + + let first_slice_segment_in_pic_flag = br.u1()? != 0; + + let no_output_of_prior_pics_flag = if (BLA_W_LP..=RSV_IRAP_VCL23).contains(&nal_unit_type) { + Some(br.u1()? != 0) + } else { + None + }; + + let slice_pic_parameter_set_id = br.ue()?; + if slice_pic_parameter_set_id > 63 { + return Err(SliceError::ValueOutOfRange { + field: "slice_pic_parameter_set_id", + got: slice_pic_parameter_set_id as i64, + }); + } + let slice_pic_parameter_set_id = slice_pic_parameter_set_id as u8; + + // §7.3.6.1: dependent_slice_segment_flag / slice_segment_address + // only appear for non-first slice segments. + let mut dependent_slice_segment_flag = false; + let mut slice_segment_address = 0u32; + if !first_slice_segment_in_pic_flag { + if pps.dependent_slice_segments_enabled_flag { + dependent_slice_segment_flag = br.u1()? != 0; + } + // slice_segment_address width is Ceil( Log2( PicSizeInCtbsY ) ) + // bits (§7.4.7.1). + let addr_bits = ceil_log2(pic_size_in_ctbs_y(sps)); + slice_segment_address = br.u(addr_bits)?; + if slice_segment_address >= pic_size_in_ctbs_y(sps) { + return Err(SliceError::ValueOutOfRange { + field: "slice_segment_address", + got: slice_segment_address as i64, + }); + } + } + + // Defaults / inferences (§7.4.7.1). + let mut slice_reserved_flags = Vec::new(); + let mut slice_type = None; + let mut pic_output_flag = true; + let mut colour_plane_id = None; + let mut slice_pic_order_cnt_lsb: Option = None; + let mut short_term_ref_pic_set_sps_flag: Option = None; + let mut inline_short_term_ref_pic_set: Option = None; + let mut short_term_ref_pic_set_idx: Option = None; + let mut num_long_term_sps: Option = None; + let mut num_long_term_pics: Option = None; + let mut long_term_ref_pics: Vec = Vec::new(); + let mut slice_temporal_mvp_enabled_flag = false; + + if !dependent_slice_segment_flag { + for _ in 0..pps.num_extra_slice_header_bits { + slice_reserved_flags.push(br.u1()? != 0); + } + let st = SliceType::from_raw(br.ue()?)?; + slice_type = Some(st); + + if pps.output_flag_present_flag { + pic_output_flag = br.u1()? != 0; + } + + if sps.separate_colour_plane_flag { + let id = br.u(2)? as u8; + colour_plane_id = Some(id); + } + + // Non-IDR POC + reference-picture-set block (§7.3.6.1). + let is_idr = nal_unit_type == IDR_W_RADL || nal_unit_type == IDR_N_LP; + if !is_idr { + // slice_pic_order_cnt_lsb u(v), width log2_max_poc_lsb_minus4+4. + let poc_lsb_bits = sps.log2_max_pic_order_cnt_lsb_minus4 + 4; + let poc_lsb = br.u(poc_lsb_bits)?; + if poc_lsb >= sps.max_pic_order_cnt_lsb() { + return Err(SliceError::ValueOutOfRange { + field: "slice_pic_order_cnt_lsb", + got: poc_lsb as i64, + }); + } + slice_pic_order_cnt_lsb = Some(poc_lsb); + + // short_term_ref_pic_set_sps_flag u(1). + let st_sps_flag = br.u1()? != 0; + short_term_ref_pic_set_sps_flag = Some(st_sps_flag); + if st_sps_flag && sps.num_short_term_ref_pic_sets == 0 { + // §7.4.7.1: when num_short_term_ref_pic_sets == 0, + // short_term_ref_pic_set_sps_flag shall be 0. + return Err(SliceError::ValueOutOfRange { + field: "short_term_ref_pic_set_sps_flag", + got: 1, + }); + } + + if !st_sps_flag { + let inline = ShortTermRefPicSet::parse_slice_inline(&mut br, sps)?; + inline_short_term_ref_pic_set = Some(inline); + } else if sps.num_short_term_ref_pic_sets > 1 { + let idx_bits = ceil_log2(sps.num_short_term_ref_pic_sets); + let idx = br.u(idx_bits)?; + if idx >= sps.num_short_term_ref_pic_sets { + return Err(SliceError::ValueOutOfRange { + field: "short_term_ref_pic_set_idx", + got: idx as i64, + }); + } + short_term_ref_pic_set_idx = Some(idx); + } + // else: short_term_ref_pic_set_idx is inferred to 0 + // (and left as None in the struct to signal "absent"). + + if sps.long_term_ref_pics_present_flag { + let (nl_sps, nl_pics, entries) = parse_long_term_ref_pic_block(&mut br, sps)?; + num_long_term_sps = Some(nl_sps); + num_long_term_pics = Some(nl_pics); + long_term_ref_pics = entries; + } + // §7.3.6.1: slice_temporal_mvp_enabled_flag is signalled + // inside the non-IDR block — an IDR picture never + // carries it and §7.4.7.1 infers it to 0. + if sps.sps_temporal_mvp_enabled_flag { + slice_temporal_mvp_enabled_flag = br.u1()? != 0; + } + } + } + + // SAO block (§7.3.6.1) — inside the !dependent gate: a dependent + // slice segment inherits the SAO flags from the associated + // independent slice segment and does not re-signal them. + let mut slice_sao_luma_flag = false; + let mut slice_sao_chroma_flag = false; + if !dependent_slice_segment_flag && sps.sample_adaptive_offset_enabled_flag { + slice_sao_luma_flag = br.u1()? != 0; + if chroma_array_type(sps) != 0 { + slice_sao_chroma_flag = br.u1()? != 0; + } + } + + // The remaining body lives inside the !dependent gate. For a + // dependent slice segment the header ends after the SAO block, + // before byte_alignment() (the rest of the header is inherited). + if dependent_slice_segment_flag { + // §7.3.6.1: the entry-point block and the header-extension + // block sit OUTSIDE the !dependent gate — a dependent slice + // segment signals its own substream entry points. + let entry_point_offsets = parse_entry_point_offsets(&mut br, sps, pps)?; + let slice_segment_header_extension_length = parse_header_extension(&mut br, pps)?; + let byte_offset = consume_byte_alignment(&mut br)?; + return Ok(Self { + first_slice_segment_in_pic_flag, + no_output_of_prior_pics_flag, + slice_pic_parameter_set_id, + dependent_slice_segment_flag, + slice_segment_address, + slice_reserved_flags, + slice_type, + pic_output_flag, + colour_plane_id, + slice_pic_order_cnt_lsb: None, + short_term_ref_pic_set_sps_flag: None, + inline_short_term_ref_pic_set: None, + short_term_ref_pic_set_idx: None, + num_long_term_sps: None, + num_long_term_pics: None, + long_term_ref_pics: Vec::new(), + slice_temporal_mvp_enabled_flag, + slice_sao_luma_flag, + slice_sao_chroma_flag, + num_ref_idx_active_override_flag: None, + num_ref_idx_l0_active_minus1: None, + num_ref_idx_l1_active_minus1: None, + mvd_l1_zero_flag: None, + cabac_init_flag: None, + collocated_from_l0_flag: None, + collocated_ref_idx: None, + five_minus_max_num_merge_cand: None, + use_integer_mv_flag: false, + pred_weight_table: None, + slice_qp_delta: None, + slice_cb_qp_offset: 0, + slice_cr_qp_offset: 0, + slice_act_y_qp_offset: 0, + slice_act_cb_qp_offset: 0, + slice_act_cr_qp_offset: 0, + cu_chroma_qp_offset_enabled_flag: false, + deblocking: None, + slice_loop_filter_across_slices_enabled_flag: None, + entry_point_offsets, + slice_segment_header_extension_length, + byte_offset_to_slice_data: Some(byte_offset), + ref_pic_lists_modification: None, + opaque_tail: None, + }); + } + + // §7.3.6.1: for P / B slices, the SAO block is immediately + // followed by the `num_ref_idx_active_override_flag` / + // `num_ref_idx_lX_active_minus1` block. This is the in-place + // prerequisite for the later `ref_pic_lists_modification()` + // call (its `list_entry_lX[]` loop indexes `0..= + // num_ref_idx_lX_active_minus1`). The §7.4.7.1 inference rule + // fills both `num_ref_idx_lX_active_minus1` values from the PPS + // defaults when the override flag is 0; both values are capped + // at 14. + let st = slice_type.expect("independent slice has a slice_type"); + let ( + num_ref_idx_active_override_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + ) = if st.is_inter() { + let override_flag = br.u1()? != 0; + let (n0, n1) = if override_flag { + let n0 = br.ue()?; + if n0 > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: n0 as i64, + }); + } + let n1 = if matches!(st, SliceType::B) { + let v = br.ue()?; + if v > 14 { + return Err(SliceError::ValueOutOfRange { + field: "num_ref_idx_l1_active_minus1", + got: v as i64, + }); + } + Some(v as u8) + } else { + None + }; + (n0 as u8, n1) + } else { + // §7.4.7.1 inference defaults from the PPS. + let n1 = if matches!(st, SliceType::B) { + Some(pps.num_ref_idx_l1_default_active_minus1) + } else { + None + }; + (pps.num_ref_idx_l0_default_active_minus1, n1) + }; + (Some(override_flag), Some(n0), n1) + } else { + (None, None, None) + }; + + // §7.3.6.1 inter-slice continuation: after the + // `num_ref_idx_active_override_flag` block, the spec emits + // if( lists_modification_present_flag && NumPicTotalCurr > 1 ) + // ref_pic_lists_modification( ) + // if( slice_type == B ) mvd_l1_zero_flag u(1) + // if( cabac_init_present_flag ) cabac_init_flag u(1) + // if( slice_temporal_mvp_enabled_flag ) { + // if( slice_type == B ) collocated_from_l0_flag u(1) (else inferred 1, §7.4.7.1) + // if( ( collocated_from_l0_flag && num_ref_idx_l0_active_minus1 > 0 ) || + // ( !collocated_from_l0_flag && num_ref_idx_l1_active_minus1 > 0 ) ) + // collocated_ref_idx ue(v) (else inferred 0) + // } + // followed by the weighted-pred-table gate. + // + // The `ref_pic_lists_modification()` gate consumes the + // §7.4.7.2 `NumPicTotalCurr` derivation (equation 7-57). When + // `pps.lists_modification_present_flag == 0` the + // `if(... && NumPicTotalCurr > 1)` short-circuit applies + // without needing the derivation, so the bit stream advances + // straight to `mvd_l1_zero_flag`. When the flag is 1 we attempt + // to derive `NumPicTotalCurr` from the resolved slice-header + // state (active short-term RPS + long-term entries): + // + // * For the inline-form short-term RPS + // (`short_term_ref_pic_set_sps_flag == 0`) the on-wire form + // per §7.4.8 has `inter_ref_pic_set_prediction_flag == 0` + // when `stRpsIdx == num_short_term_ref_pic_sets` (the + // slice-inline index): the `used_by_curr_pic_s{0,1}_flag` + // arrays come directly from the inline RPS. The §7.4.8 form + // *is* allowed at the slice-inline index when the SPS has + // `num_short_term_ref_pic_sets > 0`; in that case the parser + // defers (the derivation requires walking the source RPS + // chain and is out of scope here). + // * For the SPS-form (`short_term_ref_pic_set_sps_flag == 1`) + // the active RPS is `sps.short_term_ref_pic_sets[idx]`. When + // that RPS uses the explicit form the per-position + // `used_by_curr_pic_sX_flag` arrays are usable directly; when + // it uses inter-prediction the §7.4.8 derivation must be run + // first and the parser defers. + // + // The §F.7.4.7.2 multilayer-extension variant and the + // SCC `pps_curr_pic_ref_enabled_flag` closing-clause are wired + // through [`NumPicTotalCurrInputs`] but the base-profile call + // site here leaves both at their `false` defaults (the PPS + // SCC extension is not yet surfaced; multilayer extension is + // forwarded via the long-term-ref builder). + // + // For IDR slices the entire non-IDR POC/RPS block is absent + // and `inline_short_term_ref_pic_set` / `long_term_ref_pics` + // are empty: `NumPicTotalCurr` is `0` and the gate is + // statically false. + let (ref_pic_lists_modification, num_pic_total_curr_resolved) = if st.is_inter() + && pps.lists_modification_present_flag + { + match resolve_active_short_term_rps( + sps, + short_term_ref_pic_set_sps_flag, + inline_short_term_ref_pic_set.as_ref(), + short_term_ref_pic_set_idx, + ) { + ActiveShortTermRps::Materialized(m) => { + let lt_used = collect_used_by_curr_pic_lt(&long_term_ref_pics, sps); + let inputs = NumPicTotalCurrInputs::from_used_flags( + &m.used_by_curr_pic_s0, + &m.used_by_curr_pic_s1, + <_used, + ); + let npc = inputs.compute(); + if npc > 1 { + let l0_active = + num_ref_idx_l0_active_minus1.ok_or(SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: -1, + })?; + let l1_active = num_ref_idx_l1_active_minus1.unwrap_or(0); + let rplm = + RefPicListsModification::parse(&mut br, st, l0_active, l1_active, npc)?; + (Some(rplm), Some(npc)) + } else { + // `NumPicTotalCurr <= 1` — the §7.3.6.1 + // gate is statically false; the structure + // is not signalled and we continue at + // `mvd_l1_zero_flag`. + (None, Some(npc)) + } + } + ActiveShortTermRps::Empty => { + // IDR or no RPS picked: `NumPicTotalCurr == 0`, + // gate is statically false. + (None, Some(0)) + } + ActiveShortTermRps::MaterializeFailed => { + // §7.4.8 derivation could not run (malformed + // `RefRpsIdx` chain or array-length mismatch); + // defer to opaque tail so the caller can salvage + // the rest of the bitstream. + return Ok(Self { + first_slice_segment_in_pic_flag, + no_output_of_prior_pics_flag, + slice_pic_parameter_set_id, + dependent_slice_segment_flag, + slice_segment_address, + slice_reserved_flags, + slice_type, + pic_output_flag, + colour_plane_id, + slice_pic_order_cnt_lsb, + short_term_ref_pic_set_sps_flag, + inline_short_term_ref_pic_set, + short_term_ref_pic_set_idx, + num_long_term_sps, + num_long_term_pics, + long_term_ref_pics, + slice_temporal_mvp_enabled_flag, + slice_sao_luma_flag, + slice_sao_chroma_flag, + num_ref_idx_active_override_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + mvd_l1_zero_flag: None, + cabac_init_flag: None, + collocated_from_l0_flag: None, + collocated_ref_idx: None, + five_minus_max_num_merge_cand: None, + use_integer_mv_flag: false, + pred_weight_table: None, + slice_qp_delta: None, + slice_cb_qp_offset: 0, + slice_cr_qp_offset: 0, + slice_act_y_qp_offset: 0, + slice_act_cb_qp_offset: 0, + slice_act_cr_qp_offset: 0, + cu_chroma_qp_offset_enabled_flag: false, + deblocking: None, + slice_loop_filter_across_slices_enabled_flag: None, + entry_point_offsets: None, + slice_segment_header_extension_length: None, + byte_offset_to_slice_data: None, + ref_pic_lists_modification: None, + opaque_tail: Some(OpaqueTail::capture_at(br.bit_pos(), rbsp)), + }); + } + } + } else { + (None, None) + }; + // `num_pic_total_curr_resolved` is currently only used to gate + // the in-place RPLM parse above; future rounds may surface it + // on the slice header (the §8.3.4 implicit reference-list + // derivation needs the same value). + let _ = num_pic_total_curr_resolved; + + // §7.3.6.1 inter-slice mvd / cabac-init / collocated block — + // reached only when `slice_type` is P or B and the + // `ref_pic_lists_modification()` block is statically absent + // (`pps.lists_modification_present_flag == 0`, which makes the + // §7.3.6.1 outer `if(... && NumPicTotalCurr > 1)` false + // unconditionally). For an I slice the entire block is absent + // and the four fields stay `None`. + let (mvd_l1_zero_flag, cabac_init_flag, collocated_from_l0_flag, collocated_ref_idx) = + if st.is_inter() { + // §7.3.6.1 `if( slice_type == B ) mvd_l1_zero_flag u(1)`. + let mvd_l1_zero = if matches!(st, SliceType::B) { + Some(br.u1()? != 0) + } else { + None + }; + + // §7.3.6.1 `if( cabac_init_present_flag ) cabac_init_flag + // u(1)`. §7.4.7.1: inferred to 0 when absent. + let cabac_init = if pps.cabac_init_present_flag { + Some(br.u1()? != 0) + } else { + Some(false) + }; + + // §7.3.6.1 temporal-MVP block. + let (coll_from_l0, coll_ref_idx) = if slice_temporal_mvp_enabled_flag { + // `if( slice_type == B ) collocated_from_l0_flag u(1)`, + // else §7.4.7.1 inference to 1. + let from_l0 = if matches!(st, SliceType::B) { + br.u1()? != 0 + } else { + true + }; + + // §7.3.6.1: `collocated_ref_idx` is present iff the + // active list (selected by `collocated_from_l0_flag`) + // has more than one entry. §7.4.7.1: inferred to 0 + // when absent. Both `num_ref_idx_lX_active_minus1` + // values are `Some(_)` at this point (the override + // block populated them for every inter slice, and L1 + // is populated for B slices). + let n0 = num_ref_idx_l0_active_minus1.expect("L0 active populated for inter"); + let needs_ref_idx = if from_l0 { + n0 > 0 + } else { + // !from_l0 implies slice_type == B (an I/P slice + // takes the inferred `true` branch). For a B slice + // L1 is signalled by the override block. + let n1 = num_ref_idx_l1_active_minus1.expect("L1 active populated for B"); + n1 > 0 + }; + let ref_idx = if needs_ref_idx { + let raw = br.ue()?; + let max = if from_l0 { + n0 as u32 + } else { + num_ref_idx_l1_active_minus1.unwrap() as u32 + }; + if raw > max { + return Err(SliceError::ValueOutOfRange { + field: "collocated_ref_idx", + got: raw as i64, + }); + } + raw + } else { + 0 + }; + + (Some(from_l0), Some(ref_idx)) + } else { + (None, None) + }; + + (mvd_l1_zero, cabac_init, coll_from_l0, coll_ref_idx) + } else { + (None, None, None, None) + }; + + // §7.3.6.1 P / B `pred_weight_table()` gate. The table is + // signalled iff either `(weighted_pred_flag && slice_type == P)` + // or `(weighted_bipred_flag && slice_type == B)`. When the gate + // is statically absent the parser walks straight past it into + // the merge-candidate block; when it is present the standalone + // [`PredWeightTable::parse`] is invoked in place with the + // base-profile single-layer assumption (every per-i §7.3.6.3 + // outer gate `true` — see [`PredWeightTableInputs::base_profile`]). + // This is the only single-layer configuration this crate + // currently surfaces: the SPS range / multilayer / SCC + // extensions are not yet wired through, so the bit-depth + // arguments fall back to the SPS `BitDepthY` / `BitDepthC` + // (`WpOffsetHalfRangeY` = `WpOffsetHalfRangeC` = 128 per §7.4.7.3 + // because `high_precision_offsets_enabled_flag` defaults to 0). + // The per-i outer-gate decisions, when needed for the + // multilayer-extension / SCC self-reference cases, will be + // threaded through here once those extensions are surfaced. + let weighted_pred_table_present = (pps.weighted_pred_flag && matches!(st, SliceType::P)) + || (pps.weighted_bipred_flag && matches!(st, SliceType::B)); + let pred_weight_table = if weighted_pred_table_present { + // Resolve the active L0 / L1 cardinalities the table parser + // needs. Both have been populated by the override block + // above (§7.4.7.1 inference fills L0 for P/B and L1 for B + // when override == 0). + let n0 = num_ref_idx_l0_active_minus1.expect("L0 active populated for inter"); + let n1 = if matches!(st, SliceType::B) { + num_ref_idx_l1_active_minus1.expect("L1 active populated for B") + } else { + 0 + }; + let inputs = PredWeightTableInputs::base_profile( + st, + n0, + n1, + chroma_array_type(sps), + sps.bit_depth_luma(), + sps.bit_depth_chroma(), + ); + Some(PredWeightTable::parse(&mut br, &inputs)?) + } else { + None + }; + + // §7.3.6.1 `five_minus_max_num_merge_cand` (ue(v)), signalled + // for every inter slice immediately after the (optional) + // pred_weight_table(). §7.4.7.1 derives + // `MaxNumMergeCand = 5 - five_minus_max_num_merge_cand`, with + // the conformance constraint `1 <= MaxNumMergeCand <= 5` — + // i.e. the wire value lies in 0..=4. The SCC + // `use_integer_mv_flag` (gated on + // `motion_vector_resolution_control_idc == 2`) is statically + // absent because the PPS SCC extension is not surfaced by this + // crate yet (§7.4.7.1: when not present, + // `motion_vector_resolution_control_idc` is inferred to 0). + let five_minus_max_num_merge_cand = if st.is_inter() { + let v = br.ue()?; + if v > 4 { + return Err(SliceError::ValueOutOfRange { + field: "five_minus_max_num_merge_cand", + got: v as i64, + }); + } + Some(v) + } else { + None + }; + + // §7.3.6.1: use_integer_mv_flag is present for inter slices + // when motion_vector_resolution_control_idc == 2; otherwise + // §7.4.7.1 infers it equal to the idc value. + let mv_res_idc = sps + .sps_scc_extension + .as_ref() + .map_or(0, |s| s.motion_vector_resolution_control_idc); + let use_integer_mv_flag = if st.is_inter() && mv_res_idc == 2 { + br.u1()? != 0 + } else { + mv_res_idc == 1 + }; + + // Slice QP / chroma QP / deblocking / loop-filter / entry-points + // tail (§7.3.6.1) — shared by I, P and B independent slice + // segments. + let slice_qp_delta = br.se()?; + + let mut slice_cb_qp_offset = 0i8; + let mut slice_cr_qp_offset = 0i8; + if pps.pps_slice_chroma_qp_offsets_present_flag { + slice_cb_qp_offset = parse_qp_offset(&mut br, "slice_cb_qp_offset")?; + slice_cr_qp_offset = parse_qp_offset(&mut br, "slice_cr_qp_offset")?; + } + + // SCC adaptive-colour-transform per-slice QP offsets (§7.3.6.1), + // present only when the SCC PPS body set + // `pps_slice_act_qp_offsets_present_flag`. §7.4.7.1 bounds the + // sum `PpsActQpOffset{Y,Cb,Cr} + slice_act_{y,cb,cr}_qp_offset` + // to −12..=12; the per-element offsets themselves are se(v) with + // no independent bound, so the conformance check is applied to + // the combined value using the PPS-level offsets. + let mut slice_act_y_qp_offset = 0i32; + let mut slice_act_cb_qp_offset = 0i32; + let mut slice_act_cr_qp_offset = 0i32; + let pps_slice_act_qp_offsets_present_flag = pps + .pps_scc_extension + .as_ref() + .map(|scc| scc.pps_slice_act_qp_offsets_present_flag) + .unwrap_or(false); + if pps_slice_act_qp_offsets_present_flag { + // The presence of the offsets implies a decoded SCC body. + let scc = pps + .pps_scc_extension + .as_ref() + .expect("pps_slice_act_qp_offsets_present_flag implies SCC body"); + slice_act_y_qp_offset = parse_slice_act_qp_offset( + &mut br, + "slice_act_y_qp_offset", + scc.pps_act_qp_offset_y(), + )?; + slice_act_cb_qp_offset = parse_slice_act_qp_offset( + &mut br, + "slice_act_cb_qp_offset", + scc.pps_act_qp_offset_cb(), + )?; + slice_act_cr_qp_offset = parse_slice_act_qp_offset( + &mut br, + "slice_act_cr_qp_offset", + scc.pps_act_qp_offset_cr(), + )?; + } + + // `cu_chroma_qp_offset_enabled_flag` (§7.3.6.1), present only + // when the range-extension `chroma_qp_offset_list_enabled_flag` + // is set; inferred to 0 otherwise (§7.4.7.1). + let chroma_qp_offset_list_enabled_flag = pps + .pps_range_extension + .as_ref() + .map(|re| re.chroma_qp_offset_list_enabled_flag) + .unwrap_or(false); + let cu_chroma_qp_offset_enabled_flag = if chroma_qp_offset_list_enabled_flag { + br.u1()? != 0 + } else { + false + }; + + // Deblocking override (§7.3.6.1). + let deblocking = parse_slice_deblocking(&mut br, pps)?; + + // slice_loop_filter_across_slices_enabled_flag gate (§7.3.6.1). + let slice_loop_filter_across_slices_enabled_flag = if pps + .pps_loop_filter_across_slices_enabled_flag + && (slice_sao_luma_flag || slice_sao_chroma_flag || !deblocking.disabled_flag) + { + br.u1()? != 0 + } else { + pps.pps_loop_filter_across_slices_enabled_flag + }; + + // Entry-point-offset block (§7.3.6.1). §7.4.7.1 bounds + // `num_entry_point_offsets` by the active partitioning: the + // tile count when only `tiles_enabled_flag == 1`, + // `PicHeightInCtbsY` when only + // `entropy_coding_sync_enabled_flag == 1`, and + // `NumTileColumns * PicHeightInCtbsY` when both are 1 + // (wavefronts inside every tile). Each + // `entry_point_offset_minus1[i]` is `offset_len_minus1 + 1` + // bits wide and is read into [`EntryPointOffsets:: + // entry_point_offset_minus1`] (a per-index `Vec`); the + // byte length of subset `i` follows as + // `entry_point_offset_minus1[i] + 1` (§7.4.7.1) and is exposed + // via [`EntryPointOffsets::subset_length`]. + let entry_point_offsets = parse_entry_point_offsets(&mut br, sps, pps)?; + + // Slice-segment-header extension block (§7.3.6.1). + let slice_segment_header_extension_length = parse_header_extension(&mut br, pps)?; + + let byte_offset = consume_byte_alignment(&mut br)?; + + Ok(Self { + first_slice_segment_in_pic_flag, + no_output_of_prior_pics_flag, + slice_pic_parameter_set_id, + dependent_slice_segment_flag, + slice_segment_address, + slice_reserved_flags, + slice_type, + pic_output_flag, + colour_plane_id, + slice_pic_order_cnt_lsb, + short_term_ref_pic_set_sps_flag, + inline_short_term_ref_pic_set, + short_term_ref_pic_set_idx, + num_long_term_sps, + num_long_term_pics, + long_term_ref_pics, + slice_temporal_mvp_enabled_flag, + slice_sao_luma_flag, + slice_sao_chroma_flag, + num_ref_idx_active_override_flag, + num_ref_idx_l0_active_minus1, + num_ref_idx_l1_active_minus1, + mvd_l1_zero_flag, + cabac_init_flag, + collocated_from_l0_flag, + collocated_ref_idx, + five_minus_max_num_merge_cand, + use_integer_mv_flag, + pred_weight_table, + slice_qp_delta: Some(slice_qp_delta), + slice_cb_qp_offset, + slice_cr_qp_offset, + slice_act_y_qp_offset, + slice_act_cb_qp_offset, + slice_act_cr_qp_offset, + cu_chroma_qp_offset_enabled_flag, + deblocking: Some(deblocking), + slice_loop_filter_across_slices_enabled_flag: Some( + slice_loop_filter_across_slices_enabled_flag, + ), + entry_point_offsets, + slice_segment_header_extension_length, + byte_offset_to_slice_data: Some(byte_offset), + ref_pic_lists_modification, + opaque_tail: None, + }) + } + + /// `SliceQpY = 26 + init_qp_minus26 + slice_qp_delta` (equation + /// 7-54). Returns `None` when `slice_qp_delta` was not parsed (a + /// deferred body); `pps` supplies `init_qp_minus26`. + pub fn slice_qp_y(&self, pps: &PicParameterSet) -> Option { + self.slice_qp_delta.map(|d| 26 + pps.init_qp_minus26 + d) + } + + /// `MaxNumMergeCand` per §7.4.7.1 equation 7-53: + /// `MaxNumMergeCand = 5 - five_minus_max_num_merge_cand`. Returns + /// `None` for I slices (the field is absent) and for headers whose + /// parse stopped before the merge-candidate block. The derived + /// value is guaranteed to lie in 1..=5 — `Self::parse` rejects an + /// out-of-range wire value at decode time. + pub fn max_num_merge_cand(&self) -> Option { + self.five_minus_max_num_merge_cand + .map(|v| 5u8.saturating_sub(v as u8)) + } +} + +/// `ChromaArrayType` per §7.4.2.2: equal to `chroma_format_idc` unless +/// `separate_colour_plane_flag == 1`, in which case it is 0. +fn chroma_array_type(sps: &SeqParameterSet) -> u8 { + if sps.separate_colour_plane_flag { + 0 + } else { + sps.chroma_format_idc + } +} + +/// `PicSizeInCtbsY = PicWidthInCtbsY * PicHeightInCtbsY` +/// (equations 7-15/7-17/7-19). `CtbSizeY = 1 << CtbLog2SizeY` and the +/// per-dimension counts use ceiling division. +fn pic_size_in_ctbs_y(sps: &SeqParameterSet) -> u32 { + let ctb_size = 1u32 << sps.log2_ctb_size(); + let width_in_ctbs = sps.pic_width_in_luma_samples.div_ceil(ctb_size); + let height_in_ctbs = sps.pic_height_in_luma_samples.div_ceil(ctb_size); + width_in_ctbs * height_in_ctbs +} + +/// `PicHeightInCtbsY` per equation 7-19: the picture height in CTBs, +/// i.e. `Ceil(pic_height_in_luma_samples / CtbSizeY)`. +fn pic_height_in_ctbs_y(sps: &SeqParameterSet) -> u32 { + let ctb_size = 1u32 << sps.log2_ctb_size(); + sps.pic_height_in_luma_samples.div_ceil(ctb_size) +} + +/// §7.3.6.1 — the entry-point-offset block (`num_entry_point_offsets`, +/// `offset_len_minus1`, `entry_point_offset_minus1[i]`), present when +/// tiles or entropy-coding sync are enabled. Signalled by BOTH +/// independent and dependent slice segments. +fn parse_entry_point_offsets( + br: &mut BitReader<'_>, + sps: &SeqParameterSet, + pps: &PicParameterSet, +) -> Result, SliceError> { + if !(pps.tiles_enabled_flag || pps.entropy_coding_sync_enabled_flag) { + return Ok(None); + } + let num_entry_point_offsets = br.ue()?; + let max_num_entry_point_offsets = num_entry_point_offsets_upper_bound(sps, pps); + if num_entry_point_offsets > max_num_entry_point_offsets { + return Err(SliceError::ValueOutOfRange { + field: "num_entry_point_offsets", + got: num_entry_point_offsets as i64, + }); + } + let (offset_len_minus1, entry_point_offset_minus1) = if num_entry_point_offsets > 0 { + let v = br.ue()?; + if v > 31 { + return Err(SliceError::ValueOutOfRange { + field: "offset_len_minus1", + got: v as i64, + }); + } + let len = v as u8; + let bits = len + 1; + let mut offsets = Vec::with_capacity(num_entry_point_offsets as usize); + for _ in 0..num_entry_point_offsets { + offsets.push(br.u(bits)?); + } + (len, offsets) + } else { + (0, Vec::new()) + }; + Ok(Some(EntryPointOffsets { + num_entry_point_offsets, + offset_len_minus1, + entry_point_offset_minus1, + })) +} + +/// §7.3.6.1 — the slice-segment-header extension block (length + +/// skipped payload bytes), present for BOTH independent and dependent +/// slice segments when the PPS signals it. +fn parse_header_extension( + br: &mut BitReader<'_>, + pps: &PicParameterSet, +) -> Result, SliceError> { + if !pps.slice_segment_header_extension_present_flag { + return Ok(None); + } + let len = br.ue()?; + for _ in 0..len { + br.skip(8)?; + } + Ok(Some(len)) +} + +/// §7.4.7.1 upper bound on the slice header's +/// `num_entry_point_offsets` for the active PPS partitioning. The +/// caller has already gated on `tiles_enabled_flag || +/// entropy_coding_sync_enabled_flag`. +fn num_entry_point_offsets_upper_bound(sps: &SeqParameterSet, pps: &PicParameterSet) -> u32 { + // §7.4.7.1, three-way constraint: + // * tiles == 0, sync == 1 ⇒ 0 .. PicHeightInCtbsY − 1 + // * tiles == 1, sync == 0 ⇒ 0 .. cols * rows − 1 + // * tiles == 1, sync == 1 ⇒ 0 .. cols * PicHeightInCtbsY − 1 + // (wavefront rows counted per tile COLUMN — every tile row of a + // column contributes its CTB rows, summing to PicHeightInCtbsY). + // Arithmetic in u64 keeps the parser defensive against a + // pathological PPS even though no conforming level overflows u32. + let bound = if pps.tiles_enabled_flag { + let cols = u64::from(pps.tiles.num_tile_columns_minus1) + 1; + if pps.entropy_coding_sync_enabled_flag { + cols.saturating_mul(u64::from(pic_height_in_ctbs_y(sps))) + .saturating_sub(1) + } else { + let rows = u64::from(pps.tiles.num_tile_rows_minus1) + 1; + cols.saturating_mul(rows).saturating_sub(1) + } + } else { + u64::from(pic_height_in_ctbs_y(sps)).saturating_sub(1) + }; + u32::try_from(bound).unwrap_or(u32::MAX) +} + +/// `Ceil( Log2( n ) )` — the §7.4.7.1 width formula for +/// `slice_segment_address`. For `n <= 1` the width is 0 bits (a +/// single-CTB picture has no address to signal). +fn ceil_log2(n: u32) -> u8 { + if n <= 1 { + 0 + } else { + // Ceil(Log2(n)) = bit-width of (n - 1). + (32 - (n - 1).leading_zeros()) as u8 + } +} + +/// Parse one `se(v)` chroma QP offset, range-checked to −12..=12. +fn parse_qp_offset(br: &mut BitReader<'_>, field: &'static str) -> Result { + let v = br.se()?; + if !(-12..=12).contains(&v) { + return Err(SliceError::ValueOutOfRange { + field, + got: v as i64, + }); + } + Ok(v as i8) +} + +/// Parse a `slice_act_*_qp_offset` (`se(v)`, §7.3.6.1) and enforce the +/// §7.4.7.1 conformance bound on its sum with the PPS-level offset: +/// `pps_act_qp_offset + slice_act_qp_offset` must lie in −12..=12. +fn parse_slice_act_qp_offset( + br: &mut BitReader<'_>, + field: &'static str, + pps_act_qp_offset: i32, +) -> Result { + let v = br.se()?; + let sum = pps_act_qp_offset + v; + if !(-12..=12).contains(&sum) { + return Err(SliceError::ValueOutOfRange { + field, + got: sum as i64, + }); + } + Ok(v) +} + +/// Parse the deblocking-filter override block of §7.3.6.1, applying the +/// §7.4.7.1 inference rules for the absent fields. +fn parse_slice_deblocking( + br: &mut BitReader<'_>, + pps: &PicParameterSet, +) -> Result { + // deblocking_filter_override_flag only present when + // deblocking_filter_override_enabled_flag (PPS). + let override_flag = if pps.deblocking.override_enabled_flag { + br.u1()? != 0 + } else { + false + }; + + if !override_flag { + // Inferred from the PPS (§7.4.7.1). + return Ok(SliceDeblocking { + disabled_flag: pps.deblocking.disabled_flag, + beta_offset_div2: pps.deblocking.beta_offset_div2, + tc_offset_div2: pps.deblocking.tc_offset_div2, + }); + } + + let disabled_flag = br.u1()? != 0; + let (beta, tc) = if !disabled_flag { + let beta = br.se()?; + if !(-6..=6).contains(&beta) { + return Err(SliceError::ValueOutOfRange { + field: "slice_beta_offset_div2", + got: beta as i64, + }); + } + let tc = br.se()?; + if !(-6..=6).contains(&tc) { + return Err(SliceError::ValueOutOfRange { + field: "slice_tc_offset_div2", + got: tc as i64, + }); + } + (beta as i8, tc as i8) + } else { + // When deblocking is disabled the offsets are not signalled and + // are inferred to 0 (their effect is moot when disabled). + (0, 0) + }; + + Ok(SliceDeblocking { + disabled_flag, + beta_offset_div2: beta, + tc_offset_div2: tc, + }) +} + +/// Parse the long-term-ref-pic block of §7.3.6.1 (the body gated by +/// `long_term_ref_pics_present_flag` on the SPS), returning the parsed +/// `(num_long_term_sps, num_long_term_pics, entries)` triple. +/// +/// The block: +/// +/// ```text +/// if( num_long_term_ref_pics_sps > 0 ) +/// num_long_term_sps ue(v) +/// num_long_term_pics ue(v) +/// for( i = 0; i < num_long_term_sps + num_long_term_pics; i++ ) { +/// if( i < num_long_term_sps ) { +/// if( num_long_term_ref_pics_sps > 1 ) +/// lt_idx_sps[i] u(v) — Ceil(Log2(num_long_term_ref_pics_sps)) +/// } else { +/// poc_lsb_lt[i] u(v) — log2_max_poc_lsb_minus4+4 +/// used_by_curr_pic_lt_flag[i] u(1) +/// } +/// delta_poc_msb_present_flag[i] u(1) +/// if( delta_poc_msb_present_flag[i] ) +/// delta_poc_msb_cycle_lt[i] ue(v) +/// } +/// ``` +fn parse_long_term_ref_pic_block( + br: &mut BitReader<'_>, + sps: &SeqParameterSet, +) -> Result<(u32, u32, Vec), SliceError> { + let num_long_term_sps = if sps.num_long_term_ref_pics_sps > 0 { + let v = br.ue()?; + if v > sps.num_long_term_ref_pics_sps { + return Err(SliceError::ValueOutOfRange { + field: "num_long_term_sps", + got: v as i64, + }); + } + v + } else { + 0 + }; + let num_long_term_pics = br.ue()?; + // §7.4.7.1 bounds num_long_term_pics by the SPS DPB capacity; we + // apply a defensive sanity ceiling instead of computing the full + // DPB-derived bound (which needs RPS counts not yet wired through + // here). A pathological encoder could otherwise drive an unbounded + // allocation. + if num_long_term_pics > HEVC_MAX_LONG_TERM_PICS_IN_SLICE as u32 { + return Err(SliceError::ValueOutOfRange { + field: "num_long_term_pics", + got: num_long_term_pics as i64, + }); + } + let total = num_long_term_sps + num_long_term_pics; + let lt_idx_bits = if sps.num_long_term_ref_pics_sps > 1 { + ceil_log2(sps.num_long_term_ref_pics_sps) + } else { + 0 + }; + let poc_lsb_bits = sps.log2_max_pic_order_cnt_lsb_minus4 + 4; + + let mut entries = Vec::with_capacity(total as usize); + for i in 0..total { + let source = if i < num_long_term_sps { + let lt_idx_sps = if lt_idx_bits > 0 { + let v = br.u(lt_idx_bits)?; + if v >= sps.num_long_term_ref_pics_sps { + return Err(SliceError::ValueOutOfRange { + field: "lt_idx_sps", + got: v as i64, + }); + } + v + } else { + 0 + }; + SliceLongTermRefPicSource::Sps { lt_idx_sps } + } else { + let poc_lsb_lt = br.u(poc_lsb_bits)?; + let used_by_curr_pic_lt_flag = br.u1()? != 0; + SliceLongTermRefPicSource::InSlice { + poc_lsb_lt, + used_by_curr_pic_lt_flag, + } + }; + let delta_poc_msb_present_flag = br.u1()? != 0; + let delta_poc_msb_cycle_lt = if delta_poc_msb_present_flag { + br.ue()? + } else { + 0 + }; + entries.push(SliceLongTermRefPic { + source, + delta_poc_msb_present_flag, + delta_poc_msb_cycle_lt, + }); + } + Ok((num_long_term_sps, num_long_term_pics, entries)) +} + +/// Resolution of the active short-term RPS for the in-place +/// `NumPicTotalCurr` derivation at the §7.3.6.1 +/// `ref_pic_lists_modification()` gate. The result is always the +/// post-§7.4.8 materialised form (explicit or inter-predicted both +/// produce the same shape). +enum ActiveShortTermRps { + /// The active short-term RPS has been resolved to its post-§7.4.8 + /// form. The contained `UsedByCurrPicS{0,1}` arrays are the + /// per-position flags consumed by equation 7-57. + Materialized(crate::sps::MaterializedShortTermRefPicSet), + /// The slice has no active short-term RPS (an IDR slice, where the + /// non-IDR POC/RPS block is absent). `NumPicTotalCurr` is `0`. + Empty, + /// Materialisation of the active RPS failed — for instance because + /// the inter-RPS-prediction `used_by_curr_pic_flag` / + /// `use_delta_flag` arrays did not match the source RPS's + /// `NumDeltaPocs[RefRpsIdx] + 1`. The slice parser surfaces this + /// as a deferred opaque tail so the caller can investigate without + /// the parse aborting. + MaterializeFailed, +} + +/// Resolve the active short-term RPS for the current slice given the +/// already-parsed §7.3.6.1 RPS gate state, running the §7.4.8 +/// derivation against the SPS list when needed. See §7.4.8 for the +/// `stRpsIdx` selection. +fn resolve_active_short_term_rps( + sps: &SeqParameterSet, + short_term_ref_pic_set_sps_flag: Option, + inline_rps: Option<&ShortTermRefPicSet>, + short_term_ref_pic_set_idx: Option, +) -> ActiveShortTermRps { + // Materialise the SPS list once; we may need it both as a source + // for the slice-inline inter-RPS-prediction and as the active RPS + // for the SPS form. The list is short (cap + // `HEVC_MAX_NUM_SHORT_TERM_RPS = 64`) so this is inexpensive + // relative to a frame decode. + let sps_materialised = match sps.materialize_short_term_ref_pic_sets() { + Ok(v) => v, + Err(_) => return ActiveShortTermRps::MaterializeFailed, + }; + match short_term_ref_pic_set_sps_flag { + None => ActiveShortTermRps::Empty, + Some(false) => match inline_rps { + None => ActiveShortTermRps::Empty, + Some(rps) => { + let source = if rps.inter_ref_pic_set_prediction_flag { + // For the slice-inline form `stRpsIdx == + // num_short_term_ref_pic_sets` and the source is + // `RefRpsIdx = num_short_term_ref_pic_sets - + // (delta_idx_minus1 + 1)` per equation 7-59. + let st_rps_idx = sps.num_short_term_ref_pic_sets as i64; + let ref_rps_idx = st_rps_idx - (rps.delta_idx_minus1 as i64 + 1); + if ref_rps_idx < 0 { + return ActiveShortTermRps::MaterializeFailed; + } + sps_materialised.get(ref_rps_idx as usize) + } else { + None + }; + match rps.materialize(source) { + Ok(m) => ActiveShortTermRps::Materialized(m), + Err(_) => ActiveShortTermRps::MaterializeFailed, + } + } + }, + Some(true) => { + // §7.4.7.1: when not signalled (because + // `num_short_term_ref_pic_sets <= 1`), the index is + // inferred to 0. + let idx = short_term_ref_pic_set_idx.unwrap_or(0) as usize; + match sps_materialised.into_iter().nth(idx) { + None => ActiveShortTermRps::Empty, + Some(m) => ActiveShortTermRps::Materialized(m), + } + } + } +} + +/// Resolve the per-entry `UsedByCurrPicLt[i]` flags for the active +/// long-term-ref-pic block, per §7.4.7.1. SPS-resident entries pick +/// `used_by_curr_pic_lt_sps_flag[lt_idx_sps[i]]`; in-slice entries +/// carry the flag directly on the wire. +/// +/// Returns `false` for any out-of-range SPS lookup (the slice parser +/// rejects `lt_idx_sps >= num_long_term_ref_pics_sps` already; the +/// fallback is defensive). +fn collect_used_by_curr_pic_lt( + entries: &[SliceLongTermRefPic], + sps: &SeqParameterSet, +) -> Vec { + entries + .iter() + .map(|e| e.used_by_curr_pic_lt(sps).unwrap_or(false)) + .collect() +} + +/// Defensive upper bound on `num_long_term_pics` (§7.4.7.1 bounds the +/// value by `sps_max_dec_pic_buffering_minus1[TemporalId] − …`; an +/// HEVC DPB is bounded by `MaxDpbSize` which is bounded by +/// `sps_max_dec_pic_buffering_minus1` ≤ 15 per §7.4.3.2.1). +const HEVC_MAX_LONG_TERM_PICS_IN_SLICE: usize = 16; + +/// Consume `byte_alignment()` (§7.3.2.4): one `alignment_bit_equal_to_one` +/// followed by `alignment_bit_equal_to_zero` bits until the cursor is on +/// a byte boundary. Returns the byte offset (from the start of the RBSP) +/// of the first byte that follows. +fn consume_byte_alignment(br: &mut BitReader<'_>) -> Result { + // alignment_bit_equal_to_one. + let _ = br.u1()?; + while br.bit_pos() % 8 != 0 { + let _ = br.u1()?; + } + Ok(br.bit_pos() / 8) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::sps::LongTermRefPicEntry; + + /// Build a minimal SPS for slice-header parsing context. Only the + /// fields the slice parser reads are populated meaningfully; the + /// rest carry defaults that do not affect the header parse. + #[allow(clippy::too_many_arguments)] + fn ctx_sps( + chroma_format_idc: u8, + separate_colour_plane_flag: bool, + sao: bool, + mvp: bool, + width: u32, + height: u32, + log2_diff_max_min_cb: u8, + log2_min_cb_minus3: u8, + log2_max_poc_lsb_minus4: u8, + ) -> SeqParameterSet { + // Hand-assemble the smallest valid SPS RBSP that decodes to the + // requested gate values, by parsing the tiny fixture's SPS and + // patching the relevant fields. The slice parser only consults + // chroma_format_idc, separate_colour_plane_flag, + // sample_adaptive_offset_enabled_flag, + // sps_temporal_mvp_enabled_flag, the CTB / picture-size + // derivations, and log2_max_pic_order_cnt_lsb_minus4, so a + // patched struct is sufficient for these unit tests. + let mut sps = SeqParameterSet::parse(TINY_SPS_RBSP).expect("tiny SPS"); + sps.chroma_format_idc = chroma_format_idc; + sps.separate_colour_plane_flag = separate_colour_plane_flag; + sps.sample_adaptive_offset_enabled_flag = sao; + sps.sps_temporal_mvp_enabled_flag = mvp; + sps.pic_width_in_luma_samples = width; + sps.pic_height_in_luma_samples = height; + sps.log2_diff_max_min_luma_coding_block_size = log2_diff_max_min_cb; + sps.log2_min_luma_coding_block_size_minus3 = log2_min_cb_minus3; + sps.log2_max_pic_order_cnt_lsb_minus4 = log2_max_poc_lsb_minus4; + sps + } + + /// SPS RBSP body from the tiny fixture (see `sps.rs` tests). + const TINY_SPS_RBSP: &[u8] = &[ + 0x01, 0x04, 0x08, 0x00, 0x00, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x00, 0x00, 0x1E, 0xA0, 0x88, + 0x45, 0x96, 0xEA, 0xAF, 0x2B, 0xC0, 0x5A, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x32, 0x10, + ]; + /// PPS RBSP body from the tiny fixture (see `pps.rs` tests). + const TINY_PPS_RBSP: &[u8] = &[0xC1, 0x73, 0xC0, 0x89]; + + #[test] + fn slice_type_table_7_7() { + assert_eq!(SliceType::from_raw(0).unwrap(), SliceType::B); + assert_eq!(SliceType::from_raw(1).unwrap(), SliceType::P); + assert_eq!(SliceType::from_raw(2).unwrap(), SliceType::I); + assert!(SliceType::from_raw(3).is_err()); + assert!(!SliceType::I.is_inter()); + assert!(SliceType::P.is_inter()); + assert!(SliceType::B.is_inter()); + } + + #[test] + fn ceil_log2_widths() { + // §7.4.7.1: slice_segment_address width = Ceil(Log2(N)). + assert_eq!(ceil_log2(1), 0); + assert_eq!(ceil_log2(2), 1); + assert_eq!(ceil_log2(3), 2); + assert_eq!(ceil_log2(4), 2); + assert_eq!(ceil_log2(5), 3); + assert_eq!(ceil_log2(8), 3); + assert_eq!(ceil_log2(9), 4); + } + + /// Hand-assembled minimal independent I-slice IDR header. With the + /// fixture SPS/PPS gates (sao=1, mvp=1, chroma=1, single CTB, + /// loop-filter-across-slices=1) the bit layout is: + /// first(1)=1 no_output(1)=0 pps_id ue=1 (->0) + /// slice_type ue=011 (->2,I) mvp(1)=0 sao_l(1)=1 sao_c(1)=0 + /// qp_delta se=011 (->-1) lf_across(1)=1 + /// byte_alignment: 1 then zeros. + /// We assemble those bits ourselves so the parse is fully + /// controlled (the tiny fixture's own slice trace is internally + /// inconsistent — see the module-level note / docs gap). + #[test] + fn parses_hand_assembled_i_idr_header() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + // pps from the fixture has loop_filter_across_slices=1, + // tiles=0, ecs=0, deblock-ctrl-present=0, chroma-qp-off=0. + + // Build the bit string. + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag (IRAP) + (0b1, 1), // pps_id ue(v) '1' -> 0 + (0b011, 3), // slice_type ue(v) '011' -> 2 (I) + // slice_temporal_mvp_enabled_flag: absent for an IDR — the + // §7.3.6.1 flag sits inside the non-IDR block. + (1, 1), // slice_sao_luma_flag + (0, 1), // slice_sao_chroma_flag (chroma!=0) + (0b011, 3), // slice_qp_delta se(v) '011' -> -1 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment: alignment_bit_equal_to_one + ]); + let rbsp = pack_bits(&bits); + + let sh = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect("slice header"); + assert!(sh.first_slice_segment_in_pic_flag); + assert_eq!(sh.no_output_of_prior_pics_flag, Some(false)); + assert_eq!(sh.slice_pic_parameter_set_id, 0); + assert!(!sh.dependent_slice_segment_flag); + assert_eq!(sh.slice_segment_address, 0); + assert_eq!(sh.slice_type, Some(SliceType::I)); + assert!(!sh.slice_temporal_mvp_enabled_flag); + assert!(sh.slice_sao_luma_flag); + assert!(!sh.slice_sao_chroma_flag); + assert_eq!(sh.slice_qp_delta, Some(-1)); + assert_eq!(sh.slice_loop_filter_across_slices_enabled_flag, Some(true)); + assert!(sh.opaque_tail.is_none()); + // init_qp from the fixture PPS is 26, so SliceQpY = 26 + -1 = 25. + assert_eq!(sh.slice_qp_y(&pps), Some(25)); + // The header must byte-align: with 1+1+1+3+1+1+3+1=12 bits + // before alignment, alignment consumes bits 12..16 (one '1' + // plus zero pad), so slice data begins at byte 2. + assert_eq!(sh.byte_offset_to_slice_data, Some(2)); + } + + /// I-slice whose PPS carries an SCC body with + /// `pps_slice_act_qp_offsets_present_flag == 1`: the three + /// `slice_act_{y,cb,cr}_qp_offset` se(v) fields (§7.3.6.1) are + /// parsed after `slice_qp_delta`, with the §7.4.7.1 sum bound + /// enforced against the PPS-level offsets. + #[test] + fn parses_slice_act_qp_offsets_when_pps_signals_them() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.pps_scc_extension = Some(crate::pps::PpsSccExtension { + pps_slice_act_qp_offsets_present_flag: true, + ..Default::default() + }); + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag (IRAP) + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + // slice_temporal_mvp_enabled_flag: absent for an IDR. + (1, 1), // slice_sao_luma_flag + (0, 1), // slice_sao_chroma_flag + (0b011, 3), // slice_qp_delta se '011' -> -1 + // pps_slice_chroma_qp_offsets_present_flag = 0 → absent. + // slice_act_*_qp_offset (PpsActQpOffset* all 0 here): + (0b1, 1), // slice_act_y_qp_offset se '1' -> 0 + (0b010, 3), // slice_act_cb_qp_offset se '010' -> +1 + (0b011, 3), // slice_act_cr_qp_offset se '011' -> -1 + // chroma_qp_offset_list_enabled_flag = 0 → + // cu_chroma_qp_offset_enabled_flag absent. + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::I)); + assert_eq!(sh.slice_qp_delta, Some(-1)); + assert_eq!(sh.slice_act_y_qp_offset, 0); + assert_eq!(sh.slice_act_cb_qp_offset, 1); + assert_eq!(sh.slice_act_cr_qp_offset, -1); + assert!(!sh.cu_chroma_qp_offset_enabled_flag); + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// I-slice whose PPS range-extension sets + /// `chroma_qp_offset_list_enabled_flag == 1`: the + /// `cu_chroma_qp_offset_enabled_flag` u(1) (§7.3.6.1) is parsed + /// after the QP-offset block. + #[test] + fn parses_cu_chroma_qp_offset_enabled_flag_when_list_enabled() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.pps_range_extension = Some(crate::pps::PpsRangeExtension { + chroma_qp_offset_list_enabled_flag: true, + ..Default::default() + }); + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + // slice_temporal_mvp_enabled_flag: absent for an IDR. + (1, 1), // slice_sao_luma_flag + (0, 1), // slice_sao_chroma_flag + (0b011, 3), // slice_qp_delta se -> -1 + // act offsets absent (pps_slice_act_qp_offsets_present_flag 0) + (1, 1), // cu_chroma_qp_offset_enabled_flag = 1 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::I)); + assert!(sh.cu_chroma_qp_offset_enabled_flag); + assert!(sh.opaque_tail.is_none()); + } + + /// §7.4.7.1: a `slice_act_y_qp_offset` whose sum with the PPS-level + /// `PpsActQpOffsetY` falls outside −12..=12 is rejected. + #[test] + fn rejects_out_of_range_slice_act_qp_offset_sum() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + // PpsActQpOffsetY = +10 (pps_act_y_qp_offset_plus5 = 15). + pps.pps_scc_extension = Some(crate::pps::PpsSccExtension { + pps_slice_act_qp_offsets_present_flag: true, + pps_act_y_qp_offset_plus5: 15, + ..Default::default() + }); + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + // slice_temporal_mvp_enabled_flag: absent for an IDR. + (1, 1), // slice_sao_luma_flag + (0, 1), // slice_sao_chroma_flag + (0b011, 3), // slice_qp_delta se -> -1 + // slice_act_y_qp_offset = +5 (se '0001010') → sum 10+5 = 15 > 12 + (0b0001010, 7), + ]); + let rbsp = pack_bits(&bits); + let err = + SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect_err("act sum range"); + assert!(matches!( + err, + SliceError::ValueOutOfRange { + field: "slice_act_y_qp_offset", + got: 15 + } + )); + } + + /// Non-IDR **I-slice** (CRA, type 21 — in the IRAP range so + /// `no_output_of_prior_pics_flag` is present): the POC + RPS block + /// is now parsed inline (round 105), so the parser reaches + /// `byte_alignment()` with no opaque tail. + #[test] + fn parses_non_idr_i_slice_cra_with_inline_zero_rps() { + // Tiny SPS context: num_short_term_ref_pic_sets = 0, so + // short_term_ref_pic_set_sps_flag must be 0 and the in-line RPS + // (stRpsIdx = 0, no inter-RPS-prediction signal) reads + // num_negative_pics + num_positive_pics, both 0. + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag (CRA = 21 ∈ IRAP range) + (0b1, 1), // pps_id ue '1' -> 0 + (0b011, 3), // slice_type ue '011' -> 2 (I) + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + // in-line st_ref_pic_set( num_short_term_ref_pic_sets = 0 ): + // stRpsIdx == 0 so inter_ref_pic_set_prediction_flag absent. + (0b1, 1), // num_negative_pics ue '1' -> 0 + (0b1, 1), // num_positive_pics ue '1' -> 0 + (0, 1), // slice_temporal_mvp_enabled_flag = 0 + (1, 1), // slice_sao_luma_flag = 1 + (0, 1), // slice_sao_chroma_flag = 0 + (0b1, 1), // slice_qp_delta se '1' -> 0 + // pps.lf_across=1 and sao_luma OR !deblock.disabled => present. + // PPS deblocking override_enabled_flag=0, disabled_flag=0 by + // inference => !disabled_flag is true => gate fires. + (1, 1), // slice_loop_filter_across_slices_enabled_flag = 1 + (1, 1), // byte_alignment one-bit + ]); + let rbsp = pack_bits(&bits); + // CRA_NUT (NAL type 21) is in BLA_W_LP..=RSV_IRAP_VCL23 (16..=23). + let sh = SliceSegmentHeader::parse(&rbsp, 21, &sps, &pps).expect("slice header"); + assert!(sh.first_slice_segment_in_pic_flag); + assert_eq!(sh.no_output_of_prior_pics_flag, Some(false)); + assert_eq!(sh.slice_type, Some(SliceType::I)); + assert_eq!(sh.slice_pic_order_cnt_lsb, Some(0)); + assert_eq!(sh.short_term_ref_pic_set_sps_flag, Some(false)); + let inline = sh + .inline_short_term_ref_pic_set + .as_ref() + .expect("inline ST RPS"); + assert!(!inline.inter_ref_pic_set_prediction_flag); + assert_eq!(inline.num_negative_pics, 0); + assert_eq!(inline.num_positive_pics, 0); + assert!(sh.short_term_ref_pic_set_idx.is_none()); + assert_eq!(sh.num_long_term_sps, None); // SPS gate off + assert_eq!(sh.num_long_term_pics, None); + assert!(!sh.slice_temporal_mvp_enabled_flag); + assert!(sh.slice_sao_luma_flag); + assert!(!sh.slice_sao_chroma_flag); + assert_eq!(sh.slice_qp_delta, Some(0)); + // Tail consumed, byte_alignment reached. + assert!(sh.opaque_tail.is_none()); + assert_eq!(sh.byte_offset_to_slice_data, Some(3)); + } + + /// Non-IDR I-slice using the SPS-resident ST RPS (the SPS has + /// `num_short_term_ref_pic_sets == 1`, so + /// `short_term_ref_pic_set_idx` is **absent** — its value is + /// inferred to 0 — and the slice header reads no extra bits for + /// the RPS). + #[test] + fn parses_non_idr_i_slice_with_sps_rps_single_entry() { + let mut sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + // Forge an SPS with one short-term-RPS entry so the gate path + // matches the §7.3.6.1 "else if( num_short_term_ref_pic_sets > 1 )" + // branch FALSE path: short_term_ref_pic_set_idx absent. + sps.num_short_term_ref_pic_sets = 1; + sps.short_term_ref_pic_sets = vec![ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 0, + num_positive_pics: 0, + ..Default::default() + }]; + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IRAP) + (0b1, 1), // pps_id ue '1' -> 0 + (0b011, 3), // slice_type ue '011' -> 2 (I) + (0, 8), // slice_pic_order_cnt_lsb = 0 + (1, 1), // short_term_ref_pic_set_sps_flag = 1 + // num_short_term_ref_pic_sets == 1 so short_term_ref_pic_set_idx + // is NOT signalled (inferred 0). + (0, 1), // slice_temporal_mvp_enabled_flag = 0 + (1, 1), // sao_luma = 1 + (0, 1), // sao_chroma = 0 + (0b1, 1), // slice_qp_delta se '1' -> 0 + (1, 1), // lf_across_slices = 1 + (1, 1), // byte_alignment one bit + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 21, &sps, &pps).expect("slice header"); + assert_eq!(sh.short_term_ref_pic_set_sps_flag, Some(true)); + assert!(sh.inline_short_term_ref_pic_set.is_none()); + assert!(sh.short_term_ref_pic_set_idx.is_none()); + assert_eq!(sh.slice_qp_delta, Some(0)); + assert!(sh.opaque_tail.is_none()); + } + + /// Non-IDR I-slice using the SPS-resident ST RPS with multiple + /// entries: `short_term_ref_pic_set_idx` is signalled `u(v)` with + /// width `Ceil(Log2(num_short_term_ref_pic_sets))`. + #[test] + fn parses_non_idr_i_slice_with_sps_rps_idx_signalled() { + let mut sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + sps.num_short_term_ref_pic_sets = 3; // idx width = 2 bits + sps.short_term_ref_pic_sets = vec![ + ShortTermRefPicSet::default(), + ShortTermRefPicSet::default(), + ShortTermRefPicSet::default(), + ]; + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + + let bits = concat_bits(&[ + (1, 1), + (0, 1), + (0b1, 1), + (0b011, 3), + (0, 8), // poc_lsb = 0 + (1, 1), // short_term_ref_pic_set_sps_flag = 1 + (0b10, 2), // short_term_ref_pic_set_idx u(2) = 2 + (0, 1), // mvp = 0 + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta = 0 + (1, 1), // lf_across + (1, 1), // byte_alignment + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 21, &sps, &pps).expect("slice header"); + assert_eq!(sh.short_term_ref_pic_set_idx, Some(2)); + assert!(sh.inline_short_term_ref_pic_set.is_none()); + assert!(sh.opaque_tail.is_none()); + } + + /// Long-term-ref-pic block: SPS has + /// `long_term_ref_pics_present_flag=1, num_long_term_ref_pics_sps=2`. + /// The slice header carries one SPS-indexed entry plus one in-slice + /// entry, each with `delta_poc_msb_present_flag` and the cycle. + #[test] + fn parses_non_idr_i_slice_with_long_term_block() { + use crate::sps::LongTermRefPicEntry; + let mut sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + sps.long_term_ref_pics_present_flag = true; + sps.num_long_term_ref_pics_sps = 2; // lt_idx_sps width = 1 bit + sps.long_term_ref_pics = vec![ + LongTermRefPicEntry { + poc_lsb: 0, + used_by_curr_pic: true, + }, + LongTermRefPicEntry { + poc_lsb: 4, + used_by_curr_pic: false, + }, + ]; + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IRAP) + (0b1, 1), + (0b011, 3), // I slice + (0, 8), // poc_lsb + (0, 1), // st_sps_flag = 0 (num_st_rps=0) + (0b1, 1), // num_negative_pics ue '1' -> 0 + (0b1, 1), // num_positive_pics ue '1' -> 0 + // Long-term block: + (0b010, 3), // num_long_term_sps ue '010' -> 1 + (0b010, 3), // num_long_term_pics ue '010' -> 1 + // Entry 0: SPS-indexed (i < num_long_term_sps) + (1, 1), // lt_idx_sps[0] u(1) = 1 + (0, 1), // delta_poc_msb_present_flag[0] = 0 + // Entry 1: in-slice (i >= num_long_term_sps) + (0b1010, 8), // poc_lsb_lt[1] u(8) = 0xAA bit pattern... use 10 + (1, 1), // used_by_curr_pic_lt_flag[1] = 1 + (1, 1), // delta_poc_msb_present_flag[1] = 1 + (0b010, 3), // delta_poc_msb_cycle_lt[1] ue '010' -> 1 + (0, 1), // slice_temporal_mvp_enabled_flag = 0 + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // lf_across + (1, 1), // byte_alignment + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 21, &sps, &pps).expect("slice header"); + assert_eq!(sh.num_long_term_sps, Some(1)); + assert_eq!(sh.num_long_term_pics, Some(1)); + assert_eq!(sh.long_term_ref_pics.len(), 2); + match sh.long_term_ref_pics[0].source { + SliceLongTermRefPicSource::Sps { lt_idx_sps } => assert_eq!(lt_idx_sps, 1), + other => panic!("entry 0 should be SPS-indexed: {other:?}"), + } + assert!(!sh.long_term_ref_pics[0].delta_poc_msb_present_flag); + match sh.long_term_ref_pics[1].source { + SliceLongTermRefPicSource::InSlice { + poc_lsb_lt, + used_by_curr_pic_lt_flag, + } => { + assert_eq!(poc_lsb_lt, 0b1010); // 8-bit u(v) field carrying 10 + assert!(used_by_curr_pic_lt_flag); + } + other => panic!("entry 1 should be in-slice: {other:?}"), + } + assert!(sh.long_term_ref_pics[1].delta_poc_msb_present_flag); + assert_eq!(sh.long_term_ref_pics[1].delta_poc_msb_cycle_lt, 1); + assert!(sh.opaque_tail.is_none()); + } + + /// The §7.4.7.1 cross-check: when `num_short_term_ref_pic_sets == + /// 0`, signalling `short_term_ref_pic_set_sps_flag == 1` is illegal. + #[test] + fn rejects_st_sps_flag_when_no_sps_rps() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), + (0, 1), + (0b1, 1), + (0b011, 3), // I + (0, 8), // poc_lsb + (1, 1), // short_term_ref_pic_set_sps_flag = 1 (illegal: num_st_rps=0) + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, 21, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "short_term_ref_pic_set_sps_flag", + got: 1 + } + ); + } + + /// IDR P-slice with `num_ref_idx_active_override_flag == 0` and + /// `pps.weighted_pred_flag == 1`: the parser reads the override + /// flag, infers `num_ref_idx_l0_active_minus1` from the PPS + /// default, traverses the §7.3.6.1 mvd / cabac-init / collocated + /// block (with `mvd` absent for P, `cabac_init_flag` inferred + /// `false` per §7.4.7.1, and the collocated block absent because + /// `slice_temporal_mvp_enabled_flag == 0`), and then decodes + /// `pred_weight_table()` in place (the §7.3.6.3 gate is statically + /// present because `weighted_pred_flag && slice_type == P`). + /// `ctx_sps` keeps `chroma_format_idc == 1` (4:2:0) so the chroma + /// sub-block is present, and the PPS default + /// `num_ref_idx_l0_default_active_minus1 == 0` (single L0 entry) + /// keeps the per-i loop to one iteration. The minimal table payload + /// here sets every flag off so the L0 entry's weight / offset + /// remain at their §7.4.7.3 inferred defaults; the parser then + /// walks the full inter-slice tail through `byte_alignment()`. + #[test] + fn parses_pb_with_weighted_pred_table_in_place() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR is IRAP) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // §7.3.6.3 pred_weight_table() — minimal "all flags 0" body. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] = 0 + (0, 1), // chroma_weight_l0_flag[0] = 0 + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + assert!(sh.slice_sao_luma_flag); + assert!(sh.slice_sao_chroma_flag); + // §7.4.7.1 inference: P slice with override == 0 picks up the + // PPS default for L0 and leaves L1 absent. + assert_eq!(sh.num_ref_idx_active_override_flag, Some(false)); + assert_eq!( + sh.num_ref_idx_l0_active_minus1, + Some(pps.num_ref_idx_l0_default_active_minus1) + ); + assert_eq!(sh.num_ref_idx_l1_active_minus1, None); + // §7.3.6.1 mvd / cabac-init / collocated walk for this gate + // combination: mvd absent (P), cabac inferred false, collocated + // absent (mvp off). + assert_eq!(sh.mvd_l1_zero_flag, None); + assert_eq!(sh.cabac_init_flag, Some(false)); + assert_eq!(sh.collocated_from_l0_flag, None); + assert_eq!(sh.collocated_ref_idx, None); + // pred_weight_table parsed in place — single L0 entry, all + // flags off. + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.luma_log2_weight_denom, 0); + assert_eq!(pwt.delta_chroma_log2_weight_denom, 0); + assert_eq!(pwt.entries_l0.len(), 1); + assert!(!pwt.entries_l0[0].luma_weight_flag); + assert!(!pwt.entries_l0[0].chroma_weight_flag); + // P slice → L1 block is empty. + assert!(pwt.entries_l1.is_empty()); + // Parser walked the rest of the tail past byte_alignment. + assert_eq!(sh.five_minus_max_num_merge_cand, Some(0)); + assert_eq!(sh.max_num_merge_cand(), Some(5)); + assert_eq!(sh.slice_qp_delta, Some(0)); + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// IDR P-slice with `num_ref_idx_active_override_flag == 1` and an + /// explicitly signalled `num_ref_idx_l0_active_minus1 == 1`. P + /// slices never signal L1; verify the parser materialises the + /// override flag and the explicit L0 value, leaves L1 absent, + /// decodes a two-entry `pred_weight_table()` in place (the §7.3.6.3 + /// gate is statically present here via `pps.weighted_pred_flag = + /// true`), and walks the rest of the inter-slice tail through + /// `byte_alignment()`. + #[test] + fn parses_pb_override_with_explicit_l0() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b010, 3), // num_ref_idx_l0_active_minus1 ue(v) -> 1 + // pred_weight_table() — 2 L0 entries, all flags 0. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l0_flag[1] + (0, 1), // chroma_weight_l0_flag[1] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.num_ref_idx_active_override_flag, Some(true)); + assert_eq!(sh.num_ref_idx_l0_active_minus1, Some(1)); + assert_eq!(sh.num_ref_idx_l1_active_minus1, None); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 2); + assert!(pwt.entries_l1.is_empty()); + assert!(sh.opaque_tail.is_none()); + } + + /// IDR B-slice with `num_ref_idx_active_override_flag == 1`: + /// verifies that both `num_ref_idx_l0_active_minus1` and + /// `num_ref_idx_l1_active_minus1` are read for a B slice, the + /// `mvd_l1_zero_flag` is consumed, and the in-place + /// `pred_weight_table()` body (gate statically present via + /// `pps.weighted_bipred_flag = true`) decodes both L0 and L1 + /// per-entry flag passes; the parser then walks the rest of the + /// inter-slice tail through `byte_alignment()`. + #[test] + fn parses_b_slice_override_with_both_lists() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_bipred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b1, 1), // slice_type ue(v) -> 0 (B) + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b011, 3), // num_ref_idx_l0_active_minus1 ue(v) -> 2 + (0b010, 3), // num_ref_idx_l1_active_minus1 ue(v) -> 1 + (1, 1), // mvd_l1_zero_flag = 1 + // pred_weight_table() — L0 has 3 entries, L1 has 2 entries. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l0_flag[1] + (0, 1), // chroma_weight_l0_flag[1] + (0, 1), // luma_weight_l0_flag[2] + (0, 1), // chroma_weight_l0_flag[2] + (0, 1), // luma_weight_l1_flag[0] + (0, 1), // chroma_weight_l1_flag[0] + (0, 1), // luma_weight_l1_flag[1] + (0, 1), // chroma_weight_l1_flag[1] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::B)); + assert_eq!(sh.num_ref_idx_active_override_flag, Some(true)); + assert_eq!(sh.num_ref_idx_l0_active_minus1, Some(2)); + assert_eq!(sh.num_ref_idx_l1_active_minus1, Some(1)); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 3); + assert_eq!(pwt.entries_l1.len(), 2); + assert!(sh.opaque_tail.is_none()); + } + + /// IDR B-slice with `num_ref_idx_active_override_flag == 0`: §7.4.7.1 + /// must infer BOTH L0 and L1 defaults from the PPS. The parser + /// reads through the mvd / cabac / collocated block, decodes the + /// in-place `pred_weight_table()` (gate present via + /// `pps.weighted_bipred_flag = true`) with a single L0 / L1 entry + /// each (the PPS defaults), then walks the rest of the tail to + /// `byte_alignment()`. + #[test] + fn b_slice_override_zero_infers_both_defaults() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_bipred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b1, 1), // slice_type -> B + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + (1, 1), // mvd_l1_zero_flag = 1 + // pred_weight_table() — 1 L0 + 1 L1 entry (defaults), all + // flags 0. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l1_flag[0] + (0, 1), // chroma_weight_l1_flag[0] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::B)); + assert_eq!(sh.num_ref_idx_active_override_flag, Some(false)); + assert_eq!( + sh.num_ref_idx_l0_active_minus1, + Some(pps.num_ref_idx_l0_default_active_minus1) + ); + assert_eq!( + sh.num_ref_idx_l1_active_minus1, + Some(pps.num_ref_idx_l1_default_active_minus1) + ); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 1); + assert_eq!(pwt.entries_l1.len(), 1); + assert!(sh.opaque_tail.is_none()); + } + + /// IDR B-slice with `pps.lists_modification_present_flag == 0` + /// (default for `TINY_PPS_RBSP`): the §7.3.6.1 mvd / cabac-init / + /// collocated block is walked in-place. With + /// `pps.cabac_init_present_flag == 0` (default) the cabac-init bit + /// is absent (inferred `false` per §7.4.7.1); with + /// `slice_temporal_mvp_enabled_flag == 0` the collocated block is + /// absent. `mvd_l1_zero_flag` is the only bit consumed past the + /// override block. + #[test] + fn parses_b_slice_mvd_l1_zero_walk_no_mvp() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_bipred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b1, 1), // slice_type -> B + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b010, 3), // num_ref_idx_l0_active_minus1 ue -> 1 + (0b010, 3), // num_ref_idx_l1_active_minus1 ue -> 1 + (1, 1), // mvd_l1_zero_flag = 1 + // pred_weight_table() — 2 L0 + 2 L1 entries, all flags 0. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l0_flag[1] + (0, 1), // chroma_weight_l0_flag[1] + (0, 1), // luma_weight_l1_flag[0] + (0, 1), // chroma_weight_l1_flag[0] + (0, 1), // luma_weight_l1_flag[1] + (0, 1), // chroma_weight_l1_flag[1] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.mvd_l1_zero_flag, Some(true)); + // cabac_init_present_flag == 0 → inferred 0 per §7.4.7.1. + assert_eq!(sh.cabac_init_flag, Some(false)); + // mvp off → entire collocated block absent. + assert_eq!(sh.collocated_from_l0_flag, None); + assert_eq!(sh.collocated_ref_idx, None); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 2); + assert_eq!(pwt.entries_l1.len(), 2); + assert!(sh.opaque_tail.is_none()); + } + + /// IDR P-slice with `pps.cabac_init_present_flag == 1`: the cabac- + /// init bit is signalled (P slice still walks the gate, even though + /// `mvd_l1_zero_flag` is absent). With `mvp == 0` the collocated + /// block is absent. + #[test] + fn parses_p_slice_cabac_init_walk() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.cabac_init_present_flag = true; + pps.weighted_pred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + (1, 1), // cabac_init_flag = 1 + // pred_weight_table() — 1 L0 entry, all flags 0. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + // P slice → mvd absent. + assert_eq!(sh.mvd_l1_zero_flag, None); + assert_eq!(sh.cabac_init_flag, Some(true)); + // mvp off → entire collocated block absent. + assert_eq!(sh.collocated_from_l0_flag, None); + assert_eq!(sh.collocated_ref_idx, None); + assert!(sh.pred_weight_table.is_some()); + assert!(sh.opaque_tail.is_none()); + } + + /// Non-IDR (TRAIL_R) P-slice with `mvp == 1` and + /// `num_ref_idx_l0_active_minus1 == 0` (single L0 entry): §7.4.7.1 + /// infers `collocated_from_l0_flag = 1` (no bit consumed since + /// slice_type != B) and the `collocated_ref_idx` field is absent + /// (only signalled when the active list has more than one entry). + /// `slice_temporal_mvp_enabled_flag` sits inside the §7.3.6.1 + /// non-IDR block, after the POC + RPS fields. + #[test] + fn parses_p_slice_temporal_mvp_single_ref_collocated_inferred() { + // mvp = true via the ctx_sps argument. + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue -> 1 + (0b1, 1), // num_positive_pics ue -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // slice_temporal_mvp_enabled_flag = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b1, 1), // num_ref_idx_l0_active_minus1 ue -> 0 + // pred_weight_table() — 1 L0 entry. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + // TRAIL_R (NAL type 1) — a non-IDR picture. + let sh = SliceSegmentHeader::parse(&rbsp, 1, &sps, &pps).expect("slice header"); + assert!(sh.slice_temporal_mvp_enabled_flag); + // P slice + mvp on: §7.4.7.1 infers collocated_from_l0 = 1. + assert_eq!(sh.collocated_from_l0_flag, Some(true)); + // L0 has a single entry (active_minus1 == 0) → ref_idx absent, + // inferred to 0. + assert_eq!(sh.collocated_ref_idx, Some(0)); + assert!(sh.pred_weight_table.is_some()); + assert!(sh.opaque_tail.is_none()); + } + + /// Non-IDR (TRAIL_R) P-slice with `mvp == 1` and + /// `num_ref_idx_l0_active_minus1 == 2` (three L0 entries): + /// `collocated_from_l0_flag` is inferred to 1 (P slice) and + /// `collocated_ref_idx` is signalled `ue(v)`. + #[test] + fn parses_p_slice_temporal_mvp_collocated_ref_idx_signalled() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue -> 1 + (0b1, 1), // num_positive_pics ue -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // slice_temporal_mvp_enabled_flag = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b011, 3), // num_ref_idx_l0_active_minus1 ue -> 2 + (0b010, 3), // collocated_ref_idx ue -> 1 + // pred_weight_table() — 3 L0 entries. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l0_flag[1] + (0, 1), // chroma_weight_l0_flag[1] + (0, 1), // luma_weight_l0_flag[2] + (0, 1), // chroma_weight_l0_flag[2] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + // TRAIL_R (NAL type 1) — a non-IDR picture. + let sh = SliceSegmentHeader::parse(&rbsp, 1, &sps, &pps).expect("slice header"); + assert_eq!(sh.num_ref_idx_l0_active_minus1, Some(2)); + // P slice + mvp on: §7.4.7.1 infers collocated_from_l0 = 1. + assert_eq!(sh.collocated_from_l0_flag, Some(true)); + assert_eq!(sh.collocated_ref_idx, Some(1)); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 3); + assert!(sh.opaque_tail.is_none()); + } + + /// Non-IDR (TRAIL_R) B-slice with `mvp == 1`, + /// `collocated_from_l0_flag = 0` (L1 path), and an L1 with more + /// than one entry: `collocated_ref_idx` indexes L1. + #[test] + fn parses_b_slice_temporal_mvp_collocated_from_l1() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_bipred_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id -> 0 + (0b1, 1), // slice_type -> B + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue -> 1 + (0b1, 1), // num_positive_pics ue -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // slice_temporal_mvp_enabled_flag = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b1, 1), // num_ref_idx_l0_active_minus1 ue -> 0 + (0b010, 3), // num_ref_idx_l1_active_minus1 ue -> 1 + (0, 1), // mvd_l1_zero_flag = 0 + (0, 1), // collocated_from_l0_flag = 0 + (0b010, 3), // collocated_ref_idx ue -> 1 + // pred_weight_table() — 1 L0 + 2 L1 entries, all flags 0. + (0b1, 1), // luma_log2_weight_denom ue -> 0 + (0b1, 1), // delta_chroma_log2_weight_denom se -> 0 + (0, 1), // luma_weight_l0_flag[0] + (0, 1), // chroma_weight_l0_flag[0] + (0, 1), // luma_weight_l1_flag[0] + (0, 1), // chroma_weight_l1_flag[0] + (0, 1), // luma_weight_l1_flag[1] + (0, 1), // chroma_weight_l1_flag[1] + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + // TRAIL_R (NAL type 1) — a non-IDR picture. + let sh = SliceSegmentHeader::parse(&rbsp, 1, &sps, &pps).expect("slice header"); + assert_eq!(sh.mvd_l1_zero_flag, Some(false)); + assert_eq!(sh.collocated_from_l0_flag, Some(false)); + // L1 active_minus1 == 1 → 2 entries; ref_idx = 1 indexes the + // second entry, in range. + assert_eq!(sh.collocated_ref_idx, Some(1)); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.entries_l0.len(), 1); + assert_eq!(pwt.entries_l1.len(), 2); + assert!(sh.opaque_tail.is_none()); + } + + /// `collocated_ref_idx` overflow check: a value > the active + /// `num_ref_idx_lX_active_minus1` is a §7.4.7.1 range failure. + #[test] + fn rejects_collocated_ref_idx_above_active_minus1() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue -> 1 + (0b1, 1), // num_positive_pics ue -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // mvp = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // override = 1 + (0b010, 3), // L0 active_minus1 = 1 (-> 2 entries, valid range 0..=1) + (0b011, 3), // collocated_ref_idx ue -> 2 (out of range) + ]); + let rbsp = pack_bits(&bits); + // TRAIL_R (NAL type 1) — a non-IDR picture. + let err = SliceSegmentHeader::parse(&rbsp, 1, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "collocated_ref_idx", + got: 2, + } + ); + } + + /// An IDR P-slice with `pps.lists_modification_present_flag == 1`: + /// because the §7.3.6.1 non-IDR POC/RPS block is absent for IDR + /// slices, the active short-term RPS is empty and the §7.4.7.2 + /// `NumPicTotalCurr` is `0`. The §7.3.6.1 outer gate + /// (`... && NumPicTotalCurr > 1`) is therefore statically false + /// and `ref_pic_lists_modification()` is not signalled; the parser + /// continues straight into the mvd / cabac-init / collocated block + /// (all absent for this P slice + no-MVP / no-cabac-init / + /// no-temporal-MVP configuration) and walks the rest of the tail + /// through `byte_alignment()`. + #[test] + fn skips_rplm_when_num_pic_total_curr_is_zero_idr() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.lists_modification_present_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // RPLM gate statically false (NumPicTotalCurr == 0) — no + // bits consumed; parser walks into the mvd / cabac-init / + // collocated block. With the current configuration that + // block is fully absent (P slice, no cabac_init, no MVP). + (0b010, 3), // five_minus_max_num_merge_cand ue -> 1 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.num_ref_idx_active_override_flag, Some(false)); + assert_eq!(sh.ref_pic_lists_modification, None); + assert_eq!(sh.mvd_l1_zero_flag, None); + assert_eq!(sh.cabac_init_flag, Some(false)); + assert_eq!(sh.collocated_from_l0_flag, None); + assert_eq!(sh.collocated_ref_idx, None); + assert_eq!(sh.five_minus_max_num_merge_cand, Some(1)); + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// Non-IDR P-slice with `pps.lists_modification_present_flag == 1` + /// and an inline short-term RPS in explicit form carrying two + /// `used_by_curr_pic_s0_flag` entries set to 1: §7.4.7.2 equation + /// 7-57 gives `NumPicTotalCurr == 2`, the §7.3.6.1 outer gate is + /// statically present, and `ref_pic_lists_modification()` parses + /// in place. The per-entry width of `list_entry_l0` is + /// `Ceil(Log2(2)) = 1` bit (§7.4.7.2). After RPLM the parser walks + /// the rest of the inter tail through `byte_alignment()`. + #[test] + fn parses_rplm_in_place_with_explicit_inline_rps_npc_two() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.lists_modification_present_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + // Inline st_ref_pic_set: stRpsIdx == num_short_term_ref_pic_sets + // == 0, so inter_ref_pic_set_prediction_flag is absent. + (0b011, 3), // num_negative_pics ue '011' -> 2 + (0b1, 1), // num_positive_pics ue '1' -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (0b1, 1), // delta_poc_s0_minus1[1] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[1] = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // → infers L0 active_minus1 = pps.num_ref_idx_l0_default + // RPLM gate statically present (NumPicTotalCurr == 2 > 1): + (1, 1), // ref_pic_list_modification_flag_l0 = 1 + // list_entry_l0[0 .. l0_active_minus1] — each + // `Ceil(Log2(2)) = 1` bit, range 0..=1. The PPS default + // active_minus1 from TINY_PPS_RBSP picks the loop count. + // We feed enough bits for the largest plausible default + // and check that the slice parser caps the count from the + // resolved override-or-default value. + (0, 1), // list_entry_l0[0] = 0 + (0b010, 3), // five_minus_max_num_merge_cand ue -> 1 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + // TRAIL_N (Table 7-1 value 0) is non-IDR / non-IRAP. + let sh = SliceSegmentHeader::parse(&rbsp, 0, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + assert_eq!(sh.short_term_ref_pic_set_sps_flag, Some(false)); + let inline = sh + .inline_short_term_ref_pic_set + .as_ref() + .expect("inline ST RPS"); + assert_eq!(inline.num_negative_pics, 2); + assert_eq!(inline.used_by_curr_pic_s0_flag, vec![true, true]); + let rplm = sh + .ref_pic_lists_modification + .as_ref() + .expect("RPLM parsed in place"); + assert!(rplm.ref_pic_list_modification_flag_l0); + // L0 active_minus1 == 0 (PPS TINY default) → 1 entry. + assert_eq!(rplm.list_entry_l0, vec![0]); + // P slice → L1 fields are not signalled. + assert_eq!(rplm.ref_pic_list_modification_flag_l1, None); + assert!(rplm.list_entry_l1.is_empty()); + // Full inter tail walked, no opaque suffix. + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// Non-IDR P-slice with `pps.lists_modification_present_flag == 1` + /// and an inline short-term RPS in explicit form carrying *one* + /// `used_by_curr_pic_s0_flag` entry: equation 7-57 gives + /// `NumPicTotalCurr == 1`, the §7.3.6.1 outer gate is statically + /// false, `ref_pic_lists_modification()` is not signalled, and the + /// parser continues straight into the rest of the inter tail. + #[test] + fn skips_rplm_when_num_pic_total_curr_is_one() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.lists_modification_present_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue '010' -> 1 + (0b1, 1), // num_positive_pics ue '1' -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // No RPLM (gate statically false at NPC == 1). + (0b010, 3), // five_minus_max_num_merge_cand ue -> 1 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 0, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + assert_eq!(sh.ref_pic_lists_modification, None); + assert_eq!(sh.five_minus_max_num_merge_cand, Some(1)); + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// Non-IDR P-slice with `pps.lists_modification_present_flag == 1` + /// using an SPS-resident short-term RPS whose + /// `inter_ref_pic_set_prediction_flag == 1` with malformed + /// per-position arrays (lengths do not match the source's + /// `NumDeltaPocs[RefRpsIdx] + 1`). The §7.4.8 materialiser rejects + /// the chain and the parser surfaces an opaque tail starting at the + /// `ref_pic_lists_modification()` bit so the caller can inspect the + /// bitstream. + #[test] + fn defers_rplm_when_active_st_rps_uses_inter_prediction() { + let mut sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + sps.num_short_term_ref_pic_sets = 2; + sps.short_term_ref_pic_sets = vec![ + ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 1, + num_positive_pics: 0, + delta_poc_s0_minus1: vec![0], + used_by_curr_pic_s0_flag: vec![true], + ..Default::default() + }, + ShortTermRefPicSet { + // The picked RPS is in inter-prediction form but the + // arrays are empty (length 0 ≠ source's NumDeltaPocs+1 + // = 2) — materialisation fails and the parse defers. + inter_ref_pic_set_prediction_flag: true, + ..Default::default() + }, + ]; + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.lists_modification_present_flag = true; + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (1, 1), // short_term_ref_pic_set_sps_flag = 1 + // num_short_term_ref_pic_sets == 2 → idx field width = 1 bit. + (1, 1), // short_term_ref_pic_set_idx u(1) = 1 (the inter-predicted RPS) + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // (Deferral begins here; remaining bits are opaque.) + (1, 1), + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 0, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + assert_eq!(sh.short_term_ref_pic_set_sps_flag, Some(true)); + assert_eq!(sh.short_term_ref_pic_set_idx, Some(1)); + assert!(sh.ref_pic_lists_modification.is_none()); + assert_eq!(sh.mvd_l1_zero_flag, None); + assert_eq!(sh.cabac_init_flag, None); + assert!(sh.opaque_tail.is_some()); + assert!(sh.byte_offset_to_slice_data.is_none()); + } + + /// Non-IDR P-slice with `pps.lists_modification_present_flag == 1` + /// using an SPS-resident short-term RPS whose + /// `inter_ref_pic_set_prediction_flag == 1` and well-formed + /// per-position arrays. The §7.4.8 materialiser succeeds: the + /// derived RPS has `NumPicTotalCurr == 1` (single positive POC + /// gated `false`) so the §7.3.6.1 outer gate is statically false + /// and the parser walks the inter-slice tail to `byte_alignment()` + /// without surfacing an opaque tail. Closes the prior §7.4.8 + /// deferral point for this configuration. + #[test] + fn parses_p_slice_with_sps_inter_predicted_rps_npc_le_1() { + let mut sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + sps.num_short_term_ref_pic_sets = 2; + // Same fixture used by sps::tests::materialize_inter_rps_prediction_matches_fixture: + // * Source (idx 0): explicit, num_neg=1, num_pos=0, + // delta_poc_s0_minus1=[0], used_by_curr_pic_s0_flag=[true]. + // * Inter (idx 1): delta_rps_sign=false, + // abs_delta_rps_minus1=0 (deltaRps=+1), + // used_by_curr_pic_flag=[true,false], use_delta_flag=[true,true]. + // Derived (idx 1): DeltaPocS1=[+1], UsedByCurrPicS1=[false] + // ⇒ NumPicTotalCurr = 0 (the lone positive's used flag is + // false), gate is statically false. + sps.short_term_ref_pic_sets = vec![ + ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 1, + num_positive_pics: 0, + delta_poc_s0_minus1: vec![0], + used_by_curr_pic_s0_flag: vec![true], + ..Default::default() + }, + ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: vec![true, false], + use_delta_flag: vec![true, true], + ..Default::default() + }, + ]; + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.lists_modification_present_flag = true; + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (1, 1), // short_term_ref_pic_set_sps_flag = 1 + // num_short_term_ref_pic_sets == 2 → idx field width = 1 bit. + (1, 1), // short_term_ref_pic_set_idx u(1) = 1 (the inter-predicted RPS) + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // (NumPicTotalCurr == 0 → ref_pic_lists_modification gate + // is statically absent; the parser walks straight to + // `mvd_l1_zero_flag`, which is absent for P, then the + // inferred `cabac_init_flag = false`, then the absent + // collocated block, then five_minus_max_num_merge_cand.) + (0b010, 3), // five_minus_max_num_merge_cand ue -> 1 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag = 1 + (1, 1), // byte_alignment '1' bit (rest zero-padded) + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, 0, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + assert_eq!(sh.short_term_ref_pic_set_sps_flag, Some(true)); + assert_eq!(sh.short_term_ref_pic_set_idx, Some(1)); + // §7.4.8 materialisation succeeded, NumPicTotalCurr == 0 ⇒ + // gate statically false, no RPLM signalled. + assert!(sh.ref_pic_lists_modification.is_none()); + // The parser walked through to byte_alignment(). + assert!(sh.opaque_tail.is_none()); + assert_eq!(sh.five_minus_max_num_merge_cand, Some(1)); + assert_eq!(sh.slice_qp_delta, Some(0)); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// IDR P-slice that walks the full inter-slice tail through + /// `byte_alignment()` because the §7.3.6.3 `pred_weight_table()` + /// gate is statically absent (`pps.weighted_pred_flag == 0`, + /// inherited from `TINY_PPS_RBSP`). After the override block, the + /// parser walks past `mvd_l1_zero_flag` (absent for P) and + /// `cabac_init_flag` (absent + inferred `false` because + /// `pps.cabac_init_present_flag == 0`), past the collocated block + /// (absent because `slice_temporal_mvp_enabled_flag == 0`), reads + /// `five_minus_max_num_merge_cand`, then the I-slice-shared tail + /// (`slice_qp_delta` + chroma QP + deblocking + loop-filter + + /// entry-points + extension + byte_alignment). The `use_integer_mv_flag` + /// SCC bit is statically absent because the PPS SCC extension is + /// not surfaced (motion_vector_resolution_control_idc inferred 0). + #[test] + fn parses_p_slice_full_inter_tail_no_weighted_pred() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + // Sanity: TINY_PPS keeps the weighted-pred gate statically off. + assert!(!pps.weighted_pred_flag); + assert!(!pps.weighted_bipred_flag); + assert!(!pps.cabac_init_present_flag); + assert!(!pps.lists_modification_present_flag); + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // (no mvd / cabac_init / collocated bits — all inferred) + (0b010, 3), // five_minus_max_num_merge_cand ue -> 1 + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag = 1 + (1, 1), // byte_alignment '1' bit (rest are 0 to byte boundary) + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + // §7.4.7.1 inference: P override == 0 → L0 from PPS default. + assert_eq!( + sh.num_ref_idx_l0_active_minus1, + Some(pps.num_ref_idx_l0_default_active_minus1) + ); + assert_eq!(sh.num_ref_idx_l1_active_minus1, None); + assert_eq!(sh.mvd_l1_zero_flag, None); + assert_eq!(sh.cabac_init_flag, Some(false)); + assert_eq!(sh.collocated_from_l0_flag, None); + assert_eq!(sh.collocated_ref_idx, None); + // five_minus_max_num_merge_cand = 1 → MaxNumMergeCand = 4. + assert_eq!(sh.five_minus_max_num_merge_cand, Some(1)); + assert_eq!(sh.max_num_merge_cand(), Some(4)); + assert_eq!(sh.slice_qp_delta, Some(0)); + assert_eq!(sh.slice_loop_filter_across_slices_enabled_flag, Some(true)); + // Tail walked to byte_alignment; no opaque suffix. + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// Non-IDR (TRAIL_R) B-slice walking the full inter-slice tail + /// through `byte_alignment()` with `pps.weighted_bipred_flag == 0`: + /// exercises the B-only `mvd_l1_zero_flag` bit and the temporal-MVP + /// `collocated_from_l0_flag` signalling, then walks straight to + /// `five_minus_max_num_merge_cand` and the shared I-slice tail. + #[test] + fn parses_b_slice_full_inter_tail_with_mvp() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), // first + (0b1, 1), // pps_id ue -> 0 + (0b1, 1), // slice_type ue -> B + (0, 8), // slice_pic_order_cnt_lsb u(8) = 0 + (0, 1), // short_term_ref_pic_set_sps_flag = 0 + (0b010, 3), // num_negative_pics ue -> 1 + (0b1, 1), // num_positive_pics ue -> 0 + (0b1, 1), // delta_poc_s0_minus1[0] ue -> 0 + (1, 1), // used_by_curr_pic_s0_flag[0] = 1 + (1, 1), // slice_temporal_mvp_enabled_flag = 1 + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + (0b010, 3), // num_ref_idx_l0_active_minus1 ue -> 1 + (0b1, 1), // num_ref_idx_l1_active_minus1 ue -> 0 + (0, 1), // mvd_l1_zero_flag = 0 + // cabac_init_flag absent (cabac_init_present_flag == 0). + (1, 1), // collocated_from_l0_flag = 1 + (0b010, 3), // collocated_ref_idx ue -> 1 (L0 has 2 entries, in range) + (0b1, 1), // five_minus_max_num_merge_cand ue -> 0 + (0b011, 3), // slice_qp_delta se -> -1 + (1, 1), // slice_loop_filter_across_slices_enabled_flag = 1 + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + // TRAIL_R (NAL type 1) — a non-IDR picture. + let sh = SliceSegmentHeader::parse(&rbsp, 1, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::B)); + assert!(sh.slice_temporal_mvp_enabled_flag); + assert_eq!(sh.mvd_l1_zero_flag, Some(false)); + assert_eq!(sh.collocated_from_l0_flag, Some(true)); + assert_eq!(sh.collocated_ref_idx, Some(1)); + assert_eq!(sh.five_minus_max_num_merge_cand, Some(0)); + assert_eq!(sh.max_num_merge_cand(), Some(5)); + assert_eq!(sh.slice_qp_delta, Some(-1)); + assert!(sh.opaque_tail.is_none()); + } + + /// IDR P-slice with `pps.weighted_pred_flag == 1` and a non-trivial + /// `pred_weight_table()` body (single L0 entry, `luma_log2_weight_denom + /// == 2`, `luma_weight_l0_flag == 1`, `delta_luma_weight_l0[0] == 5`, + /// `luma_offset_l0[0] == 0`; chroma flag off). Verifies the in-place + /// PWT decode resolves the §7.4.7.3 derived `LumaWeightL0[0] = (1 << + /// 2) + 5 = 9` correctly and the parser continues to walk the rest + /// of the inter-slice tail through `byte_alignment()`. + #[test] + fn parses_p_slice_in_place_pwt_resolves_luma_weight() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let mut fields: Vec<(u32, u8)> = vec![ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 → L0 = PPS default (0) + ]; + // pred_weight_table() + fields.push(ue_codeword(2)); // luma_log2_weight_denom = 2 + fields.push(se_codeword(0)); // delta_chroma_log2_weight_denom = 0 + fields.push((1, 1)); // luma_weight_l0_flag[0] + fields.push((0, 1)); // chroma_weight_l0_flag[0] + fields.push(se_codeword(5)); // delta_luma_weight_l0[0] + fields.push(se_codeword(0)); // luma_offset_l0[0] + // Inter-slice tail + fields.push(ue_codeword(0)); // five_minus_max_num_merge_cand + fields.push(se_codeword(0)); // slice_qp_delta + fields.push((1, 1)); // slice_loop_filter_across_slices_enabled_flag + fields.push((1, 1)); // byte_alignment '1' + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::P)); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.luma_log2_weight_denom, 2); + assert_eq!(pwt.entries_l0.len(), 1); + assert!(pwt.entries_l0[0].luma_weight_flag); + assert!(!pwt.entries_l0[0].chroma_weight_flag); + assert_eq!(pwt.entries_l0[0].delta_luma_weight, 5); + // §7.4.7.3 derived LumaWeightL0[0] = (1 << 2) + 5 = 9. + assert_eq!(pwt.luma_weight_l0(0), Some(9)); + // The chroma flag is off → derived ChromaWeightL0[0][j] = 1 << + // ChromaLog2WeightDenom = 1 << 2 = 4 (inferred form). + assert_eq!(pwt.chroma_weight_l0(0, 0), Some(4)); + // ChromaOffsetL0[0][j] inferred to 0 when the chroma flag is off. + assert_eq!(pwt.chroma_offset_l0(0, 0, 128), Some(0)); + // Header walked to byte_alignment. + assert!(sh.opaque_tail.is_none()); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// IDR B-slice with `pps.weighted_bipred_flag == 1` and a + /// `pred_weight_table()` body that carries an L1 chroma weight + + /// offset delta. Verifies the in-place call site populates both L0 + /// and L1 entries, the chroma sub-block on L1 is parsed, and the + /// derived `ChromaWeightL1` / `ChromaOffsetL1` resolve correctly. + #[test] + fn parses_b_slice_in_place_pwt_resolves_l1_chroma() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_bipred_flag = true; + let mut fields: Vec<(u32, u8)> = vec![ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id ue -> 0 + (0b1, 1), // slice_type ue -> B + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + (1, 1), // mvd_l1_zero_flag = 1 + ]; + // pred_weight_table() — 1 L0 + 1 L1 entry. + fields.push(ue_codeword(1)); // luma_log2_weight_denom = 1 + fields.push(se_codeword(1)); // delta_chroma_log2_weight_denom = 1 → ChromaLog2WeightDenom = 2 + fields.push((0, 1)); // luma_weight_l0_flag[0] + fields.push((0, 1)); // chroma_weight_l0_flag[0] + fields.push((0, 1)); // luma_weight_l1_flag[0] + fields.push((1, 1)); // chroma_weight_l1_flag[0] = 1 + fields.push(se_codeword(2)); // delta_chroma_weight_l1[0][0] = 2 + fields.push(se_codeword(-1)); // delta_chroma_offset_l1[0][0] = -1 + fields.push(se_codeword(-3)); // delta_chroma_weight_l1[0][1] = -3 + fields.push(se_codeword(0)); // delta_chroma_offset_l1[0][1] = 0 + // Inter-slice tail + fields.push(ue_codeword(0)); // five_minus_max_num_merge_cand + fields.push(se_codeword(0)); // slice_qp_delta + fields.push((1, 1)); // slice_loop_filter_across_slices_enabled_flag + fields.push((1, 1)); // byte_alignment '1' + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::B)); + let pwt = sh.pred_weight_table.as_ref().expect("PWT decoded in place"); + assert_eq!(pwt.luma_log2_weight_denom, 1); + assert_eq!(pwt.chroma_log2_weight_denom(), 2); + assert_eq!(pwt.entries_l0.len(), 1); + assert_eq!(pwt.entries_l1.len(), 1); + assert!(!pwt.entries_l1[0].luma_weight_flag); + assert!(pwt.entries_l1[0].chroma_weight_flag); + assert_eq!(pwt.entries_l1[0].delta_chroma_weight, [2, -3]); + assert_eq!(pwt.entries_l1[0].delta_chroma_offset, [-1, 0]); + // §7.4.7.3 derived ChromaWeightL1[0][j] = (1 << 2) + delta: + // j=0: 4 + 2 = 6; j=1: 4 + (-3) = 1. + assert_eq!(pwt.chroma_weight_l1(0, 0), Some(6)); + assert_eq!(pwt.chroma_weight_l1(0, 1), Some(1)); + // Equation 7-58 with WpOffsetHalfRangeC = 128 (base-profile bit + // depths, high_precision_offsets_enabled_flag = 0): + // j=0: 128 + (-1) - ((128 * 6) >> 2) = 127 - 192 = -65. + // j=1: 128 + 0 - ((128 * 1) >> 2) = 128 - 32 = 96. + assert_eq!(pwt.chroma_offset_l1(0, 0, 128), Some(-65)); + assert_eq!(pwt.chroma_offset_l1(0, 1, 128), Some(96)); + // L0 chroma flag was off → inferred ChromaWeightL0[0][j] = 4. + assert_eq!(pwt.chroma_weight_l0(0, 0), Some(4)); + assert!(sh.opaque_tail.is_none()); + } + + /// A `pred_weight_table()` body that violates the §7.4.7.3 range + /// bound on `delta_luma_weight_l0` (out-of-range value 128) surfaces + /// from the in-place call site as the same + /// [`SliceError::ValueOutOfRange`] the standalone parser raises — + /// the failure must propagate from `SliceSegmentHeader::parse`. + #[test] + fn in_place_pwt_propagates_range_error() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.weighted_pred_flag = true; + let mut fields: Vec<(u32, u8)> = vec![ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id ue -> 0 + (0b010, 3), // slice_type ue -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 → L0 default = 0 + ]; + fields.push(ue_codeword(0)); // luma_log2_weight_denom = 0 + fields.push(se_codeword(0)); // delta_chroma_log2_weight_denom = 0 + fields.push((1, 1)); // luma_weight_l0_flag[0] + fields.push((0, 1)); // chroma_weight_l0_flag[0] + fields.push(se_codeword(128)); // delta_luma_weight_l0[0] = 128 (out of range) + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "delta_luma_weight_l0", + got: 128, + } + ); + } + + /// `five_minus_max_num_merge_cand > 4` is a §7.4.7.1 conformance + /// violation (the derived `MaxNumMergeCand` would fall below 1). + /// Encode wire value 5 as ue(v) = `0b00110` (5 bits). + #[test] + fn rejects_five_minus_max_num_merge_cand_above_4() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (0, 1), // num_ref_idx_active_override_flag = 0 + // mvd / cabac / collocated all inferred absent. + ue_codeword(5), // five_minus_max_num_merge_cand = 5 (illegal) + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "five_minus_max_num_merge_cand", + got: 5, + } + ); + } + + /// `num_ref_idx_l0_active_minus1 > 14` is a range failure (§7.4.7.1). + /// Encode value 15 as ue(v) = `0b000010000` (9 bits). + #[test] + fn rejects_num_ref_idx_l0_active_minus1_above_14() { + let sps = ctx_sps(1, false, true, false, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b010, 3), // slice_type -> P + (1, 1), // sao_luma + (1, 1), // sao_chroma + (1, 1), // num_ref_idx_active_override_flag = 1 + ue_codeword(15), // num_ref_idx_l0_active_minus1 = 15 -> illegal + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_W_RADL, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: 15, + } + ); + } + + /// Non-first dependent slice segment: dependent flag + address are + /// read, then the body ends after SAO (no slice_type etc.). + #[test] + fn parses_dependent_slice_segment() { + // 4-CTB picture (2x2) so slice_segment_address is 2 bits wide. + // PPS must have dependent_slice_segments_enabled_flag; the + // fixture PPS has it 0, so patch a parsed PPS. + let sps = ctx_sps(1, false, true, true, 32, 32, 1, 0, 4); // 32/16=2 -> 2x2=4 CTBs + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.dependent_slice_segments_enabled_flag = true; + // first=0, dependent=1, slice_segment_address u(2)=2, then the + // header ends: every remaining §7.3.6.1 field (slice_type, SAO + // flags, QP, …) lives inside the !dependent gate and is + // inherited from the associated independent slice segment. The + // header goes straight to byte_alignment(). + let bits = concat_bits(&[ + (0, 1), // first_slice_segment_in_pic_flag = 0 + (0b1, 1), // pps_id ue -> 0 + (1, 1), // dependent_slice_segment_flag + (0b10, 2), // slice_segment_address = 2 + (1, 1), // byte_alignment one bit + ]); + let rbsp = pack_bits(&bits); + // Use a non-IRAP type so no_output is absent and the layout + // above matches. + let sh = + SliceSegmentHeader::parse(&rbsp, 0 /* TRAIL_N */, &sps, &pps).expect("slice header"); + assert!(!sh.first_slice_segment_in_pic_flag); + assert!(sh.dependent_slice_segment_flag); + assert_eq!(sh.slice_segment_address, 2); + assert_eq!(sh.slice_type, None); + // SAO flags are not signalled in a dependent segment — they are + // inherited by the caller; the struct leaves them false. + assert!(!sh.slice_sao_luma_flag); + assert!(!sh.slice_sao_chroma_flag); + assert!(sh.opaque_tail.is_none()); + assert_eq!(sh.byte_offset_to_slice_data, Some(1)); + } + + #[test] + fn rejects_truncated_rbsp() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + // Only one byte; first bit reads ok but ue() for pps_id runs off + // a short enough buffer eventually. Use an empty buffer to force + // truncation on the very first read. + let err = SliceSegmentHeader::parse(&[], IDR_N_LP, &sps, &pps).unwrap_err(); + assert_eq!(err, SliceError::Truncated); + } + + #[test] + fn rejects_slice_type_out_of_range() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + // slice_type ue(v) = 3 ('00100') is out of Table 7-7 range. + let bits = concat_bits(&[ + (1, 1), // first + (0, 1), // no_output (IDR) + (0b1, 1), // pps_id -> 0 + (0b00100, 5), // slice_type ue -> 3 (illegal) + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).unwrap_err(); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "slice_type", + got: 3 + } + ); + } + + #[test] + fn end_to_end_via_nal_walker() { + use crate::nal::collect_nal_units; + // Build an Annex B stream carrying a single IDR_N_LP slice NAL + // whose RBSP is the hand-assembled I-slice header from + // `parses_hand_assembled_i_idr_header`. + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output_of_prior_pics_flag (IRAP) + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + (1, 1), // slice_sao_luma_flag + (0, 1), // slice_sao_chroma_flag + (0b011, 3), // slice_qp_delta se -> -1 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (1, 1), // byte_alignment one bit + ]); + let body = pack_bits(&bits); + // NAL header for IDR_N_LP (type 20), layer 0, temporal_id 0. + let b0 = (IDR_N_LP & 0x3F) << 1; + let b1 = 0x01; // temporal_id_plus1 = 1 + let mut stream = vec![0x00, 0x00, 0x01, b0, b1]; + stream.extend_from_slice(&body); + let units = collect_nal_units(&stream).expect("walker"); + assert_eq!(units.len(), 1); + let u = &units[0]; + assert_eq!(u.header.nal_unit_type, IDR_N_LP); + let sh = SliceSegmentHeader::parse(&u.rbsp, u.header.nal_unit_type, &sps, &pps) + .expect("slice header"); + assert_eq!(sh.slice_type, Some(SliceType::I)); + assert_eq!(sh.slice_qp_delta, Some(-1)); + assert_eq!(sh.slice_qp_y(&pps), Some(25)); + } + + // --- §7.3.6.2 ref_pic_lists_modification() --- + + /// Hand-build a `ref_pic_lists_modification()` RBSP and parse it for + /// a P slice with the modification flag set and a single L0 entry. + /// `NumPicTotalCurr == 2` so the per-entry width is + /// `Ceil(Log2(2)) == 1` bit. With `num_ref_idx_l0_active_minus1 == + /// 0` the loop reads exactly one `list_entry_l0`. The bits are: + /// `ref_pic_list_modification_flag_l0` (1) = 1 + /// `list_entry_l0[0]` (u(1)) = 1 + /// (B-only L1 fields are absent for a P slice.) + #[test] + fn parses_p_slice_l0_only_modification() { + let bits = concat_bits(&[(1, 1), (1, 1)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse( + &mut br, + SliceType::P, + 0, /* num_ref_idx_l0_active_minus1 */ + 0, /* num_ref_idx_l1_active_minus1 (ignored for P) */ + 2, /* NumPicTotalCurr */ + ) + .expect("ref_pic_lists_modification"); + + assert!(m.ref_pic_list_modification_flag_l0); + assert_eq!(m.list_entry_l0, vec![1]); + // P slice: list-1 fields absent. + assert!(m.ref_pic_list_modification_flag_l1.is_none()); + assert!(m.list_entry_l1.is_empty()); + // Exactly 2 bits consumed. + assert_eq!(br.bit_pos(), 2); + } + + /// B slice with both list-0 and list-1 modifications active. + /// `NumPicTotalCurr == 4` so the per-entry width is + /// `Ceil(Log2(4)) == 2` bits. With both `num_ref_idx_lX_active_minus1 + /// == 1` each list contributes 2 entries. + /// flag_l0 (1)=1 + /// list_entry_l0[0] u(2)=0b10=2 + /// list_entry_l0[1] u(2)=0b00=0 + /// flag_l1 (1)=1 + /// list_entry_l1[0] u(2)=0b01=1 + /// list_entry_l1[1] u(2)=0b11=3 + /// Total = 1 + 2 + 2 + 1 + 2 + 2 = 10 bits. + #[test] + fn parses_b_slice_both_lists_modification() { + let bits = concat_bits(&[ + (1, 1), // ref_pic_list_modification_flag_l0 + (0b10, 2), // list_entry_l0[0] = 2 + (0b00, 2), // list_entry_l0[1] = 0 + (1, 1), // ref_pic_list_modification_flag_l1 + (0b01, 2), // list_entry_l1[0] = 1 + (0b11, 2), // list_entry_l1[1] = 3 + ]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse(&mut br, SliceType::B, 1, 1, 4).expect("parse"); + + assert!(m.ref_pic_list_modification_flag_l0); + assert_eq!(m.list_entry_l0, vec![2, 0]); + assert_eq!(m.ref_pic_list_modification_flag_l1, Some(true)); + assert_eq!(m.list_entry_l1, vec![1, 3]); + assert_eq!(br.bit_pos(), 10); + } + + /// B slice where the L0 modification flag is 0 (implicit + /// derivation): the L0 entry list is empty, and the L1 flag is + /// read immediately after. `NumPicTotalCurr == 3` so per-entry + /// width is `Ceil(Log2(3)) == 2` bits. + /// flag_l0 (1)=0 + /// flag_l1 (1)=1 + /// list_entry_l1[0] u(2)=0b10=2 + /// 4 bits total; the parser must NOT have consumed any L0 entries. + #[test] + fn parses_b_slice_l0_implicit_l1_explicit() { + let bits = concat_bits(&[(0, 1), (1, 1), (0b10, 2)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse(&mut br, SliceType::B, 0, 0, 3).expect("parse"); + + assert!(!m.ref_pic_list_modification_flag_l0); + assert!(m.list_entry_l0.is_empty()); + assert_eq!(m.ref_pic_list_modification_flag_l1, Some(true)); + assert_eq!(m.list_entry_l1, vec![2]); + assert_eq!(br.bit_pos(), 4); + } + + /// Both flags zero: a minimal degenerate case where the entire + /// structure is two bits and produces empty entry lists. + #[test] + fn parses_b_slice_both_flags_zero() { + let bits = concat_bits(&[(0, 1), (0, 1)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse(&mut br, SliceType::B, 0, 0, 2).expect("parse"); + + assert!(!m.ref_pic_list_modification_flag_l0); + assert!(m.list_entry_l0.is_empty()); + assert_eq!(m.ref_pic_list_modification_flag_l1, Some(false)); + assert!(m.list_entry_l1.is_empty()); + assert_eq!(br.bit_pos(), 2); + } + + /// P slice with `flag_l0 == 0`: exactly one bit consumed, no list + /// entries, and no L1 fields present. + #[test] + fn parses_p_slice_l0_implicit() { + let bits = concat_bits(&[(0, 1)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse(&mut br, SliceType::P, 14, 14, 5).expect("parse"); + + assert!(!m.ref_pic_list_modification_flag_l0); + assert!(m.list_entry_l0.is_empty()); + assert!(m.ref_pic_list_modification_flag_l1.is_none()); + assert!(m.list_entry_l1.is_empty()); + assert_eq!(br.bit_pos(), 1); + } + + /// §7.4.7.2 range check: `list_entry_l0[i]` must be + /// `< NumPicTotalCurr`. With `NumPicTotalCurr == 3` the per-entry + /// width is 2 bits, so the value `3` (0b11) is legally encodable + /// but is rejected by the range check. + #[test] + fn list_entry_l0_value_must_be_less_than_num_pic_total_curr() { + let bits = concat_bits(&[ + (1, 1), // flag_l0 + (0b11, 2), // list_entry_l0[0] = 3 — illegal: must be <= 2 + ]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::P, 0, 0, 3) + .expect_err("out-of-range entry must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "list_entry_l0", + got: 3, + } + ); + } + + /// §7.4.7.2 range check for L1: same rule, exercised through the + /// B-slice branch. + #[test] + fn list_entry_l1_value_must_be_less_than_num_pic_total_curr() { + // NumPicTotalCurr=2 → entry width=1 bit, max value=1. Send a + // legal L0 (flag=0) then an explicit L1 (flag=1, entry=1 OK, + // then we cannot encode 2 in 1 bit so use a 3-curr setup + // instead to exercise the range check.) + // Use NumPicTotalCurr=3 (2-bit entries) so 0b11=3 is illegal. + let bits = concat_bits(&[ + (0, 1), // flag_l0 + (1, 1), // flag_l1 + (0b11, 2), // list_entry_l1[0] = 3 — illegal + ]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::B, 0, 0, 3) + .expect_err("out-of-range L1 entry must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "list_entry_l1", + got: 3, + } + ); + } + + /// The §7.3.6.2 structure is only signalled for inter slices. The + /// parser rejects an I-slice call up front rather than reading any + /// bits (the bitreader position must stay at 0). + #[test] + fn rejects_i_slice_call() { + let rbsp = [0xFFu8; 4]; + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::I, 0, 0, 2) + .expect_err("I-slice call must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "ref_pic_lists_modification/slice_type", + got: 2, + } + ); + assert_eq!(br.bit_pos(), 0); + } + + /// The §7.3.6.1 gate guarantees `NumPicTotalCurr > 1`. The parser + /// rejects a call with `NumPicTotalCurr <= 1` (a defensive + /// pre-condition). + #[test] + fn rejects_num_pic_total_curr_le_1() { + let rbsp = [0xFFu8; 4]; + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::P, 0, 0, 1) + .expect_err("NumPicTotalCurr <= 1 must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "ref_pic_lists_modification/NumPicTotalCurr", + got: 1, + } + ); + assert_eq!(br.bit_pos(), 0); + + let mut br2 = BitReader::new(&rbsp); + let err2 = RefPicListsModification::parse(&mut br2, SliceType::B, 0, 0, 0) + .expect_err("NumPicTotalCurr == 0 must error"); + assert_eq!( + err2, + SliceError::ValueOutOfRange { + field: "ref_pic_lists_modification/NumPicTotalCurr", + got: 0, + } + ); + } + + /// `num_ref_idx_l0_active_minus1` is constrained to 0..=14 by + /// §7.4.7.1. The parser rejects a call that violates that bound, + /// matching the precondition documented on + /// [`RefPicListsModification::parse`]. + #[test] + fn rejects_num_ref_idx_l0_out_of_range() { + let rbsp = [0xFFu8; 4]; + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::P, 15, 0, 2) + .expect_err("num_ref_idx_l0_active_minus1 > 14 must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "num_ref_idx_l0_active_minus1", + got: 15, + } + ); + } + + /// Same check for L1, exercised through the B-slice branch (the + /// L1 bound is only validated for B slices). + #[test] + fn rejects_num_ref_idx_l1_out_of_range() { + let rbsp = [0xFFu8; 4]; + let mut br = BitReader::new(&rbsp); + let err = RefPicListsModification::parse(&mut br, SliceType::B, 0, 15, 2) + .expect_err("num_ref_idx_l1_active_minus1 > 14 must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "num_ref_idx_l1_active_minus1", + got: 15, + } + ); + } + + /// Maximum-active-index case: 15 entries per list (the §7.4.7.1 + /// cap, `num_ref_idx_lX_active_minus1 == 14`), with + /// `NumPicTotalCurr == 8` (3-bit entries). Bit accounting: + /// flag_l0 (1) + 15 * 3 = 46 bits for the L0 portion. + /// The P slice has no L1 fields, so the test verifies the parser + /// reads exactly 46 bits. + #[test] + fn max_active_minus1_p_slice_l0() { + let mut fields: Vec<(u32, u8)> = vec![(1, 1)]; // flag_l0 = 1 + for i in 0..15u32 { + // entry value = i mod 8 ∈ 0..=7, fits in 3 bits, in range. + fields.push((i % 8, 3)); + } + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = RefPicListsModification::parse(&mut br, SliceType::P, 14, 0, 8).expect("parse"); + assert!(m.ref_pic_list_modification_flag_l0); + assert_eq!(m.list_entry_l0.len(), 15); + for (i, &v) in m.list_entry_l0.iter().enumerate() { + assert_eq!(v, (i as u32) % 8); + } + assert_eq!(br.bit_pos(), 1 + 15 * 3); + } + + /// `Ceil(Log2(N))` width: confirm the per-entry width matches the + /// §7.4.7.2 formula for a representative set of `NumPicTotalCurr` + /// values by reading exactly the expected bit count from a flag=1 + /// L0 with a single entry. + #[test] + fn entry_width_matches_ceil_log2() { + // (num_pic_total_curr, expected_bits_per_entry) + let cases: &[(u32, u8)] = &[(2, 1), (3, 2), (4, 2), (5, 3), (8, 3), (9, 4), (16, 4)]; + for &(curr, w) in cases { + // bit layout: flag_l0=1 then list_entry_l0[0]=0 + let mut bits: Vec = vec![1]; + bits.resize(1 + w as usize, 0); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let m = + RefPicListsModification::parse(&mut br, SliceType::P, 0, 0, curr).expect("parse"); + assert_eq!(m.list_entry_l0, vec![0]); + assert_eq!(br.bit_pos(), 1 + w as usize, "curr={curr} width={w}"); + } + } + + /// Truncated RBSP: the parser surfaces [`SliceError::Truncated`] + /// if the buffer runs out mid-element. + #[test] + fn truncated_buffer_surfaces_truncated_error() { + // flag_l0=1 declared but no bits remain for list_entry_l0[0]. + let bits: Vec = vec![1]; + let rbsp = pack_bits(&bits); // one byte: 0b1000_0000 + // Restrict the reader to the first bit only. + let buf = &rbsp[..0]; // zero bytes; even flag_l0 fails + let mut br = BitReader::new(buf); + let err = RefPicListsModification::parse(&mut br, SliceType::P, 0, 0, 4) + .expect_err("empty buffer must error"); + assert_eq!(err, SliceError::Truncated); + } + + // --- §7.4.7.2 NumPicTotalCurr derivation --- + + /// Equation 7-57 with only short-term entries: two negative pics + /// both used (`UsedByCurrPicS0 = [1, 1]`), one positive pic not + /// used (`UsedByCurrPicS1 = [0]`), and no long-term entries. + /// Expected: `NumPicTotalCurr = 2`. + #[test] + fn num_pic_total_curr_short_term_only() { + let s0 = [true, true]; + let s1 = [false]; + let lt: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <); + assert_eq!(inputs.compute(), 2); + } + + /// Equation 7-57 with a mix of S0, S1 and long-term entries + /// flagged "used by current pic". Hand-derived: 2 S0 ones (3 + /// flags, 2 set) + 1 S1 one (2 flags, 1 set) + 2 LT ones (3 flags, + /// 2 set) = 5. + #[test] + fn num_pic_total_curr_mixed_short_and_long_term() { + let s0 = [true, false, true]; + let s1 = [true, false]; + let lt = [true, false, true]; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <); + assert_eq!(inputs.compute(), 5); + } + + /// Equation 7-57 with `pps_curr_pic_ref_enabled_flag == 1` adding + /// the final `NumPicTotalCurr++`. With zero short-term and zero + /// long-term contributions, the value is exactly 1 (the IBC / + /// self-reference case the SCC PPS flag enables). + #[test] + fn num_pic_total_curr_curr_pic_ref_only() { + let s0: [bool; 0] = []; + let s1: [bool; 0] = []; + let lt: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <) + .with_pps_curr_pic_ref_enabled(true); + assert_eq!(inputs.compute(), 1); + } + + /// Equation 7-57 with every contributing source: 1 S0 + 1 S1 + + /// 1 LT + `pps_curr_pic_ref_enabled_flag` = 4. + #[test] + fn num_pic_total_curr_all_contributors() { + let s0 = [true]; + let s1 = [true]; + let lt = [true]; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <) + .with_pps_curr_pic_ref_enabled(true); + assert_eq!(inputs.compute(), 4); + } + + /// Empty short-term RPS + empty long-term + no SCC self-ref = + /// `NumPicTotalCurr == 0`. The §7.4.7.1 conformance rule "when + /// the current picture contains a P or B slice, the value of + /// NumPicTotalCurr shall not be equal to 0" is the consumer's + /// responsibility — this primitive returns the literal + /// equation-7-57 value. + #[test] + fn num_pic_total_curr_zero_when_nothing_contributes() { + let s0: [bool; 0] = []; + let s1: [bool; 0] = []; + let lt: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <); + assert_eq!(inputs.compute(), 0); + } + + /// Build a short-term RPS in *explicit* form with three negative + /// and two positive pics, then derive `NumPicTotalCurr` via + /// [`NumPicTotalCurrInputs::from_explicit_short_term_rps`]. + /// Negative used flags `[1, 0, 1]` + positive `[1, 1]` + no LT = + /// 2 + 2 + 0 = 4. + #[test] + fn num_pic_total_curr_from_explicit_rps_builder() { + let rps = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 3, + num_positive_pics: 2, + delta_poc_s0_minus1: vec![0, 1, 2], + used_by_curr_pic_s0_flag: vec![true, false, true], + delta_poc_s1_minus1: vec![0, 1], + used_by_curr_pic_s1_flag: vec![true, true], + ..Default::default() + }; + let lt: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_explicit_short_term_rps(&rps, <) + .expect("explicit RPS yields builder"); + assert_eq!(inputs.compute(), 4); + } + + /// The explicit-RPS builder refuses an inter-RPS-predicted RPS: + /// the §7.4.8 derivation (equations 7-58..7-66) must run first to + /// resolve the per-position `UsedByCurrPicSX` arrays, and the + /// result fed through [`NumPicTotalCurrInputs::from_used_flags`]. + #[test] + fn num_pic_total_curr_from_explicit_rps_rejects_inter_prediction() { + let rps = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + ..Default::default() + }; + let lt: [bool; 0] = []; + assert!(NumPicTotalCurrInputs::from_explicit_short_term_rps(&rps, <).is_none()); + } + + /// §7.4.7.1 / §7.4.7.2 long-term resolution: + /// [`SliceLongTermRefPic::used_by_curr_pic_lt`] reads the SPS + /// table when the entry is `Sps { lt_idx_sps }`, and the in-slice + /// flag when the entry is `InSlice { used_by_curr_pic_lt_flag }`. + /// Construct an SPS with two LT entries (`[used=1, used=0]`) and + /// verify the SPS lookup; then verify the in-slice form. + #[test] + fn used_by_curr_pic_lt_resolves_sps_table_and_in_slice() { + let mut sps = ctx_sps(1, false, false, false, 16, 16, 0, 0, 4); + sps.long_term_ref_pics_present_flag = true; + sps.num_long_term_ref_pics_sps = 2; + sps.long_term_ref_pics = vec![ + LongTermRefPicEntry { + poc_lsb: 0, + used_by_curr_pic: true, + }, + LongTermRefPicEntry { + poc_lsb: 1, + used_by_curr_pic: false, + }, + ]; + + let sps_entry_used = SliceLongTermRefPic { + source: SliceLongTermRefPicSource::Sps { lt_idx_sps: 0 }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }; + assert_eq!(sps_entry_used.used_by_curr_pic_lt(&sps), Some(true)); + + let sps_entry_unused = SliceLongTermRefPic { + source: SliceLongTermRefPicSource::Sps { lt_idx_sps: 1 }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }; + assert_eq!(sps_entry_unused.used_by_curr_pic_lt(&sps), Some(false)); + + let in_slice_used = SliceLongTermRefPic { + source: SliceLongTermRefPicSource::InSlice { + poc_lsb_lt: 7, + used_by_curr_pic_lt_flag: true, + }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }; + assert_eq!(in_slice_used.used_by_curr_pic_lt(&sps), Some(true)); + + // Out-of-range SPS index surfaces `None`. + let sps_oob = SliceLongTermRefPic { + source: SliceLongTermRefPicSource::Sps { lt_idx_sps: 99 }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }; + assert_eq!(sps_oob.used_by_curr_pic_lt(&sps), None); + } + + /// End-to-end: build the long-term ref list a §7.3.6.1 slice + /// header would carry (one SPS-resident `used == 1` entry + one + /// in-slice `used == 0` entry + one in-slice `used == 1` entry), + /// resolve each entry's `UsedByCurrPicLt[i]`, and feed the bool + /// vector through equation 7-57. With empty short-term sets the + /// result is 2. + #[test] + fn num_pic_total_curr_from_resolved_slice_long_term_list() { + let mut sps = ctx_sps(1, false, false, false, 16, 16, 0, 0, 4); + sps.long_term_ref_pics_present_flag = true; + sps.num_long_term_ref_pics_sps = 1; + sps.long_term_ref_pics = vec![LongTermRefPicEntry { + poc_lsb: 0, + used_by_curr_pic: true, + }]; + + let slice_lt = [ + SliceLongTermRefPic { + source: SliceLongTermRefPicSource::Sps { lt_idx_sps: 0 }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }, + SliceLongTermRefPic { + source: SliceLongTermRefPicSource::InSlice { + poc_lsb_lt: 4, + used_by_curr_pic_lt_flag: false, + }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }, + SliceLongTermRefPic { + source: SliceLongTermRefPicSource::InSlice { + poc_lsb_lt: 8, + used_by_curr_pic_lt_flag: true, + }, + delta_poc_msb_present_flag: false, + delta_poc_msb_cycle_lt: 0, + }, + ]; + let used_lt: Vec = slice_lt + .iter() + .map(|e| e.used_by_curr_pic_lt(&sps).expect("in-range")) + .collect(); + let s0: [bool; 0] = []; + let s1: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, &used_lt); + assert_eq!(inputs.compute(), 2); + } + + /// F.7.4.7.2 multilayer-extension form (equation `F-56`): when + /// the slice's `nal_unit_type` is IDR, the short-term and + /// long-term loops are SKIPPED entirely, so the count starts at 0 + /// and only `pps_curr_pic_ref_enabled_flag` + the + /// `NumActiveRefLayerPics` summand contribute. Feed + /// `used_by_curr_pic_*` flags that would each contribute 1 under + /// equation 7-57 — they must be ignored. + #[test] + fn num_pic_total_curr_multilayer_skips_temporal_loops_for_idr() { + let s0 = [true]; + let s1 = [true]; + let lt = [true]; + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <) + .with_multilayer_extension(IDR_W_RADL, 3); + // Skipped loops contribute 0; pps_curr_pic_ref_enabled = false; + // NumActiveRefLayerPics = 3. + assert_eq!(inputs.compute(), 3); + + // Same inputs but flipping the SCC self-ref flag: +1 = 4. + let inputs = NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <) + .with_pps_curr_pic_ref_enabled(true) + .with_multilayer_extension(IDR_N_LP, 3); + assert_eq!(inputs.compute(), 4); + } + + /// F.7.4.7.2 multilayer-extension form for a *non-IDR* slice: the + /// short-term and long-term loops are NOT skipped, so the count + /// matches the base-spec 7-57 result plus + /// `NumActiveRefLayerPics`. + /// 1 (S0) + 1 (S1) + 1 (LT) + 2 (NumActiveRefLayerPics) = 5. + #[test] + fn num_pic_total_curr_multilayer_keeps_loops_for_non_idr() { + let s0 = [true]; + let s1 = [true]; + let lt = [true]; + // TRAIL_N (Table 7-1 value 0) is not IDR. + let inputs = + NumPicTotalCurrInputs::from_used_flags(&s0, &s1, <).with_multilayer_extension(0, 2); + assert_eq!(inputs.compute(), 5); + } + + /// §7.3.6.1 gate sanity: `NumPicTotalCurr > 1` is the condition + /// under which the slice header signals `ref_pic_lists_modification()`. + /// Compose an explicit-form RPS that would yield exactly 1 (one + /// `UsedByCurrPicS0` flag set, nothing else) and confirm + /// `NumPicTotalCurr == 1` — the §7.3.6.1 gate would not fire. + /// Then compose one that yields 2 (two flags set) and confirm the + /// gate would fire. This is a derivation cross-check, not a + /// parser invocation. + #[test] + fn num_pic_total_curr_drives_section_7_3_6_1_gate() { + let rps_one = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 1, + num_positive_pics: 0, + delta_poc_s0_minus1: vec![0], + used_by_curr_pic_s0_flag: vec![true], + ..Default::default() + }; + let lt: [bool; 0] = []; + let inputs = NumPicTotalCurrInputs::from_explicit_short_term_rps(&rps_one, <).unwrap(); + assert_eq!(inputs.compute(), 1, "gate should not fire at 1"); + + let rps_two = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + num_negative_pics: 2, + num_positive_pics: 0, + delta_poc_s0_minus1: vec![0, 1], + used_by_curr_pic_s0_flag: vec![true, true], + ..Default::default() + }; + let inputs = NumPicTotalCurrInputs::from_explicit_short_term_rps(&rps_two, <).unwrap(); + assert_eq!(inputs.compute(), 2, "gate fires at 2"); + } + + // --- §7.3.6.3 pred_weight_table() --- + + /// Build the `ue(v)` codeword for a value `v` (Table 9-3). Returns + /// `(value, width_in_bits)` ready for [`concat_bits`]. + fn ue_codeword(v: u32) -> (u32, u8) { + let plus1 = v + 1; + let m = 32 - plus1.leading_zeros() - 1; // floor(log2(v+1)) + let width = (2 * m + 1) as u8; + (plus1, width) + } + + /// `se(v)` codeword: map signed to unsigned per the §9.2.1 inverse + /// of Table 9-3 (`codeNum = 2*|v| - (v > 0 ? 1 : 0)`), then encode + /// the result as an `ue(v)`. + fn se_codeword(v: i32) -> (u32, u8) { + let code_num: u32 = if v <= 0 { + (2 * (-v)) as u32 + } else { + (2 * v - 1) as u32 + }; + ue_codeword(code_num) + } + + /// Minimal monochrome P-slice case (`ChromaArrayType == 0` so no + /// chroma fields are signalled): one reference, `luma_weight_l0_flag + /// == 1`, `delta_luma_weight_l0[0] == 5`, `luma_offset_l0[0] == 0`. + /// + /// Bit layout: + /// ```text + /// luma_log2_weight_denom ue(v) = 2 -> 0b011 (3 bits) + /// luma_weight_l0_flag[0] u(1) = 1 -> 0b1 (1 bit) + /// delta_luma_weight_l0[0] se(v) = 5 -> codeNum=9, ue(v)=0b0001010 (7 bits) + /// luma_offset_l0[0] se(v) = 0 -> codeNum=0, ue(v)=0b1 (1 bit) + /// ``` + /// total = 3 + 1 + 7 + 1 = 12 bits. + #[test] + fn parses_monochrome_p_slice_single_ref() { + let mut fields = vec![ue_codeword(2)]; // luma_log2_weight_denom + fields.push((1, 1)); // luma_weight_l0_flag[0] + fields.push(se_codeword(5)); // delta_luma_weight_l0[0] + fields.push(se_codeword(0)); // luma_offset_l0[0] + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile( + SliceType::P, + 0, + 0, + /*ChromaArrayType*/ 0, + 8, + 8, + ); + let pwt = PredWeightTable::parse(&mut br, &inputs).expect("parse"); + + assert_eq!(pwt.luma_log2_weight_denom, 2); + assert_eq!(pwt.delta_chroma_log2_weight_denom, 0); // absent → inferred 0 + assert_eq!(pwt.entries_l0.len(), 1); + assert!(pwt.entries_l0[0].luma_weight_flag); + assert!(!pwt.entries_l0[0].chroma_weight_flag); // monochrome + assert_eq!(pwt.entries_l0[0].delta_luma_weight, 5); + assert_eq!(pwt.entries_l0[0].luma_offset, 0); + assert!(pwt.entries_l1.is_empty()); + // 12 bits consumed. + assert_eq!(br.bit_pos(), 12); + // Derived: LumaWeightL0[0] = (1 << 2) + 5 = 9 + assert_eq!(pwt.luma_weight_l0(0), Some(9)); + } + + /// P-slice with `ChromaArrayType == 1` (4:2:0), one reference, + /// every flag = 1. Verifies the chroma sub-block parses and the + /// derived `ChromaLog2WeightDenom`, `ChromaWeightL0[0][j]` and + /// `ChromaOffsetL0[0][j]` resolve correctly. + /// + /// Bit layout: + /// ```text + /// luma_log2_weight_denom ue(v) = 1 -> 0b010 + /// delta_chroma_log2_weight_denom se(v) = 1 -> codeNum=1, ue(v)=0b010 + /// luma_weight_l0_flag[0] u(1) = 1 + /// chroma_weight_l0_flag[0] u(1) = 1 + /// delta_luma_weight_l0[0] se(v) = -3 -> codeNum=6, ue(v)=0b00111 + /// luma_offset_l0[0] se(v) = 7 -> codeNum=13, ue(v)=0b0001110 + /// delta_chroma_weight_l0[0][0] se(v) = 0 -> 0b1 + /// delta_chroma_offset_l0[0][0] se(v) = 2 -> codeNum=3, ue(v)=0b00100 + /// delta_chroma_weight_l0[0][1] se(v) = 0 -> 0b1 + /// delta_chroma_offset_l0[0][1] se(v) = -1 -> codeNum=2, ue(v)=0b011 + /// ``` + #[test] + fn parses_p_slice_420_single_ref_with_chroma() { + let mut fields = vec![ue_codeword(1)]; + fields.push(se_codeword(1)); + fields.push((1, 1)); // luma_weight_l0_flag + fields.push((1, 1)); // chroma_weight_l0_flag + fields.push(se_codeword(-3)); + fields.push(se_codeword(7)); + fields.push(se_codeword(0)); + fields.push(se_codeword(2)); + fields.push(se_codeword(0)); + fields.push(se_codeword(-1)); + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, 0, 0, 1, 8, 8); + let pwt = PredWeightTable::parse(&mut br, &inputs).expect("parse"); + + assert_eq!(pwt.luma_log2_weight_denom, 1); + assert_eq!(pwt.delta_chroma_log2_weight_denom, 1); + assert_eq!(pwt.chroma_log2_weight_denom(), 2); + assert_eq!(pwt.entries_l0[0].delta_luma_weight, -3); + assert_eq!(pwt.entries_l0[0].luma_offset, 7); + assert_eq!(pwt.entries_l0[0].delta_chroma_weight, [0, 0]); + assert_eq!(pwt.entries_l0[0].delta_chroma_offset, [2, -1]); + // Derived: LumaWeightL0[0] = (1 << 1) + (-3) = -1 + assert_eq!(pwt.luma_weight_l0(0), Some(-1)); + // ChromaWeightL0[0][j] = (1 << 2) + 0 = 4 for j ∈ {0, 1} + assert_eq!(pwt.chroma_weight_l0(0, 0), Some(4)); + assert_eq!(pwt.chroma_weight_l0(0, 1), Some(4)); + // Equation 7-58 with WpOffsetHalfRangeC = 128: + // raw_j0 = 128 + 2 - ((128 * 4) >> 2) = 130 - 128 = 2 + // raw_j1 = 128 + (-1) - 128 = -1 + assert_eq!(pwt.chroma_offset_l0(0, 0, 128), Some(2)); + assert_eq!(pwt.chroma_offset_l0(0, 1, 128), Some(-1)); + } + + /// B-slice with `ChromaArrayType == 1`, one ref per list, all flags + /// off (the minimal-content B case). Verifies the L1 block is + /// reached and the chroma flag pass is read on both lists; absent + /// deltas remain at 0; derived `LumaWeightLX[0]` inferred to + /// `1 << luma_log2_weight_denom`. + /// + /// Bit layout (denoms then four flag bits, all 0; L1 mirrors L0): + /// ```text + /// luma_log2_weight_denom ue(v) = 0 -> 0b1 + /// delta_chroma_log2_weight_denom se(v) = 0 -> 0b1 + /// luma_weight_l0_flag[0] u(1) = 0 + /// chroma_weight_l0_flag[0] u(1) = 0 + /// luma_weight_l1_flag[0] u(1) = 0 + /// chroma_weight_l1_flag[0] u(1) = 0 + /// ``` + /// 2 bits denoms + 4 bits flags = 6 bits. + #[test] + fn parses_b_slice_all_flags_zero() { + let mut fields = vec![ue_codeword(0), se_codeword(0)]; + fields.push((0, 1)); + fields.push((0, 1)); + fields.push((0, 1)); + fields.push((0, 1)); + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::B, 0, 0, 1, 8, 8); + let pwt = PredWeightTable::parse(&mut br, &inputs).expect("parse"); + + assert_eq!(pwt.entries_l0.len(), 1); + assert_eq!(pwt.entries_l1.len(), 1); + assert!(!pwt.entries_l0[0].luma_weight_flag); + assert!(!pwt.entries_l1[0].chroma_weight_flag); + // No deltas were signalled; absent values inferred to 0. + assert_eq!(pwt.entries_l0[0].delta_luma_weight, 0); + assert_eq!(pwt.entries_l1[0].delta_chroma_offset, [0, 0]); + // Derived LumaWeightLX[0] = (1 << 0) + 0 = 1 (inferred form). + assert_eq!(pwt.luma_weight_l0(0), Some(1)); + assert_eq!(pwt.luma_weight_l1(0), Some(1)); + // ChromaOffsetLX[i][j] inferred to 0 when chroma_weight_flag == 0. + assert_eq!(pwt.chroma_offset_l0(0, 0, 128), Some(0)); + assert_eq!(pwt.chroma_offset_l1(0, 1, 128), Some(0)); + assert_eq!(br.bit_pos(), 6); + } + + /// `luma_log2_weight_denom > 7` is a range failure (§7.4.7.3). + /// `ue(v)` value 8 encodes as `0b0001001` (7 bits). + #[test] + fn rejects_luma_log2_weight_denom_above_7() { + let bits = concat_bits(&[ue_codeword(8)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, 0, 0, 0, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "luma_log2_weight_denom", + got: 8, + } + ); + } + + /// `ChromaLog2WeightDenom = luma_log2_weight_denom + + /// delta_chroma_log2_weight_denom` ∈ 0..=7 (§7.4.7.3). Encode + /// `luma_log2_weight_denom == 3, delta_chroma_log2_weight_denom == + /// 5` → derived = 8, must error. + #[test] + fn rejects_derived_chroma_log2_weight_denom_above_7() { + let bits = concat_bits(&[ue_codeword(3), se_codeword(5)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, 0, 0, 1, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "ChromaLog2WeightDenom", + got: 8, + } + ); + } + + /// `delta_luma_weight_l0[i]` ∉ −128..=127 must error (§7.4.7.3). + /// `se(v)` value 128 encodes via codeNum = 255 → ue(v) is 15 bits + /// long; pack it and verify the parser surfaces ValueOutOfRange. + #[test] + fn rejects_delta_luma_weight_l0_above_127() { + let mut fields = vec![ue_codeword(0)]; + fields.push((1, 1)); // luma_weight_l0_flag = 1 + fields.push(se_codeword(128)); // out of range + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, 0, 0, 0, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "delta_luma_weight_l0", + got: 128, + } + ); + } + + /// `luma_offset_l0[i]` ∈ `−128..=127` for base profile (8 bits, no + /// high-precision offsets). Encode value 128 → range failure. + #[test] + fn rejects_luma_offset_l0_above_127_at_8_bit() { + let mut fields = vec![ue_codeword(0)]; + fields.push((1, 1)); // flag = 1 + fields.push(se_codeword(0)); // delta_luma_weight = 0 (in range) + fields.push(se_codeword(128)); // luma_offset = 128 out of range + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, 0, 0, 0, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "luma_offset_l0", + got: 128, + } + ); + } + + /// `high_precision_offsets_enabled_flag == true` widens + /// `WpOffsetHalfRangeY` from `1 << 7 = 128` to + /// `1 << (BitDepthY - 1)`. With `BitDepthY == 10` the new range is + /// `−512..=511`. Encode `luma_offset_l0 == 200` (was out-of-range + /// at 8-bit, in-range at 10-bit high-precision) and verify parse + /// succeeds. + #[test] + fn accepts_luma_offset_in_high_precision_range() { + let mut fields = vec![ue_codeword(0)]; + fields.push((1, 1)); + fields.push(se_codeword(0)); + fields.push(se_codeword(200)); + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs { + slice_type: SliceType::P, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + chroma_array_type: 0, + high_precision_offsets_enabled_flag: true, + bit_depth_y: 10, + bit_depth_c: 10, + signal_luma_l0: None, + signal_chroma_l0: None, + signal_luma_l1: None, + signal_chroma_l1: None, + }; + let pwt = PredWeightTable::parse(&mut br, &inputs).expect("parse"); + assert_eq!(pwt.entries_l0[0].luma_offset, 200); + } + + /// §7.3.6.3 outer gate: when the caller passes + /// `signal_luma_l0[i] == false`, the corresponding flag bit is NOT + /// consumed from the bitstream and the parsed flag is inferred to + /// `false`. Build a two-ref P slice with `signal_luma_l0 = [false, + /// true]`: only one luma-flag bit is present (the second), and + /// the parser must read exactly the right bits. + /// + /// Bit layout (monochrome, n_l0=2): + /// ```text + /// luma_log2_weight_denom ue(v) = 0 -> 0b1 (1) + /// luma_weight_l0_flag[1] u(1) = 1 (1) + /// delta_luma_weight_l0[1] se(v) = 4 -> codeNum=7, ue(v)=0b0001000 (7) + /// luma_offset_l0[1] se(v) = 0 -> 0b1 (1) + /// ``` + /// Total = 10 bits. + #[test] + fn outer_gate_suppresses_per_i_flag_bits() { + let mut fields = vec![ue_codeword(0)]; + fields.push((1, 1)); // luma_weight_l0_flag[1] + fields.push(se_codeword(4)); // delta_luma_weight_l0[1] + fields.push(se_codeword(0)); + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + + let gate_l0 = [false, true]; + let inputs = PredWeightTableInputs { + slice_type: SliceType::P, + num_ref_idx_l0_active_minus1: 1, + num_ref_idx_l1_active_minus1: 0, + chroma_array_type: 0, + high_precision_offsets_enabled_flag: false, + bit_depth_y: 8, + bit_depth_c: 8, + signal_luma_l0: Some(&gate_l0), + signal_chroma_l0: None, + signal_luma_l1: None, + signal_chroma_l1: None, + }; + let pwt = PredWeightTable::parse(&mut br, &inputs).expect("parse"); + assert_eq!(pwt.entries_l0.len(), 2); + assert!(!pwt.entries_l0[0].luma_weight_flag); // gated off → inferred 0 + assert!(pwt.entries_l0[1].luma_weight_flag); + assert_eq!(pwt.entries_l0[1].delta_luma_weight, 4); + // Position 0's deltas remain at the inferred default (0). + assert_eq!(pwt.entries_l0[0].delta_luma_weight, 0); + assert_eq!(pwt.entries_l0[0].luma_offset, 0); + // Bit accounting matches the expected layout. + assert_eq!(br.bit_pos(), 10); + } + + /// Per-i gate slice length mismatch is a precondition failure. + #[test] + fn rejects_signal_slice_length_mismatch() { + let bits = concat_bits(&[ue_codeword(0)]); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let gate_too_short = [true]; // num_ref_idx_l0_active_minus1 + 1 == 2 + let inputs = PredWeightTableInputs { + slice_type: SliceType::P, + num_ref_idx_l0_active_minus1: 1, + num_ref_idx_l1_active_minus1: 0, + chroma_array_type: 0, + high_precision_offsets_enabled_flag: false, + bit_depth_y: 8, + bit_depth_c: 8, + signal_luma_l0: Some(&gate_too_short), + signal_chroma_l0: None, + signal_luma_l1: None, + signal_chroma_l1: None, + }; + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "signal_luma_l0", + got: 1, + } + ); + } + + /// Rejects an I-slice call (the §7.3.6.1 gate + /// `weighted_pred_flag && slice_type == P` / + /// `weighted_bipred_flag && slice_type == B` excludes I slices). + #[test] + fn rejects_i_slice_call_pwt() { + let rbsp = [0xFFu8; 4]; + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::I, 0, 0, 0, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "pred_weight_table/slice_type", + got: 2, + } + ); + assert_eq!(br.bit_pos(), 0); + } + + /// §7.4.7.3 conformance: for a P slice, `sumWeightL0Flags ≤ 24`. + /// Each entry contributes up to 3 (luma=1, chroma=2), so 9 entries + /// with both flags set sum to 27, breaching the cap. Build the + /// minimal P-slice case with 9 entries (`num_ref_idx_l0_active_minus1 + /// = 8`) and verify the parser rejects. + #[test] + fn rejects_sum_weight_l0_above_24() { + let mut fields = vec![ue_codeword(0), se_codeword(0)]; + let n = 9usize; + // 9 luma_weight_l0_flag bits, all 1 + for _ in 0..n { + fields.push((1, 1)); + } + // 9 chroma_weight_l0_flag bits, all 1 + for _ in 0..n { + fields.push((1, 1)); + } + // Per-entry deltas (luma + chroma): delta=0, offset=0 + for _ in 0..n { + fields.push(se_codeword(0)); // delta_luma_weight + fields.push(se_codeword(0)); // luma_offset + for _ in 0..2 { + fields.push(se_codeword(0)); // delta_chroma_weight + fields.push(se_codeword(0)); // delta_chroma_offset + } + } + let bits = concat_bits(&fields); + let rbsp = pack_bits(&bits); + let mut br = BitReader::new(&rbsp); + let inputs = PredWeightTableInputs::base_profile(SliceType::P, (n - 1) as u8, 0, 1, 8, 8); + let err = PredWeightTable::parse(&mut br, &inputs).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "sumWeightL0Flags", + got: 27, + } + ); + } + + /// I-slice with WPP enabled (`entropy_coding_sync_enabled_flag == + /// 1`): the §7.3.6.1 entry-point block is signalled with + /// `num_entry_point_offsets = 2`, `offset_len_minus1 = 3` (each + /// entry is `u(4)`), and per-row byte offsets `{6, 9}`. Verify + /// the parser captures the offsets verbatim and exposes the + /// per-subset byte length via [`EntryPointOffsets::subset_length`] + /// (`entry_point_offset_minus1[i] + 1`, §7.4.7.1). + #[test] + fn parses_wpp_entry_point_offsets_in_place() { + // Tall enough picture for two WPP entry points: 3 CTU rows. + // With CTB size = 16 (`log2_min_cb_minus3 = 0`, + // `log2_diff_max_min_cb = 1`) and `pic_height = 48`, + // `PicHeightInCtbsY = 3`, so the upper bound on + // `num_entry_point_offsets` is 2. + let sps = ctx_sps(1, false, true, true, 16, 48, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.entropy_coding_sync_enabled_flag = true; + + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output (IRAP) + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + // slice_temporal_mvp_enabled_flag: absent for an IDR. + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + // Entry-point block. + (0b011, 3), // num_entry_point_offsets ue -> 2 + (0b00100, 5), // offset_len_minus1 ue -> 3 (entries are u(4)) + (6, 4), // entry_point_offset_minus1[0] + (9, 4), // entry_point_offset_minus1[1] + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect("slice header"); + let eps = sh.entry_point_offsets.expect("entry-point block present"); + assert_eq!(eps.num_entry_point_offsets, 2); + assert_eq!(eps.offset_len_minus1, 3); + assert_eq!(eps.entry_point_offset_minus1, vec![6, 9]); + // §7.4.7.1 subset length is `entry_point_offset_minus1[i] + 1`. + assert_eq!(eps.subset_length(0), Some(7)); + assert_eq!(eps.subset_length(1), Some(10)); + assert_eq!(eps.subset_length(2), None); + assert!(sh.byte_offset_to_slice_data.is_some()); + } + + /// Tiles enabled with a single tile (`num_tile_columns_minus1 == + /// 0`, `num_tile_rows_minus1 == 0`): the §7.4.7.1 upper bound on + /// `num_entry_point_offsets` is `1 * 1 − 1 == 0`, so the block is + /// present (the gate fires on `tiles_enabled_flag`) but + /// `num_entry_point_offsets` must be 0 and the `offset_len_minus1` + /// / per-entry loop are skipped. Verify the parser materialises an + /// empty vec and reports a bare gate. + #[test] + fn parses_tiles_block_with_single_tile_no_offsets() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.tiles_enabled_flag = true; + // tiles inferred default (cols=0, rows=0 minus1 → 1×1). + + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + // slice_temporal_mvp_enabled_flag: absent for an IDR. + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // slice_loop_filter_across_slices_enabled_flag + (0b1, 1), // num_entry_point_offsets ue -> 0 + (1, 1), // byte_alignment '1' + ]); + let rbsp = pack_bits(&bits); + let sh = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect("slice header"); + let eps = sh.entry_point_offsets.expect("entry-point block present"); + assert_eq!(eps.num_entry_point_offsets, 0); + assert_eq!(eps.offset_len_minus1, 0); + assert!(eps.entry_point_offset_minus1.is_empty()); + assert!(eps.subset_length(0).is_none()); + } + + /// §7.4.7.1: when `entropy_coding_sync_enabled_flag == 1`, the + /// upper bound on `num_entry_point_offsets` is `PicHeightInCtbsY − + /// 1`. Build an SPS with `PicHeightInCtbsY == 1` (16×16 with CTB + /// size 16): the bound is 0, so a wire value of 1 must fail the + /// range check. + #[test] + fn rejects_wpp_entry_point_offsets_above_pic_height_bound() { + let sps = ctx_sps(1, false, true, true, 16, 16, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.entropy_coding_sync_enabled_flag = true; + + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output (IRAP); tmvp flag absent for an IDR + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // lf_across + (0b010, 3), // num_entry_point_offsets ue -> 1, breaches bound 0 + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "num_entry_point_offsets", + got: 1, + } + ); + } + + /// §7.4.7.1: `offset_len_minus1` is bounded to `0..=31`. Build a + /// WPP-enabled fixture with a wire value of 32 and verify the + /// parser rejects. + #[test] + fn rejects_offset_len_minus1_above_31() { + let sps = ctx_sps(1, false, true, true, 16, 48, 1, 0, 4); + let mut pps = PicParameterSet::parse(TINY_PPS_RBSP).expect("PPS"); + pps.entropy_coding_sync_enabled_flag = true; + + let bits = concat_bits(&[ + (1, 1), // first_slice_segment_in_pic_flag + (0, 1), // no_output (IRAP); tmvp flag absent for an IDR + (0b1, 1), // pps_id ue -> 0 + (0b011, 3), // slice_type ue -> I + (1, 1), // sao_luma + (0, 1), // sao_chroma + (0b1, 1), // slice_qp_delta se -> 0 + (1, 1), // lf_across + (0b010, 3), // num_entry_point_offsets ue -> 1 + // offset_len_minus1 = 32, encoded ue: codeNum 32 has + // M = floor(log2(33)) = 5 leading zeros, then '1', then + // 5-bit suffix (33 - 32 = 1 → 00001). 11 bits total: + // 00000 1 00001 → 0b000_0010_0001. + (0b000_0010_0001, 11), + ]); + let rbsp = pack_bits(&bits); + let err = SliceSegmentHeader::parse(&rbsp, IDR_N_LP, &sps, &pps).expect_err("must error"); + assert_eq!( + err, + SliceError::ValueOutOfRange { + field: "offset_len_minus1", + got: 32, + } + ); + } + + // --- bit-packing test helpers --- + + /// A `(value, width)` pair to be packed MSB-first. + type BitField = (u32, u8); + + /// Concatenate `(value, width)` fields into a single bit vector + /// (each entry's `width` low bits of `value`, MSB-first). + fn concat_bits(fields: &[BitField]) -> Vec { + let mut bits = Vec::new(); + for &(value, width) in fields { + for i in (0..width).rev() { + bits.push(((value >> i) & 1) as u8); + } + } + bits + } + + /// Pack an MSB-first bit vector into bytes, zero-padding the final + /// byte (matching `byte_alignment()`'s zero pad). + fn pack_bits(bits: &[u8]) -> Vec { + let mut out = vec![0u8; bits.len().div_ceil(8)]; + for (i, &b) in bits.iter().enumerate() { + if b != 0 { + out[i / 8] |= 1 << (7 - (i % 8)); + } + } + out + } +} diff --git a/vendor/oxideav-h265/src/slice_data.rs b/vendor/oxideav-h265/src/slice_data.rs new file mode 100644 index 0000000..4ac1e7a --- /dev/null +++ b/vendor/oxideav-h265/src/slice_data.rs @@ -0,0 +1,1527 @@ +//! §7.3.8.1 .. §7.3.8.6 slice-data CABAC syntax-element walk. +//! +//! This module is the upper rung of the §7.3.8 slice-data parse loop: +//! it drives the CABAC engine through the per-CTU syntax structures — +//! §7.3.8.3 `sao( )`, §7.3.8.4 `coding_tree_unit( )` / +//! `coding_quadtree( )`, §7.3.8.5 `coding_unit( )`, and §7.3.8.6 +//! `prediction_unit( )` — composing the §7.3.8.3 / §7.3.8.5 / §7.3.8.6 +//! leaf decode primitives ([`crate::binarization`]) with the already +//! implemented §7.3.8.8 `transform_tree( )` recursion +//! ([`crate::transform_tree`]) and its §7.3.8.10 `transform_unit( )` +//! leaf. +//! +//! The driver produces a structured parse tree (`CodingTreeUnit` → +//! `CodingQuadtree` → `CodingUnit`) rather than reconstructed samples: +//! it decodes the complete CABAC syntax-element stream of a CTU, which +//! is the prerequisite the §8.4 / §8.5 picture-reconstruction passes +//! consume. Picture-level neighbour availability (§6.4.1) and the +//! `CtDepth` / `cu_skip_flag` neighbour grids feeding the §9.3.4.2.2 +//! `split_cu_flag` / `cu_skip_flag` ctxInc derivations are carried by +//! the picture-level [`PictureParseState`] (per-4×4-cell grids gated on +//! the §6.4.1 slice / tile availability), so a coding block's left / +//! above neighbour reads work across CTU boundaries. +//! +//! The §6.5.1 quantization-group reset (`IsCuQpDeltaCoded`, +//! `CuQpDeltaVal`, `IsCuChromaQpOffsetCoded`) is performed by the +//! §7.3.8.4 `coding_quadtree( )` walk at each node whose `log2CbSize` +//! meets the `Log2MinCuQpDeltaSize` / `Log2MinCuChromaQpOffsetSize` +//! threshold, mirroring the syntax table; the resulting +//! [`crate::transform_unit::QuantGroupState`] is threaded into the +//! transform tree. + +use crate::binarization::{ + cu_pred_mode_from_flag, cu_pred_mode_from_skip, cu_skip_flag_ctx_inc, decode_cu_skip_flag, + decode_cu_transquant_bypass_flag, decode_end_of_slice_segment_flag, decode_inter_pred_idc, + decode_intra_chroma_pred_mode, decode_merge_flag, decode_merge_idx, decode_mpm_idx, + decode_mvd_pair, decode_mvp_flag, decode_part_mode, decode_pcm_flag, decode_pred_mode_flag, + decode_prev_intra_luma_pred_flag, decode_ref_idx, decode_rem_intra_luma_pred_mode, + decode_rqt_root_cbf, decode_sao_band_position, decode_sao_eo_class, decode_sao_merge_flag, + decode_sao_offset_abs, decode_sao_offset_sign, decode_sao_type_idx, decode_split_cu_flag, + derive_intra_pred_mode_c, derive_intra_pred_mode_y, intra_luma_cand_mode_list, + luma_intra_mode_source_from_flag, split_cu_flag_ctx_inc, CuPredMode, InterPredIdc, + LumaIntraModeSource, MvdComponent, PartMode, PartModeResult, +}; +use crate::cabac::CabacEngine; +use crate::ctx_init::SliceContexts; +use crate::intra_mode_field::{IntraModeField, Neighbour}; +use crate::residual::ResidualCodingError; +use crate::transform_tree::{decode_transform_tree, TransformTree, TransformTreeParams}; +use crate::transform_unit::{CuPredMode as TuCuPredMode, QuantGroupState, TransformUnitParams}; + +/// Map the §7.3.8.5 [`binarization::CuPredMode`](CuPredMode) (which +/// carries the `MODE_SKIP` not-present variant) to the two-state +/// [`crate::transform_unit::CuPredMode`] the transform tree / unit +/// consume. A skip CU never enters the transform tree (it has no +/// residual), so `Skip` collapses to `Inter` defensively. +fn to_tu_pred_mode(m: CuPredMode) -> TuCuPredMode { + match m { + CuPredMode::Intra => TuCuPredMode::Intra, + CuPredMode::Inter | CuPredMode::Skip => TuCuPredMode::Inter, + } +} + +/// Per-CTU sequence / picture / slice constants the §7.3.8 walk reads. +/// These derive from the active SPS / PPS / slice header (§7.4.3) and +/// are constant for one slice segment's worth of CTUs. +#[derive(Debug, Clone, Copy)] +pub struct SliceDataParams { + /// `CtbLog2SizeY` (§7.4.3.2) — the luma coding-tree-block log2 size. + pub ctb_log2_size_y: u32, + /// `MinCbLog2SizeY` (§7.4.3.2) — the minimum luma coding-block log2 + /// size; bounds the §7.3.8.4 `split_cu_flag` presence gate. + pub min_cb_log2_size_y: u32, + /// `MaxTbLog2SizeY` (§7.4.3.2). + pub max_tb_log2_size_y: u32, + /// `MinTbLog2SizeY` (§7.4.3.2). + pub min_tb_log2_size_y: u32, + /// `pic_width_in_luma_samples` (§7.4.3.2.1). + pub pic_width_in_luma_samples: u32, + /// `pic_height_in_luma_samples` (§7.4.3.2.1). + pub pic_height_in_luma_samples: u32, + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, + /// 3 = 4:4:4). + pub chroma_array_type: u8, + /// `BitDepthY` (§7.4.3.2.1) — used by §7.3.8.3 `sao_offset_abs`. + pub bit_depth_luma: u32, + /// `BitDepthC` (§7.4.3.2.1) — used by §7.3.8.3 `sao_offset_abs`. + pub bit_depth_chroma: u32, + /// `slice_type == I` (§7.4.7.1). + pub slice_type_is_i: bool, + /// `slice_type == B` (§7.4.7.1). + pub slice_type_is_b: bool, + /// `slice_sao_luma_flag` (§7.4.7.1). + pub slice_sao_luma_flag: bool, + /// `slice_sao_chroma_flag` (§7.4.7.1). + pub slice_sao_chroma_flag: bool, + /// `transquant_bypass_enabled_flag` (§7.4.3.3.1). + pub transquant_bypass_enabled_flag: bool, + /// `cu_qp_delta_enabled_flag` (§7.4.3.3.1). + pub cu_qp_delta_enabled_flag: bool, + /// `Log2MinCuQpDeltaSize` (§7.4.3.3.1) = `CtbLog2SizeY − + /// diff_cu_qp_delta_depth`. + pub log2_min_cu_qp_delta_size: u32, + /// per-slice `cu_chroma_qp_offset_enabled_flag` (§7.4.9.10). + pub cu_chroma_qp_offset_enabled_flag: bool, + /// `Log2MinCuChromaQpOffsetSize` (§7.4.3.3.1). + pub log2_min_cu_chroma_qp_offset_size: u32, + /// `chroma_qp_offset_list_len_minus1` (§7.4.3.3.1). + pub chroma_qp_offset_list_len_minus1: u32, + /// `amp_enabled_flag` (§7.4.3.2.1). + pub amp_enabled_flag: bool, + /// PCM block: `pcm_enabled_flag` (§7.4.3.2.1). + pub pcm_enabled_flag: bool, + /// `Log2MinIpcmCbSizeY` (§7.4.3.2.1). + pub log2_min_ipcm_cb_size_y: u32, + /// `Log2MaxIpcmCbSizeY` (§7.4.3.2.1). + pub log2_max_ipcm_cb_size_y: u32, + /// `PcmBitDepthY` (§7.4.3.2.1 equation 7-25; meaningful only when + /// [`Self::pcm_enabled_flag`]). + pub pcm_bit_depth_luma: u32, + /// `PcmBitDepthC` (§7.4.3.2.1 equation 7-26). + pub pcm_bit_depth_chroma: u32, + /// `max_transform_hierarchy_depth_intra` (§7.4.3.2.1). + pub max_transform_hierarchy_depth_intra: u32, + /// `max_transform_hierarchy_depth_inter` (§7.4.3.2.1). + pub max_transform_hierarchy_depth_inter: u32, + /// `MaxNumMergeCand` (§7.4.7.1) — `5 − + /// five_minus_max_num_merge_cand`. + pub max_num_merge_cand: u32, + /// `num_ref_idx_l0_active_minus1` (§7.4.7.1). + pub num_ref_idx_l0_active_minus1: u32, + /// `num_ref_idx_l1_active_minus1` (§7.4.7.1). + pub num_ref_idx_l1_active_minus1: u32, + /// `mvd_l1_zero_flag` (§7.4.7.1). + pub mvd_l1_zero_flag: bool, + /// PPS `sign_data_hiding_enabled_flag` (§7.4.3.3.1). + pub sign_data_hiding_enabled_flag: bool, + /// PPS `cross_component_prediction_enabled_flag` (§7.4.3.3.1). + pub cross_component_prediction_enabled_flag: bool, + /// SCC `residual_adaptive_colour_transform_enabled_flag` + /// (§7.4.3.3.1). + pub residual_adaptive_colour_transform_enabled_flag: bool, + /// PPS `transform_skip_enabled_flag` (§7.4.3.3.1) — the §7.3.8.11 + /// `transform_skip_flag` presence gate. + pub transform_skip_enabled_flag: bool, + /// `Log2MaxTransformSkipSize` (§7.4.3.3.2) — + /// `log2_max_transform_skip_block_size_minus2 + 2` (2 when the PPS + /// range extension is absent). + pub log2_max_transform_skip_size: u32, + /// SPS range extension `implicit_rdpcm_enabled_flag` (§7.4.3.2.2) + /// — part of the §7.3.8.11 `signHidden` condition. + pub implicit_rdpcm_enabled_flag: bool, + /// SPS range extension `explicit_rdpcm_enabled_flag` (§7.4.3.2.2) + /// — the §7.3.8.11 `explicit_rdpcm_flag` presence gate. + pub explicit_rdpcm_enabled_flag: bool, + /// SPS range extension `transform_skip_context_enabled_flag` + /// (§7.4.3.2.2) — the §9.3.4.2.5 transform-skip sig-ctx gate. + pub transform_skip_context_enabled_flag: bool, + /// SPS range extension `persistent_rice_adaptation_enabled_flag` + /// (§7.4.3.2.2) — the §9.3.3.11 StatCoeff Rice path. + pub persistent_rice_adaptation_enabled_flag: bool, + /// SPS range extension `cabac_bypass_alignment_enabled_flag` + /// (§7.4.3.2.2) — the §9.3.4.3.6 aligned bypass decoding gate. + pub cabac_bypass_alignment_enabled_flag: bool, + /// SPS range extension `extended_precision_processing_flag` + /// (§7.4.3.2.2) — the §9.3.3.4 limited-EGk escape suffix gate. + pub extended_precision_processing_flag: bool, + /// SCC `palette_mode_enabled_flag` (§7.4.3.2.3) — the §7.3.8.5 + /// `palette_mode_flag` presence gate. + pub palette_mode_enabled_flag: bool, + /// SCC `palette_max_size` (§7.4.3.2.3). + pub palette_max_size: u32, + /// `PaletteMaxPredictorSize` (eq. 7-35). + pub palette_max_predictor_size: u32, +} + +/// §7.4.9.3 decoded SAO parameters for one colour component of one CTB. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SaoComponent { + /// `SaoTypeIdx[cIdx][rx][ry]` — 0 (not applied), 1 (band offset), + /// 2 (edge offset). + pub sao_type_idx: u8, + /// `sao_offset_abs[cIdx][rx][ry][0..4]` magnitudes. + pub offset_abs: [u32; 4], + /// `sao_offset_sign[cIdx][rx][ry][0..4]` (band offset only). + pub offset_sign: [u8; 4], + /// `sao_band_position[cIdx][rx][ry]` (band offset only). + pub band_position: u8, + /// `SaoEoClass[cIdx][rx][ry]` (edge offset only). + pub eo_class: u8, +} + +/// §7.3.8.3 decoded SAO parameters for one CTB (all three components). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SaoCtbParams { + /// `sao_merge_left_flag` — this CTB copies the left CTB's params. + pub merge_left: bool, + /// `sao_merge_up_flag` — this CTB copies the above CTB's params. + pub merge_up: bool, + /// Per-component parameters: `[Y, Cb, Cr]`. Only populated when + /// neither merge flag is set (otherwise the caller resolves the + /// merged source). + pub components: [SaoComponent; 3], +} + +/// One decoded §7.3.8.5 `coding_unit( )`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodingUnit { + /// Luma top-left position `(x0, y0)`. + pub x0: u32, + /// Luma top-left position `(x0, y0)`. + pub y0: u32, + /// `log2CbSize`. + pub log2_cb_size: u32, + /// `CuPredMode[x0][y0]`. + pub cu_pred_mode: CuPredMode, + /// `cu_transquant_bypass_flag`. + pub cu_transquant_bypass_flag: bool, + /// `PartMode` (§7.4.9.5). + pub part_mode: PartMode, + /// `pcm_flag[x0][y0]`. + pub pcm_flag: bool, + /// §7.3.8.7 PCM sample payload (`Some` iff [`Self::pcm_flag`]), + /// already scaled to the picture bit depth per §8.4.1 + /// equation 8-12 (`pcm_sample << (BitDepth − PcmBitDepth)`). + pub pcm: Option, + /// §7.3.8.13 palette coding unit payload (`Some` iff + /// `palette_mode_flag == 1`; such a CU has no prediction units and + /// no transform tree). + pub palette: Option>, + /// Decoded prediction units (intra: empty — the luma/chroma intra + /// modes carry the prediction; inter: 1..=4 entries). + pub prediction_units: Vec, + /// `prev_intra_luma_pred_flag` / `mpm_idx` / + /// `rem_intra_luma_pred_mode` per luma prediction block (intra + /// only), in §7.3.8.5 PB-loop order. + pub intra_luma: Vec, + /// `intra_chroma_pred_mode` values (intra only). + pub intra_chroma_pred_mode: Vec, + /// `rqt_root_cbf` (inter only; intra CUs always enter the tree). + pub rqt_root_cbf: bool, + /// The decoded §7.3.8.8 transform tree, present when the CU codes + /// residual (`!pcm_flag && (intra || rqt_root_cbf)`). + pub transform_tree: Option, +} + +/// §7.3.8.5 per-luma-prediction-block intra-mode signalling. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct IntraLumaMode { + /// `prev_intra_luma_pred_flag[xPb][yPb]`. + pub prev_intra_luma_pred_flag: bool, + /// `mpm_idx[xPb][yPb]` (present when `prev_intra_luma_pred_flag`). + pub mpm_idx: Option, + /// `rem_intra_luma_pred_mode[xPb][yPb]` (present otherwise). + pub rem_intra_luma_pred_mode: Option, +} + +/// §7.3.8.6 one decoded `prediction_unit( )`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PredictionUnit { + /// `merge_flag[x0][y0]` (`false` for a skip CU, which carries only + /// `merge_idx`). + pub merge_flag: bool, + /// `merge_idx[x0][y0]` (present for skip or merge). + pub merge_idx: Option, + /// `inter_pred_idc[x0][y0]` (present for non-merge B PUs; a P-slice + /// non-merge PU is `PRED_L0`). + pub inter_pred_idc: Option, + /// `ref_idx_l0[x0][y0]` (present for L0/BI non-merge PUs). + pub ref_idx_l0: Option, + /// `mvd_coding(…, 0)` (present for L0/BI non-merge PUs). + pub mvd_l0: Option<[MvdComponent; 2]>, + /// `mvp_l0_flag[x0][y0]`. + pub mvp_l0_flag: Option, + /// `ref_idx_l1[x0][y0]` (present for L1/BI non-merge PUs). + pub ref_idx_l1: Option, + /// `mvd_coding(…, 1)` (present for L1/BI non-merge PUs unless the + /// `mvd_l1_zero_flag && PRED_BI` zero-inference path applies). + pub mvd_l1: Option<[MvdComponent; 2]>, + /// `mvp_l1_flag[x0][y0]`. + pub mvp_l1_flag: Option, +} + +/// One node of a decoded §7.3.8.4 `coding_quadtree( )`: a split node +/// with up to four in-picture children, or a leaf coding unit. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum CodingQuadtree { + /// `split_cu_flag == 1`: the present (in-picture) children, raster + /// order; off-picture children are absent (the §7.3.8.4 boundary + /// `if( x1 < … )` guards). + Split(Vec), + /// `split_cu_flag == 0`: a leaf coding unit. + Leaf(Box), +} + +/// One decoded §7.3.8.2 `coding_tree_unit( )`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct CodingTreeUnit { + /// The §7.3.8.3 SAO parameters, when `slice_sao_luma_flag || + /// slice_sao_chroma_flag`. + pub sao: Option, + /// The §7.3.8.4 coding-quadtree root. + pub quadtree: CodingQuadtree, +} + +/// Picture-level parse state threaded across the CTUs of a picture. +/// +/// The §7.3.8 walk needs the **derived** `IntraPredModeY` / +/// `IntraPredModeC` of every intra prediction block *during* parsing: +/// the §7.4.9.11 `residual_coding( )` scan order of a 4×4 / 8×8 intra +/// transform block depends on the actual prediction mode, and that mode +/// comes from the §8.4.2 most-probable-mode derivation over the left / +/// above neighbour blocks — potentially in a different CTU. This state +/// carries the per-4×4 [`IntraModeField`] plus the per-CTB +/// `SliceAddrRs` / `TileId` grids that gate the §6.4.1 neighbour +/// availability. +#[derive(Debug)] +pub struct PictureParseState { + field: IntraModeField, + ctb_log2: u32, + pic_width: u32, + pic_height: u32, + pic_w_ctbs: u32, + /// Per-CTB `(SliceAddrRs, TileId)`, `None` until the CTU is begun. + ctb_info: Vec>, + /// The current CTU's `(SliceAddrRs, TileId)`. + cur: (u32, u32), + /// Per-4×4-cell `CtDepth` (−1 = not yet decoded) — the §9.3.4.2.2 + /// `split_cu_flag` ctxInc neighbour reads. + ct_depth: Vec, + /// Per-4×4-cell `cu_skip_flag` — the §9.3.4.2.2 `cu_skip_flag` + /// ctxInc neighbour reads. + cu_skip: Vec, + w_cells: usize, + h_cells: usize, +} + +impl PictureParseState { + /// A fresh per-picture state sized from the slice-data params. + #[must_use] + pub fn new(params: &SliceDataParams) -> Self { + let ctb = 1u32 << params.ctb_log2_size_y; + let w_ctbs = params.pic_width_in_luma_samples.div_ceil(ctb); + let h_ctbs = params.pic_height_in_luma_samples.div_ceil(ctb); + let w_cells = (params.pic_width_in_luma_samples as usize).div_ceil(4); + let h_cells = (params.pic_height_in_luma_samples as usize).div_ceil(4); + Self { + field: IntraModeField::new( + params.pic_width_in_luma_samples as usize, + params.pic_height_in_luma_samples as usize, + params.ctb_log2_size_y, + ), + ctb_log2: params.ctb_log2_size_y, + pic_width: params.pic_width_in_luma_samples, + pic_height: params.pic_height_in_luma_samples, + pic_w_ctbs: w_ctbs, + ctb_info: vec![None; (w_ctbs * h_ctbs) as usize], + cur: (0, 0), + ct_depth: vec![-1; w_cells * h_cells], + cu_skip: vec![0; w_cells * h_cells], + w_cells, + h_cells, + } + } + + fn cell(&self, x: u32, y: u32) -> usize { + ((y as usize) >> 2).min(self.h_cells - 1) * self.w_cells + + ((x as usize) >> 2).min(self.w_cells - 1) + } + + /// Record a coding block's `CtDepth` + `cu_skip_flag` over its area + /// (the §9.3.4.2.2 neighbour state for later blocks). + fn record_cu_depth(&mut self, x0: u32, y0: u32, log2_cb_size: u32, depth: u8, skip: u8) { + let n = 1u32 << log2_cb_size; + let x1 = (x0 + n).min(self.pic_width); + let y1 = (y0 + n).min(self.pic_height); + for y in (y0..y1).step_by(4) { + for x in (x0..x1).step_by(4) { + let c = self.cell(x, y); + self.ct_depth[c] = depth as i8; + self.cu_skip[c] = skip; + } + } + } + + /// `(CtDepth, available)` of the neighbour of `(x0, y0)` — the + /// §9.3.4.2.2 `split_cu_flag` ctxInc read, gated on the §6.4.1 + /// availability (in-picture, decoded, same slice, same tile). + fn neighbour_ct_depth(&self, x0: u32, y0: u32, neighbour: Neighbour) -> (u32, bool) { + let (x_nb, y_nb) = match neighbour { + Neighbour::Left => (x0.wrapping_sub(1), y0), + Neighbour::Above => (x0, y0.wrapping_sub(1)), + }; + if !self.neighbour_available(x0, y0, neighbour) { + return (0, false); + } + let d = self.ct_depth[self.cell(x_nb, y_nb)]; + if d < 0 { + return (0, false); + } + (d as u32, true) + } + + /// `(cu_skip_flag, available)` of the neighbour of `(x0, y0)` — the + /// §9.3.4.2.2 `cu_skip_flag` ctxInc read. + fn neighbour_cu_skip(&self, x0: u32, y0: u32, neighbour: Neighbour) -> (u8, bool) { + let (x_nb, y_nb) = match neighbour { + Neighbour::Left => (x0.wrapping_sub(1), y0), + Neighbour::Above => (x0, y0.wrapping_sub(1)), + }; + if !self.neighbour_available(x0, y0, neighbour) { + return (0, false); + } + let c = self.cell(x_nb, y_nb); + if self.ct_depth[c] < 0 { + return (0, false); + } + (self.cu_skip[c], true) + } + + /// Mark the CTU at `(x_ctb, y_ctb)` as belonging to slice segment + /// sequence `slice_addr_rs` and tile `tile_id` — called before its + /// syntax decode so same-CTU neighbour queries resolve. + pub fn begin_ctu(&mut self, x_ctb: u32, y_ctb: u32, slice_addr_rs: u32, tile_id: u32) { + let rs = (y_ctb >> self.ctb_log2) * self.pic_w_ctbs + (x_ctb >> self.ctb_log2); + if let Some(slot) = self.ctb_info.get_mut(rs as usize) { + *slot = Some((slice_addr_rs, tile_id)); + } + self.cur = (slice_addr_rs, tile_id); + } + + /// §6.4.1 availability of the left / above neighbour of the block at + /// `(x_pb, y_pb)`: in-picture, already decoded (the mode field's + /// `written` test), same slice and same tile. + fn neighbour_available(&self, x_pb: u32, y_pb: u32, neighbour: Neighbour) -> bool { + let (x_nb, y_nb) = match neighbour { + Neighbour::Left => (x_pb as i64 - 1, y_pb as i64), + Neighbour::Above => (x_pb as i64, y_pb as i64 - 1), + }; + if x_nb < 0 + || y_nb < 0 + || x_nb >= i64::from(self.pic_width) + || y_nb >= i64::from(self.pic_height) + { + return false; + } + let rs = + ((y_nb as u32) >> self.ctb_log2) * self.pic_w_ctbs + ((x_nb as u32) >> self.ctb_log2); + match self.ctb_info.get(rs as usize).copied().flatten() { + // §6.4.1: a neighbour in a different slice segment sequence + // or a different tile is unavailable. + Some(info) => info == self.cur, + // The neighbour's CTU has not been decoded yet. + None => false, + } + } + + /// §8.4.2 — derive `IntraPredModeY` for one luma prediction block + /// from the decoded signalling + the neighbour mode field, then + /// record it for later neighbours. + fn derive_and_record_luma_mode( + &mut self, + x_pb: u32, + y_pb: u32, + n_pb: u32, + luma: &IntraLumaMode, + ) -> u8 { + let avail_a = self.neighbour_available(x_pb, y_pb, Neighbour::Left); + let avail_b = self.neighbour_available(x_pb, y_pb, Neighbour::Above); + let cand_a = + self.field + .cand_intra_pred_mode(x_pb as usize, y_pb as usize, Neighbour::Left, avail_a); + let cand_b = self.field.cand_intra_pred_mode( + x_pb as usize, + y_pb as usize, + Neighbour::Above, + avail_b, + ); + let cand_list = intra_luma_cand_mode_list(cand_a, cand_b); + let source = luma_intra_mode_source_from_flag(u8::from(luma.prev_intra_luma_pred_flag)); + let field_val = match source { + LumaIntraModeSource::Mpm => luma.mpm_idx.unwrap_or(0), + LumaIntraModeSource::Remaining => luma.rem_intra_luma_pred_mode.unwrap_or(0), + }; + let mode = derive_intra_pred_mode_y(cand_list, source, field_val); + self.field + .record_intra_pb(x_pb as usize, y_pb as usize, n_pb as usize, mode, false); + mode + } + + /// Record a PCM coding unit (its neighbours see `INTRA_DC`). + fn record_pcm_cu(&mut self, x0: u32, y0: u32, n_cb: u32) { + self.field + .record_intra_pb(x0 as usize, y0 as usize, n_cb as usize, 1, true); + } + + /// Record an inter / skip coding unit (its neighbours see + /// `INTRA_DC`). + fn record_non_intra_cu(&mut self, x0: u32, y0: u32, n_cb: u32, mode: CuPredMode) { + self.field + .record_non_intra_cu(x0 as usize, y0 as usize, n_cb as usize, mode); + } + + /// Debug: the parse-time §8.4.2 derived mode recorded at a luma + /// location. + #[doc(hidden)] + #[must_use] + pub fn debug_mode_at(&self, x: u32, y: u32) -> Option { + self.field.recorded_mode(x as usize, y as usize) + } +} + +/// Decode one §7.3.8.3 `sao( rx, ry )` syntax structure. +/// +/// `merge_left_allowed` / `merge_up_allowed` are the §7.3.8.3 presence +/// conditions for the two merge flags (`rx > 0 && leftCtbInSliceSeg && +/// leftCtbInTile` and the symmetric up condition), already evaluated by +/// the caller against the §6.5 tile / slice geometry. When the merge +/// path is taken the per-component fields are left at their defaults. +pub fn decode_sao( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + merge_left_allowed: bool, + merge_up_allowed: bool, +) -> Result { + let mut out = SaoCtbParams::default(); + + if merge_left_allowed { + out.merge_left = decode_sao_merge_flag(engine, &mut ctx.sao_merge_flag[0])? != 0; + } + if merge_up_allowed && !out.merge_left { + out.merge_up = decode_sao_merge_flag(engine, &mut ctx.sao_merge_flag[0])? != 0; + } + if out.merge_left || out.merge_up { + return Ok(out); + } + + let num_comp = if params.chroma_array_type != 0 { 3 } else { 1 }; + for c_idx in 0..num_comp { + let read = (params.slice_sao_luma_flag && c_idx == 0) + || (params.slice_sao_chroma_flag && c_idx > 0); + if !read { + continue; + } + // sao_type_idx_luma (cIdx 0) / sao_type_idx_chroma (cIdx 1) are + // both read from the wire (sharing the Table 9-5 bank). For + // cIdx == 2 the §7.3.8.3 syntax has no read — SaoTypeIdx[2] is + // inferred equal to SaoTypeIdx[1] (§7.4.9.3). + let type_idx = if c_idx < 2 { + decode_sao_type_idx(engine, &mut ctx.sao_type_idx[0])? + } else { + out.components[1].sao_type_idx + }; + out.components[c_idx as usize].sao_type_idx = type_idx; + + if type_idx != 0 { + let bit_depth = if c_idx == 0 { + params.bit_depth_luma + } else { + params.bit_depth_chroma + }; + for i in 0..4 { + out.components[c_idx as usize].offset_abs[i] = + decode_sao_offset_abs(engine, bit_depth)?; + } + if type_idx == 1 { + // Band offset: per-i sign + band position. + for i in 0..4 { + if out.components[c_idx as usize].offset_abs[i] != 0 { + out.components[c_idx as usize].offset_sign[i] = + decode_sao_offset_sign(engine)?; + } + } + out.components[c_idx as usize].band_position = decode_sao_band_position(engine)?; + } else { + // Edge offset: eo_class for cIdx 0 and 1 (cIdx 2 shares + // cIdx 1's eo_class per §7.4.9.3). + if c_idx == 0 || c_idx == 1 { + out.components[c_idx as usize].eo_class = decode_sao_eo_class(engine)?; + } else { + out.components[2].eo_class = out.components[1].eo_class; + } + } + } + } + // §7.4.9.3: SaoTypeIdx[2] / eo_class[2] inherit cIdx 1. + if num_comp == 3 { + out.components[2].sao_type_idx = out.components[1].sao_type_idx; + if out.components[2].sao_type_idx == 2 { + out.components[2].eo_class = out.components[1].eo_class; + } + } + Ok(out) +} + +/// Build the constant (non-geometry) part of a §7.3.8.10 +/// `TransformUnitParams` template from the slice-data params + CU +/// context. The §7.3.8.8 transform-tree walk overwrites the per-node +/// geometry / cbf fields before each leaf. +fn tu_template( + params: &SliceDataParams, + cu_pred_mode: CuPredMode, + cu_transquant_bypass_flag: bool, + part_mode_2nx2n: bool, +) -> TransformUnitParams { + TransformUnitParams { + log2_trafo_size: 0, + trafo_depth: 0, + blk_idx: 0, + cu_pred_mode: to_tu_pred_mode(cu_pred_mode), + chroma_array_type: params.chroma_array_type, + cbf_luma: false, + cbf_cb: false, + cbf_cb_lower: false, + cbf_cr: false, + cbf_cr_lower: false, + intra_pred_mode_y: 0, + intra_pred_mode_c: 0, + intra_chroma_pred_mode: 0, + cu_qp_delta_enabled_flag: params.cu_qp_delta_enabled_flag, + cu_chroma_qp_offset_enabled_flag: params.cu_chroma_qp_offset_enabled_flag, + chroma_qp_offset_list_len_minus1: params.chroma_qp_offset_list_len_minus1, + cu_transquant_bypass_flag, + sign_data_hiding_enabled_flag: params.sign_data_hiding_enabled_flag, + cross_component_prediction_enabled_flag: params.cross_component_prediction_enabled_flag, + residual_adaptive_colour_transform_enabled_flag: params + .residual_adaptive_colour_transform_enabled_flag, + transform_skip_enabled_flag: params.transform_skip_enabled_flag, + log2_max_transform_skip_size: params.log2_max_transform_skip_size, + implicit_rdpcm_enabled_flag: params.implicit_rdpcm_enabled_flag, + explicit_rdpcm_enabled_flag: params.explicit_rdpcm_enabled_flag, + transform_skip_context_enabled_flag: params.transform_skip_context_enabled_flag, + persistent_rice_adaptation_enabled_flag: params.persistent_rice_adaptation_enabled_flag, + cabac_bypass_alignment_enabled_flag: params.cabac_bypass_alignment_enabled_flag, + extended_precision_processing_flag: params.extended_precision_processing_flag, + bit_depth_luma: params.bit_depth_luma as u8, + bit_depth_chroma: params.bit_depth_chroma as u8, + part_mode_2nx2n, + intra_chroma_pred_mode_corners: [0; 4], + } +} + +/// Decode one §7.3.8.6 `prediction_unit( x0, y0, nPbW, nPbH )`. +fn decode_prediction_unit( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + cu_skip_flag: bool, + ct_depth: u32, + n_pb_w: u32, + n_pb_h: u32, +) -> Result { + let mut pu = PredictionUnit { + merge_flag: false, + merge_idx: None, + inter_pred_idc: None, + ref_idx_l0: None, + mvd_l0: None, + mvp_l0_flag: None, + ref_idx_l1: None, + mvd_l1: None, + mvp_l1_flag: None, + }; + + if cu_skip_flag { + if params.max_num_merge_cand > 1 { + pu.merge_idx = Some(decode_merge_idx( + engine, + &mut ctx.merge_idx[0], + params.max_num_merge_cand, + )?); + } else { + pu.merge_idx = Some(0); + } + return Ok(pu); + } + + // MODE_INTER. + pu.merge_flag = decode_merge_flag(engine, &mut ctx.merge_flag[0])? != 0; + if pu.merge_flag { + if params.max_num_merge_cand > 1 { + pu.merge_idx = Some(decode_merge_idx( + engine, + &mut ctx.merge_idx[0], + params.max_num_merge_cand, + )?); + } else { + pu.merge_idx = Some(0); + } + return Ok(pu); + } + + // Non-merge inter. + let pred_idc = if params.slice_type_is_b { + // inter_pred_idc bin 0 ctxInc = (nPbW+nPbH != 12) ? CtDepth : 4; + // bin 1 ctxInc = 4. Bank slot layout: indices 0..=3 are the + // CtDepth-keyed slots, index 4 is the shared bin-1 slot. + let b0_slot = if n_pb_w + n_pb_h != 12 { + ct_depth.min(3) as usize + } else { + 4 + }; + // Borrow two distinct slots from the inter_pred_idc bank. + let idc = decode_inter_pred_idc_banked(engine, ctx, b0_slot, n_pb_w, n_pb_h)?; + pu.inter_pred_idc = Some(idc); + idc + } else { + // P slice: a non-merge inter PB is PRED_L0 (§7.4.9.6) — no + // inter_pred_idc on the wire. + InterPredIdc::PredL0 + }; + + if pred_idc != InterPredIdc::PredL1 { + // L0 path. + if params.num_ref_idx_l0_active_minus1 > 0 { + pu.ref_idx_l0 = Some(decode_ref_idx_l0(engine, ctx, params)?); + } else { + pu.ref_idx_l0 = Some(0); + } + pu.mvd_l0 = Some(decode_mvd_pair_banked(engine, ctx)?); + pu.mvp_l0_flag = Some(decode_mvp_flag(engine, &mut ctx.mvp_flag[0])?); + } + if pred_idc != InterPredIdc::PredL0 { + // L1 path. + if params.num_ref_idx_l1_active_minus1 > 0 { + pu.ref_idx_l1 = Some(decode_ref_idx_l1(engine, ctx, params)?); + } else { + pu.ref_idx_l1 = Some(0); + } + if params.mvd_l1_zero_flag && pred_idc == InterPredIdc::PredBi { + // MvdL1 inferred zero; mvd_coding not read. + pu.mvd_l1 = None; + } else { + pu.mvd_l1 = Some(decode_mvd_pair_banked(engine, ctx)?); + } + pu.mvp_l1_flag = Some(decode_mvp_flag(engine, &mut ctx.mvp_flag[0])?); + } + + Ok(pu) +} + +/// Helper: decode `inter_pred_idc` borrowing two distinct slots from +/// the `inter_pred_idc[5]` bank (bin-0 slot `b0_slot`, bin-1 slot 4). +fn decode_inter_pred_idc_banked( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + b0_slot: usize, + n_pb_w: u32, + n_pb_h: u32, +) -> Result { + // The bank is `[ContextModel; 5]`; bin-0 slot is in 0..=4 and bin-1 + // slot is fixed at 4. When they collide (b0_slot == 4, the + // nPbW+nPbH==12 single-bin case) only bin 0 is read, so bin 1's + // context is never dereferenced — a throwaway copy is harmless. + if b0_slot == 4 { + let mut dummy = ctx.inter_pred_idc[4]; + let r = decode_inter_pred_idc( + engine, + &mut ctx.inter_pred_idc[4], + &mut dummy, + n_pb_w, + n_pb_h, + )?; + return Ok(r); + } + let (head, tail) = ctx.inter_pred_idc.split_at_mut(4); + let b0 = &mut head[b0_slot]; + let b1 = &mut tail[0]; + Ok(decode_inter_pred_idc(engine, b0, b1, n_pb_w, n_pb_h)?) +} + +/// Decode one `mvd_coding( )` invocation (both components in the +/// §7.3.8.9 interleaved bin order), borrowing the two +/// `abs_mvd_greater0_flag` / `abs_mvd_greater1_flag` contexts. +fn decode_mvd_pair_banked( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, +) -> Result<[MvdComponent; 2], ResidualCodingError> { + Ok(decode_mvd_pair( + engine, + &mut ctx.abs_mvd_greater0_flag[0], + &mut ctx.abs_mvd_greater1_flag[0], + )?) +} + +fn decode_ref_idx_l0( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, +) -> Result { + let (c0, c1) = ctx.ref_idx.split_at_mut(1); + Ok(decode_ref_idx( + engine, + &mut c0[0], + &mut c1[0], + params.num_ref_idx_l0_active_minus1, + )?) +} + +fn decode_ref_idx_l1( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, +) -> Result { + let (c0, c1) = ctx.ref_idx.split_at_mut(1); + Ok(decode_ref_idx( + engine, + &mut c0[0], + &mut c1[0], + params.num_ref_idx_l1_active_minus1, + )?) +} + +/// Decode one §7.3.8.5 `coding_unit( x0, y0, log2CbSize )`. +#[allow(clippy::too_many_arguments)] +fn decode_coding_unit( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + state: &mut PictureParseState, + qg: &mut QuantGroupState, + x0: u32, + y0: u32, + log2_cb_size: u32, + ct_depth: u32, +) -> Result { + let n_cb_s = 1u32 << log2_cb_size; + + let cu_transquant_bypass_flag = if params.transquant_bypass_enabled_flag { + decode_cu_transquant_bypass_flag(engine, &mut ctx.cu_transquant_bypass_flag[0])? != 0 + } else { + false + }; + + // cu_skip_flag (P/B only). + let cu_skip_flag = if !params.slice_type_is_i { + let (l_skip, l_avail) = state.neighbour_cu_skip(x0, y0, Neighbour::Left); + let (a_skip, a_avail) = state.neighbour_cu_skip(x0, y0, Neighbour::Above); + let inc = cu_skip_flag_ctx_inc(l_skip, l_avail, a_skip, a_avail) as usize; + decode_cu_skip_flag(engine, &mut ctx.cu_skip_flag[inc])? != 0 + } else { + false + }; + state.record_cu_depth(x0, y0, log2_cb_size, ct_depth as u8, cu_skip_flag as u8); + + let mut cu = CodingUnit { + x0, + y0, + log2_cb_size, + cu_pred_mode: CuPredMode::Intra, + cu_transquant_bypass_flag, + part_mode: PartMode::Part2Nx2N, + pcm_flag: false, + pcm: None, + palette: None, + prediction_units: Vec::new(), + intra_luma: Vec::new(), + intra_chroma_pred_mode: Vec::new(), + rqt_root_cbf: false, + transform_tree: None, + }; + + if cu_skip_flag { + // §7.4.9.5: MODE_SKIP. One prediction_unit covering the CU. + cu.cu_pred_mode = cu_pred_mode_from_skip(params.slice_type_is_i, 1).unwrap(); + state.record_non_intra_cu(x0, y0, n_cb_s, cu.cu_pred_mode); + let pu = decode_prediction_unit(engine, ctx, params, true, ct_depth, n_cb_s, n_cb_s)?; + cu.prediction_units.push(pu); + return Ok(cu); + } + + // pred_mode_flag (P/B), else inferred MODE_INTRA on I slices. + let cu_pred_mode = if params.slice_type_is_i { + CuPredMode::Intra + } else { + let flag = decode_pred_mode_flag(engine, &mut ctx.pred_mode_flag[0])?; + cu_pred_mode_from_flag(flag) + }; + cu.cu_pred_mode = cu_pred_mode; + + // §7.3.8.5: palette_mode_flag, gated on the SCC enable, an intra + // CU and log2CbSize <= MaxTbLog2SizeY; a palette CU replaces the + // whole prediction + transform-coding tail of coding_unit( ). + if params.palette_mode_enabled_flag + && cu_pred_mode == CuPredMode::Intra + && log2_cb_size <= params.max_tb_log2_size_y + // palette_mode_flag: one Table 9-38 context-coded bin. + && engine.decode_decision(&mut ctx.palette_mode_flag[0])? != 0 + { + let pp = crate::palette::PaletteParams { + palette_max_size: params.palette_max_size, + palette_max_predictor_size: params.palette_max_predictor_size, + chroma_array_type: params.chroma_array_type, + bit_depth_luma: params.bit_depth_luma, + bit_depth_chroma: params.bit_depth_chroma, + cu_transquant_bypass_flag: cu.cu_transquant_bypass_flag, + cu_qp_delta_enabled_flag: params.cu_qp_delta_enabled_flag, + cu_chroma_qp_offset_enabled_flag: params.cu_chroma_qp_offset_enabled_flag, + chroma_qp_offset_list_len_minus1: params.chroma_qp_offset_list_len_minus1, + }; + let pal = + crate::palette::decode_palette_coding(engine, ctx, &pp, qg, 1usize << log2_cb_size)?; + // A palette CU carries no IntraPredModeY; record INTRA_DC for + // the §8.4.2 neighbour derivation (the PCM convention — the + // spec never derives a mode for palette blocks). + state.record_pcm_cu(x0, y0, n_cb_s); + cu.palette = Some(Box::new(pal)); + return Ok(cu); + } + + // part_mode: present when MODE_INTER or log2CbSize == MinCbLog2SizeY. + let part_present = + cu_pred_mode != CuPredMode::Intra || log2_cb_size == params.min_cb_log2_size_y; + let part_result: PartModeResult = if part_present { + decode_part_mode_banked(engine, ctx, cu_pred_mode, log2_cb_size, params)? + } else { + crate::binarization::part_mode_inferred() + }; + cu.part_mode = part_result.part_mode; + + if cu_pred_mode == CuPredMode::Intra { + decode_intra_cu( + engine, + ctx, + params, + state, + &mut cu, + x0, + y0, + log2_cb_size, + part_result, + qg, + )?; + } else { + state.record_non_intra_cu(x0, y0, n_cb_s, cu_pred_mode); + decode_inter_cu( + engine, + ctx, + params, + &mut cu, + x0, + y0, + log2_cb_size, + ct_depth, + part_result, + qg, + )?; + } + + Ok(cu) +} + +/// Decode `part_mode` borrowing three distinct slots from the +/// `part_mode[4]` bank. Bin 0 → slot 0, bin 1 → slot 1, bin 2 → slot 2 +/// (`log2CbSize == MinCbLog2SizeY`) or slot 3 (`>`). +fn decode_part_mode_banked( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + cu_pred_mode: CuPredMode, + log2_cb_size: u32, + params: &SliceDataParams, +) -> Result { + let bin2_slot = if log2_cb_size == params.min_cb_log2_size_y { + 2usize + } else { + 3usize + }; + // Borrow slot 0, 1 and bin2_slot (2 or 3) — all distinct. + let (lo, hi) = ctx.part_mode.split_at_mut(2); + let (c0, c1) = lo.split_at_mut(1); + let bin2 = &mut hi[bin2_slot - 2]; + Ok(decode_part_mode( + engine, + &mut c0[0], + &mut c1[0], + bin2, + cu_pred_mode, + log2_cb_size, + params.min_cb_log2_size_y, + params.amp_enabled_flag, + )?) +} + +/// §7.3.8.7 PCM sample payload of one coding unit. Values are stored +/// already scaled to the picture bit depth (§8.4.1 equation 8-12 for +/// luma and its chroma analogue): `pcm_sample << (BitDepth − +/// PcmBitDepth)` — the reconstruction writes them into the picture +/// verbatim. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct PcmSamples { + /// `pcm_sample_luma[i]` in raster order, `nCbS * nCbS` values. + pub luma: Vec, + /// Cb samples in raster order, `(nCbS / SubWidthC) * (nCbS / + /// SubHeightC)` values (empty when `ChromaArrayType == 0`). + pub cb: Vec, + /// Cr samples in raster order (same count as `cb`). + pub cr: Vec, +} + +/// §7.3.8.7 `pcm_sample( x0, y0, log2CbSize )` — the byte-aligned raw +/// sample payload of a `pcm_flag == 1` coding unit, plus the §9.3.1 +/// engine re-initialization that follows it. +fn decode_pcm_sample( + engine: &mut CabacEngine<'_>, + params: &SliceDataParams, + log2_cb_size: u32, +) -> Result { + // §9.3.4.3.5 leaves the raw bit position immediately after the + // pcm_flag terminate bin; the pcm_alignment_zero_bit run pads it + // to the byte boundary. + engine.pcm_align()?; + + let n = 1usize << log2_cb_size; + let shift_y = params + .bit_depth_luma + .saturating_sub(params.pcm_bit_depth_luma) as u16; + let mut luma = Vec::with_capacity(n * n); + for _ in 0..n * n { + let v = engine.read_raw_bits(params.pcm_bit_depth_luma as u8)? as u16; + luma.push(v << shift_y); + } + + let (mut cb, mut cr) = (Vec::new(), Vec::new()); + if params.chroma_array_type != 0 { + let (sub_w, sub_h) = crate::picture::sub_wh_c(params.chroma_array_type); + let count = (n / sub_w) * (n / sub_h); + let shift_c = params + .bit_depth_chroma + .saturating_sub(params.pcm_bit_depth_chroma) as u16; + // §7.4.9.7: the first half of pcm_sample_chroma is Cb, the + // second half Cr, each in raster order. + for plane in [&mut cb, &mut cr] { + plane.reserve(count); + for _ in 0..count { + let v = engine.read_raw_bits(params.pcm_bit_depth_chroma as u8)? as u16; + plane.push(v << shift_c); + } + } + } + + // §9.3.1: the decoding engine is re-initialized (§9.3.2.6) after + // the PCM data; context variables persist. + engine.init_engine()?; + Ok(PcmSamples { luma, cb, cr }) +} + +#[allow(clippy::too_many_arguments)] +fn decode_intra_cu( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + state: &mut PictureParseState, + cu: &mut CodingUnit, + x0: u32, + y0: u32, + log2_cb_size: u32, + part_result: PartModeResult, + qg: &mut QuantGroupState, +) -> Result<(), ResidualCodingError> { + let n_cb_s = 1u32 << log2_cb_size; + + // PCM gate. + let pcm_present = part_result.part_mode == PartMode::Part2Nx2N + && params.pcm_enabled_flag + && log2_cb_size >= params.log2_min_ipcm_cb_size_y + && log2_cb_size <= params.log2_max_ipcm_cb_size_y; + if pcm_present { + cu.pcm_flag = decode_pcm_flag(engine)? != 0; + } + if cu.pcm_flag { + // §7.3.8.7: pcm_alignment_zero_bit run, the raw u(v) sample + // payload, then the §9.3.2.6 engine re-initialization (§9.3.1). + state.record_pcm_cu(x0, y0, n_cb_s); + cu.pcm = Some(decode_pcm_sample(engine, params, log2_cb_size)?); + return Ok(()); + } + + // Luma intra mode signalling group. + let pb_offset = if part_result.part_mode == PartMode::PartNxN { + n_cb_s / 2 + } else { + n_cb_s + }; + let n_pb = (n_cb_s / pb_offset) as usize; // 1 or 2 per axis + let count = n_pb * n_pb; + + let mut prev_flags = Vec::with_capacity(count); + for _ in 0..count { + let f = + decode_prev_intra_luma_pred_flag(engine, &mut ctx.prev_intra_luma_pred_flag[0])? != 0; + prev_flags.push(f); + } + for &f in &prev_flags { + let mut entry = IntraLumaMode { + prev_intra_luma_pred_flag: f, + mpm_idx: None, + rem_intra_luma_pred_mode: None, + }; + if f { + entry.mpm_idx = Some(decode_mpm_idx(engine)?); + } else { + entry.rem_intra_luma_pred_mode = Some(decode_rem_intra_luma_pred_mode(engine)?); + } + cu.intra_luma.push(entry); + } + + // Chroma intra mode. + if params.chroma_array_type == 3 { + for _ in 0..count { + cu.intra_chroma_pred_mode + .push(decode_intra_chroma_pred_mode( + engine, + &mut ctx.intra_chroma_pred_mode[0], + )?); + } + } else if params.chroma_array_type != 0 { + cu.intra_chroma_pred_mode + .push(decode_intra_chroma_pred_mode( + engine, + &mut ctx.intra_chroma_pred_mode[0], + )?); + } + + // §8.4.2 / §8.4.3 — derive the actual `IntraPredModeY` per luma + // prediction block (recording each into the picture-level mode + // field so later blocks' MPM derivation sees it) and the derived + // `IntraPredModeC`: the §7.4.9.11 mode-dependent scan of the + // `residual_coding( )` invocations below reads them. + let pb_offsets: [(u32, u32); 4] = [ + (0, 0), + (pb_offset, 0), + (0, pb_offset), + (pb_offset, pb_offset), + ]; + let mut modes_y = [0u32; 4]; + for (i, luma) in cu.intra_luma.iter().enumerate() { + let (dx, dy) = pb_offsets[i]; + modes_y[i] = + u32::from(state.derive_and_record_luma_mode(x0 + dx, y0 + dy, pb_offset, luma)); + } + for i in cu.intra_luma.len()..4 { + modes_y[i] = modes_y[0]; + } + let mut raw_chroma = [0u8; 4]; + let mut modes_c = [0u32; 4]; + for i in 0..4 { + let raw = if cu.intra_chroma_pred_mode.len() == 4 { + cu.intra_chroma_pred_mode[i] + } else { + cu.intra_chroma_pred_mode.first().copied().unwrap_or(0) + }; + raw_chroma[i] = raw; + // §8.4.3: IntraPredModeC derives from the co-located luma mode — + // per PB for the ChromaArrayType == 3 PART_NxN case, else from + // the CU's first PB. + let luma_for_c = if cu.intra_chroma_pred_mode.len() == 4 { + modes_y[i] + } else { + modes_y[0] + }; + modes_c[i] = u32::from(derive_intra_pred_mode_c( + raw, + luma_for_c as u8, + params.chroma_array_type == 2, + )); + } + + // Intra CUs always enter the transform tree (rqt_root_cbf is not + // coded; cbf_luma presence at the root is unconditional). + let max_trafo_depth = + params.max_transform_hierarchy_depth_intra + part_result.intra_split_flag as u32; + let mut template = tu_template( + params, + CuPredMode::Intra, + cu.cu_transquant_bypass_flag, + part_result.part_mode == PartMode::Part2Nx2N, + ); + template.intra_pred_mode_y = modes_y[0]; + template.intra_pred_mode_c = modes_c[0]; + template.intra_chroma_pred_mode = raw_chroma[0]; + template.intra_chroma_pred_mode_corners = raw_chroma; + let tt_params = TransformTreeParams { + max_tb_log2_size_y: params.max_tb_log2_size_y, + min_tb_log2_size_y: params.min_tb_log2_size_y, + max_trafo_depth, + intra_split_flag: part_result.intra_split_flag, + inter_split_flag: false, + cu_pred_mode: TuCuPredMode::Intra, + chroma_array_type: params.chroma_array_type, + tu_template: template, + cu_x0: x0, + cu_y0: y0, + log2_cb_size, + intra_pred_mode_y_corners: modes_y, + intra_pred_mode_c_corners: modes_c, + }; + let tree = decode_transform_tree( + engine, + ctx, + &tt_params, + qg, + x0, + y0, + x0, + y0, + log2_cb_size, + 0, + 0, + false, + false, + false, + false, + )?; + cu.transform_tree = Some(tree); + Ok(()) +} + +#[allow(clippy::too_many_arguments)] +fn decode_inter_cu( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + cu: &mut CodingUnit, + x0: u32, + y0: u32, + log2_cb_size: u32, + ct_depth: u32, + part_result: PartModeResult, + qg: &mut QuantGroupState, +) -> Result<(), ResidualCodingError> { + let n = 1u32 << log2_cb_size; + let pm = part_result.part_mode; + + // §7.3.8.5: emit the prediction_unit calls per PartMode. + let pu_rects: Vec<(u32, u32, u32, u32)> = match pm { + PartMode::Part2Nx2N => vec![(x0, y0, n, n)], + PartMode::Part2NxN => vec![(x0, y0, n, n / 2), (x0, y0 + n / 2, n, n / 2)], + PartMode::PartNx2N => vec![(x0, y0, n / 2, n), (x0 + n / 2, y0, n / 2, n)], + PartMode::Part2NxnU => vec![(x0, y0, n, n / 4), (x0, y0 + n / 4, n, n * 3 / 4)], + PartMode::Part2NxnD => vec![(x0, y0, n, n * 3 / 4), (x0, y0 + n * 3 / 4, n, n / 4)], + PartMode::PartNLx2N => vec![(x0, y0, n / 4, n), (x0 + n / 4, y0, n * 3 / 4, n)], + PartMode::PartNRx2N => vec![(x0, y0, n * 3 / 4, n), (x0 + n * 3 / 4, y0, n / 4, n)], + PartMode::PartNxN => vec![ + (x0, y0, n / 2, n / 2), + (x0 + n / 2, y0, n / 2, n / 2), + (x0, y0 + n / 2, n / 2, n / 2), + (x0 + n / 2, y0 + n / 2, n / 2, n / 2), + ], + }; + for (px, py, pw, ph) in pu_rects { + let _ = (px, py); + let pu = decode_prediction_unit(engine, ctx, params, false, ct_depth, pw, ph)?; + cu.prediction_units.push(pu); + } + + // rqt_root_cbf: present unless PART_2Nx2N + merge. + let single_merge = pm == PartMode::Part2Nx2N + && cu + .prediction_units + .first() + .map(|p| p.merge_flag) + .unwrap_or(false); + let rqt_root_cbf = if !single_merge { + decode_rqt_root_cbf(engine, &mut ctx.rqt_root_cbf[0])? != 0 + } else { + // §7.4.9.5: not present ⇒ inferred 1. + true + }; + cu.rqt_root_cbf = rqt_root_cbf; + + if rqt_root_cbf { + let inter_split = + params.max_transform_hierarchy_depth_inter == 0 && pm != PartMode::Part2Nx2N; + let max_trafo_depth = params.max_transform_hierarchy_depth_inter; + let tt_params = TransformTreeParams { + max_tb_log2_size_y: params.max_tb_log2_size_y, + min_tb_log2_size_y: params.min_tb_log2_size_y, + max_trafo_depth, + intra_split_flag: false, + inter_split_flag: inter_split, + cu_pred_mode: TuCuPredMode::Inter, + chroma_array_type: params.chroma_array_type, + tu_template: tu_template( + params, + CuPredMode::Inter, + cu.cu_transquant_bypass_flag, + pm == PartMode::Part2Nx2N, + ), + cu_x0: x0, + cu_y0: y0, + log2_cb_size, + // Inter CUs never take the §7.4.9.11 intra-scan branch. + intra_pred_mode_y_corners: [0; 4], + intra_pred_mode_c_corners: [0; 4], + }; + let tree = decode_transform_tree( + engine, + ctx, + &tt_params, + qg, + x0, + y0, + x0, + y0, + log2_cb_size, + 0, + 0, + false, + false, + false, + false, + )?; + cu.transform_tree = Some(tree); + } + Ok(()) +} + +/// Decode one §7.3.8.4 `coding_quadtree( x0, y0, log2CbSize, cqtDepth )`. +#[allow(clippy::too_many_arguments)] +pub fn decode_coding_quadtree( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + state: &mut PictureParseState, + qg: &mut QuantGroupState, + x0: u32, + y0: u32, + log2_cb_size: u32, + cqt_depth: u32, +) -> Result { + let size = 1u32 << log2_cb_size; + let fits_w = x0 + size <= params.pic_width_in_luma_samples; + let fits_h = y0 + size <= params.pic_height_in_luma_samples; + + // split_cu_flag presence gate (§7.3.8.4). + let split_present = fits_w && fits_h && log2_cb_size > params.min_cb_log2_size_y; + let split = if split_present { + let (l_depth, l_avail) = state.neighbour_ct_depth(x0, y0, Neighbour::Left); + let (a_depth, a_avail) = state.neighbour_ct_depth(x0, y0, Neighbour::Above); + let inc = split_cu_flag_ctx_inc(l_depth, l_avail, a_depth, a_avail, cqt_depth) as usize; + decode_split_cu_flag(engine, &mut ctx.split_cu_flag[inc])? != 0 + } else { + // §7.4.9.4 inference: 1 when the block extends past the picture + // boundary OR log2CbSize > MinCbLog2SizeY, else 0. + (!fits_w || !fits_h) || log2_cb_size > params.min_cb_log2_size_y + }; + + // §6.5.1 quantization-group resets at the QG threshold. + if params.cu_qp_delta_enabled_flag && log2_cb_size >= params.log2_min_cu_qp_delta_size { + qg.is_cu_qp_delta_coded = false; + qg.cu_qp_delta_val = 0; + } + if params.cu_chroma_qp_offset_enabled_flag + && log2_cb_size >= params.log2_min_cu_chroma_qp_offset_size + { + qg.is_cu_chroma_qp_offset_coded = false; + } + + if split { + let half = 1u32 << (log2_cb_size - 1); + let x1 = x0 + half; + let y1 = y0 + half; + let child_log2 = log2_cb_size - 1; + let child_depth = cqt_depth + 1; + let mut children = Vec::with_capacity(4); + // First child always present. + children.push(decode_coding_quadtree( + engine, + ctx, + params, + state, + qg, + x0, + y0, + child_log2, + child_depth, + )?); + if x1 < params.pic_width_in_luma_samples { + children.push(decode_coding_quadtree( + engine, + ctx, + params, + state, + qg, + x1, + y0, + child_log2, + child_depth, + )?); + } + if y1 < params.pic_height_in_luma_samples { + children.push(decode_coding_quadtree( + engine, + ctx, + params, + state, + qg, + x0, + y1, + child_log2, + child_depth, + )?); + } + if x1 < params.pic_width_in_luma_samples && y1 < params.pic_height_in_luma_samples { + children.push(decode_coding_quadtree( + engine, + ctx, + params, + state, + qg, + x1, + y1, + child_log2, + child_depth, + )?); + } + Ok(CodingQuadtree::Split(children)) + } else { + let cu = decode_coding_unit( + engine, + ctx, + params, + state, + qg, + x0, + y0, + log2_cb_size, + cqt_depth, + )?; + Ok(CodingQuadtree::Leaf(Box::new(cu))) + } +} + +/// Decode one §7.3.8.2 `coding_tree_unit( )` rooted at CTB top-left +/// `(x_ctb, y_ctb)`. +/// +/// `sao_merge_left_allowed` / `sao_merge_up_allowed` are the §7.3.8.3 +/// merge-flag presence conditions (the slice-segment / tile boundary +/// tests), evaluated by the caller. +#[allow(clippy::too_many_arguments)] +pub fn decode_coding_tree_unit( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + x_ctb: u32, + y_ctb: u32, + sao_merge_left_allowed: bool, + sao_merge_up_allowed: bool, +) -> Result { + // Standalone entry point: a fresh per-picture parse state (no + // cross-CTU intra-mode memory). Multi-CTU pictures must use + // [`decode_coding_tree_unit_in_picture`] with a shared + // [`PictureParseState`] so the §8.4.2 MPM derivation sees the true + // cross-CTU neighbour modes. + let mut state = PictureParseState::new(params); + decode_coding_tree_unit_in_picture( + engine, + ctx, + params, + &mut state, + x_ctb, + y_ctb, + 0, + 0, + sao_merge_left_allowed, + sao_merge_up_allowed, + ) +} + +/// Decode one §7.3.8.2 `coding_tree_unit( )` with the shared per-picture +/// parse state (the §8.4.2 intra-mode neighbour field + the per-CTB +/// slice / tile availability grids). `slice_addr_rs` is the CTB's +/// `SliceAddrRs`; `tile_id` its §6.5.1 `TileId`. +#[allow(clippy::too_many_arguments)] +pub fn decode_coding_tree_unit_in_picture( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &SliceDataParams, + state: &mut PictureParseState, + x_ctb: u32, + y_ctb: u32, + slice_addr_rs: u32, + tile_id: u32, + sao_merge_left_allowed: bool, + sao_merge_up_allowed: bool, +) -> Result { + let mut qg = QuantGroupState::default(); + state.begin_ctu(x_ctb, y_ctb, slice_addr_rs, tile_id); + + let sao = if params.slice_sao_luma_flag || params.slice_sao_chroma_flag { + Some(decode_sao( + engine, + ctx, + params, + sao_merge_left_allowed, + sao_merge_up_allowed, + )?) + } else { + None + }; + + let quadtree = decode_coding_quadtree( + engine, + ctx, + params, + state, + &mut qg, + x_ctb, + y_ctb, + params.ctb_log2_size_y, + 0, + )?; + + Ok(CodingTreeUnit { sao, quadtree }) +} + +/// Decode the §7.3.8.1 `end_of_slice_segment_flag` that follows each +/// CTU. Re-exported here for the slice-data loop convenience; it is the +/// §9.3.4.3.5 terminate path. +pub fn end_of_slice_segment_flag( + engine: &mut CabacEngine<'_>, +) -> Result { + Ok(decode_end_of_slice_segment_flag(engine)? != 0) +} + +#[cfg(test)] +mod tests; diff --git a/vendor/oxideav-h265/src/slice_data/tests.rs b/vendor/oxideav-h265/src/slice_data/tests.rs new file mode 100644 index 0000000..b6efed6 --- /dev/null +++ b/vendor/oxideav-h265/src/slice_data/tests.rs @@ -0,0 +1,165 @@ +//! §7.3.8.1 .. §7.3.8.6 slice-data walk tests. + +use super::*; +use crate::bitreader::BitReader; +use crate::cabac::CabacEngine; + +/// A minimal Main-profile (4:2:0, 8-bit) I-slice params block, used by +/// the structural decode tests. +fn i_slice_params(ctb_log2: u32, min_cb_log2: u32) -> SliceDataParams { + SliceDataParams { + ctb_log2_size_y: ctb_log2, + min_cb_log2_size_y: min_cb_log2, + max_tb_log2_size_y: 5, + min_tb_log2_size_y: 2, + pic_width_in_luma_samples: 1 << ctb_log2, + pic_height_in_luma_samples: 1 << ctb_log2, + chroma_array_type: 1, + bit_depth_luma: 8, + bit_depth_chroma: 8, + slice_type_is_i: true, + slice_type_is_b: false, + slice_sao_luma_flag: false, + slice_sao_chroma_flag: false, + transquant_bypass_enabled_flag: false, + cu_qp_delta_enabled_flag: false, + log2_min_cu_qp_delta_size: ctb_log2, + cu_chroma_qp_offset_enabled_flag: false, + log2_min_cu_chroma_qp_offset_size: ctb_log2, + chroma_qp_offset_list_len_minus1: 0, + amp_enabled_flag: false, + pcm_enabled_flag: false, + log2_min_ipcm_cb_size_y: 3, + log2_max_ipcm_cb_size_y: 5, + pcm_bit_depth_luma: 8, + pcm_bit_depth_chroma: 8, + max_transform_hierarchy_depth_intra: 0, + max_transform_hierarchy_depth_inter: 0, + max_num_merge_cand: 5, + num_ref_idx_l0_active_minus1: 0, + num_ref_idx_l1_active_minus1: 0, + mvd_l1_zero_flag: false, + sign_data_hiding_enabled_flag: false, + cross_component_prediction_enabled_flag: false, + residual_adaptive_colour_transform_enabled_flag: false, + transform_skip_enabled_flag: false, + log2_max_transform_skip_size: 2, + implicit_rdpcm_enabled_flag: false, + explicit_rdpcm_enabled_flag: false, + transform_skip_context_enabled_flag: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + palette_mode_enabled_flag: false, + palette_max_size: 0, + palette_max_predictor_size: 0, + } +} + +fn fresh_contexts() -> SliceContexts { + // Init every bank at slice_qp_y = 26 with init_type 0 (I slice). + SliceContexts::init(0, 26) +} + +#[test] +fn parse_state_left_above_unavailable_at_origin() { + let params = i_slice_params(4, 3); + let mut state = PictureParseState::new(¶ms); + state.begin_ctu(0, 0, 0, 0); + assert_eq!(state.neighbour_ct_depth(0, 0, Neighbour::Left), (0, false)); + assert_eq!(state.neighbour_ct_depth(0, 0, Neighbour::Above), (0, false)); + assert_eq!(state.neighbour_cu_skip(0, 0, Neighbour::Left), (0, false)); + assert_eq!(state.neighbour_cu_skip(0, 0, Neighbour::Above), (0, false)); +} + +#[test] +fn parse_state_records_and_reads_back_neighbours() { + let params = i_slice_params(5, 3); // 32x32 CTB, 8x8 min CB + let mut state = PictureParseState::new(¶ms); + state.begin_ctu(0, 0, 0, 0); + // Record an 8x8 block at (0,0) with CtDepth 2. + state.record_cu_depth(0, 0, 3, 2, 0); + // The block to the right at (8,0) sees (0,0) as its left neighbour. + assert_eq!(state.neighbour_ct_depth(8, 0, Neighbour::Left), (2, true)); + // The block below at (0,8) sees (0,0) as its above neighbour. + assert_eq!(state.neighbour_ct_depth(0, 8, Neighbour::Above), (2, true)); + // A not-yet-decoded neighbour is unavailable. + assert_eq!(state.neighbour_ct_depth(16, 8, Neighbour::Left), (0, false)); +} + +#[test] +fn sao_disabled_yields_no_sao() { + // slice_sao_*_flag both false → coding_tree_unit has sao == None. + // An all-zero stream still drives a full intra-CU CABAC walk, so the + // buffer must be large enough to back every decoded bin. + let params = i_slice_params(4, 3); + let buf = [0u8; 4096]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_contexts(); + let ctu = decode_coding_tree_unit(&mut eng, &mut ctx, ¶ms, 0, 0, false, false).unwrap(); + assert!(ctu.sao.is_none()); +} + +#[test] +fn sao_band_offset_default_is_zero_type() { + // sao_merge not allowed, both components read; an all-zero CABAC + // stream drives sao_type_idx bin 0 (MPS-from-init) — the decode + // simply must not error and must produce a structurally valid + // SaoCtbParams. + let mut params = i_slice_params(4, 3); + params.slice_sao_luma_flag = true; + params.slice_sao_chroma_flag = true; + let buf = [0u8; 32]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_contexts(); + let sao = decode_sao(&mut eng, &mut ctx, ¶ms, false, false).unwrap(); + assert!(!sao.merge_left); + assert!(!sao.merge_up); + // SaoTypeIdx values are in 0..=2. + for c in sao.components.iter() { + assert!(c.sao_type_idx <= 2); + } +} + +#[test] +fn coding_quadtree_at_min_cb_is_a_leaf() { + // A 16x16 CTB with MinCbLog2SizeY = 4 cannot split (split_cu_flag + // gate requires log2CbSize > MinCbLog2SizeY) → one coding unit. + let params = i_slice_params(4, 4); + let buf = [0u8; 4096]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_contexts(); + let mut state = PictureParseState::new(¶ms); + state.begin_ctu(0, 0, 0, 0); + let mut qg = QuantGroupState::default(); + let qt = decode_coding_quadtree(&mut eng, &mut ctx, ¶ms, &mut state, &mut qg, 0, 0, 4, 0) + .unwrap(); + match qt { + CodingQuadtree::Leaf(cu) => { + assert_eq!(cu.cu_pred_mode, CuPredMode::Intra); + assert_eq!(cu.x0, 0); + assert_eq!(cu.y0, 0); + assert_eq!(cu.log2_cb_size, 4); + // An intra CU always carries a transform tree. + assert!(cu.transform_tree.is_some()); + } + CodingQuadtree::Split(_) => panic!("min-CB node must be a leaf"), + } +} + +#[test] +fn coding_tree_unit_i_slice_decodes_structurally() { + // Full CTU walk on an I slice: sao disabled, a 16x16 CTB at + // MinCbLog2SizeY = 3 may split. The decode must complete without + // error and produce a quadtree rooted at the CTB. + let params = i_slice_params(4, 3); + let buf = [0u8; 4096]; + let mut eng = CabacEngine::new(BitReader::new(&buf)).unwrap(); + let mut ctx = fresh_contexts(); + let ctu = decode_coding_tree_unit(&mut eng, &mut ctx, ¶ms, 0, 0, false, false).unwrap(); + assert!(ctu.sao.is_none()); + // The quadtree is either a leaf or a split; either is valid. + match ctu.quadtree { + CodingQuadtree::Leaf(_) | CodingQuadtree::Split(_) => {} + } +} diff --git a/vendor/oxideav-h265/src/sps.rs b/vendor/oxideav-h265/src/sps.rs new file mode 100644 index 0000000..d2d12d0 --- /dev/null +++ b/vendor/oxideav-h265/src/sps.rs @@ -0,0 +1,3501 @@ +//! Sequence Parameter Set (SPS) parser per ITU-T Rec. H.265 §7.3.2.2. +//! +//! Scope: parse the full SPS RBSP body through the +//! `strong_intra_smoothing_enabled_flag` field, the +//! `vui_parameters_present_flag` gate (whose §E.2.1 +//! `vui_parameters()` body is decoded into [`crate::vui::VuiParameters`]), +//! and the `sps_extension_present_flag` gate. When the extension gate +//! is set, the trailing bytes (extension payload + RBSP trailing +//! bits) are surfaced as an **opaque tail**: a copy of the +//! still-unparsed RBSP bytes plus the bit offset within the first +//! byte at which the opaque tail begins. The per-extension +//! `sps_*_extension( )` syntax structures are not materialised yet. +//! +//! When `scaling_list_enabled_flag == 1` and +//! `sps_scaling_list_data_present_flag == 1`, the §7.3.4 +//! `scaling_list_data()` block is parsed via the shared +//! [`crate::scaling_list`] module; otherwise the §7.4.5 default lists +//! apply. +//! +//! ## Layout summary +//! +//! ```text +//! sps_video_parameter_set_id u(4) +//! sps_max_sub_layers_minus1 u(3) +//! sps_temporal_id_nesting_flag u(1) +//! profile_tier_level( 1, sps_max_sub_layers_minus1 ) +//! sps_seq_parameter_set_id ue(v) +//! chroma_format_idc ue(v) +//! if( chroma_format_idc == 3 ) +//! separate_colour_plane_flag u(1) +//! pic_width_in_luma_samples ue(v) +//! pic_height_in_luma_samples ue(v) +//! conformance_window_flag u(1) +//! if( conformance_window_flag ) { +//! conf_win_left_offset ue(v) +//! conf_win_right_offset ue(v) +//! conf_win_top_offset ue(v) +//! conf_win_bottom_offset ue(v) +//! } +//! bit_depth_luma_minus8 ue(v) +//! bit_depth_chroma_minus8 ue(v) +//! log2_max_pic_order_cnt_lsb_minus4 ue(v) +//! sps_sub_layer_ordering_info_present_flag u(1) +//! for( i = (...) ; i <= sps_max_sub_layers_minus1; i++ ) { +//! sps_max_dec_pic_buffering_minus1[i] ue(v) +//! sps_max_num_reorder_pics[i] ue(v) +//! sps_max_latency_increase_plus1[i] ue(v) +//! } +//! log2_min_luma_coding_block_size_minus3 ue(v) +//! log2_diff_max_min_luma_coding_block_size ue(v) +//! log2_min_luma_transform_block_size_minus2 ue(v) +//! log2_diff_max_min_luma_transform_block_size ue(v) +//! max_transform_hierarchy_depth_inter ue(v) +//! max_transform_hierarchy_depth_intra ue(v) +//! scaling_list_enabled_flag u(1) +//! if( scaling_list_enabled_flag ) { +//! sps_scaling_list_data_present_flag u(1) +//! if( sps_scaling_list_data_present_flag ) +//! scaling_list_data( ) /* §7.3.4 */ +//! } +//! amp_enabled_flag u(1) +//! sample_adaptive_offset_enabled_flag u(1) +//! pcm_enabled_flag u(1) +//! if( pcm_enabled_flag ) { +//! pcm_sample_bit_depth_luma_minus1 u(4) +//! pcm_sample_bit_depth_chroma_minus1 u(4) +//! log2_min_pcm_luma_coding_block_size_minus3 ue(v) +//! log2_diff_max_min_pcm_luma_coding_block_size ue(v) +//! pcm_loop_filter_disabled_flag u(1) +//! } +//! num_short_term_ref_pic_sets ue(v) +//! for( i = 0; i < num_short_term_ref_pic_sets; i++ ) +//! st_ref_pic_set( i ) +//! long_term_ref_pics_present_flag u(1) +//! if( long_term_ref_pics_present_flag ) { +//! num_long_term_ref_pics_sps ue(v) +//! for( i = 0; i < num_long_term_ref_pics_sps; i++ ) { +//! lt_ref_pic_poc_lsb_sps[i] u(v) /* log2_max_poc_lsb+4 */ +//! used_by_curr_pic_lt_sps_flag[i] u(1) +//! } +//! } +//! sps_temporal_mvp_enabled_flag u(1) +//! strong_intra_smoothing_enabled_flag u(1) +//! vui_parameters_present_flag u(1) +//! if( vui_parameters_present_flag ) +//! vui_parameters( ) /* §E.2.1 */ +//! sps_extension_present_flag u(1) +//! if( sps_extension_present_flag ) { +//! sps_range_extension_flag u(1) +//! sps_multilayer_extension_flag u(1) +//! sps_3d_extension_flag u(1) +//! sps_scc_extension_flag u(1) +//! sps_extension_4bits u(4) +//! /* opaque tail begins at the first set body, or stays +//! empty when every flag is 0 */ +//! } +//! ``` +//! +//! When `sps_extension_present_flag == 1` the eight bits of typed +//! extension flags (`sps_range_extension_flag`, +//! `sps_multilayer_extension_flag`, `sps_3d_extension_flag`, +//! `sps_scc_extension_flag`, `sps_extension_4bits`) are decoded into +//! [`SpsExtensionFlags`]. When all five sub-fields are zero only the +//! RBSP trailing byte remains and no opaque tail is captured; otherwise +//! the extension bodies (`sps_range_extension()`, +//! `sps_multilayer_extension()`, `sps_3d_extension()`, +//! `sps_scc_extension()`, and the `sps_extension_data_flag` while-loop +//! gated by `sps_extension_4bits`) are surfaced as a single +//! [`OpaqueTail`] starting at the first body's bit position. +//! +//! Validity checks performed here, sourced from §7.4.3.2: +//! +//! * `sps_max_sub_layers_minus1` range 0..=6. +//! * `sps_video_parameter_set_id` and `sps_seq_parameter_set_id` +//! range 0..=15. +//! * `chroma_format_idc` range 0..=3. +//! * `pic_width_in_luma_samples` and `pic_height_in_luma_samples` not +//! equal to zero (the modulo-`MinCbSizeY` check is deferred — it +//! depends on the not-yet-validated `log2_min_cb_size`). +//! * `bit_depth_luma_minus8` and `bit_depth_chroma_minus8` range +//! 0..=8 (§7.4.3.2 caps the encoded bit depth at 16). +//! * `log2_max_pic_order_cnt_lsb_minus4` range 0..=12. +//! * `pcm_sample_bit_depth_luma_minus1` / `pcm_sample_bit_depth_chroma_minus1` +//! must satisfy `PcmBitDepthY <= BitDepthY` / +//! `PcmBitDepthC <= BitDepthC` per §7.4.3.2 / equation (7-25 / 7-26). +//! * `num_short_term_ref_pic_sets` range 0..=64. +//! * `num_long_term_ref_pics_sps` range 0..=32. +//! * `num_negative_pics` / `num_positive_pics` capped at 16 (the +//! §7.4.8 bound is +//! `sps_max_dec_pic_buffering_minus1[sps_max_sub_layers_minus1]`, +//! itself bounded at 16 because `MaxDpbSize` per §A.4.2 is 16). +//! * `delta_poc_s0_minus1` / `delta_poc_s1_minus1` / +//! `abs_delta_rps_minus1` range 0..=2^15-1. +//! * `sps_scaling_list_data_present_flag == 1` triggers a §7.3.4 +//! `scaling_list_data()` parse into [`ScalingListData`] via the +//! shared [`crate::scaling_list`] module. + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::scaling_list::{ScalingListData, ScalingListError}; +use crate::vps::{ProfileTierLevel, SubLayerOrderingInfo, VpsError, HEVC_MAX_SUB_LAYERS}; +use crate::vui::{VuiError, VuiParameters}; + +/// Maximum number of short-term reference picture sets an SPS may +/// carry. Per §7.4.3.2 the field is bounded at 64 inclusive. +pub const HEVC_MAX_NUM_SHORT_TERM_RPS: usize = 64; + +/// Maximum number of long-term reference pictures an SPS may carry. +/// Per §7.4.3.2 the field is bounded at 32 inclusive. +pub const HEVC_MAX_NUM_LONG_TERM_RPS: usize = 32; + +/// Maximum number of negative / positive entries permitted in one +/// short-term RPS. Per §7.4.8 the bound is +/// `sps_max_dec_pic_buffering_minus1[sps_max_sub_layers_minus1]` +/// which §A.4.2 caps at `MaxDpbSize - 1 = 15` (for typical levels); +/// 16 is a defensive upper bound for the parser. +pub const HEVC_MAX_RPS_PICS: usize = 16; + +/// Errors that can arise while parsing an SPS RBSP. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum SpsError { + /// The RBSP ran out of bits before the SPS was fully parsed. + Truncated, + /// A syntax element's parsed value was outside the legal range + /// specified for it in §7.4.3.2. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value as a `u32` (signed elements are + /// re-cast at the call site). + got: u32, + }, + /// A `scaling_list_data()` parse (§7.3.4) from the SPS failed. + ScalingList(ScalingListError), + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), + /// A `profile_tier_level()` parse from the §7.3.3 walk failed. + Ptl(VpsError), + /// A `vui_parameters()` parse (§E.2.1) from the SPS failed. + Vui(VuiError), +} + +impl core::fmt::Display for SpsError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("SPS RBSP truncated"), + Self::ValueOutOfRange { field, got } => { + write!(f, "SPS syntax element {field} out of range: {got}") + } + Self::ScalingList(e) => write!(f, "scaling-list error during SPS parse: {e}"), + Self::Bitstream(e) => write!(f, "bitstream error during SPS parse: {e}"), + Self::Ptl(e) => write!(f, "profile_tier_level error during SPS parse: {e}"), + Self::Vui(e) => write!(f, "vui_parameters error during SPS parse: {e}"), + } + } +} + +impl std::error::Error for SpsError {} + +impl From for SpsError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +impl From for SpsError { + fn from(e: VpsError) -> Self { + // Surface the inner reader-truncation directly so callers can + // distinguish "ran off the end mid-PTL" from other PTL faults. + if matches!(e, VpsError::Truncated) { + Self::Truncated + } else { + Self::Ptl(e) + } + } +} + +impl From for SpsError { + fn from(e: ScalingListError) -> Self { + // Flatten truncation / raw-reader faults to the SPS-level + // equivalents so the public surface stays predictable; carry + // the structured scaling-list faults through as-is. + match e { + ScalingListError::Truncated => Self::Truncated, + ScalingListError::Bitstream(b) => Self::Bitstream(b), + other => Self::ScalingList(other), + } + } +} + +impl From for SpsError { + fn from(e: VuiError) -> Self { + // Flatten truncation / raw-reader faults to the SPS-level + // equivalents so the public surface stays predictable; carry + // the structured VUI faults through as-is. + match e { + VuiError::Truncated => Self::Truncated, + VuiError::Bitstream(b) => Self::Bitstream(b), + other => Self::Vui(other), + } + } +} + +/// Conformance-window offsets, in §6.5.5 SubWidthC/SubHeightC units +/// (not pixel units — the multiplier depends on +/// [`SeqParameterSet::chroma_format_idc`]). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct ConformanceWindow { + /// `conf_win_left_offset` (`ue(v)`). + pub left_offset: u32, + /// `conf_win_right_offset` (`ue(v)`). + pub right_offset: u32, + /// `conf_win_top_offset` (`ue(v)`). + pub top_offset: u32, + /// `conf_win_bottom_offset` (`ue(v)`). + pub bottom_offset: u32, +} + +/// PCM-related SPS block per §7.3.2.2 (`pcm_enabled_flag == 1` only). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct PcmInfo { + /// `pcm_sample_bit_depth_luma_minus1` (`u(4)`). The §7.4.3.2 + /// `PcmBitDepthY` derivation is `value + 1`. + pub bit_depth_luma_minus1: u8, + /// `pcm_sample_bit_depth_chroma_minus1` (`u(4)`). `PcmBitDepthC = value + 1`. + pub bit_depth_chroma_minus1: u8, + /// `log2_min_pcm_luma_coding_block_size_minus3` (`ue(v)`). + /// `Log2MinIpcmCbSizeY = value + 3`. + pub log2_min_pcm_luma_coding_block_size_minus3: u8, + /// `log2_diff_max_min_pcm_luma_coding_block_size` (`ue(v)`). + /// `Log2MaxIpcmCbSizeY = Log2MinIpcmCbSizeY + value`. + pub log2_diff_max_min_pcm_luma_coding_block_size: u8, + /// `pcm_loop_filter_disabled_flag` (`u(1)`). + pub loop_filter_disabled_flag: bool, +} + +/// Short-term reference picture set per §7.3.7. Only the explicit +/// (non-inter-predicted) form materialises the per-entry POC and +/// `used_by_curr_pic` arrays; the inter-RPS-prediction form materialises +/// only the inputs to the §7.4.8 derivation (`delta_idx_minus1`, +/// `delta_rps_sign`, `abs_delta_rps_minus1`, and the +/// `used_by_curr_pic_flag` / `use_delta_flag` arrays of length +/// `NumDeltaPocs[RefRpsIdx] + 1`). +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct ShortTermRefPicSet { + /// `inter_ref_pic_set_prediction_flag` — inferred to 0 when not + /// signalled (i.e. always 0 for `stRpsIdx == 0`). + pub inter_ref_pic_set_prediction_flag: bool, + /// `delta_idx_minus1` (only meaningful when + /// `inter_ref_pic_set_prediction_flag == 1` and the index this RPS + /// is being constructed at equals `num_short_term_ref_pic_sets`; + /// otherwise inferred to 0). The §7.4.8 derivation is + /// `RefRpsIdx = stRpsIdx - (delta_idx_minus1 + 1)`. + pub delta_idx_minus1: u32, + /// `delta_rps_sign` (1-bit). + pub delta_rps_sign: bool, + /// `abs_delta_rps_minus1` (`ue(v)`, range 0..=2^15-1). + pub abs_delta_rps_minus1: u32, + /// Per-entry `used_by_curr_pic_flag[j]` for the inter-RPS-prediction + /// case. Length is `NumDeltaPocs[RefRpsIdx] + 1` when the form + /// applies, zero otherwise. + pub used_by_curr_pic_flag: Vec, + /// Per-entry `use_delta_flag[j]` for the inter-RPS-prediction case. + /// Same length / population rule as + /// [`used_by_curr_pic_flag`](Self::used_by_curr_pic_flag); per + /// §7.4.8 the value is inferred to 1 when the + /// `used_by_curr_pic_flag[j]` was 1. + pub use_delta_flag: Vec, + /// `num_negative_pics` (`ue(v)`), only meaningful in the explicit + /// form. + pub num_negative_pics: u32, + /// `num_positive_pics` (`ue(v)`), only meaningful in the explicit + /// form. + pub num_positive_pics: u32, + /// `delta_poc_s0_minus1[i]` (`ue(v)`), explicit form. Length + /// `num_negative_pics`. + pub delta_poc_s0_minus1: Vec, + /// `used_by_curr_pic_s0_flag[i]` (`u(1)`), explicit form. Length + /// `num_negative_pics`. + pub used_by_curr_pic_s0_flag: Vec, + /// `delta_poc_s1_minus1[i]` (`ue(v)`), explicit form. Length + /// `num_positive_pics`. + pub delta_poc_s1_minus1: Vec, + /// `used_by_curr_pic_s1_flag[i]` (`u(1)`), explicit form. Length + /// `num_positive_pics`. + pub used_by_curr_pic_s1_flag: Vec, +} + +impl ShortTermRefPicSet { + /// `NumDeltaPocs[stRpsIdx]` per §7.4.8: in the explicit form this + /// is `num_negative_pics + num_positive_pics`; in the inter-RPS + /// form the exact count requires the §7.4.8 derivation + /// (equations 7-61 / 7-62 / 7-71) against a materialised source + /// RPS. See [`Self::materialize`] / [`MaterializedShortTermRefPicSet`] + /// for the full derivation. + /// + /// For the inter-RPS form this helper returns the count of + /// `use_delta_flag[j] == 1` entries, which is an upper bound that + /// happens to be exact when none of the source POCs flip sign + /// across `deltaRps`. Callers that need the exact wire-conformant + /// count must materialise the RPS chain. + pub fn num_delta_pocs(&self) -> u32 { + if self.inter_ref_pic_set_prediction_flag { + self.use_delta_flag.iter().filter(|&&v| v).count() as u32 + } else { + self.num_negative_pics + self.num_positive_pics + } + } + + /// Materialise this `st_ref_pic_set(stRpsIdx)` into the post-§7.4.8 + /// per-position arrays `(NumNegativePics, DeltaPocS0[], + /// UsedByCurrPicS0[], NumPositivePics, DeltaPocS1[], + /// UsedByCurrPicS1[])` consumed by §7.4.7.2 and downstream paths. + /// + /// * For the explicit form (`inter_ref_pic_set_prediction_flag == + /// 0`) this is equations 7-63..7-70: `NumNegativePics = + /// num_negative_pics`, `NumPositivePics = num_positive_pics`, + /// `UsedByCurrPicSk[i] = used_by_curr_pic_sk_flag[i]`, and the + /// cumulative `DeltaPocS0[i] = DeltaPocS0[i-1] - + /// (delta_poc_s0_minus1[i] + 1)` recurrence with the + /// first-element seeds (`DeltaPocS0` at i=0 is + /// `-(delta_poc_s0_minus1 at 0 + 1)` and `DeltaPocS1` at i=0 is + /// `delta_poc_s1_minus1 at 0 + 1`). `source` is ignored in this + /// branch. + /// * For the inter-RPS-prediction form + /// (`inter_ref_pic_set_prediction_flag == 1`) this runs + /// equations 7-61 (negative side, source-S1-reverse + + /// `deltaRps`-self + source-S0-forward) and 7-62 (positive side, + /// source-S0-reverse + `deltaRps`-self + source-S1-forward) over + /// the already-materialised source RPS supplied via `source`, + /// with `deltaRps = (1 - 2*delta_rps_sign) * + /// (abs_delta_rps_minus1 + 1)`. The output's + /// `NumNegativePics` / `NumPositivePics` reflect the surviving + /// `dPoc < 0` / `dPoc > 0` entries with their `use_delta_flag[j] + /// == 1` gates, per equation 7-71's `NumDeltaPocs` + /// summation. The `source` argument must be `Some(_)` for the + /// inter form; the function returns + /// [`ShortTermRefPicSetMaterializeError::MissingSource`] if + /// absent. Bounds on `used_by_curr_pic_flag` / + /// `use_delta_flag` length are checked against the source's + /// `NumDeltaPocs + 1`; a mismatch returns + /// [`ShortTermRefPicSetMaterializeError::SourceLengthMismatch`]. + pub fn materialize( + &self, + source: Option<&MaterializedShortTermRefPicSet>, + ) -> Result { + if self.inter_ref_pic_set_prediction_flag { + let source = source.ok_or(ShortTermRefPicSetMaterializeError::MissingSource)?; + // `deltaRps` per equation 7-60. The bit-width of + // `abs_delta_rps_minus1` is bounded by `ue(v)` plus the + // §7.4.8 range check (<= 2^15-1 -> deltaRps fits in i32). + let abs = self.abs_delta_rps_minus1 as i64 + 1; + let delta_rps = if self.delta_rps_sign { -abs } else { abs } as i32; + let num_neg_src = source.num_negative_pics(); + let num_pos_src = source.num_positive_pics(); + let num_delta_src = source.num_delta_pocs(); // == num_neg_src + num_pos_src + // Per §7.4.8 the `used_by_curr_pic_flag` / `use_delta_flag` + // arrays have length `NumDeltaPocs[RefRpsIdx] + 1`. + let expected = (num_delta_src + 1) as usize; + if self.used_by_curr_pic_flag.len() != expected || self.use_delta_flag.len() != expected + { + return Err(ShortTermRefPicSetMaterializeError::SourceLengthMismatch { + expected: expected as u32, + got_used: self.used_by_curr_pic_flag.len(), + got_delta: self.use_delta_flag.len(), + }); + } + // Negative side (equation 7-61): walk source's positive + // POCs in reverse (their `dPoc = DeltaPocS1[RefRpsIdx][j] + // + deltaRps` may have crossed zero), then optionally + // `deltaRps` itself (only if negative), then source's + // negative POCs in forward order. + let mut delta_poc_s0 = Vec::new(); + let mut used_by_curr_pic_s0 = Vec::new(); + for j in (0..num_pos_src).rev() { + let d_poc = source.delta_poc_s1[j as usize] + delta_rps; + if d_poc < 0 && self.use_delta_flag[(num_neg_src + j) as usize] { + delta_poc_s0.push(d_poc); + used_by_curr_pic_s0 + .push(self.used_by_curr_pic_flag[(num_neg_src + j) as usize]); + } + } + if delta_rps < 0 && self.use_delta_flag[num_delta_src as usize] { + delta_poc_s0.push(delta_rps); + used_by_curr_pic_s0.push(self.used_by_curr_pic_flag[num_delta_src as usize]); + } + for j in 0..num_neg_src { + let d_poc = source.delta_poc_s0[j as usize] + delta_rps; + if d_poc < 0 && self.use_delta_flag[j as usize] { + delta_poc_s0.push(d_poc); + used_by_curr_pic_s0.push(self.used_by_curr_pic_flag[j as usize]); + } + } + // Positive side (equation 7-62): walk source's negative + // POCs in reverse (their `dPoc = DeltaPocS0[RefRpsIdx][j] + // + deltaRps` may have crossed zero), then optionally + // `deltaRps` itself (only if positive), then source's + // positive POCs in forward order. + let mut delta_poc_s1 = Vec::new(); + let mut used_by_curr_pic_s1 = Vec::new(); + for j in (0..num_neg_src).rev() { + let d_poc = source.delta_poc_s0[j as usize] + delta_rps; + if d_poc > 0 && self.use_delta_flag[j as usize] { + delta_poc_s1.push(d_poc); + used_by_curr_pic_s1.push(self.used_by_curr_pic_flag[j as usize]); + } + } + if delta_rps > 0 && self.use_delta_flag[num_delta_src as usize] { + delta_poc_s1.push(delta_rps); + used_by_curr_pic_s1.push(self.used_by_curr_pic_flag[num_delta_src as usize]); + } + for j in 0..num_pos_src { + let d_poc = source.delta_poc_s1[j as usize] + delta_rps; + if d_poc > 0 && self.use_delta_flag[(num_neg_src + j) as usize] { + delta_poc_s1.push(d_poc); + used_by_curr_pic_s1 + .push(self.used_by_curr_pic_flag[(num_neg_src + j) as usize]); + } + } + Ok(MaterializedShortTermRefPicSet { + delta_poc_s0, + used_by_curr_pic_s0, + delta_poc_s1, + used_by_curr_pic_s1, + }) + } else { + // Explicit form, equations 7-63..7-70. + let mut delta_poc_s0 = Vec::with_capacity(self.num_negative_pics as usize); + let mut prev: i32 = 0; + for (i, &delta_minus1) in self.delta_poc_s0_minus1.iter().enumerate() { + // delta_minus1 has been range-checked to 0..=2^15-1 on + // parse; the cumulative sum cannot exceed i32 capacity + // given num_negative_pics <= 16. + let step = delta_minus1 as i32 + 1; + let d = if i == 0 { -step } else { prev - step }; + delta_poc_s0.push(d); + prev = d; + } + let mut delta_poc_s1 = Vec::with_capacity(self.num_positive_pics as usize); + let mut prev: i32 = 0; + for (i, &delta_minus1) in self.delta_poc_s1_minus1.iter().enumerate() { + let step = delta_minus1 as i32 + 1; + let d = if i == 0 { step } else { prev + step }; + delta_poc_s1.push(d); + prev = d; + } + Ok(MaterializedShortTermRefPicSet { + delta_poc_s0, + used_by_curr_pic_s0: self.used_by_curr_pic_s0_flag.clone(), + delta_poc_s1, + used_by_curr_pic_s1: self.used_by_curr_pic_s1_flag.clone(), + }) + } + } +} + +/// Errors that can arise while running the §7.4.8 inter-RPS-prediction +/// derivation via [`ShortTermRefPicSet::materialize`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ShortTermRefPicSetMaterializeError { + /// The RPS uses inter-RPS prediction + /// (`inter_ref_pic_set_prediction_flag == 1`) but the caller did + /// not supply a materialised source RPS. + MissingSource, + /// The on-wire `used_by_curr_pic_flag` / `use_delta_flag` arrays + /// did not match the source RPS's `NumDeltaPocs[RefRpsIdx] + 1` + /// length. This indicates the parser and the materialiser saw + /// different source RPSes (most likely a `RefRpsIdx` mismatch). + SourceLengthMismatch { + /// Expected length: `NumDeltaPocs[RefRpsIdx] + 1`. + expected: u32, + /// Actual length of `used_by_curr_pic_flag`. + got_used: usize, + /// Actual length of `use_delta_flag`. + got_delta: usize, + }, +} + +impl core::fmt::Display for ShortTermRefPicSetMaterializeError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::MissingSource => f.write_str( + "short-term RPS materialise: inter_ref_pic_set_prediction_flag is set but no source RPS supplied", + ), + Self::SourceLengthMismatch { + expected, + got_used, + got_delta, + } => write!( + f, + "short-term RPS materialise: per-position array length mismatch: expected {expected}, got used={got_used} delta={got_delta}" + ), + } + } +} + +impl std::error::Error for ShortTermRefPicSetMaterializeError {} + +/// Materialised short-term reference-picture-set per §7.4.8 — the +/// post-derivation form that exposes the per-position `DeltaPocS0[]`, +/// `UsedByCurrPicS0[]`, `DeltaPocS1[]`, `UsedByCurrPicS1[]` arrays as +/// signed POC deltas. `NumNegativePics[stRpsIdx]` and +/// `NumPositivePics[stRpsIdx]` are exposed as the array lengths. +/// +/// The DeltaPocS0 array is in source order — i.e. the negative POCs +/// in the order §7.4.8 produces them — which for the explicit form +/// (equations 7-67 / 7-69) is descending (each element is the next +/// further-in-the-past POC) and for the inter-RPS-prediction form +/// (equation 7-61) walks source positives in reverse, then optionally +/// `deltaRps`, then source negatives in forward order. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct MaterializedShortTermRefPicSet { + /// `DeltaPocS0[stRpsIdx][i]` for `i` in + /// `0..NumNegativePics[stRpsIdx]`. All entries are strictly + /// negative. + pub delta_poc_s0: Vec, + /// `UsedByCurrPicS0[stRpsIdx][i]` for `i` in + /// `0..NumNegativePics[stRpsIdx]`. + pub used_by_curr_pic_s0: Vec, + /// `DeltaPocS1[stRpsIdx][i]` for `i` in + /// `0..NumPositivePics[stRpsIdx]`. All entries are strictly + /// positive. + pub delta_poc_s1: Vec, + /// `UsedByCurrPicS1[stRpsIdx][i]` for `i` in + /// `0..NumPositivePics[stRpsIdx]`. + pub used_by_curr_pic_s1: Vec, +} + +impl MaterializedShortTermRefPicSet { + /// `NumNegativePics[stRpsIdx]` per §7.4.8. + pub fn num_negative_pics(&self) -> u32 { + self.delta_poc_s0.len() as u32 + } + /// `NumPositivePics[stRpsIdx]` per §7.4.8. + pub fn num_positive_pics(&self) -> u32 { + self.delta_poc_s1.len() as u32 + } + /// `NumDeltaPocs[stRpsIdx]` per equation 7-71. + pub fn num_delta_pocs(&self) -> u32 { + self.num_negative_pics() + self.num_positive_pics() + } +} + +/// Long-term reference picture entry per the `long_term_ref_pics_present_flag` +/// block of §7.3.2.2. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct LongTermRefPicEntry { + /// `lt_ref_pic_poc_lsb_sps[i]` — `u(v)` whose width is + /// `log2_max_pic_order_cnt_lsb_minus4 + 4` bits. + pub poc_lsb: u32, + /// `used_by_curr_pic_lt_sps_flag[i]`. + pub used_by_curr_pic: bool, +} + +/// Opaque suffix surfaced when the parser hits an extension body it +/// does not yet decode (any of `sps_range_extension()`, +/// `sps_multilayer_extension()`, `sps_3d_extension()`, +/// `sps_scc_extension()`, or the `sps_extension_data_flag` while-loop +/// gated by `sps_extension_4bits != 0`; also reused by the +/// [`crate::pps::PicParameterSet`] extension tail). The bytes captured +/// are the still-unparsed RBSP body, starting at the byte that +/// contains the next un-read bit. `start_bit_in_first_byte` is the +/// bit offset of that next bit within `bytes[0]` (0 = MSB). +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct OpaqueTail { + /// Raw RBSP bytes from the first byte containing the next + /// un-read bit onwards (including the `rbsp_trailing_bits()` byte + /// at the end). + pub bytes: Vec, + /// Bit offset within `bytes[0]` where the opaque tail begins, + /// in MSB-first order (0..=7). + pub start_bit_in_first_byte: u8, +} + +/// SPS extension-flag block per §7.3.2.2.1 +/// (`sps_extension_present_flag == 1`), holding the four typed +/// extension-present flags and the reserved-for-future-use +/// `sps_extension_4bits` group. +/// +/// Per §7.4.3.2.1, when `sps_extension_present_flag == 0` every flag +/// in this block is inferred to 0 and `sps_extension_4bits` is +/// inferred to 0; the parser surfaces that case as +/// [`SeqParameterSet::extension_flags`] = `None`. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SpsExtensionFlags { + /// `sps_range_extension_flag` (§7.3.2.2.1). When true, a + /// `sps_range_extension()` body (§7.3.2.2.2) follows in the bit + /// stream and is currently surfaced inside the SPS + /// [`SeqParameterSet::opaque_tail`]. This flag selects the §A.3.5 + /// Format Range Extensions (RExt) profiles family. + pub sps_range_extension_flag: bool, + /// `sps_multilayer_extension_flag` (§7.3.2.2.1, Annex F / + /// scalable & multi-view extensions). When true, a + /// `sps_multilayer_extension()` body follows and is surfaced + /// inside the opaque tail. + pub sps_multilayer_extension_flag: bool, + /// `sps_3d_extension_flag` (§7.3.2.2.1, Annex I). When true, a + /// `sps_3d_extension()` body follows and is surfaced inside the + /// opaque tail. + pub sps_3d_extension_flag: bool, + /// `sps_scc_extension_flag` (§7.3.2.2.1). When true, a + /// `sps_scc_extension()` body follows and is surfaced inside the + /// opaque tail. This flag selects the §A.3.7 Screen Content + /// Coding (SCC) profiles family. + pub sps_scc_extension_flag: bool, + /// `sps_extension_4bits` (`u(4)`). For bitstreams conforming to + /// the current version of the specification this value shall be + /// 0; non-zero values are reserved for future use. The §7.4.3.2.1 + /// decoder-side rule is to allow any value and (if it is non-zero) + /// consume but ignore the `sps_extension_data_flag` while-loop it + /// gates, so the parser surfaces the value verbatim. The trailing + /// `while( more_rbsp_data() ) sps_extension_data_flag` block (only + /// signalled when this field is non-zero) is surfaced inside the + /// opaque tail. + pub sps_extension_4bits: u8, +} + +impl SpsExtensionFlags { + /// True when at least one of the four extension flags is set or + /// `sps_extension_4bits` is non-zero — i.e. when at least one + /// downstream extension body follows in the bit stream and the + /// SPS therefore carries an opaque tail starting at the first + /// body's bit position. + pub fn has_body(&self) -> bool { + self.sps_range_extension_flag + || self.sps_multilayer_extension_flag + || self.sps_3d_extension_flag + || self.sps_scc_extension_flag + || self.sps_extension_4bits != 0 + } + + /// True when the `sps_scc_extension()` body can be decoded in + /// place — it is signalled and no still-opaque body + /// (`sps_multilayer_extension()` / `sps_3d_extension()`) precedes + /// it in the bit stream. When a multilayer / 3D body precedes it, + /// the SCC body stays inside the opaque tail. + fn scc_decodable_in_place(&self) -> bool { + self.sps_scc_extension_flag + && !self.sps_multilayer_extension_flag + && !self.sps_3d_extension_flag + } + + /// True when an extension body still follows the (range + + /// optionally SCC) bodies decoded in place — i.e. a multilayer / + /// 3D body, the `sps_extension_data_flag` while-loop, or an + /// SCC body whose multilayer/3D predecessor kept it opaque. + fn has_opaque_body_after_decoded(&self) -> bool { + if self.sps_multilayer_extension_flag || self.sps_3d_extension_flag { + // The first un-decoded body is the multilayer / 3D one; + // everything from there (incl. any SCC body) is opaque. + return true; + } + // No multilayer / 3D body: SCC (if present) was decoded in + // place, so only the sps_extension_data_flag while-loop may + // remain. + self.sps_extension_4bits != 0 + } +} + +/// Decoded `sps_scc_extension()` body per §7.3.2.2.3, present when +/// [`SpsExtensionFlags::sps_scc_extension_flag`] is set and no opaque +/// multilayer / 3D body precedes it. Per §7.4.3.2.3 the absent fields +/// are inferred to 0 / empty when this struct is `None`. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct SpsSccExtension { + /// `sps_curr_pic_ref_enabled_flag` — when 1, a picture referring + /// to the SPS may be in a reference picture list of one of its own + /// slices (intra block copy). + pub sps_curr_pic_ref_enabled_flag: bool, + /// `palette_mode_enabled_flag` — when 1, the palette-mode decoding + /// process may be used for intra blocks. + pub palette_mode_enabled_flag: bool, + /// `palette_max_size` (`ue(v)`), present only when + /// `palette_mode_enabled_flag`; the maximum allowed palette size + /// (inferred 0 otherwise). + pub palette_max_size: u32, + /// `delta_palette_max_predictor_size` (`ue(v)`), present only when + /// `palette_mode_enabled_flag`. `PaletteMaxPredictorSize = + /// palette_max_size + value` (eq. 7-35). + pub delta_palette_max_predictor_size: u32, + /// `sps_palette_predictor_initializers_present_flag` — when 1, the + /// sequence palette predictor is initialised from + /// [`Self::sps_palette_predictor_initializer`]. + pub sps_palette_predictor_initializers_present_flag: bool, + /// `sps_num_palette_predictor_initializers_minus1` (`ue(v)`), + /// present only when the initializers-present flag is set; the + /// initializer table then holds `value + 1` entries per component. + pub sps_num_palette_predictor_initializers_minus1: u32, + /// `sps_palette_predictor_initializer[comp][i]` (§7.3.2.2.3), + /// indexed `[comp][i]`. `comp` runs over `numComps` (1 when + /// `chroma_format_idc == 0`, else 3). Each value is `u(v)` — + /// `BitDepthY` bits for `comp == 0`, `BitDepthC` bits otherwise. + /// Empty when no initializers are signalled. + pub sps_palette_predictor_initializer: Vec>, + /// `motion_vector_resolution_control_idc` (`u(2)`) — controls the + /// presence / inference of `use_integer_mv_flag`. + pub motion_vector_resolution_control_idc: u8, + /// `intra_boundary_filtering_disabled_flag` — when 1, the intra + /// boundary filtering process is unconditionally disabled. + pub intra_boundary_filtering_disabled_flag: bool, +} + +impl SpsSccExtension { + /// Decode `sps_scc_extension()` (§7.3.2.2.3). `chroma_format_idc` + /// selects `numComps` (1 if 0, else 3) and `bit_depth_luma` / + /// `bit_depth_chroma` give the `u(v)` width of each palette + /// predictor initializer component. + fn parse( + br: &mut BitReader, + chroma_format_idc: u8, + bit_depth_luma: u8, + bit_depth_chroma: u8, + ) -> Result { + let sps_curr_pic_ref_enabled_flag = br.u1()? != 0; + let palette_mode_enabled_flag = br.u1()? != 0; + let mut palette_max_size = 0u32; + let mut delta_palette_max_predictor_size = 0u32; + let mut sps_palette_predictor_initializers_present_flag = false; + let mut sps_num_palette_predictor_initializers_minus1 = 0u32; + let mut sps_palette_predictor_initializer = Vec::new(); + if palette_mode_enabled_flag { + palette_max_size = br.ue()?; + delta_palette_max_predictor_size = br.ue()?; + // §7.4.3.2.3: when palette_max_size == 0 the + // delta_palette_max_predictor_size must be 0 (bitstream + // conformance — a zero-size palette cannot grow the + // predictor). + if palette_max_size == 0 && delta_palette_max_predictor_size != 0 { + return Err(SpsError::ValueOutOfRange { + field: "delta_palette_max_predictor_size", + got: delta_palette_max_predictor_size, + }); + } + sps_palette_predictor_initializers_present_flag = br.u1()? != 0; + // §7.4.3.2.3: likewise the initializers-present flag must be + // 0 when palette_max_size == 0. + if palette_max_size == 0 && sps_palette_predictor_initializers_present_flag { + return Err(SpsError::ValueOutOfRange { + field: "sps_palette_predictor_initializers_present_flag", + got: 1, + }); + } + if sps_palette_predictor_initializers_present_flag { + sps_num_palette_predictor_initializers_minus1 = br.ue()?; + // §7.4.3.2.3: bounded by PaletteMaxPredictorSize − 1, + // itself capped by the profile limits (§A.3.7: + // PaletteMaxPredictorSize <= 128); reject anything past + // the largest representable predictor so a malformed + // count cannot drive the initializer allocation. + if sps_num_palette_predictor_initializers_minus1 >= 128 { + return Err(SpsError::ValueOutOfRange { + field: "sps_num_palette_predictor_initializers_minus1", + got: sps_num_palette_predictor_initializers_minus1, + }); + } + let num_comps = if chroma_format_idc == 0 { 1 } else { 3 }; + let num_entries = sps_num_palette_predictor_initializers_minus1 as usize + 1; + sps_palette_predictor_initializer.reserve(num_comps); + for comp in 0..num_comps { + let width = if comp == 0 { + bit_depth_luma + } else { + bit_depth_chroma + }; + let mut row = Vec::with_capacity(num_entries); + for _ in 0..num_entries { + row.push(br.u(width)?); + } + sps_palette_predictor_initializer.push(row); + } + } + } + let motion_vector_resolution_control_idc = br.u(2)? as u8; + // §7.4.3.2.3: the value 3 is reserved for future use and must + // not appear in a conforming bitstream of this version. + if motion_vector_resolution_control_idc == 3 { + return Err(SpsError::ValueOutOfRange { + field: "motion_vector_resolution_control_idc", + got: 3, + }); + } + let intra_boundary_filtering_disabled_flag = br.u1()? != 0; + Ok(Self { + sps_curr_pic_ref_enabled_flag, + palette_mode_enabled_flag, + palette_max_size, + delta_palette_max_predictor_size, + sps_palette_predictor_initializers_present_flag, + sps_num_palette_predictor_initializers_minus1, + sps_palette_predictor_initializer, + motion_vector_resolution_control_idc, + intra_boundary_filtering_disabled_flag, + }) + } + + /// `PaletteMaxPredictorSize` (eq. 7-35) — the maximum allowed + /// palette predictor size, `palette_max_size + + /// delta_palette_max_predictor_size`. + pub fn palette_max_predictor_size(&self) -> u32 { + self.palette_max_size + self.delta_palette_max_predictor_size + } +} + +/// Decoded `sps_range_extension()` body per §7.3.2.2.2, present when +/// [`SpsExtensionFlags::sps_range_extension_flag`] is set. Every field +/// is a single `u(1)` flag; per §7.4.3.2.2 each is inferred to 0 when +/// the `sps_range_extension()` body is absent (i.e. when +/// [`SeqParameterSet::sps_range_extension`] is `None`). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SpsRangeExtension { + /// `transform_skip_rotation_enabled_flag` — when 1, a rotation is + /// applied to the residual of intra 4×4 transform-skip / + /// transform-bypass blocks. + pub transform_skip_rotation_enabled_flag: bool, + /// `transform_skip_context_enabled_flag` — when 1, a particular + /// context is used for parsing `sig_coeff_flag` / coefficient + /// magnitudes of transform-skip / transform-bypass blocks. + pub transform_skip_context_enabled_flag: bool, + /// `implicit_rdpcm_enabled_flag` — when 1, residual modification + /// for blocks using a transform-bypass may be used for intra + /// blocks referring to the SPS. + pub implicit_rdpcm_enabled_flag: bool, + /// `explicit_rdpcm_enabled_flag` — when 1, residual modification + /// for blocks using a transform-bypass may be used for inter + /// blocks referring to the SPS. + pub explicit_rdpcm_enabled_flag: bool, + /// `extended_precision_processing_flag` — when 1, an extended + /// dynamic range is used for coefficient parsing and inverse + /// transform processing. + pub extended_precision_processing_flag: bool, + /// `intra_smoothing_disabled_flag` — when 1, the filtering process + /// of neighbouring samples is unconditionally disabled for intra + /// prediction. + pub intra_smoothing_disabled_flag: bool, + /// `high_precision_offsets_enabled_flag` — when 1, weighted + /// prediction offsets and SAO offsets use a bit depth of + /// `BitDepth` rather than the default precision. + pub high_precision_offsets_enabled_flag: bool, + /// `persistent_rice_adaptation_enabled_flag` — when 1, the Rice + /// parameter derivation for the binarization of + /// `coeff_abs_level_remaining[]` is initialised at the start of + /// each sub-block using mode-dependent statistics accumulated from + /// previous sub-blocks. + pub persistent_rice_adaptation_enabled_flag: bool, + /// `cabac_bypass_alignment_enabled_flag` — when 1, a CABAC + /// alignment process is used prior to bypass decoding of the + /// syntax elements `coeff_sign_flag[]` and + /// `coeff_abs_level_remaining[]`. + pub cabac_bypass_alignment_enabled_flag: bool, +} + +impl SpsRangeExtension { + /// Decode the nine `u(1)` flags of `sps_range_extension()` + /// (§7.3.2.2.2) in bit-stream order. + fn parse(br: &mut BitReader) -> Result { + Ok(Self { + transform_skip_rotation_enabled_flag: br.u1()? != 0, + transform_skip_context_enabled_flag: br.u1()? != 0, + implicit_rdpcm_enabled_flag: br.u1()? != 0, + explicit_rdpcm_enabled_flag: br.u1()? != 0, + extended_precision_processing_flag: br.u1()? != 0, + intra_smoothing_disabled_flag: br.u1()? != 0, + high_precision_offsets_enabled_flag: br.u1()? != 0, + persistent_rice_adaptation_enabled_flag: br.u1()? != 0, + cabac_bypass_alignment_enabled_flag: br.u1()? != 0, + }) + } +} + +/// Parsed Sequence Parameter Set per §7.3.2.2. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct SeqParameterSet { + /// `sps_video_parameter_set_id` (`u(4)`, range 0..=15). + pub vps_id: u8, + /// `sps_max_sub_layers_minus1` (`u(3)`, range 0..=6). + pub max_sub_layers_minus1: u8, + /// `sps_temporal_id_nesting_flag`. + pub temporal_id_nesting_flag: bool, + /// Parsed `profile_tier_level()` subroutine. + pub ptl: ProfileTierLevel, + /// `sps_seq_parameter_set_id` (`ue(v)`, range 0..=15). + pub sps_id: u8, + /// `chroma_format_idc` (`ue(v)`, range 0..=3). 0 monochrome, 1 + /// 4:2:0, 2 4:2:2, 3 4:4:4. + pub chroma_format_idc: u8, + /// `separate_colour_plane_flag`. Inferred to false when not + /// signalled (which is whenever `chroma_format_idc != 3`). + pub separate_colour_plane_flag: bool, + /// `pic_width_in_luma_samples` (`ue(v)`). + pub pic_width_in_luma_samples: u32, + /// `pic_height_in_luma_samples` (`ue(v)`). + pub pic_height_in_luma_samples: u32, + /// `conformance_window_flag`. + pub conformance_window_flag: bool, + /// `conf_win_*_offset` triple plus bottom — zeroed when + /// `conformance_window_flag` is false (§7.4.3.2.1). + pub conformance_window: ConformanceWindow, + /// `bit_depth_luma_minus8` (`ue(v)`, range 0..=8). The decoded + /// `BitDepthY` is `8 + value`. + pub bit_depth_luma_minus8: u8, + /// `bit_depth_chroma_minus8` (`ue(v)`, range 0..=8). + pub bit_depth_chroma_minus8: u8, + /// `log2_max_pic_order_cnt_lsb_minus4` (`ue(v)`, range 0..=12). + pub log2_max_pic_order_cnt_lsb_minus4: u8, + /// `sps_sub_layer_ordering_info_present_flag`. + pub sub_layer_ordering_info_present_flag: bool, + /// Per-sub-layer DPB / reorder / latency triples. Indices outside + /// `0..=max_sub_layers_minus1` are zero-initialised; when the + /// present flag was 0 every lower-indexed entry is copied from + /// the `[max_sub_layers_minus1]` slot (§7.4.3.2.1). + pub sub_layer_ordering_info: [SubLayerOrderingInfo; HEVC_MAX_SUB_LAYERS], + /// `log2_min_luma_coding_block_size_minus3` (`ue(v)`). + pub log2_min_luma_coding_block_size_minus3: u8, + /// `log2_diff_max_min_luma_coding_block_size` (`ue(v)`). Per the + /// `log2_ctb_size` derivation in §7.4.3.2.1, the CTU size is + /// `1 << (3 + log2_min_cb_minus3 + log2_diff_max_min_luma_cb)`. + pub log2_diff_max_min_luma_coding_block_size: u8, + /// `log2_min_luma_transform_block_size_minus2` (`ue(v)`). + pub log2_min_luma_transform_block_size_minus2: u8, + /// `log2_diff_max_min_luma_transform_block_size` (`ue(v)`). + pub log2_diff_max_min_luma_transform_block_size: u8, + /// `max_transform_hierarchy_depth_inter` (`ue(v)`). + pub max_transform_hierarchy_depth_inter: u8, + /// `max_transform_hierarchy_depth_intra` (`ue(v)`). + pub max_transform_hierarchy_depth_intra: u8, + /// `scaling_list_enabled_flag` (§7.3.2.2). When set, the SPS + /// either carries an explicit [`Self::scaling_list_data`] (when + /// `sps_scaling_list_data_present_flag == 1`) or the §7.4.5 default + /// scaling lists apply. + pub scaling_list_enabled_flag: bool, + /// `sps_scaling_list_data_present_flag` (§7.3.2.2). Inferred to + /// `false` (the §7.4.5 default lists apply) when + /// `scaling_list_enabled_flag == 0`. + pub sps_scaling_list_data_present_flag: bool, + /// The parsed §7.3.4 `scaling_list_data()` structure when + /// `sps_scaling_list_data_present_flag == 1`; `None` otherwise (the + /// §7.4.5 default lists apply). + pub scaling_list_data: Option, + /// `amp_enabled_flag` — asymmetric motion partitions. + pub amp_enabled_flag: bool, + /// `sample_adaptive_offset_enabled_flag` — SPS-level gate for + /// SAO; the per-slice gates are in the slice header. + pub sample_adaptive_offset_enabled_flag: bool, + /// `pcm_enabled_flag` — when set, [`Self::pcm`] is populated. + pub pcm_enabled_flag: bool, + /// `pcm_*` block per §7.3.2.2 (only meaningful when + /// [`Self::pcm_enabled_flag`] is true). + pub pcm: Option, + /// `num_short_term_ref_pic_sets` (`ue(v)`, range 0..=64). + pub num_short_term_ref_pic_sets: u32, + /// Parsed `st_ref_pic_set()` entries, length + /// [`Self::num_short_term_ref_pic_sets`]. + pub short_term_ref_pic_sets: Vec, + /// `long_term_ref_pics_present_flag`. + pub long_term_ref_pics_present_flag: bool, + /// `num_long_term_ref_pics_sps` (`ue(v)`, range 0..=32). Zero + /// when [`Self::long_term_ref_pics_present_flag`] is false. + pub num_long_term_ref_pics_sps: u32, + /// Per-entry long-term ref pic POC + used-by-curr-pic flag. + /// Empty when [`Self::long_term_ref_pics_present_flag`] is false. + pub long_term_ref_pics: Vec, + /// `sps_temporal_mvp_enabled_flag`. + pub sps_temporal_mvp_enabled_flag: bool, + /// `strong_intra_smoothing_enabled_flag`. + pub strong_intra_smoothing_enabled_flag: bool, + /// `vui_parameters_present_flag`. When true, the §E.2.1 + /// `vui_parameters( )` body is decoded into + /// [`Self::vui_parameters`] and parsing continues to + /// `sps_extension_present_flag`. + pub vui_parameters_present_flag: bool, + /// Parsed §E.2.1 `vui_parameters()` body when + /// [`Self::vui_parameters_present_flag`] is true; `None` + /// otherwise. + pub vui_parameters: Option, + /// `sps_extension_present_flag`. Read in both the VUI-present and + /// VUI-absent paths now that the VUI body is fully decoded. When + /// true, the typed extension flag block is decoded into + /// [`Self::extension_flags`]; any extension body that follows + /// (plus the RBSP trailing bits) is surfaced as + /// [`Self::opaque_tail`]. + pub sps_extension_present_flag: bool, + /// Typed extension-flag block, decoded when + /// `sps_extension_present_flag == 1` per §7.3.2.2.1. `None` when + /// the gate is 0; every flag is then inferred to 0 per §7.4.3.2.1. + pub extension_flags: Option, + /// Decoded `sps_range_extension()` body (§7.3.2.2.2), present when + /// `extension_flags.sps_range_extension_flag` is set. `None` + /// otherwise; per §7.4.3.2.2 every field is then inferred to 0. + pub sps_range_extension: Option, + /// Decoded `sps_scc_extension()` body (§7.3.2.2.3), present when + /// `extension_flags.sps_scc_extension_flag` is set **and** no + /// opaque multilayer / 3D body precedes it. `None` otherwise; per + /// §7.4.3.2.3 every field is then inferred to 0 / empty. + pub sps_scc_extension: Option, + /// Opaque suffix of the SPS RBSP. Populated when + /// `sps_extension_present_flag == 1` **and** + /// [`SpsExtensionFlags::has_body`] is true on the decoded flags — + /// the captured bytes start at the first set body + /// (`sps_range_extension()` if `sps_range_extension_flag`, + /// otherwise the next set flag's body) and run through + /// `rbsp_trailing_bits()`. `None` when the SPS ended cleanly + /// after `sps_extension_present_flag == 0` or after a typed flag + /// block in which every flag is 0. + pub opaque_tail: Option, +} + +impl SeqParameterSet { + /// Parse `seq_parameter_set_rbsp()` starting from the first bit + /// of the (already-unescaped) RBSP body — i.e. after the two-byte + /// NAL header has been removed (see [`crate::nal::NalUnit`]). + pub fn parse(rbsp: &[u8]) -> Result { + let mut br = BitReader::new(rbsp); + Self::parse_inner(&mut br, rbsp) + } + + /// Materialise the full SPS-level `short_term_ref_pic_sets[]` + /// list into the post-§7.4.8 form, chaining inter-RPS-prediction + /// entries through their `RefRpsIdx = stRpsIdx - + /// (delta_idx_minus1 + 1)` source. + /// + /// The returned vector is the same length as + /// [`Self::short_term_ref_pic_sets`], and the `idx`-th element is + /// the materialisation of + /// `self.short_term_ref_pic_sets[idx]`. Returns an error if any + /// in-chain materialisation fails (e.g. `RefRpsIdx` underflow, + /// `used_by_curr_pic_flag` / `use_delta_flag` length mismatch). + pub fn materialize_short_term_ref_pic_sets( + &self, + ) -> Result, ShortTermRefPicSetMaterializeError> { + let mut out: Vec = + Vec::with_capacity(self.short_term_ref_pic_sets.len()); + for (st_rps_idx, rps) in self.short_term_ref_pic_sets.iter().enumerate() { + // `RefRpsIdx = stRpsIdx - (delta_idx_minus1 + 1)` per + // equation 7-59. For the explicit form `source` is unused + // and `RefRpsIdx` is not derived. For the inter form + // `delta_idx_minus1` was parsed as 0 for any SPS-resident + // entry that did not signal it explicitly (the wire signal + // is only present at the slice-inline call site), which + // maps to the immediately-preceding entry. + let source = if rps.inter_ref_pic_set_prediction_flag { + let ref_rps_idx = (st_rps_idx as i64) - (rps.delta_idx_minus1 as i64 + 1); + if ref_rps_idx < 0 { + return Err(ShortTermRefPicSetMaterializeError::MissingSource); + } + out.get(ref_rps_idx as usize) + } else { + None + }; + out.push(rps.materialize(source)?); + } + Ok(out) + } + + fn parse_inner(br: &mut BitReader<'_>, rbsp: &[u8]) -> Result { + let vps_id = br.u(4)? as u8; + let max_sub_layers_minus1 = br.u(3)? as u8; + if max_sub_layers_minus1 > 6 { + return Err(SpsError::ValueOutOfRange { + field: "sps_max_sub_layers_minus1", + got: max_sub_layers_minus1 as u32, + }); + } + let temporal_id_nesting_flag = br.u1()? != 0; + + // profile_tier_level( 1, sps_max_sub_layers_minus1 ) + let ptl = ProfileTierLevel::parse(br, true, max_sub_layers_minus1)?; + + let sps_id_raw = br.ue()?; + if sps_id_raw > 15 { + return Err(SpsError::ValueOutOfRange { + field: "sps_seq_parameter_set_id", + got: sps_id_raw, + }); + } + let sps_id = sps_id_raw as u8; + + let chroma_format_idc_raw = br.ue()?; + if chroma_format_idc_raw > 3 { + return Err(SpsError::ValueOutOfRange { + field: "chroma_format_idc", + got: chroma_format_idc_raw, + }); + } + let chroma_format_idc = chroma_format_idc_raw as u8; + + let separate_colour_plane_flag = if chroma_format_idc == 3 { + br.u1()? != 0 + } else { + false + }; + + // §A.4.1 items b) / c): each dimension "shall be less than or + // equal to Sqrt( MaxLumaPs * 8 )". The largest Table A.8 + // MaxLumaPs is 142 606 336 (levels 7 .. 7.2), giving + // Sqrt( 142 606 336 * 8 ) = 33 776 (integer part). Enforcing + // the ceiling here keeps every downstream PicWidthInCtbsY / + // PicSizeInCtbsY derivation (eqs. 7-15 .. 7-19) inside u32. + const MAX_LUMA_DIMENSION: u32 = 33_776; + let pic_width_in_luma_samples = br.ue()?; + if pic_width_in_luma_samples == 0 || pic_width_in_luma_samples > MAX_LUMA_DIMENSION { + return Err(SpsError::ValueOutOfRange { + field: "pic_width_in_luma_samples", + got: pic_width_in_luma_samples, + }); + } + let pic_height_in_luma_samples = br.ue()?; + if pic_height_in_luma_samples == 0 || pic_height_in_luma_samples > MAX_LUMA_DIMENSION { + return Err(SpsError::ValueOutOfRange { + field: "pic_height_in_luma_samples", + got: pic_height_in_luma_samples, + }); + } + + let conformance_window_flag = br.u1()? != 0; + let conformance_window = if conformance_window_flag { + ConformanceWindow { + left_offset: br.ue()?, + right_offset: br.ue()?, + top_offset: br.ue()?, + bottom_offset: br.ue()?, + } + } else { + ConformanceWindow::default() + }; + + let bit_depth_luma_minus8_raw = br.ue()?; + if bit_depth_luma_minus8_raw > 8 { + return Err(SpsError::ValueOutOfRange { + field: "bit_depth_luma_minus8", + got: bit_depth_luma_minus8_raw, + }); + } + let bit_depth_chroma_minus8_raw = br.ue()?; + if bit_depth_chroma_minus8_raw > 8 { + return Err(SpsError::ValueOutOfRange { + field: "bit_depth_chroma_minus8", + got: bit_depth_chroma_minus8_raw, + }); + } + + let log2_max_pic_order_cnt_lsb_minus4_raw = br.ue()?; + if log2_max_pic_order_cnt_lsb_minus4_raw > 12 { + return Err(SpsError::ValueOutOfRange { + field: "log2_max_pic_order_cnt_lsb_minus4", + got: log2_max_pic_order_cnt_lsb_minus4_raw, + }); + } + + let sub_layer_ordering_info_present_flag = br.u1()? != 0; + let last = max_sub_layers_minus1 as usize; + let start = if sub_layer_ordering_info_present_flag { + 0usize + } else { + last + }; + let mut sub_layer_ordering_info = [SubLayerOrderingInfo::default(); HEVC_MAX_SUB_LAYERS]; + for entry in sub_layer_ordering_info + .iter_mut() + .take(last + 1) + .skip(start) + { + let max_dpb = br.ue()?; + let max_reorder = br.ue()?; + let max_lat = br.ue()?; + *entry = SubLayerOrderingInfo { + max_dec_pic_buffering_minus1: max_dpb, + max_num_reorder_pics: max_reorder, + max_latency_increase_plus1: max_lat, + }; + } + if !sub_layer_ordering_info_present_flag { + // §7.4.3.2.1: when the present flag is 0, every lower-indexed + // sub-layer inherits the [max_sub_layers_minus1] triple. + let copy = sub_layer_ordering_info[last]; + for entry in sub_layer_ordering_info.iter_mut().take(last) { + *entry = copy; + } + } + + let log2_min_luma_coding_block_size_minus3_raw = br.ue()?; + let log2_diff_max_min_luma_coding_block_size_raw = br.ue()?; + // §7.4.3.2.1 eqs. 7-10 / 7-11: MinCbLog2SizeY = + // log2_min_luma_coding_block_size_minus3 + 3 and CtbLog2SizeY = + // MinCbLog2SizeY + log2_diff_max_min_luma_coding_block_size. + // Every Annex A profile requires "CtbLog2SizeY derived + // according to active SPSs ... shall be in the range of 4 to 6, + // inclusive" (e.g. the §A.3.2 Main-profile item), and the + // eq.-7-13 `CtbSizeY = 1 << CtbLog2SizeY` shift (re-derived all + // over the slice/CTB layers) is only meaningful under that + // bound — reject out-of-range values here. + let ctb_log2_size_y = log2_min_luma_coding_block_size_minus3_raw + .saturating_add(3) + .saturating_add(log2_diff_max_min_luma_coding_block_size_raw); + if !(4..=6).contains(&ctb_log2_size_y) { + return Err(SpsError::ValueOutOfRange { + field: "CtbLog2SizeY", + got: ctb_log2_size_y, + }); + } + let log2_min_luma_coding_block_size_minus3 = + log2_min_luma_coding_block_size_minus3_raw as u8; + let log2_diff_max_min_luma_coding_block_size = + log2_diff_max_min_luma_coding_block_size_raw as u8; + let min_cb_log2_size_y = u32::from(log2_min_luma_coding_block_size_minus3) + 3; + + let log2_min_luma_transform_block_size_minus2_raw = br.ue()?; + // §7.4.3.2.1: "The CVS shall not contain data that result in + // MinTbLog2SizeY greater than or equal to MinCbLog2SizeY" + // (MinTbLog2SizeY = log2_min_luma_transform_block_size_minus2 + // + 2). + let min_tb_log2_size_y = log2_min_luma_transform_block_size_minus2_raw.saturating_add(2); + if min_tb_log2_size_y >= min_cb_log2_size_y { + return Err(SpsError::ValueOutOfRange { + field: "log2_min_luma_transform_block_size_minus2", + got: log2_min_luma_transform_block_size_minus2_raw, + }); + } + let log2_min_luma_transform_block_size_minus2 = + log2_min_luma_transform_block_size_minus2_raw as u8; + + let log2_diff_max_min_luma_transform_block_size_raw = br.ue()?; + // §7.4.3.2.1: "The CVS shall not contain data that result in + // MaxTbLog2SizeY greater than Min( CtbLog2SizeY, 5 )". + let max_tb_log2_size_y = + min_tb_log2_size_y.saturating_add(log2_diff_max_min_luma_transform_block_size_raw); + if max_tb_log2_size_y > ctb_log2_size_y.min(5) { + return Err(SpsError::ValueOutOfRange { + field: "log2_diff_max_min_luma_transform_block_size", + got: log2_diff_max_min_luma_transform_block_size_raw, + }); + } + let log2_diff_max_min_luma_transform_block_size = + log2_diff_max_min_luma_transform_block_size_raw as u8; + + // §7.4.3.2.1: both hierarchy depths "shall be in the range of + // 0 to CtbLog2SizeY − MinTbLog2SizeY, inclusive". + let max_hierarchy_depth = ctb_log2_size_y - min_tb_log2_size_y; + let max_transform_hierarchy_depth_inter_raw = br.ue()?; + if max_transform_hierarchy_depth_inter_raw > max_hierarchy_depth { + return Err(SpsError::ValueOutOfRange { + field: "max_transform_hierarchy_depth_inter", + got: max_transform_hierarchy_depth_inter_raw, + }); + } + let max_transform_hierarchy_depth_inter = max_transform_hierarchy_depth_inter_raw as u8; + let max_transform_hierarchy_depth_intra_raw = br.ue()?; + if max_transform_hierarchy_depth_intra_raw > max_hierarchy_depth { + return Err(SpsError::ValueOutOfRange { + field: "max_transform_hierarchy_depth_intra", + got: max_transform_hierarchy_depth_intra_raw, + }); + } + let max_transform_hierarchy_depth_intra = max_transform_hierarchy_depth_intra_raw as u8; + + let scaling_list_enabled_flag = br.u1()? != 0; + let mut sps_scaling_list_data_present_flag = false; + let mut scaling_list_data = None; + if scaling_list_enabled_flag { + // §7.3.2.2: when scaling_list_enabled_flag == 1, an inner + // sps_scaling_list_data_present_flag gates the explicit + // scaling_list_data() structure (§7.3.4). When the inner + // flag is 0 the default scaling lists (§7.4.5 Tables 7-5 / + // 7-6) apply, so the SPS still parses. + sps_scaling_list_data_present_flag = br.u1()? != 0; + if sps_scaling_list_data_present_flag { + scaling_list_data = Some(ScalingListData::parse(br)?); + } + } + + let amp_enabled_flag = br.u1()? != 0; + let sample_adaptive_offset_enabled_flag = br.u1()? != 0; + + let pcm_enabled_flag = br.u1()? != 0; + let pcm = if pcm_enabled_flag { + let bit_depth_luma_minus1 = br.u(4)? as u8; + let pcm_bit_depth_y = bit_depth_luma_minus1 as u32 + 1; + let bit_depth_y = 8 + bit_depth_luma_minus8_raw; + if pcm_bit_depth_y > bit_depth_y { + return Err(SpsError::ValueOutOfRange { + field: "pcm_sample_bit_depth_luma_minus1", + got: bit_depth_luma_minus1 as u32, + }); + } + let bit_depth_chroma_minus1 = br.u(4)? as u8; + let pcm_bit_depth_c = bit_depth_chroma_minus1 as u32 + 1; + let bit_depth_c = 8 + bit_depth_chroma_minus8_raw; + if pcm_bit_depth_c > bit_depth_c { + return Err(SpsError::ValueOutOfRange { + field: "pcm_sample_bit_depth_chroma_minus1", + got: bit_depth_chroma_minus1 as u32, + }); + } + let log2_min_pcm_luma_coding_block_size_minus3 = br.ue()? as u8; + let log2_diff_max_min_pcm_luma_coding_block_size = br.ue()? as u8; + let loop_filter_disabled_flag = br.u1()? != 0; + Some(PcmInfo { + bit_depth_luma_minus1, + bit_depth_chroma_minus1, + log2_min_pcm_luma_coding_block_size_minus3, + log2_diff_max_min_pcm_luma_coding_block_size, + loop_filter_disabled_flag, + }) + } else { + None + }; + + let num_short_term_ref_pic_sets_raw = br.ue()?; + if num_short_term_ref_pic_sets_raw > HEVC_MAX_NUM_SHORT_TERM_RPS as u32 { + return Err(SpsError::ValueOutOfRange { + field: "num_short_term_ref_pic_sets", + got: num_short_term_ref_pic_sets_raw, + }); + } + let num_short_term_ref_pic_sets = num_short_term_ref_pic_sets_raw; + let mut short_term_ref_pic_sets = Vec::with_capacity(num_short_term_ref_pic_sets as usize); + for st_rps_idx in 0..num_short_term_ref_pic_sets as usize { + let prev = if st_rps_idx == 0 { + None + } else { + short_term_ref_pic_sets.last() + }; + let rps = ShortTermRefPicSet::parse( + br, + st_rps_idx as u32, + num_short_term_ref_pic_sets, + prev, + &short_term_ref_pic_sets, + )?; + short_term_ref_pic_sets.push(rps); + } + + let long_term_ref_pics_present_flag = br.u1()? != 0; + let mut num_long_term_ref_pics_sps = 0u32; + let mut long_term_ref_pics = Vec::new(); + if long_term_ref_pics_present_flag { + let raw = br.ue()?; + if raw > HEVC_MAX_NUM_LONG_TERM_RPS as u32 { + return Err(SpsError::ValueOutOfRange { + field: "num_long_term_ref_pics_sps", + got: raw, + }); + } + num_long_term_ref_pics_sps = raw; + let poc_lsb_bits = log2_max_pic_order_cnt_lsb_minus4_raw as u8 + 4; + long_term_ref_pics.reserve(num_long_term_ref_pics_sps as usize); + for _ in 0..num_long_term_ref_pics_sps { + let poc_lsb = br.u(poc_lsb_bits)?; + let used = br.u1()? != 0; + long_term_ref_pics.push(LongTermRefPicEntry { + poc_lsb, + used_by_curr_pic: used, + }); + } + } + + let sps_temporal_mvp_enabled_flag = br.u1()? != 0; + let strong_intra_smoothing_enabled_flag = br.u1()? != 0; + + let vui_parameters_present_flag = br.u1()? != 0; + // §E.2.1: the vui_parameters() body is decoded in full when + // signalled, with the nested hrd_parameters( 1, + // sps_max_sub_layers_minus1 ) call taking the SPS-level + // maxNumSubLayersMinus1. Parsing then continues to + // sps_extension_present_flag in both paths. + let vui_parameters = if vui_parameters_present_flag { + Some(VuiParameters::parse(br, max_sub_layers_minus1)?) + } else { + None + }; + + let ( + sps_extension_present_flag, + extension_flags, + sps_range_extension, + sps_scc_extension, + opaque_tail, + ) = if br.bits_left() == 0 { + // The fixture corpus encoders sometimes elide the + // sps_extension_present_flag if no extension is signalled + // and the rbsp_trailing_bits happens to land on a byte + // boundary; the field is still required, so a buffer with + // no bits left here is a truncation. + return Err(SpsError::Truncated); + } else { + let gate = br.u1()? != 0; + if gate { + // §7.3.2.2.1: when the gate is open, decode the eight + // bits of typed extension flags first. + let sps_range_extension_flag = br.u1()? != 0; + let sps_multilayer_extension_flag = br.u1()? != 0; + let sps_3d_extension_flag = br.u1()? != 0; + let sps_scc_extension_flag = br.u1()? != 0; + let sps_extension_4bits = br.u(4)? as u8; + let flags = SpsExtensionFlags { + sps_range_extension_flag, + sps_multilayer_extension_flag, + sps_3d_extension_flag, + sps_scc_extension_flag, + sps_extension_4bits, + }; + // §7.3.2.2.1: the range extension body (if signalled) + // is the first to follow the eight typed flag bits, so + // decode it in full. + let range_ext = if flags.sps_range_extension_flag { + Some(SpsRangeExtension::parse(br)?) + } else { + None + }; + // §7.3.2.2.1 body order is range, multilayer, 3d, scc. + // The SCC body can be decoded in place only when no + // (still-opaque) multilayer / 3D body precedes it; + // otherwise it stays inside the opaque tail. + let scc_ext = if flags.scc_decodable_in_place() { + Some(SpsSccExtension::parse( + br, + chroma_format_idc, + 8 + bit_depth_luma_minus8_raw as u8, + 8 + bit_depth_chroma_minus8_raw as u8, + )?) + } else { + None + }; + // If any still-opaque body (a multilayer / 3D body, an + // SCC body kept opaque by such a predecessor, or the + // sps_extension_data_flag while-loop) follows, capture + // the rest of the RBSP as an opaque tail starting at + // the first un-decoded body's bit position. Otherwise + // only rbsp_trailing_bits remains, consumed implicitly. + let tail = if flags.has_opaque_body_after_decoded() { + Some(OpaqueTail::capture_at(br.bit_pos(), rbsp)) + } else { + None + }; + (true, Some(flags), range_ext, scc_ext, tail) + } else { + // No extension present. Only the rbsp_trailing_bits + // remain — a single `1` bit followed by zero-padding + // to a byte boundary. We do not require the caller to + // have validated it; surface nothing for the opaque tail. + (false, None, None, None, None) + } + }; + + Ok(Self { + vps_id, + max_sub_layers_minus1, + temporal_id_nesting_flag, + ptl, + sps_id, + chroma_format_idc, + separate_colour_plane_flag, + pic_width_in_luma_samples, + pic_height_in_luma_samples, + conformance_window_flag, + conformance_window, + bit_depth_luma_minus8: bit_depth_luma_minus8_raw as u8, + bit_depth_chroma_minus8: bit_depth_chroma_minus8_raw as u8, + log2_max_pic_order_cnt_lsb_minus4: log2_max_pic_order_cnt_lsb_minus4_raw as u8, + sub_layer_ordering_info_present_flag, + sub_layer_ordering_info, + log2_min_luma_coding_block_size_minus3, + log2_diff_max_min_luma_coding_block_size, + log2_min_luma_transform_block_size_minus2, + log2_diff_max_min_luma_transform_block_size, + max_transform_hierarchy_depth_inter, + max_transform_hierarchy_depth_intra, + scaling_list_enabled_flag, + sps_scaling_list_data_present_flag, + scaling_list_data, + amp_enabled_flag, + sample_adaptive_offset_enabled_flag, + pcm_enabled_flag, + pcm, + num_short_term_ref_pic_sets, + short_term_ref_pic_sets, + long_term_ref_pics_present_flag, + num_long_term_ref_pics_sps, + long_term_ref_pics, + sps_temporal_mvp_enabled_flag, + strong_intra_smoothing_enabled_flag, + vui_parameters_present_flag, + vui_parameters, + sps_extension_present_flag, + extension_flags, + sps_range_extension, + sps_scc_extension, + opaque_tail, + }) + } + + /// Convenience: derive the SPS-level `BitDepthY` (luma bit depth). + pub fn bit_depth_luma(&self) -> u8 { + 8 + self.bit_depth_luma_minus8 + } + + /// Derive the SPS-level `BitDepthC` (chroma bit depth). + pub fn bit_depth_chroma(&self) -> u8 { + 8 + self.bit_depth_chroma_minus8 + } + + /// Derive `MinCbLog2SizeY = log2_min_luma_coding_block_size_minus3 + 3` + /// (§7.4.3.2.1). + pub fn log2_min_cb_size(&self) -> u8 { + self.log2_min_luma_coding_block_size_minus3 + 3 + } + + /// Derive `CtbLog2SizeY = MinCbLog2SizeY + /// + log2_diff_max_min_luma_coding_block_size` (§7.4.3.2.1). + pub fn log2_ctb_size(&self) -> u8 { + self.log2_min_cb_size() + self.log2_diff_max_min_luma_coding_block_size + } + + /// Derive `MinTbLog2SizeY = log2_min_luma_transform_block_size_minus2 + 2` + /// (§7.4.3.2.1). + pub fn log2_min_tb_size(&self) -> u8 { + self.log2_min_luma_transform_block_size_minus2 + 2 + } + + /// Derive `MaxPicOrderCntLsb = 1 << (log2_max_pic_order_cnt_lsb_minus4 + 4)` + /// (§7.4.3.2.1). + pub fn max_pic_order_cnt_lsb(&self) -> u32 { + 1u32 << (self.log2_max_pic_order_cnt_lsb_minus4 + 4) + } +} + +impl OpaqueTail { + /// Capture all RBSP bytes from the byte holding the bit at + /// `bit_pos` (counted MSB-first from the start of `rbsp`) through + /// end-of-buffer. Used by both the SPS extension tail and the + /// [`crate::pps::PicParameterSet`] extension tail. + pub fn capture_at(bit_pos: usize, rbsp: &[u8]) -> Self { + let byte_index = bit_pos / 8; + let bit_in_byte = (bit_pos % 8) as u8; + Self { + bytes: rbsp[byte_index..].to_vec(), + start_bit_in_first_byte: bit_in_byte, + } + } +} + +impl ShortTermRefPicSet { + /// Parse the in-line slice-header `st_ref_pic_set( num_short_term_ref_pic_sets )` + /// per §7.3.6.1 / §7.3.7. + /// + /// This is the entry point the slice-header parser uses when + /// `short_term_ref_pic_set_sps_flag == 0`: the picture's short-term + /// RPS is constructed *inline* in the slice header at index + /// `stRpsIdx == num_short_term_ref_pic_sets`, with the SPS's + /// pre-existing list ([`SeqParameterSet::short_term_ref_pic_sets`]) + /// supplying `all_rps` for the §7.4.8 `RefRpsIdx` derivation. + /// + /// `br` must be positioned at the first bit of `st_ref_pic_set()`. + /// On success the reader is advanced past the structure; on a + /// truncation or range-check failure the reader state is undefined. + pub fn parse_slice_inline( + br: &mut BitReader<'_>, + sps: &SeqParameterSet, + ) -> Result { + Self::parse( + br, + sps.num_short_term_ref_pic_sets, + sps.num_short_term_ref_pic_sets, + sps.short_term_ref_pic_sets.last(), + &sps.short_term_ref_pic_sets, + ) + } + + /// Parse one `st_ref_pic_set( stRpsIdx )` per §7.3.7. + /// + /// * `st_rps_idx` is `stRpsIdx`. + /// * `num_short_term_ref_pic_sets` is the SPS-level count being + /// constructed (used to detect when `delta_idx_minus1` is signalled). + /// * `prev` is the previously-parsed RPS, used when the + /// inter-RPS-prediction form is invoked without explicit + /// `delta_idx_minus1` (i.e. `stRpsIdx < num_short_term_ref_pic_sets`). + /// * `all_rps` is the full list of RPSes parsed so far; the + /// §7.4.8 `RefRpsIdx` computation indexes into it. + fn parse( + br: &mut BitReader<'_>, + st_rps_idx: u32, + num_short_term_ref_pic_sets: u32, + prev: Option<&ShortTermRefPicSet>, + all_rps: &[ShortTermRefPicSet], + ) -> Result { + let inter_ref_pic_set_prediction_flag = if st_rps_idx != 0 { + br.u1()? != 0 + } else { + false + }; + if inter_ref_pic_set_prediction_flag { + // delta_idx_minus1 is only signalled when the RPS being + // constructed is the slice-header in-line RPS, i.e. + // stRpsIdx == num_short_term_ref_pic_sets. For SPS-resident + // entries the value is inferred to 0 per §7.4.8. + let delta_idx_minus1 = if st_rps_idx == num_short_term_ref_pic_sets { + br.ue()? + } else { + 0 + }; + if delta_idx_minus1 >= st_rps_idx { + return Err(SpsError::ValueOutOfRange { + field: "delta_idx_minus1", + got: delta_idx_minus1, + }); + } + let delta_rps_sign = br.u1()? != 0; + let abs_delta_rps_minus1 = br.ue()?; + if abs_delta_rps_minus1 > (1 << 15) - 1 { + return Err(SpsError::ValueOutOfRange { + field: "abs_delta_rps_minus1", + got: abs_delta_rps_minus1, + }); + } + // RefRpsIdx = stRpsIdx − (delta_idx_minus1 + 1) + let ref_rps_idx = (st_rps_idx as i64) - (delta_idx_minus1 as i64 + 1); + let ref_rps = if ref_rps_idx >= 0 && (ref_rps_idx as usize) < all_rps.len() { + Some(&all_rps[ref_rps_idx as usize]) + } else { + // For SPS entries we expect ref_rps_idx in-range; the + // only legal use of an out-of-range RefRpsIdx is when + // st_rps_idx == num_short_term_ref_pic_sets, which is + // the slice-header in-line case (handled elsewhere). + prev + }; + let num_delta_pocs = ref_rps.map(|r| r.num_delta_pocs()).unwrap_or(0); + let entries = num_delta_pocs as usize + 1; + let mut used_by_curr_pic_flag = Vec::with_capacity(entries); + let mut use_delta_flag = Vec::with_capacity(entries); + for _ in 0..entries { + let used = br.u1()? != 0; + used_by_curr_pic_flag.push(used); + if !used { + let ud = br.u1()? != 0; + use_delta_flag.push(ud); + } else { + // Per §7.4.8: when used_by_curr_pic_flag[j] is 1, + // use_delta_flag[j] is inferred to be 1. + use_delta_flag.push(true); + } + } + Ok(Self { + inter_ref_pic_set_prediction_flag, + delta_idx_minus1, + delta_rps_sign, + abs_delta_rps_minus1, + used_by_curr_pic_flag, + use_delta_flag, + num_negative_pics: 0, + num_positive_pics: 0, + delta_poc_s0_minus1: Vec::new(), + used_by_curr_pic_s0_flag: Vec::new(), + delta_poc_s1_minus1: Vec::new(), + used_by_curr_pic_s1_flag: Vec::new(), + }) + } else { + let num_negative_pics = br.ue()?; + if num_negative_pics > HEVC_MAX_RPS_PICS as u32 { + return Err(SpsError::ValueOutOfRange { + field: "num_negative_pics", + got: num_negative_pics, + }); + } + let num_positive_pics = br.ue()?; + if num_positive_pics > HEVC_MAX_RPS_PICS as u32 { + return Err(SpsError::ValueOutOfRange { + field: "num_positive_pics", + got: num_positive_pics, + }); + } + let mut delta_poc_s0_minus1 = Vec::with_capacity(num_negative_pics as usize); + let mut used_by_curr_pic_s0_flag = Vec::with_capacity(num_negative_pics as usize); + for _ in 0..num_negative_pics { + let dp = br.ue()?; + if dp > (1 << 15) - 1 { + return Err(SpsError::ValueOutOfRange { + field: "delta_poc_s0_minus1", + got: dp, + }); + } + delta_poc_s0_minus1.push(dp); + used_by_curr_pic_s0_flag.push(br.u1()? != 0); + } + let mut delta_poc_s1_minus1 = Vec::with_capacity(num_positive_pics as usize); + let mut used_by_curr_pic_s1_flag = Vec::with_capacity(num_positive_pics as usize); + for _ in 0..num_positive_pics { + let dp = br.ue()?; + if dp > (1 << 15) - 1 { + return Err(SpsError::ValueOutOfRange { + field: "delta_poc_s1_minus1", + got: dp, + }); + } + delta_poc_s1_minus1.push(dp); + used_by_curr_pic_s1_flag.push(br.u1()? != 0); + } + Ok(Self { + inter_ref_pic_set_prediction_flag, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: Vec::new(), + use_delta_flag: Vec::new(), + num_negative_pics, + num_positive_pics, + delta_poc_s0_minus1, + used_by_curr_pic_s0_flag, + delta_poc_s1_minus1, + used_by_curr_pic_s1_flag, + }) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::nal::{collect_nal_units, strip_emulation_prevention}; + + /// Helper: convert a bit string (any non-`0`/`1` characters are + /// ignored, useful for visual spacing) into a packed MSB-first + /// byte vector with zero-padding up to the next byte boundary. + fn bits_to_bytes(s: &str) -> Vec { + let mut bits: Vec = Vec::new(); + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut out = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + out.push(b); + } + out + } + + /// Header bits through the per-sub-layer ordering triple, with the + /// `pic_width_in_luma_samples` / `pic_height_in_luma_samples` + /// `ue(v)` bit strings supplied by the caller (the fixture default + /// is 16 × 16 → `000010001` each). Everything else is fixed: + /// `vps_id=0, max_sub_layers_minus1=0, nesting=1, a §7.3.3 PTL + /// walk (profile_idc=1, level=30), sps_id=0, chroma_format_idc=1, + /// conf_win=0, bit_depths=0, log2_max_poc_lsb_minus4=4, + /// ordering_info present with single triple {0,0,0}`. + fn synthesised_header_through_ordering(width_ue: &str, height_ue: &str) -> String { + let mut s = String::new(); + s += "0000"; // vps_id + s += "000"; // max_sub_layers_minus1 + s += "1"; // nesting flag + // profile_tier_level(1, 0) + s += "00"; // profile_space + s += "0"; // tier + s += "00001"; // profile_idc + for _ in 0..32 { + s += "0"; + } + s += "0000"; + for _ in 0..43 { + s += "0"; + } + s += "0"; + s += "00011110"; // level=30 + // sps_id ue(v)=0 + s += "1"; + // chroma_format_idc ue(v)=1 → '010' + s += "010"; + // width ue(v) + s += width_ue; + // height ue(v) + s += height_ue; + // conf_win = 0 + s += "0"; + // bd_luma=0, bd_chroma=0 + s += "1"; + s += "1"; + // log2_max_poc_lsb_minus4 = 4 → '00101' + s += "00101"; + // ordering present = 1, single triple {0,0,0} + s += "1"; + s += "1"; + s += "1"; + s += "1"; + s + } + + /// Prefix of bits that get every SPS hand-assembled fixture through + /// the structural header up to (but not including) the round-4 tail. + /// `chroma_format_idc=1, width=16, height=16, conf_win=0, bit_depths=0, + /// log2_max_poc_lsb_minus4=4, max_sub_layers_minus1=0, ordering_info + /// present with single triple {dpb=0, reorder=0, latency=0}, + /// log2_min_cb=0, log2_diff=1, log2_min_tb=0, log2_diff_tb=2, + /// max_transform_depth_*=0, scaling_list=0, amp=0, sao=1`. + /// + /// This is the EXACT same prefix the round-3 tests used; the round-4 + /// tail tests then concatenate the tail bits they want to exercise. + fn synthesised_prefix_bits() -> String { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + // log2_min_cb_minus3 = 0 + s += "1"; + // log2_diff = 1 → '010' + s += "010"; + // log2_min_tb_minus2 = 0 + s += "1"; + // log2_diff_tb = 2 → '011' + s += "011"; + // max_transform_depth_{inter,intra} = 0 + s += "1"; + s += "1"; + // scaling_list_enabled = 0 + s += "0"; + // amp_enabled = 0 + s += "0"; + // sao_enabled = 1 + s += "1"; + s + } + + /// SPS RBSP body extracted from + /// `docs/video/h265/fixtures/tiny-i-only-16x16-main/input.hevc`, + /// after the Annex B start code and the two-byte NAL header have + /// been removed and emulation-prevention bytes stripped. The wire + /// SPS (NAL idx 1, type 33) was 38 bytes including the two-byte + /// header; after §7.4.1.1 strip (3 escape bytes removed) the body + /// is 32 bytes. + const TINY_SPS_RBSP: &[u8] = &[ + 0x01, 0x04, 0x08, 0x00, 0x00, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x00, 0x00, 0x1E, 0xA0, 0x88, + 0x45, 0x96, 0xEA, 0xAF, 0x2B, 0xC0, 0x5A, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, + 0x32, 0x10, + ]; + + #[test] + fn parses_tiny_fixture_sps() { + let sps = SeqParameterSet::parse(TINY_SPS_RBSP).expect("SPS parse"); + // Trace cross-check (docs/video/h265/fixtures/tiny-i-only-16x16-main/trace.txt): + // SPS sps_id=0 vps_id=0 max_sub_layers=1 profile_idc=4 level_idc=30 + // chroma_format_idc=1 bit_depth=8 bit_depth_chroma=8 + // width=16 height=16 log2_ctb_size=4 log2_min_cb_size=3 + // log2_min_tb_size=2 sao_enabled=1 amp_enabled=0 pcm_enabled=0 + // scaling_list_enabled=0 long_term_ref_pics=0 temporal_mvp=1 + // strong_intra_smoothing=1 + assert_eq!(sps.vps_id, 0); + assert_eq!(sps.max_sub_layers_minus1, 0); // max_sub_layers = 1 + assert!(sps.temporal_id_nesting_flag); + assert_eq!(sps.ptl.general_profile_idc, 4); + assert_eq!(sps.ptl.general_level_idc, 30); + assert_eq!(sps.sps_id, 0); + assert_eq!(sps.chroma_format_idc, 1); + assert!(!sps.separate_colour_plane_flag); + assert_eq!(sps.pic_width_in_luma_samples, 16); + assert_eq!(sps.pic_height_in_luma_samples, 16); + assert!(!sps.conformance_window_flag); + assert_eq!(sps.conformance_window, ConformanceWindow::default()); + assert_eq!(sps.bit_depth_luma_minus8, 0); + assert_eq!(sps.bit_depth_chroma_minus8, 0); + assert_eq!(sps.bit_depth_luma(), 8); + assert_eq!(sps.bit_depth_chroma(), 8); + assert_eq!(sps.log2_max_pic_order_cnt_lsb_minus4, 4); // MaxPicOrderCntLsb = 256 + assert_eq!(sps.max_pic_order_cnt_lsb(), 256); + assert!(sps.sub_layer_ordering_info_present_flag); + assert_eq!( + sps.sub_layer_ordering_info[0].max_dec_pic_buffering_minus1, + 2 + ); + assert_eq!(sps.sub_layer_ordering_info[0].max_num_reorder_pics, 0); + assert_eq!(sps.sub_layer_ordering_info[0].max_latency_increase_plus1, 1); + assert_eq!(sps.log2_min_cb_size(), 3); // 8x8 minimum CU + assert_eq!(sps.log2_ctb_size(), 4); // 16x16 CTU + assert_eq!(sps.log2_min_tb_size(), 2); // 4x4 minimum TU + assert_eq!(sps.max_transform_hierarchy_depth_inter, 0); + assert_eq!(sps.max_transform_hierarchy_depth_intra, 0); + assert!(!sps.scaling_list_enabled_flag); + assert!(!sps.amp_enabled_flag); + assert!(sps.sample_adaptive_offset_enabled_flag); + // Round-4 tail. + assert!(!sps.pcm_enabled_flag); + assert!(sps.pcm.is_none()); + assert_eq!(sps.num_short_term_ref_pic_sets, 0); + assert!(sps.short_term_ref_pic_sets.is_empty()); + assert!(!sps.long_term_ref_pics_present_flag); + assert_eq!(sps.num_long_term_ref_pics_sps, 0); + assert!(sps.long_term_ref_pics.is_empty()); + assert!(sps.sps_temporal_mvp_enabled_flag); + assert!(sps.strong_intra_smoothing_enabled_flag); + // The fixture's x265 CLI encode signals a §E.2.1 VUI body. It + // decodes to a square (1:1) sample aspect ratio, an + // unspecified-but-present video_signal_type, and a timing-info + // block of vui_num_units_in_tick = 1 / vui_time_scale = 25 + // (25 fps) with neither HRD nor bitstream restriction. After + // the VUI the SPS ends cleanly: sps_extension_present_flag == 0 + // and only the rbsp_trailing_bits() remain, so no opaque tail + // is captured. + assert!(sps.vui_parameters_present_flag); + let vui = sps.vui_parameters.as_ref().expect("VUI body"); + assert!(vui.aspect_ratio_info_present_flag); + assert_eq!(vui.aspect_ratio_idc, 1); // 1:1 square + assert!(vui.sar_width.is_none()); + assert!(!vui.overscan_info_present_flag); + assert!(vui.video_signal_type_present_flag); + let vst = vui.video_signal_type.as_ref().expect("video signal type"); + assert_eq!(vst.video_format, 5); // unspecified + assert!(!vst.video_full_range_flag); + assert!(vst.colour_description.is_none()); + assert!(!vui.chroma_loc_info_present_flag); + assert!(!vui.neutral_chroma_indication_flag); + assert!(!vui.field_seq_flag); + assert!(!vui.frame_field_info_present_flag); + assert!(!vui.default_display_window_flag); + assert!(vui.vui_timing_info_present_flag); + let ti = vui.timing_info.as_ref().expect("timing info"); + assert_eq!(ti.num_units_in_tick, 1); + assert_eq!(ti.time_scale, 25); + assert!(!ti.poc_proportional_to_timing_flag); + assert!(!ti.hrd_parameters_present_flag); + assert!(!vui.bitstream_restriction_flag); + // No extension, no opaque tail. + assert!(!sps.sps_extension_present_flag); + assert!(sps.opaque_tail.is_none()); + } + + /// End-to-end: pull the SPS NAL out of the raw Annex B stream + /// through the walker, then parse it. The fixture's full byte + /// sequence is captured inline so the test does not depend on the + /// `docs/` tree at run time. + #[test] + fn parses_tiny_fixture_sps_via_nal_walker() { + // VPS NAL + SPS NAL only — the rest of the fixture (PPS / SEI + // / slice) is unrelated to this test. + let raw = &[ + // VPS: 00 00 00 01 40 01 ... + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0C, 0x01, 0xFF, 0xFF, 0x04, 0x08, 0x00, 0x00, + 0x03, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1E, 0xBA, 0x02, 0x40, + // SPS: 00 00 00 01 42 01 ... + 0x00, 0x00, 0x00, 0x01, 0x42, 0x01, 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9F, + 0xA8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1E, 0xA0, 0x88, 0x45, 0x96, 0xEA, 0xAF, 0x2B, + 0xC0, 0x5A, 0x02, 0x00, 0x00, 0x03, 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x32, 0x10, + ]; + let units = collect_nal_units(raw).expect("walker"); + assert_eq!(units.len(), 2); + assert_eq!(units[1].header.nal_unit_type, 33); // SPS_NUT + let sps = SeqParameterSet::parse(&units[1].rbsp).expect("SPS parse"); + assert_eq!(sps.sps_id, 0); + assert_eq!(sps.chroma_format_idc, 1); + assert_eq!(sps.pic_width_in_luma_samples, 16); + assert_eq!(sps.pic_height_in_luma_samples, 16); + assert_eq!(sps.log2_ctb_size(), 4); + assert!(sps.sample_adaptive_offset_enabled_flag); + assert!(!sps.pcm_enabled_flag); + assert_eq!(sps.num_short_term_ref_pic_sets, 0); + assert!(!sps.long_term_ref_pics_present_flag); + assert!(sps.sps_temporal_mvp_enabled_flag); + assert!(sps.strong_intra_smoothing_enabled_flag); + assert!(sps.vui_parameters_present_flag); + } + + #[test] + fn strip_emulation_prevention_then_parse_matches_inline_decode() { + // The wire SPS body (post NAL header, with the 3 emulation- + // prevention escapes left in) must, after a §7.4.1.1 strip, + // match TINY_SPS_RBSP exactly. + let wire = &[ + 0x01, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x03, 0x00, 0x00, + 0x1E, 0xA0, 0x88, 0x45, 0x96, 0xEA, 0xAF, 0x2B, 0xC0, 0x5A, 0x02, 0x00, 0x00, 0x03, + 0x00, 0x02, 0x00, 0x00, 0x03, 0x00, 0x32, 0x10, + ]; + let unesc = strip_emulation_prevention(wire); + assert_eq!(unesc, TINY_SPS_RBSP); + let a = SeqParameterSet::parse(&unesc).expect("SPS parse"); + let b = SeqParameterSet::parse(TINY_SPS_RBSP).expect("SPS parse"); + assert_eq!(a, b); + } + + #[test] + fn rejects_truncated_rbsp() { + // Cut the buffer just past the leading `vps_id / max_sub / + // nesting` byte — well before profile_tier_level finishes. + let err = SeqParameterSet::parse(&TINY_SPS_RBSP[..3]).unwrap_err(); + assert_eq!(err, SpsError::Truncated); + } + + /// Hand-assembled SPS exercising the `chroma_format_idc == 3` + /// path (so `separate_colour_plane_flag` is signalled) plus the + /// `conformance_window_flag == 1` four-`ue(v)` block. The remaining + /// fields are kept at minimal values to make the bit string + /// hand-traceable. + #[test] + fn parses_444_with_conformance_window() { + let mut s = String::new(); + s += "0000"; // vps_id + s += "000"; // max_sub_layers_minus1 + s += "1"; // nesting + // PTL(1,0) + s += "00"; + s += "0"; + s += "00001"; + for _ in 0..32 { + s += "0"; + } + s += "0000"; + for _ in 0..43 { + s += "0"; + } + s += "0"; + s += "00011110"; + // sps_id=0 + s += "1"; + // chroma_format_idc=3 → '00100' + s += "00100"; + // separate_colour_plane_flag=1 + s += "1"; + // width=16, height=16 + s += "000010001"; + s += "000010001"; + // conf_win=1, four ue(v)=0 + s += "1"; + s += "1"; + s += "1"; + s += "1"; + s += "1"; + // bd_luma=2 → '011' + s += "011"; + s += "011"; + // log2_max_poc_lsb_minus4=4 + s += "00101"; + // ordering present, single triple of zeros + s += "1"; + s += "1"; + s += "1"; + s += "1"; + // log2_min_cb=0 + s += "1"; + // log2_diff=1 + s += "010"; + s += "1"; + s += "011"; + s += "1"; + s += "1"; + // scaling=0 + s += "0"; + // amp=1 + s += "1"; + // sao=1 + s += "1"; + // pcm_enabled=0 + s += "0"; + // num_short_term_ref_pic_sets=0 + s += "1"; + // long_term_ref_pics_present=0 + s += "0"; + // temporal_mvp=1 + s += "1"; + // strong_intra_smoothing=0 + s += "0"; + // vui=0 + s += "0"; + // sps_extension_present=0 + s += "0"; + // rbsp trailing bits (stop bit then zero pad) + s += "1"; + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert_eq!(sps.chroma_format_idc, 3); + assert!(sps.separate_colour_plane_flag); + assert_eq!(sps.bit_depth_luma(), 10); + assert!(sps.amp_enabled_flag); + assert!(sps.sample_adaptive_offset_enabled_flag); + assert!(!sps.pcm_enabled_flag); + assert_eq!(sps.num_short_term_ref_pic_sets, 0); + assert!(!sps.long_term_ref_pics_present_flag); + assert!(sps.sps_temporal_mvp_enabled_flag); + assert!(!sps.strong_intra_smoothing_enabled_flag); + assert!(!sps.vui_parameters_present_flag); + assert!(!sps.sps_extension_present_flag); + assert!(sps.opaque_tail.is_none()); + } + + /// Hand-assembled SPS with two sub-layers and the ordering-info + /// present flag set to 0 — the [0] sub-layer must inherit the + /// [1] triple per §7.4.3.2.1. + #[test] + fn ordering_info_present_flag_zero_propagates() { + let mut s = String::new(); + s += "0000"; // vps_id + s += "001"; // max_sub_layers_minus1 = 1 + s += "1"; + // PTL(1, 1): + s += "00"; + s += "0"; + s += "00001"; + for _ in 0..32 { + s += "0"; + } + s += "0000"; + for _ in 0..43 { + s += "0"; + } + s += "0"; + s += "00011110"; // level=30 + // sub_layer_profile_present[0]/level_present[0] = 0,0 + s += "00"; + for _ in 0..14 { + s += "0"; + } + // sps_id=0 + s += "1"; + // chroma=1 + s += "010"; + // width=16, height=16 + s += "000010001"; + s += "000010001"; + // conf_win=0 + s += "0"; + // bd_luma=0 + s += "1"; + // bd_chroma=0 + s += "1"; + // log2_max_poc_lsb_minus4=4 + s += "00101"; + // sub_layer_ordering_info_present_flag = 0 + s += "0"; + // single triple at i=max_sub_layers_minus1 (=1): dpb=2 ('011'), reorder=0 ('1'), latency=0 ('1') + s += "011"; + s += "1"; + s += "1"; + s += "1"; + s += "010"; + s += "1"; + s += "011"; + s += "1"; + s += "1"; + s += "0"; + s += "0"; + s += "1"; + // pcm_enabled=0 + s += "0"; + // num_short_term_ref_pic_sets=0 + s += "1"; + // long_term=0 + s += "0"; + // temporal_mvp=1 + s += "1"; + // strong_intra_smoothing=1 + s += "1"; + // vui=0 + s += "0"; + // sps_extension_present=0 + s += "0"; + // stop bit + s += "1"; + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(!sps.sub_layer_ordering_info_present_flag); + assert_eq!(sps.max_sub_layers_minus1, 1); + assert_eq!( + sps.sub_layer_ordering_info[1].max_dec_pic_buffering_minus1, + 2 + ); + // [0] inherited from [1] + assert_eq!( + sps.sub_layer_ordering_info[0].max_dec_pic_buffering_minus1, + 2 + ); + assert!(sps.strong_intra_smoothing_enabled_flag); + } + + /// SPS prefix bits identical to `synthesised_prefix_bits()` but + /// stopping just *before* `scaling_list_enabled_flag` (i.e. after + /// `max_transform_hierarchy_depth_intra`). Round 8 scaling-list + /// tests append their own scaling_list block + the amp/sao bits + + /// the SPS tail. + fn synthesised_prefix_before_scaling_list() -> String { + let mut s = String::new(); + s += "0000"; // vps_id + s += "000"; // max_sub_layers_minus1 + s += "1"; // nesting flag + s += "00"; // profile_space + s += "0"; // tier + s += "00001"; // profile_idc + for _ in 0..32 { + s += "0"; + } + s += "0000"; + for _ in 0..43 { + s += "0"; + } + s += "0"; + s += "00011110"; // level=30 + s += "1"; // sps_id=0 + s += "010"; // chroma_format_idc=1 + s += "000010001"; // width=16 + s += "000010001"; // height=16 + s += "0"; // conf_win=0 + s += "1"; // bd_luma=0 + s += "1"; // bd_chroma=0 + s += "00101"; // log2_max_poc_lsb_minus4=4 + s += "1"; // ordering present=1 + s += "1"; // dpb=0 + s += "1"; // reorder=0 + s += "1"; // latency=0 + s += "1"; // log2_min_cb_minus3=0 + s += "010"; // log2_diff=1 + s += "1"; // log2_min_tb_minus2=0 + s += "011"; // log2_diff_tb=2 + s += "1"; // max_transform_depth_inter=0 + s += "1"; // max_transform_depth_intra=0 + s + } + + /// SPS tail bits from `amp_enabled` through the stop bit, matching + /// the round-4 minimal tail (sao=1, pcm=0, num_short_term_rps=0, + /// long_term=0, temporal_mvp=1, strong_intra_smoothing=1, vui=0, + /// extension=0, stop=1). + fn synthesised_tail_after_scaling_list() -> String { + let mut s = String::new(); + s += "0"; // amp_enabled=0 + s += "1"; // sao_enabled=1 + s += "0"; // pcm_enabled=0 + s += "1"; // num_short_term_ref_pic_sets ue=0 + s += "0"; // long_term_ref_pics=0 + s += "1"; // temporal_mvp=1 + s += "1"; // strong_intra_smoothing=1 + s += "0"; // vui=0 + s += "0"; // sps_extension_present=0 + s += "1"; // stop bit + s + } + + /// `scaling_list_enabled_flag == 1` with + /// `sps_scaling_list_data_present_flag == 0`: per §7.4.5 the + /// default scaling lists apply and the SPS parses end to end with + /// no explicit [`ScalingListData`]. + #[test] + fn scaling_list_enabled_default_lists() { + let mut s = synthesised_prefix_before_scaling_list(); + s += "1"; // scaling_list_enabled = 1 + s += "0"; // sps_scaling_list_data_present_flag = 0 + s += &synthesised_tail_after_scaling_list(); + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.scaling_list_enabled_flag); + assert!(!sps.sps_scaling_list_data_present_flag); + assert!(sps.scaling_list_data.is_none()); + } + + /// `scaling_list_enabled_flag == 1` with + /// `sps_scaling_list_data_present_flag == 1`: the SPS carries an + /// explicit `scaling_list_data()` (§7.3.4). Here every one of the + /// 24 slots signals pred_mode=0, delta=0 (use the default list), so + /// the parsed lists equal the §7.4.5 default tables. + #[test] + fn scaling_list_enabled_explicit_all_default() { + let mut s = synthesised_prefix_before_scaling_list(); + s += "1"; // scaling_list_enabled = 1 + s += "1"; // sps_scaling_list_data_present_flag = 1 + // scaling_list_data(): 24 slots, each pred_mode=0 + // ('0') + scaling_list_pred_matrix_id_delta ue=0 ('1'). + // sizeId 0/1/2 each 6 slots; sizeId 3 only 2 slots. + for size_id in 0..4 { + let step = if size_id == 3 { 3 } else { 1 }; + let mut m = 0; + while m < 6 { + s += "0"; // scaling_list_pred_mode_flag = 0 + s += "1"; // scaling_list_pred_matrix_id_delta ue = 0 + m += step; + } + } + s += &synthesised_tail_after_scaling_list(); + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.scaling_list_enabled_flag); + assert!(sps.sps_scaling_list_data_present_flag); + let data = sps.scaling_list_data.expect("scaling_list_data present"); + // 4x4 default = all 16. + assert_eq!(data.lists[0][0].coef, vec![16u16; 16]); + // 8x8 inter default for matrixId 3. + assert_eq!(data.lists[1][3].coef[63], 91); + } + + /// `chroma_format_idc` is u-Exp-Golomb so on-wire codeNum 4 would + /// decode to a value of 4 — outside the legal 0..=3 range. The + /// parser must reject it. + #[test] + fn rejects_chroma_format_idc_out_of_range() { + let mut s = String::new(); + s += "0000"; + s += "000"; + s += "1"; + s += "00"; + s += "0"; + s += "00001"; + for _ in 0..32 { + s += "0"; + } + s += "0000"; + for _ in 0..43 { + s += "0"; + } + s += "0"; + s += "00011110"; + // sps_id=0 + s += "1"; + // chroma_format_idc ue=4 → '00101' + s += "00101"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "chroma_format_idc", + got: 4 + } + ); + } + + /// Fuzz regression (r282 `parse_annexb`): an SPS whose + /// coding-block-size pair drives `CtbLog2SizeY` (§7.4.3.2.1 + /// eqs. 7-10 / 7-11) past the Annex A profile bound of 4..=6 + /// previously survived the parse and panicked downstream in every + /// `CtbSizeY = 1 << CtbLog2SizeY` (eq. 7-13) re-derivation. + #[test] + fn rejects_ctb_log2_size_above_6() { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + // log2_min_luma_coding_block_size_minus3 = 0 → MinCbLog2SizeY = 3 + s += "1"; + // log2_diff_max_min_luma_coding_block_size ue = 4 → CtbLog2SizeY = 7 + s += "00101"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "CtbLog2SizeY", + got: 7 + } + ); + } + + /// Annex A also bounds `CtbLog2SizeY` from below (4): a + /// 8×8-CTB SPS must be rejected. + #[test] + fn rejects_ctb_log2_size_below_4() { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + // log2_min_cb_minus3 = 0, log2_diff = 0 → CtbLog2SizeY = 3 + s += "1"; + s += "1"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "CtbLog2SizeY", + got: 3 + } + ); + } + + /// §7.4.3.2.1: "The CVS shall not contain data that result in + /// MinTbLog2SizeY greater than or equal to MinCbLog2SizeY". + #[test] + fn rejects_min_tb_log2_size_reaching_min_cb() { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + s += "1"; // MinCbLog2SizeY = 3 + s += "010"; // CtbLog2SizeY = 4 + s += "010"; // log2_min_tb_minus2 = 1 → MinTbLog2SizeY = 3 == MinCb + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "log2_min_luma_transform_block_size_minus2", + got: 1 + } + ); + } + + /// §7.4.3.2.1: "The CVS shall not contain data that result in + /// MaxTbLog2SizeY greater than Min( CtbLog2SizeY, 5 )". + #[test] + fn rejects_max_tb_log2_size_above_cap() { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + s += "1"; // MinCbLog2SizeY = 3 + s += "010"; // CtbLog2SizeY = 4 → cap = Min(4, 5) = 4 + s += "1"; // MinTbLog2SizeY = 2 + s += "00100"; // log2_diff_tb = 3 → MaxTbLog2SizeY = 5 > 4 + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "log2_diff_max_min_luma_transform_block_size", + got: 3 + } + ); + } + + /// §7.4.3.2.1: both hierarchy depths "shall be in the range of 0 + /// to CtbLog2SizeY − MinTbLog2SizeY, inclusive" (= 2 here). + #[test] + fn rejects_transform_hierarchy_depth_above_cap() { + let mut s = synthesised_header_through_ordering("000010001", "000010001"); + s += "1"; // MinCbLog2SizeY = 3 + s += "010"; // CtbLog2SizeY = 4 + s += "1"; // MinTbLog2SizeY = 2 + s += "011"; // log2_diff_tb = 2 → MaxTbLog2SizeY = 4 (legal) + s += "00100"; // max_transform_hierarchy_depth_inter = 3 > 2 + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "max_transform_hierarchy_depth_inter", + got: 3 + } + ); + } + + /// §A.4.1 item b): `pic_width_in_luma_samples` ≤ + /// `Sqrt( MaxLumaPs * 8 )` = 33 776 at the largest Table A.8 + /// level. An unbounded width previously let the + /// PicWidthInCtbsY × PicHeightInCtbsY product (eq. 7-19 territory) + /// overflow u32 downstream. + #[test] + fn rejects_oversized_pic_width() { + // ue(33 777): codeNum + 1 = 33 778 needs 16 bits → 15-zero + // prefix followed by the 16-bit value. + let code: u32 = 33_778; + let len = 32 - code.leading_zeros(); + let mut ue = "0".repeat(len as usize - 1); + for i in (0..len).rev() { + ue.push(if (code >> i) & 1 == 1 { '1' } else { '0' }); + } + let s = synthesised_header_through_ordering(&ue, "000010001"); + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "pic_width_in_luma_samples", + got: 33_777 + } + ); + } + + /// Hand-assembled SPS exercising the `pcm_enabled_flag == 1` + /// branch (§7.3.2.2 PCM block). + #[test] + fn parses_pcm_enabled() { + let mut s = synthesised_prefix_bits(); + // pcm_enabled_flag = 1 + s += "1"; + // pcm_sample_bit_depth_luma_minus1 = 7 (PcmBitDepthY = 8) + s += "0111"; + // pcm_sample_bit_depth_chroma_minus1 = 7 + s += "0111"; + // log2_min_pcm_luma_coding_block_size_minus3 = 0 → '1' + s += "1"; + // log2_diff_max_min_pcm_luma_coding_block_size = 0 → '1' + s += "1"; + // pcm_loop_filter_disabled_flag = 1 + s += "1"; + // num_short_term_ref_pic_sets = 0 + s += "1"; + // long_term_ref_pics_present_flag = 0 + s += "0"; + // sps_temporal_mvp_enabled_flag = 1 + s += "1"; + // strong_intra_smoothing_enabled_flag = 1 + s += "1"; + // vui_parameters_present_flag = 0 + s += "0"; + // sps_extension_present_flag = 0 + s += "0"; + // stop bit + s += "1"; + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.pcm_enabled_flag); + let pcm = sps.pcm.expect("pcm block"); + assert_eq!(pcm.bit_depth_luma_minus1, 7); + assert_eq!(pcm.bit_depth_chroma_minus1, 7); + assert_eq!(pcm.log2_min_pcm_luma_coding_block_size_minus3, 0); + assert_eq!(pcm.log2_diff_max_min_pcm_luma_coding_block_size, 0); + assert!(pcm.loop_filter_disabled_flag); + assert!(sps.sps_temporal_mvp_enabled_flag); + assert!(sps.strong_intra_smoothing_enabled_flag); + } + + /// PCM bit depth above luma bit depth must be rejected per + /// §7.4.3.2 / equation (7-25). + #[test] + fn rejects_pcm_bit_depth_exceeding_luma() { + let mut s = synthesised_prefix_bits(); + s += "1"; // pcm_enabled_flag + // pcm_sample_bit_depth_luma_minus1 = 15 (PcmBitDepthY = 16) + // BitDepthY in the synthesised prefix is 8. + s += "1111"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert_eq!( + err, + SpsError::ValueOutOfRange { + field: "pcm_sample_bit_depth_luma_minus1", + got: 15 + } + ); + } + + /// Hand-assembled SPS with one explicit short-term RPS (no + /// inter-RPS-prediction): 1 negative pic, 0 positive pics. + #[test] + fn parses_one_short_term_rps_explicit() { + let mut s = synthesised_prefix_bits(); + // pcm_enabled_flag = 0 + s += "0"; + // num_short_term_ref_pic_sets = 1 → ue(v) codeNum 1 → '010' + s += "010"; + // st_ref_pic_set(0): inter_ref_pic_set_prediction_flag is NOT + // signalled (st_rps_idx == 0); implicit 0. + // num_negative_pics = 1 → '010' + s += "010"; + // num_positive_pics = 0 → '1' + s += "1"; + // delta_poc_s0_minus1[0] = 0 → '1' + s += "1"; + // used_by_curr_pic_s0_flag[0] = 1 + s += "1"; + // long_term_ref_pics_present_flag = 0 + s += "0"; + // sps_temporal_mvp_enabled_flag = 1 + s += "1"; + // strong_intra_smoothing_enabled_flag = 0 + s += "0"; + // vui_parameters_present_flag = 0 + s += "0"; + // sps_extension_present_flag = 0 + s += "0"; + s += "1"; // stop bit + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert_eq!(sps.num_short_term_ref_pic_sets, 1); + let rps = &sps.short_term_ref_pic_sets[0]; + assert!(!rps.inter_ref_pic_set_prediction_flag); + assert_eq!(rps.num_negative_pics, 1); + assert_eq!(rps.num_positive_pics, 0); + assert_eq!(rps.delta_poc_s0_minus1, vec![0]); + assert_eq!(rps.used_by_curr_pic_s0_flag, vec![true]); + assert!(rps.delta_poc_s1_minus1.is_empty()); + assert_eq!(rps.num_delta_pocs(), 1); + } + + /// Hand-assembled SPS with two short-term RPSes, the second one + /// using inter-RPS-prediction relative to the first. Exercises + /// the `for( j = 0; j <= NumDeltaPocs[RefRpsIdx]; j++ )` loop in + /// §7.3.7 with the `use_delta_flag` inference of §7.4.8. + #[test] + fn parses_inter_rps_prediction() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm_enabled_flag + // num_short_term_ref_pic_sets = 2 → codeNum 2 → '011' + s += "011"; + // st_ref_pic_set(0): explicit, num_negative_pics=1, num_positive=0, + // delta_poc_s0_minus1[0]=0, used_by_curr_pic_s0_flag[0]=1 + s += "010"; // num_neg=1 + s += "1"; // num_pos=0 + s += "1"; // dp0=0 + s += "1"; // used=1 + // st_ref_pic_set(1): inter_ref_pic_set_prediction_flag = 1 + s += "1"; + // delta_idx_minus1 is NOT signalled (st_rps_idx=1, num=2; only + // signalled when st_rps_idx == num). Inferred to 0 → + // RefRpsIdx = 1 - (0+1) = 0. + // delta_rps_sign = 0 + s += "0"; + // abs_delta_rps_minus1 = 0 → codeNum 0 → '1' + s += "1"; + // NumDeltaPocs[0] = 1, so loop runs j=0..1 (2 entries): + // j=0: used_by_curr_pic_flag = 1 → use_delta_flag inferred 1 + s += "1"; + // j=1: used_by_curr_pic_flag = 0, use_delta_flag = 1 + s += "0"; + s += "1"; + // long_term=0, temporal_mvp=1, strong_intra_smoothing=1, vui=0, ext=0, stop + s += "0"; + s += "1"; + s += "1"; + s += "0"; + s += "0"; + s += "1"; + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert_eq!(sps.num_short_term_ref_pic_sets, 2); + let r1 = &sps.short_term_ref_pic_sets[1]; + assert!(r1.inter_ref_pic_set_prediction_flag); + assert_eq!(r1.delta_idx_minus1, 0); + assert!(!r1.delta_rps_sign); + assert_eq!(r1.abs_delta_rps_minus1, 0); + assert_eq!(r1.used_by_curr_pic_flag, vec![true, false]); + assert_eq!(r1.use_delta_flag, vec![true, true]); + } + + /// Hand-assembled SPS exercising the long-term-ref-pic block. + #[test] + fn parses_long_term_ref_pics() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm_enabled_flag = 0 + s += "1"; // num_short_term_ref_pic_sets = 0 + s += "1"; // long_term_ref_pics_present_flag = 1 + // num_long_term_ref_pics_sps = 2 → codeNum 2 → '011' + s += "011"; + // log2_max_pic_order_cnt_lsb_minus4 = 4 in the synthesised + // prefix, so lt_ref_pic_poc_lsb_sps[i] is 8 bits wide. + // i=0: poc_lsb = 0x10, used_by_curr_pic_lt_sps_flag = 1 + s += "00010000"; + s += "1"; + // i=1: poc_lsb = 0x20, used = 0 + s += "00100000"; + s += "0"; + // temporal_mvp=1, strong_intra=0, vui=0, ext=0, stop + s += "1"; + s += "0"; + s += "0"; + s += "0"; + s += "1"; + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.long_term_ref_pics_present_flag); + assert_eq!(sps.num_long_term_ref_pics_sps, 2); + assert_eq!(sps.long_term_ref_pics.len(), 2); + assert_eq!(sps.long_term_ref_pics[0].poc_lsb, 0x10); + assert!(sps.long_term_ref_pics[0].used_by_curr_pic); + assert_eq!(sps.long_term_ref_pics[1].poc_lsb, 0x20); + assert!(!sps.long_term_ref_pics[1].used_by_curr_pic); + } + + /// SPS with `vui_parameters_present_flag == 1`: the parser now + /// decodes the §E.2.1 `vui_parameters()` body in full and + /// continues to `sps_extension_present_flag`. Here the VUI is the + /// minimal all-flags-off body (ten `u(1)` flags), so no opaque + /// tail is captured. + #[test] + fn decodes_vui_then_continues_to_extension_flag() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm_enabled_flag = 0 + s += "1"; // num_short_term_ref_pic_sets = 0 + s += "0"; // long_term = 0 + s += "1"; // temporal_mvp = 1 + s += "1"; // strong_intra_smoothing = 1 + s += "1"; // vui_parameters_present_flag = 1 + // vui_parameters(): ten flags all 0 (minimal body) + s += "0000000000"; + s += "0"; // sps_extension_present_flag = 0 + s += "1"; // rbsp stop bit + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.vui_parameters_present_flag); + let vui = sps.vui_parameters.as_ref().expect("VUI body"); + assert!(!vui.aspect_ratio_info_present_flag); + assert!(!vui.overscan_info_present_flag); + assert!(!vui.video_signal_type_present_flag); + assert!(!vui.chroma_loc_info_present_flag); + assert!(!vui.vui_timing_info_present_flag); + assert!(!vui.bitstream_restriction_flag); + assert!(!sps.sps_extension_present_flag); + assert!(sps.opaque_tail.is_none()); + } + + /// SPS with `vui_parameters_present_flag == 1` whose VUI signals a + /// timing-info block, followed by `sps_extension_present_flag == 1` + /// — the extension body after the (now fully decoded) VUI is + /// surfaced as an opaque tail. + #[test] + fn decodes_vui_then_captures_extension_tail() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm_enabled_flag = 0 + s += "1"; // num_short_term_ref_pic_sets = 0 + s += "0"; // long_term = 0 + s += "1"; // temporal_mvp = 1 + s += "1"; // strong_intra_smoothing = 1 + s += "1"; // vui_parameters_present_flag = 1 + // vui_parameters(): + s += "0"; // aspect_ratio_info_present_flag = 0 + s += "0"; // overscan_info_present_flag = 0 + s += "0"; // video_signal_type_present_flag = 0 + s += "0"; // chroma_loc_info_present_flag = 0 + s += "0"; // neutral_chroma_indication_flag = 0 + s += "0"; // field_seq_flag = 0 + s += "0"; // frame_field_info_present_flag = 0 + s += "0"; // default_display_window_flag = 0 + s += "1"; // vui_timing_info_present_flag = 1 + s += "00000000000000000000000000000001"; // vui_num_units_in_tick = 1 + s += "00000000000000000000000000011001"; // vui_time_scale = 25 + s += "0"; // vui_poc_proportional_to_timing_flag = 0 + s += "0"; // vui_hrd_parameters_present_flag = 0 + s += "0"; // bitstream_restriction_flag = 0 + // sps_extension_present_flag = 1, followed by the + // typed extension flag block. Set the range-extension + // flag so the nine `sps_range_extension()` flags are + // decoded; with no further body, no opaque tail follows. + s += "1"; // sps_extension_present_flag + s += "1"; // sps_range_extension_flag = 1 + s += "000"; // sps_multilayer / sps_3d / sps_scc = 0 + s += "0000"; // sps_extension_4bits = 0 + s += "101010101"; // sps_range_extension() nine flags + s += "1"; // rbsp_trailing_bits stop bit + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let vui = sps.vui_parameters.as_ref().expect("VUI body"); + let ti = vui.timing_info.as_ref().expect("timing info"); + assert_eq!(ti.num_units_in_tick, 1); + assert_eq!(ti.time_scale, 25); + assert!(sps.sps_extension_present_flag); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(flags.sps_range_extension_flag); + assert!(!flags.sps_multilayer_extension_flag); + assert!(!flags.sps_3d_extension_flag); + assert!(!flags.sps_scc_extension_flag); + assert_eq!(flags.sps_extension_4bits, 0); + assert!(flags.has_body()); + // The range-extension body is now decoded, not opaque: with no + // multilayer/3d/scc/4bits body after it, no opaque tail remains. + assert!(sps.opaque_tail.is_none()); + let re = sps.sps_range_extension.expect("range extension body"); + assert!(re.transform_skip_rotation_enabled_flag); // 1 + assert!(!re.transform_skip_context_enabled_flag); // 0 + assert!(re.implicit_rdpcm_enabled_flag); // 1 + assert!(!re.explicit_rdpcm_enabled_flag); // 0 + assert!(re.extended_precision_processing_flag); // 1 + assert!(!re.intra_smoothing_disabled_flag); // 0 + assert!(re.high_precision_offsets_enabled_flag); // 1 + assert!(!re.persistent_rice_adaptation_enabled_flag); // 0 + assert!(re.cabac_bypass_alignment_enabled_flag); // 1 + } + + /// `sps_extension_present_flag == 1` with `sps_range_extension_flag + /// == 1` decodes the typed flag block then the nine + /// `sps_range_extension()` flags (§7.3.2.2.2) in bit-stream order. + /// This is the RExt-profile entry point (§A.3.5). + #[test] + fn decodes_sps_range_extension_body() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "1"; // sps_range_extension_flag = 1 + s += "000"; // sps_multilayer / sps_3d / sps_scc = 0 + s += "0000"; // sps_extension_4bits = 0 + // sps_range_extension() nine `u(1)` flags, all set — + // every RExt tool enabled. + s += "111111111"; + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(!sps.vui_parameters_present_flag); + assert!(sps.sps_extension_present_flag); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(flags.sps_range_extension_flag); + assert_eq!(flags.sps_extension_4bits, 0); + // No body after the range extension → no opaque tail. + assert!(sps.opaque_tail.is_none()); + let re = sps.sps_range_extension.expect("range extension body"); + assert!(re.transform_skip_rotation_enabled_flag); + assert!(re.transform_skip_context_enabled_flag); + assert!(re.implicit_rdpcm_enabled_flag); + assert!(re.explicit_rdpcm_enabled_flag); + assert!(re.extended_precision_processing_flag); + assert!(re.intra_smoothing_disabled_flag); + assert!(re.high_precision_offsets_enabled_flag); + assert!(re.persistent_rice_adaptation_enabled_flag); + assert!(re.cabac_bypass_alignment_enabled_flag); + } + + /// `sps_range_extension_flag == 1` followed by `sps_scc_extension_flag + /// == 1` (no multilayer/3D body between them): the nine + /// range-extension flags AND the `sps_scc_extension()` body + /// (§7.3.2.2.3) are both decoded in place — no opaque tail remains. + /// Palette mode disabled, so only the three leading/trailing fields + /// are present. + #[test] + fn decodes_range_extension_then_scc_body_no_palette() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "1"; // sps_range_extension_flag = 1 + s += "00"; // sps_multilayer / sps_3d = 0 + s += "1"; // sps_scc_extension_flag = 1 + s += "0000"; // sps_extension_4bits = 0 + s += "000000000"; // sps_range_extension() nine flags, all 0 + // sps_scc_extension(): + s += "1"; // sps_curr_pic_ref_enabled_flag = 1 + s += "0"; // palette_mode_enabled_flag = 0 (palette block absent) + s += "10"; // motion_vector_resolution_control_idc = 2 (u(2)) + s += "1"; // intra_boundary_filtering_disabled_flag = 1 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(flags.sps_range_extension_flag); + assert!(flags.sps_scc_extension_flag); + let re = sps.sps_range_extension.expect("range extension body"); + assert_eq!(re, SpsRangeExtension::default()); + // Both bodies are decoded in place; nothing is left opaque. + assert!(sps.opaque_tail.is_none()); + let scc = sps.sps_scc_extension.expect("scc extension body"); + assert!(scc.sps_curr_pic_ref_enabled_flag); + assert!(!scc.palette_mode_enabled_flag); + assert_eq!(scc.palette_max_size, 0); + assert_eq!(scc.delta_palette_max_predictor_size, 0); + assert!(!scc.sps_palette_predictor_initializers_present_flag); + assert!(scc.sps_palette_predictor_initializer.is_empty()); + assert_eq!(scc.motion_vector_resolution_control_idc, 2); + assert!(scc.intra_boundary_filtering_disabled_flag); + } + + /// `sps_scc_extension()` with `palette_mode_enabled_flag == 1` and + /// palette predictor initializers present: the `palette_max_size`, + /// `delta_palette_max_predictor_size`, and per-component initializer + /// table (§7.3.2.2.3) are decoded, each `u(v)` sized by `BitDepthY` / + /// `BitDepthC`. `chroma_format_idc == 1` here gives `numComps == 3`. + #[test] + fn decodes_scc_extension_palette_initializers() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0001"; // range/multilayer/3d = 0, scc = 1 + s += "0000"; // sps_extension_4bits = 0 + // sps_scc_extension(): + s += "0"; // sps_curr_pic_ref_enabled_flag = 0 + s += "1"; // palette_mode_enabled_flag = 1 + s += "00100"; // palette_max_size = ue(3) → "00100" + s += "010"; // delta_palette_max_predictor_size = ue(1) → "010" + s += "1"; // sps_palette_predictor_initializers_present_flag = 1 + s += "010"; // sps_num_palette_predictor_initializers_minus1 = ue(1) → 1 + // numComps = 3, num_entries = 2; default BitDepthY/C = 8. + // comp 0 (8-bit): 0x01, 0x02 + s += "00000001"; + s += "00000010"; + // comp 1 (8-bit): 0x03, 0x04 + s += "00000011"; + s += "00000100"; + // comp 2 (8-bit): 0x05, 0x06 + s += "00000101"; + s += "00000110"; + s += "10"; // motion_vector_resolution_control_idc = 2 (u(2)) + s += "0"; // intra_boundary_filtering_disabled_flag = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.opaque_tail.is_none()); + let scc = sps.sps_scc_extension.expect("scc extension body"); + assert!(!scc.sps_curr_pic_ref_enabled_flag); + assert!(scc.palette_mode_enabled_flag); + assert_eq!(scc.palette_max_size, 3); + assert_eq!(scc.delta_palette_max_predictor_size, 1); + // PaletteMaxPredictorSize = 3 + 1 (eq. 7-35). + assert_eq!(scc.palette_max_predictor_size(), 4); + assert!(scc.sps_palette_predictor_initializers_present_flag); + assert_eq!(scc.sps_num_palette_predictor_initializers_minus1, 1); + assert_eq!( + scc.sps_palette_predictor_initializer, + vec![vec![1, 2], vec![3, 4], vec![5, 6]], + ); + assert_eq!(scc.motion_vector_resolution_control_idc, 2); + assert!(!scc.intra_boundary_filtering_disabled_flag); + } + + /// §7.4.3.2.3 / §A.3.7: `sps_num_palette_predictor_initializers_minus1` + /// past the largest representable predictor (PaletteMaxPredictorSize + /// <= 128) is rejected BEFORE any initializer allocation — a fuzzed + /// count once drove a multi-GiB `Vec::with_capacity`. + #[test] + fn rejects_oversized_palette_predictor_initializer_count() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0001"; // range/multilayer/3d = 0, scc = 1 + s += "0000"; // sps_extension_4bits = 0 + // sps_scc_extension(): + s += "0"; // sps_curr_pic_ref_enabled_flag = 0 + s += "1"; // palette_mode_enabled_flag = 1 + s += "00100"; // palette_max_size = 3 + s += "010"; // delta_palette_max_predictor_size = 1 + s += "1"; // sps_palette_predictor_initializers_present_flag = 1 + // sps_num_palette_predictor_initializers_minus1 = ue(128): + // 129 in 8 bits = 10000001, prefix of 7 zeros. + s += "0000000"; + s += "10000001"; + s += "1"; // (whatever follows is unreached) + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).expect_err("oversized initializer count"); + assert!(matches!( + err, + SpsError::ValueOutOfRange { + field: "sps_num_palette_predictor_initializers_minus1", + got: 128 + } + )); + } + + /// §7.4.3.2.3: `motion_vector_resolution_control_idc == 3` is + /// reserved and rejected as out-of-range. + #[test] + fn rejects_reserved_motion_vector_resolution_control_idc() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0001"; // range/multilayer/3d = 0, scc = 1 + s += "0000"; // sps_extension_4bits = 0 + // sps_scc_extension(): + s += "0"; // sps_curr_pic_ref_enabled_flag = 0 + s += "0"; // palette_mode_enabled_flag = 0 + s += "11"; // motion_vector_resolution_control_idc = 3 (reserved) + s += "0"; // intra_boundary_filtering_disabled_flag = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).expect_err("reserved mvr idc"); + assert!(matches!( + err, + SpsError::ValueOutOfRange { + field: "motion_vector_resolution_control_idc", + got: 3 + } + )); + } + + /// §7.4.3.2.3: when `palette_max_size == 0`, a non-zero + /// `delta_palette_max_predictor_size` violates bitstream + /// conformance and is rejected. + #[test] + fn rejects_delta_palette_when_max_size_zero() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0001"; // range/multilayer/3d = 0, scc = 1 + s += "0000"; // sps_extension_4bits = 0 + // sps_scc_extension(): + s += "0"; // sps_curr_pic_ref_enabled_flag = 0 + s += "1"; // palette_mode_enabled_flag = 1 + s += "1"; // palette_max_size = 0 (ue) + s += "010"; // delta_palette_max_predictor_size = 1 (ue) → illegal + s += "0"; // sps_palette_predictor_initializers_present_flag = 0 + s += "00"; // motion_vector_resolution_control_idc = 0 + s += "0"; // intra_boundary_filtering_disabled_flag = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).expect_err("delta vs max_size 0"); + assert!(matches!( + err, + SpsError::ValueOutOfRange { + field: "delta_palette_max_predictor_size", + got: 1 + } + )); + } + + /// `sps_extension_present_flag == 1` with every typed extension + /// flag (and `sps_extension_4bits`) equal to 0 decodes the + /// flag block but consumes only `rbsp_trailing_bits()` afterwards + /// — no opaque tail is surfaced because no extension body follows. + #[test] + fn decodes_extension_flag_block_without_bodies() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0000"; // four typed flags all 0 + s += "0000"; // sps_extension_4bits = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(sps.sps_extension_present_flag); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(!flags.sps_range_extension_flag); + assert!(!flags.sps_multilayer_extension_flag); + assert!(!flags.sps_3d_extension_flag); + assert!(!flags.sps_scc_extension_flag); + assert_eq!(flags.sps_extension_4bits, 0); + assert!(!flags.has_body()); + assert!(sps.opaque_tail.is_none()); + } + + /// `sps_extension_present_flag == 1` with `sps_scc_extension_flag + /// == 1` (and no preceding range/multilayer/3D body) selects the + /// §A.3.7 Screen Content Coding profile family; the typed block + /// decodes cleanly and the `sps_scc_extension()` body (§7.3.2.2.3) + /// is decoded in place with no opaque tail. Palette mode disabled. + #[test] + fn decodes_scc_extension_body_no_range() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0"; // sps_range_extension_flag = 0 + s += "0"; // sps_multilayer_extension_flag = 0 + s += "0"; // sps_3d_extension_flag = 0 + s += "1"; // sps_scc_extension_flag = 1 + s += "0000"; // sps_extension_4bits = 0 + // sps_scc_extension(): + s += "1"; // sps_curr_pic_ref_enabled_flag = 1 + s += "0"; // palette_mode_enabled_flag = 0 + s += "01"; // motion_vector_resolution_control_idc = 1 (u(2)) + s += "0"; // intra_boundary_filtering_disabled_flag = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(!flags.sps_range_extension_flag); + assert!(!flags.sps_multilayer_extension_flag); + assert!(!flags.sps_3d_extension_flag); + assert!(flags.sps_scc_extension_flag); + assert_eq!(flags.sps_extension_4bits, 0); + assert!(flags.has_body()); + assert!(sps.opaque_tail.is_none()); + let scc = sps.sps_scc_extension.expect("scc extension body"); + assert!(scc.sps_curr_pic_ref_enabled_flag); + assert!(!scc.palette_mode_enabled_flag); + assert_eq!(scc.motion_vector_resolution_control_idc, 1); + assert!(!scc.intra_boundary_filtering_disabled_flag); + } + + /// When `sps_scc_extension_flag == 1` but a `sps_multilayer_extension()` + /// body precedes it (§7.3.2.2.1 body order), the SCC body cannot be + /// decoded in place and the whole multilayer-onward span — including + /// the SCC body — stays in the opaque tail. + #[test] + fn scc_stays_opaque_behind_multilayer_body() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0"; // sps_range_extension_flag = 0 + s += "1"; // sps_multilayer_extension_flag = 1 + s += "0"; // sps_3d_extension_flag = 0 + s += "1"; // sps_scc_extension_flag = 1 + s += "0000"; // sps_extension_4bits = 0 + s += "11001100"; // opaque multilayer + scc span sentinel + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let flags = sps.extension_flags.expect("extension flag block"); + assert!(flags.sps_multilayer_extension_flag); + assert!(flags.sps_scc_extension_flag); + // Multilayer body is still opaque, so the SCC body cannot be + // decoded in place; both stay in the captured tail. + assert!(sps.sps_scc_extension.is_none()); + assert!(sps.opaque_tail.is_some()); + } + + /// `sps_extension_present_flag == 1` with the four typed + /// extension flags all 0 but `sps_extension_4bits != 0` still + /// surfaces an opaque tail — the §7.3.2.2.1 + /// `while( more_rbsp_data() ) sps_extension_data_flag` block is + /// gated by `sps_extension_4bits` (the §7.4.3.2.1 decoder rule is + /// to ignore the data flags but they must be skipped past + /// rbsp_trailing_bits, so the bytes are surfaced as opaque). + #[test] + fn captures_extension_data_flag_tail_when_4bits_nonzero() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "1"; // sps_extension_present_flag = 1 + s += "0000"; // four typed flags = 0 + s += "0001"; // sps_extension_4bits = 1 (reserved, non-zero) + s += "0"; // a single sps_extension_data_flag value + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let flags = sps.extension_flags.expect("extension flag block"); + assert_eq!(flags.sps_extension_4bits, 1); + assert!(flags.has_body()); + assert!(sps.opaque_tail.is_some()); + } + + /// When `sps_extension_present_flag == 0` the typed + /// extension-flag block is absent and every flag is inferred to + /// 0 per §7.4.3.2.1. + #[test] + fn extension_flags_absent_when_gate_zero() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "0"; // sps_extension_present_flag = 0 + s += "1"; // rbsp_trailing_bits stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(!sps.sps_extension_present_flag); + assert!(sps.extension_flags.is_none()); + assert!(sps.opaque_tail.is_none()); + } + + /// SPS with both `vui` and `extension` flags off — no opaque + /// tail is captured (only the rbsp_trailing_bits remain). + #[test] + fn no_opaque_tail_when_flags_clear() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short=0 + s += "0"; // long_term=0 + s += "1"; // temporal_mvp + s += "1"; // strong_intra_smoothing + s += "0"; // vui=0 + s += "0"; // sps_extension_present=0 + s += "1"; // stop bit + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + assert!(!sps.vui_parameters_present_flag); + assert!(!sps.sps_extension_present_flag); + assert!(sps.opaque_tail.is_none()); + } + + /// `num_short_term_ref_pic_sets > 64` is illegal per §7.4.3.2. + #[test] + fn rejects_too_many_short_term_rps() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + // num_short_term_ref_pic_sets = 65 → codeNum 65 + // 65 in 0-th order Exp-Golomb: leadingZeroBits=6, + // suffix = 65 - (2^6 - 1) = 2 = '000010' + // so the bit string is '000000 1 000010' = 13 bits. + s += "0000001000010"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert!(matches!( + err, + SpsError::ValueOutOfRange { + field: "num_short_term_ref_pic_sets", + .. + } + )); + } + + /// §7.4.8 explicit-form materialisation: the cumulative recurrence + /// for `DeltaPocS0[i]` (equation 7-69) and `DeltaPocS1[i]` + /// (equation 7-70) starting from the equation-7-67 / 7-68 seeds. + #[test] + fn materialize_explicit_form_recurrence() { + // Hand-assembled RPS: num_negative_pics = 3, + // delta_poc_s0_minus1 = [0, 1, 0], used_by_curr_pic_s0_flag = + // [true, false, true]; num_positive_pics = 2, + // delta_poc_s1_minus1 = [1, 0], used_by_curr_pic_s1_flag = + // [true, true]. Per §7.4.8: + // DeltaPocS0 = [-1, -3, -4] + // DeltaPocS1 = [ 2, 3] + let rps = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: false, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: Vec::new(), + use_delta_flag: Vec::new(), + num_negative_pics: 3, + num_positive_pics: 2, + delta_poc_s0_minus1: vec![0, 1, 0], + used_by_curr_pic_s0_flag: vec![true, false, true], + delta_poc_s1_minus1: vec![1, 0], + used_by_curr_pic_s1_flag: vec![true, true], + }; + let m = rps.materialize(None).expect("explicit materialise"); + assert_eq!(m.delta_poc_s0, vec![-1, -3, -4]); + assert_eq!(m.used_by_curr_pic_s0, vec![true, false, true]); + assert_eq!(m.delta_poc_s1, vec![2, 3]); + assert_eq!(m.used_by_curr_pic_s1, vec![true, true]); + assert_eq!(m.num_negative_pics(), 3); + assert_eq!(m.num_positive_pics(), 2); + assert_eq!(m.num_delta_pocs(), 5); + } + + /// §7.4.8 inter-RPS-prediction (equations 7-61 / 7-62): a tiny + /// chain where the source has one negative POC at -1 and the + /// derived RPS uses `deltaRps = +1` to shift it past zero, so the + /// source's negative drops out and `deltaRps` itself lands as a + /// positive entry gated by the wire flags. Matches the + /// `parses_inter_rps_prediction` fixture above. + #[test] + fn materialize_inter_rps_prediction_matches_fixture() { + let src = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1], + used_by_curr_pic_s0: vec![true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + // The inter-form RPS from the existing + // `parses_inter_rps_prediction` test: deltaRps = +1, + // used_by_curr_pic_flag = [true, false], use_delta_flag = [true, + // true]. + let inter = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: vec![true, false], + use_delta_flag: vec![true, true], + num_negative_pics: 0, + num_positive_pics: 0, + delta_poc_s0_minus1: Vec::new(), + used_by_curr_pic_s0_flag: Vec::new(), + delta_poc_s1_minus1: Vec::new(), + used_by_curr_pic_s1_flag: Vec::new(), + }; + let m = inter + .materialize(Some(&src)) + .expect("inter-RPS materialise"); + // Negative side (equation 7-61): + // * No source positives. + // * deltaRps = +1 ≥ 0, skip the self-term. + // * Source negative j=0: dPoc = -1 + 1 = 0, not < 0, skip. + // ⇒ NumNegativePics = 0. + assert!(m.delta_poc_s0.is_empty()); + assert!(m.used_by_curr_pic_s0.is_empty()); + // Positive side (equation 7-62): + // * Source negative j=0 reverse: dPoc = -1 + 1 = 0, not > 0, + // skip. + // * deltaRps = +1 > 0 and use_delta_flag[NumDeltaPocs=1] = + // true ⇒ DeltaPocS1[0] = +1, UsedByCurrPicS1[0] = + // used_by_curr_pic_flag[1] = false. + // * No source positives. + // ⇒ NumPositivePics = 1. + assert_eq!(m.delta_poc_s1, vec![1]); + assert_eq!(m.used_by_curr_pic_s1, vec![false]); + } + + /// §7.4.8 inter-RPS-prediction with `deltaRps < 0`: a source + /// positive POC at +1 with `deltaRps = -2` falls onto the negative + /// side via the source-positives-reverse step of equation 7-61. + #[test] + fn materialize_inter_rps_prediction_negative_delta_rps() { + // Source: one positive POC at +1 (no negatives). + let src = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![], + used_by_curr_pic_s0: vec![], + delta_poc_s1: vec![1], + used_by_curr_pic_s1: vec![true], + }; + // Inter-form: deltaRps = -(1+1) = -2; arrays sized + // NumDeltaPocs[src]+1 = 2. + // used_by_curr_pic_flag indexed: + // * [0..NumNegativePics[src]) = none + // * [NumNegativePics, NumNegativePics + NumPositivePics) = [0..1) = j_src=0 + // * [NumDeltaPocs] = trailing slot for `deltaRps` self-term + // So used_by_curr_pic_flag = [true_for_src_pos0, true_for_self_term]. + let inter = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + delta_idx_minus1: 0, + delta_rps_sign: true, // negative + abs_delta_rps_minus1: 1, + used_by_curr_pic_flag: vec![true, true], + use_delta_flag: vec![true, true], + num_negative_pics: 0, + num_positive_pics: 0, + delta_poc_s0_minus1: Vec::new(), + used_by_curr_pic_s0_flag: Vec::new(), + delta_poc_s1_minus1: Vec::new(), + used_by_curr_pic_s1_flag: Vec::new(), + }; + let m = inter + .materialize(Some(&src)) + .expect("inter-RPS negative deltaRps"); + // Negative side (equation 7-61): + // * Source positive j=0 reverse: dPoc = 1 + (-2) = -1 < 0 and + // use_delta_flag[NumNeg=0 + 0] = use_delta_flag[0] = true + // ⇒ DeltaPocS0[0] = -1, UsedByCurrPicS0[0] = + // used_by_curr_pic_flag[0] = true. + // * deltaRps = -2 < 0 and use_delta_flag[NumDeltaPocs=1] = + // true ⇒ DeltaPocS0[1] = -2, UsedByCurrPicS0[1] = + // used_by_curr_pic_flag[1] = true. + // * No source negatives. + assert_eq!(m.delta_poc_s0, vec![-1, -2]); + assert_eq!(m.used_by_curr_pic_s0, vec![true, true]); + // Positive side: source negatives reverse: none. deltaRps < 0, + // skip self-term. Source positive j=0: dPoc = +1 + (-2) = -1, + // not > 0, skip. ⇒ empty. + assert!(m.delta_poc_s1.is_empty()); + assert!(m.used_by_curr_pic_s1.is_empty()); + } + + /// [`ShortTermRefPicSet::materialize`] rejects the inter form + /// without a source RPS. + #[test] + fn materialize_inter_rps_rejects_missing_source() { + let inter = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: vec![true], + use_delta_flag: vec![true], + ..Default::default() + }; + assert_eq!( + inter.materialize(None), + Err(ShortTermRefPicSetMaterializeError::MissingSource), + ); + } + + /// [`ShortTermRefPicSet::materialize`] surfaces a per-position + /// array-length mismatch against the source RPS's `NumDeltaPocs + + /// 1`. + #[test] + fn materialize_inter_rps_rejects_length_mismatch() { + let src = MaterializedShortTermRefPicSet { + delta_poc_s0: vec![-1, -2], + used_by_curr_pic_s0: vec![true, true], + delta_poc_s1: vec![], + used_by_curr_pic_s1: vec![], + }; + // NumDeltaPocs[src] = 2, so the inter form expects arrays of + // length 3. Pass 2-element arrays to provoke the mismatch. + let inter = ShortTermRefPicSet { + inter_ref_pic_set_prediction_flag: true, + delta_idx_minus1: 0, + delta_rps_sign: false, + abs_delta_rps_minus1: 0, + used_by_curr_pic_flag: vec![true, true], + use_delta_flag: vec![true, true], + ..Default::default() + }; + assert!(matches!( + inter.materialize(Some(&src)), + Err(ShortTermRefPicSetMaterializeError::SourceLengthMismatch { + expected: 3, + got_used: 2, + got_delta: 2, + }), + )); + } + + /// [`SeqParameterSet::materialize_short_term_ref_pic_sets`] + /// chains explicit and inter-RPS-predicted entries through their + /// `RefRpsIdx` lookups using the same fixture as + /// `parses_inter_rps_prediction`. + #[test] + fn sps_materialize_chains_inter_rps_prediction() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm_enabled_flag + s += "011"; // num_short_term_ref_pic_sets = 2 + // st_ref_pic_set(0): explicit num_neg=1, num_pos=0, + // delta_poc_s0_minus1[0]=0, used_by_curr_pic_s0_flag=1 + s += "010"; + s += "1"; + s += "1"; + s += "1"; + // st_ref_pic_set(1): inter_ref_pic_set_prediction_flag = 1, + // delta_rps_sign=0, abs_delta_rps_minus1=0 (deltaRps=+1), + // used_by_curr_pic_flag = [1, 0], use_delta_flag[1] = 1. + s += "1"; + s += "0"; + s += "1"; + s += "1"; // used_by_curr_pic_flag[0] = 1 (use_delta inferred) + s += "0"; // used_by_curr_pic_flag[1] = 0 + s += "1"; // use_delta_flag[1] = 1 + // long_term=0, temporal_mvp=1, strong_intra_smoothing=1, + // vui=0, ext=0, stop bit + s += "0"; + s += "1"; + s += "1"; + s += "0"; + s += "0"; + s += "1"; + + let bytes = bits_to_bytes(&s); + let sps = SeqParameterSet::parse(&bytes).expect("SPS parse"); + let m = sps + .materialize_short_term_ref_pic_sets() + .expect("materialize"); + assert_eq!(m.len(), 2); + // Explicit source (idx 0): DeltaPocS0=[-1], UsedByCurrPicS0=[true]. + assert_eq!(m[0].delta_poc_s0, vec![-1]); + assert_eq!(m[0].used_by_curr_pic_s0, vec![true]); + assert_eq!(m[0].num_delta_pocs(), 1); + // Inter-predicted (idx 1): NumNegativePics=0, + // NumPositivePics=1 with DeltaPocS1=[+1] from the deltaRps + // self-term (see `materialize_inter_rps_prediction_matches_fixture`). + assert!(m[1].delta_poc_s0.is_empty()); + assert_eq!(m[1].delta_poc_s1, vec![1]); + assert_eq!(m[1].used_by_curr_pic_s1, vec![false]); + } + + /// `num_long_term_ref_pics_sps > 32` is illegal per §7.4.3.2. + #[test] + fn rejects_too_many_long_term_rps() { + let mut s = synthesised_prefix_bits(); + s += "0"; // pcm + s += "1"; // num_short_term=0 + s += "1"; // long_term_ref_pics_present + // num_long_term_ref_pics_sps = 33: codeNum 33 + // leadingZeroBits=5, suffix = 33 - (2^5 - 1) = 2 = '00010' + // bit string: '00000 1 00010' = 11 bits. + s += "00000100010"; + let bytes = bits_to_bytes(&s); + let err = SeqParameterSet::parse(&bytes).unwrap_err(); + assert!(matches!( + err, + SpsError::ValueOutOfRange { + field: "num_long_term_ref_pics_sps", + .. + } + )); + } +} diff --git a/vendor/oxideav-h265/src/transform.rs b/vendor/oxideav-h265/src/transform.rs new file mode 100644 index 0000000..124921c --- /dev/null +++ b/vendor/oxideav-h265/src/transform.rs @@ -0,0 +1,1152 @@ +//! §8.6.2 / §8.6.3 / §8.6.4 — scaling, transformation and residual +//! array construction prior to the deblocking filter process. +//! +//! This module turns the parsed `TransCoeffLevel[ xC ][ yC ]` array of +//! one transform block (produced by the [`crate::residual`] §7.3.8.11 +//! driver) into the `(nTbS)x(nTbS)` array `r` of residual samples that +//! the picture-construction step (§8.6.7) adds to the prediction. +//! +//! Three ITU-T H.265 (08/2021) processes are implemented, in the +//! dependency order the spec invokes them: +//! +//! * §8.6.3 **scaling process for transform coefficients** +//! ([`scale_coefficients`]) — the dequantization step. Each +//! `TransCoeffLevel[ x ][ y ]` is multiplied by the scaling factor +//! `m[ x ][ y ]` (a flat 16 when `scaling_list_enabled_flag == 0`, +//! else `ScalingFactor[ sizeId ][ matrixId ][ x ][ y ]`), the +//! `levelScale[ qP % 6 ]` rational-step list, and `1 << ( qP / 6 )`, +//! then offset-rounded by `bdShift` and clipped to +//! `[ coeffMin, coeffMax ]` (equations 8-300..8-309). +//! * §8.6.4 **transformation process for scaled transform +//! coefficients** ([`inverse_transform`]) — the separable inverse +//! transform. Each column then each row is passed through the +//! §8.6.4.2 one-dimensional transform ([`transform_1d`]); the +//! `trType == 1` 4x4 alternate transform (the DST-VII matrix of +//! equation 8-316) is selected only for `MODE_INTRA` 4x4 luma +//! blocks, every other block uses the `trType == 0` partial-butterfly +//! DCT-II matrix of equations 8-318..8-321. The intermediate column +//! result is offset-rounded by 7 and clipped (equation 8-314). +//! * §8.6.2 **scaling and transformation process** ([`residual_block`]) +//! — the orchestration that selects between the +//! `cu_transquant_bypass_flag` pass-through (with the §8.6.2 +//! `rotateCoeffs` reordering, equation 8-297), the +//! `transform_skip_flag` `tsShift` left-shift (equation 8-298), and +//! the full scale-then-transform path, applying the final `bdShift` +//! offset-round (equation 8-299). +//! +//! All arithmetic is integer-exact per the spec: products use `i64` +//! intermediates (the §8.6.3 scale product can exceed `i32` for the +//! `extended_precision_processing_flag` ranges), and every clip uses +//! the `Clip3` bounds the surrounding subclause derives. +//! +//! ## Scope +//! +//! The transform-domain numerics are self-contained: the inputs are +//! the decoded `TransCoeffLevel` array, the derived quantization +//! parameter `qP`, the bit depth, and the small set of SPS/PPS/CU +//! flags the three subclauses read. The §8.6.1 `qP` derivation, the +//! §8.6.5 transform-bypass RDPCM residual modification, the §8.6.6 +//! cross-component-prediction modification, and the §8.6.7 picture +//! construction are the consumers' / follow-ups' responsibility — this +//! module stops at the `(nTbS)x(nTbS)` array `r`. + +use crate::scaling_list::ScalingFactorMatrix; + +/// §8.6.3 `levelScale[ k ]` rational quantization-step list, indexed by +/// `qP % 6` (the list is `{ 40, 45, 51, 57, 64, 72 }`). +pub const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72]; + +/// Colour component of the current transform block, naming the +/// `cIdx` value (0 = luma, 1 = Cb, 2 = Cr) the three subclauses branch +/// on for bit depth and `coeffMin` / `coeffMax`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Component { + /// `cIdx == 0` — luma. Uses `BitDepthY` and `CoeffMin/MaxY`. + Luma, + /// `cIdx == 1` — Cb chroma. Uses `BitDepthC` and `CoeffMin/MaxC`. + Cb, + /// `cIdx == 2` — Cr chroma. Uses `BitDepthC` and `CoeffMin/MaxC`. + Cr, +} + +impl Component { + /// `true` for the two chroma components (`cIdx != 0`). + #[inline] + #[must_use] + pub fn is_chroma(self) -> bool { + !matches!(self, Component::Luma) + } +} + +/// §8.6.4 `CuPredMode[ xTbY ][ yTbY ]` — the prediction mode of the +/// coding unit covering the transform block. Only the §8.6.2 +/// `rotateCoeffs` and §8.6.4 `trType` derivations read it. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum PredMode { + /// `MODE_INTRA`. + Intra, + /// `MODE_INTER` (or `MODE_SKIP`, which shares the inter transform + /// path for residual purposes). + Inter, +} + +/// Errors from the §8.6.2 / §8.6.3 / §8.6.4 processes. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum TransformError { + /// `nTbS` (the `1 << log2TrafoSize` block side) was not one of the + /// four legal transform-block sizes (4, 8, 16, 32). + InvalidBlockSize(usize), + /// The `TransCoeffLevel` (or `ScalingFactor`) input array did not + /// hold exactly `nTbS * nTbS` elements. + LengthMismatch { + /// The `nTbS * nTbS` count the block requires. + expected: usize, + /// The element count actually supplied. + got: usize, + }, + /// `bitDepth` was outside the 8..=16 range the equations are + /// dimensioned for. + InvalidBitDepth(u8), +} + +impl core::fmt::Display for TransformError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::InvalidBlockSize(n) => { + write!( + f, + "invalid transform block size nTbS = {n} (expected 4/8/16/32)" + ) + } + Self::LengthMismatch { expected, got } => { + write!( + f, + "coefficient array length {got} != nTbS*nTbS = {expected}" + ) + } + Self::InvalidBitDepth(b) => write!(f, "invalid bitDepth {b} (expected 8..=16)"), + } + } +} + +impl std::error::Error for TransformError {} + +/// `log2( nTbS )` for a legal transform-block side, or `None` if `n_tbs` +/// is not 4 / 8 / 16 / 32. +#[inline] +fn log2_tbs(n_tbs: usize) -> Option { + match n_tbs { + 4 => Some(2), + 8 => Some(3), + 16 => Some(4), + 32 => Some(5), + _ => None, + } +} + +/// §7.4.5 equations 7-27..7-30 — `CoeffMin` / `CoeffMax` for the given +/// `bitDepth` and `extended_precision_processing_flag`. +/// +/// Returns `( coeffMin, coeffMax )`. With the flag clear the range is +/// the fixed `[ −32768, 32767 ]`; with it set the magnitude widens to +/// `Max( 15, bitDepth + 6 )` bits. +#[inline] +#[must_use] +pub fn coeff_range(bit_depth: u8, extended_precision: bool) -> (i32, i32) { + let log2_range = if extended_precision { + core::cmp::max(15, bit_depth as i32 + 6) + } else { + 15 + }; + let mag = 1i32 << log2_range; + (-mag, mag - 1) +} + +/// `Clip3( lo, hi, x )` — clamp `x` to the inclusive `[ lo, hi ]` range +/// (§5, the clause-8 `Clip3` operator), on `i64`. +#[inline] +fn clip3(lo: i64, hi: i64, x: i64) -> i64 { + x.clamp(lo, hi) +} + +/// §8.6.3 — scaling (dequantization) process for transform +/// coefficients. +/// +/// Inputs: +/// * `levels` — the `TransCoeffLevel[ x ][ y ]` array, row-major by +/// `y` (`levels[ y * nTbS + x ]`), as [`crate::residual::ResidualBlock`] +/// stores it. +/// * `n_tbs` — the block side `nTbS` (4 / 8 / 16 / 32). +/// * `q_p` — the quantization parameter `qP` derived by §8.6.2. +/// * `bit_depth` — `BitDepthY` for luma, `BitDepthC` for chroma. +/// * `extended_precision` — `extended_precision_processing_flag`. +/// * `scaling` — the per-position scaling factor `m[ x ][ y ]`: +/// `Some( ScalingFactor )` when `scaling_list_enabled_flag == 1` and +/// the §8.6.3 "flat 16" exception does not apply, else `None` (a flat +/// 16 is used). The matrix is indexed `at( x, y )`. +/// +/// Output: the `(nTbS)x(nTbS)` array `d` of scaled coefficients, +/// row-major by `y`. +/// +/// # Errors +/// [`TransformError::InvalidBlockSize`] for a non-4/8/16/32 `n_tbs`, +/// [`TransformError::LengthMismatch`] if `levels` (or `scaling`) is not +/// `n_tbs * n_tbs` long, [`TransformError::InvalidBitDepth`] for a +/// `bit_depth` outside 8..=16. +pub fn scale_coefficients( + levels: &[i32], + n_tbs: usize, + q_p: u32, + bit_depth: u8, + extended_precision: bool, + scaling: Option<&ScalingFactorMatrix>, +) -> Result, TransformError> { + let log2_tbs = log2_tbs(n_tbs).ok_or(TransformError::InvalidBlockSize(n_tbs))?; + if !(8..=16).contains(&bit_depth) { + return Err(TransformError::InvalidBitDepth(bit_depth)); + } + let count = n_tbs * n_tbs; + if levels.len() != count { + return Err(TransformError::LengthMismatch { + expected: count, + got: levels.len(), + }); + } + if let Some(m) = scaling { + let m_count = m.dim as usize * m.dim as usize; + if m_count != count { + return Err(TransformError::LengthMismatch { + expected: count, + got: m_count, + }); + } + } + + // §8.6.3 equations 8-300/8-304 (log2TransformRange), + // 8-301/8-305 (bdShift), 8-302..8-307 (coeffMin/coeffMax). + let log2_transform_range = if extended_precision { + core::cmp::max(15, bit_depth as i32 + 6) + } else { + 15 + }; + let bd_shift = bit_depth as i32 + log2_tbs as i32 + 10 - log2_transform_range; + let (coeff_min, coeff_max) = coeff_range(bit_depth, extended_precision); + + let level_scale = LEVEL_SCALE[(q_p % 6) as usize] as i64; + let qp_div6 = q_p / 6; + // bdShift is always >= 1 for the dimensioned ranges (bitDepth >= 8, + // log2TrafoSize >= 2, log2TransformRange <= bitDepth + 6), so the + // (1 << (bdShift - 1)) rounding offset is well-formed. + let round = 1i64 << (bd_shift - 1); + + let mut d = vec![0i32; count]; + for y in 0..n_tbs { + for x in 0..n_tbs { + let idx = y * n_tbs + x; + // §8.6.3 m[ x ][ y ]: flat 16 unless an explicit + // ScalingFactor matrix is supplied (the caller folds the + // "transform_skip && nTbS > 4 ⇒ 16" exception into the + // `scaling` argument it passes). + let m = scaling.map_or(16i64, |sf| sf.at(x, y) as i64); + // §8.6.3 eq. 8-309: clip( (TransCoeffLevel * m * levelScale + // << (qP/6)) + round ) >> bdShift. + let prod = (levels[idx] as i64) * m * level_scale; + let shifted = (prod << qp_div6) + round; + let scaled = clip3(coeff_min as i64, coeff_max as i64, shifted >> bd_shift); + d[idx] = scaled as i32; + } + } + Ok(d) +} + +/// §8.6.4.2 equation 8-316 — the `trType == 1` 4x4 alternate (DST-VII) +/// transform matrix, `transMatrix[ i ][ j ]`, row-major. +#[rustfmt::skip] +const DST4: [[i32; 4]; 4] = [ + [29, 55, 74, 84], + [74, 74, 0, -74], + [84, -29, -74, 55], + [55, -84, 74, -29], +]; + +/// §8.6.4.2 equations 8-318..8-321 — the `trType == 0` 32x32 DCT-II +/// transform matrix `transMatrix[ m ][ n ]` (`m`, `n` = 0..31), +/// row-major. The smaller 4 / 8 / 16 transforms subsample column `n` +/// at stride `1 << ( 5 − log2( nTbS ) )` per equation 8-317. +#[rustfmt::skip] +const DCT32: [[i32; 32]; 32] = [ + [64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64], + [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4, -4, -13, -22, -31, -38, -46, -54, -61, -67, -73, -78, -82, -85, -88, -90, -90], + [90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90, -90, -87, -80, -70, -57, -43, -25, -9, 9, 25, 43, 57, 70, 80, 87, 90], + [90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13, 13, 38, 61, 78, 88, 90, 85, 73, 54, 31, 4, -22, -46, -67, -82, -90], + [89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89, 89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89], + [88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22, -22, -61, -85, -90, -73, -38, 4, 46, 78, 90, 82, 54, 13, -31, -67, -88], + [87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87, -87, -57, -9, 43, 80, 90, 70, 25, -25, -70, -90, -80, -43, 9, 57, 87], + [85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31, 31, 78, 90, 61, 4, -54, -88, -82, -38, 22, 73, 90, 67, 13, -46, -85], + [83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83], + [82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38, -38, -88, -73, -4, 67, 90, 46, -31, -85, -78, -13, 61, 90, 54, -22, -82], + [80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80, -80, -9, 70, 87, 25, -57, -90, -43, 43, 90, 57, -25, -87, -70, 9, 80], + [78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46, 46, 90, 38, -54, -90, -31, 61, 88, 22, -67, -85, -13, 73, 82, 4, -78], + [75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75, 75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75], + [73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54, -54, -85, 4, 88, 46, -61, -82, 13, 90, 38, -67, -78, 22, 90, 31, -73], + [70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70, -70, 43, 87, -9, -90, -25, 80, 57, -57, -80, 25, 90, 9, -87, -43, 70], + [67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61, 61, 73, -46, -82, 31, 88, -13, -90, -4, 90, 22, -85, -38, 78, 54, -67], + [64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64], + [61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67, -67, -54, 78, 38, -85, -22, 90, 4, -90, 13, 88, -31, -82, 46, 73, -61], + [57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57, -57, 80, 25, -90, 9, 87, -43, -70, 70, 43, -87, -9, 90, -25, -80, 57], + [54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73, 73, 31, -90, 22, 78, -67, -38, 90, -13, -82, 61, 46, -88, 4, 85, -54], + [50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50, 50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50], + [46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78, -78, -4, 82, -73, -13, 85, -67, -22, 88, -61, -31, 90, -54, -38, 90, -46], + [43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43, -43, 90, -57, -25, 87, -70, -9, 80, -80, 9, 70, -87, 25, 57, -90, 43], + [38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82, 82, -22, -54, 90, -61, -13, 78, -85, 31, 46, -90, 67, 4, -73, 88, -38], + [36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36], + [31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85, -85, 46, 13, -67, 90, -73, 22, 38, -82, 88, -54, -4, 61, -90, 78, -31], + [25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25, -25, 70, -90, 80, -43, -9, 57, -87, 87, -57, 9, 43, -80, 90, -70, 25], + [22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88, 88, -67, 31, 13, -54, 82, -90, 78, -46, 4, 38, -73, 90, -85, 61, -22], + [18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18, 18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18], + [13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90, -90, 82, -67, 46, -22, -4, 31, -54, 73, -85, 90, -88, 78, -61, 38, -13], + [9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9, -9, 25, -43, 57, -70, 80, -87, 90, -90, 87, -80, 70, -57, 43, -25, 9], + [4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90, 90, -90, 88, -85, 82, -78, 73, -67, 61, -54, 46, -38, 31, -22, 13, -4], +]; + +/// §8.6.4.2 — the one-dimensional transformation process. +/// +/// `trType == 1` (the `tr_type == true` argument) applies the 4x4 +/// DST-VII matrix multiplication of equation 8-316 (valid only for +/// `n_tbs == 4`); `trType == 0` applies the equation 8-317 DCT-II +/// matrix multiplication, subsampling the 32x32 base matrix's column +/// index at stride `1 << ( 5 − log2( nTbS ) )`. +/// +/// `input` is the length-`n_tbs` list `x[ j ]`; the return is the +/// length-`n_tbs` list `y[ i ]`. Products accumulate in `i64`. +#[must_use] +fn transform_1d(input: &[i64], n_tbs: usize, tr_type: bool) -> Vec { + let mut out = vec![0i64; n_tbs]; + if tr_type { + // §8.6.4.2 eq. 8-315/8-316: y[i] = Σ_j transMatrix[i][j] * x[j], + // the 4x4 DST. trType == 1 is only ever invoked with nTbS == 4. + // + // The printed eq.-8-316 matrix follows the same index convention + // eq. 8-318 states for the DCT base table ("transMatrix[ m ][ n ] + // ... with m = 0..15" — the first printed index is the column): + // each printed brace row is a *column* of transMatrix, so + // `transMatrix[ i ][ j ]` reads the in-code row-major [`DST4`] + // at `[ j ][ i ]`, exactly like the transposed [`DCT32`] read + // below. Verified byte-exact against the qp-high / qp-low + // fixture decodes (a literal `[ i ][ j ]` read of the printed + // rows diverges from the conformance output). + for (i, oi) in out.iter_mut().enumerate() { + let mut acc = 0i64; + for (j, &xj) in input.iter().enumerate() { + acc += DST4[j][i] as i64 * xj; + } + *oi = acc; + } + } else { + // §8.6.4.2 eq. 8-317: y[i] = Σ_j transMatrix[i][j * stride] * + // x[j], stride = 1 << (5 - log2(nTbS)). + // + // The §8.6.4.2 transMatrix is laid out (eq. 8-318/8-319) so that + // `transMatrix[ m ][ n ]` = `transMatrixCol0to15[ m ][ n ]` with + // `m` the column index 0..15 and `n` the row index 0..31; i.e. + // the named base table is indexed [column][row]. The in-code + // [`DCT32`] is the natural row-major listing of that base table, + // so `DCT32[ a ][ b ] == transMatrix[ b ][ a ]`. Equation 8-317's + // `transMatrix[ i ][ j*stride ]` therefore reads `DCT32[ j*stride + // ][ i ]` — the column index `j*stride` becomes the DCT32 row. + // (For DC-only input this yields the constant row-0 basis, the + // uniform synthesis the inverse transform must produce.) + let log2 = log2_tbs(n_tbs).expect("transform_1d called with non-2^k nTbS"); + let stride = 1usize << (5 - log2); + for (i, oi) in out.iter_mut().enumerate() { + let mut acc = 0i64; + for (j, &xj) in input.iter().enumerate() { + acc += DCT32[j * stride][i] as i64 * xj; + } + *oi = acc; + } + } + out +} + +/// Encoder-side forward DCT-II 1-D over the same §8.6.4.2 basis the +/// inverse synthesizes from: `y[ u ] = Σ_x DCT32[ u * stride ][ x ] * +/// x[ x ]` — the transpose of the [`transform_1d`] `trType == 0` +/// analysis, so an inverse-transformed forward output reproduces the +/// input up to the normalization shifts the encoder applies. +pub(crate) fn forward_dct_1d(input: &[i64], n_tbs: usize) -> Vec { + let log2 = log2_tbs(n_tbs).expect("forward_dct_1d called with non-2^k nTbS"); + let stride = 1usize << (5 - log2); + (0..n_tbs) + .map(|u| { + input + .iter() + .enumerate() + .map(|(x, &xv)| DCT32[u * stride][x] as i64 * xv) + .sum() + }) + .collect() +} + +/// §8.6.4 — transformation process for scaled transform coefficients. +/// +/// Inputs: +/// * `d` — the scaled-coefficient array from §8.6.3, row-major by `y` +/// (`d[ y * nTbS + x ]`). +/// * `n_tbs` — the block side. +/// * `pred_mode` / `component` — select the §8.6.4 `trType` (the 4x4 +/// DST is taken only for `MODE_INTRA`, `nTbS == 4`, luma). +/// * `bit_depth` / `extended_precision` — fix the §8.6.4 intermediate +/// `coeffMin` / `coeffMax` clip (equation 8-314). +/// +/// Output: the `(nTbS)x(nTbS)` array `r` of pre-`bdShift` residual +/// samples, row-major by `y`. The final §8.6.2 equation-8-299 +/// `bdShift` offset-round is applied by [`residual_block`], not here. +/// +/// # Errors +/// [`TransformError::InvalidBlockSize`] / [`TransformError::LengthMismatch`] +/// / [`TransformError::InvalidBitDepth`] as for [`scale_coefficients`]. +pub fn inverse_transform( + d: &[i32], + n_tbs: usize, + pred_mode: PredMode, + component: Component, + bit_depth: u8, + extended_precision: bool, +) -> Result, TransformError> { + if log2_tbs(n_tbs).is_none() { + return Err(TransformError::InvalidBlockSize(n_tbs)); + } + if !(8..=16).contains(&bit_depth) { + return Err(TransformError::InvalidBitDepth(bit_depth)); + } + let count = n_tbs * n_tbs; + if d.len() != count { + return Err(TransformError::LengthMismatch { + expected: count, + got: d.len(), + }); + } + + // §8.6.4 trType: 1 iff MODE_INTRA, nTbS == 4, cIdx == 0. + let tr_type = + matches!(pred_mode, PredMode::Intra) && n_tbs == 4 && matches!(component, Component::Luma); + // §8.6.4 eqs. 8-310..8-313: the intermediate-clip coeffMin/coeffMax. + let (coeff_min, coeff_max) = coeff_range(bit_depth, extended_precision); + + // §8.6.4 step 1: column transform d[x][y] over y -> e[x][y]. + // d is row-major by y; a column is the fixed-x slice. + let mut e = vec![0i64; count]; + for x in 0..n_tbs { + let col: Vec = (0..n_tbs).map(|y| d[y * n_tbs + x] as i64).collect(); + let te = transform_1d(&col, n_tbs, tr_type); + for (y, &v) in te.iter().enumerate() { + e[y * n_tbs + x] = v; + } + } + + // §8.6.4 step 2 (eq. 8-314): g[x][y] = clip( (e + 64) >> 7 ). + let mut g = vec![0i64; count]; + for (gv, &ev) in g.iter_mut().zip(e.iter()) { + *gv = clip3(coeff_min as i64, coeff_max as i64, (ev + 64) >> 7); + } + + // §8.6.4 step 3: row transform g[x][y] over x -> r[x][y]. + let mut r = vec![0i32; count]; + for y in 0..n_tbs { + let row: Vec = (0..n_tbs).map(|x| g[y * n_tbs + x]).collect(); + let tr = transform_1d(&row, n_tbs, tr_type); + for (x, &v) in tr.iter().enumerate() { + // r stays i64-valued through here; equation 8-299's bdShift + // round (in residual_block) is what reduces it. Per the + // spec the §8.6.4 row output is not itself clipped, so keep + // full precision and narrow at the final offset-round. + r[y * n_tbs + x] = v as i32; + } + } + Ok(r) +} + +/// Inputs to the §8.6.2 scaling-and-transformation orchestration that +/// the surrounding subclauses derive for one transform block, gathered +/// into one struct so [`residual_block`] has a stable signature as the +/// follow-up RDPCM / cross-component steps are added. +#[derive(Debug, Clone, Copy)] +pub struct BlockParams { + /// `nTbS` — the transform-block side (4 / 8 / 16 / 32). + pub n_tbs: usize, + /// `qP` — the §8.6.1-derived quantization parameter for this block. + pub q_p: u32, + /// The colour component `cIdx`. + pub component: Component, + /// `CuPredMode[ xTbY ][ yTbY ]`. + pub pred_mode: PredMode, + /// `BitDepthY` for luma, `BitDepthC` for chroma. + pub bit_depth: u8, + /// `extended_precision_processing_flag`. + pub extended_precision: bool, + /// `cu_transquant_bypass_flag` — when set, §8.6.2 bypasses scaling + /// and transformation entirely (with the `rotateCoeffs` reorder). + pub transquant_bypass: bool, + /// `transform_skip_flag[ xTbY ][ yTbY ][ cIdx ]` — when set (and + /// not bypassed), §8.6.2 replaces the inverse transform with the + /// `tsShift` left-shift (equation 8-298). + pub transform_skip: bool, + /// `transform_skip_rotation_enabled_flag` — gates the §8.6.2 + /// `rotateCoeffs` derivation (only meaningful for 4x4 intra blocks). + pub transform_skip_rotation_enabled: bool, +} + +/// §8.6.2 — the scaling and transformation process for one transform +/// block: turn `TransCoeffLevel` into the `(nTbS)x(nTbS)` residual +/// array `r`. +/// +/// `levels` is the `TransCoeffLevel[ x ][ y ]` array, row-major by `y` +/// (as [`crate::residual::ResidualBlock::levels`] stores it). `scaling` +/// is the per-position `ScalingFactor` matrix when +/// `scaling_list_enabled_flag == 1` and the §8.6.3 flat-16 exception +/// does not apply, else `None`. Returns the residual array `r`, +/// row-major by `y`. +/// +/// The three §8.6.2 branches are dispatched on `params`: +/// * `transquant_bypass` ⇒ pass `TransCoeffLevel` straight to `r`, +/// applying the `rotateCoeffs` reorder (equation 8-297); +/// * else `transform_skip` ⇒ scale (§8.6.3), `rotateCoeffs`-reorder if +/// applicable, then `<< tsShift` (equation 8-298) and the equation +/// 8-299 `bdShift` offset-round; +/// * else ⇒ scale (§8.6.3), inverse-transform (§8.6.4), then the +/// equation 8-299 `bdShift` offset-round. +/// +/// # Errors +/// [`TransformError`] as for [`scale_coefficients`] / [`inverse_transform`]. +pub fn residual_block( + levels: &[i32], + scaling: Option<&ScalingFactorMatrix>, + params: BlockParams, +) -> Result, TransformError> { + let n_tbs = params.n_tbs; + let log2_tbs = log2_tbs(n_tbs).ok_or(TransformError::InvalidBlockSize(n_tbs))?; + if !(8..=16).contains(¶ms.bit_depth) { + return Err(TransformError::InvalidBitDepth(params.bit_depth)); + } + let count = n_tbs * n_tbs; + if levels.len() != count { + return Err(TransformError::LengthMismatch { + expected: count, + got: levels.len(), + }); + } + + // §8.6.2 rotateCoeffs: 1 iff transform_skip_rotation_enabled_flag, + // nTbS == 4, MODE_INTRA. + let rotate = params.transform_skip_rotation_enabled + && n_tbs == 4 + && matches!(params.pred_mode, PredMode::Intra); + + // §8.6.2 cu_transquant_bypass_flag == 1 path (eq. 8-297 / array + // copy): no scaling, no transform, no bdShift. + if params.transquant_bypass { + let mut r = vec![0i32; count]; + for y in 0..n_tbs { + for x in 0..n_tbs { + let (sx, sy) = if rotate { + (n_tbs - x - 1, n_tbs - y - 1) + } else { + (x, y) + }; + r[y * n_tbs + x] = levels[sy * n_tbs + sx]; + } + } + return Ok(r); + } + + // §8.6.2 ordered step 1: §8.6.3 scaling process -> d. + let d = scale_coefficients( + levels, + n_tbs, + params.q_p, + params.bit_depth, + params.extended_precision, + scaling, + )?; + + // §8.6.2 equations 8-294/8-295/8-296: bitDepth, bdShift, tsShift. + let bd_shift = core::cmp::max( + 20 - params.bit_depth as i32, + if params.extended_precision { 11 } else { 0 }, + ); + + // §8.6.2 ordered step 2. + let pre = if params.transform_skip { + // eq. 8-298: r[x][y] = (rotate ? d[n-x-1][n-y-1] : d[x][y]) << tsShift. + let ts_shift = 5 + log2_tbs as i32; + let mut r = vec![0i32; count]; + for y in 0..n_tbs { + for x in 0..n_tbs { + let (sx, sy) = if rotate { + (n_tbs - x - 1, n_tbs - y - 1) + } else { + (x, y) + }; + r[y * n_tbs + x] = ((d[sy * n_tbs + sx] as i64) << ts_shift) as i32; + } + } + r + } else { + // §8.6.4 transformation process. + inverse_transform( + &d, + n_tbs, + params.pred_mode, + params.component, + params.bit_depth, + params.extended_precision, + )? + }; + + // §8.6.2 ordered step 3 (eq. 8-299): r = (r + (1 << (bdShift-1))) >> bdShift. + let mut r = vec![0i32; count]; + if bd_shift > 0 { + let round = 1i64 << (bd_shift - 1); + for (rv, &pv) in r.iter_mut().zip(pre.iter()) { + *rv = (((pv as i64) + round) >> bd_shift) as i32; + } + } else { + // bdShift == 0 only under extended-precision with bitDepth == 20 + // (out of our 8..=16 domain) — but keep the no-shift identity + // for completeness. + r.copy_from_slice(&pre); + } + Ok(r) +} + +/// §8.6.5 — residual modification process for blocks using a transform +/// bypass (RDPCM): the directional cumulative sum over the +/// `(nTbS)x(nTbS)` residual array `r`. +/// +/// `vertical` is the process input `mDir`: `false` (mDir 0) applies the +/// horizontal accumulation of eq. 8-322 (`r[x][y] += r[x-1][y]`, x +/// proceeding 1..nTbS-1), `true` (mDir 1) the vertical accumulation of +/// eq. 8-323 (`r[x][y] += r[x][y-1]`, y proceeding 1..nTbS-1). +/// +/// Invoked for inter blocks with `explicit_rdpcm_flag == 1` (mDir = +/// `explicit_rdpcm_dir_flag`, §8.5.4.2 / §8.5.4.3) and for intra blocks +/// under the implicit-RDPCM condition (`implicit_rdpcm_enabled_flag`, +/// transform skip or transquant bypass, predModeIntra 10 / 26, with +/// mDir = predModeIntra / 26 — §8.4.4.1). +/// +/// `r` is row-major by `y` (as [`residual_block`] returns it); its +/// length must be `n_tbs * n_tbs`. +pub fn rdpcm_accumulate(r: &mut [i32], n_tbs: usize, vertical: bool) { + debug_assert_eq!(r.len(), n_tbs * n_tbs); + if vertical { + // eq. 8-323: r[ x ][ y ] += r[ x ][ y − 1 ]. + for y in 1..n_tbs { + for x in 0..n_tbs { + r[y * n_tbs + x] = r[y * n_tbs + x].wrapping_add(r[(y - 1) * n_tbs + x]); + } + } + } else { + // eq. 8-322: r[ x ][ y ] += r[ x − 1 ][ y ]. + for y in 0..n_tbs { + for x in 1..n_tbs { + r[y * n_tbs + x] = r[y * n_tbs + x].wrapping_add(r[y * n_tbs + x - 1]); + } + } + } +} + +/// §8.6.8.2 — adaptive colour transformation process (inverse), applied +/// to the three co-located residual arrays of one 4:4:4 transform block +/// whose `tu_residual_act_flag` is 1. +/// +/// Ordered per the clause: +/// 1. eq. 8-326..8-328 — clip each array to its `CoeffMin/Max` range +/// (luma range for `rY`, chroma range for `rCb` / `rCr`); +/// 2. when `cu_transquant_bypass_flag == 0`, eq. 8-329..8-335 — +/// bit-depth alignment to `Max( BitDepthY, BitDepthC )` with the +/// extra `<< 1` on both chroma arrays; +/// 3. eq. 8-336..8-339 — the lifting inverse: +/// `tmp = rY − ( rCb >> 1 ); rY = tmp + rCb; +/// rCb = tmp − ( rCr >> 1 ); rCr += rCb`; +/// 4. when `cu_transquant_bypass_flag == 0`, eq. 8-340..8-342 — the +/// rounded down-shift back to the component bit depths. +/// +/// All three slices must have the same length (`nTbS * nTbS`). +pub fn act_inverse( + r_y: &mut [i32], + r_cb: &mut [i32], + r_cr: &mut [i32], + bit_depth_luma: u8, + bit_depth_chroma: u8, + extended_precision: bool, + transquant_bypass: bool, +) { + debug_assert_eq!(r_y.len(), r_cb.len()); + debug_assert_eq!(r_y.len(), r_cr.len()); + let (min_y, max_y) = coeff_range(bit_depth_luma, extended_precision); + let (min_c, max_c) = coeff_range(bit_depth_chroma, extended_precision); + // eq. 8-329..8-332. + let max_bd = bit_depth_luma.max(bit_depth_chroma); + let delta_bd_y = u32::from(max_bd - bit_depth_luma); + let delta_bd_c = u32::from(max_bd - bit_depth_chroma); + let offset_bd_y = if delta_bd_y != 0 { + 1i32 << (delta_bd_y - 1) + } else { + 0 + }; + let offset_bd_c = if delta_bd_c != 0 { + 1i32 << (delta_bd_c - 1) + } else { + 0 + }; + for i in 0..r_y.len() { + // eq. 8-326..8-328. + let mut y = r_y[i].clamp(min_y, max_y); + let mut cb = r_cb[i].clamp(min_c, max_c); + let mut cr = r_cr[i].clamp(min_c, max_c); + // eq. 8-333..8-335 (lossy only). + if !transquant_bypass { + y <<= delta_bd_y; + cb <<= delta_bd_c + 1; + cr <<= delta_bd_c + 1; + } + // eq. 8-336..8-339. + let tmp = y - (cb >> 1); + y = tmp + cb; + cb = tmp - (cr >> 1); + cr += cb; + // eq. 8-340..8-342 (lossy only). + if !transquant_bypass { + y = (y + offset_bd_y) >> delta_bd_y; + cb = (cb + offset_bd_c) >> delta_bd_c; + cr = (cr + offset_bd_c) >> delta_bd_c; + } + r_y[i] = y; + r_cb[i] = cb; + r_cr[i] = cr; + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn flat_levels(n: usize, fill: &[(usize, usize, i32)]) -> Vec { + let mut v = vec![0i32; n * n]; + for &(x, y, val) in fill { + v[y * n + x] = val; + } + v + } + + #[test] + fn coeff_range_default_is_15bit() { + assert_eq!(coeff_range(8, false), (-32768, 32767)); + assert_eq!(coeff_range(10, false), (-32768, 32767)); + } + + #[test] + fn coeff_range_extended_widens_with_bitdepth() { + // bitDepth + 6 = 18 > 15 -> magnitude 1 << 18. + assert_eq!(coeff_range(12, true), (-(1 << 18), (1 << 18) - 1)); + // bitDepth + 6 = 14 < 15 -> still 15 bits. + assert_eq!(coeff_range(8, true), (-32768, 32767)); + } + + /// §8.6.3 hand-computed scale of a single DC level. nTbS = 4 + /// (log2 = 2), bitDepth = 8, no scaling list (m = 16), + /// extended_precision = 0. qP = 6 -> qP%6 = 0 (levelScale 40), + /// qP/6 = 1. bdShift = 8 + 2 + 10 - 15 = 5, round = 16. + /// d = clip( ((level * 16 * 40) << 1 + 16) >> 5 ). + #[test] + fn scale_single_dc_matches_hand_computation() { + let n = 4; + let levels = flat_levels(n, &[(0, 0, 3)]); + let d = scale_coefficients(&levels, n, 6, 8, false, None).unwrap(); + // level 3: (3*16*40) = 1920; <<1 = 3840; +16 = 3856; >>5 = 120. + assert_eq!(d[0], 120); + // every other coefficient is 0 -> stays 0. + assert!(d[1..].iter().all(|&v| v == 0)); + } + + /// qP/6 partition: qP = 4 -> qP%6 = 4 (levelScale 64), qP/6 = 0. + /// level = -5, m = 16, bdShift = 5, round = 16. + /// (-5*16*64) = -5120; <<0 = -5120; +16 = -5104; >>5 = -160 (arith). + #[test] + fn scale_negative_level_arithmetic_shift() { + let n = 4; + let levels = flat_levels(n, &[(1, 2, -5)]); + let d = scale_coefficients(&levels, n, 4, 8, false, None).unwrap(); + assert_eq!(d[2 * n + 1], -160); + } + + /// §8.6.3 clip to CoeffMax. A huge level * big qP saturates at + /// 32767 for the default 15-bit range. + #[test] + fn scale_clips_to_coeff_max() { + let n = 4; + let levels = flat_levels(n, &[(0, 0, 30000)]); + // qP = 51 -> qP/6 = 8, large left-shift -> saturates. + let d = scale_coefficients(&levels, n, 51, 8, false, None).unwrap(); + assert_eq!(d[0], 32767); + } + + /// §8.6.2 transquant-bypass copies TransCoeffLevel verbatim (no + /// rotate when rotation not enabled). + #[test] + fn bypass_copies_levels_verbatim() { + let n = 4; + let levels = flat_levels(n, &[(0, 0, 7), (3, 3, -2), (1, 0, 5)]); + let params = BlockParams { + n_tbs: n, + q_p: 26, + component: Component::Luma, + pred_mode: PredMode::Intra, + bit_depth: 8, + extended_precision: false, + transquant_bypass: true, + transform_skip: false, + transform_skip_rotation_enabled: false, + }; + let r = residual_block(&levels, None, params).unwrap(); + assert_eq!(r, levels); + } + + /// §8.6.2 transquant-bypass with rotateCoeffs (4x4 intra, + /// rotation enabled) mirrors x and y (eq. 8-297). + #[test] + fn bypass_rotate_mirrors_coefficients() { + let n = 4; + let levels = flat_levels(n, &[(0, 0, 9)]); + let params = BlockParams { + n_tbs: n, + q_p: 0, + component: Component::Luma, + pred_mode: PredMode::Intra, + bit_depth: 8, + extended_precision: false, + transquant_bypass: true, + transform_skip: false, + transform_skip_rotation_enabled: true, + }; + let r = residual_block(&levels, None, params).unwrap(); + // r[x][y] = level[n-x-1][n-y-1]; the only nonzero level is at + // (0,0) -> lands at r[3][3]. + assert_eq!(r[3 * n + 3], 9); + assert_eq!(r[0], 0); + } + + /// The inverse DCT of a single DC coefficient is a constant field: + /// the DC basis function (transMatrix row 0, all-64 per eq. 8-319) is + /// flat, so a `d[0][0]`-only input must reconstruct to a uniform `r`. + /// This pins the §8.6.4 matrix-orientation: eq. 8-317's + /// `transMatrix[ i ][ j*stride ]` reads the in-code [`DCT32`] as + /// `DCT32[ j*stride ][ i ]` (the base table is laid out + /// [column][row], eq. 8-318/8-319), so the DC input excites the + /// constant row-0 basis. + #[test] + fn dc_only_dct_4x4_exact() { + // d has only d[0][0] = 64 (n=4, trType=0/inter). + let n = 4; + let d = flat_levels(n, &[(0, 0, 64)]); + let r = inverse_transform(&d, n, PredMode::Inter, Component::Luma, 8, false).unwrap(); + // Column transform of column 0 (input [64,0,0,0]): + // e[0][i] = transMatrix[i][0] * 64 = DCT32[0][i] * 64 + // = 64 * 64 = 4096 (row 0 of DCT32 is all 64); + // every other column is 0. + // g[x][y] = clip((e+64)>>7): g[0][.] = (4096+64)>>7 = 32; + // g[x>0][.] = (0+64)>>7 = 0. + // Row transform of row y (only x=0 nonzero, value 32): + // r[i][y] = transMatrix[i][0] * 32 = 64 * 32 = 2048 for all i. + // So the whole 4x4 block reconstructs to the constant 2048. + assert!( + r.iter().all(|&v| v == 2048), + "DC-only must be uniform: {r:?}" + ); + } + + /// trType selection: only MODE_INTRA / nTbS==4 / luma uses the DST. + /// The DST and DCT matrices differ, so the same scaled-coefficient + /// array must produce different residuals under the two prediction + /// modes. (A DC-only impulse is a valid discriminator: DST column 0 + /// is {29,74,84,55} vs DCT column 0 {64,90,90,90}.) + #[test] + fn dst_path_selected_for_4x4_intra_luma() { + let n = 4; + let d = flat_levels(n, &[(0, 0, 100)]); + let intra = inverse_transform(&d, n, PredMode::Intra, Component::Luma, 8, false).unwrap(); + let inter = inverse_transform(&d, n, PredMode::Inter, Component::Luma, 8, false).unwrap(); + assert_ne!(intra, inter, "DST (intra 4x4 luma) must differ from DCT"); + // The §8.6.4.2 column transform of [100,0,0,0] under the DST + // gives e[i][0] = DST4[i][0] * 100 = [2900, 7400, 8400, 5500]; + // the DCT gives [6400, 9000, 9000, 9000]. So intra and inter + // genuinely take different matrices. + } + + /// 4x4 chroma intra must NOT use the DST (trType requires cIdx==0). + /// A Cb 4x4 intra block must match the inter (DCT) result. + #[test] + fn chroma_4x4_intra_uses_dct_not_dst() { + let n = 4; + let d = flat_levels(n, &[(1, 2, 37), (0, 0, 100), (3, 1, -8)]); + let cb_intra = inverse_transform(&d, n, PredMode::Intra, Component::Cb, 8, false).unwrap(); + let luma_inter = + inverse_transform(&d, n, PredMode::Inter, Component::Luma, 8, false).unwrap(); + // Both take trType == 0 (DCT), so the residual arrays match. + assert_eq!(cb_intra, luma_inter); + // And both differ from the luma-intra DST path. + let luma_intra = + inverse_transform(&d, n, PredMode::Intra, Component::Luma, 8, false).unwrap(); + assert_ne!(cb_intra, luma_intra); + } + + /// transform_skip path: scale then << tsShift then >> bdShift, no + /// matrix transform. tsShift = 5 + log2(nTbS). For nTbS=4 -> 7. + #[test] + fn transform_skip_shifts_without_transform() { + let n = 4; + let levels = flat_levels(n, &[(2, 1, 1)]); + let params = BlockParams { + n_tbs: n, + q_p: 4, // levelScale 64, qP/6 = 0 + component: Component::Luma, + pred_mode: PredMode::Inter, + bit_depth: 8, + extended_precision: false, + transquant_bypass: false, + transform_skip: true, + transform_skip_rotation_enabled: false, + }; + let r = residual_block(&levels, None, params).unwrap(); + // §8.6.3 d for level 1: (1*16*64<<0 +16)>>5 = (1024+16)>>5 = 32. + // §8.6.2 ts: 32 << (5+2=7) = 4096. bdShift = max(20-8,0)=12, + // round 1<<11=2048. (4096+2048)>>12 = 6144>>12 = 1. + // coefficient is at (x=2, y=1) -> index y*n + x = n + 2. + assert_eq!(r[n + 2], 1); + // the rest are zero -> 0 << 7 = 0 -> (0+2048)>>12 = 0. + assert!(r.iter().enumerate().all(|(i, &v)| i == n + 2 || v == 0)); + } + + #[test] + fn rejects_bad_block_size() { + let levels = vec![0i32; 36]; // 6x6, illegal + assert_eq!( + scale_coefficients(&levels, 6, 26, 8, false, None), + Err(TransformError::InvalidBlockSize(6)) + ); + } + + #[test] + fn rejects_length_mismatch() { + let levels = vec![0i32; 15]; // not 16 + assert_eq!( + scale_coefficients(&levels, 4, 26, 8, false, None), + Err(TransformError::LengthMismatch { + expected: 16, + got: 15, + }) + ); + } + + #[test] + fn rejects_bad_bit_depth() { + let levels = vec![0i32; 16]; + assert_eq!( + scale_coefficients(&levels, 4, 26, 7, false, None), + Err(TransformError::InvalidBitDepth(7)) + ); + } + + /// The DST-VII matrix rows are orthogonal-ish but here we just pin + /// the equation-8-316 matrix values so a future edit can't silently + /// change them. + #[test] + fn dst_matrix_pinned() { + assert_eq!(DST4[0], [29, 55, 74, 84]); + assert_eq!(DST4[1], [74, 74, 0, -74]); + assert_eq!(DST4[3], [55, -84, 74, -29]); + } + + /// Pin a few DCT matrix cells across the col0to15 / col16to31 split. + #[test] + fn dct_matrix_pinned() { + // row 0 is all 64. + assert!(DCT32[0].iter().all(|&v| v == 64)); + // row 1, col 0 = 90, col 31 = -90 (eq. 8-319 first / 8-321 last). + assert_eq!(DCT32[1][0], 90); + assert_eq!(DCT32[1][31], -90); + // row 31, col 0 = 4, col 31 = -4. + assert_eq!(DCT32[31][0], 4); + assert_eq!(DCT32[31][31], -4); + // a col16to31 interior cell: row 2, col 16 = -90. + assert_eq!(DCT32[2][16], -90); + } + + /// §8.6.4 16x16 / 8x8 subsample stride: the nTbS=8 transform reads + /// DCT32 columns at stride 4, nTbS=16 at stride 2, nTbS=4 at + /// stride 8. Spot-check via a single-row impulse so the output is + /// exactly one basis row. + #[test] + fn dct_subsample_stride_picks_right_columns() { + // 8x8: eq. 8-317 reads transMatrix[i][j*stride] with stride 4, + // which in the in-code [`DCT32`] ([column][row] layout) is + // DCT32[j*stride][i]. + let mut x = vec![0i64; 8]; + x[0] = 1; // DC basis input (j = 0). + let y = transform_1d(&x, 8, false); + // y[i] = transMatrix[i][0] = DCT32[0][i] = 64 for all i (the + // all-64 DC basis row). + assert!( + y.iter().all(|&v| v == 64), + "DC basis must be flat 64: {y:?}" + ); + // x[1] excites transform-matrix column 1*stride = 4, i.e. + // DCT32 row 4 = [89, 75, 50, 18, ...]. + let mut x2 = vec![0i64; 8]; + x2[1] = 1; + let y2 = transform_1d(&x2, 8, false); + assert_eq!(y2[0], DCT32[4][0] as i64); // 89 + assert_eq!(y2[1], DCT32[4][1] as i64); // 75 + } + + /// §8.6.5 eq. 8-322 — horizontal RDPCM is a running sum along each + /// row (x proceeding over 1..nTbS − 1). + #[test] + fn rdpcm_horizontal_accumulates_rows() { + // Row-major 4x4: row y holds [y+1, 1, -2, 3]. + let mut r: Vec = (0..4).flat_map(|y| vec![y + 1, 1, -2, 3]).collect(); + rdpcm_accumulate(&mut r, 4, false); + for y in 0..4usize { + let base = y as i32 + 1; + assert_eq!( + &r[y * 4..y * 4 + 4], + &[base, base + 1, base - 1, base + 2], + "row {y}" + ); + } + } + + /// §8.6.5 eq. 8-323 — vertical RDPCM is a running sum down each + /// column (y proceeding over 1..nTbS − 1). + #[test] + fn rdpcm_vertical_accumulates_columns() { + // Column x holds [x, 5, -3, 1] top to bottom. + let mut r = vec![0i32; 16]; + for x in 0..4usize { + r[x] = x as i32; + r[4 + x] = 5; + r[8 + x] = -3; + r[12 + x] = 1; + } + rdpcm_accumulate(&mut r, 4, true); + for x in 0..4usize { + let x0 = x as i32; + assert_eq!( + [r[x], r[4 + x], r[8 + x], r[12 + x]], + [x0, x0 + 5, x0 + 2, x0 + 3], + "column {x}" + ); + } + } + + /// §8.6.8.2 lossless (transquant-bypass) inverse undoes the + /// matching forward lifting exactly: forward + /// `Co = c2 − c1; t = c1 + ( Co >> 1 ); Cg = c0 − t; + /// Y = t + ( Cg >> 1 )` (component order c0/c1/c2 mapped onto the + /// reconstructed rY/rCb/rCr outputs), inverse eq. 8-336..8-339. + #[test] + fn act_inverse_bypass_roundtrips_forward_lifting() { + let triples: Vec<(i32, i32, i32)> = (0..64) + .map(|i| { + let a = ((i * 37) % 51) - 25; + let b = ((i * 53) % 61) - 30; + let c = ((i * 71) % 41) - 20; + (a, b, c) + }) + .collect(); + let mut r_y = Vec::new(); + let mut r_cb = Vec::new(); + let mut r_cr = Vec::new(); + for &(c0, c1, c2) in &triples { + let co = c2 - c1; + let t = c1 + (co >> 1); + let cg = c0 - t; + let y = t + (cg >> 1); + r_y.push(y); + r_cb.push(cg); + r_cr.push(co); + } + act_inverse(&mut r_y, &mut r_cb, &mut r_cr, 8, 8, false, true); + for (i, &(c0, c1, c2)) in triples.iter().enumerate() { + assert_eq!((r_y[i], r_cb[i], r_cr[i]), (c0, c1, c2), "triple {i}"); + } + } + + /// The lossy path pre-scales both chroma arrays by `<< 1` + /// (eq. 8-334 / 8-335) even at equal bit depths (deltaBD = 0): + /// rY = 0, rCb = 4, rCr = 0 ⇒ cb = 8, tmp = −4, y = 4, cb = −4, + /// cr = −4. + #[test] + fn act_inverse_lossy_prescales_chroma() { + let mut r_y = vec![0i32]; + let mut r_cb = vec![4i32]; + let mut r_cr = vec![0i32]; + act_inverse(&mut r_y, &mut r_cb, &mut r_cr, 8, 8, false, false); + assert_eq!((r_y[0], r_cb[0], r_cr[0]), (4, -4, -4)); + } + + /// Bit-depth alignment (eq. 8-329..8-335 / 8-340..8-342): with + /// BitDepthY = 10, BitDepthC = 8 a luma-only residual survives the + /// up/down shift exactly (deltaBDY = 0, deltaBDC = 2), and a + /// chroma-only rCb = 1 aligns to 1 << 3 = 8 before the lifting. + #[test] + fn act_inverse_lossy_aligns_bit_depths() { + // Luma-only: chroma zero ⇒ y unchanged, cb/cr mirror −(y>>1) + // pattern scaled back down. + let mut r_y = vec![100i32]; + let mut r_cb = vec![0i32]; + let mut r_cr = vec![0i32]; + act_inverse(&mut r_y, &mut r_cb, &mut r_cr, 10, 8, false, false); + // deltaBDY = 0: y = 100 − 0 + 0 = 100. + // cb = tmp = 100 (aligned) → back: (100 + 2) >> 2 = 25. + assert_eq!((r_y[0], r_cb[0], r_cr[0]), (100, 25, 25)); + // Chroma-only rCb = 1 at deltaBDC = 2: cb = 1 << 3 = 8; + // tmp = −4; y = 4; cb = −4 → (−4 + 2) >> 2 = −1 (arithmetic); + // cr = −4 → −1; y stays 10-bit (deltaBDY = 0). + let mut r_y = vec![0i32]; + let mut r_cb = vec![1i32]; + let mut r_cr = vec![0i32]; + act_inverse(&mut r_y, &mut r_cb, &mut r_cr, 10, 8, false, false); + assert_eq!((r_y[0], r_cb[0], r_cr[0]), (4, -1, -1)); + } + + /// Eq. 8-326..8-328 clip the INPUT arrays to the coefficient + /// ranges before any lifting. + #[test] + fn act_inverse_clips_inputs_to_coeff_range() { + let mut r_y = vec![40000i32]; + let mut r_cb = vec![-40000i32]; + let mut r_cr = vec![0i32]; + act_inverse(&mut r_y, &mut r_cb, &mut r_cr, 8, 8, false, true); + // Clipped to (32767, −32768, 0): tmp = 32767 − (−16384) = + // 49151; y = 49151 − 32768 = 16383; cb = 49151 − 0 = 49151; + // cr = 0 + 49151 = 49151. + assert_eq!((r_y[0], r_cb[0], r_cr[0]), (16383, 49151, 49151)); + } + + /// The first row (vertical) / first column (horizontal) is left + /// unmodified — the accumulation index proceeds from 1. + #[test] + fn rdpcm_leaves_first_line_unmodified() { + let src: Vec = (0..64).map(|i| (i * 7 % 23) - 11).collect(); + let mut h = src.clone(); + rdpcm_accumulate(&mut h, 8, false); + for y in 0..8 { + assert_eq!(h[y * 8], src[y * 8], "column 0, row {y}"); + } + let mut v = src.clone(); + rdpcm_accumulate(&mut v, 8, true); + assert_eq!(&v[..8], &src[..8], "row 0"); + } +} diff --git a/vendor/oxideav-h265/src/transform_tree.rs b/vendor/oxideav-h265/src/transform_tree.rs new file mode 100644 index 0000000..cb68ffe --- /dev/null +++ b/vendor/oxideav-h265/src/transform_tree.rs @@ -0,0 +1,347 @@ +//! §7.3.8.8 `transform_tree( x0, y0, xBase, yBase, log2TrafoSize, +//! trafoDepth, blkIdx )` recursion. +//! +//! This module drives the residual-quadtree split that the §7.3.8.5 +//! `coding_unit( )` body enters (under `rqt_root_cbf`) and that bottoms +//! out in the §7.3.8.10 `transform_unit( )` leaf already implemented in +//! [`crate::transform_unit`]. It is the missing rung between the +//! coding-unit walk and the transform-unit leaf: it reads +//! `split_transform_flag`, the per-node `cbf_cb` / `cbf_cr` chroma +//! coded-block flags, recurses into four quarter-size nodes when split, +//! and at each leaf reads `cbf_luma` then invokes +//! [`crate::transform_unit::decode_transform_unit`]. +//! +//! The driver mirrors the §7.3.8.8 syntax table exactly, including the +//! inheritance gate (`trafoDepth == 0 || cbf_cb[xBase][yBase][trafoDepth +//! − 1]`) under which a node only re-reads a chroma cbf when its parent +//! had a non-zero one, the §7.4.9.8 inference rules for the flags that +//! are not present on the wire, the `ChromaArrayType == 2` lower-half +//! companion cbf reads, and the §7.3.8.8 `cbf_luma` presence condition +//! (only read at a leaf when the CU is intra, the depth is non-zero, or +//! a chroma cbf is set). +//! +//! The §6.5.1 quantization-group reset (`IsCuQpDeltaCoded`, +//! `CuQpDeltaVal`, `IsCuChromaQpOffsetCoded`) at the start of each +//! quantization group is the §7.3.8.4 `coding_quadtree( )` caller's +//! responsibility; this module threads one [`QuantGroupState`] through +//! the whole tree (each `transform_unit( )` leaf reads / updates it in +//! place). The §8.6 dequantization / inverse transform that turns the +//! decoded coefficient blocks into sample residuals likewise remains the +//! caller's responsibility. + +use crate::binarization::{ + cbf_cb_ctx_inc, cbf_chroma_inferred, cbf_cr_ctx_inc, cbf_luma_ctx_inc, cbf_luma_inferred, + decode_cbf_cb, decode_cbf_cr, decode_cbf_luma, decode_split_transform_flag, + split_transform_flag_ctx_inc, split_transform_flag_inferred, +}; +use crate::cabac::CabacEngine; +use crate::ctx_init::SliceContexts; +use crate::residual::ResidualCodingError; +use crate::transform_unit::{ + decode_transform_unit, CuPredMode, QuantGroupState, TransformUnit, TransformUnitParams, +}; + +/// Geometry + coding-unit context shared by every node of one +/// §7.3.8.8 `transform_tree( )` recursion. Every field is constant for +/// the duration of the tree (it derives from the §7.3.8.5 +/// `coding_unit( )` the tree roots in) — only the per-node +/// `(x0, y0, log2TrafoSize, trafoDepth, blkIdx)` and the inherited +/// chroma-cbf state vary as the recursion descends. +#[derive(Debug, Clone, Copy)] +pub struct TransformTreeParams { + /// `MaxTbLog2SizeY` (§7.4.3.2) — the maximum luma transform-block + /// size; bounds the §7.3.8.8 split presence gate and the §7.4.9.8 + /// "log2TrafoSize > MaxTbLog2SizeY ⇒ forced split" inference. + pub max_tb_log2_size_y: u32, + /// `MinTbLog2SizeY` (§7.4.3.2) — the minimum luma transform-block + /// size; bounds the split presence gate. + pub min_tb_log2_size_y: u32, + /// `MaxTrafoDepth` (§7.3.8.5) — the maximum residual-quadtree + /// depth for this coding unit (`max_transform_hierarchy_depth_intra + /// + IntraSplitFlag` for intra, `max_transform_hierarchy_depth_inter` + /// for inter). + pub max_trafo_depth: u32, + /// `IntraSplitFlag` (§7.4.9.5) — set when an intra CU is split into + /// `PART_NxN` partitions; forces a split at `trafoDepth == 0`. + pub intra_split_flag: bool, + /// `interSplitFlag` (§7.4.9.8) — `1` exactly when + /// `max_transform_hierarchy_depth_inter == 0 && CuPredMode == + /// MODE_INTER && PartMode != PART_2Nx2N && trafoDepth == 0`. The + /// caller derives it once for the CU (it can only be non-zero at + /// `trafoDepth == 0`). + pub inter_split_flag: bool, + /// `CuPredMode[ x0 ][ y0 ]` of the coding unit. + pub cu_pred_mode: CuPredMode, + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, + /// 3 = 4:4:4). + pub chroma_array_type: u8, + /// The non-geometric §7.3.8.10 transform-unit context that is + /// constant across the tree (prediction modes, PPS / SPS gates, + /// QP-offset list length, …). The per-node geometry fields + /// (`log2_trafo_size`, `trafo_depth`, `blk_idx`, the cbf flags) are + /// overwritten by the recursion before each leaf invocation. + pub tu_template: TransformUnitParams, + /// The coding unit's luma top-left `x` (constant across the tree) — + /// with [`Self::log2_cb_size`], locates each leaf's prediction block + /// for the per-PB intra-mode selection. + pub cu_x0: u32, + /// The coding unit's luma top-left `y`. + pub cu_y0: u32, + /// `log2CbSize` of the coding unit. + pub log2_cb_size: u32, + /// The §8.4.2-derived `IntraPredModeY` of the CU's prediction + /// blocks, `[tl, tr, bl, br]`. For `PART_2Nx2N` all four entries + /// carry the single PB's mode. Consumed by the §7.4.9.11 + /// mode-dependent scan selection of each leaf's `residual_coding()`. + pub intra_pred_mode_y_corners: [u32; 4], + /// The §8.4.3-derived `IntraPredModeC` per prediction block, + /// `[tl, tr, bl, br]` (all equal outside `ChromaArrayType == 3` + /// `PART_NxN`). + pub intra_pred_mode_c_corners: [u32; 4], +} + +/// One node of the decoded §7.3.8.8 transform tree: either an internal +/// split node carrying its four children, or a leaf carrying the +/// decoded [`TransformUnit`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum TransformTree { + /// A `split_transform_flag == 1` internal node. The chroma cbf + /// flags read at this node (before the split) are recorded so the + /// §7.3.8.8 inheritance gate and the §7.3.8.10 deferred-chroma path + /// can be reasoned about; the four children are in raster order + /// (`[tl, tr, bl, br]`). + Split { + /// `cbf_cb[ x0 ][ y0 ][ trafoDepth ]` read at this node, or the + /// §7.4.9.8 inferred value when not present. + cbf_cb: bool, + /// The `ChromaArrayType == 2` lower-half companion + /// `cbf_cb[ x0 ][ y0 + (1 << (log2TrafoSize − 1)) ][ trafoDepth ]`. + cbf_cb_lower: bool, + /// `cbf_cr[ x0 ][ y0 ][ trafoDepth ]`. + cbf_cr: bool, + /// The `ChromaArrayType == 2` lower-half companion `cbf_cr`. + cbf_cr_lower: bool, + /// The four quarter-size children, raster order `[tl, tr, bl, br]`. + children: Box<[TransformTree; 4]>, + }, + /// A `split_transform_flag == 0` leaf node, carrying the decoded + /// §7.3.8.10 transform unit and the `cbf_luma` that gated it. + Leaf { + /// `cbf_luma[ x0 ][ y0 ][ trafoDepth ]` (read or inferred to 1). + cbf_luma: bool, + /// The decoded transform unit. + unit: TransformUnit, + }, +} + +/// Decode one §7.3.8.8 `transform_tree( )` node (and, recursively, its +/// whole subtree) from the CABAC engine. +/// +/// * `x0` / `y0` — the luma top-left sample position of this node. +/// * `x_base` / `y_base` — the parent node's top-left position (equal to +/// `x0` / `y0` at the root). +/// * `log2_trafo_size` — the luma transform-block log2 size of this node. +/// * `trafo_depth` — the recursion depth (0 at the CU root). +/// * `blk_idx` — the sub-block index within the parent (0 at the root). +/// * `parent_cbf_cb` / `parent_cbf_cr` — the parent node's +/// `cbf_cb[ xBase ][ yBase ][ trafoDepth − 1 ]` / +/// `cbf_cr[ … ]`; at the root (`trafoDepth == 0`) they are ignored +/// because the §7.3.8.8 inheritance gate reads the cbf unconditionally. +/// +/// The function threads one [`QuantGroupState`] through the subtree so +/// the once-per-quantization-group `delta_qp()` / `chroma_qp_offset()` +/// gates fire exactly once. +#[allow(clippy::too_many_arguments)] +pub fn decode_transform_tree( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &TransformTreeParams, + qg: &mut QuantGroupState, + x0: u32, + y0: u32, + // xBase / yBase identify the parent node's top-left position. The + // §7.3.8.10 deferred-chroma leaf reads chroma at (xBase, yBase), but + // that positional lookup is carried into the [`crate::transform_unit`] + // leaf via the inherited `parent_cbf_cb` / `parent_cbf_cr` cbf state + // rather than raw coordinates, so these are retained for §7.3.8.8 + // signature fidelity and bounds reasoning only. + _x_base: u32, + _y_base: u32, + log2_trafo_size: u32, + trafo_depth: u32, + blk_idx: u32, + parent_cbf_cb: bool, + parent_cbf_cr: bool, + // The `ChromaArrayType == 2` lower-half companions of the parent's + // cbf flags — a `log2TrafoSize == 3` split parent reads both halves + // and its 4x4 leaves code the parent chroma at `blkIdx == 3` gated + // per half (§7.3.8.10 `cbf_cb[ xBase ][ yBase + ( tIdx << + // log2TrafoSizeC ) ][ trafoDepth ]`). + parent_cbf_cb_lower: bool, + parent_cbf_cr_lower: bool, +) -> Result { + // §7.3.8.8: split_transform_flag is read only inside the gate + // log2TrafoSize <= MaxTbLog2SizeY && log2TrafoSize > MinTbLog2SizeY + // && trafoDepth < MaxTrafoDepth && !( IntraSplitFlag && trafoDepth == 0 ) + // otherwise it is inferred (§7.4.9.8). + let split = if log2_trafo_size <= params.max_tb_log2_size_y + && log2_trafo_size > params.min_tb_log2_size_y + && trafo_depth < params.max_trafo_depth + && !(params.intra_split_flag && trafo_depth == 0) + { + let inc = split_transform_flag_ctx_inc(log2_trafo_size) as usize; + decode_split_transform_flag(engine, &mut ctx.split_transform_flag[inc])? != 0 + } else { + split_transform_flag_inferred( + log2_trafo_size, + params.max_tb_log2_size_y, + params.intra_split_flag, + trafo_depth, + // interSplitFlag is only non-zero at trafoDepth == 0 by its + // own definition; the caller's value already encodes that. + params.inter_split_flag && trafo_depth == 0, + ) != 0 + }; + + // §7.3.8.8 chroma-cbf block, gated by + // ( log2TrafoSize > 2 && ChromaArrayType != 0 ) || ChromaArrayType == 3 + let chroma_present = + (log2_trafo_size > 2 && params.chroma_array_type != 0) || params.chroma_array_type == 3; + + // The lower-half companion is read only for ChromaArrayType == 2 when + // ( !split_transform_flag || log2TrafoSize == 3 ). + let read_lower = params.chroma_array_type == 2 && (!split || log2_trafo_size == 3); + + let mut cbf_cb_lower = false; + let mut cbf_cr_lower = false; + let cbf_cb; + let cbf_cr; + + if chroma_present { + // cbf_cb: read when trafoDepth == 0 || cbf_cb[xBase][yBase][td-1]. + if trafo_depth == 0 || parent_cbf_cb { + let inc = cbf_cb_ctx_inc(trafo_depth) as usize; + cbf_cb = decode_cbf_cb(engine, &mut ctx.cbf_chroma[inc])? != 0; + if read_lower { + let inc = cbf_cb_ctx_inc(trafo_depth) as usize; + cbf_cb_lower = decode_cbf_cb(engine, &mut ctx.cbf_chroma[inc])? != 0; + } + } else { + cbf_cb = cbf_chroma_inferred() != 0; + } + // cbf_cr: symmetric. + if trafo_depth == 0 || parent_cbf_cr { + let inc = cbf_cr_ctx_inc(trafo_depth) as usize; + cbf_cr = decode_cbf_cr(engine, &mut ctx.cbf_chroma[inc])? != 0; + if read_lower { + let inc = cbf_cr_ctx_inc(trafo_depth) as usize; + cbf_cr_lower = decode_cbf_cr(engine, &mut ctx.cbf_chroma[inc])? != 0; + } + } else { + cbf_cr = cbf_chroma_inferred() != 0; + } + } else { + // §7.4.9.8: not-present chroma cbf inherits the parent value at + // deeper depths (the §7.3.8.10 transform_unit reads + // cbf_cb[xC][yC][cbfDepthC] with cbfDepthC = trafoDepth − 1 for + // the log2TrafoSize == 2 leaf), so a 4×4 luma leaf carries the + // parent's chroma cbf forward — BOTH halves for + // ChromaArrayType == 2. + cbf_cb = parent_cbf_cb; + cbf_cr = parent_cbf_cr; + cbf_cb_lower = parent_cbf_cb_lower; + cbf_cr_lower = parent_cbf_cr_lower; + } + + if split { + // Recurse into four quarter-size nodes (§7.3.8.8). + let half = 1u32 << (log2_trafo_size - 1); + let x1 = x0 + half; + let y1 = y0 + half; + let child_log2 = log2_trafo_size - 1; + let child_depth = trafo_depth + 1; + // Each child's xBase/yBase is this node's (x0, y0); the inherited + // parent cbf is this node's (cbf_cb, cbf_cr). + let mut decode_child = |xc: u32, yc: u32, idx: u32| { + decode_transform_tree( + engine, + ctx, + params, + qg, + xc, + yc, + x0, + y0, + child_log2, + child_depth, + idx, + cbf_cb, + cbf_cr, + cbf_cb_lower, + cbf_cr_lower, + ) + }; + let tl = decode_child(x0, y0, 0)?; + let tr = decode_child(x1, y0, 1)?; + let bl = decode_child(x0, y1, 2)?; + let br = decode_child(x1, y1, 3)?; + Ok(TransformTree::Split { + cbf_cb, + cbf_cb_lower, + cbf_cr, + cbf_cr_lower, + children: Box::new([tl, tr, bl, br]), + }) + } else { + // Leaf: §7.3.8.8 cbf_luma presence condition. + // CuPredMode == MODE_INTRA || trafoDepth != 0 || cbf_cb || cbf_cr + // || ( ChromaArrayType == 2 && ( cbf_cb_lower || cbf_cr_lower ) ) + let cbf_luma_present = params.cu_pred_mode == CuPredMode::Intra + || trafo_depth != 0 + || cbf_cb + || cbf_cr + || (params.chroma_array_type == 2 && (cbf_cb_lower || cbf_cr_lower)); + let cbf_luma = if cbf_luma_present { + let inc = cbf_luma_ctx_inc(trafo_depth) as usize; + decode_cbf_luma(engine, &mut ctx.cbf_luma[inc])? != 0 + } else { + cbf_luma_inferred() != 0 + }; + + // Assemble the §7.3.8.10 transform_unit params for this leaf: + // start from the template and overwrite the per-node geometry + + // cbf state. + let mut tu_params = params.tu_template; + tu_params.log2_trafo_size = log2_trafo_size; + tu_params.trafo_depth = trafo_depth; + tu_params.blk_idx = blk_idx; + tu_params.cu_pred_mode = params.cu_pred_mode; + tu_params.chroma_array_type = params.chroma_array_type; + tu_params.cbf_luma = cbf_luma; + tu_params.cbf_cb = cbf_cb; + tu_params.cbf_cb_lower = cbf_cb_lower; + tu_params.cbf_cr = cbf_cr; + tu_params.cbf_cr_lower = cbf_cr_lower; + + // §7.4.9.11 — the mode-dependent scan reads the prediction + // block THIS leaf lies in: with `IntraSplitFlag` the CU has four + // PBs at the quarter positions, otherwise one. + let pb_idx = if params.intra_split_flag && params.log2_cb_size > 0 { + let half = 1u32 << (params.log2_cb_size - 1); + (usize::from(y0.wrapping_sub(params.cu_y0) >= half) << 1) + | usize::from(x0.wrapping_sub(params.cu_x0) >= half) + } else { + 0 + }; + tu_params.intra_pred_mode_y = params.intra_pred_mode_y_corners[pb_idx]; + tu_params.intra_pred_mode_c = params.intra_pred_mode_c_corners[pb_idx]; + tu_params.intra_chroma_pred_mode = + params.tu_template.intra_chroma_pred_mode_corners[pb_idx]; + + let unit = decode_transform_unit(engine, ctx, &tu_params, qg)?; + Ok(TransformTree::Leaf { cbf_luma, unit }) + } +} + +#[cfg(test)] +mod tests; diff --git a/vendor/oxideav-h265/src/transform_tree/tests.rs b/vendor/oxideav-h265/src/transform_tree/tests.rs new file mode 100644 index 0000000..e183408 --- /dev/null +++ b/vendor/oxideav-h265/src/transform_tree/tests.rs @@ -0,0 +1,227 @@ +//! §7.3.8.8 `transform_tree( )` recursion tests. + +use super::*; +use crate::bitreader::BitReader; +use crate::transform_unit::CuPredMode; + +fn template() -> TransformUnitParams { + TransformUnitParams { + log2_trafo_size: 3, + trafo_depth: 0, + blk_idx: 0, + cu_pred_mode: CuPredMode::Intra, + chroma_array_type: 1, + cbf_luma: false, + cbf_cb: false, + cbf_cb_lower: false, + cbf_cr: false, + cbf_cr_lower: false, + intra_pred_mode_y: 0, + intra_pred_mode_c: 0, + intra_chroma_pred_mode: 0, + cu_qp_delta_enabled_flag: false, + cu_chroma_qp_offset_enabled_flag: false, + chroma_qp_offset_list_len_minus1: 0, + cu_transquant_bypass_flag: false, + sign_data_hiding_enabled_flag: false, + cross_component_prediction_enabled_flag: false, + residual_adaptive_colour_transform_enabled_flag: false, + transform_skip_enabled_flag: false, + log2_max_transform_skip_size: 2, + implicit_rdpcm_enabled_flag: false, + explicit_rdpcm_enabled_flag: false, + transform_skip_context_enabled_flag: false, + + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth_luma: 8, + bit_depth_chroma: 8, + part_mode_2nx2n: true, + intra_chroma_pred_mode_corners: [0; 4], + } +} + +fn base_params() -> TransformTreeParams { + TransformTreeParams { + max_tb_log2_size_y: 5, + min_tb_log2_size_y: 2, + max_trafo_depth: 0, + intra_split_flag: false, + inter_split_flag: false, + cu_pred_mode: CuPredMode::Intra, + chroma_array_type: 1, + tu_template: template(), + cu_x0: 0, + cu_y0: 0, + log2_cb_size: 5, + intra_pred_mode_y_corners: [0; 4], + intra_pred_mode_c_corners: [0; 4], + } +} + +#[allow(clippy::too_many_arguments)] +fn decode_root( + data: &[u8], + params: &TransformTreeParams, + log2: u32, +) -> Result { + let mut engine = CabacEngine::new(BitReader::new(data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let mut qg = QuantGroupState::default(); + decode_transform_tree( + &mut engine, + &mut ctx, + params, + &mut qg, + 0, + 0, + 0, + 0, + log2, + 0, + 0, + false, + false, + false, + false, + ) +} + +/// With `MaxTrafoDepth == 0` and `log2TrafoSize == MinTbLog2SizeY`, the +/// split-flag presence gate is closed at the root, so the node is a leaf +/// with the inferred (0) split. An intra CU always reads `cbf_luma` at a +/// leaf (§7.3.8.8 presence condition). For a 4×4 luma block the chroma +/// block isn't present so no chroma cbf bins are consumed. +#[test] +fn root_4x4_is_leaf_intra_reads_cbf_luma() { + let data = [0x00u8; 96]; + let mut params = base_params(); + params.max_trafo_depth = 0; + // 4×4 root: log2 == 2 == MinTbLog2SizeY ⇒ split gate closed. + let tree = decode_root(&data, ¶ms, 2).unwrap(); + match tree { + TransformTree::Leaf { .. } => {} + TransformTree::Split { .. } => panic!("expected a leaf at 4×4 with MaxTrafoDepth 0"), + } +} + +/// `log2TrafoSize > MaxTbLog2SizeY` forces a split (§7.4.9.8 inference) +/// even when the split-flag presence gate is closed. A 64×64 luma node +/// with MaxTbLog2SizeY == 5 is inferred split into four 32×32 children. +#[test] +fn oversize_node_forces_inferred_split() { + let data = [0x00u8; 256]; + let mut params = base_params(); + params.max_tb_log2_size_y = 5; + params.min_tb_log2_size_y = 2; + // 64×64 (log2 == 6) > MaxTbLog2SizeY ⇒ split gate closed, inferred 1. + let tree = decode_root(&data, ¶ms, 6).unwrap(); + match tree { + TransformTree::Split { children, .. } => { + // Four 32×32 children, each a leaf (32×32 == MaxTb so its + // own split gate is closed at depth 1 < MaxTrafoDepth? no, + // MaxTrafoDepth 0 closes it ⇒ leaf). + assert_eq!(children.len(), 4); + } + TransformTree::Leaf { .. } => panic!("expected an inferred split at 64×64"), + } +} + +/// `IntraSplitFlag` forces a split at `trafoDepth == 0` (§7.4.9.8) and +/// also closes the split-flag presence gate, so the split is inferred +/// without consuming a bin. +#[test] +fn intra_split_flag_forces_root_split() { + let data = [0x00u8; 256]; + let mut params = base_params(); + params.intra_split_flag = true; + params.max_trafo_depth = 1; + // 16×16 intra CU split into four 8×8 PUs ⇒ forced split at depth 0. + let tree = decode_root(&data, ¶ms, 4).unwrap(); + match tree { + TransformTree::Split { children, .. } => assert_eq!(children.len(), 4), + TransformTree::Leaf { .. } => panic!("IntraSplitFlag must force a root split"), + } +} + +/// The chroma-cbf inheritance gate: at the root (`trafoDepth == 0`) both +/// cbf_cb and cbf_cr are read unconditionally when the chroma block is +/// present (8×8 luma, 4:2:0). The all-zero stream decodes both flags to +/// 0, so the leaf's transform unit has no chroma residuals. +#[test] +fn root_8x8_reads_chroma_cbf() { + let data = [0x00u8; 96]; + let mut params = base_params(); + params.max_trafo_depth = 0; + params.chroma_array_type = 1; + let tree = decode_root(&data, ¶ms, 3).unwrap(); + match tree { + TransformTree::Leaf { unit, .. } => { + assert!(unit.residual_cb.is_empty()); + assert!(unit.residual_cr.is_empty()); + } + TransformTree::Split { .. } => panic!("expected a leaf"), + } +} + +/// Monochrome (`ChromaArrayType == 0`) never reads a chroma cbf; the +/// chroma block presence gate is closed regardless of size. +#[test] +fn monochrome_skips_chroma_cbf() { + let data = [0x00u8; 96]; + let mut params = base_params(); + params.chroma_array_type = 0; + params.tu_template.chroma_array_type = 0; + params.max_trafo_depth = 0; + let tree = decode_root(&data, ¶ms, 3).unwrap(); + match tree { + TransformTree::Leaf { unit, .. } => { + assert!(unit.residual_cb.is_empty()); + assert!(unit.residual_cr.is_empty()); + } + TransformTree::Split { .. } => panic!("expected a leaf"), + } +} + +/// An inter leaf at `trafoDepth == 0` with no chroma cbf set does NOT +/// read `cbf_luma` (the §7.3.8.8 presence condition is false), so it is +/// inferred to 1. +#[test] +fn inter_root_leaf_infers_cbf_luma() { + let data = [0x00u8; 96]; + let mut params = base_params(); + params.cu_pred_mode = CuPredMode::Inter; + params.tu_template.cu_pred_mode = CuPredMode::Inter; + params.chroma_array_type = 0; // no chroma cbf to set the condition + params.tu_template.chroma_array_type = 0; + params.max_trafo_depth = 0; + let tree = decode_root(&data, ¶ms, 3).unwrap(); + match tree { + TransformTree::Leaf { cbf_luma, .. } => { + // cbf_luma not present ⇒ inferred 1. + assert!(cbf_luma); + } + TransformTree::Split { .. } => panic!("expected a leaf"), + } +} + +/// A genuine `split_transform_flag` read: with the presence gate open +/// (16×16 luma, MaxTb 5, MinTb 2, MaxTrafoDepth 2, no IntraSplit), the +/// first context-coded bin is consumed. The result is deterministic for +/// a fixed stream — here we only assert the recursion terminates and +/// returns a well-formed tree. +#[test] +fn open_gate_reads_split_flag_and_recurses() { + let data = [0x00u8; 256]; + let mut params = base_params(); + params.max_tb_log2_size_y = 5; + params.min_tb_log2_size_y = 2; + params.max_trafo_depth = 2; + let tree = decode_root(&data, ¶ms, 4).unwrap(); + // Whatever the flag decoded to, the tree is one of the two shapes + // and (if split) carries exactly four children. + if let TransformTree::Split { children, .. } = &tree { + assert_eq!(children.len(), 4); + } +} diff --git a/vendor/oxideav-h265/src/transform_unit.rs b/vendor/oxideav-h265/src/transform_unit.rs new file mode 100644 index 0000000..ea915a9 --- /dev/null +++ b/vendor/oxideav-h265/src/transform_unit.rs @@ -0,0 +1,672 @@ +//! §7.3.8.10 `transform_unit( x0, y0, xBase, yBase, log2TrafoSize, +//! trafoDepth, blkIdx )` syntax driver. +//! +//! This module composes the per-element primitives already exposed by +//! [`crate::binarization`] (`tu_residual_act_flag`, `delta_qp()` / +//! `cu_qp_delta`, `chroma_qp_offset()` / `cu_chroma_qp_offset`, and the +//! §7.3.8.12 `cross_comp_pred()` element) together with the +//! [`crate::residual`] §7.3.8.11 `residual_coding()` driver into the +//! full §7.3.8.10 transform-unit walk. +//! +//! The driver is the leaf of the §7.3.8 quadtree that the +//! `transform_tree()` recursion bottoms out in: it consumes the coded +//! block flags the parent already decided ([`TransformUnitParams::cbf_luma`] +//! / [`TransformUnitParams::cbf_cb`] / [`TransformUnitParams::cbf_cr`]), +//! reads any present `tu_residual_act_flag`, the per-CU `delta_qp()` and +//! `chroma_qp_offset()` blocks (each gated by the once-per-quantization- +//! group `IsCuQpDeltaCoded` / `IsCuChromaQpOffsetCoded` state), and then +//! the luma / chroma `residual_coding()` invocations — including the +//! `blkIdx == 3` deferred-chroma path for the `4:2:0` / `4:2:2` +//! sub-sampled-chroma case where the chroma residuals of all four luma +//! sub-blocks are coded against the parent (`xBase`, `yBase`, +//! `log2TrafoSize`) at the last luma leaf. +//! +//! The driver does **not** own the §8.6 dequantization / inverse +//! transform that turns the returned [`crate::residual::ResidualBlock`] +//! arrays into sample residuals (that is [`crate::transform`]), nor the +//! §7.3.8.8 `transform_tree()` recursion that derives the cbf flags and +//! invokes it; both remain the caller's responsibility. + +use crate::binarization::{ + decode_cross_comp_pred, decode_cu_chroma_qp_offset, decode_cu_qp_delta, + decode_tu_residual_act_flag, log2_res_scale_abs_plus1_ctx_inc, res_scale_sign_flag_ctx_inc, + tu_residual_act_flag_inferred, CrossCompPred, CuChromaQpOffset, CuQpDelta, +}; +use crate::cabac::CabacEngine; +use crate::ctx_init::SliceContexts; +use crate::residual::{ + decode_residual_coding, residual_coding_scan_idx, ResidualBlock, ResidualCodingError, + ResidualCodingParams, +}; + +/// The §7.3.8.5 `CuPredMode` of the coding unit containing this +/// transform unit. Selects the §7.3.8.10 cross-component-prediction and +/// adaptive-colour-transform gates and the §7.4.9.11 scan-order +/// derivation. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CuPredMode { + /// `MODE_INTRA`. + Intra, + /// `MODE_INTER`. + Inter, +} + +impl CuPredMode { + /// `true` for `MODE_INTRA`. + #[must_use] + pub fn is_intra(self) -> bool { + matches!(self, CuPredMode::Intra) + } +} + +/// Caller-derived inputs to one §7.3.8.10 `transform_unit( )` +/// invocation. Every field corresponds to a variable the §7.3.8.10 +/// syntax table reads from the surrounding coding-tree / coding-unit / +/// transform-tree context. +#[derive(Debug, Clone, Copy)] +pub struct TransformUnitParams { + /// `log2TrafoSize` of the luma transform block, 2..=5. + pub log2_trafo_size: u32, + /// `trafoDepth` — the transform-tree recursion depth. + pub trafo_depth: u32, + /// `blkIdx` — the luma sub-block index within the parent transform + /// node, 0..=3. Drives the §7.3.8.10 `blkIdx == 3` deferred-chroma + /// path. + pub blk_idx: u32, + /// `CuPredMode[ x0 ][ y0 ]`. + pub cu_pred_mode: CuPredMode, + /// `ChromaArrayType` (0 = monochrome, 1 = 4:2:0, 2 = 4:2:2, + /// 3 = 4:4:4). + pub chroma_array_type: u8, + /// `cbf_luma[ x0 ][ y0 ][ trafoDepth ]` — whether the luma + /// transform block has coded coefficients. + pub cbf_luma: bool, + /// `cbf_cb[ xC ][ yC ][ cbfDepthC ]` for the primary Cb block (and + /// — for `ChromaArrayType == 2` — the lower-half Cb block; see + /// [`TransformUnitParams::cbf_cb_lower`]). + pub cbf_cb: bool, + /// The `ChromaArrayType == 2` lower-half Cb coded-block flag + /// (`cbf_cb[ xC ][ yC + (1 << log2TrafoSizeC) ][ cbfDepthC ]`). + /// Ignored when `ChromaArrayType != 2`. + pub cbf_cb_lower: bool, + /// `cbf_cr[ xC ][ yC ][ cbfDepthC ]` for the primary Cr block. + pub cbf_cr: bool, + /// The `ChromaArrayType == 2` lower-half Cr coded-block flag. + /// Ignored when `ChromaArrayType != 2`. + pub cbf_cr_lower: bool, + /// `IntraPredModeY[ x0 ][ y0 ]` — the luma intra-prediction mode + /// (used only by the §7.4.9.11 luma scan-order derivation when + /// [`CuPredMode::Intra`]). + pub intra_pred_mode_y: u32, + /// `IntraPredModeC[ x0 ][ y0 ]` — the chroma intra-prediction mode + /// (used by the §7.4.9.11 chroma scan-order derivation). + pub intra_pred_mode_c: u32, + /// `intra_chroma_pred_mode[ x0 ][ y0 ]` — the raw signalled value, + /// needed by the §7.3.8.10 cross-component-prediction / + /// adaptive-colour-transform gates (the `intra_chroma_pred_mode == 4` + /// "derived-mode" condition). + pub intra_chroma_pred_mode: u8, + /// PPS `cu_qp_delta_enabled_flag` (§7.4.3.3.1) — the §7.3.8.14 + /// `delta_qp()` outer gate. + pub cu_qp_delta_enabled_flag: bool, + /// PPS `cu_chroma_qp_offset_enabled_flag` derived state (the + /// per-slice `cu_chroma_qp_offset_enabled_flag` of §7.4.9.10) — the + /// §7.3.8.15 `chroma_qp_offset()` outer gate. + pub cu_chroma_qp_offset_enabled_flag: bool, + /// `chroma_qp_offset_list_len_minus1` (§7.4.3.3.1) — bounds the + /// `cu_chroma_qp_offset_idx` TR prefix. + pub chroma_qp_offset_list_len_minus1: u32, + /// `cu_transquant_bypass_flag[ x0 ][ y0 ]` — suppresses the + /// `chroma_qp_offset()` call (the §7.3.8.10 + /// `cbfChroma && !cu_transquant_bypass_flag` gate). + pub cu_transquant_bypass_flag: bool, + /// PPS `sign_data_hiding_enabled_flag` (§7.3.2.3.1), forwarded to + /// the `residual_coding()` invocations. + pub sign_data_hiding_enabled_flag: bool, + /// PPS `cross_component_prediction_enabled_flag` (§7.4.3.3.1) — the + /// §7.3.8.10 `cross_comp_pred()` outer gate. + pub cross_component_prediction_enabled_flag: bool, + /// SCC `residual_adaptive_colour_transform_enabled_flag` + /// (§7.4.3.3.1) — the §7.3.8.10 `tu_residual_act_flag` outer gate. + pub residual_adaptive_colour_transform_enabled_flag: bool, + /// PPS `transform_skip_enabled_flag` (§7.4.3.3.1) — the §7.3.8.11 + /// `transform_skip_flag` presence gate. + pub transform_skip_enabled_flag: bool, + /// `Log2MaxTransformSkipSize` (§7.4.3.3.2). + pub log2_max_transform_skip_size: u32, + /// SPS range extension `implicit_rdpcm_enabled_flag` (§7.4.3.2.2). + pub implicit_rdpcm_enabled_flag: bool, + /// SPS range extension `explicit_rdpcm_enabled_flag` (§7.4.3.2.2). + pub explicit_rdpcm_enabled_flag: bool, + /// SPS range extension `transform_skip_context_enabled_flag` + /// (§7.4.3.2.2). + pub transform_skip_context_enabled_flag: bool, + /// SPS range extension `persistent_rice_adaptation_enabled_flag` + /// (§7.4.3.2.2) — the §9.3.3.11 StatCoeff Rice path. + pub persistent_rice_adaptation_enabled_flag: bool, + /// SPS range extension `cabac_bypass_alignment_enabled_flag` + /// (§7.4.3.2.2) — the §9.3.4.3.6 aligned bypass decoding gate. + pub cabac_bypass_alignment_enabled_flag: bool, + /// SPS range extension `extended_precision_processing_flag` + /// (§7.4.3.2.2) — the §9.3.3.4 limited-EGk escape suffix gate. + pub extended_precision_processing_flag: bool, + /// `BitDepthY` (eq. 9-14 input for luma blocks). + pub bit_depth_luma: u8, + /// `BitDepthC` (eq. 9-14 input for chroma blocks). + pub bit_depth_chroma: u8, + /// `PartMode == PART_2Nx2N` — part of the §7.3.8.10 + /// adaptive-colour-transform predicate. + pub part_mode_2nx2n: bool, + /// The four corner `intra_chroma_pred_mode` values at the + /// quarter-block positions `(xP, yP)`, `(xP+nCbS/2, yP)`, + /// `(xP, yP+nCbS/2)`, `(xP+nCbS/2, yP+nCbS/2)` — used only by the + /// `MODE_INTRA` branch of the §7.3.8.10 adaptive-colour-transform + /// predicate (all four must be `4`). Order is row-major: + /// `[tl, tr, bl, br]`. + pub intra_chroma_pred_mode_corners: [u8; 4], +} + +/// The decoded result of one §7.3.8.10 `transform_unit( )` invocation. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct TransformUnit { + /// `tu_residual_act_flag[ x0 ][ y0 ]` (§7.4.9.10) — present value or + /// the inferred `0`. + pub tu_residual_act_flag: u8, + /// The `delta_qp()` result, present only when the §7.3.8.14 gate + /// fired (`cu_qp_delta_enabled_flag && !IsCuQpDeltaCoded`). + pub cu_qp_delta: Option, + /// The `chroma_qp_offset()` result, present only when the §7.3.8.15 + /// gate fired. + pub cu_chroma_qp_offset: Option, + /// The §7.3.8.12 Cb `cross_comp_pred( x0, y0, 0 )` result, present + /// only when the §7.3.8.10 cross-component-prediction gate fired. + pub cross_comp_pred_cb: Option, + /// The §7.3.8.12 Cr `cross_comp_pred( x0, y0, 1 )` result. + pub cross_comp_pred_cr: Option, + /// The luma `residual_coding( x0, y0, log2TrafoSize, 0 )` block, + /// present only when `cbfLuma` is set. + pub residual_luma: Option, + /// The Cb `residual_coding()` blocks, one per coded chroma sub-block + /// (`ChromaArrayType == 2` can produce two: the upper then the lower + /// half). + pub residual_cb: Vec, + /// The Cr `residual_coding()` blocks. + pub residual_cr: Vec, + /// Which chroma halves carried a coded Cb block: `[upper, lower]` + /// (`ChromaArrayType == 2`; the lower slot is always `false` + /// otherwise). Pairs [`Self::residual_cb`] entries — in coding + /// order — to their vertical positions. + pub cbf_cb_halves: [bool; 2], + /// Which chroma halves carried a coded Cr block: `[upper, lower]`. + pub cbf_cr_halves: [bool; 2], +} + +/// The once-per-quantization-group decode state the §7.3.8.10 driver +/// both reads and updates: §7.3.8.14 `IsCuQpDeltaCoded` / +/// §7.4.9.14 `CuQpDeltaVal` and §7.3.8.15 `IsCuChromaQpOffsetCoded`. +/// +/// The §7.4.3.3 quantization-group reset (`IsCuQpDeltaCoded = 0`, +/// `CuQpDeltaVal = 0`, `IsCuChromaQpOffsetCoded = 0`) at the start of +/// each coding-quadtree quantization group is the caller's +/// responsibility; this struct carries the state across the multiple +/// transform units inside one quantization group. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct QuantGroupState { + /// §7.3.8.14 `IsCuQpDeltaCoded`. + pub is_cu_qp_delta_coded: bool, + /// §7.4.9.14 `CuQpDeltaVal` — accumulated signed delta. + pub cu_qp_delta_val: i32, + /// §7.3.8.15 `IsCuChromaQpOffsetCoded`. + pub is_cu_chroma_qp_offset_coded: bool, +} + +/// Decode one §7.3.8.10 `transform_unit( )` body from the CABAC engine, +/// drawing every context from the slice-scope [`SliceContexts`] bank and +/// updating the per-quantization-group [`QuantGroupState`] in place. +/// +/// The function mirrors the §7.3.8.10 syntax table exactly: +/// +/// 1. `cbfChroma` is derived (eq. in §7.3.8.10) from the supplied +/// `cbf_cb` / `cbf_cr` (plus their `ChromaArrayType == 2` lower-half +/// companions). +/// 2. When `cbfLuma || cbfChroma`, the §7.3.8.10 adaptive-colour- +/// transform predicate is evaluated; if it holds, +/// `tu_residual_act_flag` is read, else it is inferred to 0. +/// 3. `delta_qp()` and `chroma_qp_offset()` are read, each gated on its +/// `Is…Coded` state. +/// 4. The luma `residual_coding()` is read when `cbfLuma`. +/// 5. For `log2TrafoSize > 2 || ChromaArrayType == 3`, the in-place +/// Cb/Cr residual_coding (with the cross_comp_pred prelude) is read; +/// for the `blkIdx == 3` deferred path the parent-base chroma +/// residuals are read instead. +pub fn decode_transform_unit( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &TransformUnitParams, + qg: &mut QuantGroupState, +) -> Result { + let mut tu = TransformUnit::default(); + let lower = params.chroma_array_type == 2; + tu.cbf_cb_halves = [params.cbf_cb, lower && params.cbf_cb_lower]; + tu.cbf_cr_halves = [params.cbf_cr, lower && params.cbf_cr_lower]; + + // §7.3.8.10: cbfChroma = cbf_cb[..] || cbf_cr[..] || + // ( ChromaArrayType == 2 && ( cbf_cb[lower] || cbf_cr[lower] ) ) + let cbf_chroma = params.cbf_cb + || params.cbf_cr + || (params.chroma_array_type == 2 && (params.cbf_cb_lower || params.cbf_cr_lower)); + + if params.cbf_luma || cbf_chroma { + // §7.3.8.10 adaptive-colour-transform predicate. + let act_gate = params.residual_adaptive_colour_transform_enabled_flag + && (params.cu_pred_mode == CuPredMode::Inter + || (params.part_mode_2nx2n + && params.intra_chroma_pred_mode == 4 + && params + .intra_chroma_pred_mode_corners + .iter() + .all(|&m| m == 4))); + tu.tu_residual_act_flag = if act_gate { + decode_tu_residual_act_flag(engine, &mut ctx.tu_residual_act_flag[0])? + } else { + tu_residual_act_flag_inferred() + }; + + // delta_qp(): §7.3.8.14, gated by cu_qp_delta_enabled_flag && + // !IsCuQpDeltaCoded. + if params.cu_qp_delta_enabled_flag && !qg.is_cu_qp_delta_coded { + qg.is_cu_qp_delta_coded = true; + // ctx.cu_qp_delta_abs[0] is bin 0, [1] the shared rest. + let (bin0, rest) = ctx.cu_qp_delta_abs.split_at_mut(1); + let delta = decode_cu_qp_delta(engine, &mut bin0[0], &mut rest[0])?; + qg.cu_qp_delta_val = delta.value; + tu.cu_qp_delta = Some(delta); + } + + // chroma_qp_offset(): §7.3.8.15, gated by + // cbfChroma && !cu_transquant_bypass_flag (the §7.3.8.10 outer + // gate) then cu_chroma_qp_offset_enabled_flag && + // !IsCuChromaQpOffsetCoded (the §7.3.8.15 inner gate). + if cbf_chroma + && !params.cu_transquant_bypass_flag + && params.cu_chroma_qp_offset_enabled_flag + && !qg.is_cu_chroma_qp_offset_coded + { + qg.is_cu_chroma_qp_offset_coded = true; + let offset = decode_cu_chroma_qp_offset( + engine, + &mut ctx.cu_chroma_qp_offset_flag[0], + &mut ctx.cu_chroma_qp_offset_idx[0], + params.chroma_qp_offset_list_len_minus1, + )?; + tu.cu_chroma_qp_offset = Some(offset); + } + } + + // Luma residual_coding( x0, y0, log2TrafoSize, 0 ). + if params.cbf_luma { + tu.residual_luma = Some(self::decode_one_residual( + engine, + ctx, + params, + params.log2_trafo_size, + 0, + )?); + } + + // log2TrafoSizeC = Max( 2, log2TrafoSize − ( ChromaArrayType == 3 ? 0 : 1 ) ). + let log2_trafo_size_c = core::cmp::max( + 2, + params.log2_trafo_size - if params.chroma_array_type == 3 { 0 } else { 1 }, + ); + + if params.log2_trafo_size > 2 || params.chroma_array_type == 3 { + // The in-place chroma path: cross_comp_pred + residual_coding + // for each chroma sub-block at this transform unit. + // cross_comp_pred is present only when the §7.3.8.10 gate holds. + let ccp_gate = params.cross_component_prediction_enabled_flag + && params.cbf_luma + && (params.cu_pred_mode == CuPredMode::Inter || params.intra_chroma_pred_mode == 4); + + // Cb (c == 0). + if ccp_gate { + tu.cross_comp_pred_cb = Some(self::decode_one_cross_comp_pred(engine, ctx, 0)?); + } + // ChromaArrayType == 2 ⇒ two stacked Cb sub-blocks, else one. + let chroma_sub_blocks = if params.chroma_array_type == 2 { 2 } else { 1 }; + for t_idx in 0..chroma_sub_blocks { + let coded = if t_idx == 0 { + params.cbf_cb + } else { + params.cbf_cb_lower + }; + if coded { + tu.residual_cb.push(self::decode_one_residual( + engine, + ctx, + params, + log2_trafo_size_c, + 1, + )?); + } + } + + // Cr (c == 1). + if ccp_gate { + tu.cross_comp_pred_cr = Some(self::decode_one_cross_comp_pred(engine, ctx, 1)?); + } + for t_idx in 0..chroma_sub_blocks { + let coded = if t_idx == 0 { + params.cbf_cr + } else { + params.cbf_cr_lower + }; + if coded { + tu.residual_cr.push(self::decode_one_residual( + engine, + ctx, + params, + log2_trafo_size_c, + 2, + )?); + } + } + } else if params.blk_idx == 3 { + // Deferred-chroma path: the chroma residuals of the four luma + // sub-blocks are coded against the parent node at the last luma + // leaf. residual_coding( xBase, yBase, log2TrafoSize, 1/2 ), + // here parameterised at the parent log2TrafoSize. No + // cross_comp_pred in this branch (the §7.3.8.10 table only + // invokes cross_comp_pred in the in-place branch). + let chroma_sub_blocks = if params.chroma_array_type == 2 { 2 } else { 1 }; + for t_idx in 0..chroma_sub_blocks { + let coded = if t_idx == 0 { + params.cbf_cb + } else { + params.cbf_cb_lower + }; + if coded { + tu.residual_cb.push(self::decode_one_residual( + engine, + ctx, + params, + params.log2_trafo_size, + 1, + )?); + } + } + for t_idx in 0..chroma_sub_blocks { + let coded = if t_idx == 0 { + params.cbf_cr + } else { + params.cbf_cr_lower + }; + if coded { + tu.residual_cr.push(self::decode_one_residual( + engine, + ctx, + params, + params.log2_trafo_size, + 2, + )?); + } + } + } + + Ok(tu) +} + +/// Decode one §7.3.8.12 `cross_comp_pred( x0, y0, c )` against the +/// per-component context banks sliced out of [`SliceContexts`]. +fn decode_one_cross_comp_pred( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + c: u32, +) -> Result { + // log2_res_scale_abs_plus1 ctxInc = 4*c + binIdx (Table 9-48): the + // per-component four-context bank is ctx.log2_res_scale_abs_plus1 + // sliced at [base..base+4]; res_scale_sign_flag ctxInc = c. + let base = log2_res_scale_abs_plus1_ctx_inc(0, c) as usize; + let sign_idx = res_scale_sign_flag_ctx_inc(c) as usize; + // Split the sign bank off first so both borrows are disjoint. + let (prefix_bank, sign_bank) = ( + &mut ctx.log2_res_scale_abs_plus1[base..base + 4], + &mut ctx.res_scale_sign_flag[sign_idx], + ); + Ok(decode_cross_comp_pred(engine, prefix_bank, sign_bank)?) +} + +/// Decode one `residual_coding( )` invocation for the given component, +/// deriving the §7.4.9.11 scan order and assembling the +/// [`ResidualCodingParams`]. +fn decode_one_residual( + engine: &mut CabacEngine<'_>, + ctx: &mut SliceContexts, + params: &TransformUnitParams, + log2_trafo_size: u32, + c_idx: u8, +) -> Result { + let pred_mode_intra = if c_idx == 0 { + params.intra_pred_mode_y + } else { + params.intra_pred_mode_c + }; + let scan_idx = residual_coding_scan_idx( + params.cu_pred_mode.is_intra(), + log2_trafo_size, + c_idx, + params.chroma_array_type, + pred_mode_intra, + ); + + // §7.3.8.11 leading elements: transform_skip_flag when the PPS + // enables transform skip, the CU is not transquant-bypassed, and + // the block is within Log2MaxTransformSkipSize. + let mut transform_skip = false; + if params.transform_skip_enabled_flag + && !params.cu_transquant_bypass_flag + && log2_trafo_size <= params.log2_max_transform_skip_size + { + // Table 9-25 contexts: slot 0 luma (cIdx == 0), slot 1 chroma. + let slot = usize::from(c_idx > 0); + transform_skip = engine.decode_decision(&mut ctx.transform_skip_flag[slot])? != 0; + } + // §7.3.8.11: explicit_rdpcm_flag / explicit_rdpcm_dir_flag (range + // extensions) for inter blocks under transform skip / bypass. + let mut explicit_rdpcm_flag = false; + let mut explicit_rdpcm_dir_flag = false; + if params.cu_pred_mode == CuPredMode::Inter + && params.explicit_rdpcm_enabled_flag + && (transform_skip || params.cu_transquant_bypass_flag) + { + let slot = usize::from(c_idx > 0); + explicit_rdpcm_flag = engine.decode_decision(&mut ctx.explicit_rdpcm_flag[slot])? != 0; + if explicit_rdpcm_flag { + explicit_rdpcm_dir_flag = + engine.decode_decision(&mut ctx.explicit_rdpcm_dir_flag[slot])? != 0; + } + } + + // §7.3.8.11 signHidden: forced to 0 for transquant bypass, for the + // implicit-RDPCM intra horizontal/vertical transform-skip case + // (predModeIntra 10 / 26), and for explicit RDPCM. + let implicit_rdpcm = params.cu_pred_mode.is_intra() + && params.implicit_rdpcm_enabled_flag + && transform_skip + && (pred_mode_intra == 10 || pred_mode_intra == 26); + let rc_params = ResidualCodingParams { + log2_trafo_size, + is_chroma: c_idx > 0, + scan_idx, + sign_data_hiding_enabled_flag: params.sign_data_hiding_enabled_flag, + sign_hidden_suppressed: params.cu_transquant_bypass_flag + || implicit_rdpcm + || explicit_rdpcm_flag, + // §9.3.4.2.5 — the transform-skip sig-ctx selection applies + // when transform_skip_context_enabled_flag is set and the block + // is transform-skipped or transquant-bypassed. + transform_skip_sig_ctx: params.transform_skip_context_enabled_flag + && (transform_skip || params.cu_transquant_bypass_flag), + persistent_rice_adaptation_enabled_flag: params.persistent_rice_adaptation_enabled_flag, + cabac_bypass_alignment_enabled_flag: params.cabac_bypass_alignment_enabled_flag, + extended_precision_processing_flag: params.extended_precision_processing_flag, + bit_depth: if c_idx > 0 { + params.bit_depth_chroma + } else { + params.bit_depth_luma + }, + rice_stat_transform_skip: transform_skip || params.cu_transquant_bypass_flag, + }; + let mut rb = decode_residual_coding(engine, &mut ctx.residual, &rc_params)?; + rb.transform_skip = transform_skip; + rb.explicit_rdpcm_flag = explicit_rdpcm_flag; + rb.explicit_rdpcm_dir_flag = explicit_rdpcm_dir_flag; + Ok(rb) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bitreader::BitReader; + + fn base_params() -> TransformUnitParams { + TransformUnitParams { + log2_trafo_size: 3, + trafo_depth: 0, + blk_idx: 0, + cu_pred_mode: CuPredMode::Intra, + chroma_array_type: 1, + cbf_luma: false, + cbf_cb: false, + cbf_cb_lower: false, + cbf_cr: false, + cbf_cr_lower: false, + intra_pred_mode_y: 0, + intra_pred_mode_c: 0, + intra_chroma_pred_mode: 0, + cu_qp_delta_enabled_flag: false, + cu_chroma_qp_offset_enabled_flag: false, + chroma_qp_offset_list_len_minus1: 0, + cu_transquant_bypass_flag: false, + sign_data_hiding_enabled_flag: false, + cross_component_prediction_enabled_flag: false, + residual_adaptive_colour_transform_enabled_flag: false, + transform_skip_enabled_flag: false, + log2_max_transform_skip_size: 2, + implicit_rdpcm_enabled_flag: false, + explicit_rdpcm_enabled_flag: false, + transform_skip_context_enabled_flag: false, + persistent_rice_adaptation_enabled_flag: false, + cabac_bypass_alignment_enabled_flag: false, + extended_precision_processing_flag: false, + bit_depth_luma: 8, + bit_depth_chroma: 8, + part_mode_2nx2n: true, + intra_chroma_pred_mode_corners: [0; 4], + } + } + + /// No cbf set ⇒ the syntax table reads nothing: an empty + /// transform unit, no engine bins consumed. + #[test] + fn empty_transform_unit_reads_no_bins() { + // The engine is initialised but must not be consulted since no + // cbf is set; the context bank must be left untouched. + let data = [0x5Au8; 96]; + let mut engine = CabacEngine::new(BitReader::new(&data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let ctx_before = ctx.clone(); + let mut qg = QuantGroupState::default(); + let params = base_params(); + let tu = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + assert_eq!(tu, TransformUnit::default()); + assert_eq!(tu.tu_residual_act_flag, 0); + assert!(tu.cu_qp_delta.is_none()); + assert!(tu.residual_luma.is_none()); + assert!(tu.residual_cb.is_empty()); + // No context adaptation ⇒ no bins consumed from the engine. + assert_eq!(ctx, ctx_before); + assert_eq!(qg, QuantGroupState::default()); + } + + /// `cbfLuma` set but no chroma ⇒ a single luma residual_coding is + /// invoked and the quant-group state is consulted. + #[test] + fn cbf_luma_reads_luma_residual() { + let data = [0x5Au8; 96]; + let mut engine = CabacEngine::new(BitReader::new(&data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let mut qg = QuantGroupState::default(); + let mut params = base_params(); + params.cbf_luma = true; + params.log2_trafo_size = 2; + let tu = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + assert!(tu.residual_luma.is_some()); + assert!(tu.residual_cb.is_empty()); + assert!(tu.residual_cr.is_empty()); + } + + /// `cu_qp_delta_enabled_flag` with a coded chroma block fires the + /// delta_qp() read once and flips IsCuQpDeltaCoded; a second TU in + /// the same quant group must not re-read it. + #[test] + fn delta_qp_fires_once_per_quant_group() { + // Build a stream whose first decode_decision bins yield a zero + // cu_qp_delta_abs prefix (so delta_qp consumes a bounded number + // of bins and CuQpDeltaVal == 0). + let data = [0x5Au8; 96]; + let mut engine = CabacEngine::new(BitReader::new(&data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let mut qg = QuantGroupState::default(); + let mut params = base_params(); + params.cu_qp_delta_enabled_flag = true; + params.cbf_cb = true; // makes cbfChroma true so the gate block runs + params.log2_trafo_size = 3; + let tu = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + assert!(tu.cu_qp_delta.is_some()); + assert!(qg.is_cu_qp_delta_coded); + + // Second TU in the same quant group: gate must not fire again. + let tu2 = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + assert!(tu2.cu_qp_delta.is_none()); + } + + /// The deferred-chroma path is selected only at blkIdx == 3 with + /// log2TrafoSize == 2 and ChromaArrayType != 3. + #[test] + fn deferred_chroma_path_at_blk_idx_3() { + let data = [0x5Au8; 96]; + let mut engine = CabacEngine::new(BitReader::new(&data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let mut qg = QuantGroupState::default(); + let mut params = base_params(); + params.log2_trafo_size = 2; + params.blk_idx = 3; + params.chroma_array_type = 1; + params.cbf_cb = true; + let tu = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + // The deferred path coded the Cb residual at the parent size. + assert_eq!(tu.residual_cb.len(), 1); + assert_eq!(tu.residual_cb[0].log2_trafo_size, 2); + } + + /// ChromaArrayType == 2 stacks two chroma sub-blocks; both coded + /// flags produce two residual blocks each. + #[test] + fn chroma_422_stacks_two_sub_blocks() { + let data = [0x5Au8; 96]; + let mut engine = CabacEngine::new(BitReader::new(&data)).unwrap(); + let mut ctx = SliceContexts::init(0, 26); + let mut qg = QuantGroupState::default(); + let mut params = base_params(); + params.chroma_array_type = 2; + params.log2_trafo_size = 3; + params.cbf_cb = true; + params.cbf_cb_lower = true; + params.cbf_cr = true; + params.cbf_cr_lower = true; + let tu = decode_transform_unit(&mut engine, &mut ctx, ¶ms, &mut qg).unwrap(); + assert_eq!(tu.residual_cb.len(), 2); + assert_eq!(tu.residual_cr.len(), 2); + } +} diff --git a/vendor/oxideav-h265/src/vps.rs b/vendor/oxideav-h265/src/vps.rs new file mode 100644 index 0000000..c8e4a26 --- /dev/null +++ b/vendor/oxideav-h265/src/vps.rs @@ -0,0 +1,1231 @@ +//! Video Parameter Set (VPS) parser per ITU-T Rec. H.265 §7.3.2.1. +//! +//! Parses the VPS RBSP through the layer-set inclusion matrix and the +//! VPS timing-info block (including `vps_num_units_in_tick` / +//! `vps_time_scale` / `vps_poc_proportional_to_timing_flag` / +//! `vps_num_ticks_poc_diff_one_minus1` and the `vps_num_hrd_parameters` +//! count). The per-HRD `hrd_parameters()` bodies (§E.2.2) are decoded +//! as a vector of [`crate::hrd::VpsHrdEntry`] values (one per +//! `vps_num_hrd_parameters`), with the §E.2.3 sub-layer HRD payloads +//! folded into each entry's [`crate::hrd::SubLayerHrd`]. The +//! `vps_extension_flag` follows the HRD loop; when 1, the +//! `vps_extension_data_flag` run + `rbsp_trailing_bits()` are surfaced +//! as an [`crate::sps::OpaqueTail`] for callers that want the raw +//! bytes. +//! +//! The profile-tier-level subroutine of §7.3.3 is also parsed +//! structurally: the bit positions are walked but only the leading +//! `general_profile_space` / `general_tier_flag` / `general_profile_idc` +//! / `general_level_idc` fields and the per-sub-layer +//! `sub_layer_profile_present_flag` / `sub_layer_level_present_flag` +//! gates are materialised. The remaining (mostly-reserved-zero or +//! constraint-flag) fields are skipped, but the bit-walk advances the +//! reader correctly so subsequent VPS fields land on the right bit +//! boundary. +//! +//! ## Layout summary +//! +//! ```text +//! vps_video_parameter_set_id u(4) +//! vps_base_layer_internal_flag u(1) +//! vps_base_layer_available_flag u(1) +//! vps_max_layers_minus1 u(6) +//! vps_max_sub_layers_minus1 u(3) +//! vps_temporal_id_nesting_flag u(1) +//! vps_reserved_0xffff_16bits u(16) /* must be 0xFFFF */ +//! profile_tier_level( 1, vps_max_sub_layers_minus1 ) +//! vps_sub_layer_ordering_info_present_flag u(1) +//! for( i = (...) ; i <= vps_max_sub_layers_minus1; i++ ) { +//! vps_max_dec_pic_buffering_minus1[i] ue(v) +//! vps_max_num_reorder_pics[i] ue(v) +//! vps_max_latency_increase_plus1[i] ue(v) +//! } +//! vps_max_layer_id u(6) +//! vps_num_layer_sets_minus1 ue(v) +//! for( i = 1; i <= vps_num_layer_sets_minus1; i++ ) +//! for( j = 0; j <= vps_max_layer_id; j++ ) +//! layer_id_included_flag[i][j] u(1) +//! vps_timing_info_present_flag u(1) +//! if( vps_timing_info_present_flag ) { +//! vps_num_units_in_tick u(32) +//! vps_time_scale u(32) +//! vps_poc_proportional_to_timing_flag u(1) +//! if( vps_poc_proportional_to_timing_flag ) +//! vps_num_ticks_poc_diff_one_minus1 ue(v) +//! vps_num_hrd_parameters ue(v) +//! for( i = 0; i < vps_num_hrd_parameters; i++ ) { +//! hrd_layer_set_idx[i] ue(v) +//! if( i > 0 ) cprms_present_flag[i] u(1) +//! hrd_parameters( cprms_present_flag[i], vps_max_sub_layers_minus1 ) /* §E.2.2 */ +//! } +//! } +//! vps_extension_flag u(1) +//! /* extension payload + rbsp_trailing_bits() surfaced as opaque */ +//! ``` + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::hrd::{HrdError, VpsHrdEntry}; +use crate::sps::OpaqueTail; + +/// Maximum number of sub-layers an HEVC stream may declare. +/// `vps_max_sub_layers_minus1` is u(3), so the count is bounded at 7 +/// in the bitstream; this constant is reused by [`HevcVps`] as the +/// fixed-size capacity for per-sub-layer arrays. +pub const HEVC_MAX_SUB_LAYERS: usize = 7; + +/// Maximum number of layer IDs the VPS layer-set inclusion matrix may +/// span. `vps_max_layer_id` is u(6), so the maximum signalled value is +/// 63; the inclusion matrix column count is `vps_max_layer_id + 1`, +/// which is bounded at 64. +pub const HEVC_VPS_MAX_NUM_LAYERS: usize = 64; + +/// Upper bound on `vps_num_layer_sets_minus1`. Per §7.4.3.1 +/// `vps_num_layer_sets_minus1` shall be in the range 0..=1023, so +/// the layer-set count is bounded at 1024. This crate's parser caps +/// the value here to keep an aberrantly-encoded stream from forcing a +/// 4 MB allocation (the legal max would already be ~64 KB). +pub const HEVC_VPS_MAX_NUM_LAYER_SETS: usize = 1024; + +/// Errors that can arise while parsing a VPS RBSP. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VpsError { + /// The RBSP ran out of bits before the VPS was fully parsed. + Truncated, + /// `vps_reserved_0xffff_16bits` was not `0xFFFF`. §7.4.3.1 + /// mandates the literal value. + ReservedFieldMismatch { + /// The (incorrect) value that was actually read. + got: u16, + }, + /// An Exp-Golomb code's `codeNum` exceeded what the corresponding + /// syntax element can legally hold. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value. + got: u32, + }, + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), + /// An `hrd_parameters()` body inside the VPS HRD loop was malformed. + /// Propagated up from [`crate::hrd::HrdError`] so a caller that + /// only looks at [`VpsError`] still sees the failure. + Hrd(HrdError), +} + +impl core::fmt::Display for VpsError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("VPS RBSP truncated"), + Self::ReservedFieldMismatch { got } => write!( + f, + "vps_reserved_0xffff_16bits was 0x{got:04X}, expected 0xFFFF" + ), + Self::ValueOutOfRange { field, got } => { + write!(f, "syntax element {field} out of range: {got}") + } + Self::Bitstream(e) => write!(f, "bitstream error during VPS parse: {e}"), + Self::Hrd(e) => write!(f, "hrd_parameters() error inside VPS: {e}"), + } + } +} + +impl std::error::Error for VpsError {} + +impl From for VpsError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +impl From for VpsError { + fn from(e: HrdError) -> Self { + // Surface a bitstream-truncation reported through the HRD path + // as the VPS-level Truncated variant so callers can keep their + // single-pattern truncation handler. Any other HRD failure mode + // is opaque to the VPS — preserve it verbatim. + match e { + HrdError::Truncated => Self::Truncated, + other => Self::Hrd(other), + } + } +} + +/// Parsed profile-tier-level structure (§7.3.3). +/// +/// Only the leading "general" fields and the per-sub-layer +/// present-flag gates are materialised at round-2 scope. The +/// constraint flags / reserved-zero blocks are walked over to keep +/// bit alignment but their values are intentionally discarded. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct ProfileTierLevel { + /// `general_profile_space` (`u(2)`). + pub general_profile_space: u8, + /// `general_tier_flag` (`u(1)`). + pub general_tier_flag: bool, + /// `general_profile_idc` (`u(5)`). Profile mnemonics are listed in + /// Annex A; for the Main / Main 10 / Main Still / Main 4:2:2 family + /// values 1..=4 are most common. + pub general_profile_idc: u8, + /// `general_level_idc` (`u(8)`). Per A.4 the on-wire value is + /// `30 × level_number`, e.g. 30 == level 1.0, 90 == level 3.0, + /// 120 == level 4.0. + pub general_level_idc: u8, + /// For each present sub-layer, whether its profile entry was + /// signalled (`sub_layer_profile_present_flag[i]`). + pub sub_layer_profile_present: [bool; HEVC_MAX_SUB_LAYERS], + /// For each present sub-layer, whether its level_idc was signalled + /// (`sub_layer_level_present_flag[i]`). + pub sub_layer_level_present: [bool; HEVC_MAX_SUB_LAYERS], + /// Per-sub-layer `sub_layer_level_idc[i]`; only valid for indices + /// `i` where `sub_layer_level_present[i]` is true. + pub sub_layer_level_idc: [u8; HEVC_MAX_SUB_LAYERS], +} + +impl ProfileTierLevel { + /// Parse a `profile_tier_level(profilePresentFlag, maxNumSubLayersMinus1)` + /// invocation per §7.3.3. `profile_present_flag` is supplied by + /// the calling context — for the VPS / SPS path it is always 1. + pub fn parse( + br: &mut BitReader<'_>, + profile_present_flag: bool, + max_num_sub_layers_minus1: u8, + ) -> Result { + let mut ptl = Self { + general_profile_space: 0, + general_tier_flag: false, + general_profile_idc: 0, + general_level_idc: 0, + sub_layer_profile_present: [false; HEVC_MAX_SUB_LAYERS], + sub_layer_level_present: [false; HEVC_MAX_SUB_LAYERS], + sub_layer_level_idc: [0; HEVC_MAX_SUB_LAYERS], + }; + + if profile_present_flag { + ptl.general_profile_space = br.u(2)? as u8; + ptl.general_tier_flag = br.u1()? != 0; + ptl.general_profile_idc = br.u(5)? as u8; + // 32 compatibility flags — skipped wholesale; the calling + // application can re-parse them from the bit position if + // needed later. + br.skip(32)?; + // progressive / interlaced / non_packed / frame_only + br.skip(4)?; + // The conditional block beneath these flags always consumes + // exactly 43 bits regardless of profile_idc (per the + // `/* not affected by this condition */` comment in §7.3.3 + // — the chroma-constraint, range-extension, and reserved + // alternatives all sum to 43 bits). + br.skip(43)?; + // general_inbld_flag OR general_reserved_zero_bit — always 1 bit. + br.skip(1)?; + } + // general_level_idc is always present (no `profilePresentFlag` + // guard in the §7.3.3 syntax). + ptl.general_level_idc = br.u(8)? as u8; + + // Per-sub-layer present-flag gates: 2 bits per sublayer up to + // (but excluding) maxNumSubLayersMinus1. + let max = max_num_sub_layers_minus1 as usize; + for i in 0..max { + let prof = br.u1()? != 0; + let lvl = br.u1()? != 0; + ptl.sub_layer_profile_present[i] = prof; + ptl.sub_layer_level_present[i] = lvl; + } + + // §7.3.3: if maxNumSubLayersMinus1 > 0, then for i in + // max..8: reserved_zero_2bits — exactly 2 bits each — to keep + // the per-sub-layer body byte-aligned regardless of how many + // sublayers were actually signalled. + if max_num_sub_layers_minus1 > 0 { + for _ in max..8 { + br.skip(2)?; + } + } + + // Per-sub-layer profile/level body for each i in 0..max. + for i in 0..max { + if ptl.sub_layer_profile_present[i] { + // 2 + 1 + 5 + 32 + 4 + 43 + 1 = 88 bits, identical + // layout to the general profile block above. + br.skip(88)?; + } + if ptl.sub_layer_level_present[i] { + ptl.sub_layer_level_idc[i] = br.u(8)? as u8; + } + } + + Ok(ptl) + } +} + +/// One per-sub-layer ordering-info triple from §7.3.2.1. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct SubLayerOrderingInfo { + /// `vps_max_dec_pic_buffering_minus1[i]` (`ue(v)`). + /// Implies a DPB size of `value + 1`. + pub max_dec_pic_buffering_minus1: u32, + /// `vps_max_num_reorder_pics[i]` (`ue(v)`). + pub max_num_reorder_pics: u32, + /// `vps_max_latency_increase_plus1[i]` (`ue(v)`). + /// 0 disables the constraint. + pub max_latency_increase_plus1: u32, +} + +/// One per-layer-set row of the §7.3.2.1 +/// `layer_id_included_flag[i][j]` matrix. `flags[j]` is the +/// `layer_id_included_flag[i][j]` value for layer-set `i` and +/// `nuh_layer_id == j`, with `0 <= j <= vps_max_layer_id`. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct LayerIdInclusionRow { + /// `layer_id_included_flag[i][0..=vps_max_layer_id]`. + pub flags: Vec, +} + +/// VPS timing-info block per §7.3.2.1, when +/// `vps_timing_info_present_flag == 1`. The `hrd_parameters()` bodies +/// indexed by `vps_num_hrd_parameters` are decoded as +/// [`HevcVps::hrd_parameters`] entries; consult +/// [`Self::num_hrd_parameters`] for the count and +/// [`HevcVps::hrd_parameters`] for the bodies. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VpsTimingInfo { + /// `vps_num_units_in_tick` (`u(32)`). Spec constraint: shall be + /// > 0. + pub num_units_in_tick: u32, + /// `vps_time_scale` (`u(32)`). Spec constraint: shall be > 0. + pub time_scale: u32, + /// `vps_poc_proportional_to_timing_flag` (`u(1)`). + pub poc_proportional_to_timing_flag: bool, + /// `vps_num_ticks_poc_diff_one_minus1` (`ue(v)`), only present + /// when `poc_proportional_to_timing_flag` is set. Spec range + /// 0..=2^32 - 2 (the `ue(v)` codec ceiling). + pub num_ticks_poc_diff_one_minus1: Option, + /// `vps_num_hrd_parameters` (`ue(v)`). The corresponding + /// `hrd_parameters()` bodies are decoded into + /// [`HevcVps::hrd_parameters`]. Spec constraint: + /// 0..=`vps_num_layer_sets_minus1 + 1`. + pub num_hrd_parameters: u32, +} + +/// Parsed Video Parameter Set per §7.3.2.1. +/// +/// The structural prefix (through the per-sub-layer ordering loop) is +/// fully materialised; the layer-set inclusion matrix and the +/// optional VPS timing-info block follow. When +/// `vps_timing_info_present_flag == 1` and `vps_num_hrd_parameters > +/// 0`, the per-HRD `hrd_parameters()` payloads are decoded into +/// [`Self::hrd_parameters`]. The parser then reads `vps_extension_flag` +/// and, when set, surfaces the `vps_extension_data_flag` payload (plus +/// `rbsp_trailing_bits()`) as [`Self::opaque_tail`]. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct HevcVps { + /// `vps_video_parameter_set_id` (4 bits, range 0..=15). + pub vps_id: u8, + /// `vps_base_layer_internal_flag`. + pub base_layer_internal_flag: bool, + /// `vps_base_layer_available_flag`. + pub base_layer_available_flag: bool, + /// `vps_max_layers_minus1` (u(6)). The maximum number of layers is + /// `value + 1`; for single-layer (non-SHVC) streams this is 0. + pub max_layers_minus1: u8, + /// `vps_max_sub_layers_minus1` (u(3), range 0..=6). The number of + /// temporal sub-layers is `value + 1`. + pub max_sub_layers_minus1: u8, + /// `vps_temporal_id_nesting_flag`. When the stream has only one + /// sub-layer the spec requires this to be 1. + pub temporal_id_nesting_flag: bool, + /// Parsed `profile_tier_level()` subroutine. + pub ptl: ProfileTierLevel, + /// `vps_sub_layer_ordering_info_present_flag`. When 0, only entry + /// `[max_sub_layers_minus1]` is signalled and the others inherit + /// its value. + pub sub_layer_ordering_info_present_flag: bool, + /// Per-sub-layer DPB / reorder / latency triples. Indices outside + /// `0..=max_sub_layers_minus1` are zero-initialised. + pub sub_layer_ordering_info: [SubLayerOrderingInfo; HEVC_MAX_SUB_LAYERS], + /// `vps_max_layer_id` (`u(6)`, range 0..=62). The inclusion-matrix + /// column count is `value + 1`. + pub max_layer_id: u8, + /// `vps_num_layer_sets_minus1` (`ue(v)`, range 0..=1023). The + /// number of layer sets signalled by the inclusion matrix is + /// `value + 1`; layer set 0 is implicit and not signalled in the + /// matrix. + pub num_layer_sets_minus1: u16, + /// `layer_id_included_flag[i][j]` matrix. The outer index is + /// `i = 1..=num_layer_sets_minus1`, stored at offset `i - 1` + /// (layer set 0 is implicit per §7.4.3.1). Each inner row has + /// length `max_layer_id + 1`. + pub layer_id_included_flag: Vec, + /// `vps_timing_info_present_flag`. Discriminates whether + /// [`Self::timing_info`] is populated. + pub timing_info_present_flag: bool, + /// Parsed [`VpsTimingInfo`] when [`Self::timing_info_present_flag`] + /// is set; `None` otherwise. + pub timing_info: Option, + /// Per-`hrd_parameters()` entries from the §7.3.2.1 loop, one per + /// `vps_num_hrd_parameters`. Length equals + /// `timing_info.num_hrd_parameters` when timing info is present, + /// and 0 otherwise. + pub hrd_parameters: Vec, + /// `vps_extension_flag`. Always populated now that the per-HRD + /// bodies are decoded inline; the parser unconditionally reads this + /// `u(1)` after the HRD loop completes. + pub vps_extension_flag: bool, + /// Opaque suffix of the RBSP. Populated when `vps_extension_flag == + /// 1`: the `vps_extension_data_flag` payload and the + /// `rbsp_trailing_bits()` are surfaced here for callers that want + /// the raw bytes. `None` otherwise. + pub opaque_tail: Option, +} + +impl HevcVps { + /// Parse `video_parameter_set_rbsp()` starting from the first bit + /// of the (already-unescaped) RBSP body — that is, *after* the + /// two-byte NAL header has been removed (see + /// [`crate::nal::NalUnit`]). + pub fn parse(rbsp: &[u8]) -> Result { + let mut br = BitReader::new(rbsp); + Self::parse_inner(&mut br, rbsp) + } + + fn parse_inner(br: &mut BitReader<'_>, rbsp: &[u8]) -> Result { + let vps_id = br.u(4)? as u8; + let base_layer_internal_flag = br.u1()? != 0; + let base_layer_available_flag = br.u1()? != 0; + let max_layers_minus1 = br.u(6)? as u8; + let max_sub_layers_minus1_raw = br.u(3)? as u8; + if max_sub_layers_minus1_raw > 6 { + // §7.4.3.1: range is 0..=6 (max 7 sub-layers); a 7 here is + // illegal even though u(3) can encode it. + return Err(VpsError::ValueOutOfRange { + field: "vps_max_sub_layers_minus1", + got: max_sub_layers_minus1_raw as u32, + }); + } + let temporal_id_nesting_flag = br.u1()? != 0; + let reserved = br.u(16)? as u16; + if reserved != 0xFFFF { + return Err(VpsError::ReservedFieldMismatch { got: reserved }); + } + + let ptl = ProfileTierLevel::parse(br, true, max_sub_layers_minus1_raw)?; + + let sub_layer_ordering_info_present_flag = br.u1()? != 0; + let start = if sub_layer_ordering_info_present_flag { + 0usize + } else { + max_sub_layers_minus1_raw as usize + }; + let mut sub_layer_ordering_info = [SubLayerOrderingInfo::default(); HEVC_MAX_SUB_LAYERS]; + let last = max_sub_layers_minus1_raw as usize; + for entry in sub_layer_ordering_info + .iter_mut() + .take(last + 1) + .skip(start) + { + let max_dpb = br.ue()?; + let max_reorder = br.ue()?; + let max_lat = br.ue()?; + *entry = SubLayerOrderingInfo { + max_dec_pic_buffering_minus1: max_dpb, + max_num_reorder_pics: max_reorder, + max_latency_increase_plus1: max_lat, + }; + } + // When the present flag was 0, propagate the + // [max_sub_layers_minus1] entry across the lower-indexed + // sub-layers — §7.4.3.1 dictates that they take the same value. + if !sub_layer_ordering_info_present_flag { + let copy = sub_layer_ordering_info[last]; + for entry in sub_layer_ordering_info.iter_mut().take(last) { + *entry = copy; + } + } + + // vps_max_layer_id u(6) — range 0..=62 per §7.4.3.1. u(6) can + // encode 63, which the spec marks as reserved; we accept the + // value but the count `max_layer_id + 1` is capped at 64 + // (HEVC_VPS_MAX_NUM_LAYERS). + let max_layer_id = br.u(6)? as u8; + + // vps_num_layer_sets_minus1 ue(v) — range 0..=1023. + let num_layer_sets_minus1_raw = br.ue()?; + if num_layer_sets_minus1_raw as usize >= HEVC_VPS_MAX_NUM_LAYER_SETS { + return Err(VpsError::ValueOutOfRange { + field: "vps_num_layer_sets_minus1", + got: num_layer_sets_minus1_raw, + }); + } + let num_layer_sets_minus1 = num_layer_sets_minus1_raw as u16; + + // Layer-set inclusion matrix. The for-loop in the spec starts + // at i = 1 (layer set 0 is the base set, not signalled), so the + // signalled-row count is `num_layer_sets_minus1`. Each row has + // `max_layer_id + 1` u(1) flags. + let row_width = max_layer_id as usize + 1; + let signalled_rows = num_layer_sets_minus1 as usize; + let mut layer_id_included_flag = Vec::with_capacity(signalled_rows); + for _ in 0..signalled_rows { + let mut row = Vec::with_capacity(row_width); + for _ in 0..row_width { + row.push(br.u1()? != 0); + } + layer_id_included_flag.push(LayerIdInclusionRow { flags: row }); + } + + // vps_timing_info_present_flag u(1). + let timing_info_present_flag = br.u1()? != 0; + let mut opaque_tail = None; + let mut hrd_parameters: Vec = Vec::new(); + let timing_info = if timing_info_present_flag { + // §E.2.1 / §7.3.2.1: num_units_in_tick and time_scale are + // both u(32) and "shall be greater than 0" per the + // semantics text — enforced here so a zeroed-out stream + // doesn't silently divide by zero downstream. + let num_units_in_tick = br.u(32)?; + if num_units_in_tick == 0 { + return Err(VpsError::ValueOutOfRange { + field: "vps_num_units_in_tick", + got: 0, + }); + } + let time_scale = br.u(32)?; + if time_scale == 0 { + return Err(VpsError::ValueOutOfRange { + field: "vps_time_scale", + got: 0, + }); + } + let poc_proportional_to_timing_flag = br.u1()? != 0; + let num_ticks_poc_diff_one_minus1 = if poc_proportional_to_timing_flag { + Some(br.ue()?) + } else { + None + }; + let num_hrd_parameters = br.ue()?; + // Spec range: 0..=vps_num_layer_sets_minus1 + 1. Bound the + // value as a sanity check so a malformed stream cannot + // force an unbounded loop downstream. + if num_hrd_parameters > num_layer_sets_minus1 as u32 + 1 { + return Err(VpsError::ValueOutOfRange { + field: "vps_num_hrd_parameters", + got: num_hrd_parameters, + }); + } + let info = VpsTimingInfo { + num_units_in_tick, + time_scale, + poc_proportional_to_timing_flag, + num_ticks_poc_diff_one_minus1, + num_hrd_parameters, + }; + // Decode the per-HRD entries inline per §7.3.2.1: + // + // for( i = 0; i < vps_num_hrd_parameters; i++ ) { + // hrd_layer_set_idx[ i ] ue(v) + // if( i > 0 ) cprms_present_flag[ i ] u(1) + // hrd_parameters( cprms_present_flag[ i ], vps_max_sub_layers_minus1 ) + // } + // + // The per-HRD body (§E.2.2) lives in the `crate::hrd` + // module — the `cprms_present_flag` inheritance chain is + // walked here so each entry sees the previous entry's + // common-info gates when its own flag is 0. + for i in 0..num_hrd_parameters { + let prev = hrd_parameters.last(); + let entry = VpsHrdEntry::parse(br, i, max_sub_layers_minus1_raw, prev)?; + hrd_parameters.push(entry); + } + Some(info) + } else { + None + }; + + // vps_extension_flag u(1) — always read now that the per-HRD + // bodies are decoded inline above. When set, the + // vps_extension_data_flag run plus rbsp_trailing_bits() are + // surfaced as the opaque tail (this parser does not interpret + // the extension payload). + let vps_extension_flag = br.u1()? != 0; + if vps_extension_flag { + opaque_tail = Some(OpaqueTail::capture_at(br.bit_pos(), rbsp)); + } + + Ok(Self { + vps_id, + base_layer_internal_flag, + base_layer_available_flag, + max_layers_minus1, + max_sub_layers_minus1: max_sub_layers_minus1_raw, + temporal_id_nesting_flag, + ptl, + sub_layer_ordering_info_present_flag, + sub_layer_ordering_info, + max_layer_id, + num_layer_sets_minus1, + layer_id_included_flag, + timing_info_present_flag, + timing_info, + hrd_parameters, + vps_extension_flag, + opaque_tail, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::nal::{collect_nal_units, strip_emulation_prevention}; + + /// VPS RBSP body extracted from the workspace fixture + /// `docs/video/h265/fixtures/tiny-i-only-16x16-main/input.hevc`, + /// after the Annex B start code and the two-byte NAL header have + /// been removed and emulation-prevention bytes stripped. Captured + /// inline so the test runs without docs/ on the include path. + /// + /// Source byte sequence (Annex B): `00 00 00 01 40 01 0C 01 FF FF + /// 04 08 00 00 03 00 9F A8 00 00 03 00 00 1E BA 02 40` — after + /// stripping the start code and the `40 01` NAL header, and after + /// the §7.4.1.1 strip dropping both `03` emulation bytes: + /// `0C 01 FF FF 04 08 00 00 00 9F A8 00 00 00 00 1E BA 02 40`. + const TINY_VPS_RBSP: &[u8] = &[ + 0x0C, 0x01, 0xFF, 0xFF, 0x04, 0x08, 0x00, 0x00, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x00, 0x00, + 0x1E, 0xBA, 0x02, 0x40, + ]; + + #[test] + fn parses_tiny_fixture_vps() { + let vps = HevcVps::parse(TINY_VPS_RBSP).expect("VPS parse"); + assert_eq!(vps.vps_id, 0); + assert!(vps.base_layer_internal_flag); + assert!(vps.base_layer_available_flag); + assert_eq!(vps.max_layers_minus1, 0); // 1 layer + assert_eq!(vps.max_sub_layers_minus1, 0); // 1 sub-layer + assert!(vps.temporal_id_nesting_flag); + assert_eq!(vps.ptl.general_profile_space, 0); + assert!(!vps.ptl.general_tier_flag); + assert_eq!(vps.ptl.general_profile_idc, 4); + // §A.4 maps `30 == level 1.0 × 30` ⇒ level 1.0. (Not "level + // 3.0" — that would be value 90.) The fixture's `notes.md` + // groups it as "level 3.0" but the on-wire `level_idc` is the + // raw encoded value, which is 30 ⇒ level 1.0. + assert_eq!(vps.ptl.general_level_idc, 30); + // With max_sub_layers_minus1 == 0 the per-sub-layer ordering + // loop still runs once for i == 0. The fixture encoder + // populates DPB size 3 / no reorder / latency 1 for a + // single-frame stream, so the on-wire `ue(v)` triple decodes + // to (2, 0, 1). + assert!(vps.sub_layer_ordering_info_present_flag); + assert_eq!( + vps.sub_layer_ordering_info[0].max_dec_pic_buffering_minus1, + 2 + ); + assert_eq!(vps.sub_layer_ordering_info[0].max_num_reorder_pics, 0); + assert_eq!(vps.sub_layer_ordering_info[0].max_latency_increase_plus1, 1); + } + + #[test] + fn parses_tiny_fixture_vps_via_nal_walker() { + // End-to-end check: feed the raw Annex B stream through the + // NAL walker, then parse the first NAL's RBSP as a VPS. + let raw = &[ + 0x00, 0x00, 0x00, 0x01, 0x40, 0x01, 0x0C, 0x01, 0xFF, 0xFF, 0x04, 0x08, 0x00, 0x00, + 0x03, 0x00, 0x9F, 0xA8, 0x00, 0x00, 0x03, 0x00, 0x00, 0x1E, 0xBA, 0x02, 0x40, + ]; + let units = collect_nal_units(raw).expect("walker"); + assert_eq!(units.len(), 1); + assert_eq!(units[0].header.nal_unit_type, 32); // VPS_NUT + let vps = HevcVps::parse(&units[0].rbsp).expect("VPS parse"); + assert_eq!(vps.vps_id, 0); + assert_eq!(vps.ptl.general_profile_idc, 4); + assert_eq!(vps.ptl.general_level_idc, 30); + } + + #[test] + fn rejects_wrong_reserved_field() { + // Same prefix as the fixture but flip the last bit of the + // 16-bit reserved field so it reads 0xFFFE instead of 0xFFFF. + let mut bad = TINY_VPS_RBSP.to_vec(); + bad[3] = 0xFE; // was 0xFF + let err = HevcVps::parse(&bad).unwrap_err(); + assert_eq!(err, VpsError::ReservedFieldMismatch { got: 0xFFFE }); + } + + #[test] + fn rejects_truncated_rbsp() { + // Truncate to before the reserved field finishes. + let err = HevcVps::parse(&TINY_VPS_RBSP[..3]).unwrap_err(); + assert_eq!(err, VpsError::Truncated); + } + + #[test] + fn strip_emulation_prevention_then_parse_matches_inline_decode() { + // Build the wire-format RBSP (with 03 bytes), strip them, and + // confirm the decoded VPS matches the inline-stripped fixture. + let wire = &[ + 0x0C, 0x01, 0xFF, 0xFF, 0x04, 0x08, 0x00, 0x00, 0x03, 0x00, 0x9F, 0xA8, 0x00, 0x00, + 0x03, 0x00, 0x00, 0x1E, 0xBA, 0x02, 0x40, + ]; + let unescaped = strip_emulation_prevention(wire); + assert_eq!(unescaped, TINY_VPS_RBSP); + let vps = HevcVps::parse(&unescaped).expect("VPS parse"); + let direct = HevcVps::parse(TINY_VPS_RBSP).expect("VPS parse"); + assert_eq!(vps, direct); + } + + /// Hand-assembled minimal VPS to exercise the loop expansion path + /// when `sub_layer_ordering_info_present_flag == 1`. This test + /// stresses the multi-sub-layer code path without any fixture. + #[test] + fn parses_two_sub_layer_ordering_info_present() { + // Build a VPS with max_sub_layers_minus1 = 1 (two sublayers) + // and sub_layer_ordering_info_present_flag = 1, so two + // ordering-info triples are read. + // + // Field layout bit-by-bit: + // vps_id u4 : 0000 + // base_layer_internal_flag u1 : 1 + // base_layer_available_flag u1 : 1 + // max_layers_minus1 u6 : 000000 + // max_sub_layers_minus1 u3 : 001 + // temporal_id_nesting_flag u1 : 1 + // reserved u16 : 1111_1111_1111_1111 + // profile_tier_level: + // profile_space u2 : 00 + // tier_flag u1 : 0 + // profile_idc u5 : 00001 (Main) + // 32 compat flags : all 0 + // 4 source flags (prog/i/np/fo) : 1000 + // 43-bit block : all 0 + // 1-bit reserved : 0 + // level_idc u8 : 00011110 (= 30) + // 2 bits per inner sublayer for i in 0..1: + // sub_layer_profile_present[0] u1: 0 + // sub_layer_level_present[0] u1 : 1 + // 8-N inner reserved 2-bit pads (N=1 → 7 entries × 2 bits = 14 bits): all 0 + // since sub_layer_profile_present[0] == 0 → no extra body + // sub_layer_level_present[0] == 1 → sub_layer_level_idc[0] u8 + // : 00011110 (= 30) + // sub_layer_ordering_info_present_flag u1 : 1 + // loop i = 0..1 (two iterations) each with: + // ue(v) = '1' (codeNum 0) + // ue(v) = '1' (codeNum 0) + // ue(v) = '1' (codeNum 0) + // + // We assemble the bit string and then chunk to bytes MSB-first. + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + push("0000"); // vps_id + push("1"); // base_layer_internal_flag + push("1"); // base_layer_available_flag + push("000000"); // max_layers_minus1 + push("001"); // max_sub_layers_minus1 = 1 + push("1"); // temporal_id_nesting_flag + push("1111111111111111"); // reserved + push("00"); // profile_space + push("0"); // tier_flag + push("00001"); // profile_idc = 1 + push(&"0".repeat(32)); // compat flags + push("1000"); // prog/interlaced/non_packed/frame_only + push(&"0".repeat(43)); // 43-bit block + push("0"); // 1-bit reserved + push("00011110"); // general_level_idc = 30 + push("01"); // sub_layer_profile_present[0]=0, sub_layer_level_present[0]=1 + push(&"0".repeat(2 * 7)); // 14-bit padding for i=1..8 + push("00011110"); // sub_layer_level_idc[0] = 30 + push("1"); // sub_layer_ordering_info_present_flag + push("1"); // ue=0 (max_dec_pic_buffering_minus1[0]) + push("1"); // ue=0 (max_num_reorder_pics[0]) + push("1"); // ue=0 (max_latency_increase_plus1[0]) + push("1"); // ue=0 (max_dec_pic_buffering_minus1[1]) + push("1"); // ue=0 (max_num_reorder_pics[1]) + push("1"); // ue=0 (max_latency_increase_plus1[1]) + // VPS tail (round 12 — fully parsed): + push("000000"); // vps_max_layer_id = 0 (single layer) + push("1"); // vps_num_layer_sets_minus1 ue=0 (just layer set 0) + push("0"); // vps_timing_info_present_flag = 0 + push("0"); // vps_extension_flag = 0 + + // Pad with zeros to next byte boundary and pack. + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + + let vps = HevcVps::parse(&bytes).expect("VPS parse"); + assert_eq!(vps.vps_id, 0); + assert_eq!(vps.max_sub_layers_minus1, 1); + assert!(vps.temporal_id_nesting_flag); + assert_eq!(vps.ptl.general_profile_idc, 1); + assert_eq!(vps.ptl.general_level_idc, 30); + assert!(!vps.ptl.sub_layer_profile_present[0]); + assert!(vps.ptl.sub_layer_level_present[0]); + assert_eq!(vps.ptl.sub_layer_level_idc[0], 30); + assert!(vps.sub_layer_ordering_info_present_flag); + for i in 0..=1 { + assert_eq!( + vps.sub_layer_ordering_info[i].max_dec_pic_buffering_minus1, + 0 + ); + assert_eq!(vps.sub_layer_ordering_info[i].max_num_reorder_pics, 0); + assert_eq!(vps.sub_layer_ordering_info[i].max_latency_increase_plus1, 0); + } + // Tail decoded as expected. + assert_eq!(vps.max_layer_id, 0); + assert_eq!(vps.num_layer_sets_minus1, 0); + assert!(!vps.timing_info_present_flag); + assert!(vps.timing_info.is_none()); + assert!(!vps.vps_extension_flag); + assert!(vps.opaque_tail.is_none()); + assert!(vps.hrd_parameters.is_empty()); + } + + #[test] + fn parses_ordering_info_present_flag_zero_propagates() { + // max_sub_layers_minus1 = 1, but + // sub_layer_ordering_info_present_flag = 0 → only the [1] + // entry is signalled; the [0] entry inherits it per §7.4.3.1. + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + push("0000"); // vps_id + push("1"); + push("1"); + push("000000"); + push("001"); // max_sub_layers_minus1 = 1 + push("1"); + push("1111111111111111"); + push("00"); + push("0"); + push("00001"); // profile_idc=1 + push(&"0".repeat(32)); + push("1000"); + push(&"0".repeat(43)); + push("0"); + push("00011110"); // level_idc=30 + push("00"); // sub_layer present flags both 0 + push(&"0".repeat(14)); + push("0"); // sub_layer_ordering_info_present_flag = 0 + // Only the i=1 triple is read; we want the [1] DPB = 2 (codeNum 2 = '011'). + push("011"); // max_dec_pic_buffering_minus1[1] = 2 + push("1"); // max_num_reorder_pics[1] = 0 + push("1"); // max_latency_increase_plus1[1] = 0 + // VPS tail (round 12 — fully parsed): + push("000000"); // vps_max_layer_id = 0 + push("1"); // vps_num_layer_sets_minus1 ue=0 + push("0"); // vps_timing_info_present_flag = 0 + push("0"); // vps_extension_flag = 0 + + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + let vps = HevcVps::parse(&bytes).expect("VPS parse"); + assert!(!vps.sub_layer_ordering_info_present_flag); + // [1] was signalled; [0] inherits. + assert_eq!( + vps.sub_layer_ordering_info[1].max_dec_pic_buffering_minus1, + 2 + ); + assert_eq!( + vps.sub_layer_ordering_info[0].max_dec_pic_buffering_minus1, + 2 + ); + assert_eq!(vps.max_layer_id, 0); + assert_eq!(vps.num_layer_sets_minus1, 0); + assert!(!vps.timing_info_present_flag); + } + + /// Hand-assembled minimal VPS that exercises the new tail: a + /// single extra layer set + a timing-info block with + /// `poc_proportional_to_timing_flag == 1` + zero HRDs + + /// `vps_extension_flag == 0`. + #[test] + fn parses_layer_set_matrix_and_timing_info() { + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + // Minimal prefix: single sub-layer, base Main profile, level 30. + push("0000"); // vps_id + push("1"); // base_layer_internal_flag + push("1"); // base_layer_available_flag + push("000000"); // max_layers_minus1 + push("000"); // max_sub_layers_minus1 = 0 + push("1"); // temporal_id_nesting_flag + push("1111111111111111"); // reserved + push("00"); // profile_space + push("0"); // tier_flag + push("00001"); // profile_idc = 1 + push(&"0".repeat(32)); // compat flags + push("1000"); // prog/interlaced/non_packed/frame_only + push(&"0".repeat(43)); + push("0"); + push("00011110"); // level_idc = 30 + push("1"); // sub_layer_ordering_info_present_flag = 1 + push("1"); // ue=0 (max_dec_pic_buffering_minus1[0]) + push("1"); // ue=0 (max_num_reorder_pics[0]) + push("1"); // ue=0 (max_latency_increase_plus1[0]) + // Tail: + push("000001"); // vps_max_layer_id = 1 (so row width 2) + push("010"); // vps_num_layer_sets_minus1 ue=1 (one signalled row) + // layer_id_included_flag[1][0..=1]: pick 1, 0 + push("10"); + push("1"); // vps_timing_info_present_flag = 1 + // num_units_in_tick = 1001 (NTSC-ish denominator) + for i in (0..32).rev() { + let b = (1001u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + // time_scale = 60000 + for i in (0..32).rev() { + let b = (60000u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + push("1"); // poc_proportional_to_timing_flag = 1 + push("1"); // num_ticks_poc_diff_one_minus1 ue=0 + push("1"); // num_hrd_parameters ue=0 (no HRDs — keeps tail parseable) + push("0"); // vps_extension_flag = 0 + + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + let vps = HevcVps::parse(&bytes).expect("VPS parse"); + assert_eq!(vps.max_layer_id, 1); + assert_eq!(vps.num_layer_sets_minus1, 1); + assert_eq!(vps.layer_id_included_flag.len(), 1); + assert_eq!(vps.layer_id_included_flag[0].flags, vec![true, false]); + assert!(vps.timing_info_present_flag); + let ti = vps.timing_info.as_ref().expect("timing info present"); + assert_eq!(ti.num_units_in_tick, 1001); + assert_eq!(ti.time_scale, 60000); + assert!(ti.poc_proportional_to_timing_flag); + assert_eq!(ti.num_ticks_poc_diff_one_minus1, Some(0)); + assert_eq!(ti.num_hrd_parameters, 0); + assert!(!vps.vps_extension_flag); + assert!(vps.opaque_tail.is_none()); + assert!(vps.hrd_parameters.is_empty()); + } + + /// Tail with `vps_num_hrd_parameters == 1` — the parser must + /// decode the §E.2.2 `hrd_parameters()` body inline rather than + /// surface it as the opaque tail. + #[test] + fn parses_hrd_payload_inline() { + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + push("0000"); + push("1"); + push("1"); + push("000000"); + push("000"); // max_sub_layers_minus1 = 0 + push("1"); + push("1111111111111111"); + push("00"); + push("0"); + push("00001"); + push(&"0".repeat(32)); + push("1000"); + push(&"0".repeat(43)); + push("0"); + push("00011110"); // level_idc + push("1"); // sub_layer_ordering_info_present_flag = 1 + push("1"); + push("1"); + push("1"); + // Tail: + push("000000"); // max_layer_id = 0 + push("1"); // num_layer_sets_minus1 ue=0 + push("1"); // timing_info_present_flag = 1 + for i in (0..32).rev() { + let b = (1u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + for i in (0..32).rev() { + let b = (30u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + push("0"); // poc_proportional_to_timing_flag = 0 + push("010"); // num_hrd_parameters ue=1 + // HRD entry i=0: + push("1"); // hrd_layer_set_idx ue=0 + // cprms_present_flag not signalled (i == 0); inferred 1 + // hrd_parameters( 1, 0 ): + push("0"); // nal_hrd_parameters_present_flag + push("0"); // vcl_hrd_parameters_present_flag + // (nal | vcl) = 0 → no common-info inner block + // sub-layer i=0: + push("1"); // fixed_pic_rate_general_flag = 1 → within_cvs inferred 1 + push("1"); // elemental_duration_in_tc_minus1 ue=0 + // low_delay not signalled, inferred 0 + push("1"); // cpb_cnt_minus1 ue=0 + // no NAL/VCL HRD bodies (gates = 0) + push("0"); // vps_extension_flag = 0 + + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + let vps = HevcVps::parse(&bytes).expect("VPS parse"); + let ti = vps.timing_info.as_ref().expect("timing info present"); + assert_eq!(ti.num_hrd_parameters, 1); + assert!(!ti.poc_proportional_to_timing_flag); + // The HRD body is now decoded inline, not surfaced as the + // opaque tail. vps_extension_flag is read after the HRD loop. + assert_eq!(vps.hrd_parameters.len(), 1); + let entry = &vps.hrd_parameters[0]; + assert_eq!(entry.hrd_layer_set_idx, 0); + assert!(entry.cprms_present_flag); + let common = entry.hrd.common.as_ref().expect("common present"); + assert!(!common.nal_hrd_parameters_present_flag); + assert!(!common.vcl_hrd_parameters_present_flag); + assert_eq!(entry.hrd.sub_layers.len(), 1); + let sl = &entry.hrd.sub_layers[0]; + assert!(sl.fixed_pic_rate_general_flag); + assert!(sl.fixed_pic_rate_within_cvs_flag); + assert_eq!(sl.elemental_duration_in_tc_minus1, Some(0)); + assert_eq!(sl.cpb_cnt_minus1, 0); + assert!(sl.nal_hrd.is_none()); + assert!(sl.vcl_hrd.is_none()); + assert!(!vps.vps_extension_flag); + assert!(vps.opaque_tail.is_none()); + } + + /// `vps_num_units_in_tick == 0` is forbidden by the §E.2.1 / + /// §7.3.2.1 semantics text. + #[test] + fn rejects_zero_num_units_in_tick() { + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + push("0000"); + push("1"); + push("1"); + push("000000"); + push("000"); + push("1"); + push("1111111111111111"); + push("00"); + push("0"); + push("00001"); + push(&"0".repeat(32)); + push("1000"); + push(&"0".repeat(43)); + push("0"); + push("00011110"); + push("1"); + push("1"); + push("1"); + push("1"); + push("000000"); + push("1"); + push("1"); // timing_info_present_flag = 1 + push(&"0".repeat(32)); // num_units_in_tick = 0 → invalid + push(&"0".repeat(32)); // time_scale (unread) + + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + let err = HevcVps::parse(&bytes).unwrap_err(); + assert_eq!( + err, + VpsError::ValueOutOfRange { + field: "vps_num_units_in_tick", + got: 0 + } + ); + } + + /// `vps_num_hrd_parameters == 2` with the second entry's + /// `cprms_present_flag[1] == 0` — common-info gates inherit from + /// entry 0 per §7.4.3.1. + #[test] + fn parses_two_hrd_entries_with_cprms_inheritance() { + let mut bits = Vec::::new(); + let mut push = |s: &str| { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + }; + // Same prefix as parses_layer_set_matrix_and_timing_info but + // with two layer sets (so num_hrd_parameters can be 2). + push("0000"); // vps_id + push("1"); + push("1"); + push("000000"); + push("000"); // max_sub_layers_minus1 = 0 + push("1"); + push("1111111111111111"); + push("00"); + push("0"); + push("00001"); // profile_idc = 1 + push(&"0".repeat(32)); + push("1000"); + push(&"0".repeat(43)); + push("0"); + push("00011110"); // level_idc = 30 + push("1"); // sub_layer_ordering_info_present_flag = 1 + push("1"); + push("1"); + push("1"); + push("000000"); // max_layer_id = 0 + push("011"); // vps_num_layer_sets_minus1 ue=2 → 3 layer sets, room for 3 HRDs + // layer_id_included_flag[1..=2][0..=0]: two rows of one bit each + push("1"); + push("1"); + push("1"); // timing_info_present_flag = 1 + for i in (0..32).rev() { + let b = (1u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + for i in (0..32).rev() { + let b = (30u32 >> i) & 1; + push(if b == 1 { "1" } else { "0" }); + } + push("0"); // poc_proportional_to_timing_flag = 0 + push("011"); // num_hrd_parameters ue=2 + + // HRD entry i=0: hrd_layer_set_idx=0, cprms inferred 1. + push("1"); // hrd_layer_set_idx ue=0 + // hrd_parameters( 1, 0 ): + push("1"); // nal_hrd_parameters_present_flag = 1 + push("0"); // vcl + push("0"); // sub_pic_hrd_params_present_flag = 0 + // bit_rate_scale / cpb_size_scale u(4) each + push("0000"); + push("0000"); + // initial / au / dpb_output u(5) each + push("10111"); + push("10111"); + push("10111"); + // sub-layer i=0: + push("1"); // fixed_pic_rate_general = 1 + push("1"); // elemental_duration_in_tc_minus1 ue=0 + // cpb_cnt_minus1 ue=0 + push("1"); + // NAL HRD body: CpbCnt = 1 + push("1"); // bit_rate_value_minus1 ue=0 + push("1"); // cpb_size_value_minus1 ue=0 + push("1"); // cbr_flag[0] = 1 + + // HRD entry i=1: hrd_layer_set_idx ue=1 ("010"), cprms_present_flag = 0 + push("010"); // hrd_layer_set_idx = 1 + push("0"); // cprms_present_flag[1] = 0 → inherit entry 0's common info + // hrd_parameters( 0, 0 ): no common info read; gates + // inherited (nal = true). + // sub-layer i=0: + push("1"); // fixed_pic_rate_general = 1 + push("1"); // elemental_duration_in_tc_minus1 ue=0 + // cpb_cnt_minus1 ue=0 + push("1"); + push("1"); // bit_rate_value_minus1 ue=0 + push("1"); // cpb_size_value_minus1 ue=0 + push("0"); // cbr_flag = 0 + + push("0"); // vps_extension_flag = 0 + + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + let vps = HevcVps::parse(&bytes).expect("VPS parse"); + assert_eq!(vps.hrd_parameters.len(), 2); + let e0 = &vps.hrd_parameters[0]; + assert_eq!(e0.hrd_layer_set_idx, 0); + assert!(e0.cprms_present_flag); + let common = e0.hrd.common.as_ref().expect("entry 0 common"); + assert!(common.nal_hrd_parameters_present_flag); + assert_eq!(e0.hrd.sub_layers[0].nal_hrd.as_ref().unwrap().cpb.len(), 1); + + let e1 = &vps.hrd_parameters[1]; + assert_eq!(e1.hrd_layer_set_idx, 1); + assert!(!e1.cprms_present_flag); + // common is None (cprms_present_flag = 0), but the inherited + // gates from entry 0 still drove the per-sub-layer NAL HRD body. + assert!(e1.hrd.common.is_none()); + let nal = e1.hrd.sub_layers[0] + .nal_hrd + .as_ref() + .expect("nal inherited via cprms"); + assert_eq!(nal.cpb.len(), 1); + assert!(!nal.cpb[0].cbr_flag); + } +} diff --git a/vendor/oxideav-h265/src/vui.rs b/vendor/oxideav-h265/src/vui.rs new file mode 100644 index 0000000..b428689 --- /dev/null +++ b/vendor/oxideav-h265/src/vui.rs @@ -0,0 +1,1017 @@ +//! Video Usability Information (VUI) parser per ITU-T Rec. H.265 +//! §E.2.1 (`vui_parameters()`). +//! +//! The SPS optionally carries a `vui_parameters()` body when +//! `vui_parameters_present_flag == 1`. This module decodes that body +//! into the typed [`VuiParameters`] struct, with the value ranges and +//! inference rules of §E.3.1 enforced inline as [`VuiError`]. +//! +//! The nested §E.2.3 `hrd_parameters( 1, sps_max_sub_layers_minus1 )` +//! call (reached through `vui_timing_info_present_flag` / +//! `vui_hrd_parameters_present_flag`) is delegated to the shared +//! [`crate::hrd::HrdParameters`] parser. +//! +//! ## §E.2.1 layout summary +//! +//! ```text +//! vui_parameters( ) { +//! aspect_ratio_info_present_flag u(1) +//! if( aspect_ratio_info_present_flag ) { +//! aspect_ratio_idc u(8) +//! if( aspect_ratio_idc == EXTENDED_SAR ) { // 255 +//! sar_width u(16) +//! sar_height u(16) +//! } +//! } +//! overscan_info_present_flag u(1) +//! if( overscan_info_present_flag ) +//! overscan_appropriate_flag u(1) +//! video_signal_type_present_flag u(1) +//! if( video_signal_type_present_flag ) { +//! video_format u(3) +//! video_full_range_flag u(1) +//! colour_description_present_flag u(1) +//! if( colour_description_present_flag ) { +//! colour_primaries u(8) +//! transfer_characteristics u(8) +//! matrix_coeffs u(8) +//! } +//! } +//! chroma_loc_info_present_flag u(1) +//! if( chroma_loc_info_present_flag ) { +//! chroma_sample_loc_type_top_field ue(v) // 0..=5 +//! chroma_sample_loc_type_bottom_field ue(v) // 0..=5 +//! } +//! neutral_chroma_indication_flag u(1) +//! field_seq_flag u(1) +//! frame_field_info_present_flag u(1) +//! default_display_window_flag u(1) +//! if( default_display_window_flag ) { +//! def_disp_win_left_offset ue(v) +//! def_disp_win_right_offset ue(v) +//! def_disp_win_top_offset ue(v) +//! def_disp_win_bottom_offset ue(v) +//! } +//! vui_timing_info_present_flag u(1) +//! if( vui_timing_info_present_flag ) { +//! vui_num_units_in_tick u(32) // > 0 +//! vui_time_scale u(32) // > 0 +//! vui_poc_proportional_to_timing_flag u(1) +//! if( vui_poc_proportional_to_timing_flag ) +//! vui_num_ticks_poc_diff_one_minus1 ue(v) // 0..=2^32-2 +//! vui_hrd_parameters_present_flag u(1) +//! if( vui_hrd_parameters_present_flag ) +//! hrd_parameters( 1, sps_max_sub_layers_minus1 ) // §E.2.3 +//! } +//! bitstream_restriction_flag u(1) +//! if( bitstream_restriction_flag ) { +//! tiles_fixed_structure_flag u(1) +//! motion_vectors_over_pic_boundaries_flag u(1) +//! restricted_ref_pic_lists_flag u(1) +//! min_spatial_segmentation_idc ue(v) // 0..=4095 +//! max_bytes_per_pic_denom ue(v) // 0..=16 +//! max_bits_per_min_cu_denom ue(v) // 0..=16 +//! log2_max_mv_length_horizontal ue(v) // 0..=15 +//! log2_max_mv_length_vertical ue(v) // 0..=15 +//! } +//! } +//! ``` + +use crate::bitreader::{BitReader, BitReaderError}; +use crate::hrd::{HrdError, HrdParameters}; + +/// `aspect_ratio_idc` value that signals the extended (explicit +/// `sar_width`:`sar_height`) sample aspect ratio per §E.3.1 Table E.1. +pub const EXTENDED_SAR: u8 = 255; + +/// Errors that can arise while parsing a `vui_parameters()` body. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum VuiError { + /// The RBSP ran out of bits before the VUI was fully parsed. + Truncated, + /// A syntax element's parsed value was outside the legal range + /// specified for it in §E.3.1. + ValueOutOfRange { + /// Name of the offending syntax element. + field: &'static str, + /// The (illegal) value read. + got: u32, + }, + /// The nested §E.2.3 `hrd_parameters()` parse failed. + Hrd(HrdError), + /// An unexpected bitstream-level error surfaced from the reader. + Bitstream(BitReaderError), +} + +impl core::fmt::Display for VuiError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + Self::Truncated => f.write_str("vui_parameters() RBSP truncated"), + Self::ValueOutOfRange { field, got } => { + write!(f, "VUI syntax element {field} out of range: {got}") + } + Self::Hrd(e) => write!(f, "hrd_parameters() error during VUI parse: {e}"), + Self::Bitstream(e) => write!(f, "bitstream error during VUI parse: {e}"), + } + } +} + +impl std::error::Error for VuiError {} + +impl From for VuiError { + fn from(e: BitReaderError) -> Self { + match e { + BitReaderError::EndOfBuffer => Self::Truncated, + other => Self::Bitstream(other), + } + } +} + +impl From for VuiError { + fn from(e: HrdError) -> Self { + // Flatten truncation to the VUI-level equivalent so the public + // surface stays predictable; carry structured HRD faults through. + match e { + HrdError::Truncated => Self::Truncated, + HrdError::Bitstream(b) => Self::Bitstream(b), + other => Self::Hrd(other), + } + } +} + +/// `colour_description_present_flag` block from §E.2.1 — the three +/// `u(8)` colour-signalling code points. Present only when +/// `colour_description_present_flag == 1`; §E.3.1 infers each value +/// to 2 ("unspecified") otherwise — the parser leaves this `None` and +/// the inference is the caller's responsibility. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ColourDescription { + /// `colour_primaries` (`u(8)`). + pub colour_primaries: u8, + /// `transfer_characteristics` (`u(8)`). + pub transfer_characteristics: u8, + /// `matrix_coeffs` (`u(8)`). + pub matrix_coeffs: u8, +} + +/// `video_signal_type_present_flag` block from §E.2.1. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct VideoSignalType { + /// `video_format` (`u(3)`). §E.3.1 infers 5 ("unspecified") when + /// the block is absent. + pub video_format: u8, + /// `video_full_range_flag` (`u(1)`). §E.3.1 infers 0 when absent. + pub video_full_range_flag: bool, + /// Parsed `colour_description_present_flag` block; `None` when + /// `colour_description_present_flag == 0`. + pub colour_description: Option, +} + +/// `default_display_window_flag` block from §E.2.1 — the four +/// `ue(v)` offsets, in SubWidthC / SubHeightC units (§E.3.1). +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct DefaultDisplayWindow { + /// `def_disp_win_left_offset` (`ue(v)`). + pub left_offset: u32, + /// `def_disp_win_right_offset` (`ue(v)`). + pub right_offset: u32, + /// `def_disp_win_top_offset` (`ue(v)`). + pub top_offset: u32, + /// `def_disp_win_bottom_offset` (`ue(v)`). + pub bottom_offset: u32, +} + +/// `vui_timing_info_present_flag` block from §E.2.1. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VuiTimingInfo { + /// `vui_num_units_in_tick` (`u(32)`). §E.3.1: shall be > 0. + pub num_units_in_tick: u32, + /// `vui_time_scale` (`u(32)`). §E.3.1: shall be > 0. + pub time_scale: u32, + /// `vui_poc_proportional_to_timing_flag` (`u(1)`). + pub poc_proportional_to_timing_flag: bool, + /// `vui_num_ticks_poc_diff_one_minus1` (`ue(v)`); only signalled + /// when `poc_proportional_to_timing_flag == 1`. §E.3.1 range + /// 0..=2^32 − 2 (the `ue(v)` ceiling). + pub num_ticks_poc_diff_one_minus1: Option, + /// `vui_hrd_parameters_present_flag` (`u(1)`). + pub hrd_parameters_present_flag: bool, + /// Parsed `hrd_parameters( 1, sps_max_sub_layers_minus1 )` body + /// (§E.2.3); `None` when `vui_hrd_parameters_present_flag == 0`. + pub hrd_parameters: Option, +} + +/// `bitstream_restriction_flag` block from §E.2.1. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct BitstreamRestriction { + /// `tiles_fixed_structure_flag` (`u(1)`). + pub tiles_fixed_structure_flag: bool, + /// `motion_vectors_over_pic_boundaries_flag` (`u(1)`). §E.3.1 + /// infers 1 when absent. + pub motion_vectors_over_pic_boundaries_flag: bool, + /// `restricted_ref_pic_lists_flag` (`u(1)`). + pub restricted_ref_pic_lists_flag: bool, + /// `min_spatial_segmentation_idc` (`ue(v)`, range 0..=4095). + pub min_spatial_segmentation_idc: u32, + /// `max_bytes_per_pic_denom` (`ue(v)`, range 0..=16). + pub max_bytes_per_pic_denom: u32, + /// `max_bits_per_min_cu_denom` (`ue(v)`, range 0..=16). + pub max_bits_per_min_cu_denom: u32, + /// `log2_max_mv_length_horizontal` (`ue(v)`, range 0..=15). + pub log2_max_mv_length_horizontal: u32, + /// `log2_max_mv_length_vertical` (`ue(v)`, range 0..=15). + pub log2_max_mv_length_vertical: u32, +} + +/// Parsed `vui_parameters()` body per §E.2.1. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VuiParameters { + /// `aspect_ratio_info_present_flag` (`u(1)`). + pub aspect_ratio_info_present_flag: bool, + /// `aspect_ratio_idc` (`u(8)`); §E.3.1 infers 0 ("unspecified") + /// when `aspect_ratio_info_present_flag == 0`. The parser carries + /// the inferred value either way. + pub aspect_ratio_idc: u8, + /// `sar_width` (`u(16)`); only signalled when `aspect_ratio_idc ==` + /// [`EXTENDED_SAR`]. + pub sar_width: Option, + /// `sar_height` (`u(16)`); only signalled when `aspect_ratio_idc ==` + /// [`EXTENDED_SAR`]. + pub sar_height: Option, + /// `overscan_info_present_flag` (`u(1)`). + pub overscan_info_present_flag: bool, + /// `overscan_appropriate_flag` (`u(1)`); only signalled when + /// `overscan_info_present_flag == 1`. + pub overscan_appropriate_flag: Option, + /// `video_signal_type_present_flag` (`u(1)`). + pub video_signal_type_present_flag: bool, + /// Parsed `video_signal_type_present_flag` block; `None` when + /// `video_signal_type_present_flag == 0`. + pub video_signal_type: Option, + /// `chroma_loc_info_present_flag` (`u(1)`). + pub chroma_loc_info_present_flag: bool, + /// `chroma_sample_loc_type_top_field` (`ue(v)`, range 0..=5); + /// §E.3.1 infers 0 when absent. The parser carries the inferred + /// value. + pub chroma_sample_loc_type_top_field: u32, + /// `chroma_sample_loc_type_bottom_field` (`ue(v)`, range 0..=5); + /// §E.3.1 infers 0 when absent. + pub chroma_sample_loc_type_bottom_field: u32, + /// `neutral_chroma_indication_flag` (`u(1)`). + pub neutral_chroma_indication_flag: bool, + /// `field_seq_flag` (`u(1)`). + pub field_seq_flag: bool, + /// `frame_field_info_present_flag` (`u(1)`). + pub frame_field_info_present_flag: bool, + /// `default_display_window_flag` (`u(1)`). + pub default_display_window_flag: bool, + /// Parsed `default_display_window_flag` block; `None` when + /// `default_display_window_flag == 0` (all offsets infer to 0 per + /// §E.3.1). + pub default_display_window: Option, + /// `vui_timing_info_present_flag` (`u(1)`). + pub vui_timing_info_present_flag: bool, + /// Parsed `vui_timing_info_present_flag` block; `None` when + /// `vui_timing_info_present_flag == 0`. + pub timing_info: Option, + /// `bitstream_restriction_flag` (`u(1)`). + pub bitstream_restriction_flag: bool, + /// Parsed `bitstream_restriction_flag` block; `None` when + /// `bitstream_restriction_flag == 0` (§E.3.1 default inferences + /// apply). + pub bitstream_restriction: Option, +} + +impl VuiParameters { + /// Parse a `vui_parameters()` body starting at the current `br` + /// position. + /// + /// `sps_max_sub_layers_minus1` plumbs through the + /// `maxNumSubLayersMinus1` argument to the nested §E.2.3 + /// `hrd_parameters( 1, sps_max_sub_layers_minus1 )` call. On + /// success the reader is advanced past the structure. + pub fn parse(br: &mut BitReader<'_>, sps_max_sub_layers_minus1: u8) -> Result { + let aspect_ratio_info_present_flag = br.u1()? != 0; + let mut aspect_ratio_idc = 0u8; + let mut sar_width = None; + let mut sar_height = None; + if aspect_ratio_info_present_flag { + aspect_ratio_idc = br.u(8)? as u8; + if aspect_ratio_idc == EXTENDED_SAR { + sar_width = Some(br.u(16)? as u16); + sar_height = Some(br.u(16)? as u16); + } + } + + let overscan_info_present_flag = br.u1()? != 0; + let overscan_appropriate_flag = if overscan_info_present_flag { + Some(br.u1()? != 0) + } else { + None + }; + + let video_signal_type_present_flag = br.u1()? != 0; + let video_signal_type = if video_signal_type_present_flag { + let video_format = br.u(3)? as u8; + let video_full_range_flag = br.u1()? != 0; + let colour_description_present_flag = br.u1()? != 0; + let colour_description = if colour_description_present_flag { + Some(ColourDescription { + colour_primaries: br.u(8)? as u8, + transfer_characteristics: br.u(8)? as u8, + matrix_coeffs: br.u(8)? as u8, + }) + } else { + None + }; + Some(VideoSignalType { + video_format, + video_full_range_flag, + colour_description, + }) + } else { + None + }; + + let chroma_loc_info_present_flag = br.u1()? != 0; + let (chroma_sample_loc_type_top_field, chroma_sample_loc_type_bottom_field) = + if chroma_loc_info_present_flag { + let top = br.ue()?; + // §E.3.1: range 0..=5, inclusive. + if top > 5 { + return Err(VuiError::ValueOutOfRange { + field: "chroma_sample_loc_type_top_field", + got: top, + }); + } + let bottom = br.ue()?; + if bottom > 5 { + return Err(VuiError::ValueOutOfRange { + field: "chroma_sample_loc_type_bottom_field", + got: bottom, + }); + } + (top, bottom) + } else { + // §E.3.1: inferred to 0 when not present. + (0, 0) + }; + + let neutral_chroma_indication_flag = br.u1()? != 0; + let field_seq_flag = br.u1()? != 0; + let frame_field_info_present_flag = br.u1()? != 0; + + let default_display_window_flag = br.u1()? != 0; + let default_display_window = if default_display_window_flag { + Some(DefaultDisplayWindow { + left_offset: br.ue()?, + right_offset: br.ue()?, + top_offset: br.ue()?, + bottom_offset: br.ue()?, + }) + } else { + None + }; + + let vui_timing_info_present_flag = br.u1()? != 0; + let timing_info = if vui_timing_info_present_flag { + let num_units_in_tick = br.u(32)?; + // §E.3.1: vui_num_units_in_tick shall be greater than 0. + if num_units_in_tick == 0 { + return Err(VuiError::ValueOutOfRange { + field: "vui_num_units_in_tick", + got: 0, + }); + } + let time_scale = br.u(32)?; + // §E.3.1: vui_time_scale shall be greater than 0. + if time_scale == 0 { + return Err(VuiError::ValueOutOfRange { + field: "vui_time_scale", + got: 0, + }); + } + let poc_proportional_to_timing_flag = br.u1()? != 0; + let num_ticks_poc_diff_one_minus1 = if poc_proportional_to_timing_flag { + // §E.3.1 range 0..=2^32 − 2, which is the ue(v) ceiling; + // the reader already enforces it, so no extra check. + Some(br.ue()?) + } else { + None + }; + let hrd_parameters_present_flag = br.u1()? != 0; + let hrd_parameters = if hrd_parameters_present_flag { + // §E.2.1: hrd_parameters( 1, sps_max_sub_layers_minus1 ). + // commonInfPresentFlag is 1, so no inheritance source is + // needed. + Some(HrdParameters::parse( + br, + true, + sps_max_sub_layers_minus1, + None, + )?) + } else { + None + }; + Some(VuiTimingInfo { + num_units_in_tick, + time_scale, + poc_proportional_to_timing_flag, + num_ticks_poc_diff_one_minus1, + hrd_parameters_present_flag, + hrd_parameters, + }) + } else { + None + }; + + let bitstream_restriction_flag = br.u1()? != 0; + let bitstream_restriction = if bitstream_restriction_flag { + let tiles_fixed_structure_flag = br.u1()? != 0; + let motion_vectors_over_pic_boundaries_flag = br.u1()? != 0; + let restricted_ref_pic_lists_flag = br.u1()? != 0; + let min_spatial_segmentation_idc = br.ue()?; + // §E.3.1: range 0..=4095, inclusive. + if min_spatial_segmentation_idc > 4095 { + return Err(VuiError::ValueOutOfRange { + field: "min_spatial_segmentation_idc", + got: min_spatial_segmentation_idc, + }); + } + let max_bytes_per_pic_denom = br.ue()?; + // §E.3.1: range 0..=16, inclusive. + if max_bytes_per_pic_denom > 16 { + return Err(VuiError::ValueOutOfRange { + field: "max_bytes_per_pic_denom", + got: max_bytes_per_pic_denom, + }); + } + let max_bits_per_min_cu_denom = br.ue()?; + // §E.3.1: range 0..=16, inclusive. + if max_bits_per_min_cu_denom > 16 { + return Err(VuiError::ValueOutOfRange { + field: "max_bits_per_min_cu_denom", + got: max_bits_per_min_cu_denom, + }); + } + let log2_max_mv_length_horizontal = br.ue()?; + // §E.3.1: range 0..=15, inclusive. + if log2_max_mv_length_horizontal > 15 { + return Err(VuiError::ValueOutOfRange { + field: "log2_max_mv_length_horizontal", + got: log2_max_mv_length_horizontal, + }); + } + let log2_max_mv_length_vertical = br.ue()?; + if log2_max_mv_length_vertical > 15 { + return Err(VuiError::ValueOutOfRange { + field: "log2_max_mv_length_vertical", + got: log2_max_mv_length_vertical, + }); + } + Some(BitstreamRestriction { + tiles_fixed_structure_flag, + motion_vectors_over_pic_boundaries_flag, + restricted_ref_pic_lists_flag, + min_spatial_segmentation_idc, + max_bytes_per_pic_denom, + max_bits_per_min_cu_denom, + log2_max_mv_length_horizontal, + log2_max_mv_length_vertical, + }) + } else { + None + }; + + Ok(Self { + aspect_ratio_info_present_flag, + aspect_ratio_idc, + sar_width, + sar_height, + overscan_info_present_flag, + overscan_appropriate_flag, + video_signal_type_present_flag, + video_signal_type, + chroma_loc_info_present_flag, + chroma_sample_loc_type_top_field, + chroma_sample_loc_type_bottom_field, + neutral_chroma_indication_flag, + field_seq_flag, + frame_field_info_present_flag, + default_display_window_flag, + default_display_window, + vui_timing_info_present_flag, + timing_info, + bitstream_restriction_flag, + bitstream_restriction, + }) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Helper that turns a sequence of `'0'`/`'1'` bit strings into a + /// packed RBSP byte buffer. Bits run MSB-first per H.265 §7.2. + fn bits_to_bytes(parts: &[&str]) -> Vec { + let mut bits = Vec::::new(); + for s in parts { + for c in s.chars() { + if c == '0' || c == '1' { + bits.push((c as u8) - b'0'); + } + } + } + while bits.len() % 8 != 0 { + bits.push(0); + } + let mut bytes = Vec::with_capacity(bits.len() / 8); + for chunk in bits.chunks(8) { + let mut b = 0u8; + for &bit in chunk { + b = (b << 1) | bit; + } + bytes.push(b); + } + bytes + } + + /// 0-th-order unsigned Exp-Golomb encoder per ITU-T Rec. H.265 + /// §9.2: emit `leading_zero_bits` zeros followed by + /// `binary(code + 1)` on `leading_zero_bits + 1` bits. + fn ue(code: u32) -> String { + let v = code as u64 + 1; + let bits_in_v = 64 - v.leading_zeros(); + let leading_zeros = bits_in_v - 1; + let mut s = String::new(); + for _ in 0..leading_zeros { + s.push('0'); + } + for i in (0..bits_in_v).rev() { + s.push(if (v >> i) & 1 == 1 { '1' } else { '0' }); + } + s + } + + /// Fixed-width binary string (`u(n)` literal) — `width` bits of + /// `value`, MSB-first. + fn ub(value: u32, width: u8) -> String { + let mut s = String::new(); + for i in (0..width).rev() { + s.push(if (value >> i) & 1 == 1 { '1' } else { '0' }); + } + s + } + + /// Every present flag off: the minimal `vui_parameters()` body is + /// nine `u(1)` flags (aspect / overscan / video-signal / chroma-loc + /// / neutral / field-seq / frame-field / default-display / + /// timing-info) followed by `bitstream_restriction_flag`. All + /// inference defaults apply. + #[test] + fn parses_all_flags_off() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(!vui.aspect_ratio_info_present_flag); + assert_eq!(vui.aspect_ratio_idc, 0); // inferred + assert!(vui.sar_width.is_none()); + assert!(!vui.overscan_info_present_flag); + assert!(vui.overscan_appropriate_flag.is_none()); + assert!(!vui.video_signal_type_present_flag); + assert!(vui.video_signal_type.is_none()); + assert!(!vui.chroma_loc_info_present_flag); + assert_eq!(vui.chroma_sample_loc_type_top_field, 0); // inferred + assert_eq!(vui.chroma_sample_loc_type_bottom_field, 0); + assert!(!vui.neutral_chroma_indication_flag); + assert!(!vui.field_seq_flag); + assert!(!vui.frame_field_info_present_flag); + assert!(!vui.default_display_window_flag); + assert!(vui.default_display_window.is_none()); + assert!(!vui.vui_timing_info_present_flag); + assert!(vui.timing_info.is_none()); + assert!(!vui.bitstream_restriction_flag); + assert!(vui.bitstream_restriction.is_none()); + // The reader consumed exactly 10 bits. + assert_eq!(br.bit_pos(), 10); + } + + /// `aspect_ratio_idc == EXTENDED_SAR` pulls a `sar_width` / + /// `sar_height` `u(16)` pair. + #[test] + fn parses_extended_sar() { + let bytes = bits_to_bytes(&[ + "1", // aspect_ratio_info_present_flag + &ub(255, 8), // aspect_ratio_idc = EXTENDED_SAR + &ub(0x1234, 16), // sar_width + &ub(0x5678, 16), // sar_height + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(vui.aspect_ratio_info_present_flag); + assert_eq!(vui.aspect_ratio_idc, EXTENDED_SAR); + assert_eq!(vui.sar_width, Some(0x1234)); + assert_eq!(vui.sar_height, Some(0x5678)); + } + + /// A plain `aspect_ratio_idc` (1 = square) carries no SAR pair. + #[test] + fn parses_plain_aspect_ratio_idc() { + let bytes = bits_to_bytes(&[ + "1", // aspect_ratio_info_present_flag + &ub(1, 8), // aspect_ratio_idc = 1 (square) + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert_eq!(vui.aspect_ratio_idc, 1); + assert!(vui.sar_width.is_none()); + assert!(vui.sar_height.is_none()); + } + + /// Overscan + video-signal-type with colour-description. + #[test] + fn parses_video_signal_type_with_colour_description() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "1", // overscan_info_present_flag + "1", // overscan_appropriate_flag = 1 + "1", // video_signal_type_present_flag + &ub(5, 3), // video_format = 5 (unspecified) + "1", // video_full_range_flag = 1 + "1", // colour_description_present_flag = 1 + &ub(9, 8), // colour_primaries = 9 (BT.2020) + &ub(16, 8), // transfer_characteristics = 16 (PQ) + &ub(9, 8), // matrix_coeffs = 9 (BT.2020 non-const) + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(vui.overscan_info_present_flag); + assert_eq!(vui.overscan_appropriate_flag, Some(true)); + let vst = vui.video_signal_type.expect("video signal type"); + assert_eq!(vst.video_format, 5); + assert!(vst.video_full_range_flag); + let cd = vst.colour_description.expect("colour description"); + assert_eq!(cd.colour_primaries, 9); + assert_eq!(cd.transfer_characteristics, 16); + assert_eq!(cd.matrix_coeffs, 9); + } + + /// video-signal-type present but colour-description absent. + #[test] + fn parses_video_signal_type_without_colour_description() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "1", // video_signal_type_present_flag + &ub(1, 3), // video_format = 1 + "0", // video_full_range_flag = 0 + "0", // colour_description_present_flag = 0 + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + let vst = vui.video_signal_type.expect("video signal type"); + assert_eq!(vst.video_format, 1); + assert!(!vst.video_full_range_flag); + assert!(vst.colour_description.is_none()); + } + + /// chroma-loc-info + default-display-window blocks. + #[test] + fn parses_chroma_loc_and_default_display_window() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "1", // chroma_loc_info_present_flag + &ue(2), // chroma_sample_loc_type_top_field = 2 + &ue(3), // chroma_sample_loc_type_bottom_field = 3 + "1", // neutral_chroma_indication_flag = 1 + "1", // field_seq_flag = 1 + "1", // frame_field_info_present_flag = 1 + "1", // default_display_window_flag = 1 + &ue(4), // def_disp_win_left_offset = 4 + &ue(5), // def_disp_win_right_offset = 5 + &ue(6), // def_disp_win_top_offset = 6 + &ue(7), // def_disp_win_bottom_offset = 7 + "0", // vui_timing_info_present_flag + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(vui.chroma_loc_info_present_flag); + assert_eq!(vui.chroma_sample_loc_type_top_field, 2); + assert_eq!(vui.chroma_sample_loc_type_bottom_field, 3); + assert!(vui.neutral_chroma_indication_flag); + assert!(vui.field_seq_flag); + assert!(vui.frame_field_info_present_flag); + let ddw = vui.default_display_window.expect("default display window"); + assert_eq!(ddw.left_offset, 4); + assert_eq!(ddw.right_offset, 5); + assert_eq!(ddw.top_offset, 6); + assert_eq!(ddw.bottom_offset, 7); + } + + /// Timing-info block without HRD (poc-proportional set). + #[test] + fn parses_timing_info_without_hrd() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "1", // vui_timing_info_present_flag + &ub(1080000, 32), // vui_num_units_in_tick + &ub(27000000, 32), // vui_time_scale + "1", // vui_poc_proportional_to_timing_flag = 1 + &ue(8), // vui_num_ticks_poc_diff_one_minus1 = 8 + "0", // vui_hrd_parameters_present_flag = 0 + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(vui.vui_timing_info_present_flag); + let ti = vui.timing_info.expect("timing info"); + assert_eq!(ti.num_units_in_tick, 1080000); + assert_eq!(ti.time_scale, 27000000); + assert!(ti.poc_proportional_to_timing_flag); + assert_eq!(ti.num_ticks_poc_diff_one_minus1, Some(8)); + assert!(!ti.hrd_parameters_present_flag); + assert!(ti.hrd_parameters.is_none()); + } + + /// Timing-info block with a nested `hrd_parameters( 1, + /// sps_max_sub_layers_minus1 )` body (gates off → one sub-layer). + #[test] + fn parses_timing_info_with_hrd() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "0", // chroma_loc_info_present_flag + "0", // neutral_chroma_indication_flag + "0", // field_seq_flag + "0", // frame_field_info_present_flag + "0", // default_display_window_flag + "1", // vui_timing_info_present_flag + &ub(1, 32), // vui_num_units_in_tick = 1 + &ub(50, 32), // vui_time_scale = 50 + "0", // vui_poc_proportional_to_timing_flag = 0 + "1", // vui_hrd_parameters_present_flag = 1 + // hrd_parameters( 1, 0 ): commonInfPresentFlag = 1, one sub-layer + "0", // nal_hrd_parameters_present_flag = 0 + "0", // vcl_hrd_parameters_present_flag = 0 + "1", // fixed_pic_rate_general_flag[0] = 1 + &ue(0), // elemental_duration_in_tc_minus1[0] = 0 + &ue(0), // cpb_cnt_minus1[0] = 0 + "0", // bitstream_restriction_flag + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + let ti = vui.timing_info.expect("timing info"); + assert!(ti.hrd_parameters_present_flag); + let hrd = ti.hrd_parameters.expect("hrd parameters"); + assert_eq!(hrd.max_num_sub_layers_minus1, 0); + assert_eq!(hrd.sub_layers.len(), 1); + let common = hrd.common.expect("common"); + assert!(!common.nal_hrd_parameters_present_flag); + assert!(!common.vcl_hrd_parameters_present_flag); + } + + /// `vui_num_units_in_tick == 0` is rejected per §E.3.1. + #[test] + fn rejects_zero_num_units_in_tick() { + let bytes = bits_to_bytes(&[ + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", // eight present flags off + "1", // vui_timing_info_present_flag + &ub(0, 32), // vui_num_units_in_tick = 0 → reject + &ub(50, 32), // vui_time_scale + ]); + let mut br = BitReader::new(&bytes); + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!( + err, + VuiError::ValueOutOfRange { + field: "vui_num_units_in_tick", + got: 0, + } + ); + } + + /// `vui_time_scale == 0` is rejected per §E.3.1. + #[test] + fn rejects_zero_time_scale() { + let bytes = bits_to_bytes(&[ + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", // eight present flags off + "1", // vui_timing_info_present_flag + &ub(1, 32), // vui_num_units_in_tick = 1 + &ub(0, 32), // vui_time_scale = 0 → reject + ]); + let mut br = BitReader::new(&bytes); + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!( + err, + VuiError::ValueOutOfRange { + field: "vui_time_scale", + got: 0, + } + ); + } + + /// Full `bitstream_restriction` block parses with every field. + #[test] + fn parses_bitstream_restriction() { + let bytes = bits_to_bytes(&[ + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", // eight present flags off + "0", // vui_timing_info_present_flag + "1", // bitstream_restriction_flag + "1", // tiles_fixed_structure_flag = 1 + "0", // motion_vectors_over_pic_boundaries_flag = 0 + "1", // restricted_ref_pic_lists_flag = 1 + &ue(120), // min_spatial_segmentation_idc = 120 + &ue(2), // max_bytes_per_pic_denom = 2 + &ue(1), // max_bits_per_min_cu_denom = 1 + &ue(15), // log2_max_mv_length_horizontal = 15 + &ue(15), // log2_max_mv_length_vertical = 15 + ]); + let mut br = BitReader::new(&bytes); + let vui = VuiParameters::parse(&mut br, 0).expect("parse"); + assert!(vui.bitstream_restriction_flag); + let bsr = vui.bitstream_restriction.expect("bitstream restriction"); + assert!(bsr.tiles_fixed_structure_flag); + assert!(!bsr.motion_vectors_over_pic_boundaries_flag); + assert!(bsr.restricted_ref_pic_lists_flag); + assert_eq!(bsr.min_spatial_segmentation_idc, 120); + assert_eq!(bsr.max_bytes_per_pic_denom, 2); + assert_eq!(bsr.max_bits_per_min_cu_denom, 1); + assert_eq!(bsr.log2_max_mv_length_horizontal, 15); + assert_eq!(bsr.log2_max_mv_length_vertical, 15); + } + + /// `min_spatial_segmentation_idc > 4095` is rejected per §E.3.1. + #[test] + fn rejects_min_spatial_segmentation_above_4095() { + let bytes = bits_to_bytes(&[ + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", // eight present flags off + "0", // vui_timing_info_present_flag + "1", // bitstream_restriction_flag + "0", // tiles_fixed_structure_flag + "0", // motion_vectors_over_pic_boundaries_flag + "0", // restricted_ref_pic_lists_flag + &ue(4096), // min_spatial_segmentation_idc = 4096 → reject + ]); + let mut br = BitReader::new(&bytes); + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!( + err, + VuiError::ValueOutOfRange { + field: "min_spatial_segmentation_idc", + got: 4096, + } + ); + } + + /// `chroma_sample_loc_type_top_field > 5` is rejected per §E.3.1. + #[test] + fn rejects_chroma_sample_loc_above_5() { + let bytes = bits_to_bytes(&[ + "0", // aspect_ratio_info_present_flag + "0", // overscan_info_present_flag + "0", // video_signal_type_present_flag + "1", // chroma_loc_info_present_flag + &ue(6), // chroma_sample_loc_type_top_field = 6 → reject + ]); + let mut br = BitReader::new(&bytes); + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!( + err, + VuiError::ValueOutOfRange { + field: "chroma_sample_loc_type_top_field", + got: 6, + } + ); + } + + /// `log2_max_mv_length_vertical > 15` is rejected per §E.3.1. + #[test] + fn rejects_log2_max_mv_length_above_15() { + let bytes = bits_to_bytes(&[ + "0", + "0", + "0", + "0", + "0", + "0", + "0", + "0", // eight present flags off + "0", // vui_timing_info_present_flag + "1", // bitstream_restriction_flag + "0", // tiles_fixed_structure_flag + "0", // motion_vectors_over_pic_boundaries_flag + "0", // restricted_ref_pic_lists_flag + &ue(0), // min_spatial_segmentation_idc + &ue(0), // max_bytes_per_pic_denom + &ue(0), // max_bits_per_min_cu_denom + &ue(0), // log2_max_mv_length_horizontal + &ue(16), // log2_max_mv_length_vertical = 16 → reject + ]); + let mut br = BitReader::new(&bytes); + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!( + err, + VuiError::ValueOutOfRange { + field: "log2_max_mv_length_vertical", + got: 16, + } + ); + } + + /// Truncation mid-body surfaces `VuiError::Truncated`. + #[test] + fn truncation_is_reported() { + // aspect_ratio_info_present_flag = 1 but no aspect_ratio_idc byte. + let bytes = bits_to_bytes(&["1"]); + let mut br = BitReader::new(&bytes); + // The single set bit plus padding zeros means aspect_ratio_idc + // reads 7 pad bits then runs off; force a tight buffer so the + // u(8) read truncates. A single-byte buffer has 8 bits; after + // the present flag, 7 remain, so u(8) truncates. + let err = VuiParameters::parse(&mut br, 0).unwrap_err(); + assert_eq!(err, VuiError::Truncated); + } +}